70ba1895b0a1c442198a926ef0dda47dbc4d462f
[linux-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) 2004-2010 Emulex.  All rights reserved.           *
5  * EMULEX and SLI are trademarks of Emulex.                        *
6  * www.emulex.com                                                  *
7  * Portions Copyright (C) 2004-2005 Christoph Hellwig              *
8  *                                                                 *
9  * This program is free software; you can redistribute it and/or   *
10  * modify it under the terms of version 2 of the GNU General       *
11  * Public License as published by the Free Software Foundation.    *
12  * This program is distributed in the hope that it will be useful. *
13  * ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND          *
14  * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,  *
15  * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE      *
16  * DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD *
17  * TO BE LEGALLY INVALID.  See the GNU General Public License for  *
18  * more details, a copy of which can be found in the file COPYING  *
19  * included with this package.                                     *
20  *******************************************************************/
21
22 #include <linux/blkdev.h>
23 #include <linux/delay.h>
24 #include <linux/dma-mapping.h>
25 #include <linux/idr.h>
26 #include <linux/interrupt.h>
27 #include <linux/kthread.h>
28 #include <linux/pci.h>
29 #include <linux/spinlock.h>
30 #include <linux/ctype.h>
31 #include <linux/aer.h>
32 #include <linux/slab.h>
33
34 #include <scsi/scsi.h>
35 #include <scsi/scsi_device.h>
36 #include <scsi/scsi_host.h>
37 #include <scsi/scsi_transport_fc.h>
38
39 #include "lpfc_hw4.h"
40 #include "lpfc_hw.h"
41 #include "lpfc_sli.h"
42 #include "lpfc_sli4.h"
43 #include "lpfc_nl.h"
44 #include "lpfc_disc.h"
45 #include "lpfc_scsi.h"
46 #include "lpfc.h"
47 #include "lpfc_logmsg.h"
48 #include "lpfc_crtn.h"
49 #include "lpfc_vport.h"
50 #include "lpfc_version.h"
51
52 char *_dump_buf_data;
53 unsigned long _dump_buf_data_order;
54 char *_dump_buf_dif;
55 unsigned long _dump_buf_dif_order;
56 spinlock_t _dump_buf_lock;
57
58 static void lpfc_get_hba_model_desc(struct lpfc_hba *, uint8_t *, uint8_t *);
59 static int lpfc_post_rcv_buf(struct lpfc_hba *);
60 static int lpfc_sli4_queue_create(struct lpfc_hba *);
61 static void lpfc_sli4_queue_destroy(struct lpfc_hba *);
62 static int lpfc_create_bootstrap_mbox(struct lpfc_hba *);
63 static int lpfc_setup_endian_order(struct lpfc_hba *);
64 static int lpfc_sli4_read_config(struct lpfc_hba *);
65 static void lpfc_destroy_bootstrap_mbox(struct lpfc_hba *);
66 static void lpfc_free_sgl_list(struct lpfc_hba *);
67 static int lpfc_init_sgl_list(struct lpfc_hba *);
68 static int lpfc_init_active_sgl_array(struct lpfc_hba *);
69 static void lpfc_free_active_sgl(struct lpfc_hba *);
70 static int lpfc_hba_down_post_s3(struct lpfc_hba *phba);
71 static int lpfc_hba_down_post_s4(struct lpfc_hba *phba);
72 static int lpfc_sli4_cq_event_pool_create(struct lpfc_hba *);
73 static void lpfc_sli4_cq_event_pool_destroy(struct lpfc_hba *);
74 static void lpfc_sli4_cq_event_release_all(struct lpfc_hba *);
75
76 static struct scsi_transport_template *lpfc_transport_template = NULL;
77 static struct scsi_transport_template *lpfc_vport_transport_template = NULL;
78 static DEFINE_IDR(lpfc_hba_index);
79
80 /**
81  * lpfc_config_port_prep - Perform lpfc initialization prior to config port
82  * @phba: pointer to lpfc hba data structure.
83  *
84  * This routine will do LPFC initialization prior to issuing the CONFIG_PORT
85  * mailbox command. It retrieves the revision information from the HBA and
86  * collects the Vital Product Data (VPD) about the HBA for preparing the
87  * configuration of the HBA.
88  *
89  * Return codes:
90  *   0 - success.
91  *   -ERESTART - requests the SLI layer to reset the HBA and try again.
92  *   Any other value - indicates an error.
93  **/
94 int
95 lpfc_config_port_prep(struct lpfc_hba *phba)
96 {
97         lpfc_vpd_t *vp = &phba->vpd;
98         int i = 0, rc;
99         LPFC_MBOXQ_t *pmb;
100         MAILBOX_t *mb;
101         char *lpfc_vpd_data = NULL;
102         uint16_t offset = 0;
103         static char licensed[56] =
104                     "key unlock for use with gnu public licensed code only\0";
105         static int init_key = 1;
106
107         pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
108         if (!pmb) {
109                 phba->link_state = LPFC_HBA_ERROR;
110                 return -ENOMEM;
111         }
112
113         mb = &pmb->u.mb;
114         phba->link_state = LPFC_INIT_MBX_CMDS;
115
116         if (lpfc_is_LC_HBA(phba->pcidev->device)) {
117                 if (init_key) {
118                         uint32_t *ptext = (uint32_t *) licensed;
119
120                         for (i = 0; i < 56; i += sizeof (uint32_t), ptext++)
121                                 *ptext = cpu_to_be32(*ptext);
122                         init_key = 0;
123                 }
124
125                 lpfc_read_nv(phba, pmb);
126                 memset((char*)mb->un.varRDnvp.rsvd3, 0,
127                         sizeof (mb->un.varRDnvp.rsvd3));
128                 memcpy((char*)mb->un.varRDnvp.rsvd3, licensed,
129                          sizeof (licensed));
130
131                 rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
132
133                 if (rc != MBX_SUCCESS) {
134                         lpfc_printf_log(phba, KERN_ERR, LOG_MBOX,
135                                         "0324 Config Port initialization "
136                                         "error, mbxCmd x%x READ_NVPARM, "
137                                         "mbxStatus x%x\n",
138                                         mb->mbxCommand, mb->mbxStatus);
139                         mempool_free(pmb, phba->mbox_mem_pool);
140                         return -ERESTART;
141                 }
142                 memcpy(phba->wwnn, (char *)mb->un.varRDnvp.nodename,
143                        sizeof(phba->wwnn));
144                 memcpy(phba->wwpn, (char *)mb->un.varRDnvp.portname,
145                        sizeof(phba->wwpn));
146         }
147
148         phba->sli3_options = 0x0;
149
150         /* Setup and issue mailbox READ REV command */
151         lpfc_read_rev(phba, pmb);
152         rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
153         if (rc != MBX_SUCCESS) {
154                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
155                                 "0439 Adapter failed to init, mbxCmd x%x "
156                                 "READ_REV, mbxStatus x%x\n",
157                                 mb->mbxCommand, mb->mbxStatus);
158                 mempool_free( pmb, phba->mbox_mem_pool);
159                 return -ERESTART;
160         }
161
162
163         /*
164          * The value of rr must be 1 since the driver set the cv field to 1.
165          * This setting requires the FW to set all revision fields.
166          */
167         if (mb->un.varRdRev.rr == 0) {
168                 vp->rev.rBit = 0;
169                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
170                                 "0440 Adapter failed to init, READ_REV has "
171                                 "missing revision information.\n");
172                 mempool_free(pmb, phba->mbox_mem_pool);
173                 return -ERESTART;
174         }
175
176         if (phba->sli_rev == 3 && !mb->un.varRdRev.v3rsp) {
177                 mempool_free(pmb, phba->mbox_mem_pool);
178                 return -EINVAL;
179         }
180
181         /* Save information as VPD data */
182         vp->rev.rBit = 1;
183         memcpy(&vp->sli3Feat, &mb->un.varRdRev.sli3Feat, sizeof(uint32_t));
184         vp->rev.sli1FwRev = mb->un.varRdRev.sli1FwRev;
185         memcpy(vp->rev.sli1FwName, (char*) mb->un.varRdRev.sli1FwName, 16);
186         vp->rev.sli2FwRev = mb->un.varRdRev.sli2FwRev;
187         memcpy(vp->rev.sli2FwName, (char *) mb->un.varRdRev.sli2FwName, 16);
188         vp->rev.biuRev = mb->un.varRdRev.biuRev;
189         vp->rev.smRev = mb->un.varRdRev.smRev;
190         vp->rev.smFwRev = mb->un.varRdRev.un.smFwRev;
191         vp->rev.endecRev = mb->un.varRdRev.endecRev;
192         vp->rev.fcphHigh = mb->un.varRdRev.fcphHigh;
193         vp->rev.fcphLow = mb->un.varRdRev.fcphLow;
194         vp->rev.feaLevelHigh = mb->un.varRdRev.feaLevelHigh;
195         vp->rev.feaLevelLow = mb->un.varRdRev.feaLevelLow;
196         vp->rev.postKernRev = mb->un.varRdRev.postKernRev;
197         vp->rev.opFwRev = mb->un.varRdRev.opFwRev;
198
199         /* If the sli feature level is less then 9, we must
200          * tear down all RPIs and VPIs on link down if NPIV
201          * is enabled.
202          */
203         if (vp->rev.feaLevelHigh < 9)
204                 phba->sli3_options |= LPFC_SLI3_VPORT_TEARDOWN;
205
206         if (lpfc_is_LC_HBA(phba->pcidev->device))
207                 memcpy(phba->RandomData, (char *)&mb->un.varWords[24],
208                                                 sizeof (phba->RandomData));
209
210         /* Get adapter VPD information */
211         lpfc_vpd_data = kmalloc(DMP_VPD_SIZE, GFP_KERNEL);
212         if (!lpfc_vpd_data)
213                 goto out_free_mbox;
214
215         do {
216                 lpfc_dump_mem(phba, pmb, offset, DMP_REGION_VPD);
217                 rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
218
219                 if (rc != MBX_SUCCESS) {
220                         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
221                                         "0441 VPD not present on adapter, "
222                                         "mbxCmd x%x DUMP VPD, mbxStatus x%x\n",
223                                         mb->mbxCommand, mb->mbxStatus);
224                         mb->un.varDmp.word_cnt = 0;
225                 }
226                 /* dump mem may return a zero when finished or we got a
227                  * mailbox error, either way we are done.
228                  */
229                 if (mb->un.varDmp.word_cnt == 0)
230                         break;
231                 if (mb->un.varDmp.word_cnt > DMP_VPD_SIZE - offset)
232                         mb->un.varDmp.word_cnt = DMP_VPD_SIZE - offset;
233                 lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
234                                       lpfc_vpd_data + offset,
235                                       mb->un.varDmp.word_cnt);
236                 offset += mb->un.varDmp.word_cnt;
237         } while (mb->un.varDmp.word_cnt && offset < DMP_VPD_SIZE);
238         lpfc_parse_vpd(phba, lpfc_vpd_data, offset);
239
240         kfree(lpfc_vpd_data);
241 out_free_mbox:
242         mempool_free(pmb, phba->mbox_mem_pool);
243         return 0;
244 }
245
246 /**
247  * lpfc_config_async_cmpl - Completion handler for config async event mbox cmd
248  * @phba: pointer to lpfc hba data structure.
249  * @pmboxq: pointer to the driver internal queue element for mailbox command.
250  *
251  * This is the completion handler for driver's configuring asynchronous event
252  * mailbox command to the device. If the mailbox command returns successfully,
253  * it will set internal async event support flag to 1; otherwise, it will
254  * set internal async event support flag to 0.
255  **/
256 static void
257 lpfc_config_async_cmpl(struct lpfc_hba * phba, LPFC_MBOXQ_t * pmboxq)
258 {
259         if (pmboxq->u.mb.mbxStatus == MBX_SUCCESS)
260                 phba->temp_sensor_support = 1;
261         else
262                 phba->temp_sensor_support = 0;
263         mempool_free(pmboxq, phba->mbox_mem_pool);
264         return;
265 }
266
267 /**
268  * lpfc_dump_wakeup_param_cmpl - dump memory mailbox command completion handler
269  * @phba: pointer to lpfc hba data structure.
270  * @pmboxq: pointer to the driver internal queue element for mailbox command.
271  *
272  * This is the completion handler for dump mailbox command for getting
273  * wake up parameters. When this command complete, the response contain
274  * Option rom version of the HBA. This function translate the version number
275  * into a human readable string and store it in OptionROMVersion.
276  **/
277 static void
278 lpfc_dump_wakeup_param_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
279 {
280         struct prog_id *prg;
281         uint32_t prog_id_word;
282         char dist = ' ';
283         /* character array used for decoding dist type. */
284         char dist_char[] = "nabx";
285
286         if (pmboxq->u.mb.mbxStatus != MBX_SUCCESS) {
287                 mempool_free(pmboxq, phba->mbox_mem_pool);
288                 return;
289         }
290
291         prg = (struct prog_id *) &prog_id_word;
292
293         /* word 7 contain option rom version */
294         prog_id_word = pmboxq->u.mb.un.varWords[7];
295
296         /* Decode the Option rom version word to a readable string */
297         if (prg->dist < 4)
298                 dist = dist_char[prg->dist];
299
300         if ((prg->dist == 3) && (prg->num == 0))
301                 sprintf(phba->OptionROMVersion, "%d.%d%d",
302                         prg->ver, prg->rev, prg->lev);
303         else
304                 sprintf(phba->OptionROMVersion, "%d.%d%d%c%d",
305                         prg->ver, prg->rev, prg->lev,
306                         dist, prg->num);
307         mempool_free(pmboxq, phba->mbox_mem_pool);
308         return;
309 }
310
311 /**
312  * lpfc_config_port_post - Perform lpfc initialization after config port
313  * @phba: pointer to lpfc hba data structure.
314  *
315  * This routine will do LPFC initialization after the CONFIG_PORT mailbox
316  * command call. It performs all internal resource and state setups on the
317  * port: post IOCB buffers, enable appropriate host interrupt attentions,
318  * ELS ring timers, etc.
319  *
320  * Return codes
321  *   0 - success.
322  *   Any other value - error.
323  **/
324 int
325 lpfc_config_port_post(struct lpfc_hba *phba)
326 {
327         struct lpfc_vport *vport = phba->pport;
328         struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
329         LPFC_MBOXQ_t *pmb;
330         MAILBOX_t *mb;
331         struct lpfc_dmabuf *mp;
332         struct lpfc_sli *psli = &phba->sli;
333         uint32_t status, timeout;
334         int i, j;
335         int rc;
336
337         spin_lock_irq(&phba->hbalock);
338         /*
339          * If the Config port completed correctly the HBA is not
340          * over heated any more.
341          */
342         if (phba->over_temp_state == HBA_OVER_TEMP)
343                 phba->over_temp_state = HBA_NORMAL_TEMP;
344         spin_unlock_irq(&phba->hbalock);
345
346         pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
347         if (!pmb) {
348                 phba->link_state = LPFC_HBA_ERROR;
349                 return -ENOMEM;
350         }
351         mb = &pmb->u.mb;
352
353         /* Get login parameters for NID.  */
354         rc = lpfc_read_sparam(phba, pmb, 0);
355         if (rc) {
356                 mempool_free(pmb, phba->mbox_mem_pool);
357                 return -ENOMEM;
358         }
359
360         pmb->vport = vport;
361         if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
362                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
363                                 "0448 Adapter failed init, mbxCmd x%x "
364                                 "READ_SPARM mbxStatus x%x\n",
365                                 mb->mbxCommand, mb->mbxStatus);
366                 phba->link_state = LPFC_HBA_ERROR;
367                 mp = (struct lpfc_dmabuf *) pmb->context1;
368                 mempool_free(pmb, phba->mbox_mem_pool);
369                 lpfc_mbuf_free(phba, mp->virt, mp->phys);
370                 kfree(mp);
371                 return -EIO;
372         }
373
374         mp = (struct lpfc_dmabuf *) pmb->context1;
375
376         memcpy(&vport->fc_sparam, mp->virt, sizeof (struct serv_parm));
377         lpfc_mbuf_free(phba, mp->virt, mp->phys);
378         kfree(mp);
379         pmb->context1 = NULL;
380
381         if (phba->cfg_soft_wwnn)
382                 u64_to_wwn(phba->cfg_soft_wwnn,
383                            vport->fc_sparam.nodeName.u.wwn);
384         if (phba->cfg_soft_wwpn)
385                 u64_to_wwn(phba->cfg_soft_wwpn,
386                            vport->fc_sparam.portName.u.wwn);
387         memcpy(&vport->fc_nodename, &vport->fc_sparam.nodeName,
388                sizeof (struct lpfc_name));
389         memcpy(&vport->fc_portname, &vport->fc_sparam.portName,
390                sizeof (struct lpfc_name));
391
392         /* Update the fc_host data structures with new wwn. */
393         fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
394         fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
395         fc_host_max_npiv_vports(shost) = phba->max_vpi;
396
397         /* If no serial number in VPD data, use low 6 bytes of WWNN */
398         /* This should be consolidated into parse_vpd ? - mr */
399         if (phba->SerialNumber[0] == 0) {
400                 uint8_t *outptr;
401
402                 outptr = &vport->fc_nodename.u.s.IEEE[0];
403                 for (i = 0; i < 12; i++) {
404                         status = *outptr++;
405                         j = ((status & 0xf0) >> 4);
406                         if (j <= 9)
407                                 phba->SerialNumber[i] =
408                                     (char)((uint8_t) 0x30 + (uint8_t) j);
409                         else
410                                 phba->SerialNumber[i] =
411                                     (char)((uint8_t) 0x61 + (uint8_t) (j - 10));
412                         i++;
413                         j = (status & 0xf);
414                         if (j <= 9)
415                                 phba->SerialNumber[i] =
416                                     (char)((uint8_t) 0x30 + (uint8_t) j);
417                         else
418                                 phba->SerialNumber[i] =
419                                     (char)((uint8_t) 0x61 + (uint8_t) (j - 10));
420                 }
421         }
422
423         lpfc_read_config(phba, pmb);
424         pmb->vport = vport;
425         if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
426                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
427                                 "0453 Adapter failed to init, mbxCmd x%x "
428                                 "READ_CONFIG, mbxStatus x%x\n",
429                                 mb->mbxCommand, mb->mbxStatus);
430                 phba->link_state = LPFC_HBA_ERROR;
431                 mempool_free( pmb, phba->mbox_mem_pool);
432                 return -EIO;
433         }
434
435         /* Check if the port is disabled */
436         lpfc_sli_read_link_ste(phba);
437
438         /* Reset the DFT_HBA_Q_DEPTH to the max xri  */
439         if (phba->cfg_hba_queue_depth > (mb->un.varRdConfig.max_xri+1))
440                 phba->cfg_hba_queue_depth =
441                         (mb->un.varRdConfig.max_xri + 1) -
442                                         lpfc_sli4_get_els_iocb_cnt(phba);
443
444         phba->lmt = mb->un.varRdConfig.lmt;
445
446         /* Get the default values for Model Name and Description */
447         lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
448
449         if ((phba->cfg_link_speed > LPFC_USER_LINK_SPEED_16G)
450             || ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_1G)
451                 && !(phba->lmt & LMT_1Gb))
452             || ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_2G)
453                 && !(phba->lmt & LMT_2Gb))
454             || ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_4G)
455                 && !(phba->lmt & LMT_4Gb))
456             || ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_8G)
457                 && !(phba->lmt & LMT_8Gb))
458             || ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_10G)
459                 && !(phba->lmt & LMT_10Gb))
460             || ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_16G)
461                 && !(phba->lmt & LMT_16Gb))) {
462                 /* Reset link speed to auto */
463                 lpfc_printf_log(phba, KERN_WARNING, LOG_LINK_EVENT,
464                         "1302 Invalid speed for this board: "
465                         "Reset link speed to auto: x%x\n",
466                         phba->cfg_link_speed);
467                         phba->cfg_link_speed = LPFC_USER_LINK_SPEED_AUTO;
468         }
469
470         phba->link_state = LPFC_LINK_DOWN;
471
472         /* Only process IOCBs on ELS ring till hba_state is READY */
473         if (psli->ring[psli->extra_ring].cmdringaddr)
474                 psli->ring[psli->extra_ring].flag |= LPFC_STOP_IOCB_EVENT;
475         if (psli->ring[psli->fcp_ring].cmdringaddr)
476                 psli->ring[psli->fcp_ring].flag |= LPFC_STOP_IOCB_EVENT;
477         if (psli->ring[psli->next_ring].cmdringaddr)
478                 psli->ring[psli->next_ring].flag |= LPFC_STOP_IOCB_EVENT;
479
480         /* Post receive buffers for desired rings */
481         if (phba->sli_rev != 3)
482                 lpfc_post_rcv_buf(phba);
483
484         /*
485          * Configure HBA MSI-X attention conditions to messages if MSI-X mode
486          */
487         if (phba->intr_type == MSIX) {
488                 rc = lpfc_config_msi(phba, pmb);
489                 if (rc) {
490                         mempool_free(pmb, phba->mbox_mem_pool);
491                         return -EIO;
492                 }
493                 rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
494                 if (rc != MBX_SUCCESS) {
495                         lpfc_printf_log(phba, KERN_ERR, LOG_MBOX,
496                                         "0352 Config MSI mailbox command "
497                                         "failed, mbxCmd x%x, mbxStatus x%x\n",
498                                         pmb->u.mb.mbxCommand,
499                                         pmb->u.mb.mbxStatus);
500                         mempool_free(pmb, phba->mbox_mem_pool);
501                         return -EIO;
502                 }
503         }
504
505         spin_lock_irq(&phba->hbalock);
506         /* Initialize ERATT handling flag */
507         phba->hba_flag &= ~HBA_ERATT_HANDLED;
508
509         /* Enable appropriate host interrupts */
510         status = readl(phba->HCregaddr);
511         status |= HC_MBINT_ENA | HC_ERINT_ENA | HC_LAINT_ENA;
512         if (psli->num_rings > 0)
513                 status |= HC_R0INT_ENA;
514         if (psli->num_rings > 1)
515                 status |= HC_R1INT_ENA;
516         if (psli->num_rings > 2)
517                 status |= HC_R2INT_ENA;
518         if (psli->num_rings > 3)
519                 status |= HC_R3INT_ENA;
520
521         if ((phba->cfg_poll & ENABLE_FCP_RING_POLLING) &&
522             (phba->cfg_poll & DISABLE_FCP_RING_INT))
523                 status &= ~(HC_R0INT_ENA);
524
525         writel(status, phba->HCregaddr);
526         readl(phba->HCregaddr); /* flush */
527         spin_unlock_irq(&phba->hbalock);
528
529         /* Set up ring-0 (ELS) timer */
530         timeout = phba->fc_ratov * 2;
531         mod_timer(&vport->els_tmofunc, jiffies + HZ * timeout);
532         /* Set up heart beat (HB) timer */
533         mod_timer(&phba->hb_tmofunc, jiffies + HZ * LPFC_HB_MBOX_INTERVAL);
534         phba->hb_outstanding = 0;
535         phba->last_completion_time = jiffies;
536         /* Set up error attention (ERATT) polling timer */
537         mod_timer(&phba->eratt_poll, jiffies + HZ * LPFC_ERATT_POLL_INTERVAL);
538
539         if (phba->hba_flag & LINK_DISABLED) {
540                 lpfc_printf_log(phba,
541                         KERN_ERR, LOG_INIT,
542                         "2598 Adapter Link is disabled.\n");
543                 lpfc_down_link(phba, pmb);
544                 pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
545                 rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
546                 if ((rc != MBX_SUCCESS) && (rc != MBX_BUSY)) {
547                         lpfc_printf_log(phba,
548                         KERN_ERR, LOG_INIT,
549                         "2599 Adapter failed to issue DOWN_LINK"
550                         " mbox command rc 0x%x\n", rc);
551
552                         mempool_free(pmb, phba->mbox_mem_pool);
553                         return -EIO;
554                 }
555         } else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
556                 lpfc_init_link(phba, pmb, phba->cfg_topology,
557                         phba->cfg_link_speed);
558                 pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
559                 lpfc_set_loopback_flag(phba);
560                 rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
561                 if (rc != MBX_SUCCESS) {
562                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
563                                 "0454 Adapter failed to init, mbxCmd x%x "
564                                 "INIT_LINK, mbxStatus x%x\n",
565                                 mb->mbxCommand, mb->mbxStatus);
566
567                         /* Clear all interrupt enable conditions */
568                         writel(0, phba->HCregaddr);
569                         readl(phba->HCregaddr); /* flush */
570                         /* Clear all pending interrupts */
571                         writel(0xffffffff, phba->HAregaddr);
572                         readl(phba->HAregaddr); /* flush */
573
574                         phba->link_state = LPFC_HBA_ERROR;
575                         if (rc != MBX_BUSY)
576                                 mempool_free(pmb, phba->mbox_mem_pool);
577                         return -EIO;
578                 }
579         }
580         /* MBOX buffer will be freed in mbox compl */
581         pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
582         if (!pmb) {
583                 phba->link_state = LPFC_HBA_ERROR;
584                 return -ENOMEM;
585         }
586
587         lpfc_config_async(phba, pmb, LPFC_ELS_RING);
588         pmb->mbox_cmpl = lpfc_config_async_cmpl;
589         pmb->vport = phba->pport;
590         rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
591
592         if ((rc != MBX_BUSY) && (rc != MBX_SUCCESS)) {
593                 lpfc_printf_log(phba,
594                                 KERN_ERR,
595                                 LOG_INIT,
596                                 "0456 Adapter failed to issue "
597                                 "ASYNCEVT_ENABLE mbox status x%x\n",
598                                 rc);
599                 mempool_free(pmb, phba->mbox_mem_pool);
600         }
601
602         /* Get Option rom version */
603         pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
604         if (!pmb) {
605                 phba->link_state = LPFC_HBA_ERROR;
606                 return -ENOMEM;
607         }
608
609         lpfc_dump_wakeup_param(phba, pmb);
610         pmb->mbox_cmpl = lpfc_dump_wakeup_param_cmpl;
611         pmb->vport = phba->pport;
612         rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
613
614         if ((rc != MBX_BUSY) && (rc != MBX_SUCCESS)) {
615                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT, "0435 Adapter failed "
616                                 "to get Option ROM version status x%x\n", rc);
617                 mempool_free(pmb, phba->mbox_mem_pool);
618         }
619
620         return 0;
621 }
622
623 /**
624  * lpfc_hba_init_link - Initialize the FC link
625  * @phba: pointer to lpfc hba data structure.
626  * @flag: mailbox command issue mode - either MBX_POLL or MBX_NOWAIT
627  *
628  * This routine will issue the INIT_LINK mailbox command call.
629  * It is available to other drivers through the lpfc_hba data
630  * structure for use as a delayed link up mechanism with the
631  * module parameter lpfc_suppress_link_up.
632  *
633  * Return code
634  *              0 - success
635  *              Any other value - error
636  **/
637 int
638 lpfc_hba_init_link(struct lpfc_hba *phba, uint32_t flag)
639 {
640         struct lpfc_vport *vport = phba->pport;
641         LPFC_MBOXQ_t *pmb;
642         MAILBOX_t *mb;
643         int rc;
644
645         pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
646         if (!pmb) {
647                 phba->link_state = LPFC_HBA_ERROR;
648                 return -ENOMEM;
649         }
650         mb = &pmb->u.mb;
651         pmb->vport = vport;
652
653         lpfc_init_link(phba, pmb, phba->cfg_topology, phba->cfg_link_speed);
654         pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
655         lpfc_set_loopback_flag(phba);
656         rc = lpfc_sli_issue_mbox(phba, pmb, flag);
657         if ((rc != MBX_BUSY) && (rc != MBX_SUCCESS)) {
658                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
659                         "0498 Adapter failed to init, mbxCmd x%x "
660                         "INIT_LINK, mbxStatus x%x\n",
661                         mb->mbxCommand, mb->mbxStatus);
662                 if (phba->sli_rev <= LPFC_SLI_REV3) {
663                         /* Clear all interrupt enable conditions */
664                         writel(0, phba->HCregaddr);
665                         readl(phba->HCregaddr); /* flush */
666                         /* Clear all pending interrupts */
667                         writel(0xffffffff, phba->HAregaddr);
668                         readl(phba->HAregaddr); /* flush */
669                 }
670                 phba->link_state = LPFC_HBA_ERROR;
671                 if (rc != MBX_BUSY || flag == MBX_POLL)
672                         mempool_free(pmb, phba->mbox_mem_pool);
673                 return -EIO;
674         }
675         phba->cfg_suppress_link_up = LPFC_INITIALIZE_LINK;
676         if (flag == MBX_POLL)
677                 mempool_free(pmb, phba->mbox_mem_pool);
678
679         return 0;
680 }
681
682 /**
683  * lpfc_hba_down_link - this routine downs the FC link
684  * @phba: pointer to lpfc hba data structure.
685  * @flag: mailbox command issue mode - either MBX_POLL or MBX_NOWAIT
686  *
687  * This routine will issue the DOWN_LINK mailbox command call.
688  * It is available to other drivers through the lpfc_hba data
689  * structure for use to stop the link.
690  *
691  * Return code
692  *              0 - success
693  *              Any other value - error
694  **/
695 int
696 lpfc_hba_down_link(struct lpfc_hba *phba, uint32_t flag)
697 {
698         LPFC_MBOXQ_t *pmb;
699         int rc;
700
701         pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
702         if (!pmb) {
703                 phba->link_state = LPFC_HBA_ERROR;
704                 return -ENOMEM;
705         }
706
707         lpfc_printf_log(phba,
708                 KERN_ERR, LOG_INIT,
709                 "0491 Adapter Link is disabled.\n");
710         lpfc_down_link(phba, pmb);
711         pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
712         rc = lpfc_sli_issue_mbox(phba, pmb, flag);
713         if ((rc != MBX_SUCCESS) && (rc != MBX_BUSY)) {
714                 lpfc_printf_log(phba,
715                 KERN_ERR, LOG_INIT,
716                 "2522 Adapter failed to issue DOWN_LINK"
717                 " mbox command rc 0x%x\n", rc);
718
719                 mempool_free(pmb, phba->mbox_mem_pool);
720                 return -EIO;
721         }
722         if (flag == MBX_POLL)
723                 mempool_free(pmb, phba->mbox_mem_pool);
724
725         return 0;
726 }
727
728 /**
729  * lpfc_hba_down_prep - Perform lpfc uninitialization prior to HBA reset
730  * @phba: pointer to lpfc HBA data structure.
731  *
732  * This routine will do LPFC uninitialization before the HBA is reset when
733  * bringing down the SLI Layer.
734  *
735  * Return codes
736  *   0 - success.
737  *   Any other value - error.
738  **/
739 int
740 lpfc_hba_down_prep(struct lpfc_hba *phba)
741 {
742         struct lpfc_vport **vports;
743         int i;
744
745         if (phba->sli_rev <= LPFC_SLI_REV3) {
746                 /* Disable interrupts */
747                 writel(0, phba->HCregaddr);
748                 readl(phba->HCregaddr); /* flush */
749         }
750
751         if (phba->pport->load_flag & FC_UNLOADING)
752                 lpfc_cleanup_discovery_resources(phba->pport);
753         else {
754                 vports = lpfc_create_vport_work_array(phba);
755                 if (vports != NULL)
756                         for (i = 0; i <= phba->max_vports &&
757                                 vports[i] != NULL; i++)
758                                 lpfc_cleanup_discovery_resources(vports[i]);
759                 lpfc_destroy_vport_work_array(phba, vports);
760         }
761         return 0;
762 }
763
764 /**
765  * lpfc_hba_down_post_s3 - Perform lpfc uninitialization after HBA reset
766  * @phba: pointer to lpfc HBA data structure.
767  *
768  * This routine will do uninitialization after the HBA is reset when bring
769  * down the SLI Layer.
770  *
771  * Return codes
772  *   0 - success.
773  *   Any other value - error.
774  **/
775 static int
776 lpfc_hba_down_post_s3(struct lpfc_hba *phba)
777 {
778         struct lpfc_sli *psli = &phba->sli;
779         struct lpfc_sli_ring *pring;
780         struct lpfc_dmabuf *mp, *next_mp;
781         LIST_HEAD(completions);
782         int i;
783
784         if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)
785                 lpfc_sli_hbqbuf_free_all(phba);
786         else {
787                 /* Cleanup preposted buffers on the ELS ring */
788                 pring = &psli->ring[LPFC_ELS_RING];
789                 list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
790                         list_del(&mp->list);
791                         pring->postbufq_cnt--;
792                         lpfc_mbuf_free(phba, mp->virt, mp->phys);
793                         kfree(mp);
794                 }
795         }
796
797         spin_lock_irq(&phba->hbalock);
798         for (i = 0; i < psli->num_rings; i++) {
799                 pring = &psli->ring[i];
800
801                 /* At this point in time the HBA is either reset or DOA. Either
802                  * way, nothing should be on txcmplq as it will NEVER complete.
803                  */
804                 list_splice_init(&pring->txcmplq, &completions);
805                 pring->txcmplq_cnt = 0;
806                 spin_unlock_irq(&phba->hbalock);
807
808                 /* Cancel all the IOCBs from the completions list */
809                 lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
810                                       IOERR_SLI_ABORTED);
811
812                 lpfc_sli_abort_iocb_ring(phba, pring);
813                 spin_lock_irq(&phba->hbalock);
814         }
815         spin_unlock_irq(&phba->hbalock);
816
817         return 0;
818 }
819
820 /**
821  * lpfc_hba_down_post_s4 - Perform lpfc uninitialization after HBA reset
822  * @phba: pointer to lpfc HBA data structure.
823  *
824  * This routine will do uninitialization after the HBA is reset when bring
825  * down the SLI Layer.
826  *
827  * Return codes
828  *   0 - success.
829  *   Any other value - error.
830  **/
831 static int
832 lpfc_hba_down_post_s4(struct lpfc_hba *phba)
833 {
834         struct lpfc_scsi_buf *psb, *psb_next;
835         LIST_HEAD(aborts);
836         int ret;
837         unsigned long iflag = 0;
838         struct lpfc_sglq *sglq_entry = NULL;
839
840         ret = lpfc_hba_down_post_s3(phba);
841         if (ret)
842                 return ret;
843         /* At this point in time the HBA is either reset or DOA. Either
844          * way, nothing should be on lpfc_abts_els_sgl_list, it needs to be
845          * on the lpfc_sgl_list so that it can either be freed if the
846          * driver is unloading or reposted if the driver is restarting
847          * the port.
848          */
849         spin_lock_irq(&phba->hbalock);  /* required for lpfc_sgl_list and */
850                                         /* scsl_buf_list */
851         /* abts_sgl_list_lock required because worker thread uses this
852          * list.
853          */
854         spin_lock(&phba->sli4_hba.abts_sgl_list_lock);
855         list_for_each_entry(sglq_entry,
856                 &phba->sli4_hba.lpfc_abts_els_sgl_list, list)
857                 sglq_entry->state = SGL_FREED;
858
859         list_splice_init(&phba->sli4_hba.lpfc_abts_els_sgl_list,
860                         &phba->sli4_hba.lpfc_sgl_list);
861         spin_unlock(&phba->sli4_hba.abts_sgl_list_lock);
862         /* abts_scsi_buf_list_lock required because worker thread uses this
863          * list.
864          */
865         spin_lock(&phba->sli4_hba.abts_scsi_buf_list_lock);
866         list_splice_init(&phba->sli4_hba.lpfc_abts_scsi_buf_list,
867                         &aborts);
868         spin_unlock(&phba->sli4_hba.abts_scsi_buf_list_lock);
869         spin_unlock_irq(&phba->hbalock);
870
871         list_for_each_entry_safe(psb, psb_next, &aborts, list) {
872                 psb->pCmd = NULL;
873                 psb->status = IOSTAT_SUCCESS;
874         }
875         spin_lock_irqsave(&phba->scsi_buf_list_lock, iflag);
876         list_splice(&aborts, &phba->lpfc_scsi_buf_list);
877         spin_unlock_irqrestore(&phba->scsi_buf_list_lock, iflag);
878         return 0;
879 }
880
881 /**
882  * lpfc_hba_down_post - Wrapper func for hba down post routine
883  * @phba: pointer to lpfc HBA data structure.
884  *
885  * This routine wraps the actual SLI3 or SLI4 routine for performing
886  * uninitialization after the HBA is reset when bring down the SLI Layer.
887  *
888  * Return codes
889  *   0 - success.
890  *   Any other value - error.
891  **/
892 int
893 lpfc_hba_down_post(struct lpfc_hba *phba)
894 {
895         return (*phba->lpfc_hba_down_post)(phba);
896 }
897
898 /**
899  * lpfc_hb_timeout - The HBA-timer timeout handler
900  * @ptr: unsigned long holds the pointer to lpfc hba data structure.
901  *
902  * This is the HBA-timer timeout handler registered to the lpfc driver. When
903  * this timer fires, a HBA timeout event shall be posted to the lpfc driver
904  * work-port-events bitmap and the worker thread is notified. This timeout
905  * event will be used by the worker thread to invoke the actual timeout
906  * handler routine, lpfc_hb_timeout_handler. Any periodical operations will
907  * be performed in the timeout handler and the HBA timeout event bit shall
908  * be cleared by the worker thread after it has taken the event bitmap out.
909  **/
910 static void
911 lpfc_hb_timeout(unsigned long ptr)
912 {
913         struct lpfc_hba *phba;
914         uint32_t tmo_posted;
915         unsigned long iflag;
916
917         phba = (struct lpfc_hba *)ptr;
918
919         /* Check for heart beat timeout conditions */
920         spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
921         tmo_posted = phba->pport->work_port_events & WORKER_HB_TMO;
922         if (!tmo_posted)
923                 phba->pport->work_port_events |= WORKER_HB_TMO;
924         spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
925
926         /* Tell the worker thread there is work to do */
927         if (!tmo_posted)
928                 lpfc_worker_wake_up(phba);
929         return;
930 }
931
932 /**
933  * lpfc_rrq_timeout - The RRQ-timer timeout handler
934  * @ptr: unsigned long holds the pointer to lpfc hba data structure.
935  *
936  * This is the RRQ-timer timeout handler registered to the lpfc driver. When
937  * this timer fires, a RRQ timeout event shall be posted to the lpfc driver
938  * work-port-events bitmap and the worker thread is notified. This timeout
939  * event will be used by the worker thread to invoke the actual timeout
940  * handler routine, lpfc_rrq_handler. Any periodical operations will
941  * be performed in the timeout handler and the RRQ timeout event bit shall
942  * be cleared by the worker thread after it has taken the event bitmap out.
943  **/
944 static void
945 lpfc_rrq_timeout(unsigned long ptr)
946 {
947         struct lpfc_hba *phba;
948         uint32_t tmo_posted;
949         unsigned long iflag;
950
951         phba = (struct lpfc_hba *)ptr;
952         spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
953         tmo_posted = phba->hba_flag & HBA_RRQ_ACTIVE;
954         if (!tmo_posted)
955                 phba->hba_flag |= HBA_RRQ_ACTIVE;
956         spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
957         if (!tmo_posted)
958                 lpfc_worker_wake_up(phba);
959 }
960
961 /**
962  * lpfc_hb_mbox_cmpl - The lpfc heart-beat mailbox command callback function
963  * @phba: pointer to lpfc hba data structure.
964  * @pmboxq: pointer to the driver internal queue element for mailbox command.
965  *
966  * This is the callback function to the lpfc heart-beat mailbox command.
967  * If configured, the lpfc driver issues the heart-beat mailbox command to
968  * the HBA every LPFC_HB_MBOX_INTERVAL (current 5) seconds. At the time the
969  * heart-beat mailbox command is issued, the driver shall set up heart-beat
970  * timeout timer to LPFC_HB_MBOX_TIMEOUT (current 30) seconds and marks
971  * heart-beat outstanding state. Once the mailbox command comes back and
972  * no error conditions detected, the heart-beat mailbox command timer is
973  * reset to LPFC_HB_MBOX_INTERVAL seconds and the heart-beat outstanding
974  * state is cleared for the next heart-beat. If the timer expired with the
975  * heart-beat outstanding state set, the driver will put the HBA offline.
976  **/
977 static void
978 lpfc_hb_mbox_cmpl(struct lpfc_hba * phba, LPFC_MBOXQ_t * pmboxq)
979 {
980         unsigned long drvr_flag;
981
982         spin_lock_irqsave(&phba->hbalock, drvr_flag);
983         phba->hb_outstanding = 0;
984         spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
985
986         /* Check and reset heart-beat timer is necessary */
987         mempool_free(pmboxq, phba->mbox_mem_pool);
988         if (!(phba->pport->fc_flag & FC_OFFLINE_MODE) &&
989                 !(phba->link_state == LPFC_HBA_ERROR) &&
990                 !(phba->pport->load_flag & FC_UNLOADING))
991                 mod_timer(&phba->hb_tmofunc,
992                         jiffies + HZ * LPFC_HB_MBOX_INTERVAL);
993         return;
994 }
995
996 /**
997  * lpfc_hb_timeout_handler - The HBA-timer timeout handler
998  * @phba: pointer to lpfc hba data structure.
999  *
1000  * This is the actual HBA-timer timeout handler to be invoked by the worker
1001  * thread whenever the HBA timer fired and HBA-timeout event posted. This
1002  * handler performs any periodic operations needed for the device. If such
1003  * periodic event has already been attended to either in the interrupt handler
1004  * or by processing slow-ring or fast-ring events within the HBA-timer
1005  * timeout window (LPFC_HB_MBOX_INTERVAL), this handler just simply resets
1006  * the timer for the next timeout period. If lpfc heart-beat mailbox command
1007  * is configured and there is no heart-beat mailbox command outstanding, a
1008  * heart-beat mailbox is issued and timer set properly. Otherwise, if there
1009  * has been a heart-beat mailbox command outstanding, the HBA shall be put
1010  * to offline.
1011  **/
1012 void
1013 lpfc_hb_timeout_handler(struct lpfc_hba *phba)
1014 {
1015         struct lpfc_vport **vports;
1016         LPFC_MBOXQ_t *pmboxq;
1017         struct lpfc_dmabuf *buf_ptr;
1018         int retval, i;
1019         struct lpfc_sli *psli = &phba->sli;
1020         LIST_HEAD(completions);
1021
1022         vports = lpfc_create_vport_work_array(phba);
1023         if (vports != NULL)
1024                 for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++)
1025                         lpfc_rcv_seq_check_edtov(vports[i]);
1026         lpfc_destroy_vport_work_array(phba, vports);
1027
1028         if ((phba->link_state == LPFC_HBA_ERROR) ||
1029                 (phba->pport->load_flag & FC_UNLOADING) ||
1030                 (phba->pport->fc_flag & FC_OFFLINE_MODE))
1031                 return;
1032
1033         spin_lock_irq(&phba->pport->work_port_lock);
1034
1035         if (time_after(phba->last_completion_time + LPFC_HB_MBOX_INTERVAL * HZ,
1036                 jiffies)) {
1037                 spin_unlock_irq(&phba->pport->work_port_lock);
1038                 if (!phba->hb_outstanding)
1039                         mod_timer(&phba->hb_tmofunc,
1040                                 jiffies + HZ * LPFC_HB_MBOX_INTERVAL);
1041                 else
1042                         mod_timer(&phba->hb_tmofunc,
1043                                 jiffies + HZ * LPFC_HB_MBOX_TIMEOUT);
1044                 return;
1045         }
1046         spin_unlock_irq(&phba->pport->work_port_lock);
1047
1048         if (phba->elsbuf_cnt &&
1049                 (phba->elsbuf_cnt == phba->elsbuf_prev_cnt)) {
1050                 spin_lock_irq(&phba->hbalock);
1051                 list_splice_init(&phba->elsbuf, &completions);
1052                 phba->elsbuf_cnt = 0;
1053                 phba->elsbuf_prev_cnt = 0;
1054                 spin_unlock_irq(&phba->hbalock);
1055
1056                 while (!list_empty(&completions)) {
1057                         list_remove_head(&completions, buf_ptr,
1058                                 struct lpfc_dmabuf, list);
1059                         lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
1060                         kfree(buf_ptr);
1061                 }
1062         }
1063         phba->elsbuf_prev_cnt = phba->elsbuf_cnt;
1064
1065         /* If there is no heart beat outstanding, issue a heartbeat command */
1066         if (phba->cfg_enable_hba_heartbeat) {
1067                 if (!phba->hb_outstanding) {
1068                         if ((!(psli->sli_flag & LPFC_SLI_MBOX_ACTIVE)) &&
1069                                 (list_empty(&psli->mboxq))) {
1070                                 pmboxq = mempool_alloc(phba->mbox_mem_pool,
1071                                                         GFP_KERNEL);
1072                                 if (!pmboxq) {
1073                                         mod_timer(&phba->hb_tmofunc,
1074                                                  jiffies +
1075                                                  HZ * LPFC_HB_MBOX_INTERVAL);
1076                                         return;
1077                                 }
1078
1079                                 lpfc_heart_beat(phba, pmboxq);
1080                                 pmboxq->mbox_cmpl = lpfc_hb_mbox_cmpl;
1081                                 pmboxq->vport = phba->pport;
1082                                 retval = lpfc_sli_issue_mbox(phba, pmboxq,
1083                                                 MBX_NOWAIT);
1084
1085                                 if (retval != MBX_BUSY &&
1086                                         retval != MBX_SUCCESS) {
1087                                         mempool_free(pmboxq,
1088                                                         phba->mbox_mem_pool);
1089                                         mod_timer(&phba->hb_tmofunc,
1090                                                 jiffies +
1091                                                 HZ * LPFC_HB_MBOX_INTERVAL);
1092                                         return;
1093                                 }
1094                                 phba->skipped_hb = 0;
1095                                 phba->hb_outstanding = 1;
1096                         } else if (time_before_eq(phba->last_completion_time,
1097                                         phba->skipped_hb)) {
1098                                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
1099                                         "2857 Last completion time not "
1100                                         " updated in %d ms\n",
1101                                         jiffies_to_msecs(jiffies
1102                                                  - phba->last_completion_time));
1103                         } else
1104                                 phba->skipped_hb = jiffies;
1105
1106                         mod_timer(&phba->hb_tmofunc,
1107                                   jiffies + HZ * LPFC_HB_MBOX_TIMEOUT);
1108                         return;
1109                 } else {
1110                         /*
1111                         * If heart beat timeout called with hb_outstanding set
1112                         * we need to give the hb mailbox cmd a chance to
1113                         * complete or TMO.
1114                         */
1115                         lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
1116                                         "0459 Adapter heartbeat still out"
1117                                         "standing:last compl time was %d ms.\n",
1118                                         jiffies_to_msecs(jiffies
1119                                                  - phba->last_completion_time));
1120                         mod_timer(&phba->hb_tmofunc,
1121                                   jiffies + HZ * LPFC_HB_MBOX_TIMEOUT);
1122                 }
1123         }
1124 }
1125
1126 /**
1127  * lpfc_offline_eratt - Bring lpfc offline on hardware error attention
1128  * @phba: pointer to lpfc hba data structure.
1129  *
1130  * This routine is called to bring the HBA offline when HBA hardware error
1131  * other than Port Error 6 has been detected.
1132  **/
1133 static void
1134 lpfc_offline_eratt(struct lpfc_hba *phba)
1135 {
1136         struct lpfc_sli   *psli = &phba->sli;
1137
1138         spin_lock_irq(&phba->hbalock);
1139         psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1140         spin_unlock_irq(&phba->hbalock);
1141         lpfc_offline_prep(phba);
1142
1143         lpfc_offline(phba);
1144         lpfc_reset_barrier(phba);
1145         spin_lock_irq(&phba->hbalock);
1146         lpfc_sli_brdreset(phba);
1147         spin_unlock_irq(&phba->hbalock);
1148         lpfc_hba_down_post(phba);
1149         lpfc_sli_brdready(phba, HS_MBRDY);
1150         lpfc_unblock_mgmt_io(phba);
1151         phba->link_state = LPFC_HBA_ERROR;
1152         return;
1153 }
1154
1155 /**
1156  * lpfc_sli4_offline_eratt - Bring lpfc offline on SLI4 hardware error attention
1157  * @phba: pointer to lpfc hba data structure.
1158  *
1159  * This routine is called to bring a SLI4 HBA offline when HBA hardware error
1160  * other than Port Error 6 has been detected.
1161  **/
1162 static void
1163 lpfc_sli4_offline_eratt(struct lpfc_hba *phba)
1164 {
1165         lpfc_offline_prep(phba);
1166         lpfc_offline(phba);
1167         lpfc_sli4_brdreset(phba);
1168         lpfc_hba_down_post(phba);
1169         lpfc_sli4_post_status_check(phba);
1170         lpfc_unblock_mgmt_io(phba);
1171         phba->link_state = LPFC_HBA_ERROR;
1172 }
1173
1174 /**
1175  * lpfc_handle_deferred_eratt - The HBA hardware deferred error handler
1176  * @phba: pointer to lpfc hba data structure.
1177  *
1178  * This routine is invoked to handle the deferred HBA hardware error
1179  * conditions. This type of error is indicated by HBA by setting ER1
1180  * and another ER bit in the host status register. The driver will
1181  * wait until the ER1 bit clears before handling the error condition.
1182  **/
1183 static void
1184 lpfc_handle_deferred_eratt(struct lpfc_hba *phba)
1185 {
1186         uint32_t old_host_status = phba->work_hs;
1187         struct lpfc_sli_ring  *pring;
1188         struct lpfc_sli *psli = &phba->sli;
1189
1190         /* If the pci channel is offline, ignore possible errors,
1191          * since we cannot communicate with the pci card anyway.
1192          */
1193         if (pci_channel_offline(phba->pcidev)) {
1194                 spin_lock_irq(&phba->hbalock);
1195                 phba->hba_flag &= ~DEFER_ERATT;
1196                 spin_unlock_irq(&phba->hbalock);
1197                 return;
1198         }
1199
1200         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
1201                 "0479 Deferred Adapter Hardware Error "
1202                 "Data: x%x x%x x%x\n",
1203                 phba->work_hs,
1204                 phba->work_status[0], phba->work_status[1]);
1205
1206         spin_lock_irq(&phba->hbalock);
1207         psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1208         spin_unlock_irq(&phba->hbalock);
1209
1210
1211         /*
1212          * Firmware stops when it triggred erratt. That could cause the I/Os
1213          * dropped by the firmware. Error iocb (I/O) on txcmplq and let the
1214          * SCSI layer retry it after re-establishing link.
1215          */
1216         pring = &psli->ring[psli->fcp_ring];
1217         lpfc_sli_abort_iocb_ring(phba, pring);
1218
1219         /*
1220          * There was a firmware error. Take the hba offline and then
1221          * attempt to restart it.
1222          */
1223         lpfc_offline_prep(phba);
1224         lpfc_offline(phba);
1225
1226         /* Wait for the ER1 bit to clear.*/
1227         while (phba->work_hs & HS_FFER1) {
1228                 msleep(100);
1229                 phba->work_hs = readl(phba->HSregaddr);
1230                 /* If driver is unloading let the worker thread continue */
1231                 if (phba->pport->load_flag & FC_UNLOADING) {
1232                         phba->work_hs = 0;
1233                         break;
1234                 }
1235         }
1236
1237         /*
1238          * This is to ptrotect against a race condition in which
1239          * first write to the host attention register clear the
1240          * host status register.
1241          */
1242         if ((!phba->work_hs) && (!(phba->pport->load_flag & FC_UNLOADING)))
1243                 phba->work_hs = old_host_status & ~HS_FFER1;
1244
1245         spin_lock_irq(&phba->hbalock);
1246         phba->hba_flag &= ~DEFER_ERATT;
1247         spin_unlock_irq(&phba->hbalock);
1248         phba->work_status[0] = readl(phba->MBslimaddr + 0xa8);
1249         phba->work_status[1] = readl(phba->MBslimaddr + 0xac);
1250 }
1251
1252 static void
1253 lpfc_board_errevt_to_mgmt(struct lpfc_hba *phba)
1254 {
1255         struct lpfc_board_event_header board_event;
1256         struct Scsi_Host *shost;
1257
1258         board_event.event_type = FC_REG_BOARD_EVENT;
1259         board_event.subcategory = LPFC_EVENT_PORTINTERR;
1260         shost = lpfc_shost_from_vport(phba->pport);
1261         fc_host_post_vendor_event(shost, fc_get_event_number(),
1262                                   sizeof(board_event),
1263                                   (char *) &board_event,
1264                                   LPFC_NL_VENDOR_ID);
1265 }
1266
1267 /**
1268  * lpfc_handle_eratt_s3 - The SLI3 HBA hardware error handler
1269  * @phba: pointer to lpfc hba data structure.
1270  *
1271  * This routine is invoked to handle the following HBA hardware error
1272  * conditions:
1273  * 1 - HBA error attention interrupt
1274  * 2 - DMA ring index out of range
1275  * 3 - Mailbox command came back as unknown
1276  **/
1277 static void
1278 lpfc_handle_eratt_s3(struct lpfc_hba *phba)
1279 {
1280         struct lpfc_vport *vport = phba->pport;
1281         struct lpfc_sli   *psli = &phba->sli;
1282         struct lpfc_sli_ring  *pring;
1283         uint32_t event_data;
1284         unsigned long temperature;
1285         struct temp_event temp_event_data;
1286         struct Scsi_Host  *shost;
1287
1288         /* If the pci channel is offline, ignore possible errors,
1289          * since we cannot communicate with the pci card anyway.
1290          */
1291         if (pci_channel_offline(phba->pcidev)) {
1292                 spin_lock_irq(&phba->hbalock);
1293                 phba->hba_flag &= ~DEFER_ERATT;
1294                 spin_unlock_irq(&phba->hbalock);
1295                 return;
1296         }
1297
1298         /* If resets are disabled then leave the HBA alone and return */
1299         if (!phba->cfg_enable_hba_reset)
1300                 return;
1301
1302         /* Send an internal error event to mgmt application */
1303         lpfc_board_errevt_to_mgmt(phba);
1304
1305         if (phba->hba_flag & DEFER_ERATT)
1306                 lpfc_handle_deferred_eratt(phba);
1307
1308         if ((phba->work_hs & HS_FFER6) || (phba->work_hs & HS_FFER8)) {
1309                 if (phba->work_hs & HS_FFER6)
1310                         /* Re-establishing Link */
1311                         lpfc_printf_log(phba, KERN_INFO, LOG_LINK_EVENT,
1312                                         "1301 Re-establishing Link "
1313                                         "Data: x%x x%x x%x\n",
1314                                         phba->work_hs, phba->work_status[0],
1315                                         phba->work_status[1]);
1316                 if (phba->work_hs & HS_FFER8)
1317                         /* Device Zeroization */
1318                         lpfc_printf_log(phba, KERN_INFO, LOG_LINK_EVENT,
1319                                         "2861 Host Authentication device "
1320                                         "zeroization Data:x%x x%x x%x\n",
1321                                         phba->work_hs, phba->work_status[0],
1322                                         phba->work_status[1]);
1323
1324                 spin_lock_irq(&phba->hbalock);
1325                 psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1326                 spin_unlock_irq(&phba->hbalock);
1327
1328                 /*
1329                 * Firmware stops when it triggled erratt with HS_FFER6.
1330                 * That could cause the I/Os dropped by the firmware.
1331                 * Error iocb (I/O) on txcmplq and let the SCSI layer
1332                 * retry it after re-establishing link.
1333                 */
1334                 pring = &psli->ring[psli->fcp_ring];
1335                 lpfc_sli_abort_iocb_ring(phba, pring);
1336
1337                 /*
1338                  * There was a firmware error.  Take the hba offline and then
1339                  * attempt to restart it.
1340                  */
1341                 lpfc_offline_prep(phba);
1342                 lpfc_offline(phba);
1343                 lpfc_sli_brdrestart(phba);
1344                 if (lpfc_online(phba) == 0) {   /* Initialize the HBA */
1345                         lpfc_unblock_mgmt_io(phba);
1346                         return;
1347                 }
1348                 lpfc_unblock_mgmt_io(phba);
1349         } else if (phba->work_hs & HS_CRIT_TEMP) {
1350                 temperature = readl(phba->MBslimaddr + TEMPERATURE_OFFSET);
1351                 temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
1352                 temp_event_data.event_code = LPFC_CRIT_TEMP;
1353                 temp_event_data.data = (uint32_t)temperature;
1354
1355                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
1356                                 "0406 Adapter maximum temperature exceeded "
1357                                 "(%ld), taking this port offline "
1358                                 "Data: x%x x%x x%x\n",
1359                                 temperature, phba->work_hs,
1360                                 phba->work_status[0], phba->work_status[1]);
1361
1362                 shost = lpfc_shost_from_vport(phba->pport);
1363                 fc_host_post_vendor_event(shost, fc_get_event_number(),
1364                                           sizeof(temp_event_data),
1365                                           (char *) &temp_event_data,
1366                                           SCSI_NL_VID_TYPE_PCI
1367                                           | PCI_VENDOR_ID_EMULEX);
1368
1369                 spin_lock_irq(&phba->hbalock);
1370                 phba->over_temp_state = HBA_OVER_TEMP;
1371                 spin_unlock_irq(&phba->hbalock);
1372                 lpfc_offline_eratt(phba);
1373
1374         } else {
1375                 /* The if clause above forces this code path when the status
1376                  * failure is a value other than FFER6. Do not call the offline
1377                  * twice. This is the adapter hardware error path.
1378                  */
1379                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
1380                                 "0457 Adapter Hardware Error "
1381                                 "Data: x%x x%x x%x\n",
1382                                 phba->work_hs,
1383                                 phba->work_status[0], phba->work_status[1]);
1384
1385                 event_data = FC_REG_DUMP_EVENT;
1386                 shost = lpfc_shost_from_vport(vport);
1387                 fc_host_post_vendor_event(shost, fc_get_event_number(),
1388                                 sizeof(event_data), (char *) &event_data,
1389                                 SCSI_NL_VID_TYPE_PCI | PCI_VENDOR_ID_EMULEX);
1390
1391                 lpfc_offline_eratt(phba);
1392         }
1393         return;
1394 }
1395
1396 /**
1397  * lpfc_handle_eratt_s4 - The SLI4 HBA hardware error handler
1398  * @phba: pointer to lpfc hba data structure.
1399  *
1400  * This routine is invoked to handle the SLI4 HBA hardware error attention
1401  * conditions.
1402  **/
1403 static void
1404 lpfc_handle_eratt_s4(struct lpfc_hba *phba)
1405 {
1406         struct lpfc_vport *vport = phba->pport;
1407         uint32_t event_data;
1408         struct Scsi_Host *shost;
1409
1410         /* If the pci channel is offline, ignore possible errors, since
1411          * we cannot communicate with the pci card anyway.
1412          */
1413         if (pci_channel_offline(phba->pcidev))
1414                 return;
1415         /* If resets are disabled then leave the HBA alone and return */
1416         if (!phba->cfg_enable_hba_reset)
1417                 return;
1418
1419         /* Send an internal error event to mgmt application */
1420         lpfc_board_errevt_to_mgmt(phba);
1421
1422         /* For now, the actual action for SLI4 device handling is not
1423          * specified yet, just treated it as adaptor hardware failure
1424          */
1425         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
1426                         "0143 SLI4 Adapter Hardware Error Data: x%x x%x\n",
1427                         phba->work_status[0], phba->work_status[1]);
1428
1429         event_data = FC_REG_DUMP_EVENT;
1430         shost = lpfc_shost_from_vport(vport);
1431         fc_host_post_vendor_event(shost, fc_get_event_number(),
1432                                   sizeof(event_data), (char *) &event_data,
1433                                   SCSI_NL_VID_TYPE_PCI | PCI_VENDOR_ID_EMULEX);
1434
1435         lpfc_sli4_offline_eratt(phba);
1436 }
1437
1438 /**
1439  * lpfc_handle_eratt - Wrapper func for handling hba error attention
1440  * @phba: pointer to lpfc HBA data structure.
1441  *
1442  * This routine wraps the actual SLI3 or SLI4 hba error attention handling
1443  * routine from the API jump table function pointer from the lpfc_hba struct.
1444  *
1445  * Return codes
1446  *   0 - success.
1447  *   Any other value - error.
1448  **/
1449 void
1450 lpfc_handle_eratt(struct lpfc_hba *phba)
1451 {
1452         (*phba->lpfc_handle_eratt)(phba);
1453 }
1454
1455 /**
1456  * lpfc_handle_latt - The HBA link event handler
1457  * @phba: pointer to lpfc hba data structure.
1458  *
1459  * This routine is invoked from the worker thread to handle a HBA host
1460  * attention link event.
1461  **/
1462 void
1463 lpfc_handle_latt(struct lpfc_hba *phba)
1464 {
1465         struct lpfc_vport *vport = phba->pport;
1466         struct lpfc_sli   *psli = &phba->sli;
1467         LPFC_MBOXQ_t *pmb;
1468         volatile uint32_t control;
1469         struct lpfc_dmabuf *mp;
1470         int rc = 0;
1471
1472         pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
1473         if (!pmb) {
1474                 rc = 1;
1475                 goto lpfc_handle_latt_err_exit;
1476         }
1477
1478         mp = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
1479         if (!mp) {
1480                 rc = 2;
1481                 goto lpfc_handle_latt_free_pmb;
1482         }
1483
1484         mp->virt = lpfc_mbuf_alloc(phba, 0, &mp->phys);
1485         if (!mp->virt) {
1486                 rc = 3;
1487                 goto lpfc_handle_latt_free_mp;
1488         }
1489
1490         /* Cleanup any outstanding ELS commands */
1491         lpfc_els_flush_all_cmd(phba);
1492
1493         psli->slistat.link_event++;
1494         lpfc_read_topology(phba, pmb, mp);
1495         pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
1496         pmb->vport = vport;
1497         /* Block ELS IOCBs until we have processed this mbox command */
1498         phba->sli.ring[LPFC_ELS_RING].flag |= LPFC_STOP_IOCB_EVENT;
1499         rc = lpfc_sli_issue_mbox (phba, pmb, MBX_NOWAIT);
1500         if (rc == MBX_NOT_FINISHED) {
1501                 rc = 4;
1502                 goto lpfc_handle_latt_free_mbuf;
1503         }
1504
1505         /* Clear Link Attention in HA REG */
1506         spin_lock_irq(&phba->hbalock);
1507         writel(HA_LATT, phba->HAregaddr);
1508         readl(phba->HAregaddr); /* flush */
1509         spin_unlock_irq(&phba->hbalock);
1510
1511         return;
1512
1513 lpfc_handle_latt_free_mbuf:
1514         phba->sli.ring[LPFC_ELS_RING].flag &= ~LPFC_STOP_IOCB_EVENT;
1515         lpfc_mbuf_free(phba, mp->virt, mp->phys);
1516 lpfc_handle_latt_free_mp:
1517         kfree(mp);
1518 lpfc_handle_latt_free_pmb:
1519         mempool_free(pmb, phba->mbox_mem_pool);
1520 lpfc_handle_latt_err_exit:
1521         /* Enable Link attention interrupts */
1522         spin_lock_irq(&phba->hbalock);
1523         psli->sli_flag |= LPFC_PROCESS_LA;
1524         control = readl(phba->HCregaddr);
1525         control |= HC_LAINT_ENA;
1526         writel(control, phba->HCregaddr);
1527         readl(phba->HCregaddr); /* flush */
1528
1529         /* Clear Link Attention in HA REG */
1530         writel(HA_LATT, phba->HAregaddr);
1531         readl(phba->HAregaddr); /* flush */
1532         spin_unlock_irq(&phba->hbalock);
1533         lpfc_linkdown(phba);
1534         phba->link_state = LPFC_HBA_ERROR;
1535
1536         lpfc_printf_log(phba, KERN_ERR, LOG_MBOX,
1537                      "0300 LATT: Cannot issue READ_LA: Data:%d\n", rc);
1538
1539         return;
1540 }
1541
1542 /**
1543  * lpfc_parse_vpd - Parse VPD (Vital Product Data)
1544  * @phba: pointer to lpfc hba data structure.
1545  * @vpd: pointer to the vital product data.
1546  * @len: length of the vital product data in bytes.
1547  *
1548  * This routine parses the Vital Product Data (VPD). The VPD is treated as
1549  * an array of characters. In this routine, the ModelName, ProgramType, and
1550  * ModelDesc, etc. fields of the phba data structure will be populated.
1551  *
1552  * Return codes
1553  *   0 - pointer to the VPD passed in is NULL
1554  *   1 - success
1555  **/
1556 int
1557 lpfc_parse_vpd(struct lpfc_hba *phba, uint8_t *vpd, int len)
1558 {
1559         uint8_t lenlo, lenhi;
1560         int Length;
1561         int i, j;
1562         int finished = 0;
1563         int index = 0;
1564
1565         if (!vpd)
1566                 return 0;
1567
1568         /* Vital Product */
1569         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
1570                         "0455 Vital Product Data: x%x x%x x%x x%x\n",
1571                         (uint32_t) vpd[0], (uint32_t) vpd[1], (uint32_t) vpd[2],
1572                         (uint32_t) vpd[3]);
1573         while (!finished && (index < (len - 4))) {
1574                 switch (vpd[index]) {
1575                 case 0x82:
1576                 case 0x91:
1577                         index += 1;
1578                         lenlo = vpd[index];
1579                         index += 1;
1580                         lenhi = vpd[index];
1581                         index += 1;
1582                         i = ((((unsigned short)lenhi) << 8) + lenlo);
1583                         index += i;
1584                         break;
1585                 case 0x90:
1586                         index += 1;
1587                         lenlo = vpd[index];
1588                         index += 1;
1589                         lenhi = vpd[index];
1590                         index += 1;
1591                         Length = ((((unsigned short)lenhi) << 8) + lenlo);
1592                         if (Length > len - index)
1593                                 Length = len - index;
1594                         while (Length > 0) {
1595                         /* Look for Serial Number */
1596                         if ((vpd[index] == 'S') && (vpd[index+1] == 'N')) {
1597                                 index += 2;
1598                                 i = vpd[index];
1599                                 index += 1;
1600                                 j = 0;
1601                                 Length -= (3+i);
1602                                 while(i--) {
1603                                         phba->SerialNumber[j++] = vpd[index++];
1604                                         if (j == 31)
1605                                                 break;
1606                                 }
1607                                 phba->SerialNumber[j] = 0;
1608                                 continue;
1609                         }
1610                         else if ((vpd[index] == 'V') && (vpd[index+1] == '1')) {
1611                                 phba->vpd_flag |= VPD_MODEL_DESC;
1612                                 index += 2;
1613                                 i = vpd[index];
1614                                 index += 1;
1615                                 j = 0;
1616                                 Length -= (3+i);
1617                                 while(i--) {
1618                                         phba->ModelDesc[j++] = vpd[index++];
1619                                         if (j == 255)
1620                                                 break;
1621                                 }
1622                                 phba->ModelDesc[j] = 0;
1623                                 continue;
1624                         }
1625                         else if ((vpd[index] == 'V') && (vpd[index+1] == '2')) {
1626                                 phba->vpd_flag |= VPD_MODEL_NAME;
1627                                 index += 2;
1628                                 i = vpd[index];
1629                                 index += 1;
1630                                 j = 0;
1631                                 Length -= (3+i);
1632                                 while(i--) {
1633                                         phba->ModelName[j++] = vpd[index++];
1634                                         if (j == 79)
1635                                                 break;
1636                                 }
1637                                 phba->ModelName[j] = 0;
1638                                 continue;
1639                         }
1640                         else if ((vpd[index] == 'V') && (vpd[index+1] == '3')) {
1641                                 phba->vpd_flag |= VPD_PROGRAM_TYPE;
1642                                 index += 2;
1643                                 i = vpd[index];
1644                                 index += 1;
1645                                 j = 0;
1646                                 Length -= (3+i);
1647                                 while(i--) {
1648                                         phba->ProgramType[j++] = vpd[index++];
1649                                         if (j == 255)
1650                                                 break;
1651                                 }
1652                                 phba->ProgramType[j] = 0;
1653                                 continue;
1654                         }
1655                         else if ((vpd[index] == 'V') && (vpd[index+1] == '4')) {
1656                                 phba->vpd_flag |= VPD_PORT;
1657                                 index += 2;
1658                                 i = vpd[index];
1659                                 index += 1;
1660                                 j = 0;
1661                                 Length -= (3+i);
1662                                 while(i--) {
1663                                 phba->Port[j++] = vpd[index++];
1664                                 if (j == 19)
1665                                         break;
1666                                 }
1667                                 phba->Port[j] = 0;
1668                                 continue;
1669                         }
1670                         else {
1671                                 index += 2;
1672                                 i = vpd[index];
1673                                 index += 1;
1674                                 index += i;
1675                                 Length -= (3 + i);
1676                         }
1677                 }
1678                 finished = 0;
1679                 break;
1680                 case 0x78:
1681                         finished = 1;
1682                         break;
1683                 default:
1684                         index ++;
1685                         break;
1686                 }
1687         }
1688
1689         return(1);
1690 }
1691
1692 /**
1693  * lpfc_get_hba_model_desc - Retrieve HBA device model name and description
1694  * @phba: pointer to lpfc hba data structure.
1695  * @mdp: pointer to the data structure to hold the derived model name.
1696  * @descp: pointer to the data structure to hold the derived description.
1697  *
1698  * This routine retrieves HBA's description based on its registered PCI device
1699  * ID. The @descp passed into this function points to an array of 256 chars. It
1700  * shall be returned with the model name, maximum speed, and the host bus type.
1701  * The @mdp passed into this function points to an array of 80 chars. When the
1702  * function returns, the @mdp will be filled with the model name.
1703  **/
1704 static void
1705 lpfc_get_hba_model_desc(struct lpfc_hba *phba, uint8_t *mdp, uint8_t *descp)
1706 {
1707         lpfc_vpd_t *vp;
1708         uint16_t dev_id = phba->pcidev->device;
1709         int max_speed;
1710         int GE = 0;
1711         int oneConnect = 0; /* default is not a oneConnect */
1712         struct {
1713                 char *name;
1714                 char *bus;
1715                 char *function;
1716         } m = {"<Unknown>", "", ""};
1717
1718         if (mdp && mdp[0] != '\0'
1719                 && descp && descp[0] != '\0')
1720                 return;
1721
1722         if (phba->lmt & LMT_10Gb)
1723                 max_speed = 10;
1724         else if (phba->lmt & LMT_8Gb)
1725                 max_speed = 8;
1726         else if (phba->lmt & LMT_4Gb)
1727                 max_speed = 4;
1728         else if (phba->lmt & LMT_2Gb)
1729                 max_speed = 2;
1730         else
1731                 max_speed = 1;
1732
1733         vp = &phba->vpd;
1734
1735         switch (dev_id) {
1736         case PCI_DEVICE_ID_FIREFLY:
1737                 m = (typeof(m)){"LP6000", "PCI", "Fibre Channel Adapter"};
1738                 break;
1739         case PCI_DEVICE_ID_SUPERFLY:
1740                 if (vp->rev.biuRev >= 1 && vp->rev.biuRev <= 3)
1741                         m = (typeof(m)){"LP7000", "PCI",
1742                                         "Fibre Channel Adapter"};
1743                 else
1744                         m = (typeof(m)){"LP7000E", "PCI",
1745                                         "Fibre Channel Adapter"};
1746                 break;
1747         case PCI_DEVICE_ID_DRAGONFLY:
1748                 m = (typeof(m)){"LP8000", "PCI",
1749                                 "Fibre Channel Adapter"};
1750                 break;
1751         case PCI_DEVICE_ID_CENTAUR:
1752                 if (FC_JEDEC_ID(vp->rev.biuRev) == CENTAUR_2G_JEDEC_ID)
1753                         m = (typeof(m)){"LP9002", "PCI",
1754                                         "Fibre Channel Adapter"};
1755                 else
1756                         m = (typeof(m)){"LP9000", "PCI",
1757                                         "Fibre Channel Adapter"};
1758                 break;
1759         case PCI_DEVICE_ID_RFLY:
1760                 m = (typeof(m)){"LP952", "PCI",
1761                                 "Fibre Channel Adapter"};
1762                 break;
1763         case PCI_DEVICE_ID_PEGASUS:
1764                 m = (typeof(m)){"LP9802", "PCI-X",
1765                                 "Fibre Channel Adapter"};
1766                 break;
1767         case PCI_DEVICE_ID_THOR:
1768                 m = (typeof(m)){"LP10000", "PCI-X",
1769                                 "Fibre Channel Adapter"};
1770                 break;
1771         case PCI_DEVICE_ID_VIPER:
1772                 m = (typeof(m)){"LPX1000",  "PCI-X",
1773                                 "Fibre Channel Adapter"};
1774                 break;
1775         case PCI_DEVICE_ID_PFLY:
1776                 m = (typeof(m)){"LP982", "PCI-X",
1777                                 "Fibre Channel Adapter"};
1778                 break;
1779         case PCI_DEVICE_ID_TFLY:
1780                 m = (typeof(m)){"LP1050", "PCI-X",
1781                                 "Fibre Channel Adapter"};
1782                 break;
1783         case PCI_DEVICE_ID_HELIOS:
1784                 m = (typeof(m)){"LP11000", "PCI-X2",
1785                                 "Fibre Channel Adapter"};
1786                 break;
1787         case PCI_DEVICE_ID_HELIOS_SCSP:
1788                 m = (typeof(m)){"LP11000-SP", "PCI-X2",
1789                                 "Fibre Channel Adapter"};
1790                 break;
1791         case PCI_DEVICE_ID_HELIOS_DCSP:
1792                 m = (typeof(m)){"LP11002-SP",  "PCI-X2",
1793                                 "Fibre Channel Adapter"};
1794                 break;
1795         case PCI_DEVICE_ID_NEPTUNE:
1796                 m = (typeof(m)){"LPe1000", "PCIe", "Fibre Channel Adapter"};
1797                 break;
1798         case PCI_DEVICE_ID_NEPTUNE_SCSP:
1799                 m = (typeof(m)){"LPe1000-SP", "PCIe", "Fibre Channel Adapter"};
1800                 break;
1801         case PCI_DEVICE_ID_NEPTUNE_DCSP:
1802                 m = (typeof(m)){"LPe1002-SP", "PCIe", "Fibre Channel Adapter"};
1803                 break;
1804         case PCI_DEVICE_ID_BMID:
1805                 m = (typeof(m)){"LP1150", "PCI-X2", "Fibre Channel Adapter"};
1806                 break;
1807         case PCI_DEVICE_ID_BSMB:
1808                 m = (typeof(m)){"LP111", "PCI-X2", "Fibre Channel Adapter"};
1809                 break;
1810         case PCI_DEVICE_ID_ZEPHYR:
1811                 m = (typeof(m)){"LPe11000", "PCIe", "Fibre Channel Adapter"};
1812                 break;
1813         case PCI_DEVICE_ID_ZEPHYR_SCSP:
1814                 m = (typeof(m)){"LPe11000", "PCIe", "Fibre Channel Adapter"};
1815                 break;
1816         case PCI_DEVICE_ID_ZEPHYR_DCSP:
1817                 m = (typeof(m)){"LP2105", "PCIe", "FCoE Adapter"};
1818                 GE = 1;
1819                 break;
1820         case PCI_DEVICE_ID_ZMID:
1821                 m = (typeof(m)){"LPe1150", "PCIe", "Fibre Channel Adapter"};
1822                 break;
1823         case PCI_DEVICE_ID_ZSMB:
1824                 m = (typeof(m)){"LPe111", "PCIe", "Fibre Channel Adapter"};
1825                 break;
1826         case PCI_DEVICE_ID_LP101:
1827                 m = (typeof(m)){"LP101", "PCI-X", "Fibre Channel Adapter"};
1828                 break;
1829         case PCI_DEVICE_ID_LP10000S:
1830                 m = (typeof(m)){"LP10000-S", "PCI", "Fibre Channel Adapter"};
1831                 break;
1832         case PCI_DEVICE_ID_LP11000S:
1833                 m = (typeof(m)){"LP11000-S", "PCI-X2", "Fibre Channel Adapter"};
1834                 break;
1835         case PCI_DEVICE_ID_LPE11000S:
1836                 m = (typeof(m)){"LPe11000-S", "PCIe", "Fibre Channel Adapter"};
1837                 break;
1838         case PCI_DEVICE_ID_SAT:
1839                 m = (typeof(m)){"LPe12000", "PCIe", "Fibre Channel Adapter"};
1840                 break;
1841         case PCI_DEVICE_ID_SAT_MID:
1842                 m = (typeof(m)){"LPe1250", "PCIe", "Fibre Channel Adapter"};
1843                 break;
1844         case PCI_DEVICE_ID_SAT_SMB:
1845                 m = (typeof(m)){"LPe121", "PCIe", "Fibre Channel Adapter"};
1846                 break;
1847         case PCI_DEVICE_ID_SAT_DCSP:
1848                 m = (typeof(m)){"LPe12002-SP", "PCIe", "Fibre Channel Adapter"};
1849                 break;
1850         case PCI_DEVICE_ID_SAT_SCSP:
1851                 m = (typeof(m)){"LPe12000-SP", "PCIe", "Fibre Channel Adapter"};
1852                 break;
1853         case PCI_DEVICE_ID_SAT_S:
1854                 m = (typeof(m)){"LPe12000-S", "PCIe", "Fibre Channel Adapter"};
1855                 break;
1856         case PCI_DEVICE_ID_HORNET:
1857                 m = (typeof(m)){"LP21000", "PCIe", "FCoE Adapter"};
1858                 GE = 1;
1859                 break;
1860         case PCI_DEVICE_ID_PROTEUS_VF:
1861                 m = (typeof(m)){"LPev12000", "PCIe IOV",
1862                                 "Fibre Channel Adapter"};
1863                 break;
1864         case PCI_DEVICE_ID_PROTEUS_PF:
1865                 m = (typeof(m)){"LPev12000", "PCIe IOV",
1866                                 "Fibre Channel Adapter"};
1867                 break;
1868         case PCI_DEVICE_ID_PROTEUS_S:
1869                 m = (typeof(m)){"LPemv12002-S", "PCIe IOV",
1870                                 "Fibre Channel Adapter"};
1871                 break;
1872         case PCI_DEVICE_ID_TIGERSHARK:
1873                 oneConnect = 1;
1874                 m = (typeof(m)){"OCe10100", "PCIe", "FCoE"};
1875                 break;
1876         case PCI_DEVICE_ID_TOMCAT:
1877                 oneConnect = 1;
1878                 m = (typeof(m)){"OCe11100", "PCIe", "FCoE"};
1879                 break;
1880         case PCI_DEVICE_ID_FALCON:
1881                 m = (typeof(m)){"LPSe12002-ML1-E", "PCIe",
1882                                 "EmulexSecure Fibre"};
1883                 break;
1884         case PCI_DEVICE_ID_BALIUS:
1885                 m = (typeof(m)){"LPVe12002", "PCIe Shared I/O",
1886                                 "Fibre Channel Adapter"};
1887                 break;
1888         case PCI_DEVICE_ID_LANCER_FC:
1889                 oneConnect = 1;
1890                 m = (typeof(m)){"Undefined", "PCIe", "Fibre Channel Adapter"};
1891                 break;
1892         case PCI_DEVICE_ID_LANCER_FCOE:
1893                 oneConnect = 1;
1894                 m = (typeof(m)){"Undefined", "PCIe", "FCoE"};
1895                 break;
1896         default:
1897                 m = (typeof(m)){"Unknown", "", ""};
1898                 break;
1899         }
1900
1901         if (mdp && mdp[0] == '\0')
1902                 snprintf(mdp, 79,"%s", m.name);
1903         /* oneConnect hba requires special processing, they are all initiators
1904          * and we put the port number on the end
1905          */
1906         if (descp && descp[0] == '\0') {
1907                 if (oneConnect)
1908                         snprintf(descp, 255,
1909                                 "Emulex OneConnect %s, %s Initiator, Port %s",
1910                                 m.name, m.function,
1911                                 phba->Port);
1912                 else
1913                         snprintf(descp, 255,
1914                                 "Emulex %s %d%s %s %s",
1915                                 m.name, max_speed, (GE) ? "GE" : "Gb",
1916                                 m.bus, m.function);
1917         }
1918 }
1919
1920 /**
1921  * lpfc_post_buffer - Post IOCB(s) with DMA buffer descriptor(s) to a IOCB ring
1922  * @phba: pointer to lpfc hba data structure.
1923  * @pring: pointer to a IOCB ring.
1924  * @cnt: the number of IOCBs to be posted to the IOCB ring.
1925  *
1926  * This routine posts a given number of IOCBs with the associated DMA buffer
1927  * descriptors specified by the cnt argument to the given IOCB ring.
1928  *
1929  * Return codes
1930  *   The number of IOCBs NOT able to be posted to the IOCB ring.
1931  **/
1932 int
1933 lpfc_post_buffer(struct lpfc_hba *phba, struct lpfc_sli_ring *pring, int cnt)
1934 {
1935         IOCB_t *icmd;
1936         struct lpfc_iocbq *iocb;
1937         struct lpfc_dmabuf *mp1, *mp2;
1938
1939         cnt += pring->missbufcnt;
1940
1941         /* While there are buffers to post */
1942         while (cnt > 0) {
1943                 /* Allocate buffer for  command iocb */
1944                 iocb = lpfc_sli_get_iocbq(phba);
1945                 if (iocb == NULL) {
1946                         pring->missbufcnt = cnt;
1947                         return cnt;
1948                 }
1949                 icmd = &iocb->iocb;
1950
1951                 /* 2 buffers can be posted per command */
1952                 /* Allocate buffer to post */
1953                 mp1 = kmalloc(sizeof (struct lpfc_dmabuf), GFP_KERNEL);
1954                 if (mp1)
1955                     mp1->virt = lpfc_mbuf_alloc(phba, MEM_PRI, &mp1->phys);
1956                 if (!mp1 || !mp1->virt) {
1957                         kfree(mp1);
1958                         lpfc_sli_release_iocbq(phba, iocb);
1959                         pring->missbufcnt = cnt;
1960                         return cnt;
1961                 }
1962
1963                 INIT_LIST_HEAD(&mp1->list);
1964                 /* Allocate buffer to post */
1965                 if (cnt > 1) {
1966                         mp2 = kmalloc(sizeof (struct lpfc_dmabuf), GFP_KERNEL);
1967                         if (mp2)
1968                                 mp2->virt = lpfc_mbuf_alloc(phba, MEM_PRI,
1969                                                             &mp2->phys);
1970                         if (!mp2 || !mp2->virt) {
1971                                 kfree(mp2);
1972                                 lpfc_mbuf_free(phba, mp1->virt, mp1->phys);
1973                                 kfree(mp1);
1974                                 lpfc_sli_release_iocbq(phba, iocb);
1975                                 pring->missbufcnt = cnt;
1976                                 return cnt;
1977                         }
1978
1979                         INIT_LIST_HEAD(&mp2->list);
1980                 } else {
1981                         mp2 = NULL;
1982                 }
1983
1984                 icmd->un.cont64[0].addrHigh = putPaddrHigh(mp1->phys);
1985                 icmd->un.cont64[0].addrLow = putPaddrLow(mp1->phys);
1986                 icmd->un.cont64[0].tus.f.bdeSize = FCELSSIZE;
1987                 icmd->ulpBdeCount = 1;
1988                 cnt--;
1989                 if (mp2) {
1990                         icmd->un.cont64[1].addrHigh = putPaddrHigh(mp2->phys);
1991                         icmd->un.cont64[1].addrLow = putPaddrLow(mp2->phys);
1992                         icmd->un.cont64[1].tus.f.bdeSize = FCELSSIZE;
1993                         cnt--;
1994                         icmd->ulpBdeCount = 2;
1995                 }
1996
1997                 icmd->ulpCommand = CMD_QUE_RING_BUF64_CN;
1998                 icmd->ulpLe = 1;
1999
2000                 if (lpfc_sli_issue_iocb(phba, pring->ringno, iocb, 0) ==
2001                     IOCB_ERROR) {
2002                         lpfc_mbuf_free(phba, mp1->virt, mp1->phys);
2003                         kfree(mp1);
2004                         cnt++;
2005                         if (mp2) {
2006                                 lpfc_mbuf_free(phba, mp2->virt, mp2->phys);
2007                                 kfree(mp2);
2008                                 cnt++;
2009                         }
2010                         lpfc_sli_release_iocbq(phba, iocb);
2011                         pring->missbufcnt = cnt;
2012                         return cnt;
2013                 }
2014                 lpfc_sli_ringpostbuf_put(phba, pring, mp1);
2015                 if (mp2)
2016                         lpfc_sli_ringpostbuf_put(phba, pring, mp2);
2017         }
2018         pring->missbufcnt = 0;
2019         return 0;
2020 }
2021
2022 /**
2023  * lpfc_post_rcv_buf - Post the initial receive IOCB buffers to ELS ring
2024  * @phba: pointer to lpfc hba data structure.
2025  *
2026  * This routine posts initial receive IOCB buffers to the ELS ring. The
2027  * current number of initial IOCB buffers specified by LPFC_BUF_RING0 is
2028  * set to 64 IOCBs.
2029  *
2030  * Return codes
2031  *   0 - success (currently always success)
2032  **/
2033 static int
2034 lpfc_post_rcv_buf(struct lpfc_hba *phba)
2035 {
2036         struct lpfc_sli *psli = &phba->sli;
2037
2038         /* Ring 0, ELS / CT buffers */
2039         lpfc_post_buffer(phba, &psli->ring[LPFC_ELS_RING], LPFC_BUF_RING0);
2040         /* Ring 2 - FCP no buffers needed */
2041
2042         return 0;
2043 }
2044
2045 #define S(N,V) (((V)<<(N))|((V)>>(32-(N))))
2046
2047 /**
2048  * lpfc_sha_init - Set up initial array of hash table entries
2049  * @HashResultPointer: pointer to an array as hash table.
2050  *
2051  * This routine sets up the initial values to the array of hash table entries
2052  * for the LC HBAs.
2053  **/
2054 static void
2055 lpfc_sha_init(uint32_t * HashResultPointer)
2056 {
2057         HashResultPointer[0] = 0x67452301;
2058         HashResultPointer[1] = 0xEFCDAB89;
2059         HashResultPointer[2] = 0x98BADCFE;
2060         HashResultPointer[3] = 0x10325476;
2061         HashResultPointer[4] = 0xC3D2E1F0;
2062 }
2063
2064 /**
2065  * lpfc_sha_iterate - Iterate initial hash table with the working hash table
2066  * @HashResultPointer: pointer to an initial/result hash table.
2067  * @HashWorkingPointer: pointer to an working hash table.
2068  *
2069  * This routine iterates an initial hash table pointed by @HashResultPointer
2070  * with the values from the working hash table pointeed by @HashWorkingPointer.
2071  * The results are putting back to the initial hash table, returned through
2072  * the @HashResultPointer as the result hash table.
2073  **/
2074 static void
2075 lpfc_sha_iterate(uint32_t * HashResultPointer, uint32_t * HashWorkingPointer)
2076 {
2077         int t;
2078         uint32_t TEMP;
2079         uint32_t A, B, C, D, E;
2080         t = 16;
2081         do {
2082                 HashWorkingPointer[t] =
2083                     S(1,
2084                       HashWorkingPointer[t - 3] ^ HashWorkingPointer[t -
2085                                                                      8] ^
2086                       HashWorkingPointer[t - 14] ^ HashWorkingPointer[t - 16]);
2087         } while (++t <= 79);
2088         t = 0;
2089         A = HashResultPointer[0];
2090         B = HashResultPointer[1];
2091         C = HashResultPointer[2];
2092         D = HashResultPointer[3];
2093         E = HashResultPointer[4];
2094
2095         do {
2096                 if (t < 20) {
2097                         TEMP = ((B & C) | ((~B) & D)) + 0x5A827999;
2098                 } else if (t < 40) {
2099                         TEMP = (B ^ C ^ D) + 0x6ED9EBA1;
2100                 } else if (t < 60) {
2101                         TEMP = ((B & C) | (B & D) | (C & D)) + 0x8F1BBCDC;
2102                 } else {
2103                         TEMP = (B ^ C ^ D) + 0xCA62C1D6;
2104                 }
2105                 TEMP += S(5, A) + E + HashWorkingPointer[t];
2106                 E = D;
2107                 D = C;
2108                 C = S(30, B);
2109                 B = A;
2110                 A = TEMP;
2111         } while (++t <= 79);
2112
2113         HashResultPointer[0] += A;
2114         HashResultPointer[1] += B;
2115         HashResultPointer[2] += C;
2116         HashResultPointer[3] += D;
2117         HashResultPointer[4] += E;
2118
2119 }
2120
2121 /**
2122  * lpfc_challenge_key - Create challenge key based on WWPN of the HBA
2123  * @RandomChallenge: pointer to the entry of host challenge random number array.
2124  * @HashWorking: pointer to the entry of the working hash array.
2125  *
2126  * This routine calculates the working hash array referred by @HashWorking
2127  * from the challenge random numbers associated with the host, referred by
2128  * @RandomChallenge. The result is put into the entry of the working hash
2129  * array and returned by reference through @HashWorking.
2130  **/
2131 static void
2132 lpfc_challenge_key(uint32_t * RandomChallenge, uint32_t * HashWorking)
2133 {
2134         *HashWorking = (*RandomChallenge ^ *HashWorking);
2135 }
2136
2137 /**
2138  * lpfc_hba_init - Perform special handling for LC HBA initialization
2139  * @phba: pointer to lpfc hba data structure.
2140  * @hbainit: pointer to an array of unsigned 32-bit integers.
2141  *
2142  * This routine performs the special handling for LC HBA initialization.
2143  **/
2144 void
2145 lpfc_hba_init(struct lpfc_hba *phba, uint32_t *hbainit)
2146 {
2147         int t;
2148         uint32_t *HashWorking;
2149         uint32_t *pwwnn = (uint32_t *) phba->wwnn;
2150
2151         HashWorking = kcalloc(80, sizeof(uint32_t), GFP_KERNEL);
2152         if (!HashWorking)
2153                 return;
2154
2155         HashWorking[0] = HashWorking[78] = *pwwnn++;
2156         HashWorking[1] = HashWorking[79] = *pwwnn;
2157
2158         for (t = 0; t < 7; t++)
2159                 lpfc_challenge_key(phba->RandomData + t, HashWorking + t);
2160
2161         lpfc_sha_init(hbainit);
2162         lpfc_sha_iterate(hbainit, HashWorking);
2163         kfree(HashWorking);
2164 }
2165
2166 /**
2167  * lpfc_cleanup - Performs vport cleanups before deleting a vport
2168  * @vport: pointer to a virtual N_Port data structure.
2169  *
2170  * This routine performs the necessary cleanups before deleting the @vport.
2171  * It invokes the discovery state machine to perform necessary state
2172  * transitions and to release the ndlps associated with the @vport. Note,
2173  * the physical port is treated as @vport 0.
2174  **/
2175 void
2176 lpfc_cleanup(struct lpfc_vport *vport)
2177 {
2178         struct lpfc_hba   *phba = vport->phba;
2179         struct lpfc_nodelist *ndlp, *next_ndlp;
2180         int i = 0;
2181
2182         if (phba->link_state > LPFC_LINK_DOWN)
2183                 lpfc_port_link_failure(vport);
2184
2185         list_for_each_entry_safe(ndlp, next_ndlp, &vport->fc_nodes, nlp_listp) {
2186                 if (!NLP_CHK_NODE_ACT(ndlp)) {
2187                         ndlp = lpfc_enable_node(vport, ndlp,
2188                                                 NLP_STE_UNUSED_NODE);
2189                         if (!ndlp)
2190                                 continue;
2191                         spin_lock_irq(&phba->ndlp_lock);
2192                         NLP_SET_FREE_REQ(ndlp);
2193                         spin_unlock_irq(&phba->ndlp_lock);
2194                         /* Trigger the release of the ndlp memory */
2195                         lpfc_nlp_put(ndlp);
2196                         continue;
2197                 }
2198                 spin_lock_irq(&phba->ndlp_lock);
2199                 if (NLP_CHK_FREE_REQ(ndlp)) {
2200                         /* The ndlp should not be in memory free mode already */
2201                         spin_unlock_irq(&phba->ndlp_lock);
2202                         continue;
2203                 } else
2204                         /* Indicate request for freeing ndlp memory */
2205                         NLP_SET_FREE_REQ(ndlp);
2206                 spin_unlock_irq(&phba->ndlp_lock);
2207
2208                 if (vport->port_type != LPFC_PHYSICAL_PORT &&
2209                     ndlp->nlp_DID == Fabric_DID) {
2210                         /* Just free up ndlp with Fabric_DID for vports */
2211                         lpfc_nlp_put(ndlp);
2212                         continue;
2213                 }
2214
2215                 if (ndlp->nlp_type & NLP_FABRIC)
2216                         lpfc_disc_state_machine(vport, ndlp, NULL,
2217                                         NLP_EVT_DEVICE_RECOVERY);
2218
2219                 lpfc_disc_state_machine(vport, ndlp, NULL,
2220                                              NLP_EVT_DEVICE_RM);
2221
2222         }
2223
2224         /* At this point, ALL ndlp's should be gone
2225          * because of the previous NLP_EVT_DEVICE_RM.
2226          * Lets wait for this to happen, if needed.
2227          */
2228         while (!list_empty(&vport->fc_nodes)) {
2229                 if (i++ > 3000) {
2230                         lpfc_printf_vlog(vport, KERN_ERR, LOG_DISCOVERY,
2231                                 "0233 Nodelist not empty\n");
2232                         list_for_each_entry_safe(ndlp, next_ndlp,
2233                                                 &vport->fc_nodes, nlp_listp) {
2234                                 lpfc_printf_vlog(ndlp->vport, KERN_ERR,
2235                                                 LOG_NODE,
2236                                                 "0282 did:x%x ndlp:x%p "
2237                                                 "usgmap:x%x refcnt:%d\n",
2238                                                 ndlp->nlp_DID, (void *)ndlp,
2239                                                 ndlp->nlp_usg_map,
2240                                                 atomic_read(
2241                                                         &ndlp->kref.refcount));
2242                         }
2243                         break;
2244                 }
2245
2246                 /* Wait for any activity on ndlps to settle */
2247                 msleep(10);
2248         }
2249 }
2250
2251 /**
2252  * lpfc_stop_vport_timers - Stop all the timers associated with a vport
2253  * @vport: pointer to a virtual N_Port data structure.
2254  *
2255  * This routine stops all the timers associated with a @vport. This function
2256  * is invoked before disabling or deleting a @vport. Note that the physical
2257  * port is treated as @vport 0.
2258  **/
2259 void
2260 lpfc_stop_vport_timers(struct lpfc_vport *vport)
2261 {
2262         del_timer_sync(&vport->els_tmofunc);
2263         del_timer_sync(&vport->fc_fdmitmo);
2264         lpfc_can_disctmo(vport);
2265         return;
2266 }
2267
2268 /**
2269  * __lpfc_sli4_stop_fcf_redisc_wait_timer - Stop FCF rediscovery wait timer
2270  * @phba: pointer to lpfc hba data structure.
2271  *
2272  * This routine stops the SLI4 FCF rediscover wait timer if it's on. The
2273  * caller of this routine should already hold the host lock.
2274  **/
2275 void
2276 __lpfc_sli4_stop_fcf_redisc_wait_timer(struct lpfc_hba *phba)
2277 {
2278         /* Clear pending FCF rediscovery wait flag */
2279         phba->fcf.fcf_flag &= ~FCF_REDISC_PEND;
2280
2281         /* Now, try to stop the timer */
2282         del_timer(&phba->fcf.redisc_wait);
2283 }
2284
2285 /**
2286  * lpfc_sli4_stop_fcf_redisc_wait_timer - Stop FCF rediscovery wait timer
2287  * @phba: pointer to lpfc hba data structure.
2288  *
2289  * This routine stops the SLI4 FCF rediscover wait timer if it's on. It
2290  * checks whether the FCF rediscovery wait timer is pending with the host
2291  * lock held before proceeding with disabling the timer and clearing the
2292  * wait timer pendig flag.
2293  **/
2294 void
2295 lpfc_sli4_stop_fcf_redisc_wait_timer(struct lpfc_hba *phba)
2296 {
2297         spin_lock_irq(&phba->hbalock);
2298         if (!(phba->fcf.fcf_flag & FCF_REDISC_PEND)) {
2299                 /* FCF rediscovery timer already fired or stopped */
2300                 spin_unlock_irq(&phba->hbalock);
2301                 return;
2302         }
2303         __lpfc_sli4_stop_fcf_redisc_wait_timer(phba);
2304         /* Clear failover in progress flags */
2305         phba->fcf.fcf_flag &= ~(FCF_DEAD_DISC | FCF_ACVL_DISC);
2306         spin_unlock_irq(&phba->hbalock);
2307 }
2308
2309 /**
2310  * lpfc_stop_hba_timers - Stop all the timers associated with an HBA
2311  * @phba: pointer to lpfc hba data structure.
2312  *
2313  * This routine stops all the timers associated with a HBA. This function is
2314  * invoked before either putting a HBA offline or unloading the driver.
2315  **/
2316 void
2317 lpfc_stop_hba_timers(struct lpfc_hba *phba)
2318 {
2319         lpfc_stop_vport_timers(phba->pport);
2320         del_timer_sync(&phba->sli.mbox_tmo);
2321         del_timer_sync(&phba->fabric_block_timer);
2322         del_timer_sync(&phba->eratt_poll);
2323         del_timer_sync(&phba->hb_tmofunc);
2324         phba->hb_outstanding = 0;
2325
2326         switch (phba->pci_dev_grp) {
2327         case LPFC_PCI_DEV_LP:
2328                 /* Stop any LightPulse device specific driver timers */
2329                 del_timer_sync(&phba->fcp_poll_timer);
2330                 break;
2331         case LPFC_PCI_DEV_OC:
2332                 /* Stop any OneConnect device sepcific driver timers */
2333                 lpfc_sli4_stop_fcf_redisc_wait_timer(phba);
2334                 break;
2335         default:
2336                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
2337                                 "0297 Invalid device group (x%x)\n",
2338                                 phba->pci_dev_grp);
2339                 break;
2340         }
2341         return;
2342 }
2343
2344 /**
2345  * lpfc_block_mgmt_io - Mark a HBA's management interface as blocked
2346  * @phba: pointer to lpfc hba data structure.
2347  *
2348  * This routine marks a HBA's management interface as blocked. Once the HBA's
2349  * management interface is marked as blocked, all the user space access to
2350  * the HBA, whether they are from sysfs interface or libdfc interface will
2351  * all be blocked. The HBA is set to block the management interface when the
2352  * driver prepares the HBA interface for online or offline.
2353  **/
2354 static void
2355 lpfc_block_mgmt_io(struct lpfc_hba * phba)
2356 {
2357         unsigned long iflag;
2358         uint8_t actcmd = MBX_HEARTBEAT;
2359         unsigned long timeout;
2360
2361
2362         spin_lock_irqsave(&phba->hbalock, iflag);
2363         phba->sli.sli_flag |= LPFC_BLOCK_MGMT_IO;
2364         if (phba->sli.mbox_active)
2365                 actcmd = phba->sli.mbox_active->u.mb.mbxCommand;
2366         spin_unlock_irqrestore(&phba->hbalock, iflag);
2367         /* Determine how long we might wait for the active mailbox
2368          * command to be gracefully completed by firmware.
2369          */
2370         timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, actcmd) * 1000) +
2371                         jiffies;
2372         /* Wait for the outstnading mailbox command to complete */
2373         while (phba->sli.mbox_active) {
2374                 /* Check active mailbox complete status every 2ms */
2375                 msleep(2);
2376                 if (time_after(jiffies, timeout)) {
2377                         lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2378                                 "2813 Mgmt IO is Blocked %x "
2379                                 "- mbox cmd %x still active\n",
2380                                 phba->sli.sli_flag, actcmd);
2381                         break;
2382                 }
2383         }
2384 }
2385
2386 /**
2387  * lpfc_online - Initialize and bring a HBA online
2388  * @phba: pointer to lpfc hba data structure.
2389  *
2390  * This routine initializes the HBA and brings a HBA online. During this
2391  * process, the management interface is blocked to prevent user space access
2392  * to the HBA interfering with the driver initialization.
2393  *
2394  * Return codes
2395  *   0 - successful
2396  *   1 - failed
2397  **/
2398 int
2399 lpfc_online(struct lpfc_hba *phba)
2400 {
2401         struct lpfc_vport *vport;
2402         struct lpfc_vport **vports;
2403         int i;
2404
2405         if (!phba)
2406                 return 0;
2407         vport = phba->pport;
2408
2409         if (!(vport->fc_flag & FC_OFFLINE_MODE))
2410                 return 0;
2411
2412         lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
2413                         "0458 Bring Adapter online\n");
2414
2415         lpfc_block_mgmt_io(phba);
2416
2417         if (!lpfc_sli_queue_setup(phba)) {
2418                 lpfc_unblock_mgmt_io(phba);
2419                 return 1;
2420         }
2421
2422         if (phba->sli_rev == LPFC_SLI_REV4) {
2423                 if (lpfc_sli4_hba_setup(phba)) { /* Initialize SLI4 HBA */
2424                         lpfc_unblock_mgmt_io(phba);
2425                         return 1;
2426                 }
2427         } else {
2428                 if (lpfc_sli_hba_setup(phba)) { /* Initialize SLI2/SLI3 HBA */
2429                         lpfc_unblock_mgmt_io(phba);
2430                         return 1;
2431                 }
2432         }
2433
2434         vports = lpfc_create_vport_work_array(phba);
2435         if (vports != NULL)
2436                 for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
2437                         struct Scsi_Host *shost;
2438                         shost = lpfc_shost_from_vport(vports[i]);
2439                         spin_lock_irq(shost->host_lock);
2440                         vports[i]->fc_flag &= ~FC_OFFLINE_MODE;
2441                         if (phba->sli3_options & LPFC_SLI3_NPIV_ENABLED)
2442                                 vports[i]->fc_flag |= FC_VPORT_NEEDS_REG_VPI;
2443                         if (phba->sli_rev == LPFC_SLI_REV4)
2444                                 vports[i]->fc_flag |= FC_VPORT_NEEDS_INIT_VPI;
2445                         spin_unlock_irq(shost->host_lock);
2446                 }
2447                 lpfc_destroy_vport_work_array(phba, vports);
2448
2449         lpfc_unblock_mgmt_io(phba);
2450         return 0;
2451 }
2452
2453 /**
2454  * lpfc_unblock_mgmt_io - Mark a HBA's management interface to be not blocked
2455  * @phba: pointer to lpfc hba data structure.
2456  *
2457  * This routine marks a HBA's management interface as not blocked. Once the
2458  * HBA's management interface is marked as not blocked, all the user space
2459  * access to the HBA, whether they are from sysfs interface or libdfc
2460  * interface will be allowed. The HBA is set to block the management interface
2461  * when the driver prepares the HBA interface for online or offline and then
2462  * set to unblock the management interface afterwards.
2463  **/
2464 void
2465 lpfc_unblock_mgmt_io(struct lpfc_hba * phba)
2466 {
2467         unsigned long iflag;
2468
2469         spin_lock_irqsave(&phba->hbalock, iflag);
2470         phba->sli.sli_flag &= ~LPFC_BLOCK_MGMT_IO;
2471         spin_unlock_irqrestore(&phba->hbalock, iflag);
2472 }
2473
2474 /**
2475  * lpfc_offline_prep - Prepare a HBA to be brought offline
2476  * @phba: pointer to lpfc hba data structure.
2477  *
2478  * This routine is invoked to prepare a HBA to be brought offline. It performs
2479  * unregistration login to all the nodes on all vports and flushes the mailbox
2480  * queue to make it ready to be brought offline.
2481  **/
2482 void
2483 lpfc_offline_prep(struct lpfc_hba * phba)
2484 {
2485         struct lpfc_vport *vport = phba->pport;
2486         struct lpfc_nodelist  *ndlp, *next_ndlp;
2487         struct lpfc_vport **vports;
2488         struct Scsi_Host *shost;
2489         int i;
2490
2491         if (vport->fc_flag & FC_OFFLINE_MODE)
2492                 return;
2493
2494         lpfc_block_mgmt_io(phba);
2495
2496         lpfc_linkdown(phba);
2497
2498         /* Issue an unreg_login to all nodes on all vports */
2499         vports = lpfc_create_vport_work_array(phba);
2500         if (vports != NULL) {
2501                 for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
2502                         if (vports[i]->load_flag & FC_UNLOADING)
2503                                 continue;
2504                         shost = lpfc_shost_from_vport(vports[i]);
2505                         spin_lock_irq(shost->host_lock);
2506                         vports[i]->vpi_state &= ~LPFC_VPI_REGISTERED;
2507                         vports[i]->fc_flag |= FC_VPORT_NEEDS_REG_VPI;
2508                         vports[i]->fc_flag &= ~FC_VFI_REGISTERED;
2509                         spin_unlock_irq(shost->host_lock);
2510
2511                         shost = lpfc_shost_from_vport(vports[i]);
2512                         list_for_each_entry_safe(ndlp, next_ndlp,
2513                                                  &vports[i]->fc_nodes,
2514                                                  nlp_listp) {
2515                                 if (!NLP_CHK_NODE_ACT(ndlp))
2516                                         continue;
2517                                 if (ndlp->nlp_state == NLP_STE_UNUSED_NODE)
2518                                         continue;
2519                                 if (ndlp->nlp_type & NLP_FABRIC) {
2520                                         lpfc_disc_state_machine(vports[i], ndlp,
2521                                                 NULL, NLP_EVT_DEVICE_RECOVERY);
2522                                         lpfc_disc_state_machine(vports[i], ndlp,
2523                                                 NULL, NLP_EVT_DEVICE_RM);
2524                                 }
2525                                 spin_lock_irq(shost->host_lock);
2526                                 ndlp->nlp_flag &= ~NLP_NPR_ADISC;
2527                                 spin_unlock_irq(shost->host_lock);
2528                                 lpfc_unreg_rpi(vports[i], ndlp);
2529                         }
2530                 }
2531         }
2532         lpfc_destroy_vport_work_array(phba, vports);
2533
2534         lpfc_sli_mbox_sys_shutdown(phba);
2535 }
2536
2537 /**
2538  * lpfc_offline - Bring a HBA offline
2539  * @phba: pointer to lpfc hba data structure.
2540  *
2541  * This routine actually brings a HBA offline. It stops all the timers
2542  * associated with the HBA, brings down the SLI layer, and eventually
2543  * marks the HBA as in offline state for the upper layer protocol.
2544  **/
2545 void
2546 lpfc_offline(struct lpfc_hba *phba)
2547 {
2548         struct Scsi_Host  *shost;
2549         struct lpfc_vport **vports;
2550         int i;
2551
2552         if (phba->pport->fc_flag & FC_OFFLINE_MODE)
2553                 return;
2554
2555         /* stop port and all timers associated with this hba */
2556         lpfc_stop_port(phba);
2557         vports = lpfc_create_vport_work_array(phba);
2558         if (vports != NULL)
2559                 for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++)
2560                         lpfc_stop_vport_timers(vports[i]);
2561         lpfc_destroy_vport_work_array(phba, vports);
2562         lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
2563                         "0460 Bring Adapter offline\n");
2564         /* Bring down the SLI Layer and cleanup.  The HBA is offline
2565            now.  */
2566         lpfc_sli_hba_down(phba);
2567         spin_lock_irq(&phba->hbalock);
2568         phba->work_ha = 0;
2569         spin_unlock_irq(&phba->hbalock);
2570         vports = lpfc_create_vport_work_array(phba);
2571         if (vports != NULL)
2572                 for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
2573                         shost = lpfc_shost_from_vport(vports[i]);
2574                         spin_lock_irq(shost->host_lock);
2575                         vports[i]->work_port_events = 0;
2576                         vports[i]->fc_flag |= FC_OFFLINE_MODE;
2577                         spin_unlock_irq(shost->host_lock);
2578                 }
2579         lpfc_destroy_vport_work_array(phba, vports);
2580 }
2581
2582 /**
2583  * lpfc_scsi_free - Free all the SCSI buffers and IOCBs from driver lists
2584  * @phba: pointer to lpfc hba data structure.
2585  *
2586  * This routine is to free all the SCSI buffers and IOCBs from the driver
2587  * list back to kernel. It is called from lpfc_pci_remove_one to free
2588  * the internal resources before the device is removed from the system.
2589  *
2590  * Return codes
2591  *   0 - successful (for now, it always returns 0)
2592  **/
2593 static int
2594 lpfc_scsi_free(struct lpfc_hba *phba)
2595 {
2596         struct lpfc_scsi_buf *sb, *sb_next;
2597         struct lpfc_iocbq *io, *io_next;
2598
2599         spin_lock_irq(&phba->hbalock);
2600         /* Release all the lpfc_scsi_bufs maintained by this host. */
2601         spin_lock(&phba->scsi_buf_list_lock);
2602         list_for_each_entry_safe(sb, sb_next, &phba->lpfc_scsi_buf_list, list) {
2603                 list_del(&sb->list);
2604                 pci_pool_free(phba->lpfc_scsi_dma_buf_pool, sb->data,
2605                               sb->dma_handle);
2606                 kfree(sb);
2607                 phba->total_scsi_bufs--;
2608         }
2609         spin_unlock(&phba->scsi_buf_list_lock);
2610
2611         /* Release all the lpfc_iocbq entries maintained by this host. */
2612         list_for_each_entry_safe(io, io_next, &phba->lpfc_iocb_list, list) {
2613                 list_del(&io->list);
2614                 kfree(io);
2615                 phba->total_iocbq_bufs--;
2616         }
2617         spin_unlock_irq(&phba->hbalock);
2618         return 0;
2619 }
2620
2621 /**
2622  * lpfc_create_port - Create an FC port
2623  * @phba: pointer to lpfc hba data structure.
2624  * @instance: a unique integer ID to this FC port.
2625  * @dev: pointer to the device data structure.
2626  *
2627  * This routine creates a FC port for the upper layer protocol. The FC port
2628  * can be created on top of either a physical port or a virtual port provided
2629  * by the HBA. This routine also allocates a SCSI host data structure (shost)
2630  * and associates the FC port created before adding the shost into the SCSI
2631  * layer.
2632  *
2633  * Return codes
2634  *   @vport - pointer to the virtual N_Port data structure.
2635  *   NULL - port create failed.
2636  **/
2637 struct lpfc_vport *
2638 lpfc_create_port(struct lpfc_hba *phba, int instance, struct device *dev)
2639 {
2640         struct lpfc_vport *vport;
2641         struct Scsi_Host  *shost;
2642         int error = 0;
2643
2644         if (dev != &phba->pcidev->dev)
2645                 shost = scsi_host_alloc(&lpfc_vport_template,
2646                                         sizeof(struct lpfc_vport));
2647         else
2648                 shost = scsi_host_alloc(&lpfc_template,
2649                                         sizeof(struct lpfc_vport));
2650         if (!shost)
2651                 goto out;
2652
2653         vport = (struct lpfc_vport *) shost->hostdata;
2654         vport->phba = phba;
2655         vport->load_flag |= FC_LOADING;
2656         vport->fc_flag |= FC_VPORT_NEEDS_REG_VPI;
2657         vport->fc_rscn_flush = 0;
2658
2659         lpfc_get_vport_cfgparam(vport);
2660         shost->unique_id = instance;
2661         shost->max_id = LPFC_MAX_TARGET;
2662         shost->max_lun = vport->cfg_max_luns;
2663         shost->this_id = -1;
2664         shost->max_cmd_len = 16;
2665         if (phba->sli_rev == LPFC_SLI_REV4) {
2666                 shost->dma_boundary =
2667                         phba->sli4_hba.pc_sli4_params.sge_supp_len-1;
2668                 shost->sg_tablesize = phba->cfg_sg_seg_cnt;
2669         }
2670
2671         /*
2672          * Set initial can_queue value since 0 is no longer supported and
2673          * scsi_add_host will fail. This will be adjusted later based on the
2674          * max xri value determined in hba setup.
2675          */
2676         shost->can_queue = phba->cfg_hba_queue_depth - 10;
2677         if (dev != &phba->pcidev->dev) {
2678                 shost->transportt = lpfc_vport_transport_template;
2679                 vport->port_type = LPFC_NPIV_PORT;
2680         } else {
2681                 shost->transportt = lpfc_transport_template;
2682                 vport->port_type = LPFC_PHYSICAL_PORT;
2683         }
2684
2685         /* Initialize all internally managed lists. */
2686         INIT_LIST_HEAD(&vport->fc_nodes);
2687         INIT_LIST_HEAD(&vport->rcv_buffer_list);
2688         spin_lock_init(&vport->work_port_lock);
2689
2690         init_timer(&vport->fc_disctmo);
2691         vport->fc_disctmo.function = lpfc_disc_timeout;
2692         vport->fc_disctmo.data = (unsigned long)vport;
2693
2694         init_timer(&vport->fc_fdmitmo);
2695         vport->fc_fdmitmo.function = lpfc_fdmi_tmo;
2696         vport->fc_fdmitmo.data = (unsigned long)vport;
2697
2698         init_timer(&vport->els_tmofunc);
2699         vport->els_tmofunc.function = lpfc_els_timeout;
2700         vport->els_tmofunc.data = (unsigned long)vport;
2701         error = scsi_add_host_with_dma(shost, dev, &phba->pcidev->dev);
2702         if (error)
2703                 goto out_put_shost;
2704
2705         spin_lock_irq(&phba->hbalock);
2706         list_add_tail(&vport->listentry, &phba->port_list);
2707         spin_unlock_irq(&phba->hbalock);
2708         return vport;
2709
2710 out_put_shost:
2711         scsi_host_put(shost);
2712 out:
2713         return NULL;
2714 }
2715
2716 /**
2717  * destroy_port -  destroy an FC port
2718  * @vport: pointer to an lpfc virtual N_Port data structure.
2719  *
2720  * This routine destroys a FC port from the upper layer protocol. All the
2721  * resources associated with the port are released.
2722  **/
2723 void
2724 destroy_port(struct lpfc_vport *vport)
2725 {
2726         struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
2727         struct lpfc_hba  *phba = vport->phba;
2728
2729         lpfc_debugfs_terminate(vport);
2730         fc_remove_host(shost);
2731         scsi_remove_host(shost);
2732
2733         spin_lock_irq(&phba->hbalock);
2734         list_del_init(&vport->listentry);
2735         spin_unlock_irq(&phba->hbalock);
2736
2737         lpfc_cleanup(vport);
2738         return;
2739 }
2740
2741 /**
2742  * lpfc_get_instance - Get a unique integer ID
2743  *
2744  * This routine allocates a unique integer ID from lpfc_hba_index pool. It
2745  * uses the kernel idr facility to perform the task.
2746  *
2747  * Return codes:
2748  *   instance - a unique integer ID allocated as the new instance.
2749  *   -1 - lpfc get instance failed.
2750  **/
2751 int
2752 lpfc_get_instance(void)
2753 {
2754         int instance = 0;
2755
2756         /* Assign an unused number */
2757         if (!idr_pre_get(&lpfc_hba_index, GFP_KERNEL))
2758                 return -1;
2759         if (idr_get_new(&lpfc_hba_index, NULL, &instance))
2760                 return -1;
2761         return instance;
2762 }
2763
2764 /**
2765  * lpfc_scan_finished - method for SCSI layer to detect whether scan is done
2766  * @shost: pointer to SCSI host data structure.
2767  * @time: elapsed time of the scan in jiffies.
2768  *
2769  * This routine is called by the SCSI layer with a SCSI host to determine
2770  * whether the scan host is finished.
2771  *
2772  * Note: there is no scan_start function as adapter initialization will have
2773  * asynchronously kicked off the link initialization.
2774  *
2775  * Return codes
2776  *   0 - SCSI host scan is not over yet.
2777  *   1 - SCSI host scan is over.
2778  **/
2779 int lpfc_scan_finished(struct Scsi_Host *shost, unsigned long time)
2780 {
2781         struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
2782         struct lpfc_hba   *phba = vport->phba;
2783         int stat = 0;
2784
2785         spin_lock_irq(shost->host_lock);
2786
2787         if (vport->load_flag & FC_UNLOADING) {
2788                 stat = 1;
2789                 goto finished;
2790         }
2791         if (time >= 30 * HZ) {
2792                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
2793                                 "0461 Scanning longer than 30 "
2794                                 "seconds.  Continuing initialization\n");
2795                 stat = 1;
2796                 goto finished;
2797         }
2798         if (time >= 15 * HZ && phba->link_state <= LPFC_LINK_DOWN) {
2799                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
2800                                 "0465 Link down longer than 15 "
2801                                 "seconds.  Continuing initialization\n");
2802                 stat = 1;
2803                 goto finished;
2804         }
2805
2806         if (vport->port_state != LPFC_VPORT_READY)
2807                 goto finished;
2808         if (vport->num_disc_nodes || vport->fc_prli_sent)
2809                 goto finished;
2810         if (vport->fc_map_cnt == 0 && time < 2 * HZ)
2811                 goto finished;
2812         if ((phba->sli.sli_flag & LPFC_SLI_MBOX_ACTIVE) != 0)
2813                 goto finished;
2814
2815         stat = 1;
2816
2817 finished:
2818         spin_unlock_irq(shost->host_lock);
2819         return stat;
2820 }
2821
2822 /**
2823  * lpfc_host_attrib_init - Initialize SCSI host attributes on a FC port
2824  * @shost: pointer to SCSI host data structure.
2825  *
2826  * This routine initializes a given SCSI host attributes on a FC port. The
2827  * SCSI host can be either on top of a physical port or a virtual port.
2828  **/
2829 void lpfc_host_attrib_init(struct Scsi_Host *shost)
2830 {
2831         struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
2832         struct lpfc_hba   *phba = vport->phba;
2833         /*
2834          * Set fixed host attributes.  Must done after lpfc_sli_hba_setup().
2835          */
2836
2837         fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
2838         fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
2839         fc_host_supported_classes(shost) = FC_COS_CLASS3;
2840
2841         memset(fc_host_supported_fc4s(shost), 0,
2842                sizeof(fc_host_supported_fc4s(shost)));
2843         fc_host_supported_fc4s(shost)[2] = 1;
2844         fc_host_supported_fc4s(shost)[7] = 1;
2845
2846         lpfc_vport_symbolic_node_name(vport, fc_host_symbolic_name(shost),
2847                                  sizeof fc_host_symbolic_name(shost));
2848
2849         fc_host_supported_speeds(shost) = 0;
2850         if (phba->lmt & LMT_10Gb)
2851                 fc_host_supported_speeds(shost) |= FC_PORTSPEED_10GBIT;
2852         if (phba->lmt & LMT_8Gb)
2853                 fc_host_supported_speeds(shost) |= FC_PORTSPEED_8GBIT;
2854         if (phba->lmt & LMT_4Gb)
2855                 fc_host_supported_speeds(shost) |= FC_PORTSPEED_4GBIT;
2856         if (phba->lmt & LMT_2Gb)
2857                 fc_host_supported_speeds(shost) |= FC_PORTSPEED_2GBIT;
2858         if (phba->lmt & LMT_1Gb)
2859                 fc_host_supported_speeds(shost) |= FC_PORTSPEED_1GBIT;
2860
2861         fc_host_maxframe_size(shost) =
2862                 (((uint32_t) vport->fc_sparam.cmn.bbRcvSizeMsb & 0x0F) << 8) |
2863                 (uint32_t) vport->fc_sparam.cmn.bbRcvSizeLsb;
2864
2865         fc_host_dev_loss_tmo(shost) = vport->cfg_devloss_tmo;
2866
2867         /* This value is also unchanging */
2868         memset(fc_host_active_fc4s(shost), 0,
2869                sizeof(fc_host_active_fc4s(shost)));
2870         fc_host_active_fc4s(shost)[2] = 1;
2871         fc_host_active_fc4s(shost)[7] = 1;
2872
2873         fc_host_max_npiv_vports(shost) = phba->max_vpi;
2874         spin_lock_irq(shost->host_lock);
2875         vport->load_flag &= ~FC_LOADING;
2876         spin_unlock_irq(shost->host_lock);
2877 }
2878
2879 /**
2880  * lpfc_stop_port_s3 - Stop SLI3 device port
2881  * @phba: pointer to lpfc hba data structure.
2882  *
2883  * This routine is invoked to stop an SLI3 device port, it stops the device
2884  * from generating interrupts and stops the device driver's timers for the
2885  * device.
2886  **/
2887 static void
2888 lpfc_stop_port_s3(struct lpfc_hba *phba)
2889 {
2890         /* Clear all interrupt enable conditions */
2891         writel(0, phba->HCregaddr);
2892         readl(phba->HCregaddr); /* flush */
2893         /* Clear all pending interrupts */
2894         writel(0xffffffff, phba->HAregaddr);
2895         readl(phba->HAregaddr); /* flush */
2896
2897         /* Reset some HBA SLI setup states */
2898         lpfc_stop_hba_timers(phba);
2899         phba->pport->work_port_events = 0;
2900 }
2901
2902 /**
2903  * lpfc_stop_port_s4 - Stop SLI4 device port
2904  * @phba: pointer to lpfc hba data structure.
2905  *
2906  * This routine is invoked to stop an SLI4 device port, it stops the device
2907  * from generating interrupts and stops the device driver's timers for the
2908  * device.
2909  **/
2910 static void
2911 lpfc_stop_port_s4(struct lpfc_hba *phba)
2912 {
2913         /* Reset some HBA SLI4 setup states */
2914         lpfc_stop_hba_timers(phba);
2915         phba->pport->work_port_events = 0;
2916         phba->sli4_hba.intr_enable = 0;
2917 }
2918
2919 /**
2920  * lpfc_stop_port - Wrapper function for stopping hba port
2921  * @phba: Pointer to HBA context object.
2922  *
2923  * This routine wraps the actual SLI3 or SLI4 hba stop port routine from
2924  * the API jump table function pointer from the lpfc_hba struct.
2925  **/
2926 void
2927 lpfc_stop_port(struct lpfc_hba *phba)
2928 {
2929         phba->lpfc_stop_port(phba);
2930 }
2931
2932 /**
2933  * lpfc_fcf_redisc_wait_start_timer - Start fcf rediscover wait timer
2934  * @phba: Pointer to hba for which this call is being executed.
2935  *
2936  * This routine starts the timer waiting for the FCF rediscovery to complete.
2937  **/
2938 void
2939 lpfc_fcf_redisc_wait_start_timer(struct lpfc_hba *phba)
2940 {
2941         unsigned long fcf_redisc_wait_tmo =
2942                 (jiffies + msecs_to_jiffies(LPFC_FCF_REDISCOVER_WAIT_TMO));
2943         /* Start fcf rediscovery wait period timer */
2944         mod_timer(&phba->fcf.redisc_wait, fcf_redisc_wait_tmo);
2945         spin_lock_irq(&phba->hbalock);
2946         /* Allow action to new fcf asynchronous event */
2947         phba->fcf.fcf_flag &= ~(FCF_AVAILABLE | FCF_SCAN_DONE);
2948         /* Mark the FCF rediscovery pending state */
2949         phba->fcf.fcf_flag |= FCF_REDISC_PEND;
2950         spin_unlock_irq(&phba->hbalock);
2951 }
2952
2953 /**
2954  * lpfc_sli4_fcf_redisc_wait_tmo - FCF table rediscover wait timeout
2955  * @ptr: Map to lpfc_hba data structure pointer.
2956  *
2957  * This routine is invoked when waiting for FCF table rediscover has been
2958  * timed out. If new FCF record(s) has (have) been discovered during the
2959  * wait period, a new FCF event shall be added to the FCOE async event
2960  * list, and then worker thread shall be waked up for processing from the
2961  * worker thread context.
2962  **/
2963 void
2964 lpfc_sli4_fcf_redisc_wait_tmo(unsigned long ptr)
2965 {
2966         struct lpfc_hba *phba = (struct lpfc_hba *)ptr;
2967
2968         /* Don't send FCF rediscovery event if timer cancelled */
2969         spin_lock_irq(&phba->hbalock);
2970         if (!(phba->fcf.fcf_flag & FCF_REDISC_PEND)) {
2971                 spin_unlock_irq(&phba->hbalock);
2972                 return;
2973         }
2974         /* Clear FCF rediscovery timer pending flag */
2975         phba->fcf.fcf_flag &= ~FCF_REDISC_PEND;
2976         /* FCF rediscovery event to worker thread */
2977         phba->fcf.fcf_flag |= FCF_REDISC_EVT;
2978         spin_unlock_irq(&phba->hbalock);
2979         lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
2980                         "2776 FCF rediscover quiescent timer expired\n");
2981         /* wake up worker thread */
2982         lpfc_worker_wake_up(phba);
2983 }
2984
2985 /**
2986  * lpfc_sli4_fw_cfg_check - Read the firmware config and verify FCoE support
2987  * @phba: pointer to lpfc hba data structure.
2988  *
2989  * This function uses the QUERY_FW_CFG mailbox command to determine if the
2990  * firmware loaded supports FCoE. A return of zero indicates that the mailbox
2991  * was successful and the firmware supports FCoE. Any other return indicates
2992  * a error. It is assumed that this function will be called before interrupts
2993  * are enabled.
2994  **/
2995 static int
2996 lpfc_sli4_fw_cfg_check(struct lpfc_hba *phba)
2997 {
2998         int rc = 0;
2999         LPFC_MBOXQ_t *mboxq;
3000         struct lpfc_mbx_query_fw_cfg *query_fw_cfg;
3001         uint32_t length;
3002         uint32_t shdr_status, shdr_add_status;
3003
3004         mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
3005         if (!mboxq) {
3006                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
3007                                 "2621 Failed to allocate mbox for "
3008                                 "query firmware config cmd\n");
3009                 return -ENOMEM;
3010         }
3011         query_fw_cfg = &mboxq->u.mqe.un.query_fw_cfg;
3012         length = (sizeof(struct lpfc_mbx_query_fw_cfg) -
3013                   sizeof(struct lpfc_sli4_cfg_mhdr));
3014         lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
3015                          LPFC_MBOX_OPCODE_QUERY_FW_CFG,
3016                          length, LPFC_SLI4_MBX_EMBED);
3017         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
3018         /* The IOCTL status is embedded in the mailbox subheader. */
3019         shdr_status = bf_get(lpfc_mbox_hdr_status,
3020                              &query_fw_cfg->header.cfg_shdr.response);
3021         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
3022                                  &query_fw_cfg->header.cfg_shdr.response);
3023         if (shdr_status || shdr_add_status || rc != MBX_SUCCESS) {
3024                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3025                                 "2622 Query Firmware Config failed "
3026                                 "mbx status x%x, status x%x add_status x%x\n",
3027                                 rc, shdr_status, shdr_add_status);
3028                 return -EINVAL;
3029         }
3030         if (!bf_get(lpfc_function_mode_fcoe_i, query_fw_cfg)) {
3031                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3032                                 "2623 FCoE Function not supported by firmware. "
3033                                 "Function mode = %08x\n",
3034                                 query_fw_cfg->function_mode);
3035                 return -EINVAL;
3036         }
3037         if (rc != MBX_TIMEOUT)
3038                 mempool_free(mboxq, phba->mbox_mem_pool);
3039         return 0;
3040 }
3041
3042 /**
3043  * lpfc_sli4_parse_latt_fault - Parse sli4 link-attention link fault code
3044  * @phba: pointer to lpfc hba data structure.
3045  * @acqe_link: pointer to the async link completion queue entry.
3046  *
3047  * This routine is to parse the SLI4 link-attention link fault code and
3048  * translate it into the base driver's read link attention mailbox command
3049  * status.
3050  *
3051  * Return: Link-attention status in terms of base driver's coding.
3052  **/
3053 static uint16_t
3054 lpfc_sli4_parse_latt_fault(struct lpfc_hba *phba,
3055                            struct lpfc_acqe_link *acqe_link)
3056 {
3057         uint16_t latt_fault;
3058
3059         switch (bf_get(lpfc_acqe_link_fault, acqe_link)) {
3060         case LPFC_ASYNC_LINK_FAULT_NONE:
3061         case LPFC_ASYNC_LINK_FAULT_LOCAL:
3062         case LPFC_ASYNC_LINK_FAULT_REMOTE:
3063                 latt_fault = 0;
3064                 break;
3065         default:
3066                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
3067                                 "0398 Invalid link fault code: x%x\n",
3068                                 bf_get(lpfc_acqe_link_fault, acqe_link));
3069                 latt_fault = MBXERR_ERROR;
3070                 break;
3071         }
3072         return latt_fault;
3073 }
3074
3075 /**
3076  * lpfc_sli4_parse_latt_type - Parse sli4 link attention type
3077  * @phba: pointer to lpfc hba data structure.
3078  * @acqe_link: pointer to the async link completion queue entry.
3079  *
3080  * This routine is to parse the SLI4 link attention type and translate it
3081  * into the base driver's link attention type coding.
3082  *
3083  * Return: Link attention type in terms of base driver's coding.
3084  **/
3085 static uint8_t
3086 lpfc_sli4_parse_latt_type(struct lpfc_hba *phba,
3087                           struct lpfc_acqe_link *acqe_link)
3088 {
3089         uint8_t att_type;
3090
3091         switch (bf_get(lpfc_acqe_link_status, acqe_link)) {
3092         case LPFC_ASYNC_LINK_STATUS_DOWN:
3093         case LPFC_ASYNC_LINK_STATUS_LOGICAL_DOWN:
3094                 att_type = LPFC_ATT_LINK_DOWN;
3095                 break;
3096         case LPFC_ASYNC_LINK_STATUS_UP:
3097                 /* Ignore physical link up events - wait for logical link up */
3098                 att_type = LPFC_ATT_RESERVED;
3099                 break;
3100         case LPFC_ASYNC_LINK_STATUS_LOGICAL_UP:
3101                 att_type = LPFC_ATT_LINK_UP;
3102                 break;
3103         default:
3104                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
3105                                 "0399 Invalid link attention type: x%x\n",
3106                                 bf_get(lpfc_acqe_link_status, acqe_link));
3107                 att_type = LPFC_ATT_RESERVED;
3108                 break;
3109         }
3110         return att_type;
3111 }
3112
3113 /**
3114  * lpfc_sli4_parse_latt_link_speed - Parse sli4 link-attention link speed
3115  * @phba: pointer to lpfc hba data structure.
3116  * @acqe_link: pointer to the async link completion queue entry.
3117  *
3118  * This routine is to parse the SLI4 link-attention link speed and translate
3119  * it into the base driver's link-attention link speed coding.
3120  *
3121  * Return: Link-attention link speed in terms of base driver's coding.
3122  **/
3123 static uint8_t
3124 lpfc_sli4_parse_latt_link_speed(struct lpfc_hba *phba,
3125                                 struct lpfc_acqe_link *acqe_link)
3126 {
3127         uint8_t link_speed;
3128
3129         switch (bf_get(lpfc_acqe_link_speed, acqe_link)) {
3130         case LPFC_ASYNC_LINK_SPEED_ZERO:
3131         case LPFC_ASYNC_LINK_SPEED_10MBPS:
3132         case LPFC_ASYNC_LINK_SPEED_100MBPS:
3133                 link_speed = LPFC_LINK_SPEED_UNKNOWN;
3134                 break;
3135         case LPFC_ASYNC_LINK_SPEED_1GBPS:
3136                 link_speed = LPFC_LINK_SPEED_1GHZ;
3137                 break;
3138         case LPFC_ASYNC_LINK_SPEED_10GBPS:
3139                 link_speed = LPFC_LINK_SPEED_10GHZ;
3140                 break;
3141         default:
3142                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
3143                                 "0483 Invalid link-attention link speed: x%x\n",
3144                                 bf_get(lpfc_acqe_link_speed, acqe_link));
3145                 link_speed = LPFC_LINK_SPEED_UNKNOWN;
3146                 break;
3147         }
3148         return link_speed;
3149 }
3150
3151 /**
3152  * lpfc_sli4_async_link_evt - Process the asynchronous FC or FCoE link event
3153  * @phba: pointer to lpfc hba data structure.
3154  * @acqe_link: pointer to the async link completion queue entry.
3155  *
3156  * This routine is to handle the SLI4 asynchronous link event.
3157  **/
3158 static void
3159 lpfc_sli4_async_link_evt(struct lpfc_hba *phba,
3160                          struct lpfc_acqe_link *acqe_link)
3161 {
3162         struct lpfc_dmabuf *mp;
3163         LPFC_MBOXQ_t *pmb;
3164         MAILBOX_t *mb;
3165         struct lpfc_mbx_read_top *la;
3166         uint8_t att_type;
3167         int rc;
3168
3169         att_type = lpfc_sli4_parse_latt_type(phba, acqe_link);
3170         if (att_type != LPFC_ATT_LINK_DOWN && att_type != LPFC_ATT_LINK_UP)
3171                 return;
3172         phba->fcoe_eventtag = acqe_link->event_tag;
3173         pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
3174         if (!pmb) {
3175                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3176                                 "0395 The mboxq allocation failed\n");
3177                 return;
3178         }
3179         mp = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
3180         if (!mp) {
3181                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3182                                 "0396 The lpfc_dmabuf allocation failed\n");
3183                 goto out_free_pmb;
3184         }
3185         mp->virt = lpfc_mbuf_alloc(phba, 0, &mp->phys);
3186         if (!mp->virt) {
3187                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3188                                 "0397 The mbuf allocation failed\n");
3189                 goto out_free_dmabuf;
3190         }
3191
3192         /* Cleanup any outstanding ELS commands */
3193         lpfc_els_flush_all_cmd(phba);
3194
3195         /* Block ELS IOCBs until we have done process link event */
3196         phba->sli.ring[LPFC_ELS_RING].flag |= LPFC_STOP_IOCB_EVENT;
3197
3198         /* Update link event statistics */
3199         phba->sli.slistat.link_event++;
3200
3201         /* Create lpfc_handle_latt mailbox command from link ACQE */
3202         lpfc_read_topology(phba, pmb, mp);
3203         pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
3204         pmb->vport = phba->pport;
3205
3206         /* Keep the link status for extra SLI4 state machine reference */
3207         phba->sli4_hba.link_state.speed =
3208                                 bf_get(lpfc_acqe_link_speed, acqe_link);
3209         phba->sli4_hba.link_state.duplex =
3210                                 bf_get(lpfc_acqe_link_duplex, acqe_link);
3211         phba->sli4_hba.link_state.status =
3212                                 bf_get(lpfc_acqe_link_status, acqe_link);
3213         phba->sli4_hba.link_state.physical =
3214                                 bf_get(lpfc_acqe_link_physical, acqe_link);
3215         phba->sli4_hba.link_state.fault =
3216                                 bf_get(lpfc_acqe_link_fault, acqe_link);
3217         phba->sli4_hba.link_state.logical_speed =
3218                                 bf_get(lpfc_acqe_qos_link_speed, acqe_link);
3219         /*
3220          * For FC Mode: issue the READ_TOPOLOGY mailbox command to fetch
3221          * topology info. Note: Optional for non FC-AL ports.
3222          */
3223         if (!(phba->hba_flag & HBA_FCOE_MODE)) {
3224                 rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
3225                 if (rc == MBX_NOT_FINISHED)
3226                         goto out_free_dmabuf;
3227                 return;
3228         }
3229         /*
3230          * For FCoE Mode: fill in all the topology information we need and call
3231          * the READ_TOPOLOGY completion routine to continue without actually
3232          * sending the READ_TOPOLOGY mailbox command to the port.
3233          */
3234         /* Parse and translate status field */
3235         mb = &pmb->u.mb;
3236         mb->mbxStatus = lpfc_sli4_parse_latt_fault(phba, acqe_link);
3237
3238         /* Parse and translate link attention fields */
3239         la = (struct lpfc_mbx_read_top *) &pmb->u.mb.un.varReadTop;
3240         la->eventTag = acqe_link->event_tag;
3241         bf_set(lpfc_mbx_read_top_att_type, la, att_type);
3242         bf_set(lpfc_mbx_read_top_link_spd, la,
3243                lpfc_sli4_parse_latt_link_speed(phba, acqe_link));
3244
3245         /* Fake the the following irrelvant fields */
3246         bf_set(lpfc_mbx_read_top_topology, la, LPFC_TOPOLOGY_PT_PT);
3247         bf_set(lpfc_mbx_read_top_alpa_granted, la, 0);
3248         bf_set(lpfc_mbx_read_top_il, la, 0);
3249         bf_set(lpfc_mbx_read_top_pb, la, 0);
3250         bf_set(lpfc_mbx_read_top_fa, la, 0);
3251         bf_set(lpfc_mbx_read_top_mm, la, 0);
3252
3253         /* Invoke the lpfc_handle_latt mailbox command callback function */
3254         lpfc_mbx_cmpl_read_topology(phba, pmb);
3255
3256         return;
3257
3258 out_free_dmabuf:
3259         kfree(mp);
3260 out_free_pmb:
3261         mempool_free(pmb, phba->mbox_mem_pool);
3262 }
3263
3264 /**
3265  * lpfc_sli4_perform_vport_cvl - Perform clear virtual link on a vport
3266  * @vport: pointer to vport data structure.
3267  *
3268  * This routine is to perform Clear Virtual Link (CVL) on a vport in
3269  * response to a CVL event.
3270  *
3271  * Return the pointer to the ndlp with the vport if successful, otherwise
3272  * return NULL.
3273  **/
3274 static struct lpfc_nodelist *
3275 lpfc_sli4_perform_vport_cvl(struct lpfc_vport *vport)
3276 {
3277         struct lpfc_nodelist *ndlp;
3278         struct Scsi_Host *shost;
3279         struct lpfc_hba *phba;
3280
3281         if (!vport)
3282                 return NULL;
3283         phba = vport->phba;
3284         if (!phba)
3285                 return NULL;
3286         ndlp = lpfc_findnode_did(vport, Fabric_DID);
3287         if (!ndlp) {
3288                 /* Cannot find existing Fabric ndlp, so allocate a new one */
3289                 ndlp = mempool_alloc(phba->nlp_mem_pool, GFP_KERNEL);
3290                 if (!ndlp)
3291                         return 0;
3292                 lpfc_nlp_init(vport, ndlp, Fabric_DID);
3293                 /* Set the node type */
3294                 ndlp->nlp_type |= NLP_FABRIC;
3295                 /* Put ndlp onto node list */
3296                 lpfc_enqueue_node(vport, ndlp);
3297         } else if (!NLP_CHK_NODE_ACT(ndlp)) {
3298                 /* re-setup ndlp without removing from node list */
3299                 ndlp = lpfc_enable_node(vport, ndlp, NLP_STE_UNUSED_NODE);
3300                 if (!ndlp)
3301                         return 0;
3302         }
3303         if ((phba->pport->port_state < LPFC_FLOGI) &&
3304                 (phba->pport->port_state != LPFC_VPORT_FAILED))
3305                 return NULL;
3306         /* If virtual link is not yet instantiated ignore CVL */
3307         if ((vport != phba->pport) && (vport->port_state < LPFC_FDISC)
3308                 && (vport->port_state != LPFC_VPORT_FAILED))
3309                 return NULL;
3310         shost = lpfc_shost_from_vport(vport);
3311         if (!shost)
3312                 return NULL;
3313         lpfc_linkdown_port(vport);
3314         lpfc_cleanup_pending_mbox(vport);
3315         spin_lock_irq(shost->host_lock);
3316         vport->fc_flag |= FC_VPORT_CVL_RCVD;
3317         spin_unlock_irq(shost->host_lock);
3318
3319         return ndlp;
3320 }
3321
3322 /**
3323  * lpfc_sli4_perform_all_vport_cvl - Perform clear virtual link on all vports
3324  * @vport: pointer to lpfc hba data structure.
3325  *
3326  * This routine is to perform Clear Virtual Link (CVL) on all vports in
3327  * response to a FCF dead event.
3328  **/
3329 static void
3330 lpfc_sli4_perform_all_vport_cvl(struct lpfc_hba *phba)
3331 {
3332         struct lpfc_vport **vports;
3333         int i;
3334
3335         vports = lpfc_create_vport_work_array(phba);
3336         if (vports)
3337                 for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++)
3338                         lpfc_sli4_perform_vport_cvl(vports[i]);
3339         lpfc_destroy_vport_work_array(phba, vports);
3340 }
3341
3342 /**
3343  * lpfc_sli4_async_fip_evt - Process the asynchronous FCoE FIP event
3344  * @phba: pointer to lpfc hba data structure.
3345  * @acqe_link: pointer to the async fcoe completion queue entry.
3346  *
3347  * This routine is to handle the SLI4 asynchronous fcoe event.
3348  **/
3349 static void
3350 lpfc_sli4_async_fip_evt(struct lpfc_hba *phba,
3351                         struct lpfc_acqe_fcoe *acqe_fcoe)
3352 {
3353         uint8_t event_type = bf_get(lpfc_acqe_fcoe_event_type, acqe_fcoe);
3354         int rc;
3355         struct lpfc_vport *vport;
3356         struct lpfc_nodelist *ndlp;
3357         struct Scsi_Host  *shost;
3358         int active_vlink_present;
3359         struct lpfc_vport **vports;
3360         int i;
3361
3362         phba->fc_eventTag = acqe_fcoe->event_tag;
3363         phba->fcoe_eventtag = acqe_fcoe->event_tag;
3364         switch (event_type) {
3365         case LPFC_FCOE_EVENT_TYPE_NEW_FCF:
3366         case LPFC_FCOE_EVENT_TYPE_FCF_PARAM_MOD:
3367                 if (event_type == LPFC_FCOE_EVENT_TYPE_NEW_FCF)
3368                         lpfc_printf_log(phba, KERN_ERR, LOG_FIP |
3369                                         LOG_DISCOVERY,
3370                                         "2546 New FCF event, evt_tag:x%x, "
3371                                         "index:x%x\n",
3372                                         acqe_fcoe->event_tag,
3373                                         acqe_fcoe->index);
3374                 else
3375                         lpfc_printf_log(phba, KERN_WARNING, LOG_FIP |
3376                                         LOG_DISCOVERY,
3377                                         "2788 FCF param modified event, "
3378                                         "evt_tag:x%x, index:x%x\n",
3379                                         acqe_fcoe->event_tag,
3380                                         acqe_fcoe->index);
3381                 if (phba->fcf.fcf_flag & FCF_DISCOVERY) {
3382                         /*
3383                          * During period of FCF discovery, read the FCF
3384                          * table record indexed by the event to update
3385                          * FCF roundrobin failover eligible FCF bmask.
3386                          */
3387                         lpfc_printf_log(phba, KERN_INFO, LOG_FIP |
3388                                         LOG_DISCOVERY,
3389                                         "2779 Read FCF (x%x) for updating "
3390                                         "roundrobin FCF failover bmask\n",
3391                                         acqe_fcoe->index);
3392                         rc = lpfc_sli4_read_fcf_rec(phba, acqe_fcoe->index);
3393                 }
3394
3395                 /* If the FCF discovery is in progress, do nothing. */
3396                 spin_lock_irq(&phba->hbalock);
3397                 if (phba->hba_flag & FCF_TS_INPROG) {
3398                         spin_unlock_irq(&phba->hbalock);
3399                         break;
3400                 }
3401                 /* If fast FCF failover rescan event is pending, do nothing */
3402                 if (phba->fcf.fcf_flag & FCF_REDISC_EVT) {
3403                         spin_unlock_irq(&phba->hbalock);
3404                         break;
3405                 }
3406
3407                 /* If the FCF has been in discovered state, do nothing. */
3408                 if (phba->fcf.fcf_flag & FCF_SCAN_DONE) {
3409                         spin_unlock_irq(&phba->hbalock);
3410                         break;
3411                 }
3412                 spin_unlock_irq(&phba->hbalock);
3413
3414                 /* Otherwise, scan the entire FCF table and re-discover SAN */
3415                 lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
3416                                 "2770 Start FCF table scan per async FCF "
3417                                 "event, evt_tag:x%x, index:x%x\n",
3418                                 acqe_fcoe->event_tag, acqe_fcoe->index);
3419                 rc = lpfc_sli4_fcf_scan_read_fcf_rec(phba,
3420                                                      LPFC_FCOE_FCF_GET_FIRST);
3421                 if (rc)
3422                         lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_DISCOVERY,
3423                                         "2547 Issue FCF scan read FCF mailbox "
3424                                         "command failed (x%x)\n", rc);
3425                 break;
3426
3427         case LPFC_FCOE_EVENT_TYPE_FCF_TABLE_FULL:
3428                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3429                         "2548 FCF Table full count 0x%x tag 0x%x\n",
3430                         bf_get(lpfc_acqe_fcoe_fcf_count, acqe_fcoe),
3431                         acqe_fcoe->event_tag);
3432                 break;
3433
3434         case LPFC_FCOE_EVENT_TYPE_FCF_DEAD:
3435                 lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_DISCOVERY,
3436                         "2549 FCF (x%x) disconnected from network, "
3437                         "tag:x%x\n", acqe_fcoe->index, acqe_fcoe->event_tag);
3438                 /*
3439                  * If we are in the middle of FCF failover process, clear
3440                  * the corresponding FCF bit in the roundrobin bitmap.
3441                  */
3442                 spin_lock_irq(&phba->hbalock);
3443                 if (phba->fcf.fcf_flag & FCF_DISCOVERY) {
3444                         spin_unlock_irq(&phba->hbalock);
3445                         /* Update FLOGI FCF failover eligible FCF bmask */
3446                         lpfc_sli4_fcf_rr_index_clear(phba, acqe_fcoe->index);
3447                         break;
3448                 }
3449                 spin_unlock_irq(&phba->hbalock);
3450
3451                 /* If the event is not for currently used fcf do nothing */
3452                 if (phba->fcf.current_rec.fcf_indx != acqe_fcoe->index)
3453                         break;
3454
3455                 /*
3456                  * Otherwise, request the port to rediscover the entire FCF
3457                  * table for a fast recovery from case that the current FCF
3458                  * is no longer valid as we are not in the middle of FCF
3459                  * failover process already.
3460                  */
3461                 spin_lock_irq(&phba->hbalock);
3462                 /* Mark the fast failover process in progress */
3463                 phba->fcf.fcf_flag |= FCF_DEAD_DISC;
3464                 spin_unlock_irq(&phba->hbalock);
3465
3466                 lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
3467                                 "2771 Start FCF fast failover process due to "
3468                                 "FCF DEAD event: evt_tag:x%x, fcf_index:x%x "
3469                                 "\n", acqe_fcoe->event_tag, acqe_fcoe->index);
3470                 rc = lpfc_sli4_redisc_fcf_table(phba);
3471                 if (rc) {
3472                         lpfc_printf_log(phba, KERN_ERR, LOG_FIP |
3473                                         LOG_DISCOVERY,
3474                                         "2772 Issue FCF rediscover mabilbox "
3475                                         "command failed, fail through to FCF "
3476                                         "dead event\n");
3477                         spin_lock_irq(&phba->hbalock);
3478                         phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
3479                         spin_unlock_irq(&phba->hbalock);
3480                         /*
3481                          * Last resort will fail over by treating this
3482                          * as a link down to FCF registration.
3483                          */
3484                         lpfc_sli4_fcf_dead_failthrough(phba);
3485                 } else {
3486                         /* Reset FCF roundrobin bmask for new discovery */
3487                         memset(phba->fcf.fcf_rr_bmask, 0,
3488                                sizeof(*phba->fcf.fcf_rr_bmask));
3489                         /*
3490                          * Handling fast FCF failover to a DEAD FCF event is
3491                          * considered equalivant to receiving CVL to all vports.
3492                          */
3493                         lpfc_sli4_perform_all_vport_cvl(phba);
3494                 }
3495                 break;
3496         case LPFC_FCOE_EVENT_TYPE_CVL:
3497                 lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_DISCOVERY,
3498                         "2718 Clear Virtual Link Received for VPI 0x%x"
3499                         " tag 0x%x\n", acqe_fcoe->index, acqe_fcoe->event_tag);
3500                 vport = lpfc_find_vport_by_vpid(phba,
3501                                 acqe_fcoe->index - phba->vpi_base);
3502                 ndlp = lpfc_sli4_perform_vport_cvl(vport);
3503                 if (!ndlp)
3504                         break;
3505                 active_vlink_present = 0;
3506
3507                 vports = lpfc_create_vport_work_array(phba);
3508                 if (vports) {
3509                         for (i = 0; i <= phba->max_vports && vports[i] != NULL;
3510                                         i++) {
3511                                 if ((!(vports[i]->fc_flag &
3512                                         FC_VPORT_CVL_RCVD)) &&
3513                                         (vports[i]->port_state > LPFC_FDISC)) {
3514                                         active_vlink_present = 1;
3515                                         break;
3516                                 }
3517                         }
3518                         lpfc_destroy_vport_work_array(phba, vports);
3519                 }
3520
3521                 if (active_vlink_present) {
3522                         /*
3523                          * If there are other active VLinks present,
3524                          * re-instantiate the Vlink using FDISC.
3525                          */
3526                         mod_timer(&ndlp->nlp_delayfunc, jiffies + HZ);
3527                         shost = lpfc_shost_from_vport(vport);
3528                         spin_lock_irq(shost->host_lock);
3529                         ndlp->nlp_flag |= NLP_DELAY_TMO;
3530                         spin_unlock_irq(shost->host_lock);
3531                         ndlp->nlp_last_elscmd = ELS_CMD_FDISC;
3532                         vport->port_state = LPFC_FDISC;
3533                 } else {
3534                         /*
3535                          * Otherwise, we request port to rediscover
3536                          * the entire FCF table for a fast recovery
3537                          * from possible case that the current FCF
3538                          * is no longer valid if we are not already
3539                          * in the FCF failover process.
3540                          */
3541                         spin_lock_irq(&phba->hbalock);
3542                         if (phba->fcf.fcf_flag & FCF_DISCOVERY) {
3543                                 spin_unlock_irq(&phba->hbalock);
3544                                 break;
3545                         }
3546                         /* Mark the fast failover process in progress */
3547                         phba->fcf.fcf_flag |= FCF_ACVL_DISC;
3548                         spin_unlock_irq(&phba->hbalock);
3549                         lpfc_printf_log(phba, KERN_INFO, LOG_FIP |
3550                                         LOG_DISCOVERY,
3551                                         "2773 Start FCF failover per CVL, "
3552                                         "evt_tag:x%x\n", acqe_fcoe->event_tag);
3553                         rc = lpfc_sli4_redisc_fcf_table(phba);
3554                         if (rc) {
3555                                 lpfc_printf_log(phba, KERN_ERR, LOG_FIP |
3556                                                 LOG_DISCOVERY,
3557                                                 "2774 Issue FCF rediscover "
3558                                                 "mabilbox command failed, "
3559                                                 "through to CVL event\n");
3560                                 spin_lock_irq(&phba->hbalock);
3561                                 phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
3562                                 spin_unlock_irq(&phba->hbalock);
3563                                 /*
3564                                  * Last resort will be re-try on the
3565                                  * the current registered FCF entry.
3566                                  */
3567                                 lpfc_retry_pport_discovery(phba);
3568                         } else
3569                                 /*
3570                                  * Reset FCF roundrobin bmask for new
3571                                  * discovery.
3572                                  */
3573                                 memset(phba->fcf.fcf_rr_bmask, 0,
3574                                        sizeof(*phba->fcf.fcf_rr_bmask));
3575                 }
3576                 break;
3577         default:
3578                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3579                         "0288 Unknown FCoE event type 0x%x event tag "
3580                         "0x%x\n", event_type, acqe_fcoe->event_tag);
3581                 break;
3582         }
3583 }
3584
3585 /**
3586  * lpfc_sli4_async_dcbx_evt - Process the asynchronous dcbx event
3587  * @phba: pointer to lpfc hba data structure.
3588  * @acqe_link: pointer to the async dcbx completion queue entry.
3589  *
3590  * This routine is to handle the SLI4 asynchronous dcbx event.
3591  **/
3592 static void
3593 lpfc_sli4_async_dcbx_evt(struct lpfc_hba *phba,
3594                          struct lpfc_acqe_dcbx *acqe_dcbx)
3595 {
3596         phba->fc_eventTag = acqe_dcbx->event_tag;
3597         lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3598                         "0290 The SLI4 DCBX asynchronous event is not "
3599                         "handled yet\n");
3600 }
3601
3602 /**
3603  * lpfc_sli4_async_grp5_evt - Process the asynchronous group5 event
3604  * @phba: pointer to lpfc hba data structure.
3605  * @acqe_link: pointer to the async grp5 completion queue entry.
3606  *
3607  * This routine is to handle the SLI4 asynchronous grp5 event. A grp5 event
3608  * is an asynchronous notified of a logical link speed change.  The Port
3609  * reports the logical link speed in units of 10Mbps.
3610  **/
3611 static void
3612 lpfc_sli4_async_grp5_evt(struct lpfc_hba *phba,
3613                          struct lpfc_acqe_grp5 *acqe_grp5)
3614 {
3615         uint16_t prev_ll_spd;
3616
3617         phba->fc_eventTag = acqe_grp5->event_tag;
3618         phba->fcoe_eventtag = acqe_grp5->event_tag;
3619         prev_ll_spd = phba->sli4_hba.link_state.logical_speed;
3620         phba->sli4_hba.link_state.logical_speed =
3621                 (bf_get(lpfc_acqe_grp5_llink_spd, acqe_grp5));
3622         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3623                         "2789 GRP5 Async Event: Updating logical link speed "
3624                         "from %dMbps to %dMbps\n", (prev_ll_spd * 10),
3625                         (phba->sli4_hba.link_state.logical_speed*10));
3626 }
3627
3628 /**
3629  * lpfc_sli4_async_event_proc - Process all the pending asynchronous event
3630  * @phba: pointer to lpfc hba data structure.
3631  *
3632  * This routine is invoked by the worker thread to process all the pending
3633  * SLI4 asynchronous events.
3634  **/
3635 void lpfc_sli4_async_event_proc(struct lpfc_hba *phba)
3636 {
3637         struct lpfc_cq_event *cq_event;
3638
3639         /* First, declare the async event has been handled */
3640         spin_lock_irq(&phba->hbalock);
3641         phba->hba_flag &= ~ASYNC_EVENT;
3642         spin_unlock_irq(&phba->hbalock);
3643         /* Now, handle all the async events */
3644         while (!list_empty(&phba->sli4_hba.sp_asynce_work_queue)) {
3645                 /* Get the first event from the head of the event queue */
3646                 spin_lock_irq(&phba->hbalock);
3647                 list_remove_head(&phba->sli4_hba.sp_asynce_work_queue,
3648                                  cq_event, struct lpfc_cq_event, list);
3649                 spin_unlock_irq(&phba->hbalock);
3650                 /* Process the asynchronous event */
3651                 switch (bf_get(lpfc_trailer_code, &cq_event->cqe.mcqe_cmpl)) {
3652                 case LPFC_TRAILER_CODE_LINK:
3653                 case LPFC_TRAILER_CODE_FC:
3654                         lpfc_sli4_async_link_evt(phba,
3655                                                  &cq_event->cqe.acqe_link);
3656                         break;
3657                 case LPFC_TRAILER_CODE_FCOE:
3658                         lpfc_sli4_async_fip_evt(phba,
3659                                                 &cq_event->cqe.acqe_fcoe);
3660                         break;
3661                 case LPFC_TRAILER_CODE_DCBX:
3662                         lpfc_sli4_async_dcbx_evt(phba,
3663                                                  &cq_event->cqe.acqe_dcbx);
3664                         break;
3665                 case LPFC_TRAILER_CODE_GRP5:
3666                         lpfc_sli4_async_grp5_evt(phba,
3667                                                  &cq_event->cqe.acqe_grp5);
3668                         break;
3669                 default:
3670                         lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3671                                         "1804 Invalid asynchrous event code: "
3672                                         "x%x\n", bf_get(lpfc_trailer_code,
3673                                         &cq_event->cqe.mcqe_cmpl));
3674                         break;
3675                 }
3676                 /* Free the completion event processed to the free pool */
3677                 lpfc_sli4_cq_event_release(phba, cq_event);
3678         }
3679 }
3680
3681 /**
3682  * lpfc_sli4_fcf_redisc_event_proc - Process fcf table rediscovery event
3683  * @phba: pointer to lpfc hba data structure.
3684  *
3685  * This routine is invoked by the worker thread to process FCF table
3686  * rediscovery pending completion event.
3687  **/
3688 void lpfc_sli4_fcf_redisc_event_proc(struct lpfc_hba *phba)
3689 {
3690         int rc;
3691
3692         spin_lock_irq(&phba->hbalock);
3693         /* Clear FCF rediscovery timeout event */
3694         phba->fcf.fcf_flag &= ~FCF_REDISC_EVT;
3695         /* Clear driver fast failover FCF record flag */
3696         phba->fcf.failover_rec.flag = 0;
3697         /* Set state for FCF fast failover */
3698         phba->fcf.fcf_flag |= FCF_REDISC_FOV;
3699         spin_unlock_irq(&phba->hbalock);
3700
3701         /* Scan FCF table from the first entry to re-discover SAN */
3702         lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
3703                         "2777 Start post-quiescent FCF table scan\n");
3704         rc = lpfc_sli4_fcf_scan_read_fcf_rec(phba, LPFC_FCOE_FCF_GET_FIRST);
3705         if (rc)
3706                 lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_DISCOVERY,
3707                                 "2747 Issue FCF scan read FCF mailbox "
3708                                 "command failed 0x%x\n", rc);
3709 }
3710
3711 /**
3712  * lpfc_api_table_setup - Set up per hba pci-device group func api jump table
3713  * @phba: pointer to lpfc hba data structure.
3714  * @dev_grp: The HBA PCI-Device group number.
3715  *
3716  * This routine is invoked to set up the per HBA PCI-Device group function
3717  * API jump table entries.
3718  *
3719  * Return: 0 if success, otherwise -ENODEV
3720  **/
3721 int
3722 lpfc_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
3723 {
3724         int rc;
3725
3726         /* Set up lpfc PCI-device group */
3727         phba->pci_dev_grp = dev_grp;
3728
3729         /* The LPFC_PCI_DEV_OC uses SLI4 */
3730         if (dev_grp == LPFC_PCI_DEV_OC)
3731                 phba->sli_rev = LPFC_SLI_REV4;
3732
3733         /* Set up device INIT API function jump table */
3734         rc = lpfc_init_api_table_setup(phba, dev_grp);
3735         if (rc)
3736                 return -ENODEV;
3737         /* Set up SCSI API function jump table */
3738         rc = lpfc_scsi_api_table_setup(phba, dev_grp);
3739         if (rc)
3740                 return -ENODEV;
3741         /* Set up SLI API function jump table */
3742         rc = lpfc_sli_api_table_setup(phba, dev_grp);
3743         if (rc)
3744                 return -ENODEV;
3745         /* Set up MBOX API function jump table */
3746         rc = lpfc_mbox_api_table_setup(phba, dev_grp);
3747         if (rc)
3748                 return -ENODEV;
3749
3750         return 0;
3751 }
3752
3753 /**
3754  * lpfc_log_intr_mode - Log the active interrupt mode
3755  * @phba: pointer to lpfc hba data structure.
3756  * @intr_mode: active interrupt mode adopted.
3757  *
3758  * This routine it invoked to log the currently used active interrupt mode
3759  * to the device.
3760  **/
3761 static void lpfc_log_intr_mode(struct lpfc_hba *phba, uint32_t intr_mode)
3762 {
3763         switch (intr_mode) {
3764         case 0:
3765                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3766                                 "0470 Enable INTx interrupt mode.\n");
3767                 break;
3768         case 1:
3769                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3770                                 "0481 Enabled MSI interrupt mode.\n");
3771                 break;
3772         case 2:
3773                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3774                                 "0480 Enabled MSI-X interrupt mode.\n");
3775                 break;
3776         default:
3777                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
3778                                 "0482 Illegal interrupt mode.\n");
3779                 break;
3780         }
3781         return;
3782 }
3783
3784 /**
3785  * lpfc_enable_pci_dev - Enable a generic PCI device.
3786  * @phba: pointer to lpfc hba data structure.
3787  *
3788  * This routine is invoked to enable the PCI device that is common to all
3789  * PCI devices.
3790  *
3791  * Return codes
3792  *      0 - successful
3793  *      other values - error
3794  **/
3795 static int
3796 lpfc_enable_pci_dev(struct lpfc_hba *phba)
3797 {
3798         struct pci_dev *pdev;
3799         int bars;
3800
3801         /* Obtain PCI device reference */
3802         if (!phba->pcidev)
3803                 goto out_error;
3804         else
3805                 pdev = phba->pcidev;
3806         /* Select PCI BARs */
3807         bars = pci_select_bars(pdev, IORESOURCE_MEM);
3808         /* Enable PCI device */
3809         if (pci_enable_device_mem(pdev))
3810                 goto out_error;
3811         /* Request PCI resource for the device */
3812         if (pci_request_selected_regions(pdev, bars, LPFC_DRIVER_NAME))
3813                 goto out_disable_device;
3814         /* Set up device as PCI master and save state for EEH */
3815         pci_set_master(pdev);
3816         pci_try_set_mwi(pdev);
3817         pci_save_state(pdev);
3818
3819         return 0;
3820
3821 out_disable_device:
3822         pci_disable_device(pdev);
3823 out_error:
3824         return -ENODEV;
3825 }
3826
3827 /**
3828  * lpfc_disable_pci_dev - Disable a generic PCI device.
3829  * @phba: pointer to lpfc hba data structure.
3830  *
3831  * This routine is invoked to disable the PCI device that is common to all
3832  * PCI devices.
3833  **/
3834 static void
3835 lpfc_disable_pci_dev(struct lpfc_hba *phba)
3836 {
3837         struct pci_dev *pdev;
3838         int bars;
3839
3840         /* Obtain PCI device reference */
3841         if (!phba->pcidev)
3842                 return;
3843         else
3844                 pdev = phba->pcidev;
3845         /* Select PCI BARs */
3846         bars = pci_select_bars(pdev, IORESOURCE_MEM);
3847         /* Release PCI resource and disable PCI device */
3848         pci_release_selected_regions(pdev, bars);
3849         pci_disable_device(pdev);
3850         /* Null out PCI private reference to driver */
3851         pci_set_drvdata(pdev, NULL);
3852
3853         return;
3854 }
3855
3856 /**
3857  * lpfc_reset_hba - Reset a hba
3858  * @phba: pointer to lpfc hba data structure.
3859  *
3860  * This routine is invoked to reset a hba device. It brings the HBA
3861  * offline, performs a board restart, and then brings the board back
3862  * online. The lpfc_offline calls lpfc_sli_hba_down which will clean up
3863  * on outstanding mailbox commands.
3864  **/
3865 void
3866 lpfc_reset_hba(struct lpfc_hba *phba)
3867 {
3868         /* If resets are disabled then set error state and return. */
3869         if (!phba->cfg_enable_hba_reset) {
3870                 phba->link_state = LPFC_HBA_ERROR;
3871                 return;
3872         }
3873         lpfc_offline_prep(phba);
3874         lpfc_offline(phba);
3875         lpfc_sli_brdrestart(phba);
3876         lpfc_online(phba);
3877         lpfc_unblock_mgmt_io(phba);
3878 }
3879
3880 /**
3881  * lpfc_sli_driver_resource_setup - Setup driver internal resources for SLI3 dev.
3882  * @phba: pointer to lpfc hba data structure.
3883  *
3884  * This routine is invoked to set up the driver internal resources specific to
3885  * support the SLI-3 HBA device it attached to.
3886  *
3887  * Return codes
3888  *      0 - successful
3889  *      other values - error
3890  **/
3891 static int
3892 lpfc_sli_driver_resource_setup(struct lpfc_hba *phba)
3893 {
3894         struct lpfc_sli *psli;
3895
3896         /*
3897          * Initialize timers used by driver
3898          */
3899
3900         /* Heartbeat timer */
3901         init_timer(&phba->hb_tmofunc);
3902         phba->hb_tmofunc.function = lpfc_hb_timeout;
3903         phba->hb_tmofunc.data = (unsigned long)phba;
3904
3905         psli = &phba->sli;
3906         /* MBOX heartbeat timer */
3907         init_timer(&psli->mbox_tmo);
3908         psli->mbox_tmo.function = lpfc_mbox_timeout;
3909         psli->mbox_tmo.data = (unsigned long) phba;
3910         /* FCP polling mode timer */
3911         init_timer(&phba->fcp_poll_timer);
3912         phba->fcp_poll_timer.function = lpfc_poll_timeout;
3913         phba->fcp_poll_timer.data = (unsigned long) phba;
3914         /* Fabric block timer */
3915         init_timer(&phba->fabric_block_timer);
3916         phba->fabric_block_timer.function = lpfc_fabric_block_timeout;
3917         phba->fabric_block_timer.data = (unsigned long) phba;
3918         /* EA polling mode timer */
3919         init_timer(&phba->eratt_poll);
3920         phba->eratt_poll.function = lpfc_poll_eratt;
3921         phba->eratt_poll.data = (unsigned long) phba;
3922
3923         /* Host attention work mask setup */
3924         phba->work_ha_mask = (HA_ERATT | HA_MBATT | HA_LATT);
3925         phba->work_ha_mask |= (HA_RXMASK << (LPFC_ELS_RING * 4));
3926
3927         /* Get all the module params for configuring this host */
3928         lpfc_get_cfgparam(phba);
3929         if (phba->pcidev->device == PCI_DEVICE_ID_HORNET) {
3930                 phba->menlo_flag |= HBA_MENLO_SUPPORT;
3931                 /* check for menlo minimum sg count */
3932                 if (phba->cfg_sg_seg_cnt < LPFC_DEFAULT_MENLO_SG_SEG_CNT)
3933                         phba->cfg_sg_seg_cnt = LPFC_DEFAULT_MENLO_SG_SEG_CNT;
3934         }
3935
3936         /*
3937          * Since the sg_tablesize is module parameter, the sg_dma_buf_size
3938          * used to create the sg_dma_buf_pool must be dynamically calculated.
3939          * 2 segments are added since the IOCB needs a command and response bde.
3940          */
3941         phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd) +
3942                 sizeof(struct fcp_rsp) +
3943                         ((phba->cfg_sg_seg_cnt + 2) * sizeof(struct ulp_bde64));
3944
3945         if (phba->cfg_enable_bg) {
3946                 phba->cfg_sg_seg_cnt = LPFC_MAX_SG_SEG_CNT;
3947                 phba->cfg_sg_dma_buf_size +=
3948                         phba->cfg_prot_sg_seg_cnt * sizeof(struct ulp_bde64);
3949         }
3950
3951         /* Also reinitialize the host templates with new values. */
3952         lpfc_vport_template.sg_tablesize = phba->cfg_sg_seg_cnt;
3953         lpfc_template.sg_tablesize = phba->cfg_sg_seg_cnt;
3954
3955         phba->max_vpi = LPFC_MAX_VPI;
3956         /* This will be set to correct value after config_port mbox */
3957         phba->max_vports = 0;
3958
3959         /*
3960          * Initialize the SLI Layer to run with lpfc HBAs.
3961          */
3962         lpfc_sli_setup(phba);
3963         lpfc_sli_queue_setup(phba);
3964
3965         /* Allocate device driver memory */
3966         if (lpfc_mem_alloc(phba, BPL_ALIGN_SZ))
3967                 return -ENOMEM;
3968
3969         return 0;
3970 }
3971
3972 /**
3973  * lpfc_sli_driver_resource_unset - Unset drvr internal resources for SLI3 dev
3974  * @phba: pointer to lpfc hba data structure.
3975  *
3976  * This routine is invoked to unset the driver internal resources set up
3977  * specific for supporting the SLI-3 HBA device it attached to.
3978  **/
3979 static void
3980 lpfc_sli_driver_resource_unset(struct lpfc_hba *phba)
3981 {
3982         /* Free device driver memory allocated */
3983         lpfc_mem_free_all(phba);
3984
3985         return;
3986 }
3987
3988 /**
3989  * lpfc_sli4_driver_resource_setup - Setup drvr internal resources for SLI4 dev
3990  * @phba: pointer to lpfc hba data structure.
3991  *
3992  * This routine is invoked to set up the driver internal resources specific to
3993  * support the SLI-4 HBA device it attached to.
3994  *
3995  * Return codes
3996  *      0 - successful
3997  *      other values - error
3998  **/
3999 static int
4000 lpfc_sli4_driver_resource_setup(struct lpfc_hba *phba)
4001 {
4002         struct lpfc_sli *psli;
4003         LPFC_MBOXQ_t *mboxq;
4004         int rc, i, hbq_count, buf_size, dma_buf_size, max_buf_size;
4005         uint8_t pn_page[LPFC_MAX_SUPPORTED_PAGES] = {0};
4006         struct lpfc_mqe *mqe;
4007         int longs, sli_family;
4008
4009         /* Before proceed, wait for POST done and device ready */
4010         rc = lpfc_sli4_post_status_check(phba);
4011         if (rc)
4012                 return -ENODEV;
4013
4014         /*
4015          * Initialize timers used by driver
4016          */
4017
4018         /* Heartbeat timer */
4019         init_timer(&phba->hb_tmofunc);
4020         phba->hb_tmofunc.function = lpfc_hb_timeout;
4021         phba->hb_tmofunc.data = (unsigned long)phba;
4022         init_timer(&phba->rrq_tmr);
4023         phba->rrq_tmr.function = lpfc_rrq_timeout;
4024         phba->rrq_tmr.data = (unsigned long)phba;
4025
4026         psli = &phba->sli;
4027         /* MBOX heartbeat timer */
4028         init_timer(&psli->mbox_tmo);
4029         psli->mbox_tmo.function = lpfc_mbox_timeout;
4030         psli->mbox_tmo.data = (unsigned long) phba;
4031         /* Fabric block timer */
4032         init_timer(&phba->fabric_block_timer);
4033         phba->fabric_block_timer.function = lpfc_fabric_block_timeout;
4034         phba->fabric_block_timer.data = (unsigned long) phba;
4035         /* EA polling mode timer */
4036         init_timer(&phba->eratt_poll);
4037         phba->eratt_poll.function = lpfc_poll_eratt;
4038         phba->eratt_poll.data = (unsigned long) phba;
4039         /* FCF rediscover timer */
4040         init_timer(&phba->fcf.redisc_wait);
4041         phba->fcf.redisc_wait.function = lpfc_sli4_fcf_redisc_wait_tmo;
4042         phba->fcf.redisc_wait.data = (unsigned long)phba;
4043
4044         /*
4045          * We need to do a READ_CONFIG mailbox command here before
4046          * calling lpfc_get_cfgparam. For VFs this will report the
4047          * MAX_XRI, MAX_VPI, MAX_RPI, MAX_IOCB, and MAX_VFI settings.
4048          * All of the resources allocated
4049          * for this Port are tied to these values.
4050          */
4051         /* Get all the module params for configuring this host */
4052         lpfc_get_cfgparam(phba);
4053         phba->max_vpi = LPFC_MAX_VPI;
4054         /* This will be set to correct value after the read_config mbox */
4055         phba->max_vports = 0;
4056
4057         /* Program the default value of vlan_id and fc_map */
4058         phba->valid_vlan = 0;
4059         phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
4060         phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
4061         phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
4062
4063         /*
4064          * Since the sg_tablesize is module parameter, the sg_dma_buf_size
4065          * used to create the sg_dma_buf_pool must be dynamically calculated.
4066          * 2 segments are added since the IOCB needs a command and response bde.
4067          * To insure that the scsi sgl does not cross a 4k page boundary only
4068          * sgl sizes of must be a power of 2.
4069          */
4070         buf_size = (sizeof(struct fcp_cmnd) + sizeof(struct fcp_rsp) +
4071                     ((phba->cfg_sg_seg_cnt + 2) * sizeof(struct sli4_sge)));
4072
4073         sli_family = bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf);
4074         max_buf_size = LPFC_SLI4_MAX_BUF_SIZE;
4075         switch (sli_family) {
4076         case LPFC_SLI_INTF_FAMILY_BE2:
4077         case LPFC_SLI_INTF_FAMILY_BE3:
4078                 /* There is a single hint for BE - 2 pages per BPL. */
4079                 if (bf_get(lpfc_sli_intf_sli_hint1, &phba->sli4_hba.sli_intf) ==
4080                     LPFC_SLI_INTF_SLI_HINT1_1)
4081                         max_buf_size = LPFC_SLI4_FL1_MAX_BUF_SIZE;
4082                 break;
4083         case LPFC_SLI_INTF_FAMILY_LNCR_A0:
4084         case LPFC_SLI_INTF_FAMILY_LNCR_B0:
4085         default:
4086                 break;
4087         }
4088         for (dma_buf_size = LPFC_SLI4_MIN_BUF_SIZE;
4089              dma_buf_size < max_buf_size && buf_size > dma_buf_size;
4090              dma_buf_size = dma_buf_size << 1)
4091                 ;
4092         if (dma_buf_size == max_buf_size)
4093                 phba->cfg_sg_seg_cnt = (dma_buf_size -
4094                         sizeof(struct fcp_cmnd) - sizeof(struct fcp_rsp) -
4095                         (2 * sizeof(struct sli4_sge))) /
4096                                 sizeof(struct sli4_sge);
4097         phba->cfg_sg_dma_buf_size = dma_buf_size;
4098
4099         /* Initialize buffer queue management fields */
4100         hbq_count = lpfc_sli_hbq_count();
4101         for (i = 0; i < hbq_count; ++i)
4102                 INIT_LIST_HEAD(&phba->hbqs[i].hbq_buffer_list);
4103         INIT_LIST_HEAD(&phba->rb_pend_list);
4104         phba->hbqs[LPFC_ELS_HBQ].hbq_alloc_buffer = lpfc_sli4_rb_alloc;
4105         phba->hbqs[LPFC_ELS_HBQ].hbq_free_buffer = lpfc_sli4_rb_free;
4106
4107         /*
4108          * Initialize the SLI Layer to run with lpfc SLI4 HBAs.
4109          */
4110         /* Initialize the Abort scsi buffer list used by driver */
4111         spin_lock_init(&phba->sli4_hba.abts_scsi_buf_list_lock);
4112         INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_scsi_buf_list);
4113         /* This abort list used by worker thread */
4114         spin_lock_init(&phba->sli4_hba.abts_sgl_list_lock);
4115
4116         /*
4117          * Initialize dirver internal slow-path work queues
4118          */
4119
4120         /* Driver internel slow-path CQ Event pool */
4121         INIT_LIST_HEAD(&phba->sli4_hba.sp_cqe_event_pool);
4122         /* Response IOCB work queue list */
4123         INIT_LIST_HEAD(&phba->sli4_hba.sp_queue_event);
4124         /* Asynchronous event CQ Event work queue list */
4125         INIT_LIST_HEAD(&phba->sli4_hba.sp_asynce_work_queue);
4126         /* Fast-path XRI aborted CQ Event work queue list */
4127         INIT_LIST_HEAD(&phba->sli4_hba.sp_fcp_xri_aborted_work_queue);
4128         /* Slow-path XRI aborted CQ Event work queue list */
4129         INIT_LIST_HEAD(&phba->sli4_hba.sp_els_xri_aborted_work_queue);
4130         /* Receive queue CQ Event work queue list */
4131         INIT_LIST_HEAD(&phba->sli4_hba.sp_unsol_work_queue);
4132
4133         /* Initialize the driver internal SLI layer lists. */
4134         lpfc_sli_setup(phba);
4135         lpfc_sli_queue_setup(phba);
4136
4137         /* Allocate device driver memory */
4138         rc = lpfc_mem_alloc(phba, SGL_ALIGN_SZ);
4139         if (rc)
4140                 return -ENOMEM;
4141
4142         /* Create the bootstrap mailbox command */
4143         rc = lpfc_create_bootstrap_mbox(phba);
4144         if (unlikely(rc))
4145                 goto out_free_mem;
4146
4147         /* Set up the host's endian order with the device. */
4148         rc = lpfc_setup_endian_order(phba);
4149         if (unlikely(rc))
4150                 goto out_free_bsmbx;
4151
4152         rc = lpfc_sli4_fw_cfg_check(phba);
4153         if (unlikely(rc))
4154                 goto out_free_bsmbx;
4155
4156         /* Set up the hba's configuration parameters. */
4157         rc = lpfc_sli4_read_config(phba);
4158         if (unlikely(rc))
4159                 goto out_free_bsmbx;
4160
4161         /* Perform a function reset */
4162         rc = lpfc_pci_function_reset(phba);
4163         if (unlikely(rc))
4164                 goto out_free_bsmbx;
4165
4166         mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
4167                                                        GFP_KERNEL);
4168         if (!mboxq) {
4169                 rc = -ENOMEM;
4170                 goto out_free_bsmbx;
4171         }
4172
4173         /* Get the Supported Pages. It is always available. */
4174         lpfc_supported_pages(mboxq);
4175         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
4176         if (unlikely(rc)) {
4177                 rc = -EIO;
4178                 mempool_free(mboxq, phba->mbox_mem_pool);
4179                 goto out_free_bsmbx;
4180         }
4181
4182         mqe = &mboxq->u.mqe;
4183         memcpy(&pn_page[0], ((uint8_t *)&mqe->un.supp_pages.word3),
4184                LPFC_MAX_SUPPORTED_PAGES);
4185         for (i = 0; i < LPFC_MAX_SUPPORTED_PAGES; i++) {
4186                 switch (pn_page[i]) {
4187                 case LPFC_SLI4_PARAMETERS:
4188                         phba->sli4_hba.pc_sli4_params.supported = 1;
4189                         break;
4190                 default:
4191                         break;
4192                 }
4193         }
4194
4195         /* Read the port's SLI4 Parameters capabilities if supported. */
4196         if (phba->sli4_hba.pc_sli4_params.supported)
4197                 rc = lpfc_pc_sli4_params_get(phba, mboxq);
4198         mempool_free(mboxq, phba->mbox_mem_pool);
4199         if (rc) {
4200                 rc = -EIO;
4201                 goto out_free_bsmbx;
4202         }
4203         /* Create all the SLI4 queues */
4204         rc = lpfc_sli4_queue_create(phba);
4205         if (rc)
4206                 goto out_free_bsmbx;
4207
4208         /* Create driver internal CQE event pool */
4209         rc = lpfc_sli4_cq_event_pool_create(phba);
4210         if (rc)
4211                 goto out_destroy_queue;
4212
4213         /* Initialize and populate the iocb list per host */
4214         rc = lpfc_init_sgl_list(phba);
4215         if (rc) {
4216                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4217                                 "1400 Failed to initialize sgl list.\n");
4218                 goto out_destroy_cq_event_pool;
4219         }
4220         rc = lpfc_init_active_sgl_array(phba);
4221         if (rc) {
4222                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4223                                 "1430 Failed to initialize sgl list.\n");
4224                 goto out_free_sgl_list;
4225         }
4226
4227         rc = lpfc_sli4_init_rpi_hdrs(phba);
4228         if (rc) {
4229                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4230                                 "1432 Failed to initialize rpi headers.\n");
4231                 goto out_free_active_sgl;
4232         }
4233
4234         /* Allocate eligible FCF bmask memory for FCF roundrobin failover */
4235         longs = (LPFC_SLI4_FCF_TBL_INDX_MAX + BITS_PER_LONG - 1)/BITS_PER_LONG;
4236         phba->fcf.fcf_rr_bmask = kzalloc(longs * sizeof(unsigned long),
4237                                          GFP_KERNEL);
4238         if (!phba->fcf.fcf_rr_bmask) {
4239                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4240                                 "2759 Failed allocate memory for FCF round "
4241                                 "robin failover bmask\n");
4242                 goto out_remove_rpi_hdrs;
4243         }
4244
4245         phba->sli4_hba.fcp_eq_hdl = kzalloc((sizeof(struct lpfc_fcp_eq_hdl) *
4246                                     phba->cfg_fcp_eq_count), GFP_KERNEL);
4247         if (!phba->sli4_hba.fcp_eq_hdl) {
4248                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4249                                 "2572 Failed allocate memory for fast-path "
4250                                 "per-EQ handle array\n");
4251                 goto out_free_fcf_rr_bmask;
4252         }
4253
4254         phba->sli4_hba.msix_entries = kzalloc((sizeof(struct msix_entry) *
4255                                       phba->sli4_hba.cfg_eqn), GFP_KERNEL);
4256         if (!phba->sli4_hba.msix_entries) {
4257                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4258                                 "2573 Failed allocate memory for msi-x "
4259                                 "interrupt vector entries\n");
4260                 goto out_free_fcp_eq_hdl;
4261         }
4262
4263         return rc;
4264
4265 out_free_fcp_eq_hdl:
4266         kfree(phba->sli4_hba.fcp_eq_hdl);
4267 out_free_fcf_rr_bmask:
4268         kfree(phba->fcf.fcf_rr_bmask);
4269 out_remove_rpi_hdrs:
4270         lpfc_sli4_remove_rpi_hdrs(phba);
4271 out_free_active_sgl:
4272         lpfc_free_active_sgl(phba);
4273 out_free_sgl_list:
4274         lpfc_free_sgl_list(phba);
4275 out_destroy_cq_event_pool:
4276         lpfc_sli4_cq_event_pool_destroy(phba);
4277 out_destroy_queue:
4278         lpfc_sli4_queue_destroy(phba);
4279 out_free_bsmbx:
4280         lpfc_destroy_bootstrap_mbox(phba);
4281 out_free_mem:
4282         lpfc_mem_free(phba);
4283         return rc;
4284 }
4285
4286 /**
4287  * lpfc_sli4_driver_resource_unset - Unset drvr internal resources for SLI4 dev
4288  * @phba: pointer to lpfc hba data structure.
4289  *
4290  * This routine is invoked to unset the driver internal resources set up
4291  * specific for supporting the SLI-4 HBA device it attached to.
4292  **/
4293 static void
4294 lpfc_sli4_driver_resource_unset(struct lpfc_hba *phba)
4295 {
4296         struct lpfc_fcf_conn_entry *conn_entry, *next_conn_entry;
4297
4298         /* Free memory allocated for msi-x interrupt vector entries */
4299         kfree(phba->sli4_hba.msix_entries);
4300
4301         /* Free memory allocated for fast-path work queue handles */
4302         kfree(phba->sli4_hba.fcp_eq_hdl);
4303
4304         /* Free the allocated rpi headers. */
4305         lpfc_sli4_remove_rpi_hdrs(phba);
4306         lpfc_sli4_remove_rpis(phba);
4307
4308         /* Free eligible FCF index bmask */
4309         kfree(phba->fcf.fcf_rr_bmask);
4310
4311         /* Free the ELS sgl list */
4312         lpfc_free_active_sgl(phba);
4313         lpfc_free_sgl_list(phba);
4314
4315         /* Free the SCSI sgl management array */
4316         kfree(phba->sli4_hba.lpfc_scsi_psb_array);
4317
4318         /* Free the SLI4 queues */
4319         lpfc_sli4_queue_destroy(phba);
4320
4321         /* Free the completion queue EQ event pool */
4322         lpfc_sli4_cq_event_release_all(phba);
4323         lpfc_sli4_cq_event_pool_destroy(phba);
4324
4325         /* Free the bsmbx region. */
4326         lpfc_destroy_bootstrap_mbox(phba);
4327
4328         /* Free the SLI Layer memory with SLI4 HBAs */
4329         lpfc_mem_free_all(phba);
4330
4331         /* Free the current connect table */
4332         list_for_each_entry_safe(conn_entry, next_conn_entry,
4333                 &phba->fcf_conn_rec_list, list) {
4334                 list_del_init(&conn_entry->list);
4335                 kfree(conn_entry);
4336         }
4337
4338         return;
4339 }
4340
4341 /**
4342  * lpfc_init_api_table_setup - Set up init api fucntion jump table
4343  * @phba: The hba struct for which this call is being executed.
4344  * @dev_grp: The HBA PCI-Device group number.
4345  *
4346  * This routine sets up the device INIT interface API function jump table
4347  * in @phba struct.
4348  *
4349  * Returns: 0 - success, -ENODEV - failure.
4350  **/
4351 int
4352 lpfc_init_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
4353 {
4354         phba->lpfc_hba_init_link = lpfc_hba_init_link;
4355         phba->lpfc_hba_down_link = lpfc_hba_down_link;
4356         switch (dev_grp) {
4357         case LPFC_PCI_DEV_LP:
4358                 phba->lpfc_hba_down_post = lpfc_hba_down_post_s3;
4359                 phba->lpfc_handle_eratt = lpfc_handle_eratt_s3;
4360                 phba->lpfc_stop_port = lpfc_stop_port_s3;
4361                 break;
4362         case LPFC_PCI_DEV_OC:
4363                 phba->lpfc_hba_down_post = lpfc_hba_down_post_s4;
4364                 phba->lpfc_handle_eratt = lpfc_handle_eratt_s4;
4365                 phba->lpfc_stop_port = lpfc_stop_port_s4;
4366                 break;
4367         default:
4368                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4369                                 "1431 Invalid HBA PCI-device group: 0x%x\n",
4370                                 dev_grp);
4371                 return -ENODEV;
4372                 break;
4373         }
4374         return 0;
4375 }
4376
4377 /**
4378  * lpfc_setup_driver_resource_phase1 - Phase1 etup driver internal resources.
4379  * @phba: pointer to lpfc hba data structure.
4380  *
4381  * This routine is invoked to set up the driver internal resources before the
4382  * device specific resource setup to support the HBA device it attached to.
4383  *
4384  * Return codes
4385  *      0 - successful
4386  *      other values - error
4387  **/
4388 static int
4389 lpfc_setup_driver_resource_phase1(struct lpfc_hba *phba)
4390 {
4391         /*
4392          * Driver resources common to all SLI revisions
4393          */
4394         atomic_set(&phba->fast_event_count, 0);
4395         spin_lock_init(&phba->hbalock);
4396
4397         /* Initialize ndlp management spinlock */
4398         spin_lock_init(&phba->ndlp_lock);
4399
4400         INIT_LIST_HEAD(&phba->port_list);
4401         INIT_LIST_HEAD(&phba->work_list);
4402         init_waitqueue_head(&phba->wait_4_mlo_m_q);
4403
4404         /* Initialize the wait queue head for the kernel thread */
4405         init_waitqueue_head(&phba->work_waitq);
4406
4407         /* Initialize the scsi buffer list used by driver for scsi IO */
4408         spin_lock_init(&phba->scsi_buf_list_lock);
4409         INIT_LIST_HEAD(&phba->lpfc_scsi_buf_list);
4410
4411         /* Initialize the fabric iocb list */
4412         INIT_LIST_HEAD(&phba->fabric_iocb_list);
4413
4414         /* Initialize list to save ELS buffers */
4415         INIT_LIST_HEAD(&phba->elsbuf);
4416
4417         /* Initialize FCF connection rec list */
4418         INIT_LIST_HEAD(&phba->fcf_conn_rec_list);
4419
4420         return 0;
4421 }
4422
4423 /**
4424  * lpfc_setup_driver_resource_phase2 - Phase2 setup driver internal resources.
4425  * @phba: pointer to lpfc hba data structure.
4426  *
4427  * This routine is invoked to set up the driver internal resources after the
4428  * device specific resource setup to support the HBA device it attached to.
4429  *
4430  * Return codes
4431  *      0 - successful
4432  *      other values - error
4433  **/
4434 static int
4435 lpfc_setup_driver_resource_phase2(struct lpfc_hba *phba)
4436 {
4437         int error;
4438
4439         /* Startup the kernel thread for this host adapter. */
4440         phba->worker_thread = kthread_run(lpfc_do_work, phba,
4441                                           "lpfc_worker_%d", phba->brd_no);
4442         if (IS_ERR(phba->worker_thread)) {
4443                 error = PTR_ERR(phba->worker_thread);
4444                 return error;
4445         }
4446
4447         return 0;
4448 }
4449
4450 /**
4451  * lpfc_unset_driver_resource_phase2 - Phase2 unset driver internal resources.
4452  * @phba: pointer to lpfc hba data structure.
4453  *
4454  * This routine is invoked to unset the driver internal resources set up after
4455  * the device specific resource setup for supporting the HBA device it
4456  * attached to.
4457  **/
4458 static void
4459 lpfc_unset_driver_resource_phase2(struct lpfc_hba *phba)
4460 {
4461         /* Stop kernel worker thread */
4462         kthread_stop(phba->worker_thread);
4463 }
4464
4465 /**
4466  * lpfc_free_iocb_list - Free iocb list.
4467  * @phba: pointer to lpfc hba data structure.
4468  *
4469  * This routine is invoked to free the driver's IOCB list and memory.
4470  **/
4471 static void
4472 lpfc_free_iocb_list(struct lpfc_hba *phba)
4473 {
4474         struct lpfc_iocbq *iocbq_entry = NULL, *iocbq_next = NULL;
4475
4476         spin_lock_irq(&phba->hbalock);
4477         list_for_each_entry_safe(iocbq_entry, iocbq_next,
4478                                  &phba->lpfc_iocb_list, list) {
4479                 list_del(&iocbq_entry->list);
4480                 kfree(iocbq_entry);
4481                 phba->total_iocbq_bufs--;
4482         }
4483         spin_unlock_irq(&phba->hbalock);
4484
4485         return;
4486 }
4487
4488 /**
4489  * lpfc_init_iocb_list - Allocate and initialize iocb list.
4490  * @phba: pointer to lpfc hba data structure.
4491  *
4492  * This routine is invoked to allocate and initizlize the driver's IOCB
4493  * list and set up the IOCB tag array accordingly.
4494  *
4495  * Return codes
4496  *      0 - successful
4497  *      other values - error
4498  **/
4499 static int
4500 lpfc_init_iocb_list(struct lpfc_hba *phba, int iocb_count)
4501 {
4502         struct lpfc_iocbq *iocbq_entry = NULL;
4503         uint16_t iotag;
4504         int i;
4505
4506         /* Initialize and populate the iocb list per host.  */
4507         INIT_LIST_HEAD(&phba->lpfc_iocb_list);
4508         for (i = 0; i < iocb_count; i++) {
4509                 iocbq_entry = kzalloc(sizeof(struct lpfc_iocbq), GFP_KERNEL);
4510                 if (iocbq_entry == NULL) {
4511                         printk(KERN_ERR "%s: only allocated %d iocbs of "
4512                                 "expected %d count. Unloading driver.\n",
4513                                 __func__, i, LPFC_IOCB_LIST_CNT);
4514                         goto out_free_iocbq;
4515                 }
4516
4517                 iotag = lpfc_sli_next_iotag(phba, iocbq_entry);
4518                 if (iotag == 0) {
4519                         kfree(iocbq_entry);
4520                         printk(KERN_ERR "%s: failed to allocate IOTAG. "
4521                                 "Unloading driver.\n", __func__);
4522                         goto out_free_iocbq;
4523                 }
4524                 iocbq_entry->sli4_xritag = NO_XRI;
4525
4526                 spin_lock_irq(&phba->hbalock);
4527                 list_add(&iocbq_entry->list, &phba->lpfc_iocb_list);
4528                 phba->total_iocbq_bufs++;
4529                 spin_unlock_irq(&phba->hbalock);
4530         }
4531
4532         return 0;
4533
4534 out_free_iocbq:
4535         lpfc_free_iocb_list(phba);
4536
4537         return -ENOMEM;
4538 }
4539
4540 /**
4541  * lpfc_free_sgl_list - Free sgl list.
4542  * @phba: pointer to lpfc hba data structure.
4543  *
4544  * This routine is invoked to free the driver's sgl list and memory.
4545  **/
4546 static void
4547 lpfc_free_sgl_list(struct lpfc_hba *phba)
4548 {
4549         struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
4550         LIST_HEAD(sglq_list);
4551
4552         spin_lock_irq(&phba->hbalock);
4553         list_splice_init(&phba->sli4_hba.lpfc_sgl_list, &sglq_list);
4554         spin_unlock_irq(&phba->hbalock);
4555
4556         list_for_each_entry_safe(sglq_entry, sglq_next,
4557                                  &sglq_list, list) {
4558                 list_del(&sglq_entry->list);
4559                 lpfc_mbuf_free(phba, sglq_entry->virt, sglq_entry->phys);
4560                 kfree(sglq_entry);
4561                 phba->sli4_hba.total_sglq_bufs--;
4562         }
4563         kfree(phba->sli4_hba.lpfc_els_sgl_array);
4564 }
4565
4566 /**
4567  * lpfc_init_active_sgl_array - Allocate the buf to track active ELS XRIs.
4568  * @phba: pointer to lpfc hba data structure.
4569  *
4570  * This routine is invoked to allocate the driver's active sgl memory.
4571  * This array will hold the sglq_entry's for active IOs.
4572  **/
4573 static int
4574 lpfc_init_active_sgl_array(struct lpfc_hba *phba)
4575 {
4576         int size;
4577         size = sizeof(struct lpfc_sglq *);
4578         size *= phba->sli4_hba.max_cfg_param.max_xri;
4579
4580         phba->sli4_hba.lpfc_sglq_active_list =
4581                 kzalloc(size, GFP_KERNEL);
4582         if (!phba->sli4_hba.lpfc_sglq_active_list)
4583                 return -ENOMEM;
4584         return 0;
4585 }
4586
4587 /**
4588  * lpfc_free_active_sgl - Free the buf that tracks active ELS XRIs.
4589  * @phba: pointer to lpfc hba data structure.
4590  *
4591  * This routine is invoked to walk through the array of active sglq entries
4592  * and free all of the resources.
4593  * This is just a place holder for now.
4594  **/
4595 static void
4596 lpfc_free_active_sgl(struct lpfc_hba *phba)
4597 {
4598         kfree(phba->sli4_hba.lpfc_sglq_active_list);
4599 }
4600
4601 /**
4602  * lpfc_init_sgl_list - Allocate and initialize sgl list.
4603  * @phba: pointer to lpfc hba data structure.
4604  *
4605  * This routine is invoked to allocate and initizlize the driver's sgl
4606  * list and set up the sgl xritag tag array accordingly.
4607  *
4608  * Return codes
4609  *      0 - successful
4610  *      other values - error
4611  **/
4612 static int
4613 lpfc_init_sgl_list(struct lpfc_hba *phba)
4614 {
4615         struct lpfc_sglq *sglq_entry = NULL;
4616         int i;
4617         int els_xri_cnt;
4618
4619         els_xri_cnt = lpfc_sli4_get_els_iocb_cnt(phba);
4620         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4621                                 "2400 lpfc_init_sgl_list els %d.\n",
4622                                 els_xri_cnt);
4623         /* Initialize and populate the sglq list per host/VF. */
4624         INIT_LIST_HEAD(&phba->sli4_hba.lpfc_sgl_list);
4625         INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_els_sgl_list);
4626
4627         /* Sanity check on XRI management */
4628         if (phba->sli4_hba.max_cfg_param.max_xri <= els_xri_cnt) {
4629                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
4630                                 "2562 No room left for SCSI XRI allocation: "
4631                                 "max_xri=%d, els_xri=%d\n",
4632                                 phba->sli4_hba.max_cfg_param.max_xri,
4633                                 els_xri_cnt);
4634                 return -ENOMEM;
4635         }
4636
4637         /* Allocate memory for the ELS XRI management array */
4638         phba->sli4_hba.lpfc_els_sgl_array =
4639                         kzalloc((sizeof(struct lpfc_sglq *) * els_xri_cnt),
4640                         GFP_KERNEL);
4641
4642         if (!phba->sli4_hba.lpfc_els_sgl_array) {
4643                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
4644                                 "2401 Failed to allocate memory for ELS "
4645                                 "XRI management array of size %d.\n",
4646                                 els_xri_cnt);
4647                 return -ENOMEM;
4648         }
4649
4650         /* Keep the SCSI XRI into the XRI management array */
4651         phba->sli4_hba.scsi_xri_max =
4652                         phba->sli4_hba.max_cfg_param.max_xri - els_xri_cnt;
4653         phba->sli4_hba.scsi_xri_cnt = 0;
4654
4655         phba->sli4_hba.lpfc_scsi_psb_array =
4656                         kzalloc((sizeof(struct lpfc_scsi_buf *) *
4657                         phba->sli4_hba.scsi_xri_max), GFP_KERNEL);
4658
4659         if (!phba->sli4_hba.lpfc_scsi_psb_array) {
4660                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
4661                                 "2563 Failed to allocate memory for SCSI "
4662                                 "XRI management array of size %d.\n",
4663                                 phba->sli4_hba.scsi_xri_max);
4664                 kfree(phba->sli4_hba.lpfc_els_sgl_array);
4665                 return -ENOMEM;
4666         }
4667
4668         for (i = 0; i < els_xri_cnt; i++) {
4669                 sglq_entry = kzalloc(sizeof(struct lpfc_sglq), GFP_KERNEL);
4670                 if (sglq_entry == NULL) {
4671                         printk(KERN_ERR "%s: only allocated %d sgls of "
4672                                 "expected %d count. Unloading driver.\n",
4673                                 __func__, i, els_xri_cnt);
4674                         goto out_free_mem;
4675                 }
4676
4677                 sglq_entry->sli4_xritag = lpfc_sli4_next_xritag(phba);
4678                 if (sglq_entry->sli4_xritag == NO_XRI) {
4679                         kfree(sglq_entry);
4680                         printk(KERN_ERR "%s: failed to allocate XRI.\n"
4681                                 "Unloading driver.\n", __func__);
4682                         goto out_free_mem;
4683                 }
4684                 sglq_entry->buff_type = GEN_BUFF_TYPE;
4685                 sglq_entry->virt = lpfc_mbuf_alloc(phba, 0, &sglq_entry->phys);
4686                 if (sglq_entry->virt == NULL) {
4687                         kfree(sglq_entry);
4688                         printk(KERN_ERR "%s: failed to allocate mbuf.\n"
4689                                 "Unloading driver.\n", __func__);
4690                         goto out_free_mem;
4691                 }
4692                 sglq_entry->sgl = sglq_entry->virt;
4693                 memset(sglq_entry->sgl, 0, LPFC_BPL_SIZE);
4694
4695                 /* The list order is used by later block SGL registraton */
4696                 spin_lock_irq(&phba->hbalock);
4697                 sglq_entry->state = SGL_FREED;
4698                 list_add_tail(&sglq_entry->list, &phba->sli4_hba.lpfc_sgl_list);
4699                 phba->sli4_hba.lpfc_els_sgl_array[i] = sglq_entry;
4700                 phba->sli4_hba.total_sglq_bufs++;
4701                 spin_unlock_irq(&phba->hbalock);
4702         }
4703         return 0;
4704
4705 out_free_mem:
4706         kfree(phba->sli4_hba.lpfc_scsi_psb_array);
4707         lpfc_free_sgl_list(phba);
4708         return -ENOMEM;
4709 }
4710
4711 /**
4712  * lpfc_sli4_init_rpi_hdrs - Post the rpi header memory region to the port
4713  * @phba: pointer to lpfc hba data structure.
4714  *
4715  * This routine is invoked to post rpi header templates to the
4716  * HBA consistent with the SLI-4 interface spec.  This routine
4717  * posts a PAGE_SIZE memory region to the port to hold up to
4718  * PAGE_SIZE modulo 64 rpi context headers.
4719  * No locks are held here because this is an initialization routine
4720  * called only from probe or lpfc_online when interrupts are not
4721  * enabled and the driver is reinitializing the device.
4722  *
4723  * Return codes
4724  *      0 - successful
4725  *      -ENOMEM - No availble memory
4726  *      -EIO - The mailbox failed to complete successfully.
4727  **/
4728 int
4729 lpfc_sli4_init_rpi_hdrs(struct lpfc_hba *phba)
4730 {
4731         int rc = 0;
4732         int longs;
4733         uint16_t rpi_count;
4734         struct lpfc_rpi_hdr *rpi_hdr;
4735
4736         INIT_LIST_HEAD(&phba->sli4_hba.lpfc_rpi_hdr_list);
4737
4738         /*
4739          * Provision an rpi bitmask range for discovery. The total count
4740          * is the difference between max and base + 1.
4741          */
4742         rpi_count = phba->sli4_hba.max_cfg_param.rpi_base +
4743                     phba->sli4_hba.max_cfg_param.max_rpi - 1;
4744
4745         longs = ((rpi_count) + BITS_PER_LONG - 1) / BITS_PER_LONG;
4746         phba->sli4_hba.rpi_bmask = kzalloc(longs * sizeof(unsigned long),
4747                                            GFP_KERNEL);
4748         if (!phba->sli4_hba.rpi_bmask)
4749                 return -ENOMEM;
4750
4751         rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
4752         if (!rpi_hdr) {
4753                 lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
4754                                 "0391 Error during rpi post operation\n");
4755                 lpfc_sli4_remove_rpis(phba);
4756                 rc = -ENODEV;
4757         }
4758
4759         return rc;
4760 }
4761
4762 /**
4763  * lpfc_sli4_create_rpi_hdr - Allocate an rpi header memory region
4764  * @phba: pointer to lpfc hba data structure.
4765  *
4766  * This routine is invoked to allocate a single 4KB memory region to
4767  * support rpis and stores them in the phba.  This single region
4768  * provides support for up to 64 rpis.  The region is used globally
4769  * by the device.
4770  *
4771  * Returns:
4772  *   A valid rpi hdr on success.
4773  *   A NULL pointer on any failure.
4774  **/
4775 struct lpfc_rpi_hdr *
4776 lpfc_sli4_create_rpi_hdr(struct lpfc_hba *phba)
4777 {
4778         uint16_t rpi_limit, curr_rpi_range;
4779         struct lpfc_dmabuf *dmabuf;
4780         struct lpfc_rpi_hdr *rpi_hdr;
4781
4782         rpi_limit = phba->sli4_hba.max_cfg_param.rpi_base +
4783                     phba->sli4_hba.max_cfg_param.max_rpi - 1;
4784
4785         spin_lock_irq(&phba->hbalock);
4786         curr_rpi_range = phba->sli4_hba.next_rpi;
4787         spin_unlock_irq(&phba->hbalock);
4788
4789         /*
4790          * The port has a limited number of rpis. The increment here
4791          * is LPFC_RPI_HDR_COUNT - 1 to account for the starting value
4792          * and to allow the full max_rpi range per port.
4793          */
4794         if ((curr_rpi_range + (LPFC_RPI_HDR_COUNT - 1)) > rpi_limit)
4795                 return NULL;
4796
4797         /*
4798          * First allocate the protocol header region for the port.  The
4799          * port expects a 4KB DMA-mapped memory region that is 4K aligned.
4800          */
4801         dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
4802         if (!dmabuf)
4803                 return NULL;
4804
4805         dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
4806                                           LPFC_HDR_TEMPLATE_SIZE,
4807                                           &dmabuf->phys,
4808                                           GFP_KERNEL);
4809         if (!dmabuf->virt) {
4810                 rpi_hdr = NULL;
4811                 goto err_free_dmabuf;
4812         }
4813
4814         memset(dmabuf->virt, 0, LPFC_HDR_TEMPLATE_SIZE);
4815         if (!IS_ALIGNED(dmabuf->phys, LPFC_HDR_TEMPLATE_SIZE)) {
4816                 rpi_hdr = NULL;
4817                 goto err_free_coherent;
4818         }
4819
4820         /* Save the rpi header data for cleanup later. */
4821         rpi_hdr = kzalloc(sizeof(struct lpfc_rpi_hdr), GFP_KERNEL);
4822         if (!rpi_hdr)
4823                 goto err_free_coherent;
4824
4825         rpi_hdr->dmabuf = dmabuf;
4826         rpi_hdr->len = LPFC_HDR_TEMPLATE_SIZE;
4827         rpi_hdr->page_count = 1;
4828         spin_lock_irq(&phba->hbalock);
4829         rpi_hdr->start_rpi = phba->sli4_hba.next_rpi;
4830         list_add_tail(&rpi_hdr->list, &phba->sli4_hba.lpfc_rpi_hdr_list);
4831
4832         /*
4833          * The next_rpi stores the next module-64 rpi value to post
4834          * in any subsequent rpi memory region postings.
4835          */
4836         phba->sli4_hba.next_rpi += LPFC_RPI_HDR_COUNT;
4837         spin_unlock_irq(&phba->hbalock);
4838         return rpi_hdr;
4839
4840  err_free_coherent:
4841         dma_free_coherent(&phba->pcidev->dev, LPFC_HDR_TEMPLATE_SIZE,
4842                           dmabuf->virt, dmabuf->phys);
4843  err_free_dmabuf:
4844         kfree(dmabuf);
4845         return NULL;
4846 }
4847
4848 /**
4849  * lpfc_sli4_remove_rpi_hdrs - Remove all rpi header memory regions
4850  * @phba: pointer to lpfc hba data structure.
4851  *
4852  * This routine is invoked to remove all memory resources allocated
4853  * to support rpis. This routine presumes the caller has released all
4854  * rpis consumed by fabric or port logins and is prepared to have
4855  * the header pages removed.
4856  **/
4857 void
4858 lpfc_sli4_remove_rpi_hdrs(struct lpfc_hba *phba)
4859 {
4860         struct lpfc_rpi_hdr *rpi_hdr, *next_rpi_hdr;
4861
4862         list_for_each_entry_safe(rpi_hdr, next_rpi_hdr,
4863                                  &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
4864                 list_del(&rpi_hdr->list);
4865                 dma_free_coherent(&phba->pcidev->dev, rpi_hdr->len,
4866                                   rpi_hdr->dmabuf->virt, rpi_hdr->dmabuf->phys);
4867                 kfree(rpi_hdr->dmabuf);
4868                 kfree(rpi_hdr);
4869         }
4870
4871         phba->sli4_hba.next_rpi = phba->sli4_hba.max_cfg_param.rpi_base;
4872         memset(phba->sli4_hba.rpi_bmask, 0, sizeof(*phba->sli4_hba.rpi_bmask));
4873 }
4874
4875 /**
4876  * lpfc_hba_alloc - Allocate driver hba data structure for a device.
4877  * @pdev: pointer to pci device data structure.
4878  *
4879  * This routine is invoked to allocate the driver hba data structure for an
4880  * HBA device. If the allocation is successful, the phba reference to the
4881  * PCI device data structure is set.
4882  *
4883  * Return codes
4884  *      pointer to @phba - successful
4885  *      NULL - error
4886  **/
4887 static struct lpfc_hba *
4888 lpfc_hba_alloc(struct pci_dev *pdev)
4889 {
4890         struct lpfc_hba *phba;
4891
4892         /* Allocate memory for HBA structure */
4893         phba = kzalloc(sizeof(struct lpfc_hba), GFP_KERNEL);
4894         if (!phba) {
4895                 dev_err(&pdev->dev, "failed to allocate hba struct\n");
4896                 return NULL;
4897         }
4898
4899         /* Set reference to PCI device in HBA structure */
4900         phba->pcidev = pdev;
4901
4902         /* Assign an unused board number */
4903         phba->brd_no = lpfc_get_instance();
4904         if (phba->brd_no < 0) {
4905                 kfree(phba);
4906                 return NULL;
4907         }
4908
4909         spin_lock_init(&phba->ct_ev_lock);
4910         INIT_LIST_HEAD(&phba->ct_ev_waiters);
4911
4912         return phba;
4913 }
4914
4915 /**
4916  * lpfc_hba_free - Free driver hba data structure with a device.
4917  * @phba: pointer to lpfc hba data structure.
4918  *
4919  * This routine is invoked to free the driver hba data structure with an
4920  * HBA device.
4921  **/
4922 static void
4923 lpfc_hba_free(struct lpfc_hba *phba)
4924 {
4925         /* Release the driver assigned board number */
4926         idr_remove(&lpfc_hba_index, phba->brd_no);
4927
4928         kfree(phba);
4929         return;
4930 }
4931
4932 /**
4933  * lpfc_create_shost - Create hba physical port with associated scsi host.
4934  * @phba: pointer to lpfc hba data structure.
4935  *
4936  * This routine is invoked to create HBA physical port and associate a SCSI
4937  * host with it.
4938  *
4939  * Return codes
4940  *      0 - successful
4941  *      other values - error
4942  **/
4943 static int
4944 lpfc_create_shost(struct lpfc_hba *phba)
4945 {
4946         struct lpfc_vport *vport;
4947         struct Scsi_Host  *shost;
4948
4949         /* Initialize HBA FC structure */
4950         phba->fc_edtov = FF_DEF_EDTOV;
4951         phba->fc_ratov = FF_DEF_RATOV;
4952         phba->fc_altov = FF_DEF_ALTOV;
4953         phba->fc_arbtov = FF_DEF_ARBTOV;
4954
4955         atomic_set(&phba->sdev_cnt, 0);
4956         vport = lpfc_create_port(phba, phba->brd_no, &phba->pcidev->dev);
4957         if (!vport)
4958                 return -ENODEV;
4959
4960         shost = lpfc_shost_from_vport(vport);
4961         phba->pport = vport;
4962         lpfc_debugfs_initialize(vport);
4963         /* Put reference to SCSI host to driver's device private data */
4964         pci_set_drvdata(phba->pcidev, shost);
4965
4966         return 0;
4967 }
4968
4969 /**
4970  * lpfc_destroy_shost - Destroy hba physical port with associated scsi host.
4971  * @phba: pointer to lpfc hba data structure.
4972  *
4973  * This routine is invoked to destroy HBA physical port and the associated
4974  * SCSI host.
4975  **/
4976 static void
4977 lpfc_destroy_shost(struct lpfc_hba *phba)
4978 {
4979         struct lpfc_vport *vport = phba->pport;
4980
4981         /* Destroy physical port that associated with the SCSI host */
4982         destroy_port(vport);
4983
4984         return;
4985 }
4986
4987 /**
4988  * lpfc_setup_bg - Setup Block guard structures and debug areas.
4989  * @phba: pointer to lpfc hba data structure.
4990  * @shost: the shost to be used to detect Block guard settings.
4991  *
4992  * This routine sets up the local Block guard protocol settings for @shost.
4993  * This routine also allocates memory for debugging bg buffers.
4994  **/
4995 static void
4996 lpfc_setup_bg(struct lpfc_hba *phba, struct Scsi_Host *shost)
4997 {
4998         int pagecnt = 10;
4999         if (lpfc_prot_mask && lpfc_prot_guard) {
5000                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5001                                 "1478 Registering BlockGuard with the "
5002                                 "SCSI layer\n");
5003                 scsi_host_set_prot(shost, lpfc_prot_mask);
5004                 scsi_host_set_guard(shost, lpfc_prot_guard);
5005         }
5006         if (!_dump_buf_data) {
5007                 while (pagecnt) {
5008                         spin_lock_init(&_dump_buf_lock);
5009                         _dump_buf_data =
5010                                 (char *) __get_free_pages(GFP_KERNEL, pagecnt);
5011                         if (_dump_buf_data) {
5012                                 lpfc_printf_log(phba, KERN_ERR, LOG_BG,
5013                                         "9043 BLKGRD: allocated %d pages for "
5014                                        "_dump_buf_data at 0x%p\n",
5015                                        (1 << pagecnt), _dump_buf_data);
5016                                 _dump_buf_data_order = pagecnt;
5017                                 memset(_dump_buf_data, 0,
5018                                        ((1 << PAGE_SHIFT) << pagecnt));
5019                                 break;
5020                         } else
5021                                 --pagecnt;
5022                 }
5023                 if (!_dump_buf_data_order)
5024                         lpfc_printf_log(phba, KERN_ERR, LOG_BG,
5025                                 "9044 BLKGRD: ERROR unable to allocate "
5026                                "memory for hexdump\n");
5027         } else
5028                 lpfc_printf_log(phba, KERN_ERR, LOG_BG,
5029                         "9045 BLKGRD: already allocated _dump_buf_data=0x%p"
5030                        "\n", _dump_buf_data);
5031         if (!_dump_buf_dif) {
5032                 while (pagecnt) {
5033                         _dump_buf_dif =
5034                                 (char *) __get_free_pages(GFP_KERNEL, pagecnt);
5035                         if (_dump_buf_dif) {
5036                                 lpfc_printf_log(phba, KERN_ERR, LOG_BG,
5037                                         "9046 BLKGRD: allocated %d pages for "
5038                                        "_dump_buf_dif at 0x%p\n",
5039                                        (1 << pagecnt), _dump_buf_dif);
5040                                 _dump_buf_dif_order = pagecnt;
5041                                 memset(_dump_buf_dif, 0,
5042                                        ((1 << PAGE_SHIFT) << pagecnt));
5043                                 break;
5044                         } else
5045                                 --pagecnt;
5046                 }
5047                 if (!_dump_buf_dif_order)
5048                         lpfc_printf_log(phba, KERN_ERR, LOG_BG,
5049                         "9047 BLKGRD: ERROR unable to allocate "
5050                                "memory for hexdump\n");
5051         } else
5052                 lpfc_printf_log(phba, KERN_ERR, LOG_BG,
5053                         "9048 BLKGRD: already allocated _dump_buf_dif=0x%p\n",
5054                        _dump_buf_dif);
5055 }
5056
5057 /**
5058  * lpfc_post_init_setup - Perform necessary device post initialization setup.
5059  * @phba: pointer to lpfc hba data structure.
5060  *
5061  * This routine is invoked to perform all the necessary post initialization
5062  * setup for the device.
5063  **/
5064 static void
5065 lpfc_post_init_setup(struct lpfc_hba *phba)
5066 {
5067         struct Scsi_Host  *shost;
5068         struct lpfc_adapter_event_header adapter_event;
5069
5070         /* Get the default values for Model Name and Description */
5071         lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
5072
5073         /*
5074          * hba setup may have changed the hba_queue_depth so we need to
5075          * adjust the value of can_queue.
5076          */
5077         shost = pci_get_drvdata(phba->pcidev);
5078         shost->can_queue = phba->cfg_hba_queue_depth - 10;
5079         if (phba->sli3_options & LPFC_SLI3_BG_ENABLED)
5080                 lpfc_setup_bg(phba, shost);
5081
5082         lpfc_host_attrib_init(shost);
5083
5084         if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
5085                 spin_lock_irq(shost->host_lock);
5086                 lpfc_poll_start_timer(phba);
5087                 spin_unlock_irq(shost->host_lock);
5088         }
5089
5090         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5091                         "0428 Perform SCSI scan\n");
5092         /* Send board arrival event to upper layer */
5093         adapter_event.event_type = FC_REG_ADAPTER_EVENT;
5094         adapter_event.subcategory = LPFC_EVENT_ARRIVAL;
5095         fc_host_post_vendor_event(shost, fc_get_event_number(),
5096                                   sizeof(adapter_event),
5097                                   (char *) &adapter_event,
5098                                   LPFC_NL_VENDOR_ID);
5099         return;
5100 }
5101
5102 /**
5103  * lpfc_sli_pci_mem_setup - Setup SLI3 HBA PCI memory space.
5104  * @phba: pointer to lpfc hba data structure.
5105  *
5106  * This routine is invoked to set up the PCI device memory space for device
5107  * with SLI-3 interface spec.
5108  *
5109  * Return codes
5110  *      0 - successful
5111  *      other values - error
5112  **/
5113 static int
5114 lpfc_sli_pci_mem_setup(struct lpfc_hba *phba)
5115 {
5116         struct pci_dev *pdev;
5117         unsigned long bar0map_len, bar2map_len;
5118         int i, hbq_count;
5119         void *ptr;
5120         int error = -ENODEV;
5121
5122         /* Obtain PCI device reference */
5123         if (!phba->pcidev)
5124                 return error;
5125         else
5126                 pdev = phba->pcidev;
5127
5128         /* Set the device DMA mask size */
5129         if (pci_set_dma_mask(pdev, DMA_BIT_MASK(64)) != 0
5130          || pci_set_consistent_dma_mask(pdev,DMA_BIT_MASK(64)) != 0) {
5131                 if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32)) != 0
5132                  || pci_set_consistent_dma_mask(pdev,DMA_BIT_MASK(32)) != 0) {
5133                         return error;
5134                 }
5135         }
5136
5137         /* Get the bus address of Bar0 and Bar2 and the number of bytes
5138          * required by each mapping.
5139          */
5140         phba->pci_bar0_map = pci_resource_start(pdev, 0);
5141         bar0map_len = pci_resource_len(pdev, 0);
5142
5143         phba->pci_bar2_map = pci_resource_start(pdev, 2);
5144         bar2map_len = pci_resource_len(pdev, 2);
5145
5146         /* Map HBA SLIM to a kernel virtual address. */
5147         phba->slim_memmap_p = ioremap(phba->pci_bar0_map, bar0map_len);
5148         if (!phba->slim_memmap_p) {
5149                 dev_printk(KERN_ERR, &pdev->dev,
5150                            "ioremap failed for SLIM memory.\n");
5151                 goto out;
5152         }
5153
5154         /* Map HBA Control Registers to a kernel virtual address. */
5155         phba->ctrl_regs_memmap_p = ioremap(phba->pci_bar2_map, bar2map_len);
5156         if (!phba->ctrl_regs_memmap_p) {
5157                 dev_printk(KERN_ERR, &pdev->dev,
5158                            "ioremap failed for HBA control registers.\n");
5159                 goto out_iounmap_slim;
5160         }
5161
5162         /* Allocate memory for SLI-2 structures */
5163         phba->slim2p.virt = dma_alloc_coherent(&pdev->dev,
5164                                                SLI2_SLIM_SIZE,
5165                                                &phba->slim2p.phys,
5166                                                GFP_KERNEL);
5167         if (!phba->slim2p.virt)
5168                 goto out_iounmap;
5169
5170         memset(phba->slim2p.virt, 0, SLI2_SLIM_SIZE);
5171         phba->mbox = phba->slim2p.virt + offsetof(struct lpfc_sli2_slim, mbx);
5172         phba->mbox_ext = (phba->slim2p.virt +
5173                 offsetof(struct lpfc_sli2_slim, mbx_ext_words));
5174         phba->pcb = (phba->slim2p.virt + offsetof(struct lpfc_sli2_slim, pcb));
5175         phba->IOCBs = (phba->slim2p.virt +
5176                        offsetof(struct lpfc_sli2_slim, IOCBs));
5177
5178         phba->hbqslimp.virt = dma_alloc_coherent(&pdev->dev,
5179                                                  lpfc_sli_hbq_size(),
5180                                                  &phba->hbqslimp.phys,
5181                                                  GFP_KERNEL);
5182         if (!phba->hbqslimp.virt)
5183                 goto out_free_slim;
5184
5185         hbq_count = lpfc_sli_hbq_count();
5186         ptr = phba->hbqslimp.virt;
5187         for (i = 0; i < hbq_count; ++i) {
5188                 phba->hbqs[i].hbq_virt = ptr;
5189                 INIT_LIST_HEAD(&phba->hbqs[i].hbq_buffer_list);
5190                 ptr += (lpfc_hbq_defs[i]->entry_count *
5191                         sizeof(struct lpfc_hbq_entry));
5192         }
5193         phba->hbqs[LPFC_ELS_HBQ].hbq_alloc_buffer = lpfc_els_hbq_alloc;
5194         phba->hbqs[LPFC_ELS_HBQ].hbq_free_buffer = lpfc_els_hbq_free;
5195
5196         memset(phba->hbqslimp.virt, 0, lpfc_sli_hbq_size());
5197
5198         INIT_LIST_HEAD(&phba->rb_pend_list);
5199
5200         phba->MBslimaddr = phba->slim_memmap_p;
5201         phba->HAregaddr = phba->ctrl_regs_memmap_p + HA_REG_OFFSET;
5202         phba->CAregaddr = phba->ctrl_regs_memmap_p + CA_REG_OFFSET;
5203         phba->HSregaddr = phba->ctrl_regs_memmap_p + HS_REG_OFFSET;
5204         phba->HCregaddr = phba->ctrl_regs_memmap_p + HC_REG_OFFSET;
5205
5206         return 0;
5207
5208 out_free_slim:
5209         dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
5210                           phba->slim2p.virt, phba->slim2p.phys);
5211 out_iounmap:
5212         iounmap(phba->ctrl_regs_memmap_p);
5213 out_iounmap_slim:
5214         iounmap(phba->slim_memmap_p);
5215 out:
5216         return error;
5217 }
5218
5219 /**
5220  * lpfc_sli_pci_mem_unset - Unset SLI3 HBA PCI memory space.
5221  * @phba: pointer to lpfc hba data structure.
5222  *
5223  * This routine is invoked to unset the PCI device memory space for device
5224  * with SLI-3 interface spec.
5225  **/
5226 static void
5227 lpfc_sli_pci_mem_unset(struct lpfc_hba *phba)
5228 {
5229         struct pci_dev *pdev;
5230
5231         /* Obtain PCI device reference */
5232         if (!phba->pcidev)
5233                 return;
5234         else
5235                 pdev = phba->pcidev;
5236
5237         /* Free coherent DMA memory allocated */
5238         dma_free_coherent(&pdev->dev, lpfc_sli_hbq_size(),
5239                           phba->hbqslimp.virt, phba->hbqslimp.phys);
5240         dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
5241                           phba->slim2p.virt, phba->slim2p.phys);
5242
5243         /* I/O memory unmap */
5244         iounmap(phba->ctrl_regs_memmap_p);
5245         iounmap(phba->slim_memmap_p);
5246
5247         return;
5248 }
5249
5250 /**
5251  * lpfc_sli4_post_status_check - Wait for SLI4 POST done and check status
5252  * @phba: pointer to lpfc hba data structure.
5253  *
5254  * This routine is invoked to wait for SLI4 device Power On Self Test (POST)
5255  * done and check status.
5256  *
5257  * Return 0 if successful, otherwise -ENODEV.
5258  **/
5259 int
5260 lpfc_sli4_post_status_check(struct lpfc_hba *phba)
5261 {
5262         struct lpfc_register sta_reg, uerrlo_reg, uerrhi_reg;
5263         int i, port_error = -ENODEV;
5264
5265         if (!phba->sli4_hba.STAregaddr)
5266                 return -ENODEV;
5267
5268         /* Wait up to 30 seconds for the SLI Port POST done and ready */
5269         for (i = 0; i < 3000; i++) {
5270                 sta_reg.word0 = readl(phba->sli4_hba.STAregaddr);
5271                 /* Encounter fatal POST error, break out */
5272                 if (bf_get(lpfc_hst_state_perr, &sta_reg)) {
5273                         port_error = -ENODEV;
5274                         break;
5275                 }
5276                 if (LPFC_POST_STAGE_ARMFW_READY ==
5277                     bf_get(lpfc_hst_state_port_status, &sta_reg)) {
5278                         port_error = 0;
5279                         break;
5280                 }
5281                 msleep(10);
5282         }
5283
5284         if (port_error)
5285                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5286                         "1408 Failure HBA POST Status: sta_reg=0x%x, "
5287                         "perr=x%x, sfi=x%x, nip=x%x, ipc=x%x, xrom=x%x, "
5288                         "dl=x%x, pstatus=x%x\n", sta_reg.word0,
5289                         bf_get(lpfc_hst_state_perr, &sta_reg),
5290                         bf_get(lpfc_hst_state_sfi, &sta_reg),
5291                         bf_get(lpfc_hst_state_nip, &sta_reg),
5292                         bf_get(lpfc_hst_state_ipc, &sta_reg),
5293                         bf_get(lpfc_hst_state_xrom, &sta_reg),
5294                         bf_get(lpfc_hst_state_dl, &sta_reg),
5295                         bf_get(lpfc_hst_state_port_status, &sta_reg));
5296
5297         /* Log device information */
5298         phba->sli4_hba.sli_intf.word0 = readl(phba->sli4_hba.SLIINTFregaddr);
5299         if (bf_get(lpfc_sli_intf_valid,
5300                    &phba->sli4_hba.sli_intf) == LPFC_SLI_INTF_VALID) {
5301                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5302                                 "2534 Device Info: ChipType=0x%x, SliRev=0x%x, "
5303                                 "IFType=0x%x, SLIHint_1=0x%x, SLIHint_2=0x%x, "
5304                                 "FT=0x%x\n",
5305                                 bf_get(lpfc_sli_intf_sli_family,
5306                                        &phba->sli4_hba.sli_intf),
5307                                 bf_get(lpfc_sli_intf_slirev,
5308                                        &phba->sli4_hba.sli_intf),
5309                                 bf_get(lpfc_sli_intf_if_type,
5310                                        &phba->sli4_hba.sli_intf),
5311                                 bf_get(lpfc_sli_intf_sli_hint1,
5312                                        &phba->sli4_hba.sli_intf),
5313                                 bf_get(lpfc_sli_intf_sli_hint2,
5314                                        &phba->sli4_hba.sli_intf),
5315                                 bf_get(lpfc_sli_intf_func_type,
5316                                        &phba->sli4_hba.sli_intf));
5317         }
5318
5319         phba->sli4_hba.ue_mask_lo = readl(phba->sli4_hba.UEMASKLOregaddr);
5320         phba->sli4_hba.ue_mask_hi = readl(phba->sli4_hba.UEMASKHIregaddr);
5321         /* With uncoverable error, log the error message and return error */
5322         uerrlo_reg.word0 = readl(phba->sli4_hba.UERRLOregaddr);
5323         uerrhi_reg.word0 = readl(phba->sli4_hba.UERRHIregaddr);
5324         if ((~phba->sli4_hba.ue_mask_lo & uerrlo_reg.word0) ||
5325             (~phba->sli4_hba.ue_mask_hi & uerrhi_reg.word0)) {
5326                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5327                                 "1422 HBA Unrecoverable error: "
5328                                 "uerr_lo_reg=0x%x, uerr_hi_reg=0x%x, "
5329                                 "ue_mask_lo_reg=0x%x, ue_mask_hi_reg=0x%x\n",
5330                                 uerrlo_reg.word0, uerrhi_reg.word0,
5331                                 phba->sli4_hba.ue_mask_lo,
5332                                 phba->sli4_hba.ue_mask_hi);
5333                 return -ENODEV;
5334         }
5335
5336         return port_error;
5337 }
5338
5339 /**
5340  * lpfc_sli4_bar0_register_memmap - Set up SLI4 BAR0 register memory map.
5341  * @phba: pointer to lpfc hba data structure.
5342  *
5343  * This routine is invoked to set up SLI4 BAR0 PCI config space register
5344  * memory map.
5345  **/
5346 static void
5347 lpfc_sli4_bar0_register_memmap(struct lpfc_hba *phba)
5348 {
5349         phba->sli4_hba.UERRLOregaddr = phba->sli4_hba.conf_regs_memmap_p +
5350                                         LPFC_UERR_STATUS_LO;
5351         phba->sli4_hba.UERRHIregaddr = phba->sli4_hba.conf_regs_memmap_p +
5352                                         LPFC_UERR_STATUS_HI;
5353         phba->sli4_hba.UEMASKLOregaddr = phba->sli4_hba.conf_regs_memmap_p +
5354                                         LPFC_UE_MASK_LO;
5355         phba->sli4_hba.UEMASKHIregaddr = phba->sli4_hba.conf_regs_memmap_p +
5356                                         LPFC_UE_MASK_HI;
5357         phba->sli4_hba.SLIINTFregaddr = phba->sli4_hba.conf_regs_memmap_p +
5358                                         LPFC_SLI_INTF;
5359 }
5360
5361 /**
5362  * lpfc_sli4_bar1_register_memmap - Set up SLI4 BAR1 register memory map.
5363  * @phba: pointer to lpfc hba data structure.
5364  *
5365  * This routine is invoked to set up SLI4 BAR1 control status register (CSR)
5366  * memory map.
5367  **/
5368 static void
5369 lpfc_sli4_bar1_register_memmap(struct lpfc_hba *phba)
5370 {
5371
5372         phba->sli4_hba.STAregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
5373                                     LPFC_HST_STATE;
5374         phba->sli4_hba.ISRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
5375                                     LPFC_HST_ISR0;
5376         phba->sli4_hba.IMRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
5377                                     LPFC_HST_IMR0;
5378         phba->sli4_hba.ISCRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
5379                                      LPFC_HST_ISCR0;
5380         return;
5381 }
5382
5383 /**
5384  * lpfc_sli4_bar2_register_memmap - Set up SLI4 BAR2 register memory map.
5385  * @phba: pointer to lpfc hba data structure.
5386  * @vf: virtual function number
5387  *
5388  * This routine is invoked to set up SLI4 BAR2 doorbell register memory map
5389  * based on the given viftual function number, @vf.
5390  *
5391  * Return 0 if successful, otherwise -ENODEV.
5392  **/
5393 static int
5394 lpfc_sli4_bar2_register_memmap(struct lpfc_hba *phba, uint32_t vf)
5395 {
5396         if (vf > LPFC_VIR_FUNC_MAX)
5397                 return -ENODEV;
5398
5399         phba->sli4_hba.RQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
5400                                 vf * LPFC_VFR_PAGE_SIZE + LPFC_RQ_DOORBELL);
5401         phba->sli4_hba.WQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
5402                                 vf * LPFC_VFR_PAGE_SIZE + LPFC_WQ_DOORBELL);
5403         phba->sli4_hba.EQCQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
5404                                 vf * LPFC_VFR_PAGE_SIZE + LPFC_EQCQ_DOORBELL);
5405         phba->sli4_hba.MQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
5406                                 vf * LPFC_VFR_PAGE_SIZE + LPFC_MQ_DOORBELL);
5407         phba->sli4_hba.BMBXregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
5408                                 vf * LPFC_VFR_PAGE_SIZE + LPFC_BMBX);
5409         return 0;
5410 }
5411
5412 /**
5413  * lpfc_create_bootstrap_mbox - Create the bootstrap mailbox
5414  * @phba: pointer to lpfc hba data structure.
5415  *
5416  * This routine is invoked to create the bootstrap mailbox
5417  * region consistent with the SLI-4 interface spec.  This
5418  * routine allocates all memory necessary to communicate
5419  * mailbox commands to the port and sets up all alignment
5420  * needs.  No locks are expected to be held when calling
5421  * this routine.
5422  *
5423  * Return codes
5424  *      0 - successful
5425  *      -ENOMEM - could not allocated memory.
5426  **/
5427 static int
5428 lpfc_create_bootstrap_mbox(struct lpfc_hba *phba)
5429 {
5430         uint32_t bmbx_size;
5431         struct lpfc_dmabuf *dmabuf;
5432         struct dma_address *dma_address;
5433         uint32_t pa_addr;
5434         uint64_t phys_addr;
5435
5436         dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
5437         if (!dmabuf)
5438                 return -ENOMEM;
5439
5440         /*
5441          * The bootstrap mailbox region is comprised of 2 parts
5442          * plus an alignment restriction of 16 bytes.
5443          */
5444         bmbx_size = sizeof(struct lpfc_bmbx_create) + (LPFC_ALIGN_16_BYTE - 1);
5445         dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
5446                                           bmbx_size,
5447                                           &dmabuf->phys,
5448                                           GFP_KERNEL);
5449         if (!dmabuf->virt) {
5450                 kfree(dmabuf);
5451                 return -ENOMEM;
5452         }
5453         memset(dmabuf->virt, 0, bmbx_size);
5454
5455         /*
5456          * Initialize the bootstrap mailbox pointers now so that the register
5457          * operations are simple later.  The mailbox dma address is required
5458          * to be 16-byte aligned.  Also align the virtual memory as each
5459          * maibox is copied into the bmbx mailbox region before issuing the
5460          * command to the port.
5461          */
5462         phba->sli4_hba.bmbx.dmabuf = dmabuf;
5463         phba->sli4_hba.bmbx.bmbx_size = bmbx_size;
5464
5465         phba->sli4_hba.bmbx.avirt = PTR_ALIGN(dmabuf->virt,
5466                                               LPFC_ALIGN_16_BYTE);
5467         phba->sli4_hba.bmbx.aphys = ALIGN(dmabuf->phys,
5468                                               LPFC_ALIGN_16_BYTE);
5469
5470         /*
5471          * Set the high and low physical addresses now.  The SLI4 alignment
5472          * requirement is 16 bytes and the mailbox is posted to the port
5473          * as two 30-bit addresses.  The other data is a bit marking whether
5474          * the 30-bit address is the high or low address.
5475          * Upcast bmbx aphys to 64bits so shift instruction compiles
5476          * clean on 32 bit machines.
5477          */
5478         dma_address = &phba->sli4_hba.bmbx.dma_address;
5479         phys_addr = (uint64_t)phba->sli4_hba.bmbx.aphys;
5480         pa_addr = (uint32_t) ((phys_addr >> 34) & 0x3fffffff);
5481         dma_address->addr_hi = (uint32_t) ((pa_addr << 2) |
5482                                            LPFC_BMBX_BIT1_ADDR_HI);
5483
5484         pa_addr = (uint32_t) ((phba->sli4_hba.bmbx.aphys >> 4) & 0x3fffffff);
5485         dma_address->addr_lo = (uint32_t) ((pa_addr << 2) |
5486                                            LPFC_BMBX_BIT1_ADDR_LO);
5487         return 0;
5488 }
5489
5490 /**
5491  * lpfc_destroy_bootstrap_mbox - Destroy all bootstrap mailbox resources
5492  * @phba: pointer to lpfc hba data structure.
5493  *
5494  * This routine is invoked to teardown the bootstrap mailbox
5495  * region and release all host resources. This routine requires
5496  * the caller to ensure all mailbox commands recovered, no
5497  * additional mailbox comands are sent, and interrupts are disabled
5498  * before calling this routine.
5499  *
5500  **/
5501 static void
5502 lpfc_destroy_bootstrap_mbox(struct lpfc_hba *phba)
5503 {
5504         dma_free_coherent(&phba->pcidev->dev,
5505                           phba->sli4_hba.bmbx.bmbx_size,
5506                           phba->sli4_hba.bmbx.dmabuf->virt,
5507                           phba->sli4_hba.bmbx.dmabuf->phys);
5508
5509         kfree(phba->sli4_hba.bmbx.dmabuf);
5510         memset(&phba->sli4_hba.bmbx, 0, sizeof(struct lpfc_bmbx));
5511 }
5512
5513 /**
5514  * lpfc_sli4_read_config - Get the config parameters.
5515  * @phba: pointer to lpfc hba data structure.
5516  *
5517  * This routine is invoked to read the configuration parameters from the HBA.
5518  * The configuration parameters are used to set the base and maximum values
5519  * for RPI's XRI's VPI's VFI's and FCFIs. These values also affect the resource
5520  * allocation for the port.
5521  *
5522  * Return codes
5523  *      0 - successful
5524  *      -ENOMEM - No availble memory
5525  *      -EIO - The mailbox failed to complete successfully.
5526  **/
5527 static int
5528 lpfc_sli4_read_config(struct lpfc_hba *phba)
5529 {
5530         LPFC_MBOXQ_t *pmb;
5531         struct lpfc_mbx_read_config *rd_config;
5532         uint32_t rc = 0;
5533
5534         pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5535         if (!pmb) {
5536                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5537                                 "2011 Unable to allocate memory for issuing "
5538                                 "SLI_CONFIG_SPECIAL mailbox command\n");
5539                 return -ENOMEM;
5540         }
5541
5542         lpfc_read_config(phba, pmb);
5543
5544         rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
5545         if (rc != MBX_SUCCESS) {
5546                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5547                         "2012 Mailbox failed , mbxCmd x%x "
5548                         "READ_CONFIG, mbxStatus x%x\n",
5549                         bf_get(lpfc_mqe_command, &pmb->u.mqe),
5550                         bf_get(lpfc_mqe_status, &pmb->u.mqe));
5551                 rc = -EIO;
5552         } else {
5553                 rd_config = &pmb->u.mqe.un.rd_config;
5554                 phba->sli4_hba.max_cfg_param.max_xri =
5555                         bf_get(lpfc_mbx_rd_conf_xri_count, rd_config);
5556                 phba->sli4_hba.max_cfg_param.xri_base =
5557                         bf_get(lpfc_mbx_rd_conf_xri_base, rd_config);
5558                 phba->sli4_hba.max_cfg_param.max_vpi =
5559                         bf_get(lpfc_mbx_rd_conf_vpi_count, rd_config);
5560                 phba->sli4_hba.max_cfg_param.vpi_base =
5561                         bf_get(lpfc_mbx_rd_conf_vpi_base, rd_config);
5562                 phba->sli4_hba.max_cfg_param.max_rpi =
5563                         bf_get(lpfc_mbx_rd_conf_rpi_count, rd_config);
5564                 phba->sli4_hba.max_cfg_param.rpi_base =
5565                         bf_get(lpfc_mbx_rd_conf_rpi_base, rd_config);
5566                 phba->sli4_hba.max_cfg_param.max_vfi =
5567                         bf_get(lpfc_mbx_rd_conf_vfi_count, rd_config);
5568                 phba->sli4_hba.max_cfg_param.vfi_base =
5569                         bf_get(lpfc_mbx_rd_conf_vfi_base, rd_config);
5570                 phba->sli4_hba.max_cfg_param.max_fcfi =
5571                         bf_get(lpfc_mbx_rd_conf_fcfi_count, rd_config);
5572                 phba->sli4_hba.max_cfg_param.fcfi_base =
5573                         bf_get(lpfc_mbx_rd_conf_fcfi_base, rd_config);
5574                 phba->sli4_hba.max_cfg_param.max_eq =
5575                         bf_get(lpfc_mbx_rd_conf_eq_count, rd_config);
5576                 phba->sli4_hba.max_cfg_param.max_rq =
5577                         bf_get(lpfc_mbx_rd_conf_rq_count, rd_config);
5578                 phba->sli4_hba.max_cfg_param.max_wq =
5579                         bf_get(lpfc_mbx_rd_conf_wq_count, rd_config);
5580                 phba->sli4_hba.max_cfg_param.max_cq =
5581                         bf_get(lpfc_mbx_rd_conf_cq_count, rd_config);
5582                 phba->lmt = bf_get(lpfc_mbx_rd_conf_lmt, rd_config);
5583                 phba->sli4_hba.next_xri = phba->sli4_hba.max_cfg_param.xri_base;
5584                 phba->vpi_base = phba->sli4_hba.max_cfg_param.vpi_base;
5585                 phba->vfi_base = phba->sli4_hba.max_cfg_param.vfi_base;
5586                 phba->sli4_hba.next_rpi = phba->sli4_hba.max_cfg_param.rpi_base;
5587                 phba->max_vpi = (phba->sli4_hba.max_cfg_param.max_vpi > 0) ?
5588                                 (phba->sli4_hba.max_cfg_param.max_vpi - 1) : 0;
5589                 phba->max_vports = phba->max_vpi;
5590                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5591                                 "2003 cfg params XRI(B:%d M:%d), "
5592                                 "VPI(B:%d M:%d) "
5593                                 "VFI(B:%d M:%d) "
5594                                 "RPI(B:%d M:%d) "
5595                                 "FCFI(B:%d M:%d)\n",
5596                                 phba->sli4_hba.max_cfg_param.xri_base,
5597                                 phba->sli4_hba.max_cfg_param.max_xri,
5598                                 phba->sli4_hba.max_cfg_param.vpi_base,
5599                                 phba->sli4_hba.max_cfg_param.max_vpi,
5600                                 phba->sli4_hba.max_cfg_param.vfi_base,
5601                                 phba->sli4_hba.max_cfg_param.max_vfi,
5602                                 phba->sli4_hba.max_cfg_param.rpi_base,
5603                                 phba->sli4_hba.max_cfg_param.max_rpi,
5604                                 phba->sli4_hba.max_cfg_param.fcfi_base,
5605                                 phba->sli4_hba.max_cfg_param.max_fcfi);
5606         }
5607         mempool_free(pmb, phba->mbox_mem_pool);
5608
5609         /* Reset the DFT_HBA_Q_DEPTH to the max xri  */
5610         if (phba->cfg_hba_queue_depth >
5611                 (phba->sli4_hba.max_cfg_param.max_xri -
5612                         lpfc_sli4_get_els_iocb_cnt(phba)))
5613                 phba->cfg_hba_queue_depth =
5614                         phba->sli4_hba.max_cfg_param.max_xri -
5615                                 lpfc_sli4_get_els_iocb_cnt(phba);
5616         return rc;
5617 }
5618
5619 /**
5620  * lpfc_dev_endian_order_setup - Notify the port of the host's endian order.
5621  * @phba: pointer to lpfc hba data structure.
5622  *
5623  * This routine is invoked to setup the host-side endian order to the
5624  * HBA consistent with the SLI-4 interface spec.
5625  *
5626  * Return codes
5627  *      0 - successful
5628  *      -ENOMEM - No availble memory
5629  *      -EIO - The mailbox failed to complete successfully.
5630  **/
5631 static int
5632 lpfc_setup_endian_order(struct lpfc_hba *phba)
5633 {
5634         LPFC_MBOXQ_t *mboxq;
5635         uint32_t rc = 0;
5636         uint32_t endian_mb_data[2] = {HOST_ENDIAN_LOW_WORD0,
5637                                       HOST_ENDIAN_HIGH_WORD1};
5638
5639         mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5640         if (!mboxq) {
5641                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5642                                 "0492 Unable to allocate memory for issuing "
5643                                 "SLI_CONFIG_SPECIAL mailbox command\n");
5644                 return -ENOMEM;
5645         }
5646
5647         /*
5648          * The SLI4_CONFIG_SPECIAL mailbox command requires the first two
5649          * words to contain special data values and no other data.
5650          */
5651         memset(mboxq, 0, sizeof(LPFC_MBOXQ_t));
5652         memcpy(&mboxq->u.mqe, &endian_mb_data, sizeof(endian_mb_data));
5653         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5654         if (rc != MBX_SUCCESS) {
5655                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5656                                 "0493 SLI_CONFIG_SPECIAL mailbox failed with "
5657                                 "status x%x\n",
5658                                 rc);
5659                 rc = -EIO;
5660         }
5661
5662         mempool_free(mboxq, phba->mbox_mem_pool);
5663         return rc;
5664 }
5665
5666 /**
5667  * lpfc_sli4_queue_create - Create all the SLI4 queues
5668  * @phba: pointer to lpfc hba data structure.
5669  *
5670  * This routine is invoked to allocate all the SLI4 queues for the FCoE HBA
5671  * operation. For each SLI4 queue type, the parameters such as queue entry
5672  * count (queue depth) shall be taken from the module parameter. For now,
5673  * we just use some constant number as place holder.
5674  *
5675  * Return codes
5676  *      0 - successful
5677  *      -ENOMEM - No availble memory
5678  *      -EIO - The mailbox failed to complete successfully.
5679  **/
5680 static int
5681 lpfc_sli4_queue_create(struct lpfc_hba *phba)
5682 {
5683         struct lpfc_queue *qdesc;
5684         int fcp_eqidx, fcp_cqidx, fcp_wqidx;
5685         int cfg_fcp_wq_count;
5686         int cfg_fcp_eq_count;
5687
5688         /*
5689          * Sanity check for confiugred queue parameters against the run-time
5690          * device parameters
5691          */
5692
5693         /* Sanity check on FCP fast-path WQ parameters */
5694         cfg_fcp_wq_count = phba->cfg_fcp_wq_count;
5695         if (cfg_fcp_wq_count >
5696             (phba->sli4_hba.max_cfg_param.max_wq - LPFC_SP_WQN_DEF)) {
5697                 cfg_fcp_wq_count = phba->sli4_hba.max_cfg_param.max_wq -
5698                                    LPFC_SP_WQN_DEF;
5699                 if (cfg_fcp_wq_count < LPFC_FP_WQN_MIN) {
5700                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5701                                         "2581 Not enough WQs (%d) from "
5702                                         "the pci function for supporting "
5703                                         "FCP WQs (%d)\n",
5704                                         phba->sli4_hba.max_cfg_param.max_wq,
5705                                         phba->cfg_fcp_wq_count);
5706                         goto out_error;
5707                 }
5708                 lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
5709                                 "2582 Not enough WQs (%d) from the pci "
5710                                 "function for supporting the requested "
5711                                 "FCP WQs (%d), the actual FCP WQs can "
5712                                 "be supported: %d\n",
5713                                 phba->sli4_hba.max_cfg_param.max_wq,
5714                                 phba->cfg_fcp_wq_count, cfg_fcp_wq_count);
5715         }
5716         /* The actual number of FCP work queues adopted */
5717         phba->cfg_fcp_wq_count = cfg_fcp_wq_count;
5718
5719         /* Sanity check on FCP fast-path EQ parameters */
5720         cfg_fcp_eq_count = phba->cfg_fcp_eq_count;
5721         if (cfg_fcp_eq_count >
5722             (phba->sli4_hba.max_cfg_param.max_eq - LPFC_SP_EQN_DEF)) {
5723                 cfg_fcp_eq_count = phba->sli4_hba.max_cfg_param.max_eq -
5724                                    LPFC_SP_EQN_DEF;
5725                 if (cfg_fcp_eq_count < LPFC_FP_EQN_MIN) {
5726                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5727                                         "2574 Not enough EQs (%d) from the "
5728                                         "pci function for supporting FCP "
5729                                         "EQs (%d)\n",
5730                                         phba->sli4_hba.max_cfg_param.max_eq,
5731                                         phba->cfg_fcp_eq_count);
5732                         goto out_error;
5733                 }
5734                 lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
5735                                 "2575 Not enough EQs (%d) from the pci "
5736                                 "function for supporting the requested "
5737                                 "FCP EQs (%d), the actual FCP EQs can "
5738                                 "be supported: %d\n",
5739                                 phba->sli4_hba.max_cfg_param.max_eq,
5740                                 phba->cfg_fcp_eq_count, cfg_fcp_eq_count);
5741         }
5742         /* It does not make sense to have more EQs than WQs */
5743         if (cfg_fcp_eq_count > phba->cfg_fcp_wq_count) {
5744                 lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
5745                                 "2593 The FCP EQ count(%d) cannot be greater "
5746                                 "than the FCP WQ count(%d), limiting the "
5747                                 "FCP EQ count to %d\n", cfg_fcp_eq_count,
5748                                 phba->cfg_fcp_wq_count,
5749                                 phba->cfg_fcp_wq_count);
5750                 cfg_fcp_eq_count = phba->cfg_fcp_wq_count;
5751         }
5752         /* The actual number of FCP event queues adopted */
5753         phba->cfg_fcp_eq_count = cfg_fcp_eq_count;
5754         /* The overall number of event queues used */
5755         phba->sli4_hba.cfg_eqn = phba->cfg_fcp_eq_count + LPFC_SP_EQN_DEF;
5756
5757         /*
5758          * Create Event Queues (EQs)
5759          */
5760
5761         /* Get EQ depth from module parameter, fake the default for now */
5762         phba->sli4_hba.eq_esize = LPFC_EQE_SIZE_4B;
5763         phba->sli4_hba.eq_ecount = LPFC_EQE_DEF_COUNT;
5764
5765         /* Create slow path event queue */
5766         qdesc = lpfc_sli4_queue_alloc(phba, phba->sli4_hba.eq_esize,
5767                                       phba->sli4_hba.eq_ecount);
5768         if (!qdesc) {
5769                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5770                                 "0496 Failed allocate slow-path EQ\n");
5771                 goto out_error;
5772         }
5773         phba->sli4_hba.sp_eq = qdesc;
5774
5775         /* Create fast-path FCP Event Queue(s) */
5776         phba->sli4_hba.fp_eq = kzalloc((sizeof(struct lpfc_queue *) *
5777                                phba->cfg_fcp_eq_count), GFP_KERNEL);
5778         if (!phba->sli4_hba.fp_eq) {
5779                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5780                                 "2576 Failed allocate memory for fast-path "
5781