[SCSI] lpfc 8.3.20: Implement the FC and SLI async event handlers
[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 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 FCoE 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.type =
3214                                 bf_get(lpfc_acqe_link_type, acqe_link);
3215         phba->sli4_hba.link_state.number =
3216                                 bf_get(lpfc_acqe_link_number, acqe_link);
3217         phba->sli4_hba.link_state.fault =
3218                                 bf_get(lpfc_acqe_link_fault, acqe_link);
3219         phba->sli4_hba.link_state.logical_speed =
3220                         bf_get(lpfc_acqe_logical_link_speed, acqe_link);
3221         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3222                         "2900 Async FCoE Link event - Speed:%dGBit duplex:x%x "
3223                         "LA Type:x%x Port Type:%d Port Number:%d Logical "
3224                         "speed:%dMbps Fault:%d\n",
3225                         phba->sli4_hba.link_state.speed,
3226                         phba->sli4_hba.link_state.topology,
3227                         phba->sli4_hba.link_state.status,
3228                         phba->sli4_hba.link_state.type,
3229                         phba->sli4_hba.link_state.number,
3230                         phba->sli4_hba.link_state.logical_speed * 10,
3231                         phba->sli4_hba.link_state.fault);
3232         /*
3233          * For FC Mode: issue the READ_TOPOLOGY mailbox command to fetch
3234          * topology info. Note: Optional for non FC-AL ports.
3235          */
3236         if (!(phba->hba_flag & HBA_FCOE_MODE)) {
3237                 rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
3238                 if (rc == MBX_NOT_FINISHED)
3239                         goto out_free_dmabuf;
3240                 return;
3241         }
3242         /*
3243          * For FCoE Mode: fill in all the topology information we need and call
3244          * the READ_TOPOLOGY completion routine to continue without actually
3245          * sending the READ_TOPOLOGY mailbox command to the port.
3246          */
3247         /* Parse and translate status field */
3248         mb = &pmb->u.mb;
3249         mb->mbxStatus = lpfc_sli4_parse_latt_fault(phba, acqe_link);
3250
3251         /* Parse and translate link attention fields */
3252         la = (struct lpfc_mbx_read_top *) &pmb->u.mb.un.varReadTop;
3253         la->eventTag = acqe_link->event_tag;
3254         bf_set(lpfc_mbx_read_top_att_type, la, att_type);
3255         bf_set(lpfc_mbx_read_top_link_spd, la,
3256                lpfc_sli4_parse_latt_link_speed(phba, acqe_link));
3257
3258         /* Fake the the following irrelvant fields */
3259         bf_set(lpfc_mbx_read_top_topology, la, LPFC_TOPOLOGY_PT_PT);
3260         bf_set(lpfc_mbx_read_top_alpa_granted, la, 0);
3261         bf_set(lpfc_mbx_read_top_il, la, 0);
3262         bf_set(lpfc_mbx_read_top_pb, la, 0);
3263         bf_set(lpfc_mbx_read_top_fa, la, 0);
3264         bf_set(lpfc_mbx_read_top_mm, la, 0);
3265
3266         /* Invoke the lpfc_handle_latt mailbox command callback function */
3267         lpfc_mbx_cmpl_read_topology(phba, pmb);
3268
3269         return;
3270
3271 out_free_dmabuf:
3272         kfree(mp);
3273 out_free_pmb:
3274         mempool_free(pmb, phba->mbox_mem_pool);
3275 }
3276
3277 /**
3278  * lpfc_sli4_async_fc_evt - Process the asynchronous FC link event
3279  * @phba: pointer to lpfc hba data structure.
3280  * @acqe_fc: pointer to the async fc completion queue entry.
3281  *
3282  * This routine is to handle the SLI4 asynchronous FC event. It will simply log
3283  * that the event was received and then issue a read_topology mailbox command so
3284  * that the rest of the driver will treat it the same as SLI3.
3285  **/
3286 static void
3287 lpfc_sli4_async_fc_evt(struct lpfc_hba *phba, struct lpfc_acqe_fc_la *acqe_fc)
3288 {
3289         struct lpfc_dmabuf *mp;
3290         LPFC_MBOXQ_t *pmb;
3291         int rc;
3292
3293         if (bf_get(lpfc_trailer_type, acqe_fc) !=
3294             LPFC_FC_LA_EVENT_TYPE_FC_LINK) {
3295                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3296                                 "2895 Non FC link Event detected.(%d)\n",
3297                                 bf_get(lpfc_trailer_type, acqe_fc));
3298                 return;
3299         }
3300         /* Keep the link status for extra SLI4 state machine reference */
3301         phba->sli4_hba.link_state.speed =
3302                                 bf_get(lpfc_acqe_fc_la_speed, acqe_fc);
3303         phba->sli4_hba.link_state.duplex = LPFC_ASYNC_LINK_DUPLEX_FULL;
3304         phba->sli4_hba.link_state.topology =
3305                                 bf_get(lpfc_acqe_fc_la_topology, acqe_fc);
3306         phba->sli4_hba.link_state.status =
3307                                 bf_get(lpfc_acqe_fc_la_att_type, acqe_fc);
3308         phba->sli4_hba.link_state.type =
3309                                 bf_get(lpfc_acqe_fc_la_port_type, acqe_fc);
3310         phba->sli4_hba.link_state.number =
3311                                 bf_get(lpfc_acqe_fc_la_port_number, acqe_fc);
3312         phba->sli4_hba.link_state.fault =
3313                                 bf_get(lpfc_acqe_link_fault, acqe_fc);
3314         phba->sli4_hba.link_state.logical_speed =
3315                                 bf_get(lpfc_acqe_fc_la_llink_spd, acqe_fc);
3316         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3317                         "2896 Async FC event - Speed:%dGBaud Topology:x%x "
3318                         "LA Type:x%x Port Type:%d Port Number:%d Logical speed:"
3319                         "%dMbps Fault:%d\n",
3320                         phba->sli4_hba.link_state.speed,
3321                         phba->sli4_hba.link_state.topology,
3322                         phba->sli4_hba.link_state.status,
3323                         phba->sli4_hba.link_state.type,
3324                         phba->sli4_hba.link_state.number,
3325                         phba->sli4_hba.link_state.logical_speed * 10,
3326                         phba->sli4_hba.link_state.fault);
3327         pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
3328         if (!pmb) {
3329                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3330                                 "2897 The mboxq allocation failed\n");
3331                 return;
3332         }
3333         mp = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
3334         if (!mp) {
3335                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3336                                 "2898 The lpfc_dmabuf allocation failed\n");
3337                 goto out_free_pmb;
3338         }
3339         mp->virt = lpfc_mbuf_alloc(phba, 0, &mp->phys);
3340         if (!mp->virt) {
3341                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3342                                 "2899 The mbuf allocation failed\n");
3343                 goto out_free_dmabuf;
3344         }
3345
3346         /* Cleanup any outstanding ELS commands */
3347         lpfc_els_flush_all_cmd(phba);
3348
3349         /* Block ELS IOCBs until we have done process link event */
3350         phba->sli.ring[LPFC_ELS_RING].flag |= LPFC_STOP_IOCB_EVENT;
3351
3352         /* Update link event statistics */
3353         phba->sli.slistat.link_event++;
3354
3355         /* Create lpfc_handle_latt mailbox command from link ACQE */
3356         lpfc_read_topology(phba, pmb, mp);
3357         pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
3358         pmb->vport = phba->pport;
3359
3360         rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
3361         if (rc == MBX_NOT_FINISHED)
3362                 goto out_free_dmabuf;
3363         return;
3364
3365 out_free_dmabuf:
3366         kfree(mp);
3367 out_free_pmb:
3368         mempool_free(pmb, phba->mbox_mem_pool);
3369 }
3370
3371 /**
3372  * lpfc_sli4_async_sli_evt - Process the asynchronous SLI link event
3373  * @phba: pointer to lpfc hba data structure.
3374  * @acqe_fc: pointer to the async SLI completion queue entry.
3375  *
3376  * This routine is to handle the SLI4 asynchronous SLI events.
3377  **/
3378 static void
3379 lpfc_sli4_async_sli_evt(struct lpfc_hba *phba, struct lpfc_acqe_sli *acqe_sli)
3380 {
3381         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3382                         "2901 Async SLI event - Event Data1:x%08x Event Data2:"
3383                         "x%08x SLI Event Type:%d",
3384                         acqe_sli->event_data1, acqe_sli->event_data2,
3385                         bf_get(lpfc_trailer_type, acqe_sli));
3386         return;
3387 }
3388
3389 /**
3390  * lpfc_sli4_perform_vport_cvl - Perform clear virtual link on a vport
3391  * @vport: pointer to vport data structure.
3392  *
3393  * This routine is to perform Clear Virtual Link (CVL) on a vport in
3394  * response to a CVL event.
3395  *
3396  * Return the pointer to the ndlp with the vport if successful, otherwise
3397  * return NULL.
3398  **/
3399 static struct lpfc_nodelist *
3400 lpfc_sli4_perform_vport_cvl(struct lpfc_vport *vport)
3401 {
3402         struct lpfc_nodelist *ndlp;
3403         struct Scsi_Host *shost;
3404         struct lpfc_hba *phba;
3405
3406         if (!vport)
3407                 return NULL;
3408         phba = vport->phba;
3409         if (!phba)
3410                 return NULL;
3411         ndlp = lpfc_findnode_did(vport, Fabric_DID);
3412         if (!ndlp) {
3413                 /* Cannot find existing Fabric ndlp, so allocate a new one */
3414                 ndlp = mempool_alloc(phba->nlp_mem_pool, GFP_KERNEL);
3415                 if (!ndlp)
3416                         return 0;
3417                 lpfc_nlp_init(vport, ndlp, Fabric_DID);
3418                 /* Set the node type */
3419                 ndlp->nlp_type |= NLP_FABRIC;
3420                 /* Put ndlp onto node list */
3421                 lpfc_enqueue_node(vport, ndlp);
3422         } else if (!NLP_CHK_NODE_ACT(ndlp)) {
3423                 /* re-setup ndlp without removing from node list */
3424                 ndlp = lpfc_enable_node(vport, ndlp, NLP_STE_UNUSED_NODE);
3425                 if (!ndlp)
3426                         return 0;
3427         }
3428         if ((phba->pport->port_state < LPFC_FLOGI) &&
3429                 (phba->pport->port_state != LPFC_VPORT_FAILED))
3430                 return NULL;
3431         /* If virtual link is not yet instantiated ignore CVL */
3432         if ((vport != phba->pport) && (vport->port_state < LPFC_FDISC)
3433                 && (vport->port_state != LPFC_VPORT_FAILED))
3434                 return NULL;
3435         shost = lpfc_shost_from_vport(vport);
3436         if (!shost)
3437                 return NULL;
3438         lpfc_linkdown_port(vport);
3439         lpfc_cleanup_pending_mbox(vport);
3440         spin_lock_irq(shost->host_lock);
3441         vport->fc_flag |= FC_VPORT_CVL_RCVD;
3442         spin_unlock_irq(shost->host_lock);
3443
3444         return ndlp;
3445 }
3446
3447 /**
3448  * lpfc_sli4_perform_all_vport_cvl - Perform clear virtual link on all vports
3449  * @vport: pointer to lpfc hba data structure.
3450  *
3451  * This routine is to perform Clear Virtual Link (CVL) on all vports in
3452  * response to a FCF dead event.
3453  **/
3454 static void
3455 lpfc_sli4_perform_all_vport_cvl(struct lpfc_hba *phba)
3456 {
3457         struct lpfc_vport **vports;
3458         int i;
3459
3460         vports = lpfc_create_vport_work_array(phba);
3461         if (vports)
3462                 for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++)
3463                         lpfc_sli4_perform_vport_cvl(vports[i]);
3464         lpfc_destroy_vport_work_array(phba, vports);
3465 }
3466
3467 /**
3468  * lpfc_sli4_async_fip_evt - Process the asynchronous FCoE FIP event
3469  * @phba: pointer to lpfc hba data structure.
3470  * @acqe_link: pointer to the async fcoe completion queue entry.
3471  *
3472  * This routine is to handle the SLI4 asynchronous fcoe event.
3473  **/
3474 static void
3475 lpfc_sli4_async_fip_evt(struct lpfc_hba *phba,
3476                         struct lpfc_acqe_fip *acqe_fip)
3477 {
3478         uint8_t event_type = bf_get(lpfc_trailer_type, acqe_fip);
3479         int rc;
3480         struct lpfc_vport *vport;
3481         struct lpfc_nodelist *ndlp;
3482         struct Scsi_Host  *shost;
3483         int active_vlink_present;
3484         struct lpfc_vport **vports;
3485         int i;
3486
3487         phba->fc_eventTag = acqe_fip->event_tag;
3488         phba->fcoe_eventtag = acqe_fip->event_tag;
3489         switch (event_type) {
3490         case LPFC_FIP_EVENT_TYPE_NEW_FCF:
3491         case LPFC_FIP_EVENT_TYPE_FCF_PARAM_MOD:
3492                 if (event_type == LPFC_FIP_EVENT_TYPE_NEW_FCF)
3493                         lpfc_printf_log(phba, KERN_ERR, LOG_FIP |
3494                                         LOG_DISCOVERY,
3495                                         "2546 New FCF event, evt_tag:x%x, "
3496                                         "index:x%x\n",
3497                                         acqe_fip->event_tag,
3498                                         acqe_fip->index);
3499                 else
3500                         lpfc_printf_log(phba, KERN_WARNING, LOG_FIP |
3501                                         LOG_DISCOVERY,
3502                                         "2788 FCF param modified event, "
3503                                         "evt_tag:x%x, index:x%x\n",
3504                                         acqe_fip->event_tag,
3505                                         acqe_fip->index);
3506                 if (phba->fcf.fcf_flag & FCF_DISCOVERY) {
3507                         /*
3508                          * During period of FCF discovery, read the FCF
3509                          * table record indexed by the event to update
3510                          * FCF roundrobin failover eligible FCF bmask.
3511                          */
3512                         lpfc_printf_log(phba, KERN_INFO, LOG_FIP |
3513                                         LOG_DISCOVERY,
3514                                         "2779 Read FCF (x%x) for updating "
3515                                         "roundrobin FCF failover bmask\n",
3516                                         acqe_fip->index);
3517                         rc = lpfc_sli4_read_fcf_rec(phba, acqe_fip->index);
3518                 }
3519
3520                 /* If the FCF discovery is in progress, do nothing. */
3521                 spin_lock_irq(&phba->hbalock);
3522                 if (phba->hba_flag & FCF_TS_INPROG) {
3523                         spin_unlock_irq(&phba->hbalock);
3524                         break;
3525                 }
3526                 /* If fast FCF failover rescan event is pending, do nothing */
3527                 if (phba->fcf.fcf_flag & FCF_REDISC_EVT) {
3528                         spin_unlock_irq(&phba->hbalock);
3529                         break;
3530                 }
3531
3532                 /* If the FCF has been in discovered state, do nothing. */
3533                 if (phba->fcf.fcf_flag & FCF_SCAN_DONE) {
3534                         spin_unlock_irq(&phba->hbalock);
3535                         break;
3536                 }
3537                 spin_unlock_irq(&phba->hbalock);
3538
3539                 /* Otherwise, scan the entire FCF table and re-discover SAN */
3540                 lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
3541                                 "2770 Start FCF table scan per async FCF "
3542                                 "event, evt_tag:x%x, index:x%x\n",
3543                                 acqe_fip->event_tag, acqe_fip->index);
3544                 rc = lpfc_sli4_fcf_scan_read_fcf_rec(phba,
3545                                                      LPFC_FCOE_FCF_GET_FIRST);
3546                 if (rc)
3547                         lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_DISCOVERY,
3548                                         "2547 Issue FCF scan read FCF mailbox "
3549                                         "command failed (x%x)\n", rc);
3550                 break;
3551
3552         case LPFC_FIP_EVENT_TYPE_FCF_TABLE_FULL:
3553                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3554                         "2548 FCF Table full count 0x%x tag 0x%x\n",
3555                         bf_get(lpfc_acqe_fip_fcf_count, acqe_fip),
3556                         acqe_fip->event_tag);
3557                 break;
3558
3559         case LPFC_FIP_EVENT_TYPE_FCF_DEAD:
3560                 lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_DISCOVERY,
3561                         "2549 FCF (x%x) disconnected from network, "
3562                         "tag:x%x\n", acqe_fip->index, acqe_fip->event_tag);
3563                 /*
3564                  * If we are in the middle of FCF failover process, clear
3565                  * the corresponding FCF bit in the roundrobin bitmap.
3566                  */
3567                 spin_lock_irq(&phba->hbalock);
3568                 if (phba->fcf.fcf_flag & FCF_DISCOVERY) {
3569                         spin_unlock_irq(&phba->hbalock);
3570                         /* Update FLOGI FCF failover eligible FCF bmask */
3571                         lpfc_sli4_fcf_rr_index_clear(phba, acqe_fip->index);
3572                         break;
3573                 }
3574                 spin_unlock_irq(&phba->hbalock);
3575
3576                 /* If the event is not for currently used fcf do nothing */
3577                 if (phba->fcf.current_rec.fcf_indx != acqe_fip->index)
3578                         break;
3579
3580                 /*
3581                  * Otherwise, request the port to rediscover the entire FCF
3582                  * table for a fast recovery from case that the current FCF
3583                  * is no longer valid as we are not in the middle of FCF
3584                  * failover process already.
3585                  */
3586                 spin_lock_irq(&phba->hbalock);
3587                 /* Mark the fast failover process in progress */
3588                 phba->fcf.fcf_flag |= FCF_DEAD_DISC;
3589                 spin_unlock_irq(&phba->hbalock);
3590
3591                 lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
3592                                 "2771 Start FCF fast failover process due to "
3593                                 "FCF DEAD event: evt_tag:x%x, fcf_index:x%x "
3594                                 "\n", acqe_fip->event_tag, acqe_fip->index);
3595                 rc = lpfc_sli4_redisc_fcf_table(phba);
3596                 if (rc) {
3597                         lpfc_printf_log(phba, KERN_ERR, LOG_FIP |
3598                                         LOG_DISCOVERY,
3599                                         "2772 Issue FCF rediscover mabilbox "
3600                                         "command failed, fail through to FCF "
3601                                         "dead event\n");
3602                         spin_lock_irq(&phba->hbalock);
3603                         phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
3604                         spin_unlock_irq(&phba->hbalock);
3605                         /*
3606                          * Last resort will fail over by treating this
3607                          * as a link down to FCF registration.
3608                          */
3609                         lpfc_sli4_fcf_dead_failthrough(phba);
3610                 } else {
3611                         /* Reset FCF roundrobin bmask for new discovery */
3612                         memset(phba->fcf.fcf_rr_bmask, 0,
3613                                sizeof(*phba->fcf.fcf_rr_bmask));
3614                         /*
3615                          * Handling fast FCF failover to a DEAD FCF event is
3616                          * considered equalivant to receiving CVL to all vports.
3617                          */
3618                         lpfc_sli4_perform_all_vport_cvl(phba);
3619                 }
3620                 break;
3621         case LPFC_FIP_EVENT_TYPE_CVL:
3622                 lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_DISCOVERY,
3623                         "2718 Clear Virtual Link Received for VPI 0x%x"
3624                         " tag 0x%x\n", acqe_fip->index, acqe_fip->event_tag);
3625                 vport = lpfc_find_vport_by_vpid(phba,
3626                                 acqe_fip->index - phba->vpi_base);
3627                 ndlp = lpfc_sli4_perform_vport_cvl(vport);
3628                 if (!ndlp)
3629                         break;
3630                 active_vlink_present = 0;
3631
3632                 vports = lpfc_create_vport_work_array(phba);
3633                 if (vports) {
3634                         for (i = 0; i <= phba->max_vports && vports[i] != NULL;
3635                                         i++) {
3636                                 if ((!(vports[i]->fc_flag &
3637                                         FC_VPORT_CVL_RCVD)) &&
3638                                         (vports[i]->port_state > LPFC_FDISC)) {
3639                                         active_vlink_present = 1;
3640                                         break;
3641                                 }
3642                         }
3643                         lpfc_destroy_vport_work_array(phba, vports);
3644                 }
3645
3646                 if (active_vlink_present) {
3647                         /*
3648                          * If there are other active VLinks present,
3649                          * re-instantiate the Vlink using FDISC.
3650                          */
3651                         mod_timer(&ndlp->nlp_delayfunc, jiffies + HZ);
3652                         shost = lpfc_shost_from_vport(vport);
3653                         spin_lock_irq(shost->host_lock);
3654                         ndlp->nlp_flag |= NLP_DELAY_TMO;
3655                         spin_unlock_irq(shost->host_lock);
3656                         ndlp->nlp_last_elscmd = ELS_CMD_FDISC;
3657                         vport->port_state = LPFC_FDISC;
3658                 } else {
3659                         /*
3660                          * Otherwise, we request port to rediscover
3661                          * the entire FCF table for a fast recovery
3662                          * from possible case that the current FCF
3663                          * is no longer valid if we are not already
3664                          * in the FCF failover process.
3665                          */
3666                         spin_lock_irq(&phba->hbalock);
3667                         if (phba->fcf.fcf_flag & FCF_DISCOVERY) {
3668                                 spin_unlock_irq(&phba->hbalock);
3669                                 break;
3670                         }
3671                         /* Mark the fast failover process in progress */
3672                         phba->fcf.fcf_flag |= FCF_ACVL_DISC;
3673                         spin_unlock_irq(&phba->hbalock);
3674                         lpfc_printf_log(phba, KERN_INFO, LOG_FIP |
3675                                         LOG_DISCOVERY,
3676                                         "2773 Start FCF failover per CVL, "
3677                                         "evt_tag:x%x\n", acqe_fip->event_tag);
3678                         rc = lpfc_sli4_redisc_fcf_table(phba);
3679                         if (rc) {
3680                                 lpfc_printf_log(phba, KERN_ERR, LOG_FIP |
3681                                                 LOG_DISCOVERY,
3682                                                 "2774 Issue FCF rediscover "
3683                                                 "mabilbox command failed, "
3684                                                 "through to CVL event\n");
3685                                 spin_lock_irq(&phba->hbalock);
3686                                 phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
3687                                 spin_unlock_irq(&phba->hbalock);
3688                                 /*
3689                                  * Last resort will be re-try on the
3690                                  * the current registered FCF entry.
3691                                  */
3692                                 lpfc_retry_pport_discovery(phba);
3693                         } else
3694                                 /*
3695                                  * Reset FCF roundrobin bmask for new
3696                                  * discovery.
3697                                  */
3698                                 memset(phba->fcf.fcf_rr_bmask, 0,
3699                                        sizeof(*phba->fcf.fcf_rr_bmask));
3700                 }
3701                 break;
3702         default:
3703                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3704                         "0288 Unknown FCoE event type 0x%x event tag "
3705                         "0x%x\n", event_type, acqe_fip->event_tag);
3706                 break;
3707         }
3708 }
3709
3710 /**
3711  * lpfc_sli4_async_dcbx_evt - Process the asynchronous dcbx event
3712  * @phba: pointer to lpfc hba data structure.
3713  * @acqe_link: pointer to the async dcbx completion queue entry.
3714  *
3715  * This routine is to handle the SLI4 asynchronous dcbx event.
3716  **/
3717 static void
3718 lpfc_sli4_async_dcbx_evt(struct lpfc_hba *phba,
3719                          struct lpfc_acqe_dcbx *acqe_dcbx)
3720 {
3721         phba->fc_eventTag = acqe_dcbx->event_tag;
3722         lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3723                         "0290 The SLI4 DCBX asynchronous event is not "
3724                         "handled yet\n");
3725 }
3726
3727 /**
3728  * lpfc_sli4_async_grp5_evt - Process the asynchronous group5 event
3729  * @phba: pointer to lpfc hba data structure.
3730  * @acqe_link: pointer to the async grp5 completion queue entry.
3731  *
3732  * This routine is to handle the SLI4 asynchronous grp5 event. A grp5 event
3733  * is an asynchronous notified of a logical link speed change.  The Port
3734  * reports the logical link speed in units of 10Mbps.
3735  **/
3736 static void
3737 lpfc_sli4_async_grp5_evt(struct lpfc_hba *phba,
3738                          struct lpfc_acqe_grp5 *acqe_grp5)
3739 {
3740         uint16_t prev_ll_spd;
3741
3742         phba->fc_eventTag = acqe_grp5->event_tag;
3743         phba->fcoe_eventtag = acqe_grp5->event_tag;
3744         prev_ll_spd = phba->sli4_hba.link_state.logical_speed;
3745         phba->sli4_hba.link_state.logical_speed =
3746                 (bf_get(lpfc_acqe_grp5_llink_spd, acqe_grp5));
3747         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3748                         "2789 GRP5 Async Event: Updating logical link speed "
3749                         "from %dMbps to %dMbps\n", (prev_ll_spd * 10),
3750                         (phba->sli4_hba.link_state.logical_speed*10));
3751 }
3752
3753 /**
3754  * lpfc_sli4_async_event_proc - Process all the pending asynchronous event
3755  * @phba: pointer to lpfc hba data structure.
3756  *
3757  * This routine is invoked by the worker thread to process all the pending
3758  * SLI4 asynchronous events.
3759  **/
3760 void lpfc_sli4_async_event_proc(struct lpfc_hba *phba)
3761 {
3762         struct lpfc_cq_event *cq_event;
3763
3764         /* First, declare the async event has been handled */
3765         spin_lock_irq(&phba->hbalock);
3766         phba->hba_flag &= ~ASYNC_EVENT;
3767         spin_unlock_irq(&phba->hbalock);
3768         /* Now, handle all the async events */
3769         while (!list_empty(&phba->sli4_hba.sp_asynce_work_queue)) {
3770                 /* Get the first event from the head of the event queue */
3771                 spin_lock_irq(&phba->hbalock);
3772                 list_remove_head(&phba->sli4_hba.sp_asynce_work_queue,
3773                                  cq_event, struct lpfc_cq_event, list);
3774                 spin_unlock_irq(&phba->hbalock);
3775                 /* Process the asynchronous event */
3776                 switch (bf_get(lpfc_trailer_code, &cq_event->cqe.mcqe_cmpl)) {
3777                 case LPFC_TRAILER_CODE_LINK:
3778                         lpfc_sli4_async_link_evt(phba,
3779                                                  &cq_event->cqe.acqe_link);
3780                         break;
3781                 case LPFC_TRAILER_CODE_FCOE:
3782                         lpfc_sli4_async_fip_evt(phba, &cq_event->cqe.acqe_fip);
3783                         break;
3784                 case LPFC_TRAILER_CODE_DCBX:
3785                         lpfc_sli4_async_dcbx_evt(phba,
3786                                                  &cq_event->cqe.acqe_dcbx);
3787                         break;
3788                 case LPFC_TRAILER_CODE_GRP5:
3789                         lpfc_sli4_async_grp5_evt(phba,
3790                                                  &cq_event->cqe.acqe_grp5);
3791                         break;
3792                 case LPFC_TRAILER_CODE_FC:
3793                         lpfc_sli4_async_fc_evt(phba, &cq_event->cqe.acqe_fc);
3794                         break;
3795                 case LPFC_TRAILER_CODE_SLI:
3796                         lpfc_sli4_async_sli_evt(phba, &cq_event->cqe.acqe_sli);
3797                         break;
3798                 default:
3799                         lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3800                                         "1804 Invalid asynchrous event code: "
3801                                         "x%x\n", bf_get(lpfc_trailer_code,
3802                                         &cq_event->cqe.mcqe_cmpl));
3803                         break;
3804                 }
3805                 /* Free the completion event processed to the free pool */
3806                 lpfc_sli4_cq_event_release(phba, cq_event);
3807         }
3808 }
3809
3810 /**
3811  * lpfc_sli4_fcf_redisc_event_proc - Process fcf table rediscovery event
3812  * @phba: pointer to lpfc hba data structure.
3813  *
3814  * This routine is invoked by the worker thread to process FCF table
3815  * rediscovery pending completion event.
3816  **/
3817 void lpfc_sli4_fcf_redisc_event_proc(struct lpfc_hba *phba)
3818 {
3819         int rc;
3820
3821         spin_lock_irq(&phba->hbalock);
3822         /* Clear FCF rediscovery timeout event */
3823         phba->fcf.fcf_flag &= ~FCF_REDISC_EVT;
3824         /* Clear driver fast failover FCF record flag */
3825         phba->fcf.failover_rec.flag = 0;
3826         /* Set state for FCF fast failover */
3827         phba->fcf.fcf_flag |= FCF_REDISC_FOV;
3828         spin_unlock_irq(&phba->hbalock);
3829
3830         /* Scan FCF table from the first entry to re-discover SAN */
3831         lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
3832                         "2777 Start post-quiescent FCF table scan\n");
3833         rc = lpfc_sli4_fcf_scan_read_fcf_rec(phba, LPFC_FCOE_FCF_GET_FIRST);
3834         if (rc)
3835                 lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_DISCOVERY,
3836                                 "2747 Issue FCF scan read FCF mailbox "
3837                                 "command failed 0x%x\n", rc);
3838 }
3839
3840 /**
3841  * lpfc_api_table_setup - Set up per hba pci-device group func api jump table
3842  * @phba: pointer to lpfc hba data structure.
3843  * @dev_grp: The HBA PCI-Device group number.
3844  *
3845  * This routine is invoked to set up the per HBA PCI-Device group function
3846  * API jump table entries.
3847  *
3848  * Return: 0 if success, otherwise -ENODEV
3849  **/
3850 int
3851 lpfc_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
3852 {
3853         int rc;
3854
3855         /* Set up lpfc PCI-device group */
3856         phba->pci_dev_grp = dev_grp;
3857
3858         /* The LPFC_PCI_DEV_OC uses SLI4 */
3859         if (dev_grp == LPFC_PCI_DEV_OC)
3860                 phba->sli_rev = LPFC_SLI_REV4;
3861
3862         /* Set up device INIT API function jump table */
3863         rc = lpfc_init_api_table_setup(phba, dev_grp);
3864         if (rc)
3865                 return -ENODEV;
3866         /* Set up SCSI API function jump table */
3867         rc = lpfc_scsi_api_table_setup(phba, dev_grp);
3868         if (rc)
3869                 return -ENODEV;
3870         /* Set up SLI API function jump table */
3871         rc = lpfc_sli_api_table_setup(phba, dev_grp);
3872         if (rc)
3873                 return -ENODEV;
3874         /* Set up MBOX API function jump table */
3875         rc = lpfc_mbox_api_table_setup(phba, dev_grp);
3876         if (rc)
3877                 return -ENODEV;
3878
3879         return 0;
3880 }
3881
3882 /**
3883  * lpfc_log_intr_mode - Log the active interrupt mode
3884  * @phba: pointer to lpfc hba data structure.
3885  * @intr_mode: active interrupt mode adopted.
3886  *
3887  * This routine it invoked to log the currently used active interrupt mode
3888  * to the device.
3889  **/
3890 static void lpfc_log_intr_mode(struct lpfc_hba *phba, uint32_t intr_mode)
3891 {
3892         switch (intr_mode) {
3893         case 0:
3894                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3895                                 "0470 Enable INTx interrupt mode.\n");
3896                 break;
3897         case 1:
3898                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3899                                 "0481 Enabled MSI interrupt mode.\n");
3900                 break;
3901         case 2:
3902                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3903                                 "0480 Enabled MSI-X interrupt mode.\n");
3904                 break;
3905         default:
3906                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
3907                                 "0482 Illegal interrupt mode.\n");
3908                 break;
3909         }
3910         return;
3911 }
3912
3913 /**
3914  * lpfc_enable_pci_dev - Enable a generic PCI device.
3915  * @phba: pointer to lpfc hba data structure.
3916  *
3917  * This routine is invoked to enable the PCI device that is common to all
3918  * PCI devices.
3919  *
3920  * Return codes
3921  *      0 - successful
3922  *      other values - error
3923  **/
3924 static int
3925 lpfc_enable_pci_dev(struct lpfc_hba *phba)
3926 {
3927         struct pci_dev *pdev;
3928         int bars;
3929
3930         /* Obtain PCI device reference */
3931         if (!phba->pcidev)
3932                 goto out_error;
3933         else
3934                 pdev = phba->pcidev;
3935         /* Select PCI BARs */
3936         bars = pci_select_bars(pdev, IORESOURCE_MEM);
3937         /* Enable PCI device */
3938         if (pci_enable_device_mem(pdev))
3939                 goto out_error;
3940         /* Request PCI resource for the device */
3941         if (pci_request_selected_regions(pdev, bars, LPFC_DRIVER_NAME))
3942                 goto out_disable_device;
3943         /* Set up device as PCI master and save state for EEH */
3944         pci_set_master(pdev);
3945         pci_try_set_mwi(pdev);
3946         pci_save_state(pdev);
3947
3948         return 0;
3949
3950 out_disable_device:
3951         pci_disable_device(pdev);
3952 out_error:
3953         return -ENODEV;
3954 }
3955
3956 /**
3957  * lpfc_disable_pci_dev - Disable a generic PCI device.
3958  * @phba: pointer to lpfc hba data structure.
3959  *
3960  * This routine is invoked to disable the PCI device that is common to all
3961  * PCI devices.
3962  **/
3963 static void
3964 lpfc_disable_pci_dev(struct lpfc_hba *phba)
3965 {
3966         struct pci_dev *pdev;
3967         int bars;
3968
3969         /* Obtain PCI device reference */
3970         if (!phba->pcidev)
3971                 return;
3972         else
3973                 pdev = phba->pcidev;
3974         /* Select PCI BARs */
3975         bars = pci_select_bars(pdev, IORESOURCE_MEM);
3976         /* Release PCI resource and disable PCI device */
3977         pci_release_selected_regions(pdev, bars);
3978         pci_disable_device(pdev);
3979         /* Null out PCI private reference to driver */
3980         pci_set_drvdata(pdev, NULL);
3981
3982         return;
3983 }
3984
3985 /**
3986  * lpfc_reset_hba - Reset a hba
3987  * @phba: pointer to lpfc hba data structure.
3988  *
3989  * This routine is invoked to reset a hba device. It brings the HBA
3990  * offline, performs a board restart, and then brings the board back
3991  * online. The lpfc_offline calls lpfc_sli_hba_down which will clean up
3992  * on outstanding mailbox commands.
3993  **/
3994 void
3995 lpfc_reset_hba(struct lpfc_hba *phba)
3996 {
3997         /* If resets are disabled then set error state and return. */
3998         if (!phba->cfg_enable_hba_reset) {
3999                 phba->link_state = LPFC_HBA_ERROR;
4000                 return;
4001         }
4002         lpfc_offline_prep(phba);
4003         lpfc_offline(phba);
4004         lpfc_sli_brdrestart(phba);
4005         lpfc_online(phba);
4006         lpfc_unblock_mgmt_io(phba);
4007 }
4008
4009 /**
4010  * lpfc_sli_driver_resource_setup - Setup driver internal resources for SLI3 dev.
4011  * @phba: pointer to lpfc hba data structure.
4012  *
4013  * This routine is invoked to set up the driver internal resources specific to
4014  * support the SLI-3 HBA device it attached to.
4015  *
4016  * Return codes
4017  *      0 - successful
4018  *      other values - error
4019  **/
4020 static int
4021 lpfc_sli_driver_resource_setup(struct lpfc_hba *phba)
4022 {
4023         struct lpfc_sli *psli;
4024
4025         /*
4026          * Initialize timers used by driver
4027          */
4028
4029         /* Heartbeat timer */
4030         init_timer(&phba->hb_tmofunc);
4031         phba->hb_tmofunc.function = lpfc_hb_timeout;
4032         phba->hb_tmofunc.data = (unsigned long)phba;
4033
4034         psli = &phba->sli;
4035         /* MBOX heartbeat timer */
4036         init_timer(&psli->mbox_tmo);
4037         psli->mbox_tmo.function = lpfc_mbox_timeout;
4038         psli->mbox_tmo.data = (unsigned long) phba;
4039         /* FCP polling mode timer */
4040         init_timer(&phba->fcp_poll_timer);
4041         phba->fcp_poll_timer.function = lpfc_poll_timeout;
4042         phba->fcp_poll_timer.data = (unsigned long) phba;
4043         /* Fabric block timer */
4044         init_timer(&phba->fabric_block_timer);
4045         phba->fabric_block_timer.function = lpfc_fabric_block_timeout;
4046         phba->fabric_block_timer.data = (unsigned long) phba;
4047         /* EA polling mode timer */
4048         init_timer(&phba->eratt_poll);
4049         phba->eratt_poll.function = lpfc_poll_eratt;
4050         phba->eratt_poll.data = (unsigned long) phba;
4051
4052         /* Host attention work mask setup */
4053         phba->work_ha_mask = (HA_ERATT | HA_MBATT | HA_LATT);
4054         phba->work_ha_mask |= (HA_RXMASK << (LPFC_ELS_RING * 4));
4055
4056         /* Get all the module params for configuring this host */
4057         lpfc_get_cfgparam(phba);
4058         if (phba->pcidev->device == PCI_DEVICE_ID_HORNET) {
4059                 phba->menlo_flag |= HBA_MENLO_SUPPORT;
4060                 /* check for menlo minimum sg count */
4061                 if (phba->cfg_sg_seg_cnt < LPFC_DEFAULT_MENLO_SG_SEG_CNT)
4062                         phba->cfg_sg_seg_cnt = LPFC_DEFAULT_MENLO_SG_SEG_CNT;
4063         }
4064
4065         /*
4066          * Since the sg_tablesize is module parameter, the sg_dma_buf_size
4067          * used to create the sg_dma_buf_pool must be dynamically calculated.
4068          * 2 segments are added since the IOCB needs a command and response bde.
4069          */
4070         phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd) +
4071                 sizeof(struct fcp_rsp) +
4072                         ((phba->cfg_sg_seg_cnt + 2) * sizeof(struct ulp_bde64));
4073
4074         if (phba->cfg_enable_bg) {
4075                 phba->cfg_sg_seg_cnt = LPFC_MAX_SG_SEG_CNT;
4076                 phba->cfg_sg_dma_buf_size +=
4077                         phba->cfg_prot_sg_seg_cnt * sizeof(struct ulp_bde64);
4078         }
4079
4080         /* Also reinitialize the host templates with new values. */
4081         lpfc_vport_template.sg_tablesize = phba->cfg_sg_seg_cnt;
4082         lpfc_template.sg_tablesize = phba->cfg_sg_seg_cnt;
4083
4084         phba->max_vpi = LPFC_MAX_VPI;
4085         /* This will be set to correct value after config_port mbox */
4086         phba->max_vports = 0;
4087
4088         /*
4089          * Initialize the SLI Layer to run with lpfc HBAs.
4090          */
4091         lpfc_sli_setup(phba);
4092         lpfc_sli_queue_setup(phba);
4093
4094         /* Allocate device driver memory */
4095         if (lpfc_mem_alloc(phba, BPL_ALIGN_SZ))
4096                 return -ENOMEM;
4097
4098         return 0;
4099 }
4100
4101 /**
4102  * lpfc_sli_driver_resource_unset - Unset drvr internal resources for SLI3 dev
4103  * @phba: pointer to lpfc hba data structure.
4104  *
4105  * This routine is invoked to unset the driver internal resources set up
4106  * specific for supporting the SLI-3 HBA device it attached to.
4107  **/
4108 static void
4109 lpfc_sli_driver_resource_unset(struct lpfc_hba *phba)
4110 {
4111         /* Free device driver memory allocated */
4112         lpfc_mem_free_all(phba);
4113
4114         return;
4115 }
4116
4117 /**
4118  * lpfc_sli4_driver_resource_setup - Setup drvr internal resources for SLI4 dev
4119  * @phba: pointer to lpfc hba data structure.
4120  *
4121  * This routine is invoked to set up the driver internal resources specific to
4122  * support the SLI-4 HBA device it attached to.
4123  *
4124  * Return codes
4125  *      0 - successful
4126  *      other values - error
4127  **/
4128 static int
4129 lpfc_sli4_driver_resource_setup(struct lpfc_hba *phba)
4130 {
4131         struct lpfc_sli *psli;
4132         LPFC_MBOXQ_t *mboxq;
4133         int rc, i, hbq_count, buf_size, dma_buf_size, max_buf_size;
4134         uint8_t pn_page[LPFC_MAX_SUPPORTED_PAGES] = {0};
4135         struct lpfc_mqe *mqe;
4136         int longs, sli_family;
4137
4138         /* Before proceed, wait for POST done and device ready */
4139         rc = lpfc_sli4_post_status_check(phba);
4140         if (rc)
4141                 return -ENODEV;
4142
4143         /*
4144          * Initialize timers used by driver
4145          */
4146
4147         /* Heartbeat timer */
4148         init_timer(&phba->hb_tmofunc);
4149         phba->hb_tmofunc.function = lpfc_hb_timeout;
4150         phba->hb_tmofunc.data = (unsigned long)phba;
4151         init_timer(&phba->rrq_tmr);
4152         phba->rrq_tmr.function = lpfc_rrq_timeout;
4153         phba->rrq_tmr.data = (unsigned long)phba;
4154
4155         psli = &phba->sli;
4156         /* MBOX heartbeat timer */
4157         init_timer(&psli->mbox_tmo);
4158         psli->mbox_tmo.function = lpfc_mbox_timeout;
4159         psli->mbox_tmo.data = (unsigned long) phba;
4160         /* Fabric block timer */
4161         init_timer(&phba->fabric_block_timer);
4162         phba->fabric_block_timer.function = lpfc_fabric_block_timeout;
4163         phba->fabric_block_timer.data = (unsigned long) phba;
4164         /* EA polling mode timer */
4165         init_timer(&phba->eratt_poll);
4166         phba->eratt_poll.function = lpfc_poll_eratt;
4167         phba->eratt_poll.data = (unsigned long) phba;
4168         /* FCF rediscover timer */
4169         init_timer(&phba->fcf.redisc_wait);
4170         phba->fcf.redisc_wait.function = lpfc_sli4_fcf_redisc_wait_tmo;
4171         phba->fcf.redisc_wait.data = (unsigned long)phba;
4172
4173         /*
4174          * We need to do a READ_CONFIG mailbox command here before
4175          * calling lpfc_get_cfgparam. For VFs this will report the
4176          * MAX_XRI, MAX_VPI, MAX_RPI, MAX_IOCB, and MAX_VFI settings.
4177          * All of the resources allocated
4178          * for this Port are tied to these values.
4179          */
4180         /* Get all the module params for configuring this host */
4181         lpfc_get_cfgparam(phba);
4182         phba->max_vpi = LPFC_MAX_VPI;
4183         /* This will be set to correct value after the read_config mbox */
4184         phba->max_vports = 0;
4185
4186         /* Program the default value of vlan_id and fc_map */
4187         phba->valid_vlan = 0;
4188         phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
4189         phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
4190         phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
4191
4192         /*
4193          * Since the sg_tablesize is module parameter, the sg_dma_buf_size
4194          * used to create the sg_dma_buf_pool must be dynamically calculated.
4195          * 2 segments are added since the IOCB needs a command and response bde.
4196          * To insure that the scsi sgl does not cross a 4k page boundary only
4197          * sgl sizes of must be a power of 2.
4198          */
4199         buf_size = (sizeof(struct fcp_cmnd) + sizeof(struct fcp_rsp) +
4200                     ((phba->cfg_sg_seg_cnt + 2) * sizeof(struct sli4_sge)));
4201
4202         sli_family = bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf);
4203         max_buf_size = LPFC_SLI4_MAX_BUF_SIZE;
4204         switch (sli_family) {
4205         case LPFC_SLI_INTF_FAMILY_BE2:
4206         case LPFC_SLI_INTF_FAMILY_BE3:
4207                 /* There is a single hint for BE - 2 pages per BPL. */
4208                 if (bf_get(lpfc_sli_intf_sli_hint1, &phba->sli4_hba.sli_intf) ==
4209                     LPFC_SLI_INTF_SLI_HINT1_1)
4210                         max_buf_size = LPFC_SLI4_FL1_MAX_BUF_SIZE;
4211                 break;
4212         case LPFC_SLI_INTF_FAMILY_LNCR_A0:
4213         case LPFC_SLI_INTF_FAMILY_LNCR_B0:
4214         default:
4215                 break;
4216         }
4217         for (dma_buf_size = LPFC_SLI4_MIN_BUF_SIZE;
4218              dma_buf_size < max_buf_size && buf_size > dma_buf_size;
4219              dma_buf_size = dma_buf_size << 1)
4220                 ;
4221         if (dma_buf_size == max_buf_size)
4222                 phba->cfg_sg_seg_cnt = (dma_buf_size -
4223                         sizeof(struct fcp_cmnd) - sizeof(struct fcp_rsp) -
4224                         (2 * sizeof(struct sli4_sge))) /
4225                                 sizeof(struct sli4_sge);
4226         phba->cfg_sg_dma_buf_size = dma_buf_size;
4227
4228         /* Initialize buffer queue management fields */
4229         hbq_count = lpfc_sli_hbq_count();
4230         for (i = 0; i < hbq_count; ++i)
4231                 INIT_LIST_HEAD(&phba->hbqs[i].hbq_buffer_list);
4232         INIT_LIST_HEAD(&phba->rb_pend_list);
4233         phba->hbqs[LPFC_ELS_HBQ].hbq_alloc_buffer = lpfc_sli4_rb_alloc;
4234         phba->hbqs[LPFC_ELS_HBQ].hbq_free_buffer = lpfc_sli4_rb_free;
4235
4236         /*
4237          * Initialize the SLI Layer to run with lpfc SLI4 HBAs.
4238          */
4239         /* Initialize the Abort scsi buffer list used by driver */
4240         spin_lock_init(&phba->sli4_hba.abts_scsi_buf_list_lock);
4241         INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_scsi_buf_list);
4242         /* This abort list used by worker thread */
4243         spin_lock_init(&phba->sli4_hba.abts_sgl_list_lock);
4244
4245         /*
4246          * Initialize dirver internal slow-path work queues
4247          */
4248
4249         /* Driver internel slow-path CQ Event pool */
4250         INIT_LIST_HEAD(&phba->sli4_hba.sp_cqe_event_pool);
4251         /* Response IOCB work queue list */
4252         INIT_LIST_HEAD(&phba->sli4_hba.sp_queue_event);
4253         /* Asynchronous event CQ Event work queue list */
4254         INIT_LIST_HEAD(&phba->sli4_hba.sp_asynce_work_queue);
4255         /* Fast-path XRI aborted CQ Event work queue list */
4256         INIT_LIST_HEAD(&phba->sli4_hba.sp_fcp_xri_aborted_work_queue);
4257         /* Slow-path XRI aborted CQ Event work queue list */
4258         INIT_LIST_HEAD(&phba->sli4_hba.sp_els_xri_aborted_work_queue);
4259         /* Receive queue CQ Event work queue list */
4260         INIT_LIST_HEAD(&phba->sli4_hba.sp_unsol_work_queue);
4261
4262         /* Initialize the driver internal SLI layer lists. */
4263         lpfc_sli_setup(phba);
4264         lpfc_sli_queue_setup(phba);
4265
4266         /* Allocate device driver memory */
4267         rc = lpfc_mem_alloc(phba, SGL_ALIGN_SZ);
4268         if (rc)
4269                 return -ENOMEM;
4270
4271         /* Create the bootstrap mailbox command */
4272         rc = lpfc_create_bootstrap_mbox(phba);
4273         if (unlikely(rc))
4274                 goto out_free_mem;
4275
4276         /* Set up the host's endian order with the device. */
4277         rc = lpfc_setup_endian_order(phba);
4278         if (unlikely(rc))
4279                 goto out_free_bsmbx;
4280
4281         rc = lpfc_sli4_fw_cfg_check(phba);
4282         if (unlikely(rc))
4283                 goto out_free_bsmbx;
4284
4285         /* Set up the hba's configuration parameters. */
4286         rc = lpfc_sli4_read_config(phba);
4287         if (unlikely(rc))
4288                 goto out_free_bsmbx;
4289
4290         /* Perform a function reset */
4291         rc = lpfc_pci_function_reset(phba);
4292         if (unlikely(rc))
4293                 goto out_free_bsmbx;
4294
4295         mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
4296                                                        GFP_KERNEL);
4297         if (!mboxq) {
4298                 rc = -ENOMEM;
4299                 goto out_free_bsmbx;
4300         }
4301
4302         /* Get the Supported Pages. It is always available. */
4303         lpfc_supported_pages(mboxq);
4304         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
4305         if (unlikely(rc)) {
4306                 rc = -EIO;
4307                 mempool_free(mboxq, phba->mbox_mem_pool);
4308                 goto out_free_bsmbx;
4309         }
4310
4311         mqe = &mboxq->u.mqe;
4312         memcpy(&pn_page[0], ((uint8_t *)&mqe->un.supp_pages.word3),
4313                LPFC_MAX_SUPPORTED_PAGES);
4314         for (i = 0; i < LPFC_MAX_SUPPORTED_PAGES; i++) {
4315                 switch (pn_page[i]) {
4316                 case LPFC_SLI4_PARAMETERS:
4317                         phba->sli4_hba.pc_sli4_params.supported = 1;
4318                         break;
4319                 default:
4320                         break;
4321                 }
4322         }
4323
4324         /* Read the port's SLI4 Parameters capabilities if supported. */
4325         if (phba->sli4_hba.pc_sli4_params.supported)
4326                 rc = lpfc_pc_sli4_params_get(phba, mboxq);
4327         mempool_free(mboxq, phba->mbox_mem_pool);
4328         if (rc) {
4329                 rc = -EIO;
4330                 goto out_free_bsmbx;
4331         }
4332         /* Create all the SLI4 queues */
4333         rc = lpfc_sli4_queue_create(phba);
4334         if (rc)
4335                 goto out_free_bsmbx;
4336
4337         /* Create driver internal CQE event pool */
4338         rc = lpfc_sli4_cq_event_pool_create(phba);
4339         if (rc)
4340                 goto out_destroy_queue;
4341
4342         /* Initialize and populate the iocb list per host */
4343         rc = lpfc_init_sgl_list(phba);
4344         if (rc) {
4345                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4346                                 "1400 Failed to initialize sgl list.\n");
4347                 goto out_destroy_cq_event_pool;
4348         }
4349         rc = lpfc_init_active_sgl_array(phba);
4350         if (rc) {
4351                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4352                                 "1430 Failed to initialize sgl list.\n");
4353                 goto out_free_sgl_list;
4354         }
4355
4356         rc = lpfc_sli4_init_rpi_hdrs(phba);
4357         if (rc) {
4358                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4359                                 "1432 Failed to initialize rpi headers.\n");
4360                 goto out_free_active_sgl;
4361         }
4362
4363         /* Allocate eligible FCF bmask memory for FCF roundrobin failover */
4364         longs = (LPFC_SLI4_FCF_TBL_INDX_MAX + BITS_PER_LONG - 1)/BITS_PER_LONG;
4365         phba->fcf.fcf_rr_bmask = kzalloc(longs * sizeof(unsigned long),
4366                                          GFP_KERNEL);
4367         if (!phba->fcf.fcf_rr_bmask) {
4368                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4369                                 "2759 Failed allocate memory for FCF round "
4370                                 "robin failover bmask\n");
4371                 goto out_remove_rpi_hdrs;
4372         }
4373
4374         phba->sli4_hba.fcp_eq_hdl = kzalloc((sizeof(struct lpfc_fcp_eq_hdl) *
4375                                     phba->cfg_fcp_eq_count), GFP_KERNEL);
4376         if (!phba->sli4_hba.fcp_eq_hdl) {
4377                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4378                                 "2572 Failed allocate memory for fast-path "
4379                                 "per-EQ handle array\n");
4380                 goto out_free_fcf_rr_bmask;
4381         }
4382
4383         phba->sli4_hba.msix_entries = kzalloc((sizeof(struct msix_entry) *
4384                                       phba->sli4_hba.cfg_eqn), GFP_KERNEL);
4385         if (!phba->sli4_hba.msix_entries) {
4386                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4387                                 "2573 Failed allocate memory for msi-x "
4388                                 "interrupt vector entries\n");
4389                 goto out_free_fcp_eq_hdl;
4390         }
4391
4392         return rc;
4393
4394 out_free_fcp_eq_hdl:
4395         kfree(phba->sli4_hba.fcp_eq_hdl);
4396 out_free_fcf_rr_bmask:
4397         kfree(phba->fcf.fcf_rr_bmask);
4398 out_remove_rpi_hdrs:
4399         lpfc_sli4_remove_rpi_hdrs(phba);
4400 out_free_active_sgl:
4401         lpfc_free_active_sgl(phba);
4402 out_free_sgl_list:
4403         lpfc_free_sgl_list(phba);
4404 out_destroy_cq_event_pool:
4405         lpfc_sli4_cq_event_pool_destroy(phba);
4406 out_destroy_queue:
4407         lpfc_sli4_queue_destroy(phba);
4408 out_free_bsmbx:
4409         lpfc_destroy_bootstrap_mbox(phba);
4410 out_free_mem:
4411         lpfc_mem_free(phba);
4412         return rc;
4413 }
4414
4415 /**
4416  * lpfc_sli4_driver_resource_unset - Unset drvr internal resources for SLI4 dev
4417  * @phba: pointer to lpfc hba data structure.
4418  *
4419  * This routine is invoked to unset the driver internal resources set up
4420  * specific for supporting the SLI-4 HBA device it attached to.
4421  **/
4422 static void
4423 lpfc_sli4_driver_resource_unset(struct lpfc_hba *phba)
4424 {
4425         struct lpfc_fcf_conn_entry *conn_entry, *next_conn_entry;
4426
4427         /* Free memory allocated for msi-x interrupt vector entries */
4428         kfree(phba->sli4_hba.msix_entries);
4429
4430         /* Free memory allocated for fast-path work queue handles */
4431         kfree(phba->sli4_hba.fcp_eq_hdl);
4432
4433         /* Free the allocated rpi headers. */
4434         lpfc_sli4_remove_rpi_hdrs(phba);
4435         lpfc_sli4_remove_rpis(phba);
4436
4437         /* Free eligible FCF index bmask */
4438         kfree(phba->fcf.fcf_rr_bmask);
4439
4440         /* Free the ELS sgl list */
4441         lpfc_free_active_sgl(phba);
4442         lpfc_free_sgl_list(phba);
4443
4444         /* Free the SCSI sgl management array */
4445         kfree(phba->sli4_hba.lpfc_scsi_psb_array);
4446
4447         /* Free the SLI4 queues */
4448         lpfc_sli4_queue_destroy(phba);
4449
4450         /* Free the completion queue EQ event pool */
4451         lpfc_sli4_cq_event_release_all(phba);
4452         lpfc_sli4_cq_event_pool_destroy(phba);
4453
4454         /* Free the bsmbx region. */
4455         lpfc_destroy_bootstrap_mbox(phba);
4456
4457         /* Free the SLI Layer memory with SLI4 HBAs */
4458         lpfc_mem_free_all(phba);
4459
4460         /* Free the current connect table */
4461         list_for_each_entry_safe(conn_entry, next_conn_entry,
4462                 &phba->fcf_conn_rec_list, list) {
4463                 list_del_init(&conn_entry->list);
4464                 kfree(conn_entry);
4465         }
4466
4467         return;
4468 }
4469
4470 /**
4471  * lpfc_init_api_table_setup - Set up init api fucntion jump table
4472  * @phba: The hba struct for which this call is being executed.
4473  * @dev_grp: The HBA PCI-Device group number.
4474  *
4475  * This routine sets up the device INIT interface API function jump table
4476  * in @phba struct.
4477  *
4478  * Returns: 0 - success, -ENODEV - failure.
4479  **/
4480 int
4481 lpfc_init_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
4482 {
4483         phba->lpfc_hba_init_link = lpfc_hba_init_link;
4484         phba->lpfc_hba_down_link = lpfc_hba_down_link;
4485         switch (dev_grp) {
4486         case LPFC_PCI_DEV_LP:
4487                 phba->lpfc_hba_down_post = lpfc_hba_down_post_s3;
4488                 phba->lpfc_handle_eratt = lpfc_handle_eratt_s3;
4489                 phba->lpfc_stop_port = lpfc_stop_port_s3;
4490                 break;
4491         case LPFC_PCI_DEV_OC:
4492                 phba->lpfc_hba_down_post = lpfc_hba_down_post_s4;
4493                 phba->lpfc_handle_eratt = lpfc_handle_eratt_s4;
4494                 phba->lpfc_stop_port = lpfc_stop_port_s4;
4495                 break;
4496         default:
4497                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4498                                 "1431 Invalid HBA PCI-device group: 0x%x\n",
4499                                 dev_grp);
4500                 return -ENODEV;
4501                 break;
4502         }
4503         return 0;
4504 }
4505
4506 /**
4507  * lpfc_setup_driver_resource_phase1 - Phase1 etup driver internal resources.
4508  * @phba: pointer to lpfc hba data structure.
4509  *
4510  * This routine is invoked to set up the driver internal resources before the
4511  * device specific resource setup to support the HBA device it attached to.
4512  *
4513  * Return codes
4514  *      0 - successful
4515  *      other values - error
4516  **/
4517 static int
4518 lpfc_setup_driver_resource_phase1(struct lpfc_hba *phba)
4519 {
4520         /*
4521          * Driver resources common to all SLI revisions
4522          */
4523         atomic_set(&phba->fast_event_count, 0);
4524         spin_lock_init(&phba->hbalock);
4525
4526         /* Initialize ndlp management spinlock */
4527         spin_lock_init(&phba->ndlp_lock);
4528
4529         INIT_LIST_HEAD(&phba->port_list);
4530         INIT_LIST_HEAD(&phba->work_list);
4531         init_waitqueue_head(&phba->wait_4_mlo_m_q);
4532
4533         /* Initialize the wait queue head for the kernel thread */
4534         init_waitqueue_head(&phba->work_waitq);
4535
4536         /* Initialize the scsi buffer list used by driver for scsi IO */
4537         spin_lock_init(&phba->scsi_buf_list_lock);
4538         INIT_LIST_HEAD(&phba->lpfc_scsi_buf_list);
4539
4540         /* Initialize the fabric iocb list */
4541         INIT_LIST_HEAD(&phba->fabric_iocb_list);
4542
4543         /* Initialize list to save ELS buffers */
4544         INIT_LIST_HEAD(&phba->elsbuf);
4545
4546         /* Initialize FCF connection rec list */
4547         INIT_LIST_HEAD(&phba->fcf_conn_rec_list);
4548
4549         return 0;
4550 }
4551
4552 /**
4553  * lpfc_setup_driver_resource_phase2 - Phase2 setup driver internal resources.
4554  * @phba: pointer to lpfc hba data structure.
4555  *
4556  * This routine is invoked to set up the driver internal resources after the
4557  * device specific resource setup to support the HBA device it attached to.
4558  *
4559  * Return codes
4560  *      0 - successful
4561  *      other values - error
4562  **/
4563 static int
4564 lpfc_setup_driver_resource_phase2(struct lpfc_hba *phba)
4565 {
4566         int error;
4567
4568         /* Startup the kernel thread for this host adapter. */
4569         phba->worker_thread = kthread_run(lpfc_do_work, phba,
4570                                           "lpfc_worker_%d", phba->brd_no);
4571         if (IS_ERR(phba->worker_thread)) {
4572                 error = PTR_ERR(phba->worker_thread);
4573                 return error;
4574         }
4575
4576         return 0;
4577 }
4578
4579 /**
4580  * lpfc_unset_driver_resource_phase2 - Phase2 unset driver internal resources.
4581  * @phba: pointer to lpfc hba data structure.
4582  *
4583  * This routine is invoked to unset the driver internal resources set up after
4584  * the device specific resource setup for supporting the HBA device it
4585  * attached to.
4586  **/
4587 static void
4588 lpfc_unset_driver_resource_phase2(struct lpfc_hba *phba)
4589 {
4590         /* Stop kernel worker thread */
4591         kthread_stop(phba->worker_thread);
4592 }
4593
4594 /**
4595  * lpfc_free_iocb_list - Free iocb list.
4596  * @phba: pointer to lpfc hba data structure.
4597  *
4598  * This routine is invoked to free the driver's IOCB list and memory.
4599  **/
4600 static void
4601 lpfc_free_iocb_list(struct lpfc_hba *phba)
4602 {
4603         struct lpfc_iocbq *iocbq_entry = NULL, *iocbq_next = NULL;
4604
4605         spin_lock_irq(&phba->hbalock);
4606         list_for_each_entry_safe(iocbq_entry, iocbq_next,
4607                                  &phba->lpfc_iocb_list, list) {
4608                 list_del(&iocbq_entry->list);
4609                 kfree(iocbq_entry);
4610                 phba->total_iocbq_bufs--;
4611         }
4612         spin_unlock_irq(&phba->hbalock);
4613
4614         return;
4615 }
4616
4617 /**
4618  * lpfc_init_iocb_list - Allocate and initialize iocb list.
4619  * @phba: pointer to lpfc hba data structure.
4620  *
4621  * This routine is invoked to allocate and initizlize the driver's IOCB
4622  * list and set up the IOCB tag array accordingly.
4623  *
4624  * Return codes
4625  *      0 - successful
4626  *      other values - error
4627  **/
4628 static int
4629 lpfc_init_iocb_list(struct lpfc_hba *phba, int iocb_count)
4630 {
4631         struct lpfc_iocbq *iocbq_entry = NULL;
4632         uint16_t iotag;
4633         int i;
4634
4635         /* Initialize and populate the iocb list per host.  */
4636         INIT_LIST_HEAD(&phba->lpfc_iocb_list);
4637         for (i = 0; i < iocb_count; i++) {
4638                 iocbq_entry = kzalloc(sizeof(struct lpfc_iocbq), GFP_KERNEL);
4639                 if (iocbq_entry == NULL) {
4640                         printk(KERN_ERR "%s: only allocated %d iocbs of "
4641                                 "expected %d count. Unloading driver.\n",
4642                                 __func__, i, LPFC_IOCB_LIST_CNT);
4643                         goto out_free_iocbq;
4644                 }
4645
4646                 iotag = lpfc_sli_next_iotag(phba, iocbq_entry);
4647                 if (iotag == 0) {
4648                         kfree(iocbq_entry);
4649                         printk(KERN_ERR "%s: failed to allocate IOTAG. "
4650                                 "Unloading driver.\n", __func__);
4651                         goto out_free_iocbq;
4652                 }
4653                 iocbq_entry->sli4_xritag = NO_XRI;
4654
4655                 spin_lock_irq(&phba->hbalock);
4656                 list_add(&iocbq_entry->list, &phba->lpfc_iocb_list);
4657                 phba->total_iocbq_bufs++;
4658                 spin_unlock_irq(&phba->hbalock);
4659         }
4660
4661         return 0;
4662
4663 out_free_iocbq:
4664         lpfc_free_iocb_list(phba);
4665
4666         return -ENOMEM;
4667 }
4668
4669 /**
4670  * lpfc_free_sgl_list - Free sgl list.
4671  * @phba: pointer to lpfc hba data structure.
4672  *
4673  * This routine is invoked to free the driver's sgl list and memory.
4674  **/
4675 static void
4676 lpfc_free_sgl_list(struct lpfc_hba *phba)
4677 {
4678         struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
4679         LIST_HEAD(sglq_list);
4680
4681         spin_lock_irq(&phba->hbalock);
4682         list_splice_init(&phba->sli4_hba.lpfc_sgl_list, &sglq_list);
4683         spin_unlock_irq(&phba->hbalock);
4684
4685         list_for_each_entry_safe(sglq_entry, sglq_next,
4686                                  &sglq_list, list) {
4687                 list_del(&sglq_entry->list);
4688                 lpfc_mbuf_free(phba, sglq_entry->virt, sglq_entry->phys);
4689                 kfree(sglq_entry);
4690                 phba->sli4_hba.total_sglq_bufs--;
4691         }
4692         kfree(phba->sli4_hba.lpfc_els_sgl_array);
4693 }
4694
4695 /**
4696  * lpfc_init_active_sgl_array - Allocate the buf to track active ELS XRIs.
4697  * @phba: pointer to lpfc hba data structure.
4698  *
4699  * This routine is invoked to allocate the driver's active sgl memory.
4700  * This array will hold the sglq_entry's for active IOs.
4701  **/
4702 static int
4703 lpfc_init_active_sgl_array(struct lpfc_hba *phba)
4704 {
4705         int size;
4706         size = sizeof(struct lpfc_sglq *);
4707         size *= phba->sli4_hba.max_cfg_param.max_xri;
4708
4709         phba->sli4_hba.lpfc_sglq_active_list =
4710                 kzalloc(size, GFP_KERNEL);
4711         if (!phba->sli4_hba.lpfc_sglq_active_list)
4712                 return -ENOMEM;
4713         return 0;
4714 }
4715
4716 /**
4717  * lpfc_free_active_sgl - Free the buf that tracks active ELS XRIs.
4718  * @phba: pointer to lpfc hba data structure.
4719  *
4720  * This routine is invoked to walk through the array of active sglq entries
4721  * and free all of the resources.
4722  * This is just a place holder for now.
4723  **/
4724 static void
4725 lpfc_free_active_sgl(struct lpfc_hba *phba)
4726 {
4727         kfree(phba->sli4_hba.lpfc_sglq_active_list);
4728 }
4729
4730 /**
4731  * lpfc_init_sgl_list - Allocate and initialize sgl list.
4732  * @phba: pointer to lpfc hba data structure.
4733  *
4734  * This routine is invoked to allocate and initizlize the driver's sgl
4735  * list and set up the sgl xritag tag array accordingly.
4736  *
4737  * Return codes
4738  *      0 - successful
4739  *      other values - error
4740  **/
4741 static int
4742 lpfc_init_sgl_list(struct lpfc_hba *phba)
4743 {
4744         struct lpfc_sglq *sglq_entry = NULL;
4745         int i;
4746         int els_xri_cnt;
4747
4748         els_xri_cnt = lpfc_sli4_get_els_iocb_cnt(phba);
4749         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4750                                 "2400 lpfc_init_sgl_list els %d.\n",
4751                                 els_xri_cnt);
4752         /* Initialize and populate the sglq list per host/VF. */
4753         INIT_LIST_HEAD(&phba->sli4_hba.lpfc_sgl_list);
4754         INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_els_sgl_list);
4755
4756         /* Sanity check on XRI management */
4757         if (phba->sli4_hba.max_cfg_param.max_xri <= els_xri_cnt) {
4758                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
4759                                 "2562 No room left for SCSI XRI allocation: "
4760                                 "max_xri=%d, els_xri=%d\n",
4761                                 phba->sli4_hba.max_cfg_param.max_xri,
4762                                 els_xri_cnt);
4763                 return -ENOMEM;
4764         }
4765
4766         /* Allocate memory for the ELS XRI management array */
4767         phba->sli4_hba.lpfc_els_sgl_array =
4768                         kzalloc((sizeof(struct lpfc_sglq *) * els_xri_cnt),
4769                         GFP_KERNEL);
4770
4771         if (!phba->sli4_hba.lpfc_els_sgl_array) {
4772                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
4773                                 "2401 Failed to allocate memory for ELS "
4774                                 "XRI management array of size %d.\n",
4775                                 els_xri_cnt);
4776                 return -ENOMEM;
4777         }
4778
4779         /* Keep the SCSI XRI into the XRI management array */
4780         phba->sli4_hba.scsi_xri_max =
4781                         phba->sli4_hba.max_cfg_param.max_xri - els_xri_cnt;
4782         phba->sli4_hba.scsi_xri_cnt = 0;
4783
4784         phba->sli4_hba.lpfc_scsi_psb_array =
4785                         kzalloc((sizeof(struct lpfc_scsi_buf *) *
4786                         phba->sli4_hba.scsi_xri_max), GFP_KERNEL);
4787
4788         if (!phba->sli4_hba.lpfc_scsi_psb_array) {
4789                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
4790                                 "2563 Failed to allocate memory for SCSI "
4791                                 "XRI management array of size %d.\n",
4792                                 phba->sli4_hba.scsi_xri_max);
4793                 kfree(phba->sli4_hba.lpfc_els_sgl_array);
4794                 return -ENOMEM;
4795         }
4796
4797         for (i = 0; i < els_xri_cnt; i++) {
4798                 sglq_entry = kzalloc(sizeof(struct lpfc_sglq), GFP_KERNEL);
4799                 if (sglq_entry == NULL) {
4800                         printk(KERN_ERR "%s: only allocated %d sgls of "
4801                                 "expected %d count. Unloading driver.\n",
4802                                 __func__, i, els_xri_cnt);
4803                         goto out_free_mem;
4804                 }
4805
4806                 sglq_entry->sli4_xritag = lpfc_sli4_next_xritag(phba);
4807                 if (sglq_entry->sli4_xritag == NO_XRI) {
4808                         kfree(sglq_entry);
4809                         printk(KERN_ERR "%s: failed to allocate XRI.\n"
4810                                 "Unloading driver.\n", __func__);
4811                         goto out_free_mem;
4812                 }
4813                 sglq_entry->buff_type = GEN_BUFF_TYPE;
4814                 sglq_entry->virt = lpfc_mbuf_alloc(phba, 0, &sglq_entry->phys);
4815                 if (sglq_entry->virt == NULL) {
4816                         kfree(sglq_entry);
4817                         printk(KERN_ERR "%s: failed to allocate mbuf.\n"
4818                                 "Unloading driver.\n", __func__);
4819                         goto out_free_mem;
4820                 }
4821                 sglq_entry->sgl = sglq_entry->virt;
4822                 memset(sglq_entry->sgl, 0, LPFC_BPL_SIZE);
4823
4824                 /* The list order is used by later block SGL registraton */
4825                 spin_lock_irq(&phba->hbalock);
4826                 sglq_entry->state = SGL_FREED;
4827                 list_add_tail(&sglq_entry->list, &phba->sli4_hba.lpfc_sgl_list);
4828                 phba->sli4_hba.lpfc_els_sgl_array[i] = sglq_entry;
4829                 phba->sli4_hba.total_sglq_bufs++;
4830                 spin_unlock_irq(&phba->hbalock);
4831         }
4832         return 0;
4833
4834 out_free_mem:
4835         kfree(phba->sli4_hba.lpfc_scsi_psb_array);
4836         lpfc_free_sgl_list(phba);
4837         return -ENOMEM;
4838 }
4839
4840 /**
4841  * lpfc_sli4_init_rpi_hdrs - Post the rpi header memory region to the port
4842  * @phba: pointer to lpfc hba data structure.
4843  *
4844  * This routine is invoked to post rpi header templates to the
4845  * HBA consistent with the SLI-4 interface spec.  This routine
4846  * posts a PAGE_SIZE memory region to the port to hold up to
4847  * PAGE_SIZE modulo 64 rpi context headers.
4848  * No locks are held here because this is an initialization routine
4849  * called only from probe or lpfc_online when interrupts are not
4850  * enabled and the driver is reinitializing the device.
4851  *
4852  * Return codes
4853  *      0 - successful
4854  *      -ENOMEM - No availble memory
4855  *      -EIO - The mailbox failed to complete successfully.
4856  **/
4857 int
4858 lpfc_sli4_init_rpi_hdrs(struct lpfc_hba *phba)
4859 {
4860         int rc = 0;
4861         int longs;
4862         uint16_t rpi_count;
4863         struct lpfc_rpi_hdr *rpi_hdr;
4864
4865         INIT_LIST_HEAD(&phba->sli4_hba.lpfc_rpi_hdr_list);
4866
4867         /*
4868          * Provision an rpi bitmask range for discovery. The total count
4869          * is the difference between max and base + 1.
4870          */
4871         rpi_count = phba->sli4_hba.max_cfg_param.rpi_base +
4872                     phba->sli4_hba.max_cfg_param.max_rpi - 1;
4873
4874         longs = ((rpi_count) + BITS_PER_LONG - 1) / BITS_PER_LONG;
4875         phba->sli4_hba.rpi_bmask = kzalloc(longs * sizeof(unsigned long),
4876                                            GFP_KERNEL);
4877         if (!phba->sli4_hba.rpi_bmask)
4878                 return -ENOMEM;
4879
4880         rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
4881         if (!rpi_hdr) {
4882                 lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
4883                                 "0391 Error during rpi post operation\n");
4884                 lpfc_sli4_remove_rpis(phba);
4885                 rc = -ENODEV;
4886         }
4887
4888         return rc;
4889 }
4890
4891 /**
4892  * lpfc_sli4_create_rpi_hdr - Allocate an rpi header memory region
4893  * @phba: pointer to lpfc hba data structure.
4894  *
4895  * This routine is invoked to allocate a single 4KB memory region to
4896  * support rpis and stores them in the phba.  This single region
4897  * provides support for up to 64 rpis.  The region is used globally
4898  * by the device.
4899  *
4900  * Returns:
4901  *   A valid rpi hdr on success.
4902  *   A NULL pointer on any failure.
4903  **/
4904 struct lpfc_rpi_hdr *
4905 lpfc_sli4_create_rpi_hdr(struct lpfc_hba *phba)
4906 {
4907         uint16_t rpi_limit, curr_rpi_range;
4908         struct lpfc_dmabuf *dmabuf;
4909         struct lpfc_rpi_hdr *rpi_hdr;
4910
4911         rpi_limit = phba->sli4_hba.max_cfg_param.rpi_base +
4912                     phba->sli4_hba.max_cfg_param.max_rpi - 1;
4913
4914         spin_lock_irq(&phba->hbalock);
4915         curr_rpi_range = phba->sli4_hba.next_rpi;
4916         spin_unlock_irq(&phba->hbalock);
4917
4918         /*
4919          * The port has a limited number of rpis. The increment here
4920          * is LPFC_RPI_HDR_COUNT - 1 to account for the starting value
4921          * and to allow the full max_rpi range per port.
4922          */
4923         if ((curr_rpi_range + (LPFC_RPI_HDR_COUNT - 1)) > rpi_limit)
4924                 return NULL;
4925
4926         /*
4927          * First allocate the protocol header region for the port.  The
4928          * port expects a 4KB DMA-mapped memory region that is 4K aligned.
4929          */
4930         dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
4931         if (!dmabuf)
4932                 return NULL;
4933
4934         dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
4935                                           LPFC_HDR_TEMPLATE_SIZE,
4936                                           &dmabuf->phys,
4937                                           GFP_KERNEL);
4938         if (!dmabuf->virt) {
4939                 rpi_hdr = NULL;
4940                 goto err_free_dmabuf;
4941         }
4942
4943         memset(dmabuf->virt, 0, LPFC_HDR_TEMPLATE_SIZE);
4944         if (!IS_ALIGNED(dmabuf->phys, LPFC_HDR_TEMPLATE_SIZE)) {
4945                 rpi_hdr = NULL;
4946                 goto err_free_coherent;
4947         }
4948
4949         /* Save the rpi header data for cleanup later. */
4950         rpi_hdr = kzalloc(sizeof(struct lpfc_rpi_hdr), GFP_KERNEL);
4951         if (!rpi_hdr)
4952                 goto err_free_coherent;
4953
4954         rpi_hdr->dmabuf = dmabuf;
4955         rpi_hdr->len = LPFC_HDR_TEMPLATE_SIZE;
4956         rpi_hdr->page_count = 1;
4957         spin_lock_irq(&phba->hbalock);
4958         rpi_hdr->start_rpi = phba->sli4_hba.next_rpi;
4959         list_add_tail(&rpi_hdr->list, &phba->sli4_hba.lpfc_rpi_hdr_list);
4960
4961         /*
4962          * The next_rpi stores the next module-64 rpi value to post
4963          * in any subsequent rpi memory region postings.
4964          */
4965         phba->sli4_hba.next_rpi += LPFC_RPI_HDR_COUNT;
4966         spin_unlock_irq(&phba->hbalock);
4967         return rpi_hdr;
4968
4969  err_free_coherent:
4970         dma_free_coherent(&phba->pcidev->dev, LPFC_HDR_TEMPLATE_SIZE,
4971                           dmabuf->virt, dmabuf->phys);
4972  err_free_dmabuf:
4973         kfree(dmabuf);
4974         return NULL;
4975 }
4976
4977 /**
4978  * lpfc_sli4_remove_rpi_hdrs - Remove all rpi header memory regions
4979  * @phba: pointer to lpfc hba data structure.
4980  *
4981  * This routine is invoked to remove all memory resources allocated
4982  * to support rpis. This routine presumes the caller has released all
4983  * rpis consumed by fabric or port logins and is prepared to have
4984  * the header pages removed.
4985  **/
4986 void
4987 lpfc_sli4_remove_rpi_hdrs(struct lpfc_hba *phba)
4988 {
4989         struct lpfc_rpi_hdr *rpi_hdr, *next_rpi_hdr;
4990
4991         list_for_each_entry_safe(rpi_hdr, next_rpi_hdr,
4992                                  &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
4993                 list_del(&rpi_hdr->list);
4994                 dma_free_coherent(&phba->pcidev->dev, rpi_hdr->len,
4995                                   rpi_hdr->dmabuf->virt, rpi_hdr->dmabuf->phys);
4996                 kfree(rpi_hdr->dmabuf);
4997                 kfree(rpi_hdr);
4998         }
4999
5000         phba->sli4_hba.next_rpi = phba->sli4_hba.max_cfg_param.rpi_base;
5001         memset(phba->sli4_hba.rpi_bmask, 0, sizeof(*phba->sli4_hba.rpi_bmask));
5002 }
5003
5004 /**
5005  * lpfc_hba_alloc - Allocate driver hba data structure for a device.
5006  * @pdev: pointer to pci device data structure.
5007  *
5008  * This routine is invoked to allocate the driver hba data structure for an
5009  * HBA device. If the allocation is successful, the phba reference to the
5010  * PCI device data structure is set.
5011  *
5012  * Return codes
5013  *      pointer to @phba - successful
5014  *      NULL - error
5015  **/
5016 static struct lpfc_hba *
5017 lpfc_hba_alloc(struct pci_dev *pdev)
5018 {
5019         struct lpfc_hba *phba;
5020
5021         /* Allocate memory for HBA structure */
5022         phba = kzalloc(sizeof(struct lpfc_hba), GFP_KERNEL);
5023         if (!phba) {
5024                 dev_err(&pdev->dev, "failed to allocate hba struct\n");
5025                 return NULL;
5026         }
5027
5028         /* Set reference to PCI device in HBA structure */
5029         phba->pcidev = pdev;
5030
5031         /* Assign an unused board number */
5032         phba->brd_no = lpfc_get_instance();
5033         if (phba->brd_no < 0) {
5034                 kfree(phba);
5035                 return NULL;
5036         }
5037
5038         spin_lock_init(&phba->ct_ev_lock);
5039         INIT_LIST_HEAD(&phba->ct_ev_waiters);
5040
5041         return phba;
5042 }
5043
5044 /**
5045  * lpfc_hba_free - Free driver hba data structure with a device.
5046  * @phba: pointer to lpfc hba data structure.
5047  *
5048  * This routine is invoked to free the driver hba data structure with an
5049  * HBA device.
5050  **/
5051 static void
5052 lpfc_hba_free(struct lpfc_hba *phba)
5053 {
5054         /* Release the driver assigned board number */
5055         idr_remove(&lpfc_hba_index, phba->brd_no);
5056
5057         kfree(phba);
5058         return;
5059 }
5060
5061 /**
5062  * lpfc_create_shost - Create hba physical port with associated scsi host.
5063  * @phba: pointer to lpfc hba data structure.
5064  *
5065  * This routine is invoked to create HBA physical port and associate a SCSI
5066  * host with it.
5067  *
5068  * Return codes
5069  *      0 - successful
5070  *      other values - error
5071  **/
5072 static int
5073 lpfc_create_shost(struct lpfc_hba *phba)
5074 {
5075         struct lpfc_vport *vport;
5076         struct Scsi_Host  *shost;
5077
5078         /* Initialize HBA FC structure */
5079         phba->fc_edtov = FF_DEF_EDTOV;
5080         phba->fc_ratov = FF_DEF_RATOV;
5081         phba->fc_altov = FF_DEF_ALTOV;
5082         phba->fc_arbtov = FF_DEF_ARBTOV;
5083
5084         atomic_set(&phba->sdev_cnt, 0);
5085         vport = lpfc_create_port(phba, phba->brd_no, &phba->pcidev->dev);
5086         if (!vport)
5087                 return -ENODEV;
5088
5089         shost = lpfc_shost_from_vport(vport);
5090         phba->pport = vport;
5091         lpfc_debugfs_initialize(vport);
5092         /* Put reference to SCSI host to driver's device private data */
5093         pci_set_drvdata(phba->pcidev, shost);
5094
5095         return 0;
5096 }
5097
5098 /**
5099  * lpfc_destroy_shost - Destroy hba physical port with associated scsi host.
5100  * @phba: pointer to lpfc hba data structure.
5101  *
5102  * This routine is invoked to destroy HBA physical port and the associated
5103  * SCSI host.
5104  **/
5105 static void
5106 lpfc_destroy_shost(struct lpfc_hba *phba)
5107 {
5108         struct lpfc_vport *vport = phba->pport;
5109
5110         /* Destroy physical port that associated with the SCSI host */
5111         destroy_port(vport);
5112
5113         return;
5114 }
5115
5116 /**
5117  * lpfc_setup_bg - Setup Block guard structures and debug areas.
5118  * @phba: pointer to lpfc hba data structure.
5119  * @shost: the shost to be used to detect Block guard settings.
5120  *
5121  * This routine sets up the local Block guard protocol settings for @shost.
5122  * This routine also allocates memory for debugging bg buffers.
5123  **/
5124 static void
5125 lpfc_setup_bg(struct lpfc_hba *phba, struct Scsi_Host *shost)
5126 {
5127         int pagecnt = 10;
5128         if (lpfc_prot_mask && lpfc_prot_guard) {
5129                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5130                                 "1478 Registering BlockGuard with the "
5131                                 "SCSI layer\n");
5132                 scsi_host_set_prot(shost, lpfc_prot_mask);
5133                 scsi_host_set_guard(shost, lpfc_prot_guard);
5134         }
5135         if (!_dump_buf_data) {
5136                 while (pagecnt) {
5137                         spin_lock_init(&_dump_buf_lock);
5138                         _dump_buf_data =
5139                                 (char *) __get_free_pages(GFP_KERNEL, pagecnt);
5140                         if (_dump_buf_data) {
5141                                 lpfc_printf_log(phba, KERN_ERR, LOG_BG,
5142                                         "9043 BLKGRD: allocated %d pages for "
5143                                        "_dump_buf_data at 0x%p\n",
5144                                        (1 << pagecnt), _dump_buf_data);
5145                                 _dump_buf_data_order = pagecnt;
5146                                 memset(_dump_buf_data, 0,
5147                                        ((1 << PAGE_SHIFT) << pagecnt));
5148                                 break;
5149                         } else
5150                                 --pagecnt;
5151                 }
5152                 if (!_dump_buf_data_order)
5153                         lpfc_printf_log(phba, KERN_ERR, LOG_BG,
5154                                 "9044 BLKGRD: ERROR unable to allocate "
5155                                "memory for hexdump\n");
5156         } else
5157                 lpfc_printf_log(phba, KERN_ERR, LOG_BG,
5158                         "9045 BLKGRD: already allocated _dump_buf_data=0x%p"
5159                        "\n", _dump_buf_data);
5160         if (!_dump_buf_dif) {
5161                 while (pagecnt) {
5162                         _dump_buf_dif =
5163                                 (char *) __get_free_pages(GFP_KERNEL, pagecnt);
5164                         if (_dump_buf_dif) {
5165                                 lpfc_printf_log(phba, KERN_ERR, LOG_BG,
5166                                         "9046 BLKGRD: allocated %d pages for "
5167                                        "_dump_buf_dif at 0x%p\n",
5168                                        (1 << pagecnt), _dump_buf_dif);
5169                                 _dump_buf_dif_order = pagecnt;
5170                                 memset(_dump_buf_dif, 0,
5171                                        ((1 << PAGE_SHIFT) << pagecnt));
5172                                 break;
5173                         } else
5174                                 --pagecnt;
5175                 }
5176                 if (!_dump_buf_dif_order)
5177                         lpfc_printf_log(phba, KERN_ERR, LOG_BG,
5178                         "9047 BLKGRD: ERROR unable to allocate "
5179                                "memory for hexdump\n");
5180         } else
5181                 lpfc_printf_log(phba, KERN_ERR, LOG_BG,
5182                         "9048 BLKGRD: already allocated _dump_buf_dif=0x%p\n",
5183                        _dump_buf_dif);
5184 }
5185
5186 /**
5187  * lpfc_post_init_setup - Perform necessary device post initialization setup.
5188  * @phba: pointer to lpfc hba data structure.
5189  *
5190  * This routine is invoked to perform all the necessary post initialization
5191  * setup for the device.
5192  **/
5193 static void
5194 lpfc_post_init_setup(struct lpfc_hba *phba)
5195 {
5196         struct Scsi_Host  *shost;
5197         struct lpfc_adapter_event_header adapter_event;
5198
5199         /* Get the default values for Model Name and Description */
5200         lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
5201
5202         /*
5203          * hba setup may have changed the hba_queue_depth so we need to
5204          * adjust the value of can_queue.
5205          */
5206         shost = pci_get_drvdata(phba->pcidev);
5207         shost->can_queue = phba->cfg_hba_queue_depth - 10;
5208         if (phba->sli3_options & LPFC_SLI3_BG_ENABLED)
5209                 lpfc_setup_bg(phba, shost);
5210
5211         lpfc_host_attrib_init(shost);
5212
5213         if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
5214                 spin_lock_irq(shost->host_lock);
5215                 lpfc_poll_start_timer(phba);
5216                 spin_unlock_irq(shost->host_lock);
5217         }
5218
5219         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5220                         "0428 Perform SCSI scan\n");
5221         /* Send board arrival event to upper layer */
5222         adapter_event.event_type = FC_REG_ADAPTER_EVENT;
5223         adapter_event.subcategory = LPFC_EVENT_ARRIVAL;
5224         fc_host_post_vendor_event(shost, fc_get_event_number(),
5225                                   sizeof(adapter_event),
5226                                   (char *) &adapter_event,
5227                                   LPFC_NL_VENDOR_ID);
5228         return;
5229 }
5230
5231 /**
5232  * lpfc_sli_pci_mem_setup - Setup SLI3 HBA PCI memory space.
5233  * @phba: pointer to lpfc hba data structure.
5234  *
5235  * This routine is invoked to set up the PCI device memory space for device
5236  * with SLI-3 interface spec.
5237  *
5238  * Return codes
5239  *      0 - successful
5240  *      other values - error
5241  **/
5242 static int
5243 lpfc_sli_pci_mem_setup(struct lpfc_hba *phba)
5244 {
5245         struct pci_dev *pdev;
5246         unsigned long bar0map_len, bar2map_len;
5247         int i, hbq_count;
5248         void *ptr;
5249         int error = -ENODEV;
5250
5251         /* Obtain PCI device reference */
5252         if (!phba->pcidev)
5253                 return error;
5254         else
5255                 pdev = phba->pcidev;
5256
5257         /* Set the device DMA mask size */
5258         if (pci_set_dma_mask(pdev, DMA_BIT_MASK(64)) != 0
5259          || pci_set_consistent_dma_mask(pdev,DMA_BIT_MASK(64)) != 0) {
5260                 if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32)) != 0
5261                  || pci_set_consistent_dma_mask(pdev,DMA_BIT_MASK(32)) != 0) {
5262                         return error;
5263                 }
5264         }
5265
5266         /* Get the bus address of Bar0 and Bar2 and the number of bytes
5267          * required by each mapping.
5268          */
5269         phba->pci_bar0_map = pci_resource_start(pdev, 0);
5270         bar0map_len = pci_resource_len(pdev, 0);
5271
5272         phba->pci_bar2_map = pci_resource_start(pdev, 2);
5273         bar2map_len = pci_resource_len(pdev, 2);
5274
5275         /* Map HBA SLIM to a kernel virtual address. */
5276         phba->slim_memmap_p = ioremap(phba->pci_bar0_map, bar0map_len);
5277         if (!phba->slim_memmap_p) {
5278                 dev_printk(KERN_ERR, &pdev->dev,
5279                            "ioremap failed for SLIM memory.\n");
5280                 goto out;
5281         }
5282
5283         /* Map HBA Control Registers to a kernel virtual address. */
5284         phba->ctrl_regs_memmap_p = ioremap(phba->pci_bar2_map, bar2map_len);
5285         if (!phba->ctrl_regs_memmap_p) {
5286                 dev_printk(KERN_ERR, &pdev->dev,
5287                            "ioremap failed for HBA control registers.\n");
5288                 goto out_iounmap_slim;
5289         }
5290
5291         /* Allocate memory for SLI-2 structures */
5292         phba->slim2p.virt = dma_alloc_coherent(&pdev->dev,
5293                                                SLI2_SLIM_SIZE,
5294                                                &phba->slim2p.phys,
5295                                                GFP_KERNEL);
5296         if (!phba->slim2p.virt)
5297                 goto out_iounmap;
5298
5299         memset(phba->slim2p.virt, 0, SLI2_SLIM_SIZE);
5300         phba->mbox = phba->slim2p.virt + offsetof(struct lpfc_sli2_slim, mbx);
5301         phba->mbox_ext = (phba->slim2p.virt +
5302                 offsetof(struct lpfc_sli2_slim, mbx_ext_words));
5303         phba->pcb = (phba->slim2p.virt + offsetof(struct lpfc_sli2_slim, pcb));
5304         phba->IOCBs = (phba->slim2p.virt +
5305                        offsetof(struct lpfc_sli2_slim, IOCBs));
5306
5307         phba->hbqslimp.virt = dma_alloc_coherent(&pdev->dev,
5308                                                  lpfc_sli_hbq_size(),
5309                                                  &phba->hbqslimp.phys,
5310                                                  GFP_KERNEL);
5311         if (!phba->hbqslimp.virt)
5312                 goto out_free_slim;
5313
5314         hbq_count = lpfc_sli_hbq_count();
5315         ptr = phba->hbqslimp.virt;
5316         for (i = 0; i < hbq_count; ++i) {
5317                 phba->hbqs[i].hbq_virt = ptr;
5318                 INIT_LIST_HEAD(&phba->hbqs[i].hbq_buffer_list);
5319                 ptr += (lpfc_hbq_defs[i]->entry_count *
5320                         sizeof(struct lpfc_hbq_entry));
5321         }
5322         phba->hbqs[LPFC_ELS_HBQ].hbq_alloc_buffer = lpfc_els_hbq_alloc;
5323         phba->hbqs[LPFC_ELS_HBQ].hbq_free_buffer = lpfc_els_hbq_free;
5324
5325         memset(phba->hbqslimp.virt, 0, lpfc_sli_hbq_size());
5326
5327         INIT_LIST_HEAD(&phba->rb_pend_list);
5328
5329         phba->MBslimaddr = phba->slim_memmap_p;
5330         phba->HAregaddr = phba->ctrl_regs_memmap_p + HA_REG_OFFSET;
5331         phba->CAregaddr = phba->ctrl_regs_memmap_p + CA_REG_OFFSET;
5332         phba->HSregaddr = phba->ctrl_regs_memmap_p + HS_REG_OFFSET;
5333         phba->HCregaddr = phba->ctrl_regs_memmap_p + HC_REG_OFFSET;
5334
5335         return 0;
5336
5337 out_free_slim:
5338         dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
5339                           phba->slim2p.virt, phba->slim2p.phys);
5340 out_iounmap:
5341         iounmap(phba->ctrl_regs_memmap_p);
5342 out_iounmap_slim:
5343         iounmap(phba->slim_memmap_p);
5344 out:
5345         return error;
5346 }
5347
5348 /**
5349  * lpfc_sli_pci_mem_unset - Unset SLI3 HBA PCI memory space.
5350  * @phba: pointer to lpfc hba data structure.
5351  *
5352  * This routine is invoked to unset the PCI device memory space for device
5353  * with SLI-3 interface spec.
5354  **/
5355 static void
5356 lpfc_sli_pci_mem_unset(struct lpfc_hba *phba)
5357 {
5358         struct pci_dev *pdev;
5359
5360         /* Obtain PCI device reference */
5361         if (!phba->pcidev)
5362                 return;
5363         else
5364                 pdev = phba->pcidev;
5365
5366         /* Free coherent DMA memory allocated */
5367         dma_free_coherent(&pdev->dev, lpfc_sli_hbq_size(),
5368                           phba->hbqslimp.virt, phba->hbqslimp.phys);
5369         dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
5370                           phba->slim2p.virt, phba->slim2p.phys);
5371
5372         /* I/O memory unmap */
5373         iounmap(phba->ctrl_regs_memmap_p);
5374         iounmap(phba->slim_memmap_p);
5375
5376         return;
5377 }
5378
5379 /**
5380  * lpfc_sli4_post_status_check - Wait for SLI4 POST done and check status
5381  * @phba: pointer to lpfc hba data structure.
5382  *
5383  * This routine is invoked to wait for SLI4 device Power On Self Test (POST)
5384  * done and check status.
5385  *
5386  * Return 0 if successful, otherwise -ENODEV.
5387  **/
5388 int
5389 lpfc_sli4_post_status_check(struct lpfc_hba *phba)
5390 {
5391         struct lpfc_register sta_reg, uerrlo_reg, uerrhi_reg;
5392         int i, port_error = -ENODEV;
5393
5394         if (!phba->sli4_hba.STAregaddr)
5395                 return -ENODEV;
5396
5397         /* Wait up to 30 seconds for the SLI Port POST done and ready */
5398         for (i = 0; i < 3000; i++) {
5399                 sta_reg.word0 = readl(phba->sli4_hba.STAregaddr);
5400                 /* Encounter fatal POST error, break out */
5401                 if (bf_get(lpfc_hst_state_perr, &sta_reg)) {
5402                         port_error = -ENODEV;
5403                         break;
5404                 }
5405                 if (LPFC_POST_STAGE_ARMFW_READY ==
5406                     bf_get(lpfc_hst_state_port_status, &sta_reg)) {
5407                         port_error = 0;
5408                         break;
5409                 }
5410                 msleep(10);
5411         }
5412
5413         if (port_error)
5414                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5415                         "1408 Failure HBA POST Status: sta_reg=0x%x, "
5416                         "perr=x%x, sfi=x%x, nip=x%x, ipc=x%x, xrom=x%x, "
5417                         "dl=x%x, pstatus=x%x\n", sta_reg.word0,
5418                         bf_get(lpfc_hst_state_perr, &sta_reg),
5419                         bf_get(lpfc_hst_state_sfi, &sta_reg),
5420                         bf_get(lpfc_hst_state_nip, &sta_reg),
5421                         bf_get(lpfc_hst_state_ipc, &sta_reg),
5422                         bf_get(lpfc_hst_state_xrom, &sta_reg),
5423                         bf_get(lpfc_hst_state_dl, &sta_reg),
5424                         bf_get(lpfc_hst_state_port_status, &sta_reg));
5425
5426         /* Log device information */
5427         phba->sli4_hba.sli_intf.word0 = readl(phba->sli4_hba.SLIINTFregaddr);
5428         if (bf_get(lpfc_sli_intf_valid,
5429                    &phba->sli4_hba.sli_intf) == LPFC_SLI_INTF_VALID) {
5430                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5431                                 "2534 Device Info: ChipType=0x%x, SliRev=0x%x, "
5432                                 "IFType=0x%x, SLIHint_1=0x%x, SLIHint_2=0x%x, "
5433                                 "FT=0x%x\n",
5434                                 bf_get(lpfc_sli_intf_sli_family,
5435                                        &phba->sli4_hba.sli_intf),
5436                                 bf_get(lpfc_sli_intf_slirev,
5437                                        &phba->sli4_hba.sli_intf),
5438                                 bf_get(lpfc_sli_intf_if_type,
5439                                        &phba->sli4_hba.sli_intf),
5440                                 bf_get(lpfc_sli_intf_sli_hint1,
5441                                        &phba->sli4_hba.sli_intf),
5442                                 bf_get(lpfc_sli_intf_sli_hint2,
5443                                        &phba->sli4_hba.sli_intf),
5444                                 bf_get(lpfc_sli_intf_func_type,
5445                                        &phba->sli4_hba.sli_intf));
5446         }
5447
5448         phba->sli4_hba.ue_mask_lo = readl(phba->sli4_hba.UEMASKLOregaddr);
5449         phba->sli4_hba.ue_mask_hi = readl(phba->sli4_hba.UEMASKHIregaddr);
5450         /* With uncoverable error, log the error message and return error */
5451         uerrlo_reg.word0 = readl(phba->sli4_hba.UERRLOregaddr);
5452         uerrhi_reg.word0 = readl(phba->sli4_hba.UERRHIregaddr);
5453         if ((~phba->sli4_hba.ue_mask_lo & uerrlo_reg.word0) ||
5454             (~phba->sli4_hba.ue_mask_hi & uerrhi_reg.word0)) {
5455                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5456                                 "1422 HBA Unrecoverable error: "
5457                                 "uerr_lo_reg=0x%x, uerr_hi_reg=0x%x, "
5458                                 "ue_mask_lo_reg=0x%x, ue_mask_hi_reg=0x%x\n",
5459                                 uerrlo_reg.word0, uerrhi_reg.word0,
5460                                 phba->sli4_hba.ue_mask_lo,
5461                                 phba->sli4_hba.ue_mask_hi);
5462                 return -ENODEV;
5463         }
5464
5465         return port_error;
5466 }
5467
5468 /**
5469  * lpfc_sli4_bar0_register_memmap - Set up SLI4 BAR0 register memory map.
5470  * @phba: pointer to lpfc hba data structure.
5471  *
5472  * This routine is invoked to set up SLI4 BAR0 PCI config space register
5473  * memory map.
5474  **/
5475 static void
5476 lpfc_sli4_bar0_register_memmap(struct lpfc_hba *phba)
5477 {
5478         phba->sli4_hba.UERRLOregaddr = phba->sli4_hba.conf_regs_memmap_p +
5479                                         LPFC_UERR_STATUS_LO;
5480         phba->sli4_hba.UERRHIregaddr = phba->sli4_hba.conf_regs_memmap_p +
5481                                         LPFC_UERR_STATUS_HI;
5482         phba->sli4_hba.UEMASKLOregaddr = phba->sli4_hba.conf_regs_memmap_p +
5483                                         LPFC_UE_MASK_LO;
5484         phba->sli4_hba.UEMASKHIregaddr = phba->sli4_hba.conf_regs_memmap_p +
5485                                         LPFC_UE_MASK_HI;
5486         phba->sli4_hba.SLIINTFregaddr = phba->sli4_hba.conf_regs_memmap_p +
5487                                         LPFC_SLI_INTF;
5488 }
5489
5490 /**
5491  * lpfc_sli4_bar1_register_memmap - Set up SLI4 BAR1 register memory map.
5492  * @phba: pointer to lpfc hba data structure.
5493  *
5494  * This routine is invoked to set up SLI4 BAR1 control status register (CSR)
5495  * memory map.
5496  **/
5497 static void
5498 lpfc_sli4_bar1_register_memmap(struct lpfc_hba *phba)
5499 {
5500
5501         phba->sli4_hba.STAregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
5502                                     LPFC_HST_STATE;
5503         phba->sli4_hba.ISRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
5504                                     LPFC_HST_ISR0;
5505         phba->sli4_hba.IMRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
5506                                     LPFC_HST_IMR0;
5507         phba->sli4_hba.ISCRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
5508                                      LPFC_HST_ISCR0;
5509         return;
5510 }
5511
5512 /**
5513  * lpfc_sli4_bar2_register_memmap - Set up SLI4 BAR2 register memory map.
5514  * @phba: pointer to lpfc hba data structure.
5515  * @vf: virtual function number
5516  *
5517  * This routine is invoked to set up SLI4 BAR2 doorbell register memory map
5518  * based on the given viftual function number, @vf.
5519  *
5520  * Return 0 if successful, otherwise -ENODEV.
5521  **/
5522 static int
5523 lpfc_sli4_bar2_register_memmap(struct lpfc_hba *phba, uint32_t vf)
5524 {
5525         if (vf > LPFC_VIR_FUNC_MAX)
5526                 return -ENODEV;
5527
5528         phba->sli4_hba.RQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
5529                                 vf * LPFC_VFR_PAGE_SIZE + LPFC_RQ_DOORBELL);
5530         phba->sli4_hba.WQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
5531                                 vf * LPFC_VFR_PAGE_SIZE + LPFC_WQ_DOORBELL);
5532         phba->sli4_hba.EQCQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
5533                                 vf * LPFC_VFR_PAGE_SIZE + LPFC_EQCQ_DOORBELL);
5534         phba->sli4_hba.MQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
5535                                 vf * LPFC_VFR_PAGE_SIZE + LPFC_MQ_DOORBELL);
5536         phba->sli4_hba.BMBXregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
5537                                 vf * LPFC_VFR_PAGE_SIZE + LPFC_BMBX);
5538         return 0;
5539 }
5540
5541 /**
5542  * lpfc_create_bootstrap_mbox - Create the bootstrap mailbox
5543  * @phba: pointer to lpfc hba data structure.
5544  *
5545  * This routine is invoked to create the bootstrap mailbox
5546  * region consistent with the SLI-4 interface spec.  This
5547  * routine allocates all memory necessary to communicate
5548  * mailbox commands to the port and sets up all alignment
5549  * needs.  No locks are expected to be held when calling
5550  * this routine.
5551  *
5552  * Return codes
5553  *      0 - successful
5554  *      -ENOMEM - could not allocated memory.
5555  **/
5556 static int
5557 lpfc_create_bootstrap_mbox(struct lpfc_hba *phba)
5558 {
5559         uint32_t bmbx_size;
5560         struct lpfc_dmabuf *dmabuf;
5561         struct dma_address *dma_address;
5562         uint32_t pa_addr;
5563         uint64_t phys_addr;
5564
5565         dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
5566         if (!dmabuf)
5567                 return -ENOMEM;
5568
5569         /*
5570          * The bootstrap mailbox region is comprised of 2 parts
5571          * plus an alignment restriction of 16 bytes.
5572          */
5573         bmbx_size = sizeof(struct lpfc_bmbx_create) + (LPFC_ALIGN_16_BYTE - 1);
5574         dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
5575                                           bmbx_size,
5576                                           &dmabuf->phys,
5577                                           GFP_KERNEL);
5578         if (!dmabuf->virt) {
5579                 kfree(dmabuf);
5580                 return -ENOMEM;
5581         }
5582         memset(dmabuf->virt, 0, bmbx_size);
5583
5584         /*
5585          * Initialize the bootstrap mailbox pointers now so that the register
5586          * operations are simple later.  The mailbox dma address is required
5587          * to be 16-byte aligned.  Also align the virtual memory as each
5588          * maibox is copied into the bmbx mailbox region before issuing the
5589          * command to the port.
5590          */
5591         phba->sli4_hba.bmbx.dmabuf = dmabuf;
5592         phba->sli4_hba.bmbx.bmbx_size = bmbx_size;
5593
5594         phba->sli4_hba.bmbx.avirt = PTR_ALIGN(dmabuf->virt,
5595                                               LPFC_ALIGN_16_BYTE);
5596         phba->sli4_hba.bmbx.aphys = ALIGN(dmabuf->phys,
5597                                               LPFC_ALIGN_16_BYTE);
5598
5599         /*
5600          * Set the high and low physical addresses now.  The SLI4 alignment
5601          * requirement is 16 bytes and the mailbox is posted to the port
5602          * as two 30-bit addresses.  The other data is a bit marking whether
5603          * the 30-bit address is the high or low address.
5604          * Upcast bmbx aphys to 64bits so shift instruction compiles
5605          * clean on 32 bit machines.
5606          */
5607         dma_address = &phba->sli4_hba.bmbx.dma_address;
5608         phys_addr = (uint64_t)phba->sli4_hba.bmbx.aphys;
5609         pa_addr = (uint32_t) ((phys_addr >> 34) & 0x3fffffff);
5610         dma_address->addr_hi = (uint32_t) ((pa_addr << 2) |
5611                                            LPFC_BMBX_BIT1_ADDR_HI);
5612
5613         pa_addr = (uint32_t) ((phba->sli4_hba.bmbx.aphys >> 4) & 0x3fffffff);
5614         dma_address->addr_lo = (uint32_t) ((pa_addr << 2) |
5615                                            LPFC_BMBX_BIT1_ADDR_LO);
5616         return 0;
5617 }
5618
5619 /**
5620  * lpfc_destroy_bootstrap_mbox - Destroy all bootstrap mailbox resources
5621  * @phba: pointer to lpfc hba data structure.
5622  *
5623  * This routine is invoked to teardown the bootstrap mailbox
5624  * region and release all host resources. This routine requires
5625  * the caller to ensure all mailbox commands recovered, no
5626  * additional mailbox comands are sent, and interrupts are disabled
5627  * before calling this routine.
5628  *
5629  **/
5630 static void
5631 lpfc_destroy_bootstrap_mbox(struct lpfc_hba *phba)
5632 {
5633         dma_free_coherent(&phba->pcidev->dev,
5634                           phba->sli4_hba.bmbx.bmbx_size,
5635                           phba->sli4_hba.bmbx.dmabuf->virt,
5636                           phba->sli4_hba.bmbx.dmabuf->phys);
5637
5638         kfree(phba->sli4_hba.bmbx.dmabuf);
5639         memset(&phba->sli4_hba.bmbx, 0, sizeof(struct lpfc_bmbx));
5640 }
5641
5642 /**
5643  * lpfc_sli4_read_config - Get the config parameters.
5644  * @phba: pointer to lpfc hba data structure.
5645  *
5646  * This routine is invoked to read the configuration parameters from the HBA.
5647  * The configuration parameters are used to set the base and maximum values
5648  * for RPI's XRI's VPI's VFI's and FCFIs. These values also affect the resource
5649  * allocation for the port.
5650  *
5651  * Return codes
5652  *      0 - successful
5653  *      -ENOMEM - No availble memory
5654  *      -EIO - The mailbox failed to complete successfully.
5655  **/
5656 static int
5657 lpfc_sli4_read_config(struct lpfc_hba *phba)
5658 {
5659         LPFC_MBOXQ_t *pmb;
5660         struct lpfc_mbx_read_config *rd_config;
5661         uint32_t rc = 0;
5662
5663         pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5664         if (!pmb) {
5665                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5666                                 "2011 Unable to allocate memory for issuing "
5667                                 "SLI_CONFIG_SPECIAL mailbox command\n");
5668                 return -ENOMEM;
5669         }
5670
5671         lpfc_read_config(phba, pmb);
5672
5673         rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
5674         if (rc != MBX_SUCCESS) {
5675                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5676                         "2012 Mailbox failed , mbxCmd x%x "
5677                         "READ_CONFIG, mbxStatus x%x\n",
5678                         bf_get(lpfc_mqe_command, &pmb->u.mqe),
5679                         bf_get(lpfc_mqe_status, &pmb->u.mqe));
5680                 rc = -EIO;
5681         } else {
5682                 rd_config = &pmb->u.mqe.un.rd_config;
5683                 phba->sli4_hba.max_cfg_param.max_xri =
5684                         bf_get(lpfc_mbx_rd_conf_xri_count, rd_config);
5685                 phba->sli4_hba.max_cfg_param.xri_base =
5686                         bf_get(lpfc_mbx_rd_conf_xri_base, rd_config);
5687                 phba->sli4_hba.max_cfg_param.max_vpi =
5688                         bf_get(lpfc_mbx_rd_conf_vpi_count, rd_config);
5689                 phba->sli4_hba.max_cfg_param.vpi_base =
5690                         bf_get(lpfc_mbx_rd_conf_vpi_base, rd_config);
5691                 phba->sli4_hba.max_cfg_param.max_rpi =
5692                         bf_get(lpfc_mbx_rd_conf_rpi_count, rd_config);
5693                 phba->sli4_hba.max_cfg_param.rpi_base =
5694                         bf_get(lpfc_mbx_rd_conf_rpi_base, rd_config);
5695                 phba->sli4_hba.max_cfg_param.max_vfi =
5696                         bf_get(lpfc_mbx_rd_conf_vfi_count, rd_config);
5697                 phba->sli4_hba.max_cfg_param.vfi_base =
5698                         bf_get(lpfc_mbx_rd_conf_vfi_base, rd_config);
5699                 phba->sli4_hba.max_cfg_param.max_fcfi =
5700                         bf_get(lpfc_mbx_rd_conf_fcfi_count, rd_config);
5701                 phba->sli4_hba.max_cfg_param.fcfi_base =
5702                         bf_get(lpfc_mbx_rd_conf_fcfi_base, rd_config);
5703                 phba->sli4_hba.max_cfg_param.max_eq =
5704                         bf_get(lpfc_mbx_rd_conf_eq_count, rd_config);
5705                 phba->sli4_hba.max_cfg_param.max_rq =
5706                         bf_get(lpfc_mbx_rd_conf_rq_count, rd_config);
5707                 phba->sli4_hba.max_cfg_param.max_wq =
5708                         bf_get(lpfc_mbx_rd_conf_wq_count, rd_config);
5709                 phba->sli4_hba.max_cfg_param.max_cq =
5710                         bf_get(lpfc_mbx_rd_conf_cq_count, rd_config);
5711                 phba->lmt = bf_get(lpfc_mbx_rd_conf_lmt, rd_config);
5712                 phba->sli4_hba.next_xri = phba->sli4_hba.max_cfg_param.xri_base;
5713                 phba->vpi_base = phba->sli4_hba.max_cfg_param.vpi_base;
5714                 phba->vfi_base = phba->sli4_hba.max_cfg_param.vfi_base;
5715                 phba->sli4_hba.next_rpi = phba->sli4_hba.max_cfg_param.rpi_base;
5716                 phba->max_vpi = (phba->sli4_hba.max_cfg_param.max_vpi > 0) ?
5717                                 (phba->sli4_hba.max_cfg_param.max_vpi - 1) : 0;
5718                 phba->max_vports = phba->max_vpi;
5719                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5720                                 "2003 cfg params XRI(B:%d M:%d), "
5721                                 "VPI(B:%d M:%d) "
5722                                 "VFI(B:%d M:%d) "
5723                                 "RPI(B:%d M:%d) "
5724                                 "FCFI(B:%d M:%d)\n",
5725                                 phba->sli4_hba.max_cfg_param.xri_base,
5726                                 phba->sli4_hba.max_cfg_param.max_xri,
5727                                 phba->sli4_hba.max_cfg_param.vpi_base,
5728                                 phba->sli4_hba.max_cfg_param.max_vpi,
5729                                 phba->sli4_hba.max_cfg_param.vfi_base,
5730                                 phba->sli4_hba.max_cfg_param.max_vfi,
5731                                 phba->sli4_hba.max_cfg_param.rpi_base,
5732                                 phba->sli4_hba.max_cfg_param.max_rpi,
5733                                 phba->sli4_hba.max_cfg_param.fcfi_base,
5734                                 phba->sli4_hba.max_cfg_param.max_fcfi);
5735         }
5736         mempool_free(pmb, phba->mbox_mem_pool);
5737
5738         /* Reset the DFT_HBA_Q_DEPTH to the max xri  */
5739         if (phba->cfg_hba_queue_depth >
5740                 (phba->sli4_hba.max_cfg_param.max_xri -
5741                         lpfc_sli4_get_els_iocb_cnt(phba)))
5742                 phba->cfg_hba_queue_depth =
5743                         phba->sli4_hba.max_cfg_param.max_xri -
5744                                 lpfc_sli4_get_els_iocb_cnt(phba);
5745         return rc;
5746 }
5747
5748 /**
5749  * lpfc_dev_endian_order_setup - Notify the port of the host's endian order.
5750  * @phba: pointer to lpfc hba data structure.
5751  *
5752  * This routine is invoked to setup the host-side endian order to the
5753  * HBA consistent with the SLI-4 interface spec.
5754  *
5755  * Return codes
5756  *      0 - successful
5757  *      -ENOMEM - No availble memory
5758  *      -EIO - The mailbox failed to complete successfully.
5759  **/
5760 static int
5761 lpfc_setup_endian_order(struct lpfc_hba *phba)
5762 {
5763         LPFC_MBOXQ_t *mboxq;
5764         uint32_t rc = 0;
5765         uint32_t endian_mb_data[2] = {HOST_ENDIAN_LOW_WORD0,
5766                                       HOST_ENDIAN_HIGH_WORD1};
5767
5768         mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5769         if (!mboxq) {
5770                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5771                                 "0492 Unable to allocate memory for issuing "
5772                                 "SLI_CONFIG_SPECIAL mailbox command\n");
5773                 return -ENOMEM;
5774         }
5775
5776         /*
5777          * The SLI4_CONFIG_SPECIAL mailbox command requires the first two
5778          * words to contain special data values and no other data.
5779          */
5780         memset(mboxq, 0, sizeof(LPFC_MBOXQ_t));
5781         memcpy(&mboxq->u.mqe, &endian_mb_data, sizeof(endian_mb_data));
5782         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5783         if (rc != MBX_SUCCESS) {
5784                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5785                                 "0493 SLI_CONFIG_SPECIAL mailbox failed with "
5786                                 "status x%x\n",
5787                                 rc);