Merge git://git.kernel.org/pub/scm/linux/kernel/git/pkl/squashfs-next
[pandora-kernel.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-2011 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 #include <linux/firmware.h>
34
35 #include <scsi/scsi.h>
36 #include <scsi/scsi_device.h>
37 #include <scsi/scsi_host.h>
38 #include <scsi/scsi_transport_fc.h>
39
40 #include "lpfc_hw4.h"
41 #include "lpfc_hw.h"
42 #include "lpfc_sli.h"
43 #include "lpfc_sli4.h"
44 #include "lpfc_nl.h"
45 #include "lpfc_disc.h"
46 #include "lpfc_scsi.h"
47 #include "lpfc.h"
48 #include "lpfc_logmsg.h"
49 #include "lpfc_crtn.h"
50 #include "lpfc_vport.h"
51 #include "lpfc_version.h"
52
53 char *_dump_buf_data;
54 unsigned long _dump_buf_data_order;
55 char *_dump_buf_dif;
56 unsigned long _dump_buf_dif_order;
57 spinlock_t _dump_buf_lock;
58
59 static void lpfc_get_hba_model_desc(struct lpfc_hba *, uint8_t *, uint8_t *);
60 static int lpfc_post_rcv_buf(struct lpfc_hba *);
61 static int lpfc_sli4_queue_verify(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         do {
215                 lpfc_dump_mem(phba, pmb, offset, DMP_REGION_VPD);
216                 rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
217
218                 if (rc != MBX_SUCCESS) {
219                         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
220                                         "0441 VPD not present on adapter, "
221                                         "mbxCmd x%x DUMP VPD, mbxStatus x%x\n",
222                                         mb->mbxCommand, mb->mbxStatus);
223                         mb->un.varDmp.word_cnt = 0;
224                 }
225                 /* dump mem may return a zero when finished or we got a
226                  * mailbox error, either way we are done.
227                  */
228                 if (mb->un.varDmp.word_cnt == 0)
229                         break;
230                 if (mb->un.varDmp.word_cnt > DMP_VPD_SIZE - offset)
231                         mb->un.varDmp.word_cnt = DMP_VPD_SIZE - offset;
232                 lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
233                                       lpfc_vpd_data + offset,
234                                       mb->un.varDmp.word_cnt);
235                 offset += mb->un.varDmp.word_cnt;
236         } while (mb->un.varDmp.word_cnt && offset < DMP_VPD_SIZE);
237         lpfc_parse_vpd(phba, lpfc_vpd_data, offset);
238
239         kfree(lpfc_vpd_data);
240 out_free_mbox:
241         mempool_free(pmb, phba->mbox_mem_pool);
242         return 0;
243 }
244
245 /**
246  * lpfc_config_async_cmpl - Completion handler for config async event mbox cmd
247  * @phba: pointer to lpfc hba data structure.
248  * @pmboxq: pointer to the driver internal queue element for mailbox command.
249  *
250  * This is the completion handler for driver's configuring asynchronous event
251  * mailbox command to the device. If the mailbox command returns successfully,
252  * it will set internal async event support flag to 1; otherwise, it will
253  * set internal async event support flag to 0.
254  **/
255 static void
256 lpfc_config_async_cmpl(struct lpfc_hba * phba, LPFC_MBOXQ_t * pmboxq)
257 {
258         if (pmboxq->u.mb.mbxStatus == MBX_SUCCESS)
259                 phba->temp_sensor_support = 1;
260         else
261                 phba->temp_sensor_support = 0;
262         mempool_free(pmboxq, phba->mbox_mem_pool);
263         return;
264 }
265
266 /**
267  * lpfc_dump_wakeup_param_cmpl - dump memory mailbox command completion handler
268  * @phba: pointer to lpfc hba data structure.
269  * @pmboxq: pointer to the driver internal queue element for mailbox command.
270  *
271  * This is the completion handler for dump mailbox command for getting
272  * wake up parameters. When this command complete, the response contain
273  * Option rom version of the HBA. This function translate the version number
274  * into a human readable string and store it in OptionROMVersion.
275  **/
276 static void
277 lpfc_dump_wakeup_param_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
278 {
279         struct prog_id *prg;
280         uint32_t prog_id_word;
281         char dist = ' ';
282         /* character array used for decoding dist type. */
283         char dist_char[] = "nabx";
284
285         if (pmboxq->u.mb.mbxStatus != MBX_SUCCESS) {
286                 mempool_free(pmboxq, phba->mbox_mem_pool);
287                 return;
288         }
289
290         prg = (struct prog_id *) &prog_id_word;
291
292         /* word 7 contain option rom version */
293         prog_id_word = pmboxq->u.mb.un.varWords[7];
294
295         /* Decode the Option rom version word to a readable string */
296         if (prg->dist < 4)
297                 dist = dist_char[prg->dist];
298
299         if ((prg->dist == 3) && (prg->num == 0))
300                 sprintf(phba->OptionROMVersion, "%d.%d%d",
301                         prg->ver, prg->rev, prg->lev);
302         else
303                 sprintf(phba->OptionROMVersion, "%d.%d%d%c%d",
304                         prg->ver, prg->rev, prg->lev,
305                         dist, prg->num);
306         mempool_free(pmboxq, phba->mbox_mem_pool);
307         return;
308 }
309
310 /**
311  * lpfc_update_vport_wwn - Updates the fc_nodename, fc_portname,
312  *      cfg_soft_wwnn, cfg_soft_wwpn
313  * @vport: pointer to lpfc vport data structure.
314  *
315  *
316  * Return codes
317  *   None.
318  **/
319 void
320 lpfc_update_vport_wwn(struct lpfc_vport *vport)
321 {
322         /* If the soft name exists then update it using the service params */
323         if (vport->phba->cfg_soft_wwnn)
324                 u64_to_wwn(vport->phba->cfg_soft_wwnn,
325                            vport->fc_sparam.nodeName.u.wwn);
326         if (vport->phba->cfg_soft_wwpn)
327                 u64_to_wwn(vport->phba->cfg_soft_wwpn,
328                            vport->fc_sparam.portName.u.wwn);
329
330         /*
331          * If the name is empty or there exists a soft name
332          * then copy the service params name, otherwise use the fc name
333          */
334         if (vport->fc_nodename.u.wwn[0] == 0 || vport->phba->cfg_soft_wwnn)
335                 memcpy(&vport->fc_nodename, &vport->fc_sparam.nodeName,
336                         sizeof(struct lpfc_name));
337         else
338                 memcpy(&vport->fc_sparam.nodeName, &vport->fc_nodename,
339                         sizeof(struct lpfc_name));
340
341         if (vport->fc_portname.u.wwn[0] == 0 || vport->phba->cfg_soft_wwpn)
342                 memcpy(&vport->fc_portname, &vport->fc_sparam.portName,
343                         sizeof(struct lpfc_name));
344         else
345                 memcpy(&vport->fc_sparam.portName, &vport->fc_portname,
346                         sizeof(struct lpfc_name));
347 }
348
349 /**
350  * lpfc_config_port_post - Perform lpfc initialization after config port
351  * @phba: pointer to lpfc hba data structure.
352  *
353  * This routine will do LPFC initialization after the CONFIG_PORT mailbox
354  * command call. It performs all internal resource and state setups on the
355  * port: post IOCB buffers, enable appropriate host interrupt attentions,
356  * ELS ring timers, etc.
357  *
358  * Return codes
359  *   0 - success.
360  *   Any other value - error.
361  **/
362 int
363 lpfc_config_port_post(struct lpfc_hba *phba)
364 {
365         struct lpfc_vport *vport = phba->pport;
366         struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
367         LPFC_MBOXQ_t *pmb;
368         MAILBOX_t *mb;
369         struct lpfc_dmabuf *mp;
370         struct lpfc_sli *psli = &phba->sli;
371         uint32_t status, timeout;
372         int i, j;
373         int rc;
374
375         spin_lock_irq(&phba->hbalock);
376         /*
377          * If the Config port completed correctly the HBA is not
378          * over heated any more.
379          */
380         if (phba->over_temp_state == HBA_OVER_TEMP)
381                 phba->over_temp_state = HBA_NORMAL_TEMP;
382         spin_unlock_irq(&phba->hbalock);
383
384         pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
385         if (!pmb) {
386                 phba->link_state = LPFC_HBA_ERROR;
387                 return -ENOMEM;
388         }
389         mb = &pmb->u.mb;
390
391         /* Get login parameters for NID.  */
392         rc = lpfc_read_sparam(phba, pmb, 0);
393         if (rc) {
394                 mempool_free(pmb, phba->mbox_mem_pool);
395                 return -ENOMEM;
396         }
397
398         pmb->vport = vport;
399         if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
400                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
401                                 "0448 Adapter failed init, mbxCmd x%x "
402                                 "READ_SPARM mbxStatus x%x\n",
403                                 mb->mbxCommand, mb->mbxStatus);
404                 phba->link_state = LPFC_HBA_ERROR;
405                 mp = (struct lpfc_dmabuf *) pmb->context1;
406                 mempool_free(pmb, phba->mbox_mem_pool);
407                 lpfc_mbuf_free(phba, mp->virt, mp->phys);
408                 kfree(mp);
409                 return -EIO;
410         }
411
412         mp = (struct lpfc_dmabuf *) pmb->context1;
413
414         memcpy(&vport->fc_sparam, mp->virt, sizeof (struct serv_parm));
415         lpfc_mbuf_free(phba, mp->virt, mp->phys);
416         kfree(mp);
417         pmb->context1 = NULL;
418         lpfc_update_vport_wwn(vport);
419
420         /* Update the fc_host data structures with new wwn. */
421         fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
422         fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
423         fc_host_max_npiv_vports(shost) = phba->max_vpi;
424
425         /* If no serial number in VPD data, use low 6 bytes of WWNN */
426         /* This should be consolidated into parse_vpd ? - mr */
427         if (phba->SerialNumber[0] == 0) {
428                 uint8_t *outptr;
429
430                 outptr = &vport->fc_nodename.u.s.IEEE[0];
431                 for (i = 0; i < 12; i++) {
432                         status = *outptr++;
433                         j = ((status & 0xf0) >> 4);
434                         if (j <= 9)
435                                 phba->SerialNumber[i] =
436                                     (char)((uint8_t) 0x30 + (uint8_t) j);
437                         else
438                                 phba->SerialNumber[i] =
439                                     (char)((uint8_t) 0x61 + (uint8_t) (j - 10));
440                         i++;
441                         j = (status & 0xf);
442                         if (j <= 9)
443                                 phba->SerialNumber[i] =
444                                     (char)((uint8_t) 0x30 + (uint8_t) j);
445                         else
446                                 phba->SerialNumber[i] =
447                                     (char)((uint8_t) 0x61 + (uint8_t) (j - 10));
448                 }
449         }
450
451         lpfc_read_config(phba, pmb);
452         pmb->vport = vport;
453         if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
454                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
455                                 "0453 Adapter failed to init, mbxCmd x%x "
456                                 "READ_CONFIG, mbxStatus x%x\n",
457                                 mb->mbxCommand, mb->mbxStatus);
458                 phba->link_state = LPFC_HBA_ERROR;
459                 mempool_free( pmb, phba->mbox_mem_pool);
460                 return -EIO;
461         }
462
463         /* Check if the port is disabled */
464         lpfc_sli_read_link_ste(phba);
465
466         /* Reset the DFT_HBA_Q_DEPTH to the max xri  */
467         if (phba->cfg_hba_queue_depth > (mb->un.varRdConfig.max_xri+1))
468                 phba->cfg_hba_queue_depth =
469                         (mb->un.varRdConfig.max_xri + 1) -
470                                         lpfc_sli4_get_els_iocb_cnt(phba);
471
472         phba->lmt = mb->un.varRdConfig.lmt;
473
474         /* Get the default values for Model Name and Description */
475         lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
476
477         if ((phba->cfg_link_speed > LPFC_USER_LINK_SPEED_16G)
478             || ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_1G)
479                 && !(phba->lmt & LMT_1Gb))
480             || ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_2G)
481                 && !(phba->lmt & LMT_2Gb))
482             || ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_4G)
483                 && !(phba->lmt & LMT_4Gb))
484             || ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_8G)
485                 && !(phba->lmt & LMT_8Gb))
486             || ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_10G)
487                 && !(phba->lmt & LMT_10Gb))
488             || ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_16G)
489                 && !(phba->lmt & LMT_16Gb))) {
490                 /* Reset link speed to auto */
491                 lpfc_printf_log(phba, KERN_ERR, LOG_LINK_EVENT,
492                         "1302 Invalid speed for this board: "
493                         "Reset link speed to auto: x%x\n",
494                         phba->cfg_link_speed);
495                         phba->cfg_link_speed = LPFC_USER_LINK_SPEED_AUTO;
496         }
497
498         phba->link_state = LPFC_LINK_DOWN;
499
500         /* Only process IOCBs on ELS ring till hba_state is READY */
501         if (psli->ring[psli->extra_ring].cmdringaddr)
502                 psli->ring[psli->extra_ring].flag |= LPFC_STOP_IOCB_EVENT;
503         if (psli->ring[psli->fcp_ring].cmdringaddr)
504                 psli->ring[psli->fcp_ring].flag |= LPFC_STOP_IOCB_EVENT;
505         if (psli->ring[psli->next_ring].cmdringaddr)
506                 psli->ring[psli->next_ring].flag |= LPFC_STOP_IOCB_EVENT;
507
508         /* Post receive buffers for desired rings */
509         if (phba->sli_rev != 3)
510                 lpfc_post_rcv_buf(phba);
511
512         /*
513          * Configure HBA MSI-X attention conditions to messages if MSI-X mode
514          */
515         if (phba->intr_type == MSIX) {
516                 rc = lpfc_config_msi(phba, pmb);
517                 if (rc) {
518                         mempool_free(pmb, phba->mbox_mem_pool);
519                         return -EIO;
520                 }
521                 rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
522                 if (rc != MBX_SUCCESS) {
523                         lpfc_printf_log(phba, KERN_ERR, LOG_MBOX,
524                                         "0352 Config MSI mailbox command "
525                                         "failed, mbxCmd x%x, mbxStatus x%x\n",
526                                         pmb->u.mb.mbxCommand,
527                                         pmb->u.mb.mbxStatus);
528                         mempool_free(pmb, phba->mbox_mem_pool);
529                         return -EIO;
530                 }
531         }
532
533         spin_lock_irq(&phba->hbalock);
534         /* Initialize ERATT handling flag */
535         phba->hba_flag &= ~HBA_ERATT_HANDLED;
536
537         /* Enable appropriate host interrupts */
538         if (lpfc_readl(phba->HCregaddr, &status)) {
539                 spin_unlock_irq(&phba->hbalock);
540                 return -EIO;
541         }
542         status |= HC_MBINT_ENA | HC_ERINT_ENA | HC_LAINT_ENA;
543         if (psli->num_rings > 0)
544                 status |= HC_R0INT_ENA;
545         if (psli->num_rings > 1)
546                 status |= HC_R1INT_ENA;
547         if (psli->num_rings > 2)
548                 status |= HC_R2INT_ENA;
549         if (psli->num_rings > 3)
550                 status |= HC_R3INT_ENA;
551
552         if ((phba->cfg_poll & ENABLE_FCP_RING_POLLING) &&
553             (phba->cfg_poll & DISABLE_FCP_RING_INT))
554                 status &= ~(HC_R0INT_ENA);
555
556         writel(status, phba->HCregaddr);
557         readl(phba->HCregaddr); /* flush */
558         spin_unlock_irq(&phba->hbalock);
559
560         /* Set up ring-0 (ELS) timer */
561         timeout = phba->fc_ratov * 2;
562         mod_timer(&vport->els_tmofunc, jiffies + HZ * timeout);
563         /* Set up heart beat (HB) timer */
564         mod_timer(&phba->hb_tmofunc, jiffies + HZ * LPFC_HB_MBOX_INTERVAL);
565         phba->hb_outstanding = 0;
566         phba->last_completion_time = jiffies;
567         /* Set up error attention (ERATT) polling timer */
568         mod_timer(&phba->eratt_poll, jiffies + HZ * LPFC_ERATT_POLL_INTERVAL);
569
570         if (phba->hba_flag & LINK_DISABLED) {
571                 lpfc_printf_log(phba,
572                         KERN_ERR, LOG_INIT,
573                         "2598 Adapter Link is disabled.\n");
574                 lpfc_down_link(phba, pmb);
575                 pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
576                 rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
577                 if ((rc != MBX_SUCCESS) && (rc != MBX_BUSY)) {
578                         lpfc_printf_log(phba,
579                         KERN_ERR, LOG_INIT,
580                         "2599 Adapter failed to issue DOWN_LINK"
581                         " mbox command rc 0x%x\n", rc);
582
583                         mempool_free(pmb, phba->mbox_mem_pool);
584                         return -EIO;
585                 }
586         } else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
587                 lpfc_init_link(phba, pmb, phba->cfg_topology,
588                         phba->cfg_link_speed);
589                 pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
590                 lpfc_set_loopback_flag(phba);
591                 rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
592                 if (rc != MBX_SUCCESS) {
593                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
594                                 "0454 Adapter failed to init, mbxCmd x%x "
595                                 "INIT_LINK, mbxStatus x%x\n",
596                                 mb->mbxCommand, mb->mbxStatus);
597
598                         /* Clear all interrupt enable conditions */
599                         writel(0, phba->HCregaddr);
600                         readl(phba->HCregaddr); /* flush */
601                         /* Clear all pending interrupts */
602                         writel(0xffffffff, phba->HAregaddr);
603                         readl(phba->HAregaddr); /* flush */
604                         phba->link_state = LPFC_HBA_ERROR;
605                         if (rc != MBX_BUSY)
606                                 mempool_free(pmb, phba->mbox_mem_pool);
607                         return -EIO;
608                 }
609         }
610         /* MBOX buffer will be freed in mbox compl */
611         pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
612         if (!pmb) {
613                 phba->link_state = LPFC_HBA_ERROR;
614                 return -ENOMEM;
615         }
616
617         lpfc_config_async(phba, pmb, LPFC_ELS_RING);
618         pmb->mbox_cmpl = lpfc_config_async_cmpl;
619         pmb->vport = phba->pport;
620         rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
621
622         if ((rc != MBX_BUSY) && (rc != MBX_SUCCESS)) {
623                 lpfc_printf_log(phba,
624                                 KERN_ERR,
625                                 LOG_INIT,
626                                 "0456 Adapter failed to issue "
627                                 "ASYNCEVT_ENABLE mbox status x%x\n",
628                                 rc);
629                 mempool_free(pmb, phba->mbox_mem_pool);
630         }
631
632         /* Get Option rom version */
633         pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
634         if (!pmb) {
635                 phba->link_state = LPFC_HBA_ERROR;
636                 return -ENOMEM;
637         }
638
639         lpfc_dump_wakeup_param(phba, pmb);
640         pmb->mbox_cmpl = lpfc_dump_wakeup_param_cmpl;
641         pmb->vport = phba->pport;
642         rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
643
644         if ((rc != MBX_BUSY) && (rc != MBX_SUCCESS)) {
645                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT, "0435 Adapter failed "
646                                 "to get Option ROM version status x%x\n", rc);
647                 mempool_free(pmb, phba->mbox_mem_pool);
648         }
649
650         return 0;
651 }
652
653 /**
654  * lpfc_hba_init_link - Initialize the FC link
655  * @phba: pointer to lpfc hba data structure.
656  * @flag: mailbox command issue mode - either MBX_POLL or MBX_NOWAIT
657  *
658  * This routine will issue the INIT_LINK mailbox command call.
659  * It is available to other drivers through the lpfc_hba data
660  * structure for use as a delayed link up mechanism with the
661  * module parameter lpfc_suppress_link_up.
662  *
663  * Return code
664  *              0 - success
665  *              Any other value - error
666  **/
667 int
668 lpfc_hba_init_link(struct lpfc_hba *phba, uint32_t flag)
669 {
670         struct lpfc_vport *vport = phba->pport;
671         LPFC_MBOXQ_t *pmb;
672         MAILBOX_t *mb;
673         int rc;
674
675         pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
676         if (!pmb) {
677                 phba->link_state = LPFC_HBA_ERROR;
678                 return -ENOMEM;
679         }
680         mb = &pmb->u.mb;
681         pmb->vport = vport;
682
683         lpfc_init_link(phba, pmb, phba->cfg_topology, phba->cfg_link_speed);
684         pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
685         lpfc_set_loopback_flag(phba);
686         rc = lpfc_sli_issue_mbox(phba, pmb, flag);
687         if ((rc != MBX_BUSY) && (rc != MBX_SUCCESS)) {
688                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
689                         "0498 Adapter failed to init, mbxCmd x%x "
690                         "INIT_LINK, mbxStatus x%x\n",
691                         mb->mbxCommand, mb->mbxStatus);
692                 if (phba->sli_rev <= LPFC_SLI_REV3) {
693                         /* Clear all interrupt enable conditions */
694                         writel(0, phba->HCregaddr);
695                         readl(phba->HCregaddr); /* flush */
696                         /* Clear all pending interrupts */
697                         writel(0xffffffff, phba->HAregaddr);
698                         readl(phba->HAregaddr); /* flush */
699                 }
700                 phba->link_state = LPFC_HBA_ERROR;
701                 if (rc != MBX_BUSY || flag == MBX_POLL)
702                         mempool_free(pmb, phba->mbox_mem_pool);
703                 return -EIO;
704         }
705         phba->cfg_suppress_link_up = LPFC_INITIALIZE_LINK;
706         if (flag == MBX_POLL)
707                 mempool_free(pmb, phba->mbox_mem_pool);
708
709         return 0;
710 }
711
712 /**
713  * lpfc_hba_down_link - this routine downs the FC link
714  * @phba: pointer to lpfc hba data structure.
715  * @flag: mailbox command issue mode - either MBX_POLL or MBX_NOWAIT
716  *
717  * This routine will issue the DOWN_LINK mailbox command call.
718  * It is available to other drivers through the lpfc_hba data
719  * structure for use to stop the link.
720  *
721  * Return code
722  *              0 - success
723  *              Any other value - error
724  **/
725 int
726 lpfc_hba_down_link(struct lpfc_hba *phba, uint32_t flag)
727 {
728         LPFC_MBOXQ_t *pmb;
729         int rc;
730
731         pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
732         if (!pmb) {
733                 phba->link_state = LPFC_HBA_ERROR;
734                 return -ENOMEM;
735         }
736
737         lpfc_printf_log(phba,
738                 KERN_ERR, LOG_INIT,
739                 "0491 Adapter Link is disabled.\n");
740         lpfc_down_link(phba, pmb);
741         pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
742         rc = lpfc_sli_issue_mbox(phba, pmb, flag);
743         if ((rc != MBX_SUCCESS) && (rc != MBX_BUSY)) {
744                 lpfc_printf_log(phba,
745                 KERN_ERR, LOG_INIT,
746                 "2522 Adapter failed to issue DOWN_LINK"
747                 " mbox command rc 0x%x\n", rc);
748
749                 mempool_free(pmb, phba->mbox_mem_pool);
750                 return -EIO;
751         }
752         if (flag == MBX_POLL)
753                 mempool_free(pmb, phba->mbox_mem_pool);
754
755         return 0;
756 }
757
758 /**
759  * lpfc_hba_down_prep - Perform lpfc uninitialization prior to HBA reset
760  * @phba: pointer to lpfc HBA data structure.
761  *
762  * This routine will do LPFC uninitialization before the HBA is reset when
763  * bringing down the SLI Layer.
764  *
765  * Return codes
766  *   0 - success.
767  *   Any other value - error.
768  **/
769 int
770 lpfc_hba_down_prep(struct lpfc_hba *phba)
771 {
772         struct lpfc_vport **vports;
773         int i;
774
775         if (phba->sli_rev <= LPFC_SLI_REV3) {
776                 /* Disable interrupts */
777                 writel(0, phba->HCregaddr);
778                 readl(phba->HCregaddr); /* flush */
779         }
780
781         if (phba->pport->load_flag & FC_UNLOADING)
782                 lpfc_cleanup_discovery_resources(phba->pport);
783         else {
784                 vports = lpfc_create_vport_work_array(phba);
785                 if (vports != NULL)
786                         for (i = 0; i <= phba->max_vports &&
787                                 vports[i] != NULL; i++)
788                                 lpfc_cleanup_discovery_resources(vports[i]);
789                 lpfc_destroy_vport_work_array(phba, vports);
790         }
791         return 0;
792 }
793
794 /**
795  * lpfc_hba_down_post_s3 - Perform lpfc uninitialization after HBA reset
796  * @phba: pointer to lpfc HBA data structure.
797  *
798  * This routine will do uninitialization after the HBA is reset when bring
799  * down the SLI Layer.
800  *
801  * Return codes
802  *   0 - success.
803  *   Any other value - error.
804  **/
805 static int
806 lpfc_hba_down_post_s3(struct lpfc_hba *phba)
807 {
808         struct lpfc_sli *psli = &phba->sli;
809         struct lpfc_sli_ring *pring;
810         struct lpfc_dmabuf *mp, *next_mp;
811         LIST_HEAD(completions);
812         int i;
813
814         if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)
815                 lpfc_sli_hbqbuf_free_all(phba);
816         else {
817                 /* Cleanup preposted buffers on the ELS ring */
818                 pring = &psli->ring[LPFC_ELS_RING];
819                 list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
820                         list_del(&mp->list);
821                         pring->postbufq_cnt--;
822                         lpfc_mbuf_free(phba, mp->virt, mp->phys);
823                         kfree(mp);
824                 }
825         }
826
827         spin_lock_irq(&phba->hbalock);
828         for (i = 0; i < psli->num_rings; i++) {
829                 pring = &psli->ring[i];
830
831                 /* At this point in time the HBA is either reset or DOA. Either
832                  * way, nothing should be on txcmplq as it will NEVER complete.
833                  */
834                 list_splice_init(&pring->txcmplq, &completions);
835                 pring->txcmplq_cnt = 0;
836                 spin_unlock_irq(&phba->hbalock);
837
838                 /* Cancel all the IOCBs from the completions list */
839                 lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
840                                       IOERR_SLI_ABORTED);
841
842                 lpfc_sli_abort_iocb_ring(phba, pring);
843                 spin_lock_irq(&phba->hbalock);
844         }
845         spin_unlock_irq(&phba->hbalock);
846
847         return 0;
848 }
849
850 /**
851  * lpfc_hba_down_post_s4 - Perform lpfc uninitialization after HBA reset
852  * @phba: pointer to lpfc HBA data structure.
853  *
854  * This routine will do uninitialization after the HBA is reset when bring
855  * down the SLI Layer.
856  *
857  * Return codes
858  *   0 - success.
859  *   Any other value - error.
860  **/
861 static int
862 lpfc_hba_down_post_s4(struct lpfc_hba *phba)
863 {
864         struct lpfc_scsi_buf *psb, *psb_next;
865         LIST_HEAD(aborts);
866         int ret;
867         unsigned long iflag = 0;
868         struct lpfc_sglq *sglq_entry = NULL;
869
870         ret = lpfc_hba_down_post_s3(phba);
871         if (ret)
872                 return ret;
873         /* At this point in time the HBA is either reset or DOA. Either
874          * way, nothing should be on lpfc_abts_els_sgl_list, it needs to be
875          * on the lpfc_sgl_list so that it can either be freed if the
876          * driver is unloading or reposted if the driver is restarting
877          * the port.
878          */
879         spin_lock_irq(&phba->hbalock);  /* required for lpfc_sgl_list and */
880                                         /* scsl_buf_list */
881         /* abts_sgl_list_lock required because worker thread uses this
882          * list.
883          */
884         spin_lock(&phba->sli4_hba.abts_sgl_list_lock);
885         list_for_each_entry(sglq_entry,
886                 &phba->sli4_hba.lpfc_abts_els_sgl_list, list)
887                 sglq_entry->state = SGL_FREED;
888
889         list_splice_init(&phba->sli4_hba.lpfc_abts_els_sgl_list,
890                         &phba->sli4_hba.lpfc_sgl_list);
891         spin_unlock(&phba->sli4_hba.abts_sgl_list_lock);
892         /* abts_scsi_buf_list_lock required because worker thread uses this
893          * list.
894          */
895         spin_lock(&phba->sli4_hba.abts_scsi_buf_list_lock);
896         list_splice_init(&phba->sli4_hba.lpfc_abts_scsi_buf_list,
897                         &aborts);
898         spin_unlock(&phba->sli4_hba.abts_scsi_buf_list_lock);
899         spin_unlock_irq(&phba->hbalock);
900
901         list_for_each_entry_safe(psb, psb_next, &aborts, list) {
902                 psb->pCmd = NULL;
903                 psb->status = IOSTAT_SUCCESS;
904         }
905         spin_lock_irqsave(&phba->scsi_buf_list_lock, iflag);
906         list_splice(&aborts, &phba->lpfc_scsi_buf_list);
907         spin_unlock_irqrestore(&phba->scsi_buf_list_lock, iflag);
908         return 0;
909 }
910
911 /**
912  * lpfc_hba_down_post - Wrapper func for hba down post routine
913  * @phba: pointer to lpfc HBA data structure.
914  *
915  * This routine wraps the actual SLI3 or SLI4 routine for performing
916  * uninitialization after the HBA is reset when bring down the SLI Layer.
917  *
918  * Return codes
919  *   0 - success.
920  *   Any other value - error.
921  **/
922 int
923 lpfc_hba_down_post(struct lpfc_hba *phba)
924 {
925         return (*phba->lpfc_hba_down_post)(phba);
926 }
927
928 /**
929  * lpfc_hb_timeout - The HBA-timer timeout handler
930  * @ptr: unsigned long holds the pointer to lpfc hba data structure.
931  *
932  * This is the HBA-timer timeout handler registered to the lpfc driver. When
933  * this timer fires, a HBA timeout event shall be posted to the lpfc driver
934  * work-port-events bitmap and the worker thread is notified. This timeout
935  * event will be used by the worker thread to invoke the actual timeout
936  * handler routine, lpfc_hb_timeout_handler. Any periodical operations will
937  * be performed in the timeout handler and the HBA timeout event bit shall
938  * be cleared by the worker thread after it has taken the event bitmap out.
939  **/
940 static void
941 lpfc_hb_timeout(unsigned long ptr)
942 {
943         struct lpfc_hba *phba;
944         uint32_t tmo_posted;
945         unsigned long iflag;
946
947         phba = (struct lpfc_hba *)ptr;
948
949         /* Check for heart beat timeout conditions */
950         spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
951         tmo_posted = phba->pport->work_port_events & WORKER_HB_TMO;
952         if (!tmo_posted)
953                 phba->pport->work_port_events |= WORKER_HB_TMO;
954         spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
955
956         /* Tell the worker thread there is work to do */
957         if (!tmo_posted)
958                 lpfc_worker_wake_up(phba);
959         return;
960 }
961
962 /**
963  * lpfc_rrq_timeout - The RRQ-timer timeout handler
964  * @ptr: unsigned long holds the pointer to lpfc hba data structure.
965  *
966  * This is the RRQ-timer timeout handler registered to the lpfc driver. When
967  * this timer fires, a RRQ timeout event shall be posted to the lpfc driver
968  * work-port-events bitmap and the worker thread is notified. This timeout
969  * event will be used by the worker thread to invoke the actual timeout
970  * handler routine, lpfc_rrq_handler. Any periodical operations will
971  * be performed in the timeout handler and the RRQ timeout event bit shall
972  * be cleared by the worker thread after it has taken the event bitmap out.
973  **/
974 static void
975 lpfc_rrq_timeout(unsigned long ptr)
976 {
977         struct lpfc_hba *phba;
978         unsigned long iflag;
979
980         phba = (struct lpfc_hba *)ptr;
981         spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
982         phba->hba_flag |= HBA_RRQ_ACTIVE;
983         spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
984         lpfc_worker_wake_up(phba);
985 }
986
987 /**
988  * lpfc_hb_mbox_cmpl - The lpfc heart-beat mailbox command callback function
989  * @phba: pointer to lpfc hba data structure.
990  * @pmboxq: pointer to the driver internal queue element for mailbox command.
991  *
992  * This is the callback function to the lpfc heart-beat mailbox command.
993  * If configured, the lpfc driver issues the heart-beat mailbox command to
994  * the HBA every LPFC_HB_MBOX_INTERVAL (current 5) seconds. At the time the
995  * heart-beat mailbox command is issued, the driver shall set up heart-beat
996  * timeout timer to LPFC_HB_MBOX_TIMEOUT (current 30) seconds and marks
997  * heart-beat outstanding state. Once the mailbox command comes back and
998  * no error conditions detected, the heart-beat mailbox command timer is
999  * reset to LPFC_HB_MBOX_INTERVAL seconds and the heart-beat outstanding
1000  * state is cleared for the next heart-beat. If the timer expired with the
1001  * heart-beat outstanding state set, the driver will put the HBA offline.
1002  **/
1003 static void
1004 lpfc_hb_mbox_cmpl(struct lpfc_hba * phba, LPFC_MBOXQ_t * pmboxq)
1005 {
1006         unsigned long drvr_flag;
1007
1008         spin_lock_irqsave(&phba->hbalock, drvr_flag);
1009         phba->hb_outstanding = 0;
1010         spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
1011
1012         /* Check and reset heart-beat timer is necessary */
1013         mempool_free(pmboxq, phba->mbox_mem_pool);
1014         if (!(phba->pport->fc_flag & FC_OFFLINE_MODE) &&
1015                 !(phba->link_state == LPFC_HBA_ERROR) &&
1016                 !(phba->pport->load_flag & FC_UNLOADING))
1017                 mod_timer(&phba->hb_tmofunc,
1018                         jiffies + HZ * LPFC_HB_MBOX_INTERVAL);
1019         return;
1020 }
1021
1022 /**
1023  * lpfc_hb_timeout_handler - The HBA-timer timeout handler
1024  * @phba: pointer to lpfc hba data structure.
1025  *
1026  * This is the actual HBA-timer timeout handler to be invoked by the worker
1027  * thread whenever the HBA timer fired and HBA-timeout event posted. This
1028  * handler performs any periodic operations needed for the device. If such
1029  * periodic event has already been attended to either in the interrupt handler
1030  * or by processing slow-ring or fast-ring events within the HBA-timer
1031  * timeout window (LPFC_HB_MBOX_INTERVAL), this handler just simply resets
1032  * the timer for the next timeout period. If lpfc heart-beat mailbox command
1033  * is configured and there is no heart-beat mailbox command outstanding, a
1034  * heart-beat mailbox is issued and timer set properly. Otherwise, if there
1035  * has been a heart-beat mailbox command outstanding, the HBA shall be put
1036  * to offline.
1037  **/
1038 void
1039 lpfc_hb_timeout_handler(struct lpfc_hba *phba)
1040 {
1041         struct lpfc_vport **vports;
1042         LPFC_MBOXQ_t *pmboxq;
1043         struct lpfc_dmabuf *buf_ptr;
1044         int retval, i;
1045         struct lpfc_sli *psli = &phba->sli;
1046         LIST_HEAD(completions);
1047
1048         vports = lpfc_create_vport_work_array(phba);
1049         if (vports != NULL)
1050                 for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++)
1051                         lpfc_rcv_seq_check_edtov(vports[i]);
1052         lpfc_destroy_vport_work_array(phba, vports);
1053
1054         if ((phba->link_state == LPFC_HBA_ERROR) ||
1055                 (phba->pport->load_flag & FC_UNLOADING) ||
1056                 (phba->pport->fc_flag & FC_OFFLINE_MODE))
1057                 return;
1058
1059         spin_lock_irq(&phba->pport->work_port_lock);
1060
1061         if (time_after(phba->last_completion_time + LPFC_HB_MBOX_INTERVAL * HZ,
1062                 jiffies)) {
1063                 spin_unlock_irq(&phba->pport->work_port_lock);
1064                 if (!phba->hb_outstanding)
1065                         mod_timer(&phba->hb_tmofunc,
1066                                 jiffies + HZ * LPFC_HB_MBOX_INTERVAL);
1067                 else
1068                         mod_timer(&phba->hb_tmofunc,
1069                                 jiffies + HZ * LPFC_HB_MBOX_TIMEOUT);
1070                 return;
1071         }
1072         spin_unlock_irq(&phba->pport->work_port_lock);
1073
1074         if (phba->elsbuf_cnt &&
1075                 (phba->elsbuf_cnt == phba->elsbuf_prev_cnt)) {
1076                 spin_lock_irq(&phba->hbalock);
1077                 list_splice_init(&phba->elsbuf, &completions);
1078                 phba->elsbuf_cnt = 0;
1079                 phba->elsbuf_prev_cnt = 0;
1080                 spin_unlock_irq(&phba->hbalock);
1081
1082                 while (!list_empty(&completions)) {
1083                         list_remove_head(&completions, buf_ptr,
1084                                 struct lpfc_dmabuf, list);
1085                         lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
1086                         kfree(buf_ptr);
1087                 }
1088         }
1089         phba->elsbuf_prev_cnt = phba->elsbuf_cnt;
1090
1091         /* If there is no heart beat outstanding, issue a heartbeat command */
1092         if (phba->cfg_enable_hba_heartbeat) {
1093                 if (!phba->hb_outstanding) {
1094                         if ((!(psli->sli_flag & LPFC_SLI_MBOX_ACTIVE)) &&
1095                                 (list_empty(&psli->mboxq))) {
1096                                 pmboxq = mempool_alloc(phba->mbox_mem_pool,
1097                                                         GFP_KERNEL);
1098                                 if (!pmboxq) {
1099                                         mod_timer(&phba->hb_tmofunc,
1100                                                  jiffies +
1101                                                  HZ * LPFC_HB_MBOX_INTERVAL);
1102                                         return;
1103                                 }
1104
1105                                 lpfc_heart_beat(phba, pmboxq);
1106                                 pmboxq->mbox_cmpl = lpfc_hb_mbox_cmpl;
1107                                 pmboxq->vport = phba->pport;
1108                                 retval = lpfc_sli_issue_mbox(phba, pmboxq,
1109                                                 MBX_NOWAIT);
1110
1111                                 if (retval != MBX_BUSY &&
1112                                         retval != MBX_SUCCESS) {
1113                                         mempool_free(pmboxq,
1114                                                         phba->mbox_mem_pool);
1115                                         mod_timer(&phba->hb_tmofunc,
1116                                                 jiffies +
1117                                                 HZ * LPFC_HB_MBOX_INTERVAL);
1118                                         return;
1119                                 }
1120                                 phba->skipped_hb = 0;
1121                                 phba->hb_outstanding = 1;
1122                         } else if (time_before_eq(phba->last_completion_time,
1123                                         phba->skipped_hb)) {
1124                                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
1125                                         "2857 Last completion time not "
1126                                         " updated in %d ms\n",
1127                                         jiffies_to_msecs(jiffies
1128                                                  - phba->last_completion_time));
1129                         } else
1130                                 phba->skipped_hb = jiffies;
1131
1132                         mod_timer(&phba->hb_tmofunc,
1133                                   jiffies + HZ * LPFC_HB_MBOX_TIMEOUT);
1134                         return;
1135                 } else {
1136                         /*
1137                         * If heart beat timeout called with hb_outstanding set
1138                         * we need to give the hb mailbox cmd a chance to
1139                         * complete or TMO.
1140                         */
1141                         lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
1142                                         "0459 Adapter heartbeat still out"
1143                                         "standing:last compl time was %d ms.\n",
1144                                         jiffies_to_msecs(jiffies
1145                                                  - phba->last_completion_time));
1146                         mod_timer(&phba->hb_tmofunc,
1147                                   jiffies + HZ * LPFC_HB_MBOX_TIMEOUT);
1148                 }
1149         }
1150 }
1151
1152 /**
1153  * lpfc_offline_eratt - Bring lpfc offline on hardware error attention
1154  * @phba: pointer to lpfc hba data structure.
1155  *
1156  * This routine is called to bring the HBA offline when HBA hardware error
1157  * other than Port Error 6 has been detected.
1158  **/
1159 static void
1160 lpfc_offline_eratt(struct lpfc_hba *phba)
1161 {
1162         struct lpfc_sli   *psli = &phba->sli;
1163
1164         spin_lock_irq(&phba->hbalock);
1165         psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1166         spin_unlock_irq(&phba->hbalock);
1167         lpfc_offline_prep(phba);
1168
1169         lpfc_offline(phba);
1170         lpfc_reset_barrier(phba);
1171         spin_lock_irq(&phba->hbalock);
1172         lpfc_sli_brdreset(phba);
1173         spin_unlock_irq(&phba->hbalock);
1174         lpfc_hba_down_post(phba);
1175         lpfc_sli_brdready(phba, HS_MBRDY);
1176         lpfc_unblock_mgmt_io(phba);
1177         phba->link_state = LPFC_HBA_ERROR;
1178         return;
1179 }
1180
1181 /**
1182  * lpfc_sli4_offline_eratt - Bring lpfc offline on SLI4 hardware error attention
1183  * @phba: pointer to lpfc hba data structure.
1184  *
1185  * This routine is called to bring a SLI4 HBA offline when HBA hardware error
1186  * other than Port Error 6 has been detected.
1187  **/
1188 static void
1189 lpfc_sli4_offline_eratt(struct lpfc_hba *phba)
1190 {
1191         lpfc_offline_prep(phba);
1192         lpfc_offline(phba);
1193         lpfc_sli4_brdreset(phba);
1194         lpfc_hba_down_post(phba);
1195         lpfc_sli4_post_status_check(phba);
1196         lpfc_unblock_mgmt_io(phba);
1197         phba->link_state = LPFC_HBA_ERROR;
1198 }
1199
1200 /**
1201  * lpfc_handle_deferred_eratt - The HBA hardware deferred error handler
1202  * @phba: pointer to lpfc hba data structure.
1203  *
1204  * This routine is invoked to handle the deferred HBA hardware error
1205  * conditions. This type of error is indicated by HBA by setting ER1
1206  * and another ER bit in the host status register. The driver will
1207  * wait until the ER1 bit clears before handling the error condition.
1208  **/
1209 static void
1210 lpfc_handle_deferred_eratt(struct lpfc_hba *phba)
1211 {
1212         uint32_t old_host_status = phba->work_hs;
1213         struct lpfc_sli_ring  *pring;
1214         struct lpfc_sli *psli = &phba->sli;
1215
1216         /* If the pci channel is offline, ignore possible errors,
1217          * since we cannot communicate with the pci card anyway.
1218          */
1219         if (pci_channel_offline(phba->pcidev)) {
1220                 spin_lock_irq(&phba->hbalock);
1221                 phba->hba_flag &= ~DEFER_ERATT;
1222                 spin_unlock_irq(&phba->hbalock);
1223                 return;
1224         }
1225
1226         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
1227                 "0479 Deferred Adapter Hardware Error "
1228                 "Data: x%x x%x x%x\n",
1229                 phba->work_hs,
1230                 phba->work_status[0], phba->work_status[1]);
1231
1232         spin_lock_irq(&phba->hbalock);
1233         psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1234         spin_unlock_irq(&phba->hbalock);
1235
1236
1237         /*
1238          * Firmware stops when it triggred erratt. That could cause the I/Os
1239          * dropped by the firmware. Error iocb (I/O) on txcmplq and let the
1240          * SCSI layer retry it after re-establishing link.
1241          */
1242         pring = &psli->ring[psli->fcp_ring];
1243         lpfc_sli_abort_iocb_ring(phba, pring);
1244
1245         /*
1246          * There was a firmware error. Take the hba offline and then
1247          * attempt to restart it.
1248          */
1249         lpfc_offline_prep(phba);
1250         lpfc_offline(phba);
1251
1252         /* Wait for the ER1 bit to clear.*/
1253         while (phba->work_hs & HS_FFER1) {
1254                 msleep(100);
1255                 if (lpfc_readl(phba->HSregaddr, &phba->work_hs)) {
1256                         phba->work_hs = UNPLUG_ERR ;
1257                         break;
1258                 }
1259                 /* If driver is unloading let the worker thread continue */
1260                 if (phba->pport->load_flag & FC_UNLOADING) {
1261                         phba->work_hs = 0;
1262                         break;
1263                 }
1264         }
1265
1266         /*
1267          * This is to ptrotect against a race condition in which
1268          * first write to the host attention register clear the
1269          * host status register.
1270          */
1271         if ((!phba->work_hs) && (!(phba->pport->load_flag & FC_UNLOADING)))
1272                 phba->work_hs = old_host_status & ~HS_FFER1;
1273
1274         spin_lock_irq(&phba->hbalock);
1275         phba->hba_flag &= ~DEFER_ERATT;
1276         spin_unlock_irq(&phba->hbalock);
1277         phba->work_status[0] = readl(phba->MBslimaddr + 0xa8);
1278         phba->work_status[1] = readl(phba->MBslimaddr + 0xac);
1279 }
1280
1281 static void
1282 lpfc_board_errevt_to_mgmt(struct lpfc_hba *phba)
1283 {
1284         struct lpfc_board_event_header board_event;
1285         struct Scsi_Host *shost;
1286
1287         board_event.event_type = FC_REG_BOARD_EVENT;
1288         board_event.subcategory = LPFC_EVENT_PORTINTERR;
1289         shost = lpfc_shost_from_vport(phba->pport);
1290         fc_host_post_vendor_event(shost, fc_get_event_number(),
1291                                   sizeof(board_event),
1292                                   (char *) &board_event,
1293                                   LPFC_NL_VENDOR_ID);
1294 }
1295
1296 /**
1297  * lpfc_handle_eratt_s3 - The SLI3 HBA hardware error handler
1298  * @phba: pointer to lpfc hba data structure.
1299  *
1300  * This routine is invoked to handle the following HBA hardware error
1301  * conditions:
1302  * 1 - HBA error attention interrupt
1303  * 2 - DMA ring index out of range
1304  * 3 - Mailbox command came back as unknown
1305  **/
1306 static void
1307 lpfc_handle_eratt_s3(struct lpfc_hba *phba)
1308 {
1309         struct lpfc_vport *vport = phba->pport;
1310         struct lpfc_sli   *psli = &phba->sli;
1311         struct lpfc_sli_ring  *pring;
1312         uint32_t event_data;
1313         unsigned long temperature;
1314         struct temp_event temp_event_data;
1315         struct Scsi_Host  *shost;
1316
1317         /* If the pci channel is offline, ignore possible errors,
1318          * since we cannot communicate with the pci card anyway.
1319          */
1320         if (pci_channel_offline(phba->pcidev)) {
1321                 spin_lock_irq(&phba->hbalock);
1322                 phba->hba_flag &= ~DEFER_ERATT;
1323                 spin_unlock_irq(&phba->hbalock);
1324                 return;
1325         }
1326
1327         /* If resets are disabled then leave the HBA alone and return */
1328         if (!phba->cfg_enable_hba_reset)
1329                 return;
1330
1331         /* Send an internal error event to mgmt application */
1332         lpfc_board_errevt_to_mgmt(phba);
1333
1334         if (phba->hba_flag & DEFER_ERATT)
1335                 lpfc_handle_deferred_eratt(phba);
1336
1337         if ((phba->work_hs & HS_FFER6) || (phba->work_hs & HS_FFER8)) {
1338                 if (phba->work_hs & HS_FFER6)
1339                         /* Re-establishing Link */
1340                         lpfc_printf_log(phba, KERN_INFO, LOG_LINK_EVENT,
1341                                         "1301 Re-establishing Link "
1342                                         "Data: x%x x%x x%x\n",
1343                                         phba->work_hs, phba->work_status[0],
1344                                         phba->work_status[1]);
1345                 if (phba->work_hs & HS_FFER8)
1346                         /* Device Zeroization */
1347                         lpfc_printf_log(phba, KERN_INFO, LOG_LINK_EVENT,
1348                                         "2861 Host Authentication device "
1349                                         "zeroization Data:x%x x%x x%x\n",
1350                                         phba->work_hs, phba->work_status[0],
1351                                         phba->work_status[1]);
1352
1353                 spin_lock_irq(&phba->hbalock);
1354                 psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1355                 spin_unlock_irq(&phba->hbalock);
1356
1357                 /*
1358                 * Firmware stops when it triggled erratt with HS_FFER6.
1359                 * That could cause the I/Os dropped by the firmware.
1360                 * Error iocb (I/O) on txcmplq and let the SCSI layer
1361                 * retry it after re-establishing link.
1362                 */
1363                 pring = &psli->ring[psli->fcp_ring];
1364                 lpfc_sli_abort_iocb_ring(phba, pring);
1365
1366                 /*
1367                  * There was a firmware error.  Take the hba offline and then
1368                  * attempt to restart it.
1369                  */
1370                 lpfc_offline_prep(phba);
1371                 lpfc_offline(phba);
1372                 lpfc_sli_brdrestart(phba);
1373                 if (lpfc_online(phba) == 0) {   /* Initialize the HBA */
1374                         lpfc_unblock_mgmt_io(phba);
1375                         return;
1376                 }
1377                 lpfc_unblock_mgmt_io(phba);
1378         } else if (phba->work_hs & HS_CRIT_TEMP) {
1379                 temperature = readl(phba->MBslimaddr + TEMPERATURE_OFFSET);
1380                 temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
1381                 temp_event_data.event_code = LPFC_CRIT_TEMP;
1382                 temp_event_data.data = (uint32_t)temperature;
1383
1384                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
1385                                 "0406 Adapter maximum temperature exceeded "
1386                                 "(%ld), taking this port offline "
1387                                 "Data: x%x x%x x%x\n",
1388                                 temperature, phba->work_hs,
1389                                 phba->work_status[0], phba->work_status[1]);
1390
1391                 shost = lpfc_shost_from_vport(phba->pport);
1392                 fc_host_post_vendor_event(shost, fc_get_event_number(),
1393                                           sizeof(temp_event_data),
1394                                           (char *) &temp_event_data,
1395                                           SCSI_NL_VID_TYPE_PCI
1396                                           | PCI_VENDOR_ID_EMULEX);
1397
1398                 spin_lock_irq(&phba->hbalock);
1399                 phba->over_temp_state = HBA_OVER_TEMP;
1400                 spin_unlock_irq(&phba->hbalock);
1401                 lpfc_offline_eratt(phba);
1402
1403         } else {
1404                 /* The if clause above forces this code path when the status
1405                  * failure is a value other than FFER6. Do not call the offline
1406                  * twice. This is the adapter hardware error path.
1407                  */
1408                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
1409                                 "0457 Adapter Hardware Error "
1410                                 "Data: x%x x%x x%x\n",
1411                                 phba->work_hs,
1412                                 phba->work_status[0], phba->work_status[1]);
1413
1414                 event_data = FC_REG_DUMP_EVENT;
1415                 shost = lpfc_shost_from_vport(vport);
1416                 fc_host_post_vendor_event(shost, fc_get_event_number(),
1417                                 sizeof(event_data), (char *) &event_data,
1418                                 SCSI_NL_VID_TYPE_PCI | PCI_VENDOR_ID_EMULEX);
1419
1420                 lpfc_offline_eratt(phba);
1421         }
1422         return;
1423 }
1424
1425 /**
1426  * lpfc_handle_eratt_s4 - The SLI4 HBA hardware error handler
1427  * @phba: pointer to lpfc hba data structure.
1428  *
1429  * This routine is invoked to handle the SLI4 HBA hardware error attention
1430  * conditions.
1431  **/
1432 static void
1433 lpfc_handle_eratt_s4(struct lpfc_hba *phba)
1434 {
1435         struct lpfc_vport *vport = phba->pport;
1436         uint32_t event_data;
1437         struct Scsi_Host *shost;
1438         uint32_t if_type;
1439         struct lpfc_register portstat_reg;
1440         int rc;
1441
1442         /* If the pci channel is offline, ignore possible errors, since
1443          * we cannot communicate with the pci card anyway.
1444          */
1445         if (pci_channel_offline(phba->pcidev))
1446                 return;
1447         /* If resets are disabled then leave the HBA alone and return */
1448         if (!phba->cfg_enable_hba_reset)
1449                 return;
1450
1451         /* Send an internal error event to mgmt application */
1452         lpfc_board_errevt_to_mgmt(phba);
1453
1454         /* For now, the actual action for SLI4 device handling is not
1455          * specified yet, just treated it as adaptor hardware failure
1456          */
1457         event_data = FC_REG_DUMP_EVENT;
1458         shost = lpfc_shost_from_vport(vport);
1459         fc_host_post_vendor_event(shost, fc_get_event_number(),
1460                                   sizeof(event_data), (char *) &event_data,
1461                                   SCSI_NL_VID_TYPE_PCI | PCI_VENDOR_ID_EMULEX);
1462
1463         if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
1464         switch (if_type) {
1465         case LPFC_SLI_INTF_IF_TYPE_0:
1466                 lpfc_sli4_offline_eratt(phba);
1467                 break;
1468         case LPFC_SLI_INTF_IF_TYPE_2:
1469                 portstat_reg.word0 =
1470                         readl(phba->sli4_hba.u.if_type2.STATUSregaddr);
1471
1472                 if (bf_get(lpfc_sliport_status_oti, &portstat_reg)) {
1473                         /* TODO: Register for Overtemp async events. */
1474                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
1475                                 "2889 Port Overtemperature event, "
1476                                 "taking port\n");
1477                         spin_lock_irq(&phba->hbalock);
1478                         phba->over_temp_state = HBA_OVER_TEMP;
1479                         spin_unlock_irq(&phba->hbalock);
1480                         lpfc_sli4_offline_eratt(phba);
1481                         return;
1482                 }
1483                 /*
1484                  * On error status condition, driver need to wait for port
1485                  * ready before performing reset.
1486                  */
1487                 rc = lpfc_sli4_pdev_status_reg_wait(phba);
1488                 if (!rc) {
1489                         /* need reset: attempt for port recovery */
1490                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
1491                                         "2887 Port Error: Attempting "
1492                                         "Port Recovery\n");
1493                         lpfc_offline_prep(phba);
1494                         lpfc_offline(phba);
1495                         lpfc_sli_brdrestart(phba);
1496                         if (lpfc_online(phba) == 0) {
1497                                 lpfc_unblock_mgmt_io(phba);
1498                                 return;
1499                         }
1500                         /* fall through for not able to recover */
1501                 }
1502                 lpfc_sli4_offline_eratt(phba);
1503                 break;
1504         case LPFC_SLI_INTF_IF_TYPE_1:
1505         default:
1506                 break;
1507         }
1508 }
1509
1510 /**
1511  * lpfc_handle_eratt - Wrapper func for handling hba error attention
1512  * @phba: pointer to lpfc HBA data structure.
1513  *
1514  * This routine wraps the actual SLI3 or SLI4 hba error attention handling
1515  * routine from the API jump table function pointer from the lpfc_hba struct.
1516  *
1517  * Return codes
1518  *   0 - success.
1519  *   Any other value - error.
1520  **/
1521 void
1522 lpfc_handle_eratt(struct lpfc_hba *phba)
1523 {
1524         (*phba->lpfc_handle_eratt)(phba);
1525 }
1526
1527 /**
1528  * lpfc_handle_latt - The HBA link event handler
1529  * @phba: pointer to lpfc hba data structure.
1530  *
1531  * This routine is invoked from the worker thread to handle a HBA host
1532  * attention link event.
1533  **/
1534 void
1535 lpfc_handle_latt(struct lpfc_hba *phba)
1536 {
1537         struct lpfc_vport *vport = phba->pport;
1538         struct lpfc_sli   *psli = &phba->sli;
1539         LPFC_MBOXQ_t *pmb;
1540         volatile uint32_t control;
1541         struct lpfc_dmabuf *mp;
1542         int rc = 0;
1543
1544         pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
1545         if (!pmb) {
1546                 rc = 1;
1547                 goto lpfc_handle_latt_err_exit;
1548         }
1549
1550         mp = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
1551         if (!mp) {
1552                 rc = 2;
1553                 goto lpfc_handle_latt_free_pmb;
1554         }
1555
1556         mp->virt = lpfc_mbuf_alloc(phba, 0, &mp->phys);
1557         if (!mp->virt) {
1558                 rc = 3;
1559                 goto lpfc_handle_latt_free_mp;
1560         }
1561
1562         /* Cleanup any outstanding ELS commands */
1563         lpfc_els_flush_all_cmd(phba);
1564
1565         psli->slistat.link_event++;
1566         lpfc_read_topology(phba, pmb, mp);
1567         pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
1568         pmb->vport = vport;
1569         /* Block ELS IOCBs until we have processed this mbox command */
1570         phba->sli.ring[LPFC_ELS_RING].flag |= LPFC_STOP_IOCB_EVENT;
1571         rc = lpfc_sli_issue_mbox (phba, pmb, MBX_NOWAIT);
1572         if (rc == MBX_NOT_FINISHED) {
1573                 rc = 4;
1574                 goto lpfc_handle_latt_free_mbuf;
1575         }
1576
1577         /* Clear Link Attention in HA REG */
1578         spin_lock_irq(&phba->hbalock);
1579         writel(HA_LATT, phba->HAregaddr);
1580         readl(phba->HAregaddr); /* flush */
1581         spin_unlock_irq(&phba->hbalock);
1582
1583         return;
1584
1585 lpfc_handle_latt_free_mbuf:
1586         phba->sli.ring[LPFC_ELS_RING].flag &= ~LPFC_STOP_IOCB_EVENT;
1587         lpfc_mbuf_free(phba, mp->virt, mp->phys);
1588 lpfc_handle_latt_free_mp:
1589         kfree(mp);
1590 lpfc_handle_latt_free_pmb:
1591         mempool_free(pmb, phba->mbox_mem_pool);
1592 lpfc_handle_latt_err_exit:
1593         /* Enable Link attention interrupts */
1594         spin_lock_irq(&phba->hbalock);
1595         psli->sli_flag |= LPFC_PROCESS_LA;
1596         control = readl(phba->HCregaddr);
1597         control |= HC_LAINT_ENA;
1598         writel(control, phba->HCregaddr);
1599         readl(phba->HCregaddr); /* flush */
1600
1601         /* Clear Link Attention in HA REG */
1602         writel(HA_LATT, phba->HAregaddr);
1603         readl(phba->HAregaddr); /* flush */
1604         spin_unlock_irq(&phba->hbalock);
1605         lpfc_linkdown(phba);
1606         phba->link_state = LPFC_HBA_ERROR;
1607
1608         lpfc_printf_log(phba, KERN_ERR, LOG_MBOX,
1609                      "0300 LATT: Cannot issue READ_LA: Data:%d\n", rc);
1610
1611         return;
1612 }
1613
1614 /**
1615  * lpfc_parse_vpd - Parse VPD (Vital Product Data)
1616  * @phba: pointer to lpfc hba data structure.
1617  * @vpd: pointer to the vital product data.
1618  * @len: length of the vital product data in bytes.
1619  *
1620  * This routine parses the Vital Product Data (VPD). The VPD is treated as
1621  * an array of characters. In this routine, the ModelName, ProgramType, and
1622  * ModelDesc, etc. fields of the phba data structure will be populated.
1623  *
1624  * Return codes
1625  *   0 - pointer to the VPD passed in is NULL
1626  *   1 - success
1627  **/
1628 int
1629 lpfc_parse_vpd(struct lpfc_hba *phba, uint8_t *vpd, int len)
1630 {
1631         uint8_t lenlo, lenhi;
1632         int Length;
1633         int i, j;
1634         int finished = 0;
1635         int index = 0;
1636
1637         if (!vpd)
1638                 return 0;
1639
1640         /* Vital Product */
1641         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
1642                         "0455 Vital Product Data: x%x x%x x%x x%x\n",
1643                         (uint32_t) vpd[0], (uint32_t) vpd[1], (uint32_t) vpd[2],
1644                         (uint32_t) vpd[3]);
1645         while (!finished && (index < (len - 4))) {
1646                 switch (vpd[index]) {
1647                 case 0x82:
1648                 case 0x91:
1649                         index += 1;
1650                         lenlo = vpd[index];
1651                         index += 1;
1652                         lenhi = vpd[index];
1653                         index += 1;
1654                         i = ((((unsigned short)lenhi) << 8) + lenlo);
1655                         index += i;
1656                         break;
1657                 case 0x90:
1658                         index += 1;
1659                         lenlo = vpd[index];
1660                         index += 1;
1661                         lenhi = vpd[index];
1662                         index += 1;
1663                         Length = ((((unsigned short)lenhi) << 8) + lenlo);
1664                         if (Length > len - index)
1665                                 Length = len - index;
1666                         while (Length > 0) {
1667                         /* Look for Serial Number */
1668                         if ((vpd[index] == 'S') && (vpd[index+1] == 'N')) {
1669                                 index += 2;
1670                                 i = vpd[index];
1671                                 index += 1;
1672                                 j = 0;
1673                                 Length -= (3+i);
1674                                 while(i--) {
1675                                         phba->SerialNumber[j++] = vpd[index++];
1676                                         if (j == 31)
1677                                                 break;
1678                                 }
1679                                 phba->SerialNumber[j] = 0;
1680                                 continue;
1681                         }
1682                         else if ((vpd[index] == 'V') && (vpd[index+1] == '1')) {
1683                                 phba->vpd_flag |= VPD_MODEL_DESC;
1684                                 index += 2;
1685                                 i = vpd[index];
1686                                 index += 1;
1687                                 j = 0;
1688                                 Length -= (3+i);
1689                                 while(i--) {
1690                                         phba->ModelDesc[j++] = vpd[index++];
1691                                         if (j == 255)
1692                                                 break;
1693                                 }
1694                                 phba->ModelDesc[j] = 0;
1695                                 continue;
1696                         }
1697                         else if ((vpd[index] == 'V') && (vpd[index+1] == '2')) {
1698                                 phba->vpd_flag |= VPD_MODEL_NAME;
1699                                 index += 2;
1700                                 i = vpd[index];
1701                                 index += 1;
1702                                 j = 0;
1703                                 Length -= (3+i);
1704                                 while(i--) {
1705                                         phba->ModelName[j++] = vpd[index++];
1706                                         if (j == 79)
1707                                                 break;
1708                                 }
1709                                 phba->ModelName[j] = 0;
1710                                 continue;
1711                         }
1712                         else if ((vpd[index] == 'V') && (vpd[index+1] == '3')) {
1713                                 phba->vpd_flag |= VPD_PROGRAM_TYPE;
1714                                 index += 2;
1715                                 i = vpd[index];
1716                                 index += 1;
1717                                 j = 0;
1718                                 Length -= (3+i);
1719                                 while(i--) {
1720                                         phba->ProgramType[j++] = vpd[index++];
1721                                         if (j == 255)
1722                                                 break;
1723                                 }
1724                                 phba->ProgramType[j] = 0;
1725                                 continue;
1726                         }
1727                         else if ((vpd[index] == 'V') && (vpd[index+1] == '4')) {
1728                                 phba->vpd_flag |= VPD_PORT;
1729                                 index += 2;
1730                                 i = vpd[index];
1731                                 index += 1;
1732                                 j = 0;
1733                                 Length -= (3+i);
1734                                 while(i--) {
1735                                         if ((phba->sli_rev == LPFC_SLI_REV4) &&
1736                                             (phba->sli4_hba.pport_name_sta ==
1737                                              LPFC_SLI4_PPNAME_GET)) {
1738                                                 j++;
1739                                                 index++;
1740                                         } else
1741                                                 phba->Port[j++] = vpd[index++];
1742                                         if (j == 19)
1743                                                 break;
1744                                 }
1745                                 if ((phba->sli_rev != LPFC_SLI_REV4) ||
1746                                     (phba->sli4_hba.pport_name_sta ==
1747                                      LPFC_SLI4_PPNAME_NON))
1748                                         phba->Port[j] = 0;
1749                                 continue;
1750                         }
1751                         else {
1752                                 index += 2;
1753                                 i = vpd[index];
1754                                 index += 1;
1755                                 index += i;
1756                                 Length -= (3 + i);
1757                         }
1758                 }
1759                 finished = 0;
1760                 break;
1761                 case 0x78:
1762                         finished = 1;
1763                         break;
1764                 default:
1765                         index ++;
1766                         break;
1767                 }
1768         }
1769
1770         return(1);
1771 }
1772
1773 /**
1774  * lpfc_get_hba_model_desc - Retrieve HBA device model name and description
1775  * @phba: pointer to lpfc hba data structure.
1776  * @mdp: pointer to the data structure to hold the derived model name.
1777  * @descp: pointer to the data structure to hold the derived description.
1778  *
1779  * This routine retrieves HBA's description based on its registered PCI device
1780  * ID. The @descp passed into this function points to an array of 256 chars. It
1781  * shall be returned with the model name, maximum speed, and the host bus type.
1782  * The @mdp passed into this function points to an array of 80 chars. When the
1783  * function returns, the @mdp will be filled with the model name.
1784  **/
1785 static void
1786 lpfc_get_hba_model_desc(struct lpfc_hba *phba, uint8_t *mdp, uint8_t *descp)
1787 {
1788         lpfc_vpd_t *vp;
1789         uint16_t dev_id = phba->pcidev->device;
1790         int max_speed;
1791         int GE = 0;
1792         int oneConnect = 0; /* default is not a oneConnect */
1793         struct {
1794                 char *name;
1795                 char *bus;
1796                 char *function;
1797         } m = {"<Unknown>", "", ""};
1798
1799         if (mdp && mdp[0] != '\0'
1800                 && descp && descp[0] != '\0')
1801                 return;
1802
1803         if (phba->lmt & LMT_16Gb)
1804                 max_speed = 16;
1805         else if (phba->lmt & LMT_10Gb)
1806                 max_speed = 10;
1807         else if (phba->lmt & LMT_8Gb)
1808                 max_speed = 8;
1809         else if (phba->lmt & LMT_4Gb)
1810                 max_speed = 4;
1811         else if (phba->lmt & LMT_2Gb)
1812                 max_speed = 2;
1813         else
1814                 max_speed = 1;
1815
1816         vp = &phba->vpd;
1817
1818         switch (dev_id) {
1819         case PCI_DEVICE_ID_FIREFLY:
1820                 m = (typeof(m)){"LP6000", "PCI", "Fibre Channel Adapter"};
1821                 break;
1822         case PCI_DEVICE_ID_SUPERFLY:
1823                 if (vp->rev.biuRev >= 1 && vp->rev.biuRev <= 3)
1824                         m = (typeof(m)){"LP7000", "PCI",
1825                                         "Fibre Channel Adapter"};
1826                 else
1827                         m = (typeof(m)){"LP7000E", "PCI",
1828                                         "Fibre Channel Adapter"};
1829                 break;
1830         case PCI_DEVICE_ID_DRAGONFLY:
1831                 m = (typeof(m)){"LP8000", "PCI",
1832                                 "Fibre Channel Adapter"};
1833                 break;
1834         case PCI_DEVICE_ID_CENTAUR:
1835                 if (FC_JEDEC_ID(vp->rev.biuRev) == CENTAUR_2G_JEDEC_ID)
1836                         m = (typeof(m)){"LP9002", "PCI",
1837                                         "Fibre Channel Adapter"};
1838                 else
1839                         m = (typeof(m)){"LP9000", "PCI",
1840                                         "Fibre Channel Adapter"};
1841                 break;
1842         case PCI_DEVICE_ID_RFLY:
1843                 m = (typeof(m)){"LP952", "PCI",
1844                                 "Fibre Channel Adapter"};
1845                 break;
1846         case PCI_DEVICE_ID_PEGASUS:
1847                 m = (typeof(m)){"LP9802", "PCI-X",
1848                                 "Fibre Channel Adapter"};
1849                 break;
1850         case PCI_DEVICE_ID_THOR:
1851                 m = (typeof(m)){"LP10000", "PCI-X",
1852                                 "Fibre Channel Adapter"};
1853                 break;
1854         case PCI_DEVICE_ID_VIPER:
1855                 m = (typeof(m)){"LPX1000",  "PCI-X",
1856                                 "Fibre Channel Adapter"};
1857                 break;
1858         case PCI_DEVICE_ID_PFLY:
1859                 m = (typeof(m)){"LP982", "PCI-X",
1860                                 "Fibre Channel Adapter"};
1861                 break;
1862         case PCI_DEVICE_ID_TFLY:
1863                 m = (typeof(m)){"LP1050", "PCI-X",
1864                                 "Fibre Channel Adapter"};
1865                 break;
1866         case PCI_DEVICE_ID_HELIOS:
1867                 m = (typeof(m)){"LP11000", "PCI-X2",
1868                                 "Fibre Channel Adapter"};
1869                 break;
1870         case PCI_DEVICE_ID_HELIOS_SCSP:
1871                 m = (typeof(m)){"LP11000-SP", "PCI-X2",
1872                                 "Fibre Channel Adapter"};
1873                 break;
1874         case PCI_DEVICE_ID_HELIOS_DCSP:
1875                 m = (typeof(m)){"LP11002-SP",  "PCI-X2",
1876                                 "Fibre Channel Adapter"};
1877                 break;
1878         case PCI_DEVICE_ID_NEPTUNE:
1879                 m = (typeof(m)){"LPe1000", "PCIe", "Fibre Channel Adapter"};
1880                 break;
1881         case PCI_DEVICE_ID_NEPTUNE_SCSP:
1882                 m = (typeof(m)){"LPe1000-SP", "PCIe", "Fibre Channel Adapter"};
1883                 break;
1884         case PCI_DEVICE_ID_NEPTUNE_DCSP:
1885                 m = (typeof(m)){"LPe1002-SP", "PCIe", "Fibre Channel Adapter"};
1886                 break;
1887         case PCI_DEVICE_ID_BMID:
1888                 m = (typeof(m)){"LP1150", "PCI-X2", "Fibre Channel Adapter"};
1889                 break;
1890         case PCI_DEVICE_ID_BSMB:
1891                 m = (typeof(m)){"LP111", "PCI-X2", "Fibre Channel Adapter"};
1892                 break;
1893         case PCI_DEVICE_ID_ZEPHYR:
1894                 m = (typeof(m)){"LPe11000", "PCIe", "Fibre Channel Adapter"};
1895                 break;
1896         case PCI_DEVICE_ID_ZEPHYR_SCSP:
1897                 m = (typeof(m)){"LPe11000", "PCIe", "Fibre Channel Adapter"};
1898                 break;
1899         case PCI_DEVICE_ID_ZEPHYR_DCSP:
1900                 m = (typeof(m)){"LP2105", "PCIe", "FCoE Adapter"};
1901                 GE = 1;
1902                 break;
1903         case PCI_DEVICE_ID_ZMID:
1904                 m = (typeof(m)){"LPe1150", "PCIe", "Fibre Channel Adapter"};
1905                 break;
1906         case PCI_DEVICE_ID_ZSMB:
1907                 m = (typeof(m)){"LPe111", "PCIe", "Fibre Channel Adapter"};
1908                 break;
1909         case PCI_DEVICE_ID_LP101:
1910                 m = (typeof(m)){"LP101", "PCI-X", "Fibre Channel Adapter"};
1911                 break;
1912         case PCI_DEVICE_ID_LP10000S:
1913                 m = (typeof(m)){"LP10000-S", "PCI", "Fibre Channel Adapter"};
1914                 break;
1915         case PCI_DEVICE_ID_LP11000S:
1916                 m = (typeof(m)){"LP11000-S", "PCI-X2", "Fibre Channel Adapter"};
1917                 break;
1918         case PCI_DEVICE_ID_LPE11000S:
1919                 m = (typeof(m)){"LPe11000-S", "PCIe", "Fibre Channel Adapter"};
1920                 break;
1921         case PCI_DEVICE_ID_SAT:
1922                 m = (typeof(m)){"LPe12000", "PCIe", "Fibre Channel Adapter"};
1923                 break;
1924         case PCI_DEVICE_ID_SAT_MID:
1925                 m = (typeof(m)){"LPe1250", "PCIe", "Fibre Channel Adapter"};
1926                 break;
1927         case PCI_DEVICE_ID_SAT_SMB:
1928                 m = (typeof(m)){"LPe121", "PCIe", "Fibre Channel Adapter"};
1929                 break;
1930         case PCI_DEVICE_ID_SAT_DCSP:
1931                 m = (typeof(m)){"LPe12002-SP", "PCIe", "Fibre Channel Adapter"};
1932                 break;
1933         case PCI_DEVICE_ID_SAT_SCSP:
1934                 m = (typeof(m)){"LPe12000-SP", "PCIe", "Fibre Channel Adapter"};
1935                 break;
1936         case PCI_DEVICE_ID_SAT_S:
1937                 m = (typeof(m)){"LPe12000-S", "PCIe", "Fibre Channel Adapter"};
1938                 break;
1939         case PCI_DEVICE_ID_HORNET:
1940                 m = (typeof(m)){"LP21000", "PCIe", "FCoE Adapter"};
1941                 GE = 1;
1942                 break;
1943         case PCI_DEVICE_ID_PROTEUS_VF:
1944                 m = (typeof(m)){"LPev12000", "PCIe IOV",
1945                                 "Fibre Channel Adapter"};
1946                 break;
1947         case PCI_DEVICE_ID_PROTEUS_PF:
1948                 m = (typeof(m)){"LPev12000", "PCIe IOV",
1949                                 "Fibre Channel Adapter"};
1950                 break;
1951         case PCI_DEVICE_ID_PROTEUS_S:
1952                 m = (typeof(m)){"LPemv12002-S", "PCIe IOV",
1953                                 "Fibre Channel Adapter"};
1954                 break;
1955         case PCI_DEVICE_ID_TIGERSHARK:
1956                 oneConnect = 1;
1957                 m = (typeof(m)){"OCe10100", "PCIe", "FCoE"};
1958                 break;
1959         case PCI_DEVICE_ID_TOMCAT:
1960                 oneConnect = 1;
1961                 m = (typeof(m)){"OCe11100", "PCIe", "FCoE"};
1962                 break;
1963         case PCI_DEVICE_ID_FALCON:
1964                 m = (typeof(m)){"LPSe12002-ML1-E", "PCIe",
1965                                 "EmulexSecure Fibre"};
1966                 break;
1967         case PCI_DEVICE_ID_BALIUS:
1968                 m = (typeof(m)){"LPVe12002", "PCIe Shared I/O",
1969                                 "Fibre Channel Adapter"};
1970                 break;
1971         case PCI_DEVICE_ID_LANCER_FC:
1972         case PCI_DEVICE_ID_LANCER_FC_VF:
1973                 m = (typeof(m)){"LPe16000", "PCIe", "Fibre Channel Adapter"};
1974                 break;
1975         case PCI_DEVICE_ID_LANCER_FCOE:
1976         case PCI_DEVICE_ID_LANCER_FCOE_VF:
1977                 oneConnect = 1;
1978                 m = (typeof(m)){"OCe15100", "PCIe", "FCoE"};
1979                 break;
1980         default:
1981                 m = (typeof(m)){"Unknown", "", ""};
1982                 break;
1983         }
1984
1985         if (mdp && mdp[0] == '\0')
1986                 snprintf(mdp, 79,"%s", m.name);
1987         /*
1988          * oneConnect hba requires special processing, they are all initiators
1989          * and we put the port number on the end
1990          */
1991         if (descp && descp[0] == '\0') {
1992                 if (oneConnect)
1993                         snprintf(descp, 255,
1994                                 "Emulex OneConnect %s, %s Initiator, Port %s",
1995                                 m.name, m.function,
1996                                 phba->Port);
1997                 else
1998                         snprintf(descp, 255,
1999                                 "Emulex %s %d%s %s %s",
2000                                 m.name, max_speed, (GE) ? "GE" : "Gb",
2001                                 m.bus, m.function);
2002         }
2003 }
2004
2005 /**
2006  * lpfc_post_buffer - Post IOCB(s) with DMA buffer descriptor(s) to a IOCB ring
2007  * @phba: pointer to lpfc hba data structure.
2008  * @pring: pointer to a IOCB ring.
2009  * @cnt: the number of IOCBs to be posted to the IOCB ring.
2010  *
2011  * This routine posts a given number of IOCBs with the associated DMA buffer
2012  * descriptors specified by the cnt argument to the given IOCB ring.
2013  *
2014  * Return codes
2015  *   The number of IOCBs NOT able to be posted to the IOCB ring.
2016  **/
2017 int
2018 lpfc_post_buffer(struct lpfc_hba *phba, struct lpfc_sli_ring *pring, int cnt)
2019 {
2020         IOCB_t *icmd;
2021         struct lpfc_iocbq *iocb;
2022         struct lpfc_dmabuf *mp1, *mp2;
2023
2024         cnt += pring->missbufcnt;
2025
2026         /* While there are buffers to post */
2027         while (cnt > 0) {
2028                 /* Allocate buffer for  command iocb */
2029                 iocb = lpfc_sli_get_iocbq(phba);
2030                 if (iocb == NULL) {
2031                         pring->missbufcnt = cnt;
2032                         return cnt;
2033                 }
2034                 icmd = &iocb->iocb;
2035
2036                 /* 2 buffers can be posted per command */
2037                 /* Allocate buffer to post */
2038                 mp1 = kmalloc(sizeof (struct lpfc_dmabuf), GFP_KERNEL);
2039                 if (mp1)
2040                     mp1->virt = lpfc_mbuf_alloc(phba, MEM_PRI, &mp1->phys);
2041                 if (!mp1 || !mp1->virt) {
2042                         kfree(mp1);
2043                         lpfc_sli_release_iocbq(phba, iocb);
2044                         pring->missbufcnt = cnt;
2045                         return cnt;
2046                 }
2047
2048                 INIT_LIST_HEAD(&mp1->list);
2049                 /* Allocate buffer to post */
2050                 if (cnt > 1) {
2051                         mp2 = kmalloc(sizeof (struct lpfc_dmabuf), GFP_KERNEL);
2052                         if (mp2)
2053                                 mp2->virt = lpfc_mbuf_alloc(phba, MEM_PRI,
2054                                                             &mp2->phys);
2055                         if (!mp2 || !mp2->virt) {
2056                                 kfree(mp2);
2057                                 lpfc_mbuf_free(phba, mp1->virt, mp1->phys);
2058                                 kfree(mp1);
2059                                 lpfc_sli_release_iocbq(phba, iocb);
2060                                 pring->missbufcnt = cnt;
2061                                 return cnt;
2062                         }
2063
2064                         INIT_LIST_HEAD(&mp2->list);
2065                 } else {
2066                         mp2 = NULL;
2067                 }
2068
2069                 icmd->un.cont64[0].addrHigh = putPaddrHigh(mp1->phys);
2070                 icmd->un.cont64[0].addrLow = putPaddrLow(mp1->phys);
2071                 icmd->un.cont64[0].tus.f.bdeSize = FCELSSIZE;
2072                 icmd->ulpBdeCount = 1;
2073                 cnt--;
2074                 if (mp2) {
2075                         icmd->un.cont64[1].addrHigh = putPaddrHigh(mp2->phys);
2076                         icmd->un.cont64[1].addrLow = putPaddrLow(mp2->phys);
2077                         icmd->un.cont64[1].tus.f.bdeSize = FCELSSIZE;
2078                         cnt--;
2079                         icmd->ulpBdeCount = 2;
2080                 }
2081
2082                 icmd->ulpCommand = CMD_QUE_RING_BUF64_CN;
2083                 icmd->ulpLe = 1;
2084
2085                 if (lpfc_sli_issue_iocb(phba, pring->ringno, iocb, 0) ==
2086                     IOCB_ERROR) {
2087                         lpfc_mbuf_free(phba, mp1->virt, mp1->phys);
2088                         kfree(mp1);
2089                         cnt++;
2090                         if (mp2) {
2091                                 lpfc_mbuf_free(phba, mp2->virt, mp2->phys);
2092                                 kfree(mp2);
2093                                 cnt++;
2094                         }
2095                         lpfc_sli_release_iocbq(phba, iocb);
2096                         pring->missbufcnt = cnt;
2097                         return cnt;
2098                 }
2099                 lpfc_sli_ringpostbuf_put(phba, pring, mp1);
2100                 if (mp2)
2101                         lpfc_sli_ringpostbuf_put(phba, pring, mp2);
2102         }
2103         pring->missbufcnt = 0;
2104         return 0;
2105 }
2106
2107 /**
2108  * lpfc_post_rcv_buf - Post the initial receive IOCB buffers to ELS ring
2109  * @phba: pointer to lpfc hba data structure.
2110  *
2111  * This routine posts initial receive IOCB buffers to the ELS ring. The
2112  * current number of initial IOCB buffers specified by LPFC_BUF_RING0 is
2113  * set to 64 IOCBs.
2114  *
2115  * Return codes
2116  *   0 - success (currently always success)
2117  **/
2118 static int
2119 lpfc_post_rcv_buf(struct lpfc_hba *phba)
2120 {
2121         struct lpfc_sli *psli = &phba->sli;
2122
2123         /* Ring 0, ELS / CT buffers */
2124         lpfc_post_buffer(phba, &psli->ring[LPFC_ELS_RING], LPFC_BUF_RING0);
2125         /* Ring 2 - FCP no buffers needed */
2126
2127         return 0;
2128 }
2129
2130 #define S(N,V) (((V)<<(N))|((V)>>(32-(N))))
2131
2132 /**
2133  * lpfc_sha_init - Set up initial array of hash table entries
2134  * @HashResultPointer: pointer to an array as hash table.
2135  *
2136  * This routine sets up the initial values to the array of hash table entries
2137  * for the LC HBAs.
2138  **/
2139 static void
2140 lpfc_sha_init(uint32_t * HashResultPointer)
2141 {
2142         HashResultPointer[0] = 0x67452301;
2143         HashResultPointer[1] = 0xEFCDAB89;
2144         HashResultPointer[2] = 0x98BADCFE;
2145         HashResultPointer[3] = 0x10325476;
2146         HashResultPointer[4] = 0xC3D2E1F0;
2147 }
2148
2149 /**
2150  * lpfc_sha_iterate - Iterate initial hash table with the working hash table
2151  * @HashResultPointer: pointer to an initial/result hash table.
2152  * @HashWorkingPointer: pointer to an working hash table.
2153  *
2154  * This routine iterates an initial hash table pointed by @HashResultPointer
2155  * with the values from the working hash table pointeed by @HashWorkingPointer.
2156  * The results are putting back to the initial hash table, returned through
2157  * the @HashResultPointer as the result hash table.
2158  **/
2159 static void
2160 lpfc_sha_iterate(uint32_t * HashResultPointer, uint32_t * HashWorkingPointer)
2161 {
2162         int t;
2163         uint32_t TEMP;
2164         uint32_t A, B, C, D, E;
2165         t = 16;
2166         do {
2167                 HashWorkingPointer[t] =
2168                     S(1,
2169                       HashWorkingPointer[t - 3] ^ HashWorkingPointer[t -
2170                                                                      8] ^
2171                       HashWorkingPointer[t - 14] ^ HashWorkingPointer[t - 16]);
2172         } while (++t <= 79);
2173         t = 0;
2174         A = HashResultPointer[0];
2175         B = HashResultPointer[1];
2176         C = HashResultPointer[2];
2177         D = HashResultPointer[3];
2178         E = HashResultPointer[4];
2179
2180         do {
2181                 if (t < 20) {
2182                         TEMP = ((B & C) | ((~B) & D)) + 0x5A827999;
2183                 } else if (t < 40) {
2184                         TEMP = (B ^ C ^ D) + 0x6ED9EBA1;
2185                 } else if (t < 60) {
2186                         TEMP = ((B & C) | (B & D) | (C & D)) + 0x8F1BBCDC;
2187                 } else {
2188                         TEMP = (B ^ C ^ D) + 0xCA62C1D6;
2189                 }
2190                 TEMP += S(5, A) + E + HashWorkingPointer[t];
2191                 E = D;
2192                 D = C;
2193                 C = S(30, B);
2194                 B = A;
2195                 A = TEMP;
2196         } while (++t <= 79);
2197
2198         HashResultPointer[0] += A;
2199         HashResultPointer[1] += B;
2200         HashResultPointer[2] += C;
2201         HashResultPointer[3] += D;
2202         HashResultPointer[4] += E;
2203
2204 }
2205
2206 /**
2207  * lpfc_challenge_key - Create challenge key based on WWPN of the HBA
2208  * @RandomChallenge: pointer to the entry of host challenge random number array.
2209  * @HashWorking: pointer to the entry of the working hash array.
2210  *
2211  * This routine calculates the working hash array referred by @HashWorking
2212  * from the challenge random numbers associated with the host, referred by
2213  * @RandomChallenge. The result is put into the entry of the working hash
2214  * array and returned by reference through @HashWorking.
2215  **/
2216 static void
2217 lpfc_challenge_key(uint32_t * RandomChallenge, uint32_t * HashWorking)
2218 {
2219         *HashWorking = (*RandomChallenge ^ *HashWorking);
2220 }
2221
2222 /**
2223  * lpfc_hba_init - Perform special handling for LC HBA initialization
2224  * @phba: pointer to lpfc hba data structure.
2225  * @hbainit: pointer to an array of unsigned 32-bit integers.
2226  *
2227  * This routine performs the special handling for LC HBA initialization.
2228  **/
2229 void
2230 lpfc_hba_init(struct lpfc_hba *phba, uint32_t *hbainit)
2231 {
2232         int t;
2233         uint32_t *HashWorking;
2234         uint32_t *pwwnn = (uint32_t *) phba->wwnn;
2235
2236         HashWorking = kcalloc(80, sizeof(uint32_t), GFP_KERNEL);
2237         if (!HashWorking)
2238                 return;
2239
2240         HashWorking[0] = HashWorking[78] = *pwwnn++;
2241         HashWorking[1] = HashWorking[79] = *pwwnn;
2242
2243         for (t = 0; t < 7; t++)
2244                 lpfc_challenge_key(phba->RandomData + t, HashWorking + t);
2245
2246         lpfc_sha_init(hbainit);
2247         lpfc_sha_iterate(hbainit, HashWorking);
2248         kfree(HashWorking);
2249 }
2250
2251 /**
2252  * lpfc_cleanup - Performs vport cleanups before deleting a vport
2253  * @vport: pointer to a virtual N_Port data structure.
2254  *
2255  * This routine performs the necessary cleanups before deleting the @vport.
2256  * It invokes the discovery state machine to perform necessary state
2257  * transitions and to release the ndlps associated with the @vport. Note,
2258  * the physical port is treated as @vport 0.
2259  **/
2260 void
2261 lpfc_cleanup(struct lpfc_vport *vport)
2262 {
2263         struct lpfc_hba   *phba = vport->phba;
2264         struct lpfc_nodelist *ndlp, *next_ndlp;
2265         int i = 0;
2266
2267         if (phba->link_state > LPFC_LINK_DOWN)
2268                 lpfc_port_link_failure(vport);
2269
2270         list_for_each_entry_safe(ndlp, next_ndlp, &vport->fc_nodes, nlp_listp) {
2271                 if (!NLP_CHK_NODE_ACT(ndlp)) {
2272                         ndlp = lpfc_enable_node(vport, ndlp,
2273                                                 NLP_STE_UNUSED_NODE);
2274                         if (!ndlp)
2275                                 continue;
2276                         spin_lock_irq(&phba->ndlp_lock);
2277                         NLP_SET_FREE_REQ(ndlp);
2278                         spin_unlock_irq(&phba->ndlp_lock);
2279                         /* Trigger the release of the ndlp memory */
2280                         lpfc_nlp_put(ndlp);
2281                         continue;
2282                 }
2283                 spin_lock_irq(&phba->ndlp_lock);
2284                 if (NLP_CHK_FREE_REQ(ndlp)) {
2285                         /* The ndlp should not be in memory free mode already */
2286                         spin_unlock_irq(&phba->ndlp_lock);
2287                         continue;
2288                 } else
2289                         /* Indicate request for freeing ndlp memory */
2290                         NLP_SET_FREE_REQ(ndlp);
2291                 spin_unlock_irq(&phba->ndlp_lock);
2292
2293                 if (vport->port_type != LPFC_PHYSICAL_PORT &&
2294                     ndlp->nlp_DID == Fabric_DID) {
2295                         /* Just free up ndlp with Fabric_DID for vports */
2296                         lpfc_nlp_put(ndlp);
2297                         continue;
2298                 }
2299
2300                 if (ndlp->nlp_type & NLP_FABRIC)
2301                         lpfc_disc_state_machine(vport, ndlp, NULL,
2302                                         NLP_EVT_DEVICE_RECOVERY);
2303
2304                 lpfc_disc_state_machine(vport, ndlp, NULL,
2305                                              NLP_EVT_DEVICE_RM);
2306
2307         }
2308
2309         /* At this point, ALL ndlp's should be gone
2310          * because of the previous NLP_EVT_DEVICE_RM.
2311          * Lets wait for this to happen, if needed.
2312          */
2313         while (!list_empty(&vport->fc_nodes)) {
2314                 if (i++ > 3000) {
2315                         lpfc_printf_vlog(vport, KERN_ERR, LOG_DISCOVERY,
2316                                 "0233 Nodelist not empty\n");
2317                         list_for_each_entry_safe(ndlp, next_ndlp,
2318                                                 &vport->fc_nodes, nlp_listp) {
2319                                 lpfc_printf_vlog(ndlp->vport, KERN_ERR,
2320                                                 LOG_NODE,
2321                                                 "0282 did:x%x ndlp:x%p "
2322                                                 "usgmap:x%x refcnt:%d\n",
2323                                                 ndlp->nlp_DID, (void *)ndlp,
2324                                                 ndlp->nlp_usg_map,
2325                                                 atomic_read(
2326                                                         &ndlp->kref.refcount));
2327                         }
2328                         break;
2329                 }
2330
2331                 /* Wait for any activity on ndlps to settle */
2332                 msleep(10);
2333         }
2334         lpfc_cleanup_vports_rrqs(vport, NULL);
2335 }
2336
2337 /**
2338  * lpfc_stop_vport_timers - Stop all the timers associated with a vport
2339  * @vport: pointer to a virtual N_Port data structure.
2340  *
2341  * This routine stops all the timers associated with a @vport. This function
2342  * is invoked before disabling or deleting a @vport. Note that the physical
2343  * port is treated as @vport 0.
2344  **/
2345 void
2346 lpfc_stop_vport_timers(struct lpfc_vport *vport)
2347 {
2348         del_timer_sync(&vport->els_tmofunc);
2349         del_timer_sync(&vport->fc_fdmitmo);
2350         del_timer_sync(&vport->delayed_disc_tmo);
2351         lpfc_can_disctmo(vport);
2352         return;
2353 }
2354
2355 /**
2356  * __lpfc_sli4_stop_fcf_redisc_wait_timer - Stop FCF rediscovery wait timer
2357  * @phba: pointer to lpfc hba data structure.
2358  *
2359  * This routine stops the SLI4 FCF rediscover wait timer if it's on. The
2360  * caller of this routine should already hold the host lock.
2361  **/
2362 void
2363 __lpfc_sli4_stop_fcf_redisc_wait_timer(struct lpfc_hba *phba)
2364 {
2365         /* Clear pending FCF rediscovery wait flag */
2366         phba->fcf.fcf_flag &= ~FCF_REDISC_PEND;
2367
2368         /* Now, try to stop the timer */
2369         del_timer(&phba->fcf.redisc_wait);
2370 }
2371
2372 /**
2373  * lpfc_sli4_stop_fcf_redisc_wait_timer - Stop FCF rediscovery wait timer
2374  * @phba: pointer to lpfc hba data structure.
2375  *
2376  * This routine stops the SLI4 FCF rediscover wait timer if it's on. It
2377  * checks whether the FCF rediscovery wait timer is pending with the host
2378  * lock held before proceeding with disabling the timer and clearing the
2379  * wait timer pendig flag.
2380  **/
2381 void
2382 lpfc_sli4_stop_fcf_redisc_wait_timer(struct lpfc_hba *phba)
2383 {
2384         spin_lock_irq(&phba->hbalock);
2385         if (!(phba->fcf.fcf_flag & FCF_REDISC_PEND)) {
2386                 /* FCF rediscovery timer already fired or stopped */
2387                 spin_unlock_irq(&phba->hbalock);
2388                 return;
2389         }
2390         __lpfc_sli4_stop_fcf_redisc_wait_timer(phba);
2391         /* Clear failover in progress flags */
2392         phba->fcf.fcf_flag &= ~(FCF_DEAD_DISC | FCF_ACVL_DISC);
2393         spin_unlock_irq(&phba->hbalock);
2394 }
2395
2396 /**
2397  * lpfc_stop_hba_timers - Stop all the timers associated with an HBA
2398  * @phba: pointer to lpfc hba data structure.
2399  *
2400  * This routine stops all the timers associated with a HBA. This function is
2401  * invoked before either putting a HBA offline or unloading the driver.
2402  **/
2403 void
2404 lpfc_stop_hba_timers(struct lpfc_hba *phba)
2405 {
2406         lpfc_stop_vport_timers(phba->pport);
2407         del_timer_sync(&phba->sli.mbox_tmo);
2408         del_timer_sync(&phba->fabric_block_timer);
2409         del_timer_sync(&phba->eratt_poll);
2410         del_timer_sync(&phba->hb_tmofunc);
2411         if (phba->sli_rev == LPFC_SLI_REV4) {
2412                 del_timer_sync(&phba->rrq_tmr);
2413                 phba->hba_flag &= ~HBA_RRQ_ACTIVE;
2414         }
2415         phba->hb_outstanding = 0;
2416
2417         switch (phba->pci_dev_grp) {
2418         case LPFC_PCI_DEV_LP:
2419                 /* Stop any LightPulse device specific driver timers */
2420                 del_timer_sync(&phba->fcp_poll_timer);
2421                 break;
2422         case LPFC_PCI_DEV_OC:
2423                 /* Stop any OneConnect device sepcific driver timers */
2424                 lpfc_sli4_stop_fcf_redisc_wait_timer(phba);
2425                 break;
2426         default:
2427                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
2428                                 "0297 Invalid device group (x%x)\n",
2429                                 phba->pci_dev_grp);
2430                 break;
2431         }
2432         return;
2433 }
2434
2435 /**
2436  * lpfc_block_mgmt_io - Mark a HBA's management interface as blocked
2437  * @phba: pointer to lpfc hba data structure.
2438  *
2439  * This routine marks a HBA's management interface as blocked. Once the HBA's
2440  * management interface is marked as blocked, all the user space access to
2441  * the HBA, whether they are from sysfs interface or libdfc interface will
2442  * all be blocked. The HBA is set to block the management interface when the
2443  * driver prepares the HBA interface for online or offline.
2444  **/
2445 static void
2446 lpfc_block_mgmt_io(struct lpfc_hba * phba)
2447 {
2448         unsigned long iflag;
2449         uint8_t actcmd = MBX_HEARTBEAT;
2450         unsigned long timeout;
2451
2452         timeout = msecs_to_jiffies(LPFC_MBOX_TMO * 1000) + jiffies;
2453         spin_lock_irqsave(&phba->hbalock, iflag);
2454         phba->sli.sli_flag |= LPFC_BLOCK_MGMT_IO;
2455         if (phba->sli.mbox_active) {
2456                 actcmd = phba->sli.mbox_active->u.mb.mbxCommand;
2457                 /* Determine how long we might wait for the active mailbox
2458                  * command to be gracefully completed by firmware.
2459                  */
2460                 timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
2461                                 phba->sli.mbox_active) * 1000) + jiffies;
2462         }
2463         spin_unlock_irqrestore(&phba->hbalock, iflag);
2464
2465         /* Wait for the outstnading mailbox command to complete */
2466         while (phba->sli.mbox_active) {
2467                 /* Check active mailbox complete status every 2ms */
2468                 msleep(2);
2469                 if (time_after(jiffies, timeout)) {
2470                         lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2471                                 "2813 Mgmt IO is Blocked %x "
2472                                 "- mbox cmd %x still active\n",
2473                                 phba->sli.sli_flag, actcmd);
2474                         break;
2475                 }
2476         }
2477 }
2478
2479 /**
2480  * lpfc_online - Initialize and bring a HBA online
2481  * @phba: pointer to lpfc hba data structure.
2482  *
2483  * This routine initializes the HBA and brings a HBA online. During this
2484  * process, the management interface is blocked to prevent user space access
2485  * to the HBA interfering with the driver initialization.
2486  *
2487  * Return codes
2488  *   0 - successful
2489  *   1 - failed
2490  **/
2491 int
2492 lpfc_online(struct lpfc_hba *phba)
2493 {
2494         struct lpfc_vport *vport;
2495         struct lpfc_vport **vports;
2496         int i;
2497
2498         if (!phba)
2499                 return 0;
2500         vport = phba->pport;
2501
2502         if (!(vport->fc_flag & FC_OFFLINE_MODE))
2503                 return 0;
2504
2505         lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
2506                         "0458 Bring Adapter online\n");
2507
2508         lpfc_block_mgmt_io(phba);
2509
2510         if (!lpfc_sli_queue_setup(phba)) {
2511                 lpfc_unblock_mgmt_io(phba);
2512                 return 1;
2513         }
2514
2515         if (phba->sli_rev == LPFC_SLI_REV4) {
2516                 if (lpfc_sli4_hba_setup(phba)) { /* Initialize SLI4 HBA */
2517                         lpfc_unblock_mgmt_io(phba);
2518                         return 1;
2519                 }
2520         } else {
2521                 if (lpfc_sli_hba_setup(phba)) { /* Initialize SLI2/SLI3 HBA */
2522                         lpfc_unblock_mgmt_io(phba);
2523                         return 1;
2524                 }
2525         }
2526
2527         vports = lpfc_create_vport_work_array(phba);
2528         if (vports != NULL)
2529                 for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
2530                         struct Scsi_Host *shost;
2531                         shost = lpfc_shost_from_vport(vports[i]);
2532                         spin_lock_irq(shost->host_lock);
2533                         vports[i]->fc_flag &= ~FC_OFFLINE_MODE;
2534                         if (phba->sli3_options & LPFC_SLI3_NPIV_ENABLED)
2535                                 vports[i]->fc_flag |= FC_VPORT_NEEDS_REG_VPI;
2536                         if (phba->sli_rev == LPFC_SLI_REV4)
2537                                 vports[i]->fc_flag |= FC_VPORT_NEEDS_INIT_VPI;
2538                         spin_unlock_irq(shost->host_lock);
2539                 }
2540                 lpfc_destroy_vport_work_array(phba, vports);
2541
2542         lpfc_unblock_mgmt_io(phba);
2543         return 0;
2544 }
2545
2546 /**
2547  * lpfc_unblock_mgmt_io - Mark a HBA's management interface to be not blocked
2548  * @phba: pointer to lpfc hba data structure.
2549  *
2550  * This routine marks a HBA's management interface as not blocked. Once the
2551  * HBA's management interface is marked as not blocked, all the user space
2552  * access to the HBA, whether they are from sysfs interface or libdfc
2553  * interface will be allowed. The HBA is set to block the management interface
2554  * when the driver prepares the HBA interface for online or offline and then
2555  * set to unblock the management interface afterwards.
2556  **/
2557 void
2558 lpfc_unblock_mgmt_io(struct lpfc_hba * phba)
2559 {
2560         unsigned long iflag;
2561
2562         spin_lock_irqsave(&phba->hbalock, iflag);
2563         phba->sli.sli_flag &= ~LPFC_BLOCK_MGMT_IO;
2564         spin_unlock_irqrestore(&phba->hbalock, iflag);
2565 }
2566
2567 /**
2568  * lpfc_offline_prep - Prepare a HBA to be brought offline
2569  * @phba: pointer to lpfc hba data structure.
2570  *
2571  * This routine is invoked to prepare a HBA to be brought offline. It performs
2572  * unregistration login to all the nodes on all vports and flushes the mailbox
2573  * queue to make it ready to be brought offline.
2574  **/
2575 void
2576 lpfc_offline_prep(struct lpfc_hba * phba)
2577 {
2578         struct lpfc_vport *vport = phba->pport;
2579         struct lpfc_nodelist  *ndlp, *next_ndlp;
2580         struct lpfc_vport **vports;
2581         struct Scsi_Host *shost;
2582         int i;
2583
2584         if (vport->fc_flag & FC_OFFLINE_MODE)
2585                 return;
2586
2587         lpfc_block_mgmt_io(phba);
2588
2589         lpfc_linkdown(phba);
2590
2591         /* Issue an unreg_login to all nodes on all vports */
2592         vports = lpfc_create_vport_work_array(phba);
2593         if (vports != NULL) {
2594                 for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
2595                         if (vports[i]->load_flag & FC_UNLOADING)
2596                                 continue;
2597                         shost = lpfc_shost_from_vport(vports[i]);
2598                         spin_lock_irq(shost->host_lock);
2599                         vports[i]->vpi_state &= ~LPFC_VPI_REGISTERED;
2600                         vports[i]->fc_flag |= FC_VPORT_NEEDS_REG_VPI;
2601                         vports[i]->fc_flag &= ~FC_VFI_REGISTERED;
2602                         spin_unlock_irq(shost->host_lock);
2603
2604                         shost = lpfc_shost_from_vport(vports[i]);
2605                         list_for_each_entry_safe(ndlp, next_ndlp,
2606                                                  &vports[i]->fc_nodes,
2607                                                  nlp_listp) {
2608                                 if (!NLP_CHK_NODE_ACT(ndlp))
2609                                         continue;
2610                                 if (ndlp->nlp_state == NLP_STE_UNUSED_NODE)
2611                                         continue;
2612                                 if (ndlp->nlp_type & NLP_FABRIC) {
2613                                         lpfc_disc_state_machine(vports[i], ndlp,
2614                                                 NULL, NLP_EVT_DEVICE_RECOVERY);
2615                                         lpfc_disc_state_machine(vports[i], ndlp,
2616                                                 NULL, NLP_EVT_DEVICE_RM);
2617                                 }
2618                                 spin_lock_irq(shost->host_lock);
2619                                 ndlp->nlp_flag &= ~NLP_NPR_ADISC;
2620                                 spin_unlock_irq(shost->host_lock);
2621                                 lpfc_unreg_rpi(vports[i], ndlp);
2622                         }
2623                 }
2624         }
2625         lpfc_destroy_vport_work_array(phba, vports);
2626
2627         lpfc_sli_mbox_sys_shutdown(phba);
2628 }
2629
2630 /**
2631  * lpfc_offline - Bring a HBA offline
2632  * @phba: pointer to lpfc hba data structure.
2633  *
2634  * This routine actually brings a HBA offline. It stops all the timers
2635  * associated with the HBA, brings down the SLI layer, and eventually
2636  * marks the HBA as in offline state for the upper layer protocol.
2637  **/
2638 void
2639 lpfc_offline(struct lpfc_hba *phba)
2640 {
2641         struct Scsi_Host  *shost;
2642         struct lpfc_vport **vports;
2643         int i;
2644
2645         if (phba->pport->fc_flag & FC_OFFLINE_MODE)
2646                 return;
2647
2648         /* stop port and all timers associated with this hba */
2649         lpfc_stop_port(phba);
2650         vports = lpfc_create_vport_work_array(phba);
2651         if (vports != NULL)
2652                 for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++)
2653                         lpfc_stop_vport_timers(vports[i]);
2654         lpfc_destroy_vport_work_array(phba, vports);
2655         lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
2656                         "0460 Bring Adapter offline\n");
2657         /* Bring down the SLI Layer and cleanup.  The HBA is offline
2658            now.  */
2659         lpfc_sli_hba_down(phba);
2660         spin_lock_irq(&phba->hbalock);
2661         phba->work_ha = 0;
2662         spin_unlock_irq(&phba->hbalock);
2663         vports = lpfc_create_vport_work_array(phba);
2664         if (vports != NULL)
2665                 for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
2666                         shost = lpfc_shost_from_vport(vports[i]);
2667                         spin_lock_irq(shost->host_lock);
2668                         vports[i]->work_port_events = 0;
2669                         vports[i]->fc_flag |= FC_OFFLINE_MODE;
2670                         spin_unlock_irq(shost->host_lock);
2671                 }
2672         lpfc_destroy_vport_work_array(phba, vports);
2673 }
2674
2675 /**
2676  * lpfc_scsi_free - Free all the SCSI buffers and IOCBs from driver lists
2677  * @phba: pointer to lpfc hba data structure.
2678  *
2679  * This routine is to free all the SCSI buffers and IOCBs from the driver
2680  * list back to kernel. It is called from lpfc_pci_remove_one to free
2681  * the internal resources before the device is removed from the system.
2682  *
2683  * Return codes
2684  *   0 - successful (for now, it always returns 0)
2685  **/
2686 static int
2687 lpfc_scsi_free(struct lpfc_hba *phba)
2688 {
2689         struct lpfc_scsi_buf *sb, *sb_next;
2690         struct lpfc_iocbq *io, *io_next;
2691
2692         spin_lock_irq(&phba->hbalock);
2693         /* Release all the lpfc_scsi_bufs maintained by this host. */
2694         spin_lock(&phba->scsi_buf_list_lock);
2695         list_for_each_entry_safe(sb, sb_next, &phba->lpfc_scsi_buf_list, list) {
2696                 list_del(&sb->list);
2697                 pci_pool_free(phba->lpfc_scsi_dma_buf_pool, sb->data,
2698                               sb->dma_handle);
2699                 kfree(sb);
2700                 phba->total_scsi_bufs--;
2701         }
2702         spin_unlock(&phba->scsi_buf_list_lock);
2703
2704         /* Release all the lpfc_iocbq entries maintained by this host. */
2705         list_for_each_entry_safe(io, io_next, &phba->lpfc_iocb_list, list) {
2706                 list_del(&io->list);
2707                 kfree(io);
2708                 phba->total_iocbq_bufs--;
2709         }
2710
2711         spin_unlock_irq(&phba->hbalock);
2712         return 0;
2713 }
2714
2715 /**
2716  * lpfc_create_port - Create an FC port
2717  * @phba: pointer to lpfc hba data structure.
2718  * @instance: a unique integer ID to this FC port.
2719  * @dev: pointer to the device data structure.
2720  *
2721  * This routine creates a FC port for the upper layer protocol. The FC port
2722  * can be created on top of either a physical port or a virtual port provided
2723  * by the HBA. This routine also allocates a SCSI host data structure (shost)
2724  * and associates the FC port created before adding the shost into the SCSI
2725  * layer.
2726  *
2727  * Return codes
2728  *   @vport - pointer to the virtual N_Port data structure.
2729  *   NULL - port create failed.
2730  **/
2731 struct lpfc_vport *
2732 lpfc_create_port(struct lpfc_hba *phba, int instance, struct device *dev)
2733 {
2734         struct lpfc_vport *vport;
2735         struct Scsi_Host  *shost;
2736         int error = 0;
2737
2738         if (dev != &phba->pcidev->dev)
2739                 shost = scsi_host_alloc(&lpfc_vport_template,
2740                                         sizeof(struct lpfc_vport));
2741         else
2742                 shost = scsi_host_alloc(&lpfc_template,
2743                                         sizeof(struct lpfc_vport));
2744         if (!shost)
2745                 goto out;
2746
2747         vport = (struct lpfc_vport *) shost->hostdata;
2748         vport->phba = phba;
2749         vport->load_flag |= FC_LOADING;
2750         vport->fc_flag |= FC_VPORT_NEEDS_REG_VPI;
2751         vport->fc_rscn_flush = 0;
2752
2753         lpfc_get_vport_cfgparam(vport);
2754         shost->unique_id = instance;
2755         shost->max_id = LPFC_MAX_TARGET;
2756         shost->max_lun = vport->cfg_max_luns;
2757         shost->this_id = -1;
2758         shost->max_cmd_len = 16;
2759         if (phba->sli_rev == LPFC_SLI_REV4) {
2760                 shost->dma_boundary =
2761                         phba->sli4_hba.pc_sli4_params.sge_supp_len-1;
2762                 shost->sg_tablesize = phba->cfg_sg_seg_cnt;
2763         }
2764
2765         /*
2766          * Set initial can_queue value since 0 is no longer supported and
2767          * scsi_add_host will fail. This will be adjusted later based on the
2768          * max xri value determined in hba setup.
2769          */
2770         shost->can_queue = phba->cfg_hba_queue_depth - 10;
2771         if (dev != &phba->pcidev->dev) {
2772                 shost->transportt = lpfc_vport_transport_template;
2773                 vport->port_type = LPFC_NPIV_PORT;
2774         } else {
2775                 shost->transportt = lpfc_transport_template;
2776                 vport->port_type = LPFC_PHYSICAL_PORT;
2777         }
2778
2779         /* Initialize all internally managed lists. */
2780         INIT_LIST_HEAD(&vport->fc_nodes);
2781         INIT_LIST_HEAD(&vport->rcv_buffer_list);
2782         spin_lock_init(&vport->work_port_lock);
2783
2784         init_timer(&vport->fc_disctmo);
2785         vport->fc_disctmo.function = lpfc_disc_timeout;
2786         vport->fc_disctmo.data = (unsigned long)vport;
2787
2788         init_timer(&vport->fc_fdmitmo);
2789         vport->fc_fdmitmo.function = lpfc_fdmi_tmo;
2790         vport->fc_fdmitmo.data = (unsigned long)vport;
2791
2792         init_timer(&vport->els_tmofunc);
2793         vport->els_tmofunc.function = lpfc_els_timeout;
2794         vport->els_tmofunc.data = (unsigned long)vport;
2795
2796         init_timer(&vport->delayed_disc_tmo);
2797         vport->delayed_disc_tmo.function = lpfc_delayed_disc_tmo;
2798         vport->delayed_disc_tmo.data = (unsigned long)vport;
2799
2800         error = scsi_add_host_with_dma(shost, dev, &phba->pcidev->dev);
2801         if (error)
2802                 goto out_put_shost;
2803
2804         spin_lock_irq(&phba->hbalock);
2805         list_add_tail(&vport->listentry, &phba->port_list);
2806         spin_unlock_irq(&phba->hbalock);
2807         return vport;
2808
2809 out_put_shost:
2810         scsi_host_put(shost);
2811 out:
2812         return NULL;
2813 }
2814
2815 /**
2816  * destroy_port -  destroy an FC port
2817  * @vport: pointer to an lpfc virtual N_Port data structure.
2818  *
2819  * This routine destroys a FC port from the upper layer protocol. All the
2820  * resources associated with the port are released.
2821  **/
2822 void
2823 destroy_port(struct lpfc_vport *vport)
2824 {
2825         struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
2826         struct lpfc_hba  *phba = vport->phba;
2827
2828         lpfc_debugfs_terminate(vport);
2829         fc_remove_host(shost);
2830         scsi_remove_host(shost);
2831
2832         spin_lock_irq(&phba->hbalock);
2833         list_del_init(&vport->listentry);
2834         spin_unlock_irq(&phba->hbalock);
2835
2836         lpfc_cleanup(vport);
2837         return;
2838 }
2839
2840 /**
2841  * lpfc_get_instance - Get a unique integer ID
2842  *
2843  * This routine allocates a unique integer ID from lpfc_hba_index pool. It
2844  * uses the kernel idr facility to perform the task.
2845  *
2846  * Return codes:
2847  *   instance - a unique integer ID allocated as the new instance.
2848  *   -1 - lpfc get instance failed.
2849  **/
2850 int
2851 lpfc_get_instance(void)
2852 {
2853         int instance = 0;
2854
2855         /* Assign an unused number */
2856         if (!idr_pre_get(&lpfc_hba_index, GFP_KERNEL))
2857                 return -1;
2858         if (idr_get_new(&lpfc_hba_index, NULL, &instance))
2859                 return -1;
2860         return instance;
2861 }
2862
2863 /**
2864  * lpfc_scan_finished - method for SCSI layer to detect whether scan is done
2865  * @shost: pointer to SCSI host data structure.
2866  * @time: elapsed time of the scan in jiffies.
2867  *
2868  * This routine is called by the SCSI layer with a SCSI host to determine
2869  * whether the scan host is finished.
2870  *
2871  * Note: there is no scan_start function as adapter initialization will have
2872  * asynchronously kicked off the link initialization.
2873  *
2874  * Return codes
2875  *   0 - SCSI host scan is not over yet.
2876  *   1 - SCSI host scan is over.
2877  **/
2878 int lpfc_scan_finished(struct Scsi_Host *shost, unsigned long time)
2879 {
2880         struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
2881         struct lpfc_hba   *phba = vport->phba;
2882         int stat = 0;
2883
2884         spin_lock_irq(shost->host_lock);
2885
2886         if (vport->load_flag & FC_UNLOADING) {
2887                 stat = 1;
2888                 goto finished;
2889         }
2890         if (time >= 30 * HZ) {
2891                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
2892                                 "0461 Scanning longer than 30 "
2893                                 "seconds.  Continuing initialization\n");
2894                 stat = 1;
2895                 goto finished;
2896         }
2897         if (time >= 15 * HZ && phba->link_state <= LPFC_LINK_DOWN) {
2898                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
2899                                 "0465 Link down longer than 15 "
2900                                 "seconds.  Continuing initialization\n");
2901                 stat = 1;
2902                 goto finished;
2903         }
2904
2905         if (vport->port_state != LPFC_VPORT_READY)
2906                 goto finished;
2907         if (vport->num_disc_nodes || vport->fc_prli_sent)
2908                 goto finished;
2909         if (vport->fc_map_cnt == 0 && time < 2 * HZ)
2910                 goto finished;
2911         if ((phba->sli.sli_flag & LPFC_SLI_MBOX_ACTIVE) != 0)
2912                 goto finished;
2913
2914         stat = 1;
2915
2916 finished:
2917         spin_unlock_irq(shost->host_lock);
2918         return stat;
2919 }
2920
2921 /**
2922  * lpfc_host_attrib_init - Initialize SCSI host attributes on a FC port
2923  * @shost: pointer to SCSI host data structure.
2924  *
2925  * This routine initializes a given SCSI host attributes on a FC port. The
2926  * SCSI host can be either on top of a physical port or a virtual port.
2927  **/
2928 void lpfc_host_attrib_init(struct Scsi_Host *shost)
2929 {
2930         struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
2931         struct lpfc_hba   *phba = vport->phba;
2932         /*
2933          * Set fixed host attributes.  Must done after lpfc_sli_hba_setup().
2934          */
2935
2936         fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
2937         fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
2938         fc_host_supported_classes(shost) = FC_COS_CLASS3;
2939
2940         memset(fc_host_supported_fc4s(shost), 0,
2941                sizeof(fc_host_supported_fc4s(shost)));
2942         fc_host_supported_fc4s(shost)[2] = 1;
2943         fc_host_supported_fc4s(shost)[7] = 1;
2944
2945         lpfc_vport_symbolic_node_name(vport, fc_host_symbolic_name(shost),
2946                                  sizeof fc_host_symbolic_name(shost));
2947
2948         fc_host_supported_speeds(shost) = 0;
2949         if (phba->lmt & LMT_16Gb)
2950                 fc_host_supported_speeds(shost) |= FC_PORTSPEED_16GBIT;
2951         if (phba->lmt & LMT_10Gb)
2952                 fc_host_supported_speeds(shost) |= FC_PORTSPEED_10GBIT;
2953         if (phba->lmt & LMT_8Gb)
2954                 fc_host_supported_speeds(shost) |= FC_PORTSPEED_8GBIT;
2955         if (phba->lmt & LMT_4Gb)
2956                 fc_host_supported_speeds(shost) |= FC_PORTSPEED_4GBIT;
2957         if (phba->lmt & LMT_2Gb)
2958                 fc_host_supported_speeds(shost) |= FC_PORTSPEED_2GBIT;
2959         if (phba->lmt & LMT_1Gb)
2960                 fc_host_supported_speeds(shost) |= FC_PORTSPEED_1GBIT;
2961
2962         fc_host_maxframe_size(shost) =
2963                 (((uint32_t) vport->fc_sparam.cmn.bbRcvSizeMsb & 0x0F) << 8) |
2964                 (uint32_t) vport->fc_sparam.cmn.bbRcvSizeLsb;
2965
2966         fc_host_dev_loss_tmo(shost) = vport->cfg_devloss_tmo;
2967
2968         /* This value is also unchanging */
2969         memset(fc_host_active_fc4s(shost), 0,
2970                sizeof(fc_host_active_fc4s(shost)));
2971         fc_host_active_fc4s(shost)[2] = 1;
2972         fc_host_active_fc4s(shost)[7] = 1;
2973
2974         fc_host_max_npiv_vports(shost) = phba->max_vpi;
2975         spin_lock_irq(shost->host_lock);
2976         vport->load_flag &= ~FC_LOADING;
2977         spin_unlock_irq(shost->host_lock);
2978 }
2979
2980 /**
2981  * lpfc_stop_port_s3 - Stop SLI3 device port
2982  * @phba: pointer to lpfc hba data structure.
2983  *
2984  * This routine is invoked to stop an SLI3 device port, it stops the device
2985  * from generating interrupts and stops the device driver's timers for the
2986  * device.
2987  **/
2988 static void
2989 lpfc_stop_port_s3(struct lpfc_hba *phba)
2990 {
2991         /* Clear all interrupt enable conditions */
2992         writel(0, phba->HCregaddr);
2993         readl(phba->HCregaddr); /* flush */
2994         /* Clear all pending interrupts */
2995         writel(0xffffffff, phba->HAregaddr);
2996         readl(phba->HAregaddr); /* flush */
2997
2998         /* Reset some HBA SLI setup states */
2999         lpfc_stop_hba_timers(phba);
3000         phba->pport->work_port_events = 0;
3001 }
3002
3003 /**
3004  * lpfc_stop_port_s4 - Stop SLI4 device port
3005  * @phba: pointer to lpfc hba data structure.
3006  *
3007  * This routine is invoked to stop an SLI4 device port, it stops the device
3008  * from generating interrupts and stops the device driver's timers for the
3009  * device.
3010  **/
3011 static void
3012 lpfc_stop_port_s4(struct lpfc_hba *phba)
3013 {
3014         /* Reset some HBA SLI4 setup states */
3015         lpfc_stop_hba_timers(phba);
3016         phba->pport->work_port_events = 0;
3017         phba->sli4_hba.intr_enable = 0;
3018 }
3019
3020 /**
3021  * lpfc_stop_port - Wrapper function for stopping hba port
3022  * @phba: Pointer to HBA context object.
3023  *
3024  * This routine wraps the actual SLI3 or SLI4 hba stop port routine from
3025  * the API jump table function pointer from the lpfc_hba struct.
3026  **/
3027 void
3028 lpfc_stop_port(struct lpfc_hba *phba)
3029 {
3030         phba->lpfc_stop_port(phba);
3031 }
3032
3033 /**
3034  * lpfc_fcf_redisc_wait_start_timer - Start fcf rediscover wait timer
3035  * @phba: Pointer to hba for which this call is being executed.
3036  *
3037  * This routine starts the timer waiting for the FCF rediscovery to complete.
3038  **/
3039 void
3040 lpfc_fcf_redisc_wait_start_timer(struct lpfc_hba *phba)
3041 {
3042         unsigned long fcf_redisc_wait_tmo =
3043                 (jiffies + msecs_to_jiffies(LPFC_FCF_REDISCOVER_WAIT_TMO));
3044         /* Start fcf rediscovery wait period timer */
3045         mod_timer(&phba->fcf.redisc_wait, fcf_redisc_wait_tmo);
3046         spin_lock_irq(&phba->hbalock);
3047         /* Allow action to new fcf asynchronous event */
3048         phba->fcf.fcf_flag &= ~(FCF_AVAILABLE | FCF_SCAN_DONE);
3049         /* Mark the FCF rediscovery pending state */
3050         phba->fcf.fcf_flag |= FCF_REDISC_PEND;
3051         spin_unlock_irq(&phba->hbalock);
3052 }
3053
3054 /**
3055  * lpfc_sli4_fcf_redisc_wait_tmo - FCF table rediscover wait timeout
3056  * @ptr: Map to lpfc_hba data structure pointer.
3057  *
3058  * This routine is invoked when waiting for FCF table rediscover has been
3059  * timed out. If new FCF record(s) has (have) been discovered during the
3060  * wait period, a new FCF event shall be added to the FCOE async event
3061  * list, and then worker thread shall be waked up for processing from the
3062  * worker thread context.
3063  **/
3064 void
3065 lpfc_sli4_fcf_redisc_wait_tmo(unsigned long ptr)
3066 {
3067         struct lpfc_hba *phba = (struct lpfc_hba *)ptr;
3068
3069         /* Don't send FCF rediscovery event if timer cancelled */
3070         spin_lock_irq(&phba->hbalock);
3071         if (!(phba->fcf.fcf_flag & FCF_REDISC_PEND)) {
3072                 spin_unlock_irq(&phba->hbalock);
3073                 return;
3074         }
3075         /* Clear FCF rediscovery timer pending flag */
3076         phba->fcf.fcf_flag &= ~FCF_REDISC_PEND;
3077         /* FCF rediscovery event to worker thread */
3078         phba->fcf.fcf_flag |= FCF_REDISC_EVT;
3079         spin_unlock_irq(&phba->hbalock);
3080         lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
3081                         "2776 FCF rediscover quiescent timer expired\n");
3082         /* wake up worker thread */
3083         lpfc_worker_wake_up(phba);
3084 }
3085
3086 /**
3087  * lpfc_sli4_parse_latt_fault - Parse sli4 link-attention link fault code
3088  * @phba: pointer to lpfc hba data structure.
3089  * @acqe_link: pointer to the async link completion queue entry.
3090  *
3091  * This routine is to parse the SLI4 link-attention link fault code and
3092  * translate it into the base driver's read link attention mailbox command
3093  * status.
3094  *
3095  * Return: Link-attention status in terms of base driver's coding.
3096  **/
3097 static uint16_t
3098 lpfc_sli4_parse_latt_fault(struct lpfc_hba *phba,
3099                            struct lpfc_acqe_link *acqe_link)
3100 {
3101         uint16_t latt_fault;
3102
3103         switch (bf_get(lpfc_acqe_link_fault, acqe_link)) {
3104         case LPFC_ASYNC_LINK_FAULT_NONE:
3105         case LPFC_ASYNC_LINK_FAULT_LOCAL:
3106         case LPFC_ASYNC_LINK_FAULT_REMOTE:
3107                 latt_fault = 0;
3108                 break;
3109         default:
3110                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
3111                                 "0398 Invalid link fault code: x%x\n",
3112                                 bf_get(lpfc_acqe_link_fault, acqe_link));
3113                 latt_fault = MBXERR_ERROR;
3114                 break;
3115         }
3116         return latt_fault;
3117 }
3118
3119 /**
3120  * lpfc_sli4_parse_latt_type - Parse sli4 link attention type
3121  * @phba: pointer to lpfc hba data structure.
3122  * @acqe_link: pointer to the async link completion queue entry.
3123  *
3124  * This routine is to parse the SLI4 link attention type and translate it
3125  * into the base driver's link attention type coding.
3126  *
3127  * Return: Link attention type in terms of base driver's coding.
3128  **/
3129 static uint8_t
3130 lpfc_sli4_parse_latt_type(struct lpfc_hba *phba,
3131                           struct lpfc_acqe_link *acqe_link)
3132 {
3133         uint8_t att_type;
3134
3135         switch (bf_get(lpfc_acqe_link_status, acqe_link)) {
3136         case LPFC_ASYNC_LINK_STATUS_DOWN:
3137         case LPFC_ASYNC_LINK_STATUS_LOGICAL_DOWN:
3138                 att_type = LPFC_ATT_LINK_DOWN;
3139                 break;
3140         case LPFC_ASYNC_LINK_STATUS_UP:
3141                 /* Ignore physical link up events - wait for logical link up */
3142                 att_type = LPFC_ATT_RESERVED;
3143                 break;
3144         case LPFC_ASYNC_LINK_STATUS_LOGICAL_UP:
3145                 att_type = LPFC_ATT_LINK_UP;
3146                 break;
3147         default:
3148                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
3149                                 "0399 Invalid link attention type: x%x\n",
3150                                 bf_get(lpfc_acqe_link_status, acqe_link));
3151                 att_type = LPFC_ATT_RESERVED;
3152                 break;
3153         }
3154         return att_type;
3155 }
3156
3157 /**
3158  * lpfc_sli4_parse_latt_link_speed - Parse sli4 link-attention link speed
3159  * @phba: pointer to lpfc hba data structure.
3160  * @acqe_link: pointer to the async link completion queue entry.
3161  *
3162  * This routine is to parse the SLI4 link-attention link speed and translate
3163  * it into the base driver's link-attention link speed coding.
3164  *
3165  * Return: Link-attention link speed in terms of base driver's coding.
3166  **/
3167 static uint8_t
3168 lpfc_sli4_parse_latt_link_speed(struct lpfc_hba *phba,
3169                                 struct lpfc_acqe_link *acqe_link)
3170 {
3171         uint8_t link_speed;
3172
3173         switch (bf_get(lpfc_acqe_link_speed, acqe_link)) {
3174         case LPFC_ASYNC_LINK_SPEED_ZERO:
3175         case LPFC_ASYNC_LINK_SPEED_10MBPS:
3176         case LPFC_ASYNC_LINK_SPEED_100MBPS:
3177                 link_speed = LPFC_LINK_SPEED_UNKNOWN;
3178                 break;
3179         case LPFC_ASYNC_LINK_SPEED_1GBPS:
3180                 link_speed = LPFC_LINK_SPEED_1GHZ;
3181                 break;
3182         case LPFC_ASYNC_LINK_SPEED_10GBPS:
3183                 link_speed = LPFC_LINK_SPEED_10GHZ;
3184                 break;
3185         default:
3186                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
3187                                 "0483 Invalid link-attention link speed: x%x\n",
3188                                 bf_get(lpfc_acqe_link_speed, acqe_link));
3189                 link_speed = LPFC_LINK_SPEED_UNKNOWN;
3190                 break;
3191         }
3192         return link_speed;
3193 }
3194
3195 /**
3196  * lpfc_sli4_async_link_evt - Process the asynchronous FCoE link event
3197  * @phba: pointer to lpfc hba data structure.
3198  * @acqe_link: pointer to the async link completion queue entry.
3199  *
3200  * This routine is to handle the SLI4 asynchronous FCoE link event.
3201  **/
3202 static void
3203 lpfc_sli4_async_link_evt(struct lpfc_hba *phba,
3204                          struct lpfc_acqe_link *acqe_link)
3205 {
3206         struct lpfc_dmabuf *mp;
3207         LPFC_MBOXQ_t *pmb;
3208         MAILBOX_t *mb;
3209         struct lpfc_mbx_read_top *la;
3210         uint8_t att_type;
3211         int rc;
3212
3213         att_type = lpfc_sli4_parse_latt_type(phba, acqe_link);
3214         if (att_type != LPFC_ATT_LINK_DOWN && att_type != LPFC_ATT_LINK_UP)
3215                 return;
3216         phba->fcoe_eventtag = acqe_link->event_tag;
3217         pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
3218         if (!pmb) {
3219                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3220                                 "0395 The mboxq allocation failed\n");
3221                 return;
3222         }
3223         mp = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
3224         if (!mp) {
3225                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3226                                 "0396 The lpfc_dmabuf allocation failed\n");
3227                 goto out_free_pmb;
3228         }
3229         mp->virt = lpfc_mbuf_alloc(phba, 0, &mp->phys);
3230         if (!mp->virt) {
3231                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3232                                 "0397 The mbuf allocation failed\n");
3233                 goto out_free_dmabuf;
3234         }
3235
3236         /* Cleanup any outstanding ELS commands */
3237         lpfc_els_flush_all_cmd(phba);
3238
3239         /* Block ELS IOCBs until we have done process link event */
3240         phba->sli.ring[LPFC_ELS_RING].flag |= LPFC_STOP_IOCB_EVENT;
3241
3242         /* Update link event statistics */
3243         phba->sli.slistat.link_event++;
3244
3245         /* Create lpfc_handle_latt mailbox command from link ACQE */
3246         lpfc_read_topology(phba, pmb, mp);
3247         pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
3248         pmb->vport = phba->pport;
3249
3250         /* Keep the link status for extra SLI4 state machine reference */
3251         phba->sli4_hba.link_state.speed =
3252                                 bf_get(lpfc_acqe_link_speed, acqe_link);
3253         phba->sli4_hba.link_state.duplex =
3254                                 bf_get(lpfc_acqe_link_duplex, acqe_link);
3255         phba->sli4_hba.link_state.status =
3256                                 bf_get(lpfc_acqe_link_status, acqe_link);
3257         phba->sli4_hba.link_state.type =
3258                                 bf_get(lpfc_acqe_link_type, acqe_link);
3259         phba->sli4_hba.link_state.number =
3260                                 bf_get(lpfc_acqe_link_number, acqe_link);
3261         phba->sli4_hba.link_state.fault =
3262                                 bf_get(lpfc_acqe_link_fault, acqe_link);
3263         phba->sli4_hba.link_state.logical_speed =
3264                         bf_get(lpfc_acqe_logical_link_speed, acqe_link);
3265         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3266                         "2900 Async FC/FCoE Link event - Speed:%dGBit "
3267                         "duplex:x%x LA Type:x%x Port Type:%d Port Number:%d "
3268                         "Logical speed:%dMbps Fault:%d\n",
3269                         phba->sli4_hba.link_state.speed,
3270                         phba->sli4_hba.link_state.topology,
3271                         phba->sli4_hba.link_state.status,
3272                         phba->sli4_hba.link_state.type,
3273                         phba->sli4_hba.link_state.number,
3274                         phba->sli4_hba.link_state.logical_speed * 10,
3275                         phba->sli4_hba.link_state.fault);
3276         /*
3277          * For FC Mode: issue the READ_TOPOLOGY mailbox command to fetch
3278          * topology info. Note: Optional for non FC-AL ports.
3279          */
3280         if (!(phba->hba_flag & HBA_FCOE_MODE)) {
3281                 rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
3282                 if (rc == MBX_NOT_FINISHED)
3283                         goto out_free_dmabuf;
3284                 return;
3285         }
3286         /*
3287          * For FCoE Mode: fill in all the topology information we need and call
3288          * the READ_TOPOLOGY completion routine to continue without actually
3289          * sending the READ_TOPOLOGY mailbox command to the port.
3290          */
3291         /* Parse and translate status field */
3292         mb = &pmb->u.mb;
3293         mb->mbxStatus = lpfc_sli4_parse_latt_fault(phba, acqe_link);
3294
3295         /* Parse and translate link attention fields */
3296         la = (struct lpfc_mbx_read_top *) &pmb->u.mb.un.varReadTop;
3297         la->eventTag = acqe_link->event_tag;
3298         bf_set(lpfc_mbx_read_top_att_type, la, att_type);
3299         bf_set(lpfc_mbx_read_top_link_spd, la,
3300                lpfc_sli4_parse_latt_link_speed(phba, acqe_link));
3301
3302         /* Fake the the following irrelvant fields */
3303         bf_set(lpfc_mbx_read_top_topology, la, LPFC_TOPOLOGY_PT_PT);
3304         bf_set(lpfc_mbx_read_top_alpa_granted, la, 0);
3305         bf_set(lpfc_mbx_read_top_il, la, 0);
3306         bf_set(lpfc_mbx_read_top_pb, la, 0);
3307         bf_set(lpfc_mbx_read_top_fa, la, 0);
3308         bf_set(lpfc_mbx_read_top_mm, la, 0);
3309
3310         /* Invoke the lpfc_handle_latt mailbox command callback function */
3311         lpfc_mbx_cmpl_read_topology(phba, pmb);
3312
3313         return;
3314
3315 out_free_dmabuf:
3316         kfree(mp);
3317 out_free_pmb:
3318         mempool_free(pmb, phba->mbox_mem_pool);
3319 }
3320
3321 /**
3322  * lpfc_sli4_async_fc_evt - Process the asynchronous FC link event
3323  * @phba: pointer to lpfc hba data structure.
3324  * @acqe_fc: pointer to the async fc completion queue entry.
3325  *
3326  * This routine is to handle the SLI4 asynchronous FC event. It will simply log
3327  * that the event was received and then issue a read_topology mailbox command so
3328  * that the rest of the driver will treat it the same as SLI3.
3329  **/
3330 static void
3331 lpfc_sli4_async_fc_evt(struct lpfc_hba *phba, struct lpfc_acqe_fc_la *acqe_fc)
3332 {
3333         struct lpfc_dmabuf *mp;
3334         LPFC_MBOXQ_t *pmb;
3335         int rc;
3336
3337         if (bf_get(lpfc_trailer_type, acqe_fc) !=
3338             LPFC_FC_LA_EVENT_TYPE_FC_LINK) {
3339                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3340                                 "2895 Non FC link Event detected.(%d)\n",
3341                                 bf_get(lpfc_trailer_type, acqe_fc));
3342                 return;
3343         }
3344         /* Keep the link status for extra SLI4 state machine reference */
3345         phba->sli4_hba.link_state.speed =
3346                                 bf_get(lpfc_acqe_fc_la_speed, acqe_fc);
3347         phba->sli4_hba.link_state.duplex = LPFC_ASYNC_LINK_DUPLEX_FULL;
3348         phba->sli4_hba.link_state.topology =
3349                                 bf_get(lpfc_acqe_fc_la_topology, acqe_fc);
3350         phba->sli4_hba.link_state.status =
3351                                 bf_get(lpfc_acqe_fc_la_att_type, acqe_fc);
3352         phba->sli4_hba.link_state.type =
3353                                 bf_get(lpfc_acqe_fc_la_port_type, acqe_fc);
3354         phba->sli4_hba.link_state.number =
3355                                 bf_get(lpfc_acqe_fc_la_port_number, acqe_fc);
3356         phba->sli4_hba.link_state.fault =
3357                                 bf_get(lpfc_acqe_link_fault, acqe_fc);
3358         phba->sli4_hba.link_state.logical_speed =
3359                                 bf_get(lpfc_acqe_fc_la_llink_spd, acqe_fc);
3360         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3361                         "2896 Async FC event - Speed:%dGBaud Topology:x%x "
3362                         "LA Type:x%x Port Type:%d Port Number:%d Logical speed:"
3363                         "%dMbps Fault:%d\n",
3364                         phba->sli4_hba.link_state.speed,
3365                         phba->sli4_hba.link_state.topology,
3366                         phba->sli4_hba.link_state.status,
3367                         phba->sli4_hba.link_state.type,
3368                         phba->sli4_hba.link_state.number,
3369                         phba->sli4_hba.link_state.logical_speed * 10,
3370                         phba->sli4_hba.link_state.fault);
3371         pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
3372         if (!pmb) {
3373                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3374                                 "2897 The mboxq allocation failed\n");
3375                 return;
3376         }
3377         mp = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
3378         if (!mp) {
3379                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3380                                 "2898 The lpfc_dmabuf allocation failed\n");
3381                 goto out_free_pmb;
3382         }
3383         mp->virt = lpfc_mbuf_alloc(phba, 0, &mp->phys);
3384         if (!mp->virt) {
3385                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3386                                 "2899 The mbuf allocation failed\n");
3387                 goto out_free_dmabuf;
3388         }
3389
3390         /* Cleanup any outstanding ELS commands */
3391         lpfc_els_flush_all_cmd(phba);
3392
3393         /* Block ELS IOCBs until we have done process link event */
3394         phba->sli.ring[LPFC_ELS_RING].flag |= LPFC_STOP_IOCB_EVENT;
3395
3396         /* Update link event statistics */
3397         phba->sli.slistat.link_event++;
3398
3399         /* Create lpfc_handle_latt mailbox command from link ACQE */
3400         lpfc_read_topology(phba, pmb, mp);
3401         pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
3402         pmb->vport = phba->pport;
3403
3404         rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
3405         if (rc == MBX_NOT_FINISHED)
3406                 goto out_free_dmabuf;
3407         return;
3408
3409 out_free_dmabuf:
3410         kfree(mp);
3411 out_free_pmb:
3412         mempool_free(pmb, phba->mbox_mem_pool);
3413 }
3414
3415 /**
3416  * lpfc_sli4_async_sli_evt - Process the asynchronous SLI link event
3417  * @phba: pointer to lpfc hba data structure.
3418  * @acqe_fc: pointer to the async SLI completion queue entry.
3419  *
3420  * This routine is to handle the SLI4 asynchronous SLI events.
3421  **/
3422 static void
3423 lpfc_sli4_async_sli_evt(struct lpfc_hba *phba, struct lpfc_acqe_sli *acqe_sli)
3424 {
3425         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3426                         "2901 Async SLI event - Event Data1:x%08x Event Data2:"
3427                         "x%08x SLI Event Type:%d",
3428                         acqe_sli->event_data1, acqe_sli->event_data2,
3429                         bf_get(lpfc_trailer_type, acqe_sli));
3430         return;
3431 }
3432
3433 /**
3434  * lpfc_sli4_perform_vport_cvl - Perform clear virtual link on a vport
3435  * @vport: pointer to vport data structure.
3436  *
3437  * This routine is to perform Clear Virtual Link (CVL) on a vport in
3438  * response to a CVL event.
3439  *
3440  * Return the pointer to the ndlp with the vport if successful, otherwise
3441  * return NULL.
3442  **/
3443 static struct lpfc_nodelist *
3444 lpfc_sli4_perform_vport_cvl(struct lpfc_vport *vport)
3445 {
3446         struct lpfc_nodelist *ndlp;
3447         struct Scsi_Host *shost;
3448         struct lpfc_hba *phba;
3449
3450         if (!vport)
3451                 return NULL;
3452         phba = vport->phba;
3453         if (!phba)
3454                 return NULL;
3455         ndlp = lpfc_findnode_did(vport, Fabric_DID);
3456         if (!ndlp) {
3457                 /* Cannot find existing Fabric ndlp, so allocate a new one */
3458                 ndlp = mempool_alloc(phba->nlp_mem_pool, GFP_KERNEL);
3459                 if (!ndlp)
3460                         return 0;
3461                 lpfc_nlp_init(vport, ndlp, Fabric_DID);
3462                 /* Set the node type */
3463                 ndlp->nlp_type |= NLP_FABRIC;
3464                 /* Put ndlp onto node list */
3465                 lpfc_enqueue_node(vport, ndlp);
3466         } else if (!NLP_CHK_NODE_ACT(ndlp)) {
3467                 /* re-setup ndlp without removing from node list */
3468                 ndlp = lpfc_enable_node(vport, ndlp, NLP_STE_UNUSED_NODE);
3469                 if (!ndlp)
3470                         return 0;
3471         }
3472         if ((phba->pport->port_state < LPFC_FLOGI) &&
3473                 (phba->pport->port_state != LPFC_VPORT_FAILED))
3474                 return NULL;
3475         /* If virtual link is not yet instantiated ignore CVL */
3476         if ((vport != phba->pport) && (vport->port_state < LPFC_FDISC)
3477                 && (vport->port_state != LPFC_VPORT_FAILED))
3478                 return NULL;
3479         shost = lpfc_shost_from_vport(vport);
3480         if (!shost)
3481                 return NULL;
3482         lpfc_linkdown_port(vport);
3483         lpfc_cleanup_pending_mbox(vport);
3484         spin_lock_irq(shost->host_lock);
3485         vport->fc_flag |= FC_VPORT_CVL_RCVD;
3486         spin_unlock_irq(shost->host_lock);
3487
3488         return ndlp;
3489 }
3490
3491 /**
3492  * lpfc_sli4_perform_all_vport_cvl - Perform clear virtual link on all vports
3493  * @vport: pointer to lpfc hba data structure.
3494  *
3495  * This routine is to perform Clear Virtual Link (CVL) on all vports in
3496  * response to a FCF dead event.
3497  **/
3498 static void
3499 lpfc_sli4_perform_all_vport_cvl(struct lpfc_hba *phba)
3500 {
3501         struct lpfc_vport **vports;
3502         int i;
3503
3504         vports = lpfc_create_vport_work_array(phba);
3505         if (vports)
3506                 for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++)
3507                         lpfc_sli4_perform_vport_cvl(vports[i]);
3508         lpfc_destroy_vport_work_array(phba, vports);
3509 }
3510
3511 /**
3512  * lpfc_sli4_async_fip_evt - Process the asynchronous FCoE FIP event
3513  * @phba: pointer to lpfc hba data structure.
3514  * @acqe_link: pointer to the async fcoe completion queue entry.
3515  *
3516  * This routine is to handle the SLI4 asynchronous fcoe event.
3517  **/
3518 static void
3519 lpfc_sli4_async_fip_evt(struct lpfc_hba *phba,
3520                         struct lpfc_acqe_fip *acqe_fip)
3521 {
3522         uint8_t event_type = bf_get(lpfc_trailer_type, acqe_fip);
3523         int rc;
3524         struct lpfc_vport *vport;
3525         struct lpfc_nodelist *ndlp;
3526         struct Scsi_Host  *shost;
3527         int active_vlink_present;
3528         struct lpfc_vport **vports;
3529         int i;
3530
3531         phba->fc_eventTag = acqe_fip->event_tag;
3532         phba->fcoe_eventtag = acqe_fip->event_tag;
3533         switch (event_type) {
3534         case LPFC_FIP_EVENT_TYPE_NEW_FCF:
3535         case LPFC_FIP_EVENT_TYPE_FCF_PARAM_MOD:
3536                 if (event_type == LPFC_FIP_EVENT_TYPE_NEW_FCF)
3537                         lpfc_printf_log(phba, KERN_ERR, LOG_FIP |
3538                                         LOG_DISCOVERY,
3539                                         "2546 New FCF event, evt_tag:x%x, "
3540                                         "index:x%x\n",
3541                                         acqe_fip->event_tag,
3542                                         acqe_fip->index);
3543                 else
3544                         lpfc_printf_log(phba, KERN_WARNING, LOG_FIP |
3545                                         LOG_DISCOVERY,
3546                                         "2788 FCF param modified event, "
3547                                         "evt_tag:x%x, index:x%x\n",
3548                                         acqe_fip->event_tag,
3549                                         acqe_fip->index);
3550                 if (phba->fcf.fcf_flag & FCF_DISCOVERY) {
3551                         /*
3552                          * During period of FCF discovery, read the FCF
3553                          * table record indexed by the event to update
3554                          * FCF roundrobin failover eligible FCF bmask.
3555                          */
3556                         lpfc_printf_log(phba, KERN_INFO, LOG_FIP |
3557                                         LOG_DISCOVERY,
3558                                         "2779 Read FCF (x%x) for updating "
3559                                         "roundrobin FCF failover bmask\n",
3560                                         acqe_fip->index);
3561                         rc = lpfc_sli4_read_fcf_rec(phba, acqe_fip->index);
3562                 }
3563
3564                 /* If the FCF discovery is in progress, do nothing. */
3565                 spin_lock_irq(&phba->hbalock);
3566                 if (phba->hba_flag & FCF_TS_INPROG) {
3567                         spin_unlock_irq(&phba->hbalock);
3568                         break;
3569                 }
3570                 /* If fast FCF failover rescan event is pending, do nothing */
3571                 if (phba->fcf.fcf_flag & FCF_REDISC_EVT) {
3572                         spin_unlock_irq(&phba->hbalock);
3573                         break;
3574                 }
3575
3576                 /* If the FCF has been in discovered state, do nothing. */
3577                 if (phba->fcf.fcf_flag & FCF_SCAN_DONE) {
3578                         spin_unlock_irq(&phba->hbalock);
3579                         break;
3580                 }
3581                 spin_unlock_irq(&phba->hbalock);
3582
3583                 /* Otherwise, scan the entire FCF table and re-discover SAN */
3584                 lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
3585                                 "2770 Start FCF table scan per async FCF "
3586                                 "event, evt_tag:x%x, index:x%x\n",
3587                                 acqe_fip->event_tag, acqe_fip->index);
3588                 rc = lpfc_sli4_fcf_scan_read_fcf_rec(phba,
3589                                                      LPFC_FCOE_FCF_GET_FIRST);
3590                 if (rc)
3591                         lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_DISCOVERY,
3592                                         "2547 Issue FCF scan read FCF mailbox "
3593                                         "command failed (x%x)\n", rc);
3594                 break;
3595
3596         case LPFC_FIP_EVENT_TYPE_FCF_TABLE_FULL:
3597                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3598                         "2548 FCF Table full count 0x%x tag 0x%x\n",
3599                         bf_get(lpfc_acqe_fip_fcf_count, acqe_fip),
3600                         acqe_fip->event_tag);
3601                 break;
3602
3603         case LPFC_FIP_EVENT_TYPE_FCF_DEAD:
3604                 lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_DISCOVERY,
3605                         "2549 FCF (x%x) disconnected from network, "
3606                         "tag:x%x\n", acqe_fip->index, acqe_fip->event_tag);
3607                 /*
3608                  * If we are in the middle of FCF failover process, clear
3609                  * the corresponding FCF bit in the roundrobin bitmap.
3610                  */
3611                 spin_lock_irq(&phba->hbalock);
3612                 if (phba->fcf.fcf_flag & FCF_DISCOVERY) {
3613                         spin_unlock_irq(&phba->hbalock);
3614                         /* Update FLOGI FCF failover eligible FCF bmask */
3615                         lpfc_sli4_fcf_rr_index_clear(phba, acqe_fip->index);
3616                         break;
3617                 }
3618                 spin_unlock_irq(&phba->hbalock);
3619
3620                 /* If the event is not for currently used fcf do nothing */
3621                 if (phba->fcf.current_rec.fcf_indx != acqe_fip->index)
3622                         break;
3623
3624                 /*
3625                  * Otherwise, request the port to rediscover the entire FCF
3626                  * table for a fast recovery from case that the current FCF
3627                  * is no longer valid as we are not in the middle of FCF
3628                  * failover process already.
3629                  */
3630                 spin_lock_irq(&phba->hbalock);
3631                 /* Mark the fast failover process in progress */
3632                 phba->fcf.fcf_flag |= FCF_DEAD_DISC;
3633                 spin_unlock_irq(&phba->hbalock);
3634
3635                 lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
3636                                 "2771 Start FCF fast failover process due to "
3637                                 "FCF DEAD event: evt_tag:x%x, fcf_index:x%x "
3638                                 "\n", acqe_fip->event_tag, acqe_fip->index);
3639                 rc = lpfc_sli4_redisc_fcf_table(phba);
3640                 if (rc) {
3641                         lpfc_printf_log(phba, KERN_ERR, LOG_FIP |
3642                                         LOG_DISCOVERY,
3643                                         "2772 Issue FCF rediscover mabilbox "
3644                                         "command failed, fail through to FCF "
3645                                         "dead event\n");
3646                         spin_lock_irq(&phba->hbalock);
3647                         phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
3648                         spin_unlock_irq(&phba->hbalock);
3649                         /*
3650                          * Last resort will fail over by treating this
3651                          * as a link down to FCF registration.
3652                          */
3653                         lpfc_sli4_fcf_dead_failthrough(phba);
3654                 } else {
3655                         /* Reset FCF roundrobin bmask for new discovery */
3656                         lpfc_sli4_clear_fcf_rr_bmask(phba);
3657                         /*
3658                          * Handling fast FCF failover to a DEAD FCF event is
3659                          * considered equalivant to receiving CVL to all vports.
3660                          */
3661                         lpfc_sli4_perform_all_vport_cvl(phba);
3662                 }
3663                 break;
3664         case LPFC_FIP_EVENT_TYPE_CVL:
3665                 lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_DISCOVERY,
3666                         "2718 Clear Virtual Link Received for VPI 0x%x"
3667                         " tag 0x%x\n", acqe_fip->index, acqe_fip->event_tag);
3668
3669                 vport = lpfc_find_vport_by_vpid(phba,
3670                                                 acqe_fip->index);
3671                 ndlp = lpfc_sli4_perform_vport_cvl(vport);
3672                 if (!ndlp)
3673                         break;
3674                 active_vlink_present = 0;
3675
3676                 vports = lpfc_create_vport_work_array(phba);
3677                 if (vports) {
3678                         for (i = 0; i <= phba->max_vports && vports[i] != NULL;
3679                                         i++) {
3680                                 if ((!(vports[i]->fc_flag &
3681                                         FC_VPORT_CVL_RCVD)) &&
3682                                         (vports[i]->port_state > LPFC_FDISC)) {
3683                                         active_vlink_present = 1;
3684                                         break;
3685                                 }
3686                         }
3687                         lpfc_destroy_vport_work_array(phba, vports);
3688                 }
3689
3690                 if (active_vlink_present) {
3691                         /*
3692                          * If there are other active VLinks present,
3693                          * re-instantiate the Vlink using FDISC.
3694                          */
3695                         mod_timer(&ndlp->nlp_delayfunc, jiffies + HZ);
3696                         shost = lpfc_shost_from_vport(vport);
3697                         spin_lock_irq(shost->host_lock);
3698                         ndlp->nlp_flag |= NLP_DELAY_TMO;
3699                         spin_unlock_irq(shost->host_lock);
3700                         ndlp->nlp_last_elscmd = ELS_CMD_FDISC;
3701                         vport->port_state = LPFC_FDISC;
3702                 } else {
3703                         /*
3704                          * Otherwise, we request port to rediscover
3705                          * the entire FCF table for a fast recovery
3706                          * from possible case that the current FCF
3707                          * is no longer valid if we are not already
3708                          * in the FCF failover process.
3709                          */
3710                         spin_lock_irq(&phba->hbalock);
3711                         if (phba->fcf.fcf_flag & FCF_DISCOVERY) {
3712                                 spin_unlock_irq(&phba->hbalock);
3713                                 break;
3714                         }
3715                         /* Mark the fast failover process in progress */
3716                         phba->fcf.fcf_flag |= FCF_ACVL_DISC;
3717                         spin_unlock_irq(&phba->hbalock);
3718                         lpfc_printf_log(phba, KERN_INFO, LOG_FIP |
3719                                         LOG_DISCOVERY,
3720                                         "2773 Start FCF failover per CVL, "
3721                                         "evt_tag:x%x\n", acqe_fip->event_tag);
3722                         rc = lpfc_sli4_redisc_fcf_table(phba);
3723                         if (rc) {
3724                                 lpfc_printf_log(phba, KERN_ERR, LOG_FIP |
3725                                                 LOG_DISCOVERY,
3726                                                 "2774 Issue FCF rediscover "
3727                                                 "mabilbox command failed, "
3728                                                 "through to CVL event\n");
3729                                 spin_lock_irq(&phba->hbalock);
3730                                 phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
3731                                 spin_unlock_irq(&phba->hbalock);
3732                                 /*
3733                                  * Last resort will be re-try on the
3734                                  * the current registered FCF entry.
3735                                  */
3736                                 lpfc_retry_pport_discovery(phba);
3737                         } else
3738                                 /*
3739                                  * Reset FCF roundrobin bmask for new
3740                                  * discovery.
3741                                  */
3742                                 lpfc_sli4_clear_fcf_rr_bmask(phba);
3743                 }
3744                 break;
3745         default:
3746                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3747                         "0288 Unknown FCoE event type 0x%x event tag "
3748                         "0x%x\n", event_type, acqe_fip->event_tag);
3749                 break;
3750         }
3751 }
3752
3753 /**
3754  * lpfc_sli4_async_dcbx_evt - Process the asynchronous dcbx event
3755  * @phba: pointer to lpfc hba data structure.
3756  * @acqe_link: pointer to the async dcbx completion queue entry.
3757  *
3758  * This routine is to handle the SLI4 asynchronous dcbx event.
3759  **/
3760 static void
3761 lpfc_sli4_async_dcbx_evt(struct lpfc_hba *phba,
3762                          struct lpfc_acqe_dcbx *acqe_dcbx)
3763 {
3764         phba->fc_eventTag = acqe_dcbx->event_tag;
3765         lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3766                         "0290 The SLI4 DCBX asynchronous event is not "
3767                         "handled yet\n");
3768 }
3769
3770 /**
3771  * lpfc_sli4_async_grp5_evt - Process the asynchronous group5 event
3772  * @phba: pointer to lpfc hba data structure.
3773  * @acqe_link: pointer to the async grp5 completion queue entry.
3774  *
3775  * This routine is to handle the SLI4 asynchronous grp5 event. A grp5 event
3776  * is an asynchronous notified of a logical link speed change.  The Port
3777  * reports the logical link speed in units of 10Mbps.
3778  **/
3779 static void
3780 lpfc_sli4_async_grp5_evt(struct lpfc_hba *phba,
3781                          struct lpfc_acqe_grp5 *acqe_grp5)
3782 {
3783         uint16_t prev_ll_spd;
3784
3785         phba->fc_eventTag = acqe_grp5->event_tag;
3786         phba->fcoe_eventtag = acqe_grp5->event_tag;
3787         prev_ll_spd = phba->sli4_hba.link_state.logical_speed;
3788         phba->sli4_hba.link_state.logical_speed =
3789                 (bf_get(lpfc_acqe_grp5_llink_spd, acqe_grp5));
3790         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3791                         "2789 GRP5 Async Event: Updating logical link speed "
3792                         "from %dMbps to %dMbps\n", (prev_ll_spd * 10),
3793                         (phba->sli4_hba.link_state.logical_speed*10));
3794 }
3795
3796 /**
3797  * lpfc_sli4_async_event_proc - Process all the pending asynchronous event
3798  * @phba: pointer to lpfc hba data structure.
3799  *
3800  * This routine is invoked by the worker thread to process all the pending
3801  * SLI4 asynchronous events.
3802  **/
3803 void lpfc_sli4_async_event_proc(struct lpfc_hba *phba)
3804 {
3805         struct lpfc_cq_event *cq_event;
3806
3807         /* First, declare the async event has been handled */
3808         spin_lock_irq(&phba->hbalock);
3809         phba->hba_flag &= ~ASYNC_EVENT;
3810         spin_unlock_irq(&phba->hbalock);
3811         /* Now, handle all the async events */
3812         while (!list_empty(&phba->sli4_hba.sp_asynce_work_queue)) {
3813                 /* Get the first event from the head of the event queue */
3814                 spin_lock_irq(&phba->hbalock);
3815                 list_remove_head(&phba->sli4_hba.sp_asynce_work_queue,
3816                                  cq_event, struct lpfc_cq_event, list);
3817                 spin_unlock_irq(&phba->hbalock);
3818                 /* Process the asynchronous event */
3819                 switch (bf_get(lpfc_trailer_code, &cq_event->cqe.mcqe_cmpl)) {
3820                 case LPFC_TRAILER_CODE_LINK:
3821                         lpfc_sli4_async_link_evt(phba,
3822                                                  &cq_event->cqe.acqe_link);
3823                         break;
3824                 case LPFC_TRAILER_CODE_FCOE:
3825                         lpfc_sli4_async_fip_evt(phba, &cq_event->cqe.acqe_fip);
3826                         break;
3827                 case LPFC_TRAILER_CODE_DCBX:
3828                         lpfc_sli4_async_dcbx_evt(phba,
3829                                                  &cq_event->cqe.acqe_dcbx);
3830                         break;
3831                 case LPFC_TRAILER_CODE_GRP5:
3832                         lpfc_sli4_async_grp5_evt(phba,
3833                                                  &cq_event->cqe.acqe_grp5);
3834                         break;
3835                 case LPFC_TRAILER_CODE_FC:
3836                         lpfc_sli4_async_fc_evt(phba, &cq_event->cqe.acqe_fc);
3837                         break;
3838                 case LPFC_TRAILER_CODE_SLI:
3839                         lpfc_sli4_async_sli_evt(phba, &cq_event->cqe.acqe_sli);
3840                         break;
3841                 default:
3842                         lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3843                                         "1804 Invalid asynchrous event code: "
3844                                         "x%x\n", bf_get(lpfc_trailer_code,
3845                                         &cq_event->cqe.mcqe_cmpl));
3846                         break;
3847                 }
3848                 /* Free the completion event processed to the free pool */
3849                 lpfc_sli4_cq_event_release(phba, cq_event);
3850         }
3851 }
3852
3853 /**
3854  * lpfc_sli4_fcf_redisc_event_proc - Process fcf table rediscovery event
3855  * @phba: pointer to lpfc hba data structure.
3856  *
3857  * This routine is invoked by the worker thread to process FCF table
3858  * rediscovery pending completion event.
3859  **/
3860 void lpfc_sli4_fcf_redisc_event_proc(struct lpfc_hba *phba)
3861 {
3862         int rc;
3863
3864         spin_lock_irq(&phba->hbalock);
3865         /* Clear FCF rediscovery timeout event */
3866         phba->fcf.fcf_flag &= ~FCF_REDISC_EVT;
3867         /* Clear driver fast failover FCF record flag */
3868         phba->fcf.failover_rec.flag = 0;
3869         /* Set state for FCF fast failover */
3870         phba->fcf.fcf_flag |= FCF_REDISC_FOV;
3871         spin_unlock_irq(&phba->hbalock);
3872
3873         /* Scan FCF table from the first entry to re-discover SAN */
3874         lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
3875                         "2777 Start post-quiescent FCF table scan\n");
3876         rc = lpfc_sli4_fcf_scan_read_fcf_rec(phba, LPFC_FCOE_FCF_GET_FIRST);
3877         if (rc)
3878                 lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_DISCOVERY,
3879                                 "2747 Issue FCF scan read FCF mailbox "
3880                                 "command failed 0x%x\n", rc);
3881 }
3882
3883 /**
3884  * lpfc_api_table_setup - Set up per hba pci-device group func api jump table
3885  * @phba: pointer to lpfc hba data structure.
3886  * @dev_grp: The HBA PCI-Device group number.
3887  *
3888  * This routine is invoked to set up the per HBA PCI-Device group function
3889  * API jump table entries.
3890  *
3891  * Return: 0 if success, otherwise -ENODEV
3892  **/
3893 int
3894 lpfc_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
3895 {
3896         int rc;
3897
3898         /* Set up lpfc PCI-device group */
3899         phba->pci_dev_grp = dev_grp;
3900
3901         /* The LPFC_PCI_DEV_OC uses SLI4 */
3902         if (dev_grp == LPFC_PCI_DEV_OC)
3903                 phba->sli_rev = LPFC_SLI_REV4;
3904
3905         /* Set up device INIT API function jump table */
3906         rc = lpfc_init_api_table_setup(phba, dev_grp);
3907         if (rc)
3908                 return -ENODEV;
3909         /* Set up SCSI API function jump table */
3910         rc = lpfc_scsi_api_table_setup(phba, dev_grp);
3911         if (rc)
3912                 return -ENODEV;
3913         /* Set up SLI API function jump table */
3914         rc = lpfc_sli_api_table_setup(phba, dev_grp);
3915         if (rc)
3916                 return -ENODEV;
3917         /* Set up MBOX API function jump table */
3918         rc = lpfc_mbox_api_table_setup(phba, dev_grp);
3919         if (rc)
3920                 return -ENODEV;
3921
3922         return 0;
3923 }
3924
3925 /**
3926  * lpfc_log_intr_mode - Log the active interrupt mode
3927  * @phba: pointer to lpfc hba data structure.
3928  * @intr_mode: active interrupt mode adopted.
3929  *
3930  * This routine it invoked to log the currently used active interrupt mode
3931  * to the device.
3932  **/
3933 static void lpfc_log_intr_mode(struct lpfc_hba *phba, uint32_t intr_mode)
3934 {
3935         switch (intr_mode) {
3936         case 0:
3937                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3938                                 "0470 Enable INTx interrupt mode.\n");
3939                 break;
3940         case 1:
3941                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3942                                 "0481 Enabled MSI interrupt mode.\n");
3943                 break;
3944         case 2:
3945                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3946                                 "0480 Enabled MSI-X interrupt mode.\n");
3947                 break;
3948         default:
3949                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
3950                                 "0482 Illegal interrupt mode.\n");
3951                 break;
3952         }
3953         return;
3954 }
3955
3956 /**
3957  * lpfc_enable_pci_dev - Enable a generic PCI device.
3958  * @phba: pointer to lpfc hba data structure.
3959  *
3960  * This routine is invoked to enable the PCI device that is common to all
3961  * PCI devices.
3962  *
3963  * Return codes
3964  *      0 - successful
3965  *      other values - error
3966  **/
3967 static int
3968 lpfc_enable_pci_dev(struct lpfc_hba *phba)
3969 {
3970         struct pci_dev *pdev;
3971         int bars = 0;
3972
3973         /* Obtain PCI device reference */
3974         if (!phba->pcidev)
3975                 goto out_error;
3976         else
3977                 pdev = phba->pcidev;
3978         /* Select PCI BARs */
3979         bars = pci_select_bars(pdev, IORESOURCE_MEM);
3980         /* Enable PCI device */
3981         if (pci_enable_device_mem(pdev))
3982                 goto out_error;
3983         /* Request PCI resource for the device */
3984         if (pci_request_selected_regions(pdev, bars, LPFC_DRIVER_NAME))
3985                 goto out_disable_device;
3986         /* Set up device as PCI master and save state for EEH */
3987         pci_set_master(pdev);
3988         pci_try_set_mwi(pdev);
3989         pci_save_state(pdev);
3990
3991         /* PCIe EEH recovery on powerpc platforms needs fundamental reset */
3992         if (pci_find_capability(pdev, PCI_CAP_ID_EXP))
3993                 pdev->needs_freset = 1;
3994
3995         return 0;
3996
3997 out_disable_device:
3998         pci_disable_device(pdev);
3999 out_error:
4000         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4001                         "1401 Failed to enable pci device, bars:x%x\n", bars);
4002         return -ENODEV;
4003 }
4004
4005 /**
4006  * lpfc_disable_pci_dev - Disable a generic PCI device.
4007  * @phba: pointer to lpfc hba data structure.
4008  *
4009  * This routine is invoked to disable the PCI device that is common to all
4010  * PCI devices.
4011  **/
4012 static void
4013 lpfc_disable_pci_dev(struct lpfc_hba *phba)
4014 {
4015         struct pci_dev *pdev;
4016         int bars;
4017
4018         /* Obtain PCI device reference */
4019         if (!phba->pcidev)
4020                 return;
4021         else
4022                 pdev = phba->pcidev;
4023         /* Select PCI BARs */
4024         bars = pci_select_bars(pdev, IORESOURCE_MEM);
4025         /* Release PCI resource and disable PCI device */
4026         pci_release_selected_regions(pdev, bars);
4027         pci_disable_device(pdev);
4028         /* Null out PCI private reference to driver */
4029         pci_set_drvdata(pdev, NULL);
4030
4031         return;
4032 }
4033
4034 /**
4035  * lpfc_reset_hba - Reset a hba
4036  * @phba: pointer to lpfc hba data structure.
4037  *
4038  * This routine is invoked to reset a hba device. It brings the HBA
4039  * offline, performs a board restart, and then brings the board back
4040  * online. The lpfc_offline calls lpfc_sli_hba_down which will clean up
4041  * on outstanding mailbox commands.
4042  **/
4043 void
4044 lpfc_reset_hba(struct lpfc_hba *phba)
4045 {
4046         /* If resets are disabled then set error state and return. */
4047         if (!phba->cfg_enable_hba_reset) {
4048                 phba->link_state = LPFC_HBA_ERROR;
4049                 return;
4050         }
4051         lpfc_offline_prep(phba);
4052         lpfc_offline(phba);
4053         lpfc_sli_brdrestart(phba);
4054         lpfc_online(phba);
4055         lpfc_unblock_mgmt_io(phba);
4056 }
4057
4058 /**
4059  * lpfc_sli_sriov_nr_virtfn_get - Get the number of sr-iov virtual functions
4060  * @phba: pointer to lpfc hba data structure.
4061  *
4062  * This function enables the PCI SR-IOV virtual functions to a physical
4063  * function. It invokes the PCI SR-IOV api with the @nr_vfn provided to
4064  * enable the number of virtual functions to the physical function. As
4065  * not all devices support SR-IOV, the return code from the pci_enable_sriov()
4066  * API call does not considered as an error condition for most of the device.
4067  **/
4068 uint16_t
4069 lpfc_sli_sriov_nr_virtfn_get(struct lpfc_hba *phba)
4070 {
4071         struct pci_dev *pdev = phba->pcidev;
4072         uint16_t nr_virtfn;
4073         int pos;
4074
4075         pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_SRIOV);
4076         if (pos == 0)
4077                 return 0;
4078
4079         pci_read_config_word(pdev, pos + PCI_SRIOV_TOTAL_VF, &nr_virtfn);
4080         return nr_virtfn;
4081 }
4082
4083 /**
4084  * lpfc_sli_probe_sriov_nr_virtfn - Enable a number of sr-iov virtual functions
4085  * @phba: pointer to lpfc hba data structure.
4086  * @nr_vfn: number of virtual functions to be enabled.
4087  *
4088  * This function enables the PCI SR-IOV virtual functions to a physical
4089  * function. It invokes the PCI SR-IOV api with the @nr_vfn provided to
4090  * enable the number of virtual functions to the physical function. As
4091  * not all devices support SR-IOV, the return code from the pci_enable_sriov()
4092  * API call does not considered as an error condition for most of the device.
4093  **/
4094 int
4095 lpfc_sli_probe_sriov_nr_virtfn(struct lpfc_hba *phba, int nr_vfn)
4096 {
4097         struct pci_dev *pdev = phba->pcidev;
4098         uint16_t max_nr_vfn;
4099         int rc;
4100
4101         max_nr_vfn = lpfc_sli_sriov_nr_virtfn_get(phba);
4102         if (nr_vfn > max_nr_vfn) {
4103                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4104                                 "3057 Requested vfs (%d) greater than "
4105                                 "supported vfs (%d)", nr_vfn, max_nr_vfn);
4106                 return -EINVAL;
4107         }
4108
4109         rc = pci_enable_sriov(pdev, nr_vfn);
4110         if (rc) {
4111                 lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
4112                                 "2806 Failed to enable sriov on this device "
4113                                 "with vfn number nr_vf:%d, rc:%d\n",
4114                                 nr_vfn, rc);
4115         } else
4116                 lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
4117                                 "2807 Successful enable sriov on this device "
4118                                 "with vfn number nr_vf:%d\n", nr_vfn);
4119         return rc;
4120 }
4121
4122 /**
4123  * lpfc_sli_driver_resource_setup - Setup driver internal resources for SLI3 dev.
4124  * @phba: pointer to lpfc hba data structure.
4125  *
4126  * This routine is invoked to set up the driver internal resources specific to
4127  * support the SLI-3 HBA device it attached to.
4128  *
4129  * Return codes
4130  *      0 - successful
4131  *      other values - error
4132  **/
4133 static int
4134 lpfc_sli_driver_resource_setup(struct lpfc_hba *phba)
4135 {
4136         struct lpfc_sli *psli;
4137         int rc;
4138
4139         /*
4140          * Initialize timers used by driver
4141          */
4142
4143         /* Heartbeat timer */
4144         init_timer(&phba->hb_tmofunc);
4145         phba->hb_tmofunc.function = lpfc_hb_timeout;
4146         phba->hb_tmofunc.data = (unsigned long)phba;
4147
4148         psli = &phba->sli;
4149         /* MBOX heartbeat timer */
4150         init_timer(&psli->mbox_tmo);
4151         psli->mbox_tmo.function = lpfc_mbox_timeout;
4152         psli->mbox_tmo.data = (unsigned long) phba;
4153         /* FCP polling mode timer */
4154         init_timer(&phba->fcp_poll_timer);
4155         phba->fcp_poll_timer.function = lpfc_poll_timeout;
4156         phba->fcp_poll_timer.data = (unsigned long) phba;
4157         /* Fabric block timer */
4158         init_timer(&phba->fabric_block_timer);
4159         phba->fabric_block_timer.function = lpfc_fabric_block_timeout;
4160         phba->fabric_block_timer.data = (unsigned long) phba;
4161         /* EA polling mode timer */
4162         init_timer(&phba->eratt_poll);
4163         phba->eratt_poll.function = lpfc_poll_eratt;
4164         phba->eratt_poll.data = (unsigned long) phba;
4165
4166         /* Host attention work mask setup */
4167         phba->work_ha_mask = (HA_ERATT | HA_MBATT | HA_LATT);
4168         phba->work_ha_mask |= (HA_RXMASK << (LPFC_ELS_RING * 4));
4169
4170         /* Get all the module params for configuring this host */
4171         lpfc_get_cfgparam(phba);
4172         if (phba->pcidev->device == PCI_DEVICE_ID_HORNET) {
4173                 phba->menlo_flag |= HBA_MENLO_SUPPORT;
4174                 /* check for menlo minimum sg count */
4175                 if (phba->cfg_sg_seg_cnt < LPFC_DEFAULT_MENLO_SG_SEG_CNT)
4176                         phba->cfg_sg_seg_cnt = LPFC_DEFAULT_MENLO_SG_SEG_CNT;
4177         }
4178
4179         /*
4180          * Since the sg_tablesize is module parameter, the sg_dma_buf_size
4181          * used to create the sg_dma_buf_pool must be dynamically calculated.
4182          * 2 segments are added since the IOCB needs a command and response bde.
4183          */
4184         phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd) +
4185                 sizeof(struct fcp_rsp) +
4186                         ((phba->cfg_sg_seg_cnt + 2) * sizeof(struct ulp_bde64));
4187
4188         if (phba->cfg_enable_bg) {
4189                 phba->cfg_sg_seg_cnt = LPFC_MAX_SG_SEG_CNT;
4190                 phba->cfg_sg_dma_buf_size +=
4191                         phba->cfg_prot_sg_seg_cnt * sizeof(struct ulp_bde64);
4192         }
4193
4194         /* Also reinitialize the host templates with new values. */
4195         lpfc_vport_template.sg_tablesize = phba->cfg_sg_seg_cnt;
4196         lpfc_template.sg_tablesize = phba->cfg_sg_seg_cnt;
4197
4198         phba->max_vpi = LPFC_MAX_VPI;
4199         /* This will be set to correct value after config_port mbox */
4200         phba->max_vports = 0;
4201
4202         /*
4203          * Initialize the SLI Layer to run with lpfc HBAs.
4204          */
4205         lpfc_sli_setup(phba);
4206         lpfc_sli_queue_setup(phba);
4207
4208         /* Allocate device driver memory */
4209         if (lpfc_mem_alloc(phba, BPL_ALIGN_SZ))
4210                 return -ENOMEM;
4211
4212         /*
4213          * Enable sr-iov virtual functions if supported and configured
4214          * through the module parameter.
4215          */
4216         if (phba->cfg_sriov_nr_virtfn > 0) {
4217                 rc = lpfc_sli_probe_sriov_nr_virtfn(phba,
4218                                                  phba->cfg_sriov_nr_virtfn);
4219                 if (rc) {
4220                         lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
4221                                         "2808 Requested number of SR-IOV "
4222                                         "virtual functions (%d) is not "
4223                                         "supported\n",
4224                                         phba->cfg_sriov_nr_virtfn);
4225                         phba->cfg_sriov_nr_virtfn = 0;
4226                 }
4227         }
4228
4229         return 0;
4230 }
4231
4232 /**
4233  * lpfc_sli_driver_resource_unset - Unset drvr internal resources for SLI3 dev
4234  * @phba: pointer to lpfc hba data structure.
4235  *
4236  * This routine is invoked to unset the driver internal resources set up
4237  * specific for supporting the SLI-3 HBA device it attached to.
4238  **/
4239 static void
4240 lpfc_sli_driver_resource_unset(struct lpfc_hba *phba)
4241 {
4242         /* Free device driver memory allocated */
4243         lpfc_mem_free_all(phba);
4244
4245         return;
4246 }
4247
4248 /**
4249  * lpfc_sli4_driver_resource_setup - Setup drvr internal resources for SLI4 dev
4250  * @phba: pointer to lpfc hba data structure.
4251  *
4252  * This routine is invoked to set up the driver internal resources specific to
4253  * support the SLI-4 HBA device it attached to.
4254  *
4255  * Return codes
4256  *      0 - successful
4257  *      other values - error
4258  **/
4259 static int
4260 lpfc_sli4_driver_resource_setup(struct lpfc_hba *phba)
4261 {
4262         struct lpfc_sli *psli;
4263         LPFC_MBOXQ_t *mboxq;
4264         int rc, i, hbq_count, buf_size, dma_buf_size, max_buf_size;
4265         uint8_t pn_page[LPFC_MAX_SUPPORTED_PAGES] = {0};
4266         struct lpfc_mqe *mqe;
4267         int longs, sli_family;
4268
4269         /* Before proceed, wait for POST done and device ready */
4270         rc = lpfc_sli4_post_status_check(phba);
4271         if (rc)
4272                 return -ENODEV;
4273
4274         /*
4275          * Initialize timers used by driver
4276          */
4277
4278         /* Heartbeat timer */
4279         init_timer(&phba->hb_tmofunc);
4280         phba->hb_tmofunc.function = lpfc_hb_timeout;
4281         phba->hb_tmofunc.data = (unsigned long)phba;
4282         init_timer(&phba->rrq_tmr);
4283         phba->rrq_tmr.function = lpfc_rrq_timeout;
4284         phba->rrq_tmr.data = (unsigned long)phba;
4285
4286         psli = &phba->sli;
4287         /* MBOX heartbeat timer */
4288         init_timer(&psli->mbox_tmo);
4289         psli->mbox_tmo.function = lpfc_mbox_timeout;
4290         psli->mbox_tmo.data = (unsigned long) phba;
4291         /* Fabric block timer */
4292         init_timer(&phba->fabric_block_timer);
4293         phba->fabric_block_timer.function = lpfc_fabric_block_timeout;
4294         phba->fabric_block_timer.data = (unsigned long) phba;
4295         /* EA polling mode timer */
4296         init_timer(&phba->eratt_poll);
4297         phba->eratt_poll.function = lpfc_poll_eratt;
4298         phba->eratt_poll.data = (unsigned long) phba;
4299         /* FCF rediscover timer */
4300         init_timer(&phba->fcf.redisc_wait);
4301         phba->fcf.redisc_wait.function = lpfc_sli4_fcf_redisc_wait_tmo;
4302         phba->fcf.redisc_wait.data = (unsigned long)phba;
4303
4304         /*
4305          * Control structure for handling external multi-buffer mailbox
4306          * command pass-through.
4307          */
4308         memset((uint8_t *)&phba->mbox_ext_buf_ctx, 0,
4309                 sizeof(struct lpfc_mbox_ext_buf_ctx));
4310         INIT_LIST_HEAD(&phba->mbox_ext_buf_ctx.ext_dmabuf_list);
4311
4312         /*
4313          * We need to do a READ_CONFIG mailbox command here before
4314          * calling lpfc_get_cfgparam. For VFs this will report the
4315          * MAX_XRI, MAX_VPI, MAX_RPI, MAX_IOCB, and MAX_VFI settings.
4316          * All of the resources allocated
4317          * for this Port are tied to these values.
4318          */
4319         /* Get all the module params for configuring this host */
4320         lpfc_get_cfgparam(phba);
4321         phba->max_vpi = LPFC_MAX_VPI;
4322         /* This will be set to correct value after the read_config mbox */
4323         phba->max_vports = 0;
4324
4325         /* Program the default value of vlan_id and fc_map */
4326         phba->valid_vlan = 0;
4327         phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
4328         phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
4329         phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
4330
4331         /*
4332          * Since the sg_tablesize is module parameter, the sg_dma_buf_size
4333          * used to create the sg_dma_buf_pool must be dynamically calculated.
4334          * 2 segments are added since the IOCB needs a command and response bde.
4335          * To insure that the scsi sgl does not cross a 4k page boundary only
4336          * sgl sizes of must be a power of 2.
4337          */
4338         buf_size = (sizeof(struct fcp_cmnd) + sizeof(struct fcp_rsp) +
4339                     ((phba->cfg_sg_seg_cnt + 2) * sizeof(struct sli4_sge)));
4340
4341         sli_family = bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf);
4342         max_buf_size = LPFC_SLI4_MAX_BUF_SIZE;
4343         switch (sli_family) {
4344         case LPFC_SLI_INTF_FAMILY_BE2:
4345         case LPFC_SLI_INTF_FAMILY_BE3:
4346                 /* There is a single hint for BE - 2 pages per BPL. */
4347                 if (bf_get(lpfc_sli_intf_sli_hint1, &phba->sli4_hba.sli_intf) ==
4348                     LPFC_SLI_INTF_SLI_HINT1_1)
4349                         max_buf_size = LPFC_SLI4_FL1_MAX_BUF_SIZE;
4350                 break;
4351         case LPFC_SLI_INTF_FAMILY_LNCR_A0:
4352         case LPFC_SLI_INTF_FAMILY_LNCR_B0:
4353         default:
4354                 break;
4355         }
4356         for (dma_buf_size = LPFC_SLI4_MIN_BUF_SIZE;
4357              dma_buf_size < max_buf_size && buf_size > dma_buf_size;
4358              dma_buf_size = dma_buf_size << 1)
4359                 ;
4360         if (dma_buf_size == max_buf_size)
4361                 phba->cfg_sg_seg_cnt = (dma_buf_size -
4362                         sizeof(struct fcp_cmnd) - sizeof(struct fcp_rsp) -
4363                         (2 * sizeof(struct sli4_sge))) /
4364                                 sizeof(struct sli4_sge);
4365         phba->cfg_sg_dma_buf_size = dma_buf_size;
4366
4367         /* Initialize buffer queue management fields */
4368         hbq_count = lpfc_sli_hbq_count();
4369         for (i = 0; i < hbq_count; ++i)
4370                 INIT_LIST_HEAD(&phba->hbqs[i].hbq_buffer_list);
4371         INIT_LIST_HEAD(&phba->rb_pend_list);
4372         phba->hbqs[LPFC_ELS_HBQ].hbq_alloc_buffer = lpfc_sli4_rb_alloc;
4373         phba->hbqs[LPFC_ELS_HBQ].hbq_free_buffer = lpfc_sli4_rb_free;
4374
4375         /*
4376          * Initialize the SLI Layer to run with lpfc SLI4 HBAs.
4377          */
4378         /* Initialize the Abort scsi buffer list used by driver */
4379         spin_lock_init(&phba->sli4_hba.abts_scsi_buf_list_lock);
4380         INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_scsi_buf_list);
4381         /* This abort list used by worker thread */
4382         spin_lock_init(&phba->sli4_hba.abts_sgl_list_lock);
4383
4384         /*
4385          * Initialize driver internal slow-path work queues
4386          */
4387
4388         /* Driver internel slow-path CQ Event pool */
4389         INIT_LIST_HEAD(&phba->sli4_hba.sp_cqe_event_pool);
4390         /* Response IOCB work queue list */
4391         INIT_LIST_HEAD(&phba->sli4_hba.sp_queue_event);
4392         /* Asynchronous event CQ Event work queue list */
4393         INIT_LIST_HEAD(&phba->sli4_hba.sp_asynce_work_queue);
4394         /* Fast-path XRI aborted CQ Event work queue list */
4395         INIT_LIST_HEAD(&phba->sli4_hba.sp_fcp_xri_aborted_work_queue);
4396         /* Slow-path XRI aborted CQ Event work queue list */
4397         INIT_LIST_HEAD(&phba->sli4_hba.sp_els_xri_aborted_work_queue);
4398         /* Receive queue CQ Event work queue list */
4399         INIT_LIST_HEAD(&phba->sli4_hba.sp_unsol_work_queue);
4400
4401         /* Initialize extent block lists. */
4402         INIT_LIST_HEAD(&phba->sli4_hba.lpfc_rpi_blk_list);
4403         INIT_LIST_HEAD(&phba->sli4_hba.lpfc_xri_blk_list);
4404         INIT_LIST_HEAD(&phba->sli4_hba.lpfc_vfi_blk_list);
4405         INIT_LIST_HEAD(&phba->lpfc_vpi_blk_list);
4406
4407         /* Initialize the driver internal SLI layer lists. */
4408         lpfc_sli_setup(phba);
4409         lpfc_sli_queue_setup(phba);
4410
4411         /* Allocate device driver memory */
4412         rc = lpfc_mem_alloc(phba, SGL_ALIGN_SZ);
4413         if (rc)
4414                 return -ENOMEM;
4415
4416         /* IF Type 2 ports get initialized now. */
4417         if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
4418             LPFC_SLI_INTF_IF_TYPE_2) {
4419                 rc = lpfc_pci_function_reset(phba);
4420                 if (unlikely(rc))
4421                         return -ENODEV;
4422         }
4423
4424         /* Create the bootstrap mailbox command */
4425         rc = lpfc_create_bootstrap_mbox(phba);
4426         if (unlikely(rc))
4427                 goto out_free_mem;
4428
4429         /* Set up the host's endian order with the device. */
4430         rc = lpfc_setup_endian_order(phba);
4431         if (unlikely(rc))
4432                 goto out_free_bsmbx;
4433
4434         /* Set up the hba's configuration parameters. */
4435         rc = lpfc_sli4_read_config(phba);
4436         if (unlikely(rc))
4437                 goto out_free_bsmbx;
4438
4439         /* IF Type 0 ports get initialized now. */
4440         if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
4441             LPFC_SLI_INTF_IF_TYPE_0) {
4442                 rc = lpfc_pci_function_reset(phba);
4443                 if (unlikely(rc))
4444                         goto out_free_bsmbx;
4445         }
4446
4447         mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
4448                                                        GFP_KERNEL);
4449         if (!mboxq) {
4450                 rc = -ENOMEM;
4451                 goto out_free_bsmbx;
4452         }
4453
4454         /* Get the Supported Pages if PORT_CAPABILITIES is supported by port. */
4455         lpfc_supported_pages(mboxq);
4456         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
4457         if (!rc) {
4458                 mqe = &mboxq->u.mqe;
4459                 memcpy(&pn_page[0], ((uint8_t *)&mqe->un.supp_pages.word3),
4460                        LPFC_MAX_SUPPORTED_PAGES);
4461                 for (i = 0; i < LPFC_MAX_SUPPORTED_PAGES; i++) {
4462                         switch (pn_page[i]) {
4463                         case LPFC_SLI4_PARAMETERS:
4464                                 phba->sli4_hba.pc_sli4_params.supported = 1;
4465                                 break;
4466                         default:
4467                                 break;
4468                         }
4469                 }
4470                 /* Read the port's SLI4 Parameters capabilities if supported. */
4471                 if (phba->sli4_hba.pc_sli4_params.supported)
4472                         rc = lpfc_pc_sli4_params_get(phba, mboxq);
4473                 if (rc) {
4474                         mempool_free(mboxq, phba->mbox_mem_pool);
4475                         rc = -EIO;
4476                         goto out_free_bsmbx;
4477                 }
4478         }
4479         /*
4480          * Get sli4 parameters that override parameters from Port capabilities.
4481          * If this call fails, it isn't critical unless the SLI4 parameters come
4482          * back in conflict.
4483          */
4484         rc = lpfc_get_sli4_parameters(phba, mboxq);
4485         if (rc) {
4486                 if (phba->sli4_hba.extents_in_use &&
4487                     phba->sli4_hba.rpi_hdrs_in_use) {
4488                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4489                                 "2999 Unsupported SLI4 Parameters "
4490                                 "Extents and RPI headers enabled.\n");
4491                         goto out_free_bsmbx;
4492                 }
4493         }
4494         mempool_free(mboxq, phba->mbox_mem_pool);
4495         /* Verify all the SLI4 queues */
4496         rc = lpfc_sli4_queue_verify(phba);
4497         if (rc)
4498                 goto out_free_bsmbx;
4499
4500         /* Create driver internal CQE event pool */
4501         rc = lpfc_sli4_cq_event_pool_create(phba);
4502         if (rc)
4503                 goto out_free_bsmbx;
4504
4505         /* Initialize and populate the iocb list per host */
4506         rc = lpfc_init_sgl_list(phba);
4507         if (rc) {
4508                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4509                                 "1400 Failed to initialize sgl list.\n");
4510                 goto out_destroy_cq_event_pool;
4511         }
4512         rc = lpfc_init_active_sgl_array(phba);
4513         if (rc) {
4514                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4515                                 "1430 Failed to initialize sgl list.\n");
4516                 goto out_free_sgl_list;
4517         }
4518         rc = lpfc_sli4_init_rpi_hdrs(phba);
4519         if (rc) {
4520                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4521                                 "1432 Failed to initialize rpi headers.\n");
4522                 goto out_free_active_sgl;
4523         }
4524
4525         /* Allocate eligible FCF bmask memory for FCF roundrobin failover */
4526         longs = (LPFC_SLI4_FCF_TBL_INDX_MAX + BITS_PER_LONG - 1)/BITS_PER_LONG;
4527         phba->fcf.fcf_rr_bmask = kzalloc(longs * sizeof(unsigned long),
4528                                          GFP_KERNEL);
4529         if (!phba->fcf.fcf_rr_bmask) {
4530                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4531                                 "2759 Failed allocate memory for FCF round "
4532                                 "robin failover bmask\n");
4533                 rc = -ENOMEM;
4534                 goto out_remove_rpi_hdrs;
4535         }
4536
4537         /*
4538          * The cfg_fcp_eq_count can be zero whenever there is exactly one
4539          * interrupt vector.  This is not an error
4540          */
4541         if (phba->cfg_fcp_eq_count) {
4542                 phba->sli4_hba.fcp_eq_hdl =
4543                                 kzalloc((sizeof(struct lpfc_fcp_eq_hdl) *
4544                                     phba->cfg_fcp_eq_count), GFP_KERNEL);
4545                 if (!phba->sli4_hba.fcp_eq_hdl) {
4546                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4547                                         "2572 Failed allocate memory for "
4548                                         "fast-path per-EQ handle array\n");
4549                         rc = -ENOMEM;
4550                         goto out_free_fcf_rr_bmask;
4551                 }
4552         }
4553
4554         phba->sli4_hba.msix_entries = kzalloc((sizeof(struct msix_entry) *
4555                                       phba->sli4_hba.cfg_eqn), GFP_KERNEL);
4556         if (!phba->sli4_hba.msix_entries) {
4557                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4558                                 "2573 Failed allocate memory for msi-x "
4559                                 "interrupt vector entries\n");
4560                 rc = -ENOMEM;
4561                 goto out_free_fcp_eq_hdl;
4562         }
4563
4564         /*
4565          * Enable sr-iov virtual functions if supported and configured
4566          * through the module parameter.
4567          */
4568         if (phba->cfg_sriov_nr_virtfn > 0) {
4569                 rc = lpfc_sli_probe_sriov_nr_virtfn(phba,
4570                                                  phba->cfg_sriov_nr_virtfn);
4571                 if (rc) {
4572                         lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
4573                                         "3020 Requested number of SR-IOV "
4574                                         "virtual functions (%d) is not "
4575                                         "supported\n",
4576                                         phba->cfg_sriov_nr_virtfn);
4577                         phba->cfg_sriov_nr_virtfn = 0;
4578                 }
4579         }
4580
4581         return 0;
4582
4583 out_free_fcp_eq_hdl:
4584         kfree(phba->sli4_hba.fcp_eq_hdl);
4585 out_free_fcf_rr_bmask:
4586         kfree(phba->fcf.fcf_rr_bmask);
4587 out_remove_rpi_hdrs:
4588         lpfc_sli4_remove_rpi_hdrs(phba);
4589 out_free_active_sgl:
4590         lpfc_free_active_sgl(phba);
4591 out_free_sgl_list:
4592         lpfc_free_sgl_list(phba);
4593 out_destroy_cq_event_pool:
4594         lpfc_sli4_cq_event_pool_destroy(phba);
4595 out_free_bsmbx:
4596         lpfc_destroy_bootstrap_mbox(phba);
4597 out_free_mem:
4598         lpfc_mem_free(phba);
4599         return rc;
4600 }
4601
4602 /**
4603  * lpfc_sli4_driver_resource_unset - Unset drvr internal resources for SLI4 dev
4604  * @phba: pointer to lpfc hba data structure.
4605  *
4606  * This routine is invoked to unset the driver internal resources set up
4607  * specific for supporting the SLI-4 HBA device it attached to.
4608  **/
4609 static void
4610 lpfc_sli4_driver_resource_unset(struct lpfc_hba *phba)
4611 {
4612         struct lpfc_fcf_conn_entry *conn_entry, *next_conn_entry;
4613
4614         /* Free memory allocated for msi-x interrupt vector entries */
4615         kfree(phba->sli4_hba.msix_entries);
4616
4617         /* Free memory allocated for fast-path work queue handles */
4618         kfree(phba->sli4_hba.fcp_eq_hdl);
4619
4620         /* Free the allocated rpi headers. */
4621         lpfc_sli4_remove_rpi_hdrs(phba);
4622         lpfc_sli4_remove_rpis(phba);
4623
4624         /* Free eligible FCF index bmask */
4625         kfree(phba->fcf.fcf_rr_bmask);
4626
4627         /* Free the ELS sgl list */
4628         lpfc_free_active_sgl(phba);
4629         lpfc_free_sgl_list(phba);
4630
4631         /* Free the SCSI sgl management array */
4632         kfree(phba->sli4_hba.lpfc_scsi_psb_array);
4633
4634         /* Free the completion queue EQ event pool */
4635         lpfc_sli4_cq_event_release_all(phba);
4636         lpfc_sli4_cq_event_pool_destroy(phba);
4637
4638         /* Release resource identifiers. */
4639         lpfc_sli4_dealloc_resource_identifiers(phba);
4640
4641         /* Free the bsmbx region. */
4642         lpfc_destroy_bootstrap_mbox(phba);
4643
4644         /* Free the SLI Layer memory with SLI4 HBAs */
4645         lpfc_mem_free_all(phba);
4646
4647         /* Free the current connect table */
4648         list_for_each_entry_safe(conn_entry, next_conn_entry,
4649                 &phba->fcf_conn_rec_list, list) {
4650                 list_del_init(&conn_entry->list);
4651                 kfree(conn_entry);
4652         }
4653
4654         return;
4655 }
4656
4657 /**
4658  * lpfc_init_api_table_setup - Set up init api function jump table
4659  * @phba: The hba struct for which this call is being executed.
4660  * @dev_grp: The HBA PCI-Device group number.
4661  *
4662  * This routine sets up the device INIT interface API function jump table
4663  * in @phba struct.
4664  *
4665  * Returns: 0 - success, -ENODEV - failure.
4666  **/
4667 int
4668 lpfc_init_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
4669 {
4670         phba->lpfc_hba_init_link = lpfc_hba_init_link;
4671         phba->lpfc_hba_down_link = lpfc_hba_down_link;
4672         phba->lpfc_selective_reset = lpfc_selective_reset;
4673         switch (dev_grp) {
4674         case LPFC_PCI_DEV_LP:
4675                 phba->lpfc_hba_down_post = lpfc_hba_down_post_s3;
4676                 phba->lpfc_handle_eratt = lpfc_handle_eratt_s3;
4677                 phba->lpfc_stop_port = lpfc_stop_port_s3;
4678                 break;
4679         case LPFC_PCI_DEV_OC:
4680                 phba->lpfc_hba_down_post = lpfc_hba_down_post_s4;
4681                 phba->lpfc_handle_eratt = lpfc_handle_eratt_s4;
4682                 phba->lpfc_stop_port = lpfc_stop_port_s4;
4683                 break;
4684         default:
4685                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4686                                 "1431 Invalid HBA PCI-device group: 0x%x\n",
4687                                 dev_grp);
4688                 return -ENODEV;
4689                 break;
4690         }
4691         return 0;
4692 }
4693
4694 /**
4695  * lpfc_setup_driver_resource_phase1 - Phase1 etup driver internal resources.
4696  * @phba: pointer to lpfc hba data structure.
4697  *
4698  * This routine is invoked to set up the driver internal resources before the
4699  * device specific resource setup to support the HBA device it attached to.
4700  *
4701  * Return codes
4702  *      0 - successful
4703  *      other values - error
4704  **/
4705 static int
4706 lpfc_setup_driver_resource_phase1(struct lpfc_hba *phba)
4707 {
4708         /*
4709          * Driver resources common to all SLI revisions
4710          */
4711         atomic_set(&phba->fast_event_count, 0);
4712         spin_lock_init(&phba->hbalock);
4713
4714         /* Initialize ndlp management spinlock */
4715         spin_lock_init(&phba->ndlp_lock);
4716
4717         INIT_LIST_HEAD(&phba->port_list);
4718         INIT_LIST_HEAD(&phba->work_list);
4719         init_waitqueue_head(&phba->wait_4_mlo_m_q);
4720
4721         /* Initialize the wait queue head for the kernel thread */
4722         init_waitqueue_head(&phba->work_waitq);
4723
4724         /* Initialize the scsi buffer list used by driver for scsi IO */
4725         spin_lock_init(&phba->scsi_buf_list_lock);
4726         INIT_LIST_HEAD(&phba->lpfc_scsi_buf_list);
4727
4728         /* Initialize the fabric iocb list */
4729         INIT_LIST_HEAD(&phba->fabric_iocb_list);
4730
4731         /* Initialize list to save ELS buffers */
4732         INIT_LIST_HEAD(&phba->elsbuf);
4733
4734         /* Initialize FCF connection rec list */
4735         INIT_LIST_HEAD(&phba->fcf_conn_rec_list);
4736
4737         return 0;
4738 }
4739
4740 /**
4741  * lpfc_setup_driver_resource_phase2 - Phase2 setup driver internal resources.
4742  * @phba: pointer to lpfc hba data structure.
4743  *
4744  * This routine is invoked to set up the driver internal resources after the
4745  * device specific resource setup to support the HBA device it attached to.
4746  *
4747  * Return codes
4748  *      0 - successful
4749  *      other values - error
4750  **/
4751 static int
4752 lpfc_setup_driver_resource_phase2(struct lpfc_hba *phba)
4753 {
4754         int error;
4755
4756         /* Startup the kernel thread for this host adapter. */
4757         phba->worker_thread = kthread_run(lpfc_do_work, phba,
4758                                           "lpfc_worker_%d", phba->brd_no);
4759         if (IS_ERR(phba->worker_thread)) {
4760                 error = PTR_ERR(phba->worker_thread);
4761                 return error;
4762         }
4763
4764         return 0;
4765 }
4766
4767 /**
4768  * lpfc_unset_driver_resource_phase2 - Phase2 unset driver internal resources.
4769  * @phba: pointer to lpfc hba data structure.
4770  *
4771  * This routine is invoked to unset the driver internal resources set up after
4772  * the device specific resource setup for supporting the HBA device it
4773  * attached to.
4774  **/
4775 static void
4776 lpfc_unset_driver_resource_phase2(struct lpfc_hba *phba)
4777 {
4778         /* Stop kernel worker thread */
4779         kthread_stop(phba->worker_thread);
4780 }
4781
4782 /**
4783  * lpfc_free_iocb_list - Free iocb list.
4784  * @phba: pointer to lpfc hba data structure.
4785  *
4786  * This routine is invoked to free the driver's IOCB list and memory.
4787  **/
4788 static void
4789 lpfc_free_iocb_list(struct lpfc_hba *phba)
4790 {
4791         struct lpfc_iocbq *iocbq_entry = NULL, *iocbq_next = NULL;
4792
4793         spin_lock_irq(&phba->hbalock);
4794         list_for_each_entry_safe(iocbq_entry, iocbq_next,
4795                                  &phba->lpfc_iocb_list, list) {
4796                 list_del(&iocbq_entry->list);
4797                 kfree(iocbq_entry);
4798                 phba->total_iocbq_bufs--;
4799         }
4800         spin_unlock_irq(&phba->hbalock);
4801
4802         return;
4803 }
4804
4805 /**
4806  * lpfc_init_iocb_list - Allocate and initialize iocb list.
4807  * @phba: pointer to lpfc hba data structure.
4808  *
4809  * This routine is invoked to allocate and initizlize the driver's IOCB
4810  * list and set up the IOCB tag array accordingly.
4811  *
4812  * Return codes
4813  *      0 - successful
4814  *      other values - error
4815  **/
4816 static int
4817 lpfc_init_iocb_list(struct lpfc_hba *phba, int iocb_count)
4818 {
4819         struct lpfc_iocbq *iocbq_entry = NULL;
4820         uint16_t iotag;
4821         int i;
4822
4823         /* Initialize and populate the iocb list per host.  */
4824         INIT_LIST_HEAD(&phba->lpfc_iocb_list);
4825         for (i = 0; i < iocb_count; i++) {
4826                 iocbq_entry = kzalloc(sizeof(struct lpfc_iocbq), GFP_KERNEL);
4827                 if (iocbq_entry == NULL) {
4828                         printk(KERN_ERR "%s: only allocated %d iocbs of "
4829                                 "expected %d count. Unloading driver.\n",
4830                                 __func__, i, LPFC_IOCB_LIST_CNT);
4831                         goto out_free_iocbq;
4832                 }
4833
4834                 iotag = lpfc_sli_next_iotag(phba, iocbq_entry);
4835                 if (iotag == 0) {
4836                         kfree(iocbq_entry);
4837                         printk(KERN_ERR "%s: failed to allocate IOTAG. "
4838                                 "Unloading driver.\n", __func__);
4839                         goto out_free_iocbq;
4840                 }
4841                 iocbq_entry->sli4_lxritag = NO_XRI;
4842                 iocbq_entry->sli4_xritag = NO_XRI;
4843
4844                 spin_lock_irq(&phba->hbalock);
4845                 list_add(&iocbq_entry->list, &phba->lpfc_iocb_list);
4846                 phba->total_iocbq_bufs++;
4847                 spin_unlock_irq(&phba->hbalock);
4848         }
4849
4850         return 0;
4851
4852 out_free_iocbq:
4853         lpfc_free_iocb_list(phba);
4854
4855         return -ENOMEM;
4856 }
4857
4858 /**
4859  * lpfc_free_sgl_list - Free sgl list.
4860  * @phba: pointer to lpfc hba data structure.
4861  *
4862  * This routine is invoked to free the driver's sgl list and memory.
4863  **/
4864 static void
4865 lpfc_free_sgl_list(struct lpfc_hba *phba)
4866 {
4867         struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
4868         LIST_HEAD(sglq_list);
4869
4870         spin_lock_irq(&phba->hbalock);
4871         list_splice_init(&phba->sli4_hba.lpfc_sgl_list, &sglq_list);
4872         spin_unlock_irq(&phba->hbalock);
4873
4874         list_for_each_entry_safe(sglq_entry, sglq_next,
4875                                  &sglq_list, list) {
4876                 list_del(&sglq_entry->list);
4877                 lpfc_mbuf_free(phba, sglq_entry->virt, sglq_entry->phys);
4878                 kfree(sglq_entry);
4879                 phba->sli4_hba.total_sglq_bufs--;
4880         }
4881         kfree(phba->sli4_hba.lpfc_els_sgl_array);
4882 }
4883
4884 /**
4885  * lpfc_init_active_sgl_array - Allocate the buf to track active ELS XRIs.
4886  * @phba: pointer to lpfc hba data structure.
4887  *
4888  * This routine is invoked to allocate the driver's active sgl memory.
4889  * This array will hold the sglq_entry's for active IOs.
4890  **/
4891 static int
4892 lpfc_init_active_sgl_array(struct lpfc_hba *phba)
4893 {
4894         int size;
4895         size = sizeof(struct lpfc_sglq *);
4896         size *= phba->sli4_hba.max_cfg_param.max_xri;
4897
4898         phba->sli4_hba.lpfc_sglq_active_list =
4899                 kzalloc(size, GFP_KERNEL);
4900         if (!phba->sli4_hba.lpfc_sglq_active_list)
4901                 return -ENOMEM;
4902         return 0;
4903 }
4904
4905 /**
4906  * lpfc_free_active_sgl - Free the buf that tracks active ELS XRIs.
4907  * @phba: pointer to lpfc hba data structure.
4908  *
4909  * This routine is invoked to walk through the array of active sglq entries
4910  * and free all of the resources.
4911  * This is just a place holder for now.
4912  **/
4913 static void
4914 lpfc_free_active_sgl(struct lpfc_hba *phba)
4915 {
4916         kfree(phba->sli4_hba.lpfc_sglq_active_list);
4917 }
4918
4919 /**
4920  * lpfc_init_sgl_list - Allocate and initialize sgl list.
4921  * @phba: pointer to lpfc hba data structure.
4922  *
4923  * This routine is invoked to allocate and initizlize the driver's sgl
4924  * list and set up the sgl xritag tag array accordingly.
4925  *
4926  * Return codes
4927  *      0 - successful
4928  *      other values - error
4929  **/
4930 static int
4931 lpfc_init_sgl_list(struct lpfc_hba *phba)
4932 {
4933         struct lpfc_sglq *sglq_entry = NULL;
4934         int i;
4935         int els_xri_cnt;
4936
4937         els_xri_cnt = lpfc_sli4_get_els_iocb_cnt(phba);
4938         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4939                                 "2400 ELS XRI count %d.\n",
4940                                 els_xri_cnt);
4941         /* Initialize and populate the sglq list per host/VF. */
4942         INIT_LIST_HEAD(&phba->sli4_hba.lpfc_sgl_list);
4943         INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_els_sgl_list);
4944
4945         /* Sanity check on XRI management */
4946         if (phba->sli4_hba.max_cfg_param.max_xri <= els_xri_cnt) {
4947                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
4948                                 "2562 No room left for SCSI XRI allocation: "
4949                                 "max_xri=%d, els_xri=%d\n",
4950                                 phba->sli4_hba.max_cfg_param.max_xri,
4951                                 els_xri_cnt);
4952                 return -ENOMEM;
4953         }
4954
4955         /* Allocate memory for the ELS XRI management array */
4956         phba->sli4_hba.lpfc_els_sgl_array =
4957                         kzalloc((sizeof(struct lpfc_sglq *) * els_xri_cnt),
4958                         GFP_KERNEL);
4959
4960         if (!phba->sli4_hba.lpfc_els_sgl_array) {
4961                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
4962                                 "2401 Failed to allocate memory for ELS "
4963                                 "XRI management array of size %d.\n",
4964                                 els_xri_cnt);
4965                 return -ENOMEM;
4966         }
4967
4968         /* Keep the SCSI XRI into the XRI management array */
4969         phba->sli4_hba.scsi_xri_max =
4970                         phba->sli4_hba.max_cfg_param.max_xri - els_xri_cnt;
4971         phba->sli4_hba.scsi_xri_cnt = 0;
4972         phba->sli4_hba.lpfc_scsi_psb_array =
4973                         kzalloc((sizeof(struct lpfc_scsi_buf *) *
4974                         phba->sli4_hba.scsi_xri_max), GFP_KERNEL);
4975
4976         if (!phba->sli4_hba.lpfc_scsi_psb_array) {
4977                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
4978                                 "2563 Failed to allocate memory for SCSI "
4979                                 "XRI management array of size %d.\n",
4980                                 phba->sli4_hba.scsi_xri_max);
4981                 kfree(phba->sli4_hba.lpfc_els_sgl_array);
4982                 return -ENOMEM;
4983         }
4984
4985         for (i = 0; i < els_xri_cnt; i++) {
4986                 sglq_entry = kzalloc(sizeof(struct lpfc_sglq), GFP_KERNEL);
4987                 if (sglq_entry == NULL) {
4988                         printk(KERN_ERR "%s: only allocated %d sgls of "
4989                                 "expected %d count. Unloading driver.\n",
4990                                 __func__, i, els_xri_cnt);
4991                         goto out_free_mem;
4992                 }
4993
4994                 sglq_entry->buff_type = GEN_BUFF_TYPE;
4995                 sglq_entry->virt = lpfc_mbuf_alloc(phba, 0, &sglq_entry->phys);
4996                 if (sglq_entry->virt == NULL) {
4997                         kfree(sglq_entry);
4998                         printk(KERN_ERR "%s: failed to allocate mbuf.\n"
4999                                 "Unloading driver.\n", __func__);
5000                         goto out_free_mem;
5001                 }
5002                 sglq_entry->sgl = sglq_entry->virt;
5003                 memset(sglq_entry->sgl, 0, LPFC_BPL_SIZE);
5004
5005                 /* The list order is used by later block SGL registraton */
5006                 spin_lock_irq(&phba->hbalock);
5007                 sglq_entry->state = SGL_FREED;
5008                 list_add_tail(&sglq_entry->list, &phba->sli4_hba.lpfc_sgl_list);
5009                 phba->sli4_hba.lpfc_els_sgl_array[i] = sglq_entry;
5010                 phba->sli4_hba.total_sglq_bufs++;
5011                 spin_unlock_irq(&phba->hbalock);
5012         }
5013         return 0;
5014
5015 out_free_mem:
5016         kfree(phba->sli4_hba.lpfc_scsi_psb_array);
5017         lpfc_free_sgl_list(phba);
5018         return -ENOMEM;
5019 }
5020
5021 /**
5022  * lpfc_sli4_init_rpi_hdrs - Post the rpi header memory region to the port
5023  * @phba: pointer to lpfc hba data structure.
5024  *
5025  * This routine is invoked to post rpi header templates to the
5026  * port for those SLI4 ports that do not support extents.  This routine
5027  * posts a PAGE_SIZE memory region to the port to hold up to
5028  * PAGE_SIZE modulo 64 rpi context headers.  This is an initialization routine
5029  * and should be called only when interrupts are disabled.
5030  *
5031  * Return codes
5032  *      0 - successful
5033  *      -ERROR - otherwise.
5034  **/
5035 int
5036 lpfc_sli4_init_rpi_hdrs(struct lpfc_hba *phba)
5037 {
5038         int rc = 0;
5039         struct lpfc_rpi_hdr *rpi_hdr;
5040
5041         INIT_LIST_HEAD(&phba->sli4_hba.lpfc_rpi_hdr_list);
5042         /*
5043          * If the SLI4 port supports extents, posting the rpi header isn't
5044          * required.  Set the expected maximum count and let the actual value
5045          * get set when extents are fully allocated.
5046          */
5047         if (!phba->sli4_hba.rpi_hdrs_in_use) {
5048                 phba->sli4_hba.next_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
5049                 return rc;
5050         }
5051         if (phba->sli4_hba.extents_in_use)
5052                 return -EIO;
5053
5054         rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
5055         if (!rpi_hdr) {
5056                 lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
5057                                 "0391 Error during rpi post operation\n");
5058                 lpfc_sli4_remove_rpis(phba);
5059                 rc = -ENODEV;
5060         }
5061
5062         return rc;
5063 }
5064
5065 /**
5066  * lpfc_sli4_create_rpi_hdr - Allocate an rpi header memory region
5067  * @phba: pointer to lpfc hba data structure.
5068  *
5069  * This routine is invoked to allocate a single 4KB memory region to
5070  * support rpis and stores them in the phba.  This single region
5071  * provides support for up to 64 rpis.  The region is used globally
5072  * by the device.
5073  *
5074  * Returns:
5075  *   A valid rpi hdr on success.
5076  *   A NULL pointer on any failure.
5077  **/
5078 struct lpfc_rpi_hdr *
5079 lpfc_sli4_create_rpi_hdr(struct lpfc_hba *phba)
5080 {
5081         uint16_t rpi_limit, curr_rpi_range;
5082         struct lpfc_dmabuf *dmabuf;
5083         struct lpfc_rpi_hdr *rpi_hdr;
5084         uint32_t rpi_count;
5085
5086         /*
5087          * If the SLI4 port supports extents, posting the rpi header isn't
5088          * required.  Set the expected maximum count and let the actual value
5089          * get set when extents are fully allocated.
5090          */
5091         if (!phba->sli4_hba.rpi_hdrs_in_use)
5092                 return NULL;
5093         if (phba->sli4_hba.extents_in_use)
5094                 return NULL;
5095
5096         /* The limit on the logical index is just the max_rpi count. */
5097         rpi_limit = phba->sli4_hba.max_cfg_param.rpi_base +
5098         phba->sli4_hba.max_cfg_param.max_rpi - 1;
5099
5100         spin_lock_irq(&phba->hbalock);
5101         /*
5102          * Establish the starting RPI in this header block.  The starting
5103          * rpi is normalized to a zero base because the physical rpi is
5104          * port based.
5105          */
5106         curr_rpi_range = phba->sli4_hba.next_rpi -
5107                 phba->sli4_hba.max_cfg_param.rpi_base;
5108         spin_unlock_irq(&phba->hbalock);
5109
5110         /*
5111          * The port has a limited number of rpis. The increment here
5112          * is LPFC_RPI_HDR_COUNT - 1 to account for the starting value
5113          * and to allow the full max_rpi range per port.
5114          */
5115         if ((curr_rpi_range + (LPFC_RPI_HDR_COUNT - 1)) > rpi_limit)
5116                 rpi_count = rpi_limit - curr_rpi_range;
5117         else
5118                 rpi_count = LPFC_RPI_HDR_COUNT;
5119
5120         if (!rpi_count)
5121                 return NULL;
5122         /*
5123          * First allocate the protocol header region for the port.  The
5124          * port expects a 4KB DMA-mapped memory region that is 4K aligned.
5125          */
5126         dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
5127         if (!dmabuf)
5128                 return NULL;
5129
5130         dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
5131                                           LPFC_HDR_TEMPLATE_SIZE,
5132                                           &dmabuf->phys,
5133                                           GFP_KERNEL);
5134         if (!dmabuf->virt) {
5135                 rpi_hdr = NULL;
5136                 goto err_free_dmabuf;
5137         }
5138
5139         memset(dmabuf->virt, 0, LPFC_HDR_TEMPLATE_SIZE);
5140         if (!IS_ALIGNED(dmabuf->phys, LPFC_HDR_TEMPLATE_SIZE)) {
5141                 rpi_hdr = NULL;
5142                 goto err_free_coherent;
5143         }
5144
5145         /* Save the rpi header data for cleanup later. */
5146         rpi_hdr = kzalloc(sizeof(struct lpfc_rpi_hdr), GFP_KERNEL);
5147         if (!rpi_hdr)
5148                 goto err_free_coherent;
5149
5150         rpi_hdr->dmabuf = dmabuf;
5151         rpi_hdr->len = LPFC_HDR_TEMPLATE_SIZE;
5152         rpi_hdr->page_count = 1;
5153         spin_lock_irq(&phba->hbalock);
5154
5155         /* The rpi_hdr stores the logical index only. */
5156         rpi_hdr->start_rpi = curr_rpi_range;
5157         list_add_tail(&rpi_hdr->list, &phba->sli4_hba.lpfc_rpi_hdr_list);
5158
5159         /*
5160          * The next_rpi stores the next logical module-64 rpi value used
5161          * to post physical rpis in subsequent rpi postings.
5162          */
5163         phba->sli4_hba.next_rpi += rpi_count;
5164         spin_unlock_irq(&phba->hbalock);
5165         return rpi_hdr;
5166
5167  err_free_coherent:
5168         dma_free_coherent(&phba->pcidev->dev, LPFC_HDR_TEMPLATE_SIZE,
5169                           dmabuf->virt, dmabuf->phys);
5170  err_free_dmabuf:
5171         kfree(dmabuf);
5172         return NULL;
5173 }
5174
5175 /**
5176  * lpfc_sli4_remove_rpi_hdrs - Remove all rpi header memory regions
5177  * @phba: pointer to lpfc hba data structure.
5178  *
5179  * This routine is invoked to remove all memory resources allocated
5180  * to support rpis for SLI4 ports not supporting extents. This routine
5181  * presumes the caller has released all rpis consumed by fabric or port
5182  * logins and is prepared to have the header pages removed.
5183  **/
5184 void
5185 lpfc_sli4_remove_rpi_hdrs(struct lpfc_hba *phba)
5186 {
5187         struct lpfc_rpi_hdr *rpi_hdr, *next_rpi_hdr;
5188
5189         if (!phba->sli4_hba.rpi_hdrs_in_use)
5190                 goto exit;
5191
5192         list_for_each_entry_safe(rpi_hdr, next_rpi_hdr,
5193                                  &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
5194                 list_del(&rpi_hdr->list);
5195                 dma_free_coherent(&phba->pcidev->dev, rpi_hdr->len,
5196                                   rpi_hdr->dmabuf->virt, rpi_hdr->dmabuf->phys);
5197                 kfree(rpi_hdr->dmabuf);
5198                 kfree(rpi_hdr);
5199         }
5200  exit:
5201         /* There are no rpis available to the port now. */
5202         phba->sli4_hba.next_rpi = 0;
5203 }
5204
5205 /**
5206  * lpfc_hba_alloc - Allocate driver hba data structure for a device.
5207  * @pdev: pointer to pci device data structure.
5208  *
5209  * This routine is invoked to allocate the driver hba data structure for an
5210  * HBA device. If the allocation is successful, the phba reference to the
5211  * PCI device data structure is set.
5212  *
5213  * Return codes
5214  *      pointer to @phba - successful
5215  *      NULL - error
5216  **/
5217 static struct lpfc_hba *
5218 lpfc_hba_alloc(struct pci_dev *pdev)
5219 {
5220         struct lpfc_hba *phba;
5221
5222         /* Allocate memory for HBA structure */
5223         phba = kzalloc(sizeof(struct lpfc_hba), GFP_KERNEL);
5224         if (!phba) {
5225                 dev_err(&pdev->dev, "failed to allocate hba struct\n");
5226                 return NULL;
5227         }
5228
5229         /* Set reference to PCI device in HBA structure */
5230         phba->pcidev = pdev;
5231
5232         /* Assign an unused board number */
5233         phba->brd_no = lpfc_get_instance();
5234         if (phba->brd_no < 0) {
5235                 kfree(phba);
5236                 return NULL;
5237         }
5238
5239         spin_lock_init(&phba->ct_ev_lock);
5240         INIT_LIST_HEAD(&phba->ct_ev_waiters);
5241
5242         return phba;
5243 }
5244
5245 /**
5246  * lpfc_hba_free - Free driver hba data structure with a device.
5247  * @phba: pointer to lpfc hba data structure.
5248  *
5249  * This routine is invoked to free the driver hba data structure with an
5250  * HBA device.
5251  **/
5252 static void
5253 lpfc_hba_free(struct lpfc_hba *phba)
5254 {
5255         /* Release the driver assigned board number */
5256         idr_remove(&lpfc_hba_index, phba->brd_no);
5257
5258         kfree(phba);
5259         return;
5260 }
5261
5262 /**
5263  * lpfc_create_shost - Create hba physical port with associated scsi host.
5264  * @phba: pointer to lpfc hba data structure.
5265  *
5266  * This routine is invoked to create HBA physical port and associate a SCSI
5267  * host with it.
5268  *
5269  * Return codes
5270  *      0 - successful
5271  *      other values - error
5272  **/
5273 static int
5274 lpfc_create_shost(struct lpfc_hba *phba)
5275 {
5276         struct lpfc_vport *vport;
5277         struct Scsi_Host  *shost;
5278
5279         /* Initialize HBA FC structure */
5280         phba->fc_edtov = FF_DEF_EDTOV;
5281         phba->fc_ratov = FF_DEF_RATOV;
5282         phba->fc_altov = FF_DEF_ALTOV;
5283         phba->fc_arbtov = FF_DEF_ARBTOV;
5284
5285         atomic_set(&phba->sdev_cnt, 0);
5286         vport = lpfc_create_port(phba, phba->brd_no, &phba->pcidev->dev);
5287         if (!vport)
5288                 return -ENODEV;
5289
5290         shost = lpfc_shost_from_vport(vport);
5291         phba->pport = vport;
5292         lpfc_debugfs_initialize(vport);
5293         /* Put reference to SCSI host to driver's device private data */
5294         pci_set_drvdata(phba->pcidev, shost);
5295
5296         return 0;
5297 }
5298
5299 /**
5300  * lpfc_destroy_shost - Destroy hba physical port with associated scsi host.
5301  * @phba: pointer to lpfc hba data structure.
5302  *
5303  * This routine is invoked to destroy HBA physical port and the associated
5304  * SCSI host.
5305  **/
5306 static void
5307 lpfc_destroy_shost(struct lpfc_hba *phba)
5308 {
5309         struct lpfc_vport *vport = phba->pport;
5310
5311         /* Destroy physical port that associated with the SCSI host */
5312         destroy_port(vport);
5313
5314         return;
5315 }
5316
5317 /**
5318  * lpfc_setup_bg - Setup Block guard structures and debug areas.
5319  * @phba: pointer to lpfc hba data structure.
5320  * @shost: the shost to be used to detect Block guard settings.
5321  *
5322  * This routine sets up the local Block guard protocol settings for @shost.
5323  * This routine also allocates memory for debugging bg buffers.
5324  **/
5325 static void
5326 lpfc_setup_bg(struct lpfc_hba *phba, struct Scsi_Host *shost)
5327 {
5328         int pagecnt = 10;
5329         if (lpfc_prot_mask && lpfc_prot_guard) {
5330                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5331                                 "1478 Registering BlockGuard with the "
5332                                 "SCSI layer\n");
5333                 scsi_host_set_prot(shost, lpfc_prot_mask);
5334                 scsi_host_set_guard(shost, lpfc_prot_guard);
5335         }
5336         if (!_dump_buf_data) {
5337                 while (pagecnt) {
5338                         spin_lock_init(&_dump_buf_lock);
5339                         _dump_buf_data =
5340                                 (char *) __get_free_pages(GFP_KERNEL, pagecnt);
5341                         if (_dump_buf_data) {
5342                                 lpfc_printf_log(phba, KERN_ERR, LOG_BG,
5343                                         "9043 BLKGRD: allocated %d pages for "
5344                                        "_dump_buf_data at 0x%p\n",
5345                                        (1 << pagecnt), _dump_buf_data);
5346                                 _dump_buf_data_order = pagecnt;
5347                                 memset(_dump_buf_data, 0,
5348                                        ((1 << PAGE_SHIFT) << pagecnt));
5349                                 break;
5350                         } else
5351                                 --pagecnt;
5352                 }
5353                 if (!_dump_buf_data_order)
5354                         lpfc_printf_log(phba, KERN_ERR, LOG_BG,
5355                                 "9044 BLKGRD: ERROR unable to allocate "
5356                                "memory for hexdump\n");
5357         } else
5358                 lpfc_printf_log(phba, KERN_ERR, LOG_BG,
5359                         "9045 BLKGRD: already allocated _dump_buf_data=0x%p"
5360                        "\n", _dump_buf_data);
5361         if (!_dump_buf_dif) {
5362                 while (pagecnt) {
5363                         _dump_buf_dif =
5364                                 (char *) __get_free_pages(GFP_KERNEL, pagecnt);
5365                         if (_dump_buf_dif) {
5366                                 lpfc_printf_log(phba, KERN_ERR, LOG_BG,
5367                                         "9046 BLKGRD: allocated %d pages for "
5368                                        "_dump_buf_dif at 0x%p\n",
5369                                        (1 << pagecnt), _dump_buf_dif);
5370                                 _dump_buf_dif_order = pagecnt;
5371                                 memset(_dump_buf_dif, 0,
5372                                        ((1 << PAGE_SHIFT) << pagecnt));
5373                                 break;
5374                         } else
5375                                 --pagecnt;
5376                 }
5377                 if (!_dump_buf_dif_order)
5378                         lpfc_printf_log(phba, KERN_ERR, LOG_BG,
5379                         "9047 BLKGRD: ERROR unable to allocate "
5380                                "memory for hexdump\n");
5381         } else
5382                 lpfc_printf_log(phba, KERN_ERR, LOG_BG,
5383                         "9048 BLKGRD: already allocated _dump_buf_dif=0x%p\n",
5384                        _dump_buf_dif);
5385 }
5386
5387 /**
5388  * lpfc_post_init_setup - Perform necessary device post initialization setup.
5389  * @phba: pointer to lpfc hba data structure.
5390  *
5391  * This routine is invoked to perform all the necessary post initialization
5392  * setup for the device.
5393  **/
5394 static void
5395 lpfc_post_init_setup(struct lpfc_hba *phba)
5396 {
5397         struct Scsi_Host  *shost;
5398         struct lpfc_adapter_event_header adapter_event;
5399
5400         /* Get the default values for Model Name and Description */
5401         lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
5402
5403         /*
5404          * hba setup may have changed the hba_queue_depth so we need to
5405          * adjust the value of can_queue.
5406          */
5407         shost = pci_get_drvdata(phba->pcidev);
5408         shost->can_queue = phba->cfg_hba_queue_depth - 10;
5409         if (phba->sli3_options & LPFC_SLI3_BG_ENABLED)
5410                 lpfc_setup_bg(phba, shost);
5411
5412         lpfc_host_attrib_init(shost);
5413
5414         if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
5415                 spin_lock_irq(shost->host_lock);
5416                 lpfc_poll_start_timer(phba);
5417                 spin_unlock_irq(shost->host_lock);
5418         }
5419
5420         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5421                         "0428 Perform SCSI scan\n");
5422         /* Send board arrival event to upper layer */
5423         adapter_event.event_type = FC_REG_ADAPTER_EVENT;
5424         adapter_event.subcategory = LPFC_EVENT_ARRIVAL;
5425         fc_host_post_vendor_event(shost, fc_get_event_number(),
5426                                   sizeof(adapter_event),
5427                                   (char *) &adapter_event,
5428                                   LPFC_NL_VENDOR_ID);
5429         return;
5430 }
5431
5432 /**
5433  * lpfc_sli_pci_mem_setup - Setup SLI3 HBA PCI memory space.
5434  * @phba: pointer to lpfc hba data structure.
5435  *
5436  * This routine is invoked to set up the PCI device memory space for device
5437  * with SLI-3 interface spec.
5438  *
5439  * Return codes
5440  *      0 - successful
5441  *      other values - error
5442  **/
5443 static int
5444 lpfc_sli_pci_mem_setup(struct lpfc_hba *phba)
5445 {
5446         struct pci_dev *pdev;
5447         unsigned long bar0map_len, bar2map_len;
5448         int i, hbq_count;
5449         void *ptr;
5450         int error = -ENODEV;
5451
5452         /* Obtain PCI device reference */
5453         if (!phba->pcidev)
5454                 return error;
5455         else
5456                 pdev = phba->pcidev;
5457
5458         /* Set the device DMA mask size */
5459         if (pci_set_dma_mask(pdev, DMA_BIT_MASK(64)) != 0
5460          || pci_set_consistent_dma_mask(pdev,DMA_BIT_MASK(64)) != 0) {
5461                 if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32)) != 0
5462                  || pci_set_consistent_dma_mask(pdev,DMA_BIT_MASK(32)) != 0) {
5463                         return error;
5464                 }
5465         }
5466
5467         /* Get the bus address of Bar0 and Bar2 and the number of bytes
5468          * required by each mapping.
5469          */
5470         phba->pci_bar0_map = pci_resource_start(pdev, 0);
5471         bar0map_len = pci_resource_len(pdev, 0);
5472
5473         phba->pci_bar2_map = pci_resource_start(pdev, 2);
5474         bar2map_len = pci_resource_len(pdev, 2);
5475
5476         /* Map HBA SLIM to a kernel virtual address. */
5477         phba->slim_memmap_p = ioremap(phba->pci_bar0_map, bar0map_len);
5478         if (!phba->slim_memmap_p) {
5479                 dev_printk(KERN_ERR, &pdev->dev,
5480                            "ioremap failed for SLIM memory.\n");
5481                 goto out;
5482         }
5483
5484         /* Map HBA Control Registers to a kernel virtual address. */
5485         phba->ctrl_regs_memmap_p = ioremap(phba->pci_bar2_map, bar2map_len);
5486         if (!phba->ctrl_regs_memmap_p) {
5487                 dev_printk(KERN_ERR, &pdev->dev,
5488                            "ioremap failed for HBA control registers.\n");
5489                 goto out_iounmap_slim;
5490         }
5491
5492         /* Allocate memory for SLI-2 structures */
5493         phba->slim2p.virt = dma_alloc_coherent(&pdev->dev,
5494                                                SLI2_SLIM_SIZE,
5495                                                &phba->slim2p.phys,
5496                                                GFP_KERNEL);
5497         if (!phba->slim2p.virt)
5498                 goto out_iounmap;
5499
5500         memset(phba->slim2p.virt, 0, SLI2_SLIM_SIZE);
5501         phba->mbox = phba->slim2p.virt + offsetof(struct lpfc_sli2_slim, mbx);
5502         phba->mbox_ext = (phba->slim2p.virt +
5503                 offsetof(struct lpfc_sli2_slim, mbx_ext_words));
5504         phba->pcb = (phba->slim2p.virt + offsetof(struct lpfc_sli2_slim, pcb));
5505         phba->IOCBs = (phba->slim2p.virt +
5506                        offsetof(struct lpfc_sli2_slim, IOCBs));
5507
5508         phba->hbqslimp.virt = dma_alloc_coherent(&pdev->dev,
5509                                                  lpfc_sli_hbq_size(),
5510                                                  &phba->hbqslimp.phys,
5511                                                  GFP_KERNEL);
5512         if (!phba->hbqslimp.virt)
5513                 goto out_free_slim;
5514
5515         hbq_count = lpfc_sli_hbq_count();
5516         ptr = phba->hbqslimp.virt;
5517         for (i = 0; i < hbq_count; ++i) {
5518                 phba->hbqs[i].hbq_virt = ptr;
5519                 INIT_LIST_HEAD(&phba->hbqs[i].hbq_buffer_list);
5520                 ptr += (lpfc_hbq_defs[i]->entry_count *
5521                         sizeof(struct lpfc_hbq_entry));
5522         }
5523         phba->hbqs[LPFC_ELS_HBQ].hbq_alloc_buffer = lpfc_els_hbq_alloc;
5524         phba->hbqs[LPFC_ELS_HBQ].hbq_free_buffer = lpfc_els_hbq_free;
5525
5526         memset(phba->hbqslimp.virt, 0, lpfc_sli_hbq_size());
5527
5528         INIT_LIST_HEAD(&phba->rb_pend_list);
5529
5530         phba->MBslimaddr = phba->slim_memmap_p;
5531         phba->HAregaddr = phba->ctrl_regs_memmap_p + HA_REG_OFFSET;
5532         phba->CAregaddr = phba->ctrl_regs_memmap_p + CA_REG_OFFSET;
5533         phba->HSregaddr = phba->ctrl_regs_memmap_p + HS_REG_OFFSET;
5534         phba->HCregaddr = phba->ctrl_regs_memmap_p + HC_REG_OFFSET;
5535
5536         return 0;
5537
5538 out_free_slim:
5539         dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
5540                           phba->slim2p.virt, phba->slim2p.phys);
5541 out_iounmap:
5542         iounmap(phba->ctrl_regs_memmap_p);
5543 out_iounmap_slim:
5544         iounmap(phba->slim_memmap_p);
5545 out:
5546         return error;
5547 }
5548
5549 /**
5550  * lpfc_sli_pci_mem_unset - Unset SLI3 HBA PCI memory space.
5551  * @phba: pointer to lpfc hba data structure.
5552  *
5553  * This routine is invoked to unset the PCI device memory space for device
5554  * with SLI-3 interface spec.
5555  **/
5556 static void
5557 lpfc_sli_pci_mem_unset(struct lpfc_hba *phba)
5558 {
5559         struct pci_dev *pdev;
5560
5561         /* Obtain PCI device reference */
5562         if (!phba->pcidev)
5563                 return;
5564         else
5565                 pdev = phba->pcidev;
5566
5567         /* Free coherent DMA memory allocated */
5568         dma_free_coherent(&pdev->dev, lpfc_sli_hbq_size(),
5569                           phba->hbqslimp.virt, phba->hbqslimp.phys);
5570         dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
5571                           phba->slim2p.virt, phba->slim2p.phys);
5572
5573         /* I/O memory unmap */
5574         iounmap(phba->ctrl_regs_memmap_p);
5575         iounmap(phba->slim_memmap_p);
5576
5577         return;
5578 }
5579
5580 /**
5581  * lpfc_sli4_post_status_check - Wait for SLI4 POST done and check status
5582  * @phba: pointer to lpfc hba data structure.
5583  *
5584  * This routine is invoked to wait for SLI4 device Power On Self Test (POST)
5585  * done and check status.
5586  *
5587  * Return 0 if successful, otherwise -ENODEV.
5588  **/
5589 int
5590 lpfc_sli4_post_status_check(struct lpfc_hba *phba)
5591 {
5592         struct lpfc_register portsmphr_reg, uerrlo_reg, uerrhi_reg;
5593         struct lpfc_register reg_data;
5594         int i, port_error = 0;
5595         uint32_t if_type;
5596
5597         memset(&portsmphr_reg, 0, sizeof(portsmphr_reg));
5598         memset(&reg_data, 0, sizeof(reg_data));
5599         if (!phba->sli4_hba.PSMPHRregaddr)
5600                 return -ENODEV;
5601
5602         /* Wait up to 30 seconds for the SLI Port POST done and ready */
5603         for (i = 0; i < 3000; i++) {
5604                 if (lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
5605                         &portsmphr_reg.word0) ||
5606                         (bf_get(lpfc_port_smphr_perr, &portsmphr_reg))) {
5607                         /* Port has a fatal POST error, break out */
5608                         port_error = -ENODEV;
5609                         break;
5610                 }
5611                 if (LPFC_POST_STAGE_PORT_READY ==
5612                     bf_get(lpfc_port_smphr_port_status, &portsmphr_reg))
5613                         break;
5614                 msleep(10);
5615         }
5616
5617         /*
5618          * If there was a port error during POST, then don't proceed with
5619          * other register reads as the data may not be valid.  Just exit.
5620          */
5621         if (port_error) {
5622                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5623                         "1408 Port Failed POST - portsmphr=0x%x, "
5624                         "perr=x%x, sfi=x%x, nip=x%x, ipc=x%x, scr1=x%x, "
5625                         "scr2=x%x, hscratch=x%x, pstatus=x%x\n",
5626                         portsmphr_reg.word0,
5627                         bf_get(lpfc_port_smphr_perr, &portsmphr_reg),
5628                         bf_get(lpfc_port_smphr_sfi, &portsmphr_reg),
5629                         bf_get(lpfc_port_smphr_nip, &portsmphr_reg),
5630                         bf_get(lpfc_port_smphr_ipc, &portsmphr_reg),
5631                         bf_get(lpfc_port_smphr_scr1, &portsmphr_reg),
5632                         bf_get(lpfc_port_smphr_scr2, &portsmphr_reg),
5633                         bf_get(lpfc_port_smphr_host_scratch, &portsmphr_reg),
5634                         bf_get(lpfc_port_smphr_port_status, &portsmphr_reg));
5635         } else {
5636                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5637                                 "2534 Device Info: SLIFamily=0x%x, "
5638                                 "SLIRev=0x%x, IFType=0x%x, SLIHint_1=0x%x, "
5639                                 "SLIHint_2=0x%x, FT=0x%x\n",
5640                                 bf_get(lpfc_sli_intf_sli_family,
5641                                        &phba->sli4_hba.sli_intf),
5642                                 bf_get(lpfc_sli_intf_slirev,
5643                                        &phba->sli4_hba.sli_intf),
5644                                 bf_get(lpfc_sli_intf_if_type,
5645                                        &phba->sli4_hba.sli_intf),
5646                                 bf_get(lpfc_sli_intf_sli_hint1,
5647                                        &phba->sli4_hba.sli_intf),
5648                                 bf_get(lpfc_sli_intf_sli_hint2,
5649                                        &phba->sli4_hba.sli_intf),
5650                                 bf_get(lpfc_sli_intf_func_type,
5651                                        &phba->sli4_hba.sli_intf));
5652                 /*
5653                  * Check for other Port errors during the initialization
5654                  * process.  Fail the load if the port did not come up
5655                  * correctly.
5656                  */
5657                 if_type = bf_get(lpfc_sli_intf_if_type,
5658                                  &phba->sli4_hba.sli_intf);
5659                 switch (if_type) {
5660                 case LPFC_SLI_INTF_IF_TYPE_0:
5661                         phba->sli4_hba.ue_mask_lo =
5662                               readl(phba->sli4_hba.u.if_type0.UEMASKLOregaddr);
5663                         phba->sli4_hba.ue_mask_hi =
5664                               readl(phba->sli4_hba.u.if_type0.UEMASKHIregaddr);
5665                         uerrlo_reg.word0 =
5666                               readl(phba->sli4_hba.u.if_type0.UERRLOregaddr);
5667                         uerrhi_reg.word0 =
5668                                 readl(phba->sli4_hba.u.if_type0.UERRHIregaddr);
5669                         if ((~phba->sli4_hba.ue_mask_lo & uerrlo_reg.word0) ||
5670                             (~phba->sli4_hba.ue_mask_hi & uerrhi_reg.word0)) {
5671                                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5672                                                 "1422 Unrecoverable Error "
5673                                                 "Detected during POST "
5674                                                 "uerr_lo_reg=0x%x, "
5675                                                 "uerr_hi_reg=0x%x, "
5676                                                 "ue_mask_lo_reg=0x%x, "
5677                                                 "ue_mask_hi_reg=0x%x\n",
5678                                                 uerrlo_reg.word0,
5679                                                 uerrhi_reg.word0,
5680                                                 phba->sli4_hba.ue_mask_lo,
5681                                                 phba->sli4_hba.ue_mask_hi);
5682                                 port_error = -ENODEV;
5683                         }
5684                         break;
5685                 case LPFC_SLI_INTF_IF_TYPE_2:
5686                         /* Final checks.  The port status should be clean. */
5687                         if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
5688                                 &reg_data.word0) ||
5689                                 (bf_get(lpfc_sliport_status_err, &reg_data) &&
5690                                  !bf_get(lpfc_sliport_status_rn, &reg_data))) {
5691                                 phba->work_status[0] =
5692                                         readl(phba->sli4_hba.u.if_type2.
5693                                               ERR1regaddr);
5694                                 phba->work_status[1] =
5695                                         readl(phba->sli4_hba.u.if_type2.
5696                                               ERR2regaddr);
5697                                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5698                                         "2888 Port Error Detected "
5699                                         "during POST: "
5700                                         "port status reg 0x%x, "
5701                                         "port_smphr reg 0x%x, "
5702                                         "error 1=0x%x, error 2=0x%x\n",
5703                                         reg_data.word0,
5704                                         portsmphr_reg.word0,
5705                                         phba->work_status[0],
5706                                         phba->work_status[1]);
5707                                 port_error = -ENODEV;
5708                         }
5709                         break;
5710                 case LPFC_SLI_INTF_IF_TYPE_1:
5711                 default:
5712                         break;
5713                 }
5714         }
5715         return port_error;
5716 }
5717
5718 /**
5719  * lpfc_sli4_bar0_register_memmap - Set up SLI4 BAR0 register memory map.
5720  * @phba: pointer to lpfc hba data structure.
5721  * @if_type:  The SLI4 interface type getting configured.
5722  *
5723  * This routine is invoked to set up SLI4 BAR0 PCI config space register
5724  * memory map.
5725  **/
5726 static void
5727 lpfc_sli4_bar0_register_memmap(struct lpfc_hba *phba, uint32_t if_type)
5728 {
5729         switch (if_type) {
5730         case LPFC_SLI_INTF_IF_TYPE_0:
5731                 phba->sli4_hba.u.if_type0.UERRLOregaddr =
5732                         phba->sli4_hba.conf_regs_memmap_p + LPFC_UERR_STATUS_LO;
5733                 phba->sli4_hba.u.if_type0.UERRHIregaddr =
5734                         phba->sli4_hba.conf_regs_memmap_p + LPFC_UERR_STATUS_HI;
5735                 phba->sli4_hba.u.if_type0.UEMASKLOregaddr =
5736                         phba->sli4_hba.conf_regs_memmap_p + LPFC_UE_MASK_LO;
5737                 phba->sli4_hba.u.if_type0.UEMASKHIregaddr =
5738                         phba->sli4_hba.conf_regs_memmap_p + LPFC_UE_MASK_HI;
5739                 phba->sli4_hba.SLIINTFregaddr =
5740                         phba->sli4_hba.conf_regs_memmap_p + LPFC_SLI_INTF;
5741                 break;
5742         case LPFC_SLI_INTF_IF_TYPE_2:
5743                 phba->sli4_hba.u.if_type2.ERR1regaddr =
5744                         phba->sli4_hba.conf_regs_memmap_p +
5745                                                 LPFC_CTL_PORT_ER1_OFFSET;
5746                 phba->sli4_hba.u.if_type2.ERR2regaddr =
5747                         phba->sli4_hba.conf_regs_memmap_p +
5748                                                 LPFC_CTL_PORT_ER2_OFFSET;
5749                 phba->sli4_hba.u.if_type2.CTRLregaddr =
5750                         phba->sli4_hba.conf_regs_memmap_p +
5751                                                 LPFC_CTL_PORT_CTL_OFFSET;
5752                 phba->sli4_hba.u.if_type2.STATUSregaddr =
5753                         phba->sli4_hba.conf_regs_memmap_p +
5754                                                 LPFC_CTL_PORT_STA_OFFSET;
5755                 phba->sli4_hba.SLIINTFregaddr =
5756                         phba->sli4_hba.conf_regs_memmap_p + LPFC_SLI_INTF;
5757                 phba->sli4_hba.PSMPHRregaddr =
5758                         phba->sli4_hba.conf_regs_memmap_p +
5759                                                 LPFC_CTL_PORT_SEM_OFFSET;
5760                 phba->sli4_hba.RQDBregaddr =
5761                         phba->sli4_hba.conf_regs_memmap_p + LPFC_RQ_DOORBELL;
5762                 phba->sli4_hba.WQDBregaddr =
5763                         phba->sli4_hba.conf_regs_memmap_p + LPFC_WQ_DOORBELL;
5764                 phba->sli4_hba.EQCQDBregaddr =
5765                         phba->sli4_hba.conf_regs_memmap_p + LPFC_EQCQ_DOORBELL;
5766                 phba->sli4_hba.MQDBregaddr =
5767                         phba->sli4_hba.conf_regs_memmap_p + LPFC_MQ_DOORBELL;
5768                 phba->sli4_hba.BMBXregaddr =
5769                         phba->sli4_hba.conf_regs_memmap_p + LPFC_BMBX;
5770                 break;
5771         case LPFC_SLI_INTF_IF_TYPE_1:
5772         default:
5773                 dev_printk(KERN_ERR, &phba->pcidev->dev,
5774                            "FATAL - unsupported SLI4 interface type - %d\n",
5775                            if_type);
5776                 break;
5777         }
5778 }
5779
5780 /**
5781  * lpfc_sli4_bar1_register_memmap - Set up SLI4 BAR1 register memory map.
5782  * @phba: pointer to lpfc hba data structure.
5783  *
5784  * This routine is invoked to set up SLI4 BAR1 control status register (CSR)
5785  * memory map.
5786  **/
5787 static void
5788 lpfc_sli4_bar1_register_memmap(struct lpfc_hba *phba)
5789 {
5790         phba->sli4_hba.PSMPHRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
5791                 LPFC_SLIPORT_IF0_SMPHR;
5792         phba->sli4_hba.ISRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
5793                 LPFC_HST_ISR0;
5794         phba->sli4_hba.IMRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
5795                 LPFC_HST_IMR0;
5796         phba->sli4_hba.ISCRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
5797                 LPFC_HST_ISCR0;
5798 }
5799
5800 /**
5801  * lpfc_sli4_bar2_register_memmap - Set up SLI4 BAR2 register memory map.
5802  * @phba: pointer to lpfc hba data structure.
5803  * @vf: virtual function number
5804  *
5805  * This routine is invoked to set up SLI4 BAR2 doorbell register memory map
5806  * based on the given viftual function number, @vf.
5807  *
5808  * Return 0 if successful, otherwise -ENODEV.
5809  **/
5810 static int
5811 lpfc_sli4_bar2_register_memmap(struct lpfc_hba *phba, uint32_t vf)
5812 {
5813         if (vf > LPFC_VIR_FUNC_MAX)
5814                 return -ENODEV;
5815
5816         phba->sli4_hba.RQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
5817                                 vf * LPFC_VFR_PAGE_SIZE + LPFC_RQ_DOORBELL);
5818         phba->sli4_hba.WQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
5819                                 vf * LPFC_VFR_PAGE_SIZE + LPFC_WQ_DOORBELL);
5820         phba->sli4_hba.EQCQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
5821                                 vf * LPFC_VFR_PAGE_SIZE + LPFC_EQCQ_DOORBELL);
5822         phba->sli4_hba.MQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
5823                                 vf * LPFC_VFR_PAGE_SIZE + LPFC_MQ_DOORBELL);
5824         phba->sli4_hba.BMBXregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
5825                                 vf * LPFC_VFR_PAGE_SIZE + LPFC_BMBX);
5826         return 0;
5827 }
5828
5829 /**
5830  * lpfc_create_bootstrap_mbox - Create the bootstrap mailbox
5831  * @phba: pointer to lpfc hba data structure.
5832  *
5833  * This routine is invoked to create the bootstrap mailbox
5834  * region consistent with the SLI-4 interface spec.  This
5835  * routine allocates all memory necessary to communicate
5836  * mailbox commands to the port and sets up all alignment
5837  * needs.  No locks are expected to be held when calling
5838  * this routine.
5839  *
5840  * Return codes
5841  *      0 - successful
5842  *      -ENOMEM - could not allocated memory.
5843  **/
5844 static int
5845 lpfc_create_bootstrap_mbox(struct lpfc_hba *phba)
5846 {
5847         uint32_t bmbx_size;
5848         struct lpfc_dmabuf *dmabuf;
5849         struct dma_address *dma_address;
5850         uint32_t pa_addr;
5851         uint64_t phys_addr;
5852
5853         dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
5854         if (!dmabuf)
5855                 return -ENOMEM;
5856
5857         /*
5858          * The bootstrap mailbox region is comprised of 2 parts
5859          * plus an alignment restriction of 16 bytes.
5860          */
5861         bmbx_size = sizeof(struct lpfc_bmbx_create) + (LPFC_ALIGN_16_BYTE - 1);
5862         dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
5863                                           bmbx_size,
5864                                           &dmabuf->phys,
5865                                           GFP_KERNEL);
5866         if (!dmabuf->virt) {
5867                 kfree(dmabuf);
5868                 return -ENOMEM;
5869         }
5870         memset(dmabuf->virt, 0, bmbx_size);
5871
5872         /*
5873          * Initialize the bootstrap mailbox pointers now so that the register
5874          * operations are simple later.  The mailbox dma address is required
5875          * to be 16-byte aligned.  Also align the virtual memory as each
5876          * maibox is copied into the bmbx mailbox region before issuing the
5877          * command to the port.
5878          */
5879         phba->sli4_hba.bmbx.dmabuf = dmabuf;
5880         phba->sli4_hba.bmbx.bmbx_size = bmbx_size;
5881
5882         phba->sli4_hba.bmbx.avirt = PTR_ALIGN(dmabuf->virt,
5883                                               LPFC_ALIGN_16_BYTE);
5884         phba->sli4_hba.bmbx.aphys = ALIGN(dmabuf->phys,
5885                                               LPFC_ALIGN_16_BYTE);
5886
5887         /*
5888          * Set the high and low physical addresses now.  The SLI4 alignment
5889          * requirement is 16 bytes and the mailbox is posted to the port
5890          * as two 30-bit addresses.  The other data is a bit marking whether
5891          * the 30-bit address is the high or low address.
5892          * Upcast bmbx aphys to 64bits so shift instruction compiles
5893          * clean on 32 bit machines.
5894          */
5895         dma_address = &phba->sli4_hba.bmbx.dma_address;
5896         phys_addr = (uint64_t)phba->sli4_hba.bmbx.aphys;
5897         pa_addr = (uint32_t) ((phys_addr >> 34) & 0x3fffffff);
5898         dma_address->addr_hi = (uint32_t) ((pa_addr << 2) |
5899                                            LPFC_BMBX_BIT1_ADDR_HI);
5900
5901         pa_addr = (uint32_t) ((phba->sli4_hba.bmbx.aphys >> 4) & 0x3fffffff);
5902         dma_address->addr_lo = (uint32_t) ((pa_addr << 2) |
5903                                            LPFC_BMBX_BIT1_ADDR_LO);
5904         return 0;
5905 }
5906
5907 /**
5908  * lpfc_destroy_bootstrap_mbox - Destroy all bootstrap mailbox resources
5909  * @phba: pointer to lpfc hba data structure.
5910  *
5911  * This routine is invoked to teardown the bootstrap mailbox
5912  * region and release all host resources. This routine requires
5913  * the caller to ensure all mailbox commands recovered, no
5914  * additional mailbox comands are sent, and interrupts are disabled
5915  * before calling this routine.
5916  *
5917  **/
5918 static void
5919 lpfc_destroy_bootstrap_mbox(struct lpfc_hba *phba)
5920 {
5921         dma_free_coherent(&phba->pcidev->dev,
5922                           phba->sli4_hba.bmbx.bmbx_size,
5923                           phba->sli4_hba.bmbx.dmabuf->virt,
5924                           phba->sli4_hba.bmbx.dmabuf->phys);
5925
5926         kfree(phba->sli4_hba.bmbx.dmabuf);
5927         memset(&phba->sli4_hba.bmbx, 0, sizeof(struct lpfc_bmbx));
5928 }
5929
5930 /**
5931  * lpfc_sli4_read_config - Get the config parameters.
5932  * @phba: pointer to lpfc hba data structure.
5933  *
5934  * This routine is invoked to read the configuration parameters from the HBA.
5935  * The configuration parameters are used to set the base and maximum values
5936  * for RPI's XRI's VPI's VFI's and FCFIs. These values also affect the resource
5937  * allocation for the port.
5938  *
5939  * Return codes
5940  *      0 - successful
5941  *      -ENOMEM - No available memory
5942  *      -EIO - The mailbox failed to complete successfully.
5943  **/
5944 static int
5945 lpfc_sli4_read_config(struct lpfc_hba *phba)
5946 {
5947         LPFC_MBOXQ_t *pmb;
5948         struct lpfc_mbx_read_config *rd_config;
5949         union  lpfc_sli4_cfg_shdr *shdr;
5950         uint32_t shdr_status, shdr_add_status;
5951         struct lpfc_mbx_get_func_cfg *get_func_cfg;
5952         struct lpfc_rsrc_desc_fcfcoe *desc;
5953         uint32_t desc_count;
5954         int length, i, rc = 0;
5955
5956         pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5957         if (!pmb) {
5958                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5959                                 "2011 Unable to allocate memory for issuing "
5960                                 "SLI_CONFIG_SPECIAL mailbox command\n");
5961                 return -ENOMEM;
5962         }
5963
5964         lpfc_read_config(phba, pmb);
5965
5966         rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
5967         if (rc != MBX_SUCCESS) {
5968                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5969                         "2012 Mailbox failed , mbxCmd x%x "
5970                         "READ_CONFIG, mbxStatus x%x\n",
5971                         bf_get(lpfc_mqe_command, &pmb->u.mqe),
5972                         bf_get(lpfc_mqe_status, &pmb->u.mqe));
5973                 rc = -EIO;
5974         } else {
5975                 rd_config = &pmb->u.mqe.un.rd_config;
5976                 phba->sli4_hba.extents_in_use =
5977                         bf_get(lpfc_mbx_rd_conf_extnts_inuse, rd_config);
5978                 phba->sli4_hba.max_cfg_param.max_xri =
5979                         bf_get(lpfc_mbx_rd_conf_xri_count, rd_config);
5980                 phba->sli4_hba.max_cfg_param.xri_base =
5981                         bf_get(lpfc_mbx_rd_conf_xri_base, rd_config);
5982                 phba->sli4_hba.max_cfg_param.max_vpi =
5983                         bf_get(lpfc_mbx_rd_conf_vpi_count, rd_config);
5984                 phba->sli4_hba.max_cfg_param.vpi_base =
5985                         bf_get(lpfc_mbx_rd_conf_vpi_base, rd_config);
5986                 phba->sli4_hba.max_cfg_param.max_rpi =
5987                         bf_get(lpfc_mbx_rd_conf_rpi_count, rd_config);
5988                 phba->sli4_hba.max_cfg_param.rpi_base =
5989                         bf_get(lpfc_mbx_rd_conf_rpi_base, rd_config);
5990                 phba->sli4_hba.max_cfg_param.max_vfi =
5991                         bf_get(lpfc_mbx_rd_conf_vfi_count, rd_config);
5992                 phba->sli4_hba.max_cfg_param.vfi_base =
5993                         bf_get(lpfc_mbx_rd_conf_vfi_base, rd_config);
5994                 phba->sli4_hba.max_cfg_param.max_fcfi =
5995                         bf_get(lpfc_mbx_rd_conf_fcfi_count, rd_config);
5996                 phba->sli4_hba.max_cfg_param.max_eq =
5997                         bf_get(lpfc_mbx_rd_conf_eq_count, rd_config);
5998                 phba->sli4_hba.max_cfg_param.max_rq =
5999                         bf_get(lpfc_mbx_rd_conf_rq_count, rd_config);
6000                 phba->sli4_hba.max_cfg_param.max_wq =
6001                         bf_get(lpfc_mbx_rd_conf_wq_count, rd_config);
6002                 phba->sli4_hba.max_cfg_param.max_cq =
6003                         bf_get(lpfc_mbx_rd_conf_cq_count, rd_config);
6004                 phba->lmt = bf_get(lpfc_mbx_rd_conf_lmt, rd_config);
6005                 phba->sli4_hba.next_xri = phba->sli4_hba.max_cfg_param.xri_base;
6006                 phba->vpi_base = phba->sli4_hba.max_cfg_param.vpi_base;
6007                 phba->vfi_base = phba->sli4_hba.max_cfg_param.vfi_base;
6008                 phba->sli4_hba.next_rpi = phba->sli4_hba.max_cfg_param.rpi_base;
6009                 phba->max_vpi = (phba->sli4_hba.max_cfg_param.max_vpi > 0) ?
6010                                 (phba->sli4_hba.max_cfg_param.max_vpi - 1) : 0;
6011                 phba->max_vports = phba->max_vpi;
6012                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6013                                 "2003 cfg params Extents? %d "
6014                                 "XRI(B:%d M:%d), "
6015                                 "VPI(B:%d M:%d) "
6016                                 "VFI(B:%d M:%d) "
6017                                 "RPI(B:%d M:%d) "
6018                                 "FCFI(Count:%d)\n",
6019                                 phba->sli4_hba.extents_in_use,
6020                                 phba->sli4_hba.max_cfg_param.xri_base,
6021                                 phba->sli4_hba.max_cfg_param.max_xri,
6022                                 phba->sli4_hba.max_cfg_param.vpi_base,
6023                                 phba->sli4_hba.max_cfg_param.max_vpi,
6024                                 phba->sli4_hba.max_cfg_param.vfi_base,
6025                                 phba->sli4_hba.max_cfg_param.max_vfi,
6026                                 phba->sli4_hba.max_cfg_param.rpi_base,
6027                                 phba->sli4_hba.max_cfg_param.max_rpi,
6028                                 phba->sli4_hba.max_cfg_param.max_fcfi);
6029         }
6030
6031         if (rc)
6032                 goto read_cfg_out;
6033
6034         /* Reset the DFT_HBA_Q_DEPTH to the max xri  */
6035         if (phba->cfg_hba_queue_depth >
6036                 (phba->sli4_hba.max_cfg_param.max_xri -
6037                         lpfc_sli4_get_els_iocb_cnt(phba)))
6038                 phba->cfg_hba_queue_depth =
6039                         phba->sli4_hba.max_cfg_param.max_xri -
6040                                 lpfc_sli4_get_els_iocb_cnt(phba);
6041
6042         if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) !=
6043             LPFC_SLI_INTF_IF_TYPE_2)
6044                 goto read_cfg_out;
6045
6046         /* get the pf# and vf# for SLI4 if_type 2 port */
6047         length = (sizeof(struct lpfc_mbx_get_func_cfg) -
6048                   sizeof(struct lpfc_sli4_cfg_mhdr));
6049         lpfc_sli4_config(phba, pmb, LPFC_MBOX_SUBSYSTEM_COMMON,
6050                          LPFC_MBOX_OPCODE_GET_FUNCTION_CONFIG,
6051                          length, LPFC_SLI4_MBX_EMBED);
6052
6053         rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
6054         shdr = (union lpfc_sli4_cfg_shdr *)
6055                                 &pmb->u.mqe.un.sli4_config.header.cfg_shdr;
6056         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
6057         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
6058         if (rc || shdr_status || shdr_add_status) {
6059                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6060                                 "3026 Mailbox failed , mbxCmd x%x "
6061                                 "GET_FUNCTION_CONFIG, mbxStatus x%x\n",
6062                                 bf_get(lpfc_mqe_command, &pmb->u.mqe),
6063                                 bf_get(lpfc_mqe_status, &pmb->u.mqe));
6064                 rc = -EIO;
6065                 goto read_cfg_out;
6066         }
6067
6068         /* search for fc_fcoe resrouce descriptor */
6069         get_func_cfg = &pmb->u.mqe.un.get_func_cfg;
6070         desc_count = get_func_cfg->func_cfg.rsrc_desc_count;
6071
6072         for (i = 0; i < LPFC_RSRC_DESC_MAX_NUM; i++) {
6073                 desc = (struct lpfc_rsrc_desc_fcfcoe *)
6074                         &get_func_cfg->func_cfg.desc[i];
6075                 if (LPFC_RSRC_DESC_TYPE_FCFCOE ==
6076                     bf_get(lpfc_rsrc_desc_pcie_type, desc)) {
6077                         phba->sli4_hba.iov.pf_number =
6078                                 bf_get(lpfc_rsrc_desc_fcfcoe_pfnum, desc);
6079                         phba->sli4_hba.iov.vf_number =
6080                                 bf_get(lpfc_rsrc_desc_fcfcoe_vfnum, desc);
6081                         break;
6082                 }
6083         }
6084
6085         if (i < LPFC_RSRC_DESC_MAX_NUM)
6086                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6087                                 "3027 GET_FUNCTION_CONFIG: pf_number:%d, "
6088                                 "vf_number:%d\n", phba->sli4_hba.iov.pf_number,
6089                                 phba->sli4_hba.iov.vf_number);
6090         else {
6091                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6092                                 "3028 GET_FUNCTION_CONFIG: failed to find "
6093                                 "Resrouce Descriptor:x%x\n",
6094                                 LPFC_RSRC_DESC_TYPE_FCFCOE);
6095                 rc = -EIO;
6096         }
6097
6098 read_cfg_out:
6099         mempool_free(pmb, phba->mbox_mem_pool);
6100         return rc;
6101 }
6102
6103 /**
6104  * lpfc_setup_endian_order - Write endian order to an SLI4 if_type 0 port.
6105  * @phba: pointer to lpfc hba data structure.
6106  *
6107  * This routine is invoked to setup the port-side endian order when
6108  * the port if_type is 0.  This routine has no function for other
6109  * if_types.
6110  *
6111  * Return codes
6112  *      0 - successful
6113  *      -ENOMEM - No available memory
6114  *      -EIO - The mailbox failed to complete successfully.
6115  **/
6116 static int
6117 lpfc_setup_endian_order(struct lpfc_hba *phba)
6118 {
6119         LPFC_MBOXQ_t *mboxq;
6120         uint32_t if_type, rc = 0;
6121         uint32_t endian_mb_data[2] = {HOST_ENDIAN_LOW_WORD0,
6122                                       HOST_ENDIAN_HIGH_WORD1};
6123
6124         if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
6125         switch (if_type) {
6126         case LPFC_SLI_INTF_IF_TYPE_0:
6127                 mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
6128                                                        GFP_KERNEL);
6129                 if (!mboxq) {
6130                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6131                                         "0492 Unable to allocate memory for "
6132                                         "issuing SLI_CONFIG_SPECIAL mailbox "
6133                                         "command\n");
6134                         return -ENOMEM;
6135                 }
6136
6137                 /*
6138                  * The SLI4_CONFIG_SPECIAL mailbox command requires the first
6139                  * two words to contain special data values and no other data.
6140                  */
6141                 memset(mboxq, 0, sizeof(LPFC_MBOXQ_t));
6142                 memcpy(&mboxq->u.mqe, &endian_mb_data, sizeof(endian_mb_data));
6143                 rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6144                 if (rc != MBX_SUCCESS) {
6145                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6146                                         "0493 SLI_CONFIG_SPECIAL mailbox "
6147                                         "failed with status x%x\n",
6148                                         rc);
6149                         rc = -EIO;
6150                 }
6151                 mempool_free(mboxq, phba->mbox_mem_pool);
6152                 break;
6153         case LPFC_SLI_INTF_IF_TYPE_2:
6154         case LPFC_SLI_INTF_IF_TYPE_1:
6155         default:
6156                 break;
6157         }
6158         return rc;
6159 }
6160
6161 /**
6162  * lpfc_sli4_queue_verify - Verify and update EQ and CQ counts
6163  * @phba: pointer to lpfc hba data structure.
6164  *
6165  * This routine is invoked to check the user settable queue counts for EQs and
6166  * CQs. after this routine is called the counts will be set to valid values that
6167  * adhere to the constraints of the system's interrupt vectors and the port's
6168  * queue resources.
6169  *
6170  * Return codes
6171  *      0 - successful
6172  *      -ENOMEM - No available memory
6173  **/
6174 static int
6175 lpfc_sli4_queue_verify(struct lpfc_hba *phba)
6176 {
6177         int cfg_fcp_wq_count;
6178         int cfg_fcp_eq_count;
6179
6180         /*
6181          * Sanity check for confiugred queue parameters against the run-time
6182          * device parameters
6183          */
6184
6185         /* Sanity check on FCP fast-path WQ parameters */
6186         cfg_fcp_wq_count = phba->cfg_fcp_wq_count;
6187         if (cfg_fcp_wq_count >
6188             (phba->sli4_hba.max_cfg_param.max_wq - LPFC_SP_WQN_DEF)) {
6189                 cfg_fcp_wq_count = phba->sli4_hba.max_cfg_param.max_wq -
6190                                    LPFC_SP_WQN_DEF;
6191                 if (cfg_fcp_wq_count < LPFC_FP_WQN_MIN) {
6192                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6193                                         "2581 Not enough WQs (%d) from "
6194                                         "the pci function for supporting "
6195                                         "FCP WQs (%d)\n",
6196                                         phba->sli4_hba.max_cfg_param.max_wq,
6197                                         phba->cfg_fcp_wq_count);
6198                         goto out_error;
6199                 }
6200                 lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6201                                 "2582 Not enough WQs (%d) from the pci "
6202                                 "function for supporting the requested "
6203                                 "FCP WQs (%d), the actual FCP WQs can "
6204                                 "be supported: %d\n",
6205                                 phba->sli4_hba.max_cfg_param.max_wq,
6206                                 phba->cfg_fcp_wq_count, cfg_fcp_wq_count);
6207         }
6208         /* The actual number of FCP work queues adopted */
6209         phba->cfg_fcp_wq_count = cfg_fcp_wq_count;
6210
6211         /* Sanity check on FCP fast-path EQ parameters */
6212         cfg_fcp_eq_count = phba->cfg_fcp_eq_count;
6213         if (cfg_fcp_eq_count >
6214             (phba->sli4_hba.max_cfg_param.max_eq - LPFC_SP_EQN_DEF)) {
6215                 cfg_fcp_eq_count = phba->sli4_hba.max_cfg_param.max_eq -
6216                                    LPFC_SP_EQN_DEF;
6217                 if (cfg_fcp_eq_count < LPFC_FP_EQN_MIN) {
6218                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6219                                         "2574 Not enough EQs (%d) from the "
6220                                         "pci function for supporting FCP "
6221                                         "EQs (%d)\n",
6222                                         phba->sli4_hba.max_cfg_param.max_eq,
6223                                         phba->cfg_fcp_eq_count);
6224                         goto out_error;
6225                 }
6226                 lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6227                                 "2575 Not enough EQs (%d) from the pci "
6228                                 "function for supporting the requested "
6229                                 "FCP EQs (%d), the actual FCP EQs can "
6230                                 "be supported: %d\n",
6231                                 phba->sli4_hba.max_cfg_param.max_eq,
6232                                 phba->cfg_fcp_eq_count, cfg_fcp_eq_count);
6233         }
6234         /* It does not make sense to have more EQs than WQs */
6235         if (cfg_fcp_eq_count > phba->cfg_fcp_wq_count) {
6236                 lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6237                                 "2593 The FCP EQ count(%d) cannot be greater "
6238                                 "than the FCP WQ count(%d), limiting the "
6239                                 "FCP EQ count to %d\n", cfg_fcp_eq_count,
6240                                 phba->cfg_fcp_wq_count,
6241                                 phba->cfg_fcp_wq_count);
6242                 cfg_fcp_eq_count = phba->cfg_fcp_wq_count;
6243         }
6244         /* The actual number of FCP event queues adopted */
6245         phba->cfg_fcp_eq_count = cfg_fcp_eq_count;
6246         /* The overall number of event queues used */
6247         phba->sli4_hba.cfg_eqn = phba->cfg_fcp_eq_count + LPFC_SP_EQN_DEF;
6248
6249         /* Get EQ depth from module parameter, fake the default for now */
6250         phba->sli4_hba.eq_esize = LPFC_EQE_SIZE_4B;
6251         phba->sli4_hba.eq_ecount = LPFC_EQE_DEF_COUNT;
6252
6253         /* Get CQ depth from module parameter, fake the default for now */
6254         phba->sli4_hba.cq_esize = LPFC_CQE_SIZE;
6255         phba->sli4_hba.cq_ecount = LPFC_CQE_DEF_COUNT;
6256
6257         return 0;
6258 out_error:
6259         return -ENOMEM;
6260 }
6261
6262 /**
6263  * lpfc_sli4_queue_create - Create all the SLI4 queues
6264  * @phba: pointer to lpfc hba data structure.
6265  *
6266  * This routine is invoked to allocate all the SLI4 queues for the FCoE HBA
6267  * operation. For each SLI4 queue type, the parameters such as queue entry
6268  * count (queue depth) shall be taken from the module parameter. For now,
6269  * we just use some constant number as place holder.
6270  *
6271  * Return codes
6272  *      0 - sucessful
6273  *      -ENOMEM - No availble memory
6274  *      -EIO - The mailbox failed to complete successfully.
6275  **/
6276 int
6277 lpfc_sli4_queue_create(struct lpfc_hba *phba)
6278 {
6279         struct lpfc_queue *qdesc;
6280         int fcp_eqidx, fcp_cqidx, fcp_wqidx;
6281
6282         /*
6283          * Create Event Queues (EQs)
6284          */
6285
6286         /* Create slow path event queue */
6287         qdesc = lpfc_sli4_queue_alloc(phba, phba->sli4_hba.eq_esize,
6288                                       phba->sli4_hba.eq_ecount);
6289         if (!qdesc) {
6290                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6291                                 "0496 Failed allocate slow-path EQ\n");
6292                 goto out_error;
6293         }
6294         phba->sli4_hba.sp_eq = qdesc;
6295
6296         /*
6297          * Create fast-path FCP Event Queue(s).  The cfg_fcp_eq_count can be
6298          * zero whenever there is exactly one interrupt vector.  This is not
6299          * an error.
6300          */
6301         if (phba->cfg_fcp_eq_count) {
6302                 phba->sli4_hba.fp_eq = kzalloc((sizeof(struct lpfc_queue *) *
6303                                        phba->cfg_fcp_eq_count), GFP_KERNEL);
6304                 if (!phba->sli4_hba.fp_eq) {
6305                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6306                                         "2576 Failed allocate memory for "
6307                                         "fast-path EQ record array\n");
6308                         goto out_free_sp_eq;
6309                 }
6310         }
6311         for (fcp_eqidx = 0; fcp_eqidx < phba->cfg_fcp_eq_count; fcp_eqidx++) {
6312                 qdesc = lpfc_sli4_queue_alloc(phba, phba->sli4_hba.eq_esize,
6313                                               phba->sli4_hba.eq_ecount);
6314                 if (!qdesc) {
6315                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6316                                         "0497 Failed allocate fast-path EQ\n");
6317                         goto out_free_fp_eq;
6318                 }
6319                 phba->sli4_hba.fp_eq[fcp_eqidx] = qdesc;
6320         }
6321
6322         /*
6323          * Create Complete Queues (CQs)
6324          */
6325
6326         /* Create slow-path Mailbox Command Complete Queue */
6327         qdesc = lpfc_sli4_queue_alloc(phba, phba->sli4_hba.cq_esize,
6328                                       phba->sli4_hba.cq_ecount);
6329         if (!qdesc) {
6330                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6331                                 "0500 Failed allocate slow-path mailbox CQ\n");
6332                 goto out_free_fp_eq;
6333         }
6334         phba->sli4_hba.mbx_cq = qdesc;
6335
6336         /* Create slow-path ELS Complete Queue */
6337         qdesc = lpfc_sli4_queue_alloc(phba, phba->sli4_hba.cq_esize,
6338                                       phba->sli4_hba.cq_ecount);
6339         if (!qdesc) {
6340                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6341                                 "0501 Failed allocate slow-path ELS CQ\n");
6342                 goto out_free_mbx_cq;
6343         }
6344         phba->sli4_hba.els_cq = qdesc;
6345
6346
6347         /*
6348          * Create fast-path FCP Completion Queue(s), one-to-one with FCP EQs.
6349          * If there are no FCP EQs then create exactly one FCP CQ.
6350          */
6351         if (phba->cfg_fcp_eq_count)
6352                 phba->sli4_hba.fcp_cq = kzalloc((sizeof(struct lpfc_queue *) *
6353                                                  phba->cfg_fcp_eq_count),
6354                                                 GFP_KERNEL);
6355         else
6356                 phba->sli4_hba.fcp_cq = kzalloc(sizeof(struct lpfc_queue *),
6357                                                 GFP_KERNEL);
6358         if (!phba->sli4_hba.fcp_cq) {
6359                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6360                                 "2577 Failed allocate memory for fast-path "
6361                                 "CQ record array\n");
6362                 goto out_free_els_cq;
6363         }
6364         fcp_cqidx = 0;
6365         do {
6366                 qdesc = lpfc_sli4_queue_alloc(phba, phba->sli4_hba.cq_esize,
6367                                               phba->sli4_hba.cq_ecount);
6368                 if (!qdesc) {
6369                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6370                                         "0499 Failed allocate fast-path FCP "
6371                                         "CQ (%d)\n", fcp_cqidx);
6372                         goto out_free_fcp_cq;
6373                 }
6374                 phba->sli4_hba.fcp_cq[fcp_cqidx] = qdesc;
6375         } while (++fcp_cqidx < phba->cfg_fcp_eq_count);
6376
6377         /* Create Mailbox Command Queue */
6378         phba->sli4_hba.mq_esize = LPFC_MQE_SIZE;
6379         phba->sli4_hba.mq_ecount = LPFC_MQE_DEF_COUNT;
6380
6381         qdesc = lpfc_sli4_queue_alloc(phba, phba->sli4_hba.mq_esize,
6382                                       phba->sli4_hba.mq_ecount);
6383         if (!qdesc) {
6384                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6385                                 "0505 Failed allocate slow-path MQ\n");
6386                 goto out_free_fcp_cq;
6387         }
6388         phba->sli4_hba.mbx_wq = qdesc;
6389
6390         /*
6391          * Create all the Work Queues (WQs)
6392          */
6393         phba->sli4_hba.wq_esize = LPFC_WQE_SIZE;
6394         phba->sli4_hba.wq_ecount = LPFC_WQE_DEF_COUNT;
6395
6396         /* Create slow-path ELS Work Queue */
6397         qdesc = lpfc_sli4_queue_alloc(phba, phba->sli4_hba.wq_esize,
6398                                       phba->sli4_hba.wq_ecount);
6399         if (!qdesc) {
6400                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6401                                 "0504 Failed allocate slow-path ELS WQ\n");
6402                 goto out_free_mbx_wq;
6403         }
6404         phba->sli4_hba.els_wq = qdesc;
6405
6406         /* Create fast-path FCP Work Queue(s) */
6407         phba->sli4_hba.fcp_wq = kzalloc((sizeof(struct lpfc_queue *) *
6408                                 phba->cfg_fcp_wq_count), GFP_KERNEL);
6409         if (!phba->sli4_hba.fcp_wq) {
6410                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6411                                 "2578 Failed allocate memory for fast-path "
6412                                 "WQ record array\n");
6413                 goto out_free_els_wq;
6414         }
6415         for (fcp_wqidx = 0; fcp_wqidx < phba->cfg_fcp_wq_count; fcp_wqidx++) {
6416                 qdesc = lpfc_sli4_queue_alloc(phba, phba->sli4_hba.wq_esize,
6417                                               phba->sli4_hba.wq_ecount);
6418                 if (!qdesc) {
6419                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6420                                         "0503 Failed allocate fast-path FCP "
6421                                         "WQ (%d)\n", fcp_wqidx);
6422                         goto out_free_fcp_wq;
6423                 }
6424                 phba->sli4_hba.fcp_wq[fcp_wqidx] = qdesc;
6425         }
6426
6427         /*
6428          * Create Receive Queue (RQ)
6429          */
6430         phba->sli4_hba.rq_esize = LPFC_RQE_SIZE;
6431         phba->sli4_hba.rq_ecount = LPFC_RQE_DEF_COUNT;
6432
6433         /* Create Receive Queue for header */
6434         qdesc = lpfc_sli4_queue_alloc(phba, phba->sli4_hba.rq_esize,
6435                                       phba->sli4_hba.rq_ecount);
6436         if (!qdesc) {
6437                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6438                                 "0506 Failed allocate receive HRQ\n");
6439                 goto out_free_fcp_wq;
6440         }
6441         phba->sli4_hba.hdr_rq = qdesc;
6442
6443         /* Create Receive Queue for data */
6444         qdesc = lpfc_sli4_queue_alloc(phba, phba->sli4_hba.rq_esize,
6445                                       phba->sli4_hba.rq_ecount);
6446         if (!qdesc) {
6447                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6448                                 "0507 Failed allocate receive DRQ\n");
6449                 goto out_free_hdr_rq;
6450         }
6451         phba->sli4_hba.dat_rq = qdesc;
6452
6453         return 0;
6454
6455 out_free_hdr_rq:
6456         lpfc_sli4_queue_free(phba->sli4_hba.hdr_rq);
6457         phba->sli4_hba.hdr_rq = NULL;
6458 out_free_fcp_wq:
6459         for (--fcp_wqidx; fcp_wqidx >= 0; fcp_wqidx--) {
6460                 lpfc_sli4_queue_free(phba->sli4_hba.fcp_wq[fcp_wqidx]);
6461                 phba->sli4_hba.fcp_wq[fcp_wqidx] = NULL;
6462         }
6463         kfree(phba->sli4_hba.fcp_wq);
6464 out_free_els_wq:
6465         lpfc_sli4_queue_free(phba->sli4_hba.els_wq);
6466         phba->sli4_hba.els_wq = NULL;
6467 out_free_mbx_wq:
6468         lpfc_sli4_queue_free(phba->sli4_hba.mbx_wq);
6469         phba->sli4_hba.mbx_wq = NULL;
6470 out_free_fcp_cq:
6471         for (--fcp_cqidx; fcp_cqidx >= 0; fcp_cqidx--) {
6472                 lpfc_sli4_queue_free(phba->sli4_hba.fcp_cq[fcp_cqidx]);
6473                 phba->sli4_hba.fcp_cq[fcp_cqidx] = NULL;
6474         }
6475         kfree(phba->sli4_hba.fcp_cq);
6476 out_free_els_cq:
6477         lpfc_sli4_queue_free(phba->sli4_hba.els_cq);
6478         phba->sli4_hba.els_cq = NULL;
6479 out_free_mbx_cq:
6480         lpfc_sli4_queue_free(phba->sli4_hba.mbx_cq);
6481         phba->sli4_hba.mbx_cq = NULL;
6482 out_free_fp_eq:
6483         for (--fcp_eqidx; fcp_eqidx >= 0; fcp_eqidx--) {
6484                 lpfc_sli4_queue_free(phba->sli4_hba.fp_eq[fcp_eqidx]);
6485                 phba->sli4_hba.fp_eq[fcp_eqidx] = NULL;
6486         }
6487         kfree(phba->sli4_hba.fp_eq);
6488 out_free_sp_eq:
6489         lpfc_sli4_queue_free(phba->sli4_hba.sp_eq);
6490         phba->sli4_hba.sp_eq = NULL;
6491 out_error:
6492         return -ENOMEM;
6493 }
6494
6495 /**
6496  * lpfc_sli4_queue_destroy - Destroy all the SLI4 queues
6497  * @phba: pointer to lpfc hba data structure.
6498  *
6499  * This routine is invoked to release all the SLI4 queues with the FCoE HBA
6500  * operation.
6501  *
6502  * Return codes
6503  *      0 - successful
6504  *      -ENOMEM - No available memory
6505  *      -EIO - The mailbox failed to complete successfully.
6506  **/
6507 void
6508 lpfc_sli4_queue_destroy(struct lpfc_hba *phba)
6509 {
6510         int fcp_qidx;
6511
6512         /* Release mailbox command work queue */
6513         lpfc_sli4_queue_free(phba->sli4_hba.mbx_wq);
6514         phba->sli4_hba.mbx_wq = NULL;
6515
6516         /* Release ELS work queue */
6517         lpfc_sli4_queue_free(phba->sli4_hba.els_wq);
6518         phba->sli4_hba.els_wq = NULL;
6519
6520         /* Release FCP work queue */
6521         for (fcp_qidx = 0; fcp_qidx < phba->cfg_fcp_wq_count; fcp_qidx++)
6522                 lpfc_sli4_queue_free(phba->sli4_hba.fcp_wq[fcp_qidx]);
6523         kfree(phba->sli4_hba.fcp_wq);
6524         phba->sli4_hba.fcp_wq = NULL;
6525
6526         /* Release unsolicited receive queue */
6527         lpfc_sli4_queue_free(phba->sli4_hba.hdr_rq);
6528         phba->sli4_hba.hdr_rq = NULL;
6529         lpfc_sli4_queue_free(phba->sli4_hba.dat_rq);
6530         phba->sli4_hba.dat_rq = NULL;
6531
6532         /* Release ELS complete queue */
6533         lpfc_sli4_queue_free(phba->sli4_hba.els_cq);
6534         phba->sli4_hba.els_cq = NULL;
6535
6536         /* Release mailbox command complete queue */
6537         lpfc_sli4_queue_free(phba->sli4_hba.mbx_cq);
6538         phba->sli4_hba.mbx_cq = NULL;
6539
6540         /* Release FCP response complete queue */
6541         fcp_qidx = 0;
6542         do
6543                 lpfc_sli4_queue_free(phba->sli4_hba.fcp_cq[fcp_qidx]);
6544         while (++fcp_qidx < phba->cfg_fcp_eq_count);
6545         kfree(phba->sli4_hba.fcp_cq);
6546         phba->sli4_hba.fcp_cq = NULL;
6547
6548         /* Release fast-path event queue */
6549         for (fcp_qidx = 0; fcp_qidx < phba->cfg_fcp_eq_count; fcp_qidx++)
6550                 lpfc_sli4_queue_free(phba->sli4_hba.fp_eq[fcp_qidx]);
6551         kfree(phba->sli4_hba.fp_eq);
6552         phba->sli4_hba.fp_eq = NULL;
6553
6554         /* Release slow-path event queue */
6555         lpfc_sli4_queue_free(phba->sli4_hba.sp_eq);
6556         phba->sli4_hba.sp_eq = NULL;
6557
6558         return;
6559 }
6560
6561 /**
6562  * lpfc_sli4_queue_setup - Set up all the SLI4 queues
6563  * @phba: pointer to lpfc hba data structure.
6564  *
6565  * This routine is invoked to set up all the SLI4 queues for the FCoE HBA
6566  * operation.
6567  *
6568  * Return codes
6569  *      0 - successful
6570  *      -ENOMEM - No available memory
6571  *      -EIO - The mailbox failed to complete successfully.
6572  **/
6573 int
6574 lpfc_sli4_queue_setup(struct lpfc_hba *phba)
6575 {
6576         int rc = -ENOMEM;
6577         int fcp_eqidx, fcp_cqidx, fcp_wqidx;
6578         int fcp_cq_index = 0;
6579
6580         /*
6581          * Set up Event Queues (EQs)
6582          */
6583
6584         /* Set up slow-path event queue */
6585         if (!phba->sli4_hba.sp_eq) {
6586                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6587                                 "0520 Slow-path EQ not allocated\n");
6588                 goto out_error;
6589         }
6590         rc = lpfc_eq_create(phba, phba->sli4_hba.sp_eq,
6591                             LPFC_SP_DEF_IMAX);
6592         if (rc) {
6593                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6594                                 "0521 Failed setup of slow-path EQ: "
6595                                 "rc = 0x%x\n", rc);
6596                 goto out_error;
6597         }
6598         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
6599                         "2583 Slow-path EQ setup: queue-id=%d\n",
6600                         phba->sli4_hba.sp_eq->queue_id);
6601
6602         /* Set up fast-path event queue */
6603         for (fcp_eqidx = 0; fcp_eqidx < phba->cfg_fcp_eq_count; fcp_eqidx++) {
6604                 if (!phba->sli4_hba.fp_eq[fcp_eqidx]) {
6605                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6606                                         "0522 Fast-path EQ (%d) not "
6607                                         "allocated\n", fcp_eqidx);
6608                         goto out_destroy_fp_eq;
6609                 }
6610                 rc = lpfc_eq_create(phba, phba->sli4_hba.fp_eq[fcp_eqidx],
6611                                     phba->cfg_fcp_imax);
6612                 if (rc) {
6613                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6614                                         "0523 Failed setup of fast-path EQ "
6615                                         "(%d), rc = 0x%x\n", fcp_eqidx, rc);
6616                         goto out_destroy_fp_eq;
6617                 }
6618                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
6619                                 "2584 Fast-path EQ setup: "
6620                                 "queue[%d]-id=%d\n", fcp_eqidx,
6621                                 phba->sli4_hba.fp_eq[fcp_eqidx]->queue_id);
6622         }
6623
6624         /*
6625          * Set up Complete Queues (CQs)
6626          */
6627
6628         /* Set up slow-path MBOX Complete Queue as the first CQ */
6629         if (!phba->sli4_hba.mbx_cq) {
6630                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6631                                 "0528 Mailbox CQ not allocated\n");
6632                 goto out_destroy_fp_eq;
6633         }
6634         rc = lpfc_cq_create(phba, phba->sli4_hba.mbx_cq, phba->sli4_hba.sp_eq,
6635                             LPFC_MCQ, LPFC_MBOX);
6636         if (rc) {
6637                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6638                                 "0529 Failed setup of slow-path mailbox CQ: "
6639                                 "rc = 0x%x\n", rc);
6640                 goto out_destroy_fp_eq;
6641         }
6642         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
6643                         "2585 MBX CQ setup: cq-id=%d, parent eq-id=%d\n",
6644                         phba->sli4_hba.mbx_cq->queue_id,
6645                         phba->sli4_hba.sp_eq->queue_id);
6646
6647         /* Set up slow-path ELS Complete Queue */
6648         if (!phba->sli4_hba.els_cq) {
6649                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6650                                 "0530 ELS CQ not allocated\n");
6651                 goto out_destroy_mbx_cq;
6652         }
6653         rc = lpfc_cq_create(phba, phba->sli4_hba.els_cq, phba->sli4_hba.sp_eq,
6654                             LPFC_WCQ, LPFC_ELS);
6655         if (rc) {
6656                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6657                                 "0531 Failed setup of slow-path ELS CQ: "
6658                                 "rc = 0x%x\n", rc);
6659                 goto out_destroy_mbx_cq;
6660         }
6661         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
6662                         "2586 ELS CQ setup: cq-id=%d, parent eq-id=%d\n",
6663                         phba->sli4_hba.els_cq->queue_id,
6664                         phba->sli4_hba.sp_eq->queue_id);
6665
6666         /* Set up fast-path FCP Response Complete Queue */
6667         fcp_cqidx = 0;
6668         do {
6669                 if (!phba->sli4_hba.fcp_cq[fcp_cqidx]) {
6670                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6671                                         "0526 Fast-path FCP CQ (%d) not "
6672                                         "allocated\n", fcp_cqidx);
6673                         goto out_destroy_fcp_cq;
6674                 }
6675                 if (phba->cfg_fcp_eq_count)
6676                         rc = lpfc_cq_create(phba,
6677                                             phba->sli4_hba.fcp_cq[fcp_cqidx],
6678                                             phba->sli4_hba.fp_eq[fcp_cqidx],
6679                                             LPFC_WCQ, LPFC_FCP);
6680                 else
6681                         rc = lpfc_cq_create(phba,
6682                                             phba->sli4_hba.fcp_cq[fcp_cqidx],
6683                                             phba->sli4_hba.sp_eq,
6684                                             LPFC_WCQ, LPFC_FCP);
6685                 if (rc) {
6686                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6687                                         "0527 Failed setup of fast-path FCP "
6688                                         "CQ (%d), rc = 0x%x\n", fcp_cqidx, rc);
6689                         goto out_destroy_fcp_cq;
6690                 }
6691                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
6692                                 "2588 FCP CQ setup: cq[%d]-id=%d, "
6693                                 "parent %seq[%d]-id=%d\n",
6694                                 fcp_cqidx,
6695                                 phba->sli4_hba.fcp_cq[fcp_cqidx]->queue_id,
6696                                 (phba->cfg_fcp_eq_count) ? "" : "sp_",
6697                                 fcp_cqidx,
6698                                 (phba->cfg_fcp_eq_count) ?
6699                                    phba->sli4_hba.fp_eq[fcp_cqidx]->queue_id :
6700                                    phba->sli4_hba.sp_eq->queue_id);
6701         } while (++fcp_cqidx < phba->cfg_fcp_eq_count);
6702
6703         /*
6704          * Set up all the Work Queues (WQs)
6705          */
6706
6707         /* Set up Mailbox Command Queue */
6708         if (!phba->sli4_hba.mbx_wq) {
6709                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6710                                 "0538 Slow-path MQ not allocated\n");
6711                 goto out_destroy_fcp_cq;
6712         }
6713         rc = lpfc_mq_create(phba, phba->sli4_hba.mbx_wq,
6714                             phba->sli4_hba.mbx_cq, LPFC_MBOX);
6715         if (rc) {
6716                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6717                                 "0539 Failed setup of slow-path MQ: "
6718                                 "rc = 0x%x\n", rc);
6719                 goto out_destroy_fcp_cq;
6720         }
6721         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
6722                         "2589 MBX MQ setup: wq-id=%d, parent cq-id=%d\n",
6723                         phba->sli4_hba.mbx_wq->queue_id,
6724                         phba->sli4_hba.mbx_cq->queue_id);
6725
6726         /* Set up slow-path ELS Work Queue */
6727         if (!phba->sli4_hba.els_wq) {
6728                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6729                                 "0536 Slow-path ELS WQ not allocated\n");
6730                 goto out_destroy_mbx_wq;
6731         }
6732         rc = lpfc_wq_create(phba, phba->sli4_hba.els_wq,
6733                             phba->sli4_hba.els_cq, LPFC_ELS);
6734         if (rc) {
6735                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6736                                 "0537 Failed setup of slow-path ELS WQ: "
6737                                 "rc = 0x%x\n", rc);
6738                 goto out_destroy_mbx_wq;
6739         }
6740         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
6741                         "2590 ELS WQ setup: wq-id=%d, parent cq-id=%d\n",
6742                         phba->sli4_hba.els_wq->queue_id,
6743                         phba->sli4_hba.els_cq->queue_id);
6744
6745         /* Set up fast-path FCP Work Queue */
6746         for (fcp_wqidx = 0; fcp_wqidx < phba->cfg_fcp_wq_count; fcp_wqidx++) {
6747                 if (!phba->sli4_hba.fcp_wq[fcp_wqidx]) {
6748                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6749                                         "0534 Fast-path FCP WQ (%d) not "
6750                                         "allocated\n", fcp_wqidx);
6751                         goto out_destroy_fcp_wq;
6752                 }
6753                 rc = lpfc_wq_create(phba, phba->sli4_hba.fcp_wq[fcp_wqidx],
6754                                     phba->sli4_hba.fcp_cq[fcp_cq_index],
6755                                     LPFC_FCP);
6756                 if (rc) {
6757                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6758                                         "0535 Failed setup of fast-path FCP "
6759                                         "WQ (%d), rc = 0x%x\n", fcp_wqidx, rc);
6760                         goto out_destroy_fcp_wq;
6761                 }
6762                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
6763                                 "2591 FCP WQ setup: wq[%d]-id=%d, "
6764                                 "parent cq[%d]-id=%d\n",
6765                                 fcp_wqidx,
6766                                 phba->sli4_hba.fcp_wq[fcp_wqidx]->queue_id,
6767                                 fcp_cq_index,
6768                                 phba->sli4_hba.fcp_cq[fcp_cq_index]->queue_id);
6769                 /* Round robin FCP Work Queue's Completion Queue assignment */
6770                 if (phba->cfg_fcp_eq_count)
6771                         fcp_cq_index = ((fcp_cq_index + 1) %
6772                                         phba->cfg_fcp_eq_count);
6773         }
6774
6775         /*
6776          * Create Receive Queue (RQ)
6777          */
6778         if (!phba->sli4_hba.hdr_rq || !phba->sli4_hba.dat_rq) {
6779                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6780                                 "0540 Receive Queue not allocated\n");
6781                 goto out_destroy_fcp_wq;
6782         }
6783
6784         lpfc_rq_adjust_repost(phba, phba->sli4_hba.hdr_rq, LPFC_ELS_HBQ);
6785         lpfc_rq_adjust_repost(phba, phba->sli4_hba.dat_rq, LPFC_ELS_HBQ);
6786
6787         rc = lpfc_rq_create(phba, phba->sli4_hba.hdr_rq, phba->sli4_hba.dat_rq,
6788                             phba->sli4_hba.els_cq, LPFC_USOL);
6789         if (rc) {
6790                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6791                                 "0541 Failed setup of Receive Queue: "
6792                                 "rc = 0x%x\n", rc);
6793                 goto out_destroy_fcp_wq;
6794         }
6795
6796         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
6797                         "2592 USL RQ setup: hdr-rq-id=%d, dat-rq-id=%d "
6798                         "parent cq-id=%d\n",
6799                         phba->sli4_hba.hdr_rq->queue_id,
6800                         phba->sli4_hba.dat_rq->queue_id,
6801                         phba->sli4_hba.els_cq->queue_id);
6802         return 0;
6803
6804 out_destroy_fcp_wq:
6805         for (--fcp_wqidx; fcp_wqidx >= 0; fcp_wqidx--)
6806                 lpfc_wq_destroy(phba, phba->sli4_hba.fcp_wq[fcp_wqidx]);
6807         lpfc_wq_destroy(phba, phba->sli4_hba.els_wq);
6808 out_destroy_mbx_wq:
6809         lpfc_mq_destroy(phba, phba->sli4_hba.mbx_wq);
6810 out_destroy_fcp_cq:
6811         for (--fcp_cqidx; fcp_cqidx >= 0; fcp_cqidx--)
6812                 lpfc_cq_destroy(phba, phba->sli4_hba.fcp_cq[fcp_cqidx]);
6813         lpfc_cq_destroy(phba, phba->sli4_hba.els_cq);
6814 out_destroy_mbx_cq:
6815         lpfc_cq_destroy(phba, phba->sli4_hba.mbx_cq);
6816 out_destroy_fp_eq:
6817         for (--fcp_eqidx; fcp_eqidx >= 0; fcp_eqidx--)
6818                 lpfc_eq_destroy(phba, phba->sli4_hba.fp_eq[fcp_eqidx]);
6819         lpfc_eq_destroy(phba, phba->sli4_hba.sp_eq);
6820 out_error:
6821         return rc;
6822 }
6823
6824 /**
6825  * lpfc_sli4_queue_unset - Unset all the SLI4 queues
6826  * @phba: pointer to lpfc hba data structure.
6827  *
6828  * This routine is invoked to unset all the SLI4 queues with the FCoE HBA
6829  * operation.
6830  *
6831  * Return codes
6832  *      0 - successful
6833  *      -ENOMEM - No available memory
6834  *      -EIO - The mailbox failed to complete successfully.
6835  **/
6836 void
6837 lpfc_sli4_queue_unset(struct lpfc_hba *phba)
6838 {
6839         int fcp_qidx;
6840
6841         /* Unset mailbox command work queue */
6842         lpfc_mq_destroy(phba, phba->sli4_hba.mbx_wq);
6843         /* Unset ELS work queue */
6844         lpfc_wq_destroy(phba, phba->sli4_hba.els_wq);
6845         /* Unset unsolicited receive queue */
6846         lpfc_rq_destroy(phba, phba->sli4_hba.hdr_rq, phba->sli4_hba.dat_rq);
6847         /* Unset FCP work queue */
6848         for (fcp_qidx = 0; fcp_qidx < phba->cfg_fcp_wq_count; fcp_qidx++)
6849                 lpfc_wq_destroy(phba, phba->sli4_hba.fcp_wq[fcp_qidx]);
6850         /* Unset mailbox command complete queue */
6851         lpfc_cq_destroy(phba, phba->sli4_hba.mbx_cq);
6852         /* Unset ELS complete queue */
6853         lpfc_cq_destroy(phba, phba->sli4_hba.els_cq);
6854         /* Unset FCP response complete queue */
6855         fcp_qidx = 0;
6856         do {
6857                 lpfc_cq_destroy(phba, phba->sli4_hba.fcp_cq[fcp_qidx]);
6858         } while (++fcp_qidx < phba->cfg_fcp_eq_count);
6859         /* Unset fast-path event queue */
6860         for (fcp_qidx = 0; fcp_qidx < phba->cfg_fcp_eq_count; fcp_qidx++)
6861                 lpfc_eq_destroy(phba, phba->sli4_hba.fp_eq[fcp_qidx]);
6862         /* Unset slow-path event queue */
6863         lpfc_eq_destroy(phba, phba->sli4_hba.sp_eq);
6864 }
6865
6866 /**
6867  * lpfc_sli4_cq_event_pool_create - Create completion-queue event free pool
6868  * @phba: pointer to lpfc hba data structure.
6869  *
6870  * This routine is invoked to allocate and set up a pool of completion queue
6871  * events. The body of the completion queue event is a completion queue entry
6872  * CQE. For now, this pool is used for the interrupt service routine to queue
6873  * the following HBA completion queue events for the worker thread to process:
6874  *   - Mailbox asynchronous events
6875  *   - Receive queue completion unsolicited events
6876  * Later, this can be used for all the slow-path events.
6877  *
6878  * Return codes
6879  *      0 - successful
6880  *      -ENOMEM - No available memory
6881  **/
6882 static int
6883 lpfc_sli4_cq_event_pool_create(struct lpfc_hba *phba)
6884 {
6885         struct lpfc_cq_event *cq_event;
6886         int i;
6887
6888         for (i = 0; i < (4 * phba->sli4_hba.cq_ecount); i++) {
6889                 cq_event = kmalloc(sizeof(struct lpfc_cq_event), GFP_KERNEL);
6890                 if (!cq_event)
6891                         goto out_pool_create_fail;
6892                 list_add_tail(&cq_event->list,
6893                               &phba->sli4_hba.sp_cqe_event_pool);
6894         }
6895         return 0;
6896
6897 out_pool_create_fail:
6898         lpfc_sli4_cq_event_pool_destroy(phba);
6899         return -ENOMEM;
6900 }
6901
6902 /**
6903  * lpfc_sli4_cq_event_pool_destroy - Free completion-queue event free pool
6904  * @phba: pointer to lpfc hba data structure.
6905  *
6906  * This routine is invoked to free the pool of completion queue events at
6907  * driver unload time. Note that, it is the responsibility of the driver
6908  * cleanup routine to free all the outstanding completion-queue events
6909  * allocated from this pool back into the pool before invoking this routine
6910  * to destroy the pool.
6911  **/
6912 static void
6913 lpfc_sli4_cq_event_pool_destroy(struct lpfc_hba *phba)
6914 {
6915         struct lpfc_cq_event *cq_event, *next_cq_event;
6916
6917         list_for_each_entry_safe(cq_event, next_cq_event,
6918                                  &phba->sli4_hba.sp_cqe_event_pool, list) {
6919                 list_del(&cq_event->list);
6920                 kfree(cq_event);
6921         }
6922 }
6923
6924 /**
6925  * __lpfc_sli4_cq_event_alloc - Allocate a completion-queue event from free pool
6926  * @phba: pointer to lpfc hba data structure.
6927  *
6928  * This routine is the lock free version of the API invoked to allocate a
6929  * completion-queue event from the free pool.
6930  *
6931  * Return: Pointer to the newly allocated completion-queue event if successful
6932  *         NULL otherwise.
6933  **/
6934 struct lpfc_cq_event *
6935 __lpfc_sli4_cq_event_alloc(struct lpfc_hba *phba)
6936 {
6937         struct lpfc_cq_event *cq_event = NULL;
6938
6939         list_remove_head(&phba->sli4_hba.sp_cqe_event_pool, cq_event,
6940                          struct lpfc_cq_event, list);
6941         return cq_event;
6942 }
6943
6944 /**
6945  * lpfc_sli4_cq_event_alloc - Allocate a completion-queue event from free pool
6946  * @phba: pointer to lpfc hba data structure.
6947  *
6948  * This routine is the lock version of the API invoked to allocate a
6949  * completion-queue event from the free pool.
6950  *
6951  * Return: Pointer to the newly allocated completion-queue event if successful
6952  *         NULL otherwise.
6953  **/
6954 struct lpfc_cq_event *
6955 lpfc_sli4_cq_event_alloc(struct lpfc_hba *phba)
6956 {
6957         struct lpfc_cq_event *cq_event;
6958         unsigned long iflags;
6959
6960         spin_lock_irqsave(&phba->hbalock, iflags);
6961         cq_event = __lpfc_sli4_cq_event_alloc(phba);
6962         spin_unlock_irqrestore(&phba->hbalock, iflags);
6963         return cq_event;
6964 }
6965
6966 /**
6967  * __lpfc_sli4_cq_event_release - Release a completion-queue event to free pool
6968  * @phba: pointer to lpfc hba data structure.
6969  * @cq_event: pointer to the completion queue event to be freed.
6970  *
6971  * This routine is the lock free version of the API invoked to release a
6972  * completion-queue event back into the free pool.
6973  **/
6974 void
6975 __lpfc_sli4_cq_event_release(struct lpfc_hba *phba,
6976                              struct lpfc_cq_event *cq_event)
6977 {
6978         list_add_tail(&cq_event->list, &phba->sli4_hba.sp_cqe_event_pool);
6979 }
6980
6981 /**
6982  * lpfc_sli4_cq_event_release - Release a completion-queue event to free pool
6983  * @phba: pointer to lpfc hba data structure.
6984  * @cq_event: pointer to the completion queue event to be freed.
6985  *
6986  * This routine is the lock version of the API invoked to release a
6987  * completion-queue event back into the free pool.
6988  **/
6989 void
6990 lpfc_sli4_cq_event_release(struct lpfc_hba *phba,
6991                            struct lpfc_cq_event *cq_event)
6992 {
6993         unsigned long iflags;
6994         spin_lock_irqsave(&phba->hbalock, iflags);
6995         __lpfc_sli4_cq_event_release(phba, cq_event);
6996         spin_unlock_irqrestore(&phba->hbalock, iflags);
6997 }
6998
6999 /**
7000  * lpfc_sli4_cq_event_release_all - Release all cq events to the free pool
7001  * @phba: pointer to lpfc hba data structure.
7002  *
7003  * This routine is to free all the pending completion-queue events to the
7004  * back into the free pool for device reset.
7005  **/
7006 static void
7007 lpfc_sli4_cq_event_release_all(struct lpfc_hba *phba)
7008 {
7009         LIST_HEAD(cqelist);
7010         struct lpfc_cq_event *cqe;
7011         unsigned long iflags;
7012
7013         /* Retrieve all the pending WCQEs from pending WCQE lists */
7014         spin_lock_irqsave(&phba->hbalock, iflags);
7015         /* Pending FCP XRI abort events */
7016         list_splice_init(&phba->sli4_hba.sp_fcp_xri_aborted_work_queue,
7017                          &cqelist);
7018         /* Pending ELS XRI abort events */
7019         list_splice_init(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
7020                          &cqelist);
7021         /* Pending asynnc events */
7022         list_splice_init(&phba->sli4_hba.sp_asynce_work_queue,
7023                          &cqelist);
7024         spin_unlock_irqrestore(&phba->hbalock, iflags);
7025
7026         while (!list_empty(&cqelist)) {
7027                 list_remove_head(&cqelist, cqe, struct lpfc_cq_event, list);
7028                 lpfc_sli4_cq_event_release(phba, cqe);
7029         }
7030 }
7031
7032 /**
7033  * lpfc_pci_function_reset - Reset pci function.
7034  * @phba: pointer to lpfc hba data structure.
7035  *
7036  * This routine is invoked to request a PCI function reset. It will destroys
7037  * all resources assigned to the PCI function which originates this request.
7038  *
7039  * Return codes
7040  *      0 - successful
7041  *      -ENOMEM - No available memory
7042  *      -EIO - The mailbox failed to complete successfully.
7043  **/
7044 int
7045 lpfc_pci_function_reset(struct lpfc_hba *phba)
7046 {
7047         LPFC_MBOXQ_t *mboxq;
7048         uint32_t rc = 0, if_type;
7049         uint32_t shdr_status, shdr_add_status;
7050         uint32_t rdy_chk, num_resets = 0, reset_again = 0;
7051         union lpfc_sli4_cfg_shdr *shdr;
7052         struct lpfc_register reg_data;
7053
7054         if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
7055         switch (if_type) {
7056         case LPFC_SLI_INTF_IF_TYPE_0:
7057                 mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
7058                                                        GFP_KERNEL);
7059                 if (!mboxq) {
7060                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7061                                         "0494 Unable to allocate memory for "
7062                                         "issuing SLI_FUNCTION_RESET mailbox "
7063                                         "command\n");
7064                         return -ENOMEM;
7065                 }
7066
7067                 /* Setup PCI function reset mailbox-ioctl command */
7068                 lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
7069                                  LPFC_MBOX_OPCODE_FUNCTION_RESET, 0,
7070                                  LPFC_SLI4_MBX_EMBED);
7071                 rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7072                 shdr = (union lpfc_sli4_cfg_shdr *)
7073                         &mboxq->u.mqe.un.sli4_config.header.cfg_shdr;
7074                 shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
7075                 shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
7076                                          &shdr->response);
7077                 if (rc != MBX_TIMEOUT)
7078                         mempool_free(mboxq, phba->mbox_mem_pool);
7079                 if (shdr_status || shdr_add_status || rc) {
7080                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7081                                         "0495 SLI_FUNCTION_RESET mailbox "
7082                                         "failed with status x%x add_status x%x,"
7083                                         " mbx status x%x\n",
7084                                         shdr_status, shdr_add_status, rc);
7085                         rc = -ENXIO;
7086                 }
7087                 break;
7088         case LPFC_SLI_INTF_IF_TYPE_2:
7089                 for (num_resets = 0;
7090                      num_resets < MAX_IF_TYPE_2_RESETS;
7091                      num_resets++) {
7092                         reg_data.word0 = 0;
7093                         bf_set(lpfc_sliport_ctrl_end, &reg_data,
7094                                LPFC_SLIPORT_LITTLE_ENDIAN);
7095                         bf_set(lpfc_sliport_ctrl_ip, &reg_data,
7096                                LPFC_SLIPORT_INIT_PORT);
7097                         writel(reg_data.word0, phba->sli4_hba.u.if_type2.
7098                                CTRLregaddr);
7099
7100                         /*
7101                          * Poll the Port Status Register and wait for RDY for
7102                          * up to 10 seconds.  If the port doesn't respond, treat
7103                          * it as an error.  If the port responds with RN, start
7104                          * the loop again.
7105                          */
7106                         for (rdy_chk = 0; rdy_chk < 1000; rdy_chk++) {
7107                                 msleep(10);
7108                                 if (lpfc_readl(phba->sli4_hba.u.if_type2.
7109                                               STATUSregaddr, &reg_data.word0)) {
7110                                         rc = -ENODEV;
7111                                         goto out;
7112                                 }
7113                                 if (bf_get(lpfc_sliport_status_rdy, &reg_data))
7114                                         break;
7115                                 if (bf_get(lpfc_sliport_status_rn, &reg_data)) {
7116                                         reset_again++;
7117                                         break;
7118                                 }
7119                         }
7120
7121                         /*
7122                          * If the port responds to the init request with
7123                          * reset needed, delay for a bit and restart the loop.
7124                          */
7125                         if (reset_again) {
7126                                 msleep(10);
7127                                 reset_again = 0;
7128                                 continue;
7129                         }
7130
7131                         /* Detect any port errors. */
7132                         if ((bf_get(lpfc_sliport_status_err, &reg_data)) ||
7133                             (rdy_chk >= 1000)) {
7134                                 phba->work_status[0] = readl(
7135                                         phba->sli4_hba.u.if_type2.ERR1regaddr);
7136                                 phba->work_status[1] = readl(
7137                                         phba->sli4_hba.u.if_type2.ERR2regaddr);
7138                                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7139                                         "2890 Port Error Detected "
7140                                         "during Port Reset: "
7141                                         "port status reg 0x%x, "
7142                                         "error 1=0x%x, error 2=0x%x\n",
7143                                         reg_data.word0,
7144                                         phba->work_status[0],
7145                                         phba->work_status[1]);
7146                                 rc = -ENODEV;
7147                         }
7148
7149                         /*
7150                          * Terminate the outer loop provided the Port indicated
7151                          * ready within 10 seconds.
7152                          */
7153                         if (rdy_chk < 1000)
7154                                 break;
7155                 }
7156                 /* delay driver action following IF_TYPE_2 function reset */
7157                 msleep(100);
7158                 break;
7159         case LPFC_SLI_INTF_IF_TYPE_1:
7160         default:
7161                 break;
7162         }
7163
7164 out:
7165         /* Catch the not-ready port failure after a port reset. */
7166         if (num_resets >= MAX_IF_TYPE_2_RESETS)
7167                 rc = -ENODEV;
7168
7169         return rc;
7170 }
7171
7172 /**
7173  * lpfc_sli4_send_nop_mbox_cmds - Send sli-4 nop mailbox commands
7174  * @phba: pointer to lpfc hba data structure.
7175  * @cnt: number of nop mailbox commands to send.
7176  *
7177  * This routine is invoked to send a number @cnt of NOP mailbox command and
7178  * wait for each command to complete.
7179  *
7180  * Return: the number of NOP mailbox command completed.
7181  **/
7182 static int
7183 lpfc_sli4_send_nop_mbox_cmds(struct lpfc_hba *phba, uint32_t cnt)
7184 {
7185         LPFC_MBOXQ_t *mboxq;
7186         int length, cmdsent;
7187         uint32_t mbox_tmo;
7188         uint32_t rc = 0;
7189         uint32_t shdr_status, shdr_add_status;
7190         union lpfc_sli4_cfg_shdr *shdr;
7191
7192         if (cnt == 0) {
7193                 lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7194                                 "2518 Requested to send 0 NOP mailbox cmd\n");
7195                 return cnt;
7196         }
7197
7198         mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7199         if (!mboxq) {
7200                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7201                                 "2519 Unable to allocate memory for issuing "
7202                                 "NOP mailbox command\n");
7203                 return 0;
7204         }
7205
7206         /* Set up NOP SLI4_CONFIG mailbox-ioctl command */
7207         length = (sizeof(struct lpfc_mbx_nop) -
7208                   sizeof(struct lpfc_sli4_cfg_mhdr));
7209         lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
7210                          LPFC_MBOX_OPCODE_NOP, length, LPFC_SLI4_MBX_EMBED);
7211
7212         for (cmdsent = 0; cmdsent < cnt; cmdsent++) {
7213                 if (!phba->sli4_hba.intr_enable)
7214                         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7215                 else {
7216                         mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
7217                         rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
7218                 }
7219                 if (rc == MBX_TIMEOUT)
7220                         break;
7221                 /* Check return status */
7222                 shdr = (union lpfc_sli4_cfg_shdr *)
7223                         &mboxq->u.mqe.un.sli4_config.header.cfg_shdr;
7224                 shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
7225                 shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
7226                                          &shdr->response);
7227                 if (shdr_status || shdr_add_status || rc) {
7228                         lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7229                                         "2520 NOP mailbox command failed "
7230                                         "status x%x add_status x%x mbx "
7231                                         "status x%x\n", shdr_status,
7232                                         shdr_add_status, rc);
7233                         break;
7234                 }
7235         }
7236
7237         if (rc != MBX_TIMEOUT)
7238                 mempool_free(mboxq, phba->mbox_mem_pool);
7239
7240         return cmdsent;
7241 }
7242
7243 /**
7244  * lpfc_sli4_pci_mem_setup - Setup SLI4 HBA PCI memory space.
7245  * @phba: pointer to lpfc hba data structure.
7246  *
7247  * This routine is invoked to set up the PCI device memory space for device
7248  * with SLI-4 interface spec.
7249  *
7250  * Return codes
7251  *      0 - successful
7252  *      other values - error
7253  **/
7254 static int
7255 lpfc_sli4_pci_mem_setup(struct lpfc_hba *phba)
7256 {
7257         struct pci_dev *pdev;
7258         unsigned long bar0map_len, bar1map_len, bar2map_len;
7259         int error = -ENODEV;
7260         uint32_t if_type;
7261
7262         /* Obtain PCI device reference */
7263         if (!phba->pcidev)
7264                 return error;
7265         else
7266                 pdev = phba->pcidev;
7267
7268         /* Set the device DMA mask size */
7269         if (pci_set_dma_mask(pdev, DMA_BIT_MASK(64)) != 0
7270          || pci_set_consistent_dma_mask(pdev,DMA_BIT_MASK(64)) != 0) {
7271                 if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32)) != 0
7272                  || pci_set_consistent_dma_mask(pdev,DMA_BIT_MASK(32)) != 0) {
7273                         return error;
7274                 }
7275         }
7276
7277         /*
7278          * The BARs and register set definitions and offset locations are
7279          * dependent on the if_type.
7280          */
7281         if (pci_read_config_dword(pdev, LPFC_SLI_INTF,
7282                                   &phba->sli4_hba.sli_intf.word0)) {
7283                 return error;
7284         }
7285
7286         /* There is no SLI3 failback for SLI4 devices. */
7287         if (bf_get(lpfc_sli_intf_valid, &phba->sli4_hba.sli_intf) !=
7288             LPFC_SLI_INTF_VALID) {
7289                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7290                                 "2894 SLI_INTF reg contents invalid "
7291                                 "sli_intf reg 0x%x\n",
7292                                 phba->sli4_hba.sli_intf.word0);
7293                 return error;
7294         }
7295
7296         if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
7297         /*
7298          * Get the bus address of SLI4 device Bar regions and the
7299          * number of bytes required by each mapping. The mapping of the
7300          * particular PCI BARs regions is dependent on the type of
7301          * SLI4 device.
7302          */
7303         if (pci_resource_start(pdev, 0)) {
7304                 phba->pci_bar0_map = pci_resource_start(pdev, 0);
7305                 bar0map_len = pci_resource_len(pdev, 0);
7306
7307                 /*
7308                  * Map SLI4 PCI Config Space Register base to a kernel virtual
7309                  * addr
7310                  */
7311                 phba->sli4_hba.conf_regs_memmap_p =
7312                         ioremap(phba->pci_bar0_map, bar0map_len);
7313                 if (!phba->sli4_hba.conf_regs_memmap_p) {
7314                         dev_printk(KERN_ERR, &pdev->dev,
7315                                    "ioremap failed for SLI4 PCI config "
7316                                    "registers.\n");
7317                         goto out;
7318                 }
7319                 /* Set up BAR0 PCI config space register memory map */
7320                 lpfc_sli4_bar0_register_memmap(phba, if_type);
7321         } else {
7322                 phba->pci_bar0_map = pci_resource_start(pdev, 1);
7323                 bar0map_len = pci_resource_len(pdev, 1);
7324                 if (if_type == LPFC_SLI_INTF_IF_TYPE_2) {
7325                         dev_printk(KERN_ERR, &pdev->dev,
7326                            "FATAL - No BAR0 mapping for SLI4, if_type 2\n");
7327                         goto out;
7328                 }
7329                 phba->sli4_hba.conf_regs_memmap_p =
7330                                 ioremap(phba->pci_bar0_map, bar0map_len);
7331                 if (!phba->sli4_hba.conf_regs_memmap_p) {
7332                         dev_printk(KERN_ERR, &pdev->dev,
7333                                 "ioremap failed for SLI4 PCI config "
7334                                 "registers.\n");
7335                                 goto out;
7336                 }
7337                 lpfc_sli4_bar0_register_memmap(phba, if_type);
7338         }
7339
7340         if ((if_type == LPFC_SLI_INTF_IF_TYPE_0) &&
7341             (pci_resource_start(pdev, 2))) {
7342                 /*
7343                  * Map SLI4 if type 0 HBA Control Register base to a kernel
7344                  * virtual address and setup the registers.
7345                  */
7346                 phba->pci_bar1_map = pci_resource_start(pdev, 2);
7347                 bar1map_len = pci_resource_len(pdev, 2);
7348                 phba->sli4_hba.ctrl_regs_memmap_p =
7349                                 ioremap(phba->pci_bar1_map, bar1map_len);
7350                 if (!phba->sli4_hba.ctrl_regs_memmap_p) {
7351                         dev_printk(KERN_ERR, &pdev->dev,
7352                            "ioremap failed for SLI4 HBA control registers.\n");
7353                         goto out_iounmap_conf;
7354                 }
7355                 lpfc_sli4_bar1_register_memmap(phba);
7356         }
7357
7358         if ((if_type == LPFC_SLI_INTF_IF_TYPE_0) &&
7359             (pci_resource_start(pdev, 4))) {
7360                 /*
7361                  * Map SLI4 if type 0 HBA Doorbell Register base to a kernel
7362                  * virtual address and setup the registers.
7363                  */
7364                 phba->pci_bar2_map = pci_resource_start(pdev, 4);
7365                 bar2map_len = pci_resource_len(pdev, 4);
7366                 phba->sli4_hba.drbl_regs_memmap_p =
7367                                 ioremap(phba->pci_bar2_map, bar2map_len);
7368                 if (!phba->sli4_hba.drbl_regs_memmap_p) {
7369                         dev_printk(KERN_ERR, &pdev->dev,
7370                            "ioremap failed for SLI4 HBA doorbell registers.\n");
7371                         goto out_iounmap_ctrl;
7372                 }
7373                 error = lpfc_sli4_bar2_register_memmap(phba, LPFC_VF0);
7374                 if (error)
7375                         goto out_iounmap_all;
7376         }
7377
7378         return 0;
7379
7380 out_iounmap_all:
7381         iounmap(phba->sli4_hba.drbl_regs_memmap_p);
7382 out_iounmap_ctrl:
7383         iounmap(phba->sli4_hba.ctrl_regs_memmap_p);
7384 out_iounmap_conf:
7385         iounmap(phba->sli4_hba.conf_regs_memmap_p);
7386 out:
7387         return error;
7388 }
7389
7390 /**
7391  * lpfc_sli4_pci_mem_unset - Unset SLI4 HBA PCI memory space.
7392  * @phba: pointer to lpfc hba data structure.
7393  *
7394  * This routine is invoked to unset the PCI device memory space for device
7395  * with SLI-4 interface spec.
7396  **/
7397 static void
7398 lpfc_sli4_pci_mem_unset(struct lpfc_hba *phba)
7399 {
7400         struct pci_dev *pdev;
7401
7402         /* Obtain PCI device reference */
7403         if (!phba->pcidev)
7404                 return;
7405         else
7406                 pdev = phba->pcidev;
7407
7408         /* Free coherent DMA memory allocated */
7409
7410         /* Unmap I/O memory space */
7411         iounmap(phba->sli4_hba.drbl_regs_memmap_p);
7412         iounmap(phba->sli4_hba.ctrl_regs_memmap_p);
7413         iounmap(phba->sli4_hba.conf_regs_memmap_p);
7414
7415         return;
7416 }
7417
7418 /**
7419  * lpfc_sli_enable_msix - Enable MSI-X interrupt mode on SLI-3 device
7420  * @phba: pointer to lpfc hba data structure.
7421  *
7422  * This routine is invoked to enable the MSI-X interrupt vectors to device
7423  * with SLI-3 interface specs. The kernel function pci_enable_msix() is
7424  * called to enable the MSI-X vectors. Note that pci_enable_msix(), once
7425  * invoked, enables either all or nothing, depending on the current
7426  * availability of PCI vector resources. The device driver is responsible
7427  * for calling the individual request_irq() to register each MSI-X vector
7428  * with a interrupt handler, which is done in this function. Note that
7429  * later when device is unloading, the driver should always call free_irq()
7430  * on all MSI-X vectors it has done request_irq() on before calling
7431  * pci_disable_msix(). Failure to do so results in a BUG_ON() and a device
7432  * will be left with MSI-X enabled and leaks its vectors.
7433  *
7434  * Return codes
7435  *   0 - successful
7436  *   other values - error
7437  **/
7438 static int
7439 lpfc_sli_enable_msix(struct lpfc_hba *phba)
7440 {
7441         int rc, i;
7442         LPFC_MBOXQ_t *pmb;
7443
7444         /* Set up MSI-X multi-message vectors */
7445         for (i = 0; i < LPFC_MSIX_VECTORS; i++)
7446                 phba->msix_entries[i].entry = i;
7447
7448         /* Configure MSI-X capability structure */
7449         rc = pci_enable_msix(phba->pcidev, phba->msix_entries,
7450                                 ARRAY_SIZE(phba->msix_entries));
7451         if (rc) {
7452                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7453                                 "0420 PCI enable MSI-X failed (%d)\n", rc);
7454                 goto msi_fail_out;
7455         }
7456         for (i = 0; i < LPFC_MSIX_VECTORS; i++)
7457                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7458                                 "0477 MSI-X entry[%d]: vector=x%x "
7459                                 "message=%d\n", i,
7460                                 phba->msix_entries[i].vector,
7461                                 phba->msix_entries[i].entry);
7462         /*
7463          * Assign MSI-X vectors to interrupt handlers
7464          */
7465
7466         /* vector-0 is associated to slow-path handler */
7467         rc = request_irq(phba->msix_entries[0].vector,
7468                          &lpfc_sli_sp_intr_handler, IRQF_SHARED,
7469                          LPFC_SP_DRIVER_HANDLER_NAME, phba);
7470         if (rc) {
7471                 lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7472                                 "0421 MSI-X slow-path request_irq failed "
7473                                 "(%d)\n", rc);
7474                 goto msi_fail_out;
7475         }
7476
7477         /* vector-1 is associated to fast-path handler */
7478         rc = request_irq(phba->msix_entries[1].vector,
7479                          &lpfc_sli_fp_intr_handler, IRQF_SHARED,
7480                          LPFC_FP_DRIVER_HANDLER_NAME, phba);
7481
7482         if (rc) {
7483                 lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7484                                 "0429 MSI-X fast-path request_irq failed "
7485                                 "(%d)\n", rc);
7486                 goto irq_fail_out;
7487         }
7488
7489         /*
7490          * Configure HBA MSI-X attention conditions to messages
7491          */
7492         pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7493
7494         if (!pmb) {
7495                 rc = -ENOMEM;
7496                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7497                                 "0474 Unable to allocate memory for issuing "
7498                                 "MBOX_CONFIG_MSI command\n");
7499                 goto mem_fail_out;
7500         }
7501         rc = lpfc_config_msi(phba, pmb);
7502         if (rc)
7503                 goto mbx_fail_out;
7504         rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
7505         if (rc != MBX_SUCCESS) {
7506                 lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX,
7507                                 "0351 Config MSI mailbox command failed, "
7508                                 "mbxCmd x%x, mbxStatus x%x\n",
7509                                 pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus);
7510                 goto mbx_fail_out;
7511         }
7512
7513         /* Free memory allocated for mailbox command */
7514         mempool_free(pmb, phba->mbox_mem_pool);
7515         return rc;
7516
7517 mbx_fail_out:
7518         /* Free memory allocated for mailbox command */
7519         mempool_free(pmb, phba->mbox_mem_pool);
7520
7521 mem_fail_out:
7522         /* free the irq already requested */
7523         free_irq(phba->msix_entries[1].vector, phba);
7524
7525 irq_fail_out:
7526         /* free the irq already requested */
7527         free_irq(phba->msix_entries[0].vector, phba);
7528
7529 msi_fail_out:
7530         /* Unconfigure MSI-X capability structure */
7531         pci_disable_msix(phba->pcidev);
7532         return rc;
7533 }
7534
7535 /**
7536  * lpfc_sli_disable_msix - Disable MSI-X interrupt mode on SLI-3 device.
7537  * @phba: pointer to lpfc hba data structure.
7538  *
7539  * This routine is invoked to release the MSI-X vectors and then disable the
7540  * MSI-X interrupt mode to device with SLI-3 interface spec.
7541  **/
7542 static void
7543 lpfc_sli_disable_msix(struct lpfc_hba *phba)
7544 {
7545         int i;
7546
7547         /* Free up MSI-X multi-message vectors */
7548         for (i = 0; i < LPFC_MSIX_VECTORS; i++)
7549                 free_irq(phba->msix_entries[i].vector, phba);
7550         /* Disable MSI-X */
7551         pci_disable_msix(phba->pcidev);
7552
7553         return;
7554 }
7555
7556 /**
7557  * lpfc_sli_enable_msi - Enable MSI interrupt mode on SLI-3 device.
7558  * @phba: pointer to lpfc hba data structure.
7559  *
7560  * This routine is invoked to enable the MSI interrupt mode to device with
7561  * SLI-3 interface spec. The kernel function pci_enable_msi() is called to
7562  * enable the MSI vector. The device driver is responsible for calling the
7563  * request_irq() to register MSI vector with a interrupt the handler, which
7564  * is done in this function.
7565  *
7566  * Return codes
7567  *      0 - successful
7568  *      other values - error
7569  */
7570 static int
7571 lpfc_sli_enable_msi(struct lpfc_hba *phba)
7572 {
7573         int rc;
7574
7575         rc = pci_enable_msi(phba->pcidev);
7576         if (!rc)
7577                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7578                                 "0462 PCI enable MSI mode success.\n");
7579         else {
7580                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7581                                 "0471 PCI enable MSI mode failed (%d)\n", rc);
7582                 return rc;
7583         }
7584
7585         rc = request_irq(phba->pcidev->irq, lpfc_sli_intr_handler,
7586                          IRQF_SHARED, LPFC_DRIVER_NAME, phba);
7587         if (rc) {
7588                 pci_disable_msi(phba->pcidev);
7589                 lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7590                                 "0478 MSI request_irq failed (%d)\n", rc);
7591         }
7592         return rc;
7593 }
7594
7595 /**
7596  * lpfc_sli_disable_msi - Disable MSI interrupt mode to SLI-3 device.
7597  * @phba: pointer to lpfc hba data structure.
7598  *
7599  * This routine is invoked to disable the MSI interrupt mode to device with
7600  * SLI-3 interface spec. The driver calls free_irq() on MSI vector it has
7601  * done request_irq() on before calling pci_disable_msi(). Failure to do so
7602  * results in a BUG_ON() and a device will be left with MSI enabled and leaks
7603  * its vector.
7604  */
7605 static void
7606 lpfc_sli_disable_msi(struct lpfc_hba *phba)
7607 {
7608         free_irq(phba->pcidev->irq, phba);
7609         pci_disable_msi(phba->pcidev);
7610         return;
7611 }
7612
7613 /**
7614  * lpfc_sli_enable_intr - Enable device interrupt to SLI-3 device.
7615  * @phba: pointer to lpfc hba data structure.
7616  *
7617  * This routine is invoked to enable device interrupt and associate driver's
7618  * interrupt handler(s) to interrupt vector(s) to device with SLI-3 interface
7619  * spec. Depends on the interrupt mode configured to the driver, the driver
7620  * will try to fallback from the configured interrupt mode to an interrupt
7621  * mode which is supported by the platform, kernel, and device in the order
7622  * of:
7623  * MSI-X -> MSI -> IRQ.
7624  *
7625  * Return codes
7626  *   0 - successful
7627  *   other values - error
7628  **/
7629 static uint32_t
7630 lpfc_sli_enable_intr(struct lpfc_hba *phba, uint32_t cfg_mode)
7631 {
7632         uint32_t intr_mode = LPFC_INTR_ERROR;
7633         int retval;
7634
7635         if (cfg_mode == 2) {
7636                 /* Need to issue conf_port mbox cmd before conf_msi mbox cmd */
7637                 retval = lpfc_sli_config_port(phba, LPFC_SLI_REV3);
7638                 if (!retval) {
7639                         /* Now, try to enable MSI-X interrupt mode */
7640                         retval = lpfc_sli_enable_msix(phba);
7641                         if (!retval) {
7642                                 /* Indicate initialization to MSI-X mode */
7643                                 phba->intr_type = MSIX;
7644                                 intr_mode = 2;
7645                         }
7646                 }
7647         }
7648
7649         /* Fallback to MSI if MSI-X initialization failed */
7650         if (cfg_mode >= 1 && phba->intr_type == NONE) {
7651                 retval = lpfc_sli_enable_msi(phba);
7652                 if (!retval) {
7653                         /* Indicate initialization to MSI mode */
7654                         phba->intr_type = MSI;
7655                         intr_mode = 1;
7656                 }
7657         }
7658
7659         /* Fallback to INTx if both MSI-X/MSI initalization failed */
7660         if (phba->intr_type == NONE) {
7661                 retval = request_irq(phba->pcidev->irq, lpfc_sli_intr_handler,
7662                                      IRQF_SHARED, LPFC_DRIVER_NAME, phba);
7663                 if (!retval) {
7664                         /* Indicate initialization to INTx mode */
7665                         phba->intr_type = INTx;
7666                         intr_mode = 0;
7667                 }
7668         }
7669         return intr_mode;
7670 }
7671
7672 /**
7673  * lpfc_sli_disable_intr - Disable device interrupt to SLI-3 device.
7674  * @phba: pointer to lpfc hba data structure.
7675  *
7676  * This routine is invoked to disable device interrupt and disassociate the
7677  * driver's interrupt handler(s) from interrupt vector(s) to device with
7678  * SLI-3 interface spec. Depending on the interrupt mode, the driver will
7679  * release the interrupt vector(s) for the message signaled interrupt.
7680  **/
7681 static void
7682 lpfc_sli_disable_intr(struct lpfc_hba *phba)
7683 {
7684         /* Disable the currently initialized interrupt mode */
7685         if (phba->intr_type == MSIX)
7686                 lpfc_sli_disable_msix(phba);
7687         else if (phba->intr_type == MSI)
7688                 lpfc_sli_disable_msi(phba);
7689         else if (phba->intr_type == INTx)
7690                 free_irq(phba->pcidev->irq, phba);
7691
7692         /* Reset interrupt management states */
7693         phba->intr_type = NONE;
7694         phba->sli.slistat.sli_intr = 0;
7695
7696         return;
7697 }
7698
7699 /**
7700  * lpfc_sli4_enable_msix - Enable MSI-X interrupt mode to SLI-4 device
7701  * @phba: pointer to lpfc hba data structure.
7702  *
7703  * This routine is invoked to enable the MSI-X interrupt vectors to device
7704  * with SLI-4 interface spec. The kernel function pci_enable_msix() is called
7705  * to enable the MSI-X vectors. Note that pci_enable_msix(), once invoked,
7706  * enables either all or nothing, depending on the current availability of
7707  * PCI vector resources. The device driver is responsible for calling the
7708  * individual request_irq() to register each MSI-X vector with a interrupt
7709  * handler, which is done in this function. Note that later when device is
7710  * unloading, the driver should always call free_irq() on all MSI-X vectors
7711  * it has done request_irq() on before calling pci_disable_msix(). Failure
7712  * to do so results in a BUG_ON() and a device will be left with MSI-X
7713  * enabled and leaks its vectors.
7714  *
7715  * Return codes
7716  * 0 - successful
7717  * other values - error
7718  **/
7719 static int
7720 lpfc_sli4_enable_msix(struct lpfc_hba *phba)
7721 {
7722         int vectors, rc, index;
7723
7724         /* Set up MSI-X multi-message vectors */
7725         for (index = 0; index < phba->sli4_hba.cfg_eqn; index++)
7726                 phba->sli4_hba.msix_entries[index].entry = index;
7727
7728         /* Configure MSI-X capability structure */
7729         vectors = phba->sli4_hba.cfg_eqn;
7730 enable_msix_vectors:
7731         rc = pci_enable_msix(phba->pcidev, phba->sli4_hba.msix_entries,
7732                              vectors);
7733         if (rc > 1) {
7734                 vectors = rc;
7735                 goto enable_msix_vectors;
7736         } else if (rc) {
7737                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7738                                 "0484 PCI enable MSI-X failed (%d)\n", rc);
7739                 goto msi_fail_out;
7740         }
7741
7742         /* Log MSI-X vector assignment */
7743         for (index = 0; index < vectors; index++)
7744                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7745                                 "0489 MSI-X entry[%d]: vector=x%x "
7746                                 "message=%d\n", index,
7747                                 phba->sli4_hba.msix_entries[index].vector,
7748                                 phba->sli4_hba.msix_entries[index].entry);
7749         /*
7750          * Assign MSI-X vectors to interrupt handlers
7751          */
7752         if (vectors > 1)
7753                 rc = request_irq(phba->sli4_hba.msix_entries[0].vector,
7754                                  &lpfc_sli4_sp_intr_handler, IRQF_SHARED,
7755                                  LPFC_SP_DRIVER_HANDLER_NAME, phba);
7756         else
7757                 /* All Interrupts need to be handled by one EQ */
7758                 rc = request_irq(phba->sli4_hba.msix_entries[0].vector,
7759                                  &lpfc_sli4_intr_handler, IRQF_SHARED,
7760                                  LPFC_DRIVER_NAME, phba);
7761         if (rc) {
7762                 lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7763                                 "0485 MSI-X slow-path request_irq failed "
7764                                 "(%d)\n", rc);
7765                 goto msi_fail_out;
7766         }
7767
7768         /* The rest of the vector(s) are associated to fast-path handler(s) */
7769         for (index = 1; index < vectors; index++) {
7770                 phba->sli4_hba.fcp_eq_hdl[index - 1].idx = index - 1;
7771                 phba->sli4_hba.fcp_eq_hdl[index - 1].phba = phba;
7772                 rc = request_irq(phba->sli4_hba.msix_entries[index].vector,
7773                                  &lpfc_sli4_fp_intr_handler, IRQF_SHARED,
7774                                  LPFC_FP_DRIVER_HANDLER_NAME,
7775                                  &phba->sli4_hba.fcp_eq_hdl[index - 1]);
7776                 if (rc) {
7777                         lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7778                                         "0486 MSI-X fast-path (%d) "
7779                                         "request_irq failed (%d)\n", index, rc);
7780                         goto cfg_fail_out;
7781                 }
7782         }
7783         phba->sli4_hba.msix_vec_nr = vectors;
7784
7785         return rc;
7786
7787 cfg_fail_out:
7788         /* free the irq already requested */
7789         for (--index; index >= 1; index--)
7790                 free_irq(phba->sli4_hba.msix_entries[index - 1].vector,
7791                          &phba->sli4_hba.fcp_eq_hdl[index - 1]);
7792
7793         /* free the irq already requested */
7794         free_irq(phba->sli4_hba.msix_entries[0].vector, phba);
7795
7796 msi_fail_out:
7797         /* Unconfigure MSI-X capability structure */
7798         pci_disable_msix(phba->pcidev);
7799         return rc;
7800 }
7801
7802 /**
7803  * lpfc_sli4_disable_msix - Disable MSI-X interrupt mode to SLI-4 device
7804  * @phba: pointer to lpfc hba data structure.
7805  *
7806  * This routine is invoked to release the MSI-X vectors and then disable the
7807  * MSI-X interrupt mode to device with SLI-4 interface spec.
7808  **/
7809 static void
7810 lpfc_sli4_disable_msix(struct lpfc_hba *phba)
7811 {
7812         int index;
7813
7814         /* Free up MSI-X multi-message vectors */
7815         free_irq(phba->sli4_hba.msix_entries[0].vector, phba);
7816
7817         for (index = 1; index < phba->sli4_hba.msix_vec_nr; index++)
7818                 free_irq(phba->sli4_hba.msix_entries[index].vector,
7819                          &phba->sli4_hba.fcp_eq_hdl[index - 1]);
7820
7821         /* Disable MSI-X */
7822         pci_disable_msix(phba->pcidev);
7823
7824         return;
7825 }
7826
7827 /**
7828  * lpfc_sli4_enable_msi - Enable MSI interrupt mode to SLI-4 device
7829  * @phba: pointer to lpfc hba data structure.
7830  *
7831  * This routine is invoked to enable the MSI interrupt mode to device with
7832  * SLI-4 interface spec. The kernel function pci_enable_msi() is called
7833  * to enable the MSI vector. The device driver is responsible for calling
7834  * the request_irq() to register MSI vector with a interrupt the handler,
7835  * which is done in this function.
7836  *
7837  * Return codes
7838  *      0 - successful
7839  *      other values - error
7840  **/
7841 static int
7842 lpfc_sli4_enable_msi(struct lpfc_hba *phba)
7843 {
7844         int rc, index;
7845
7846         rc = pci_enable_msi(phba->pcidev);
7847         if (!rc)
7848                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7849                                 "0487 PCI enable MSI mode success.\n");
7850         else {
7851                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7852                                 "0488 PCI enable MSI mode failed (%d)\n", rc);
7853                 return rc;
7854         }
7855
7856         rc = request_irq(phba->pcidev->irq, lpfc_sli4_intr_handler,
7857                          IRQF_SHARED, LPFC_DRIVER_NAME, phba);
7858         if (rc) {
7859                 pci_disable_msi(phba->pcidev);
7860                 lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7861                                 "0490 MSI request_irq failed (%d)\n", rc);
7862                 return rc;
7863         }
7864
7865         for (index = 0; index < phba->cfg_fcp_eq_count; index++) {
7866                 phba->sli4_hba.fcp_eq_hdl[index].idx = index;
7867                 phba->sli4_hba.fcp_eq_hdl[index].phba = phba;
7868         }
7869
7870         return 0;
7871 }
7872
7873 /**
7874  * lpfc_sli4_disable_msi - Disable MSI interrupt mode to SLI-4 device
7875  * @phba: pointer to lpfc hba data structure.
7876  *
7877  * This routine is invoked to disable the MSI interrupt mode to device with
7878  * SLI-4 interface spec. The driver calls free_irq() on MSI vector it has
7879  * done request_irq() on before calling pci_disable_msi(). Failure to do so
7880  * results in a BUG_ON() and a device will be left with MSI enabled and leaks
7881  * its vector.
7882  **/
7883 static void
7884 lpfc_sli4_disable_msi(struct lpfc_hba *phba)
7885 {
7886         free_irq(phba->pcidev->irq, phba);
7887         pci_disable_msi(phba->pcidev);
7888         return;
7889 }
7890
7891 /**
7892  * lpfc_sli4_enable_intr - Enable device interrupt to SLI-4 device
7893  * @phba: pointer to lpfc hba data structure.
7894  *
7895  * This routine is invoked to enable device interrupt and associate driver's
7896  * interrupt handler(s) to interrupt vector(s) to device with SLI-4
7897  * interface spec. Depends on the interrupt mode configured to the driver,
7898  * the driver will try to fallback from the configured interrupt mode to an
7899  * interrupt mode which is supported by the platform, kernel, and device in
7900  * the order of:
7901  * MSI-X -> MSI -> IRQ.
7902  *
7903  * Return codes
7904  *      0 - successful
7905  *      other values - error
7906  **/
7907 static uint32_t
7908 lpfc_sli4_enable_intr(struct lpfc_hba *phba, uint32_t cfg_mode)
7909 {
7910         uint32_t intr_mode = LPFC_INTR_ERROR;
7911         int retval, index;
7912
7913         if (cfg_mode == 2) {
7914                 /* Preparation before conf_msi mbox cmd */
7915                 retval = 0;
7916                 if (!retval) {
7917                         /* Now, try to enable MSI-X interrupt mode */
7918                         retval = lpfc_sli4_enable_msix(phba);
7919                         if (!retval) {
7920                                 /* Indicate initialization to MSI-X mode */
7921                                 phba->intr_type = MSIX;
7922                                 intr_mode = 2;
7923                         }
7924                 }
7925         }
7926
7927         /* Fallback to MSI if MSI-X initialization failed */
7928         if (cfg_mode >= 1 && phba->intr_type == NONE) {
7929                 retval = lpfc_sli4_enable_msi(phba);
7930                 if (!retval) {
7931                         /* Indicate initialization to MSI mode */
7932                         phba->intr_type = MSI;
7933                         intr_mode = 1;
7934                 }
7935         }
7936
7937         /* Fallback to INTx if both MSI-X/MSI initalization failed */
7938         if (phba->intr_type == NONE) {
7939                 retval = request_irq(phba->pcidev->irq, lpfc_sli4_intr_handler,
7940                                      IRQF_SHARED, LPFC_DRIVER_NAME, phba);
7941                 if (!retval) {
7942                         /* Indicate initialization to INTx mode */
7943                         phba->intr_type = INTx;
7944                         intr_mode = 0;
7945                         for (index = 0; index < phba->cfg_fcp_eq_count;
7946                              index++) {
7947                                 phba->sli4_hba.fcp_eq_hdl[index].idx = index;
7948                                 phba->sli4_hba.fcp_eq_hdl[index].phba = phba;
7949                         }
7950                 }
7951         }
7952         return intr_mode;
7953 }
7954
7955 /**
7956  * lpfc_sli4_disable_intr - Disable device interrupt to SLI-4 device
7957  * @phba: pointer to lpfc hba data structure.
7958  *
7959  * This routine is invoked to disable device interrupt and disassociate
7960  * the driver's interrupt handler(s) from interrupt vector(s) to device
7961  * with SLI-4 interface spec. Depending on the interrupt mode, the driver
7962  * will release the interrupt vector(s) for the message signaled interrupt.
7963  **/
7964 static void
7965 lpfc_sli4_disable_intr(struct lpfc_hba *phba)
7966 {
7967         /* Disable the currently initialized interrupt mode */
7968         if (phba->intr_type == MSIX)
7969                 lpfc_sli4_disable_msix(phba);
7970         else if (phba->intr_type == MSI)
7971                 lpfc_sli4_disable_msi(phba);
7972         else if (phba->intr_type == INTx)
7973                 free_irq(phba->pcidev->irq, phba);
7974
7975         /* Reset interrupt management states */
7976         phba->intr_type = NONE;
7977         phba->sli.slistat.sli_intr = 0;
7978
7979         return;
7980 }
7981
7982 /**
7983  * lpfc_unset_hba - Unset SLI3 hba device initialization
7984  * @phba: pointer to lpfc hba data structure.
7985  *
7986  * This routine is invoked to unset the HBA device initialization steps to
7987  * a device with SLI-3 interface spec.
7988  **/
7989 static void
7990 lpfc_unset_hba(struct lpfc_hba *phba)
7991 {
7992         struct lpfc_vport *vport = phba->pport;
7993         struct Scsi_Host  *shost = lpfc_shost_from_vport(vport);
7994
7995         spin_lock_irq(shost->host_lock);
7996         vport->load_flag |= FC_UNLOADING;
7997         spin_unlock_irq(shost->host_lock);
7998
7999         lpfc_stop_hba_timers(phba);
8000
8001         phba->pport->work_port_events = 0;
8002
8003         lpfc_sli_hba_down(phba);
8004
8005         lpfc_sli_brdrestart(phba);
8006
8007         lpfc_sli_disable_intr(phba);
8008
8009         return;
8010 }
8011
8012 /**
8013  * lpfc_sli4_unset_hba - Unset SLI4 hba device initialization.
8014  * @phba: pointer to lpfc hba data structure.
8015  *
8016  * This routine is invoked to unset the HBA device initialization steps to
8017  * a device with SLI-4 interface spec.
8018  **/
8019 static void
8020 lpfc_sli4_unset_hba(struct lpfc_hba *phba)
8021 {
8022         struct lpfc_vport *vport = phba->pport;
8023         struct Scsi_Host  *shost = lpfc_shost_from_vport(vport);
8024
8025         spin_lock_irq(shost->host_lock);
8026         vport->load_flag |= FC_UNLOADING;
8027         spin_unlock_irq(shost->host_lock);
8028
8029         phba->pport->work_port_events = 0;
8030
8031         /* Stop the SLI4 device port */
8032         lpfc_stop_port(phba);
8033
8034         lpfc_sli4_disable_intr(phba);
8035
8036         /* Reset SLI4 HBA FCoE function */
8037         lpfc_pci_function_reset(phba);
8038         lpfc_sli4_queue_destroy(phba);
8039
8040         return;
8041 }
8042
8043 /**
8044  * lpfc_sli4_xri_exchange_busy_wait - Wait for device XRI exchange busy
8045  * @phba: Pointer to HBA context object.
8046  *
8047  * This function is called in the SLI4 code path to wait for completion
8048  * of device's XRIs exchange busy. It will check the XRI exchange busy
8049  * on outstanding FCP and ELS I/Os every 10ms for up to 10 seconds; after
8050  * that, it will check the XRI exchange busy on outstanding FCP and ELS
8051  * I/Os every 30 seconds, log error message, and wait forever. Only when
8052  * all XRI exchange busy complete, the driver unload shall proceed with
8053  * invoking the function reset ioctl mailbox command to the CNA and the
8054  * the rest of the driver unload resource release.
8055  **/
8056 static void
8057 lpfc_sli4_xri_exchange_busy_wait(struct lpfc_hba *phba)
8058 {
8059         int wait_time = 0;
8060         int fcp_xri_cmpl = list_empty(&phba->sli4_hba.lpfc_abts_scsi_buf_list);
8061         int els_xri_cmpl = list_empty(&phba->sli4_hba.lpfc_abts_els_sgl_list);
8062
8063         while (!fcp_xri_cmpl || !els_xri_cmpl) {
8064                 if (wait_time > LPFC_XRI_EXCH_BUSY_WAIT_TMO) {
8065                         if (!fcp_xri_cmpl)
8066                                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8067                                                 "2877 FCP XRI exchange busy "
8068                                                 "wait time: %d seconds.\n",
8069                                                 wait_time/1000);
8070                         if (!els_xri_cmpl)
8071                                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8072                                                 "2878 ELS XRI exchange busy "
8073                                                 "wait time: %d seconds.\n",
8074                                                 wait_time/1000);
8075                         msleep(LPFC_XRI_EXCH_BUSY_WAIT_T2);
8076                         wait_time += LPFC_XRI_EXCH_BUSY_WAIT_T2;
8077                 } else {
8078                         msleep(LPFC_XRI_EXCH_BUSY_WAIT_T1);
8079                         wait_time += LPFC_XRI_EXCH_BUSY_WAIT_T1;
8080                 }
8081                 fcp_xri_cmpl =
8082                         list_empty(&phba->sli4_hba.lpfc_abts_scsi_buf_list);
8083                 els_xri_cmpl =
8084                         list_empty(&phba->sli4_hba.lpfc_abts_els_sgl_list);
8085         }
8086 }
8087
8088 /**
8089  * lpfc_sli4_hba_unset - Unset the fcoe hba
8090  * @phba: Pointer to HBA context object.
8091  *
8092  * This function is called in the SLI4 code path to reset the HBA's FCoE
8093  * function. The caller is not required to hold any lock. This routine
8094  * issues PCI function reset mailbox command to reset the FCoE function.
8095  * At the end of the function, it calls lpfc_hba_down_post function to
8096  * free any pending commands.
8097  **/
8098 static void
8099 lpfc_sli4_hba_unset(struct lpfc_hba *phba)
8100 {
8101         int wait_cnt = 0;
8102         LPFC_MBOXQ_t *mboxq;
8103         struct pci_dev *pdev = phba->pcidev;
8104
8105         lpfc_stop_hba_timers(phba);
8106         phba->sli4_hba.intr_enable = 0;
8107
8108         /*
8109          * Gracefully wait out the potential current outstanding asynchronous
8110          * mailbox command.
8111          */
8112
8113         /* First, block any pending async mailbox command from posted */
8114         spin_lock_irq(&phba->hbalock);
8115         phba->sli.sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
8116         spin_unlock_irq(&phba->hbalock);
8117         /* Now, trying to wait it out if we can */
8118         while (phba->sli.sli_flag & LPFC_SLI_MBOX_ACTIVE) {
8119                 msleep(10);
8120                 if (++wait_cnt > LPFC_ACTIVE_MBOX_WAIT_CNT)
8121                         break;
8122         }
8123         /* Forcefully release the outstanding mailbox command if timed out */
8124         if (phba->sli.sli_flag & LPFC_SLI_MBOX_ACTIVE) {
8125                 spin_lock_irq(&phba->hbalock);
8126                 mboxq = phba->sli.mbox_active;
8127                 mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
8128                 __lpfc_mbox_cmpl_put(phba, mboxq);
8129                 phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8130                 phba->sli.mbox_active = NULL;
8131                 spin_unlock_irq(&phba->hbalock);
8132         }
8133
8134         /* Abort all iocbs associated with the hba */
8135         lpfc_sli_hba_iocb_abort(phba);
8136
8137         /* Wait for completion of device XRI exchange busy */
8138         lpfc_sli4_xri_exchange_busy_wait(phba);
8139
8140         /* Disable PCI subsystem interrupt */
8141         lpfc_sli4_disable_intr(phba);
8142
8143         /* Disable SR-IOV if enabled */
8144         if (phba->cfg_sriov_nr_virtfn)
8145                 pci_disable_sriov(pdev);
8146
8147         /* Stop kthread signal shall trigger work_done one more time */
8148         kthread_stop(phba->worker_thread);
8149
8150         /* Reset SLI4 HBA FCoE function */
8151         lpfc_pci_function_reset(phba);
8152         lpfc_sli4_queue_destroy(phba);
8153
8154         /* Stop the SLI4 device port */
8155         phba->pport->work_port_events = 0;
8156 }
8157
8158  /**
8159  * lpfc_pc_sli4_params_get - Get the SLI4_PARAMS port capabilities.
8160  * @phba: Pointer to HBA context object.
8161  * @mboxq: Pointer to the mailboxq memory for the mailbox command response.
8162  *
8163  * This function is called in the SLI4 code path to read the port's
8164  * sli4 capabilities.
8165  *
8166  * This function may be be called from any context that can block-wait
8167  * for the completion.  The expectation is that this routine is called
8168  * typically from probe_one or from the online routine.
8169  **/
8170 int
8171 lpfc_pc_sli4_params_get(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
8172 {
8173         int rc;
8174         struct lpfc_mqe *mqe;
8175         struct lpfc_pc_sli4_params *sli4_params;
8176         uint32_t mbox_tmo;
8177
8178         rc = 0;
8179         mqe = &mboxq->u.mqe;
8180
8181         /* Read the port's SLI4 Parameters port capabilities */
8182         lpfc_pc_sli4_params(mboxq);
8183         if (!phba->sli4_hba.intr_enable)
8184                 rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8185         else {
8186                 mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
8187                 rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
8188         }
8189
8190         if (unlikely(rc))
8191                 return 1;
8192
8193         sli4_params = &phba->sli4_hba.pc_sli4_params;
8194         sli4_params->if_type = bf_get(if_type, &mqe->un.sli4_params);
8195         sli4_params->sli_rev = bf_get(sli_rev, &mqe->un.sli4_params);
8196         sli4_params->sli_family = bf_get(sli_family, &mqe->un.sli4_params);
8197         sli4_params->featurelevel_1 = bf_get(featurelevel_1,
8198                                              &mqe->un.sli4_params);
8199         sli4_params->featurelevel_2 = bf_get(featurelevel_2,
8200                                              &mqe->un.sli4_params);
8201         sli4_params->proto_types = mqe->un.sli4_params.word3;
8202         sli4_params->sge_supp_len = mqe->un.sli4_params.sge_supp_len;
8203         sli4_params->if_page_sz = bf_get(if_page_sz, &mqe->un.sli4_params);
8204         sli4_params->rq_db_window = bf_get(rq_db_window, &mqe->un.sli4_params);
8205         sli4_params->loopbk_scope = bf_get(loopbk_scope, &mqe->un.sli4_params);
8206         sli4_params->eq_pages_max = bf_get(eq_pages, &mqe->un.sli4_params);
8207         sli4_params->eqe_size = bf_get(eqe_size, &mqe->un.sli4_params);
8208         sli4_params->cq_pages_max = bf_get(cq_pages, &mqe->un.sli4_params);
8209         sli4_params->cqe_size = bf_get(cqe_size, &mqe->un.sli4_params);
8210         sli4_params->mq_pages_max = bf_get(mq_pages, &mqe->un.sli4_params);
8211         sli4_params->mqe_size = bf_get(mqe_size, &mqe->un.sli4_params);
8212         sli4_params->mq_elem_cnt = bf_get(mq_elem_cnt, &mqe->un.sli4_params);
8213         sli4_params->wq_pages_max = bf_get(wq_pages, &mqe->un.sli4_params);
8214         sli4_params->wqe_size = bf_get(wqe_size, &mqe->un.sli4_params);
8215         sli4_params->rq_pages_max = bf_get(rq_pages, &mqe->un.sli4_params);
8216         sli4_params->rqe_size = bf_get(rqe_size, &mqe->un.sli4_params);
8217         sli4_params->hdr_pages_max = bf_get(hdr_pages, &mqe->un.sli4_params);
8218         sli4_params->hdr_size = bf_get(hdr_size, &mqe->un.sli4_params);
8219         sli4_params->hdr_pp_align = bf_get(hdr_pp_align, &mqe->un.sli4_params);
8220         sli4_params->sgl_pages_max = bf_get(sgl_pages, &mqe->un.sli4_params);
8221         sli4_params->sgl_pp_align = bf_get(sgl_pp_align, &mqe->un.sli4_params);
8222
8223         /* Make sure that sge_supp_len can be handled by the driver */
8224         if (sli4_params->sge_supp_len > LPFC_MAX_SGE_SIZE)
8225                 sli4_params->sge_supp_len = LPFC_MAX_SGE_SIZE;
8226
8227         return rc;
8228 }
8229
8230 /**
8231  * lpfc_get_sli4_parameters - Get the SLI4 Config PARAMETERS.
8232  * @phba: Pointer to HBA context object.
8233  * @mboxq: Pointer to the mailboxq memory for the mailbox command response.
8234  *
8235  * This function is called in the SLI4 code path to read the port's
8236  * sli4 capabilities.
8237  *
8238  * This function may be be called from any context that can block-wait
8239  * for the completion.  The expectation is that this routine is called
8240  * typically from probe_one or from the online routine.
8241  **/
8242 int
8243 lpfc_get_sli4_parameters(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
8244 {
8245         int rc;
8246         struct lpfc_mqe *mqe = &mboxq->u.mqe;
8247         struct lpfc_pc_sli4_params *sli4_params;
8248         uint32_t mbox_tmo;
8249         int length;
8250         struct lpfc_sli4_parameters *mbx_sli4_parameters;
8251
8252         /*
8253          * By default, the driver assumes the SLI4 port requires RPI
8254          * header postings.  The SLI4_PARAM response will correct this
8255          * assumption.
8256          */
8257         phba->sli4_hba.rpi_hdrs_in_use = 1;
8258
8259         /* Read the port's SLI4 Config Parameters */
8260         length = (sizeof(struct lpfc_mbx_get_sli4_parameters) -
8261                   sizeof(struct lpfc_sli4_cfg_mhdr));
8262         lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
8263                          LPFC_MBOX_OPCODE_GET_SLI4_PARAMETERS,
8264                          length, LPFC_SLI4_MBX_EMBED);
8265         if (!phba->sli4_hba.intr_enable)
8266                 rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8267         else {
8268                 mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
8269                 rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
8270         }
8271         if (unlikely(rc))
8272                 return rc;
8273         sli4_params = &phba->sli4_hba.pc_sli4_params;
8274         mbx_sli4_parameters = &mqe->un.get_sli4_parameters.sli4_parameters;
8275         sli4_params->if_type = bf_get(cfg_if_type, mbx_sli4_parameters);
8276         sli4_params->sli_rev = bf_get(cfg_sli_rev, mbx_sli4_parameters);
8277         sli4_params->sli_family = bf_get(cfg_sli_family, mbx_sli4_parameters);
8278         sli4_params->featurelevel_1 = bf_get(cfg_sli_hint_1,
8279                                              mbx_sli4_parameters);
8280         sli4_params->featurelevel_2 = bf_get(cfg_sli_hint_2,
8281                                              mbx_sli4_parameters);
8282         if (bf_get(cfg_phwq, mbx_sli4_parameters))
8283                 phba->sli3_options |= LPFC_SLI4_PHWQ_ENABLED;
8284         else
8285                 phba->sli3_options &= ~LPFC_SLI4_PHWQ_ENABLED;
8286         sli4_params->sge_supp_len = mbx_sli4_parameters->sge_supp_len;
8287         sli4_params->loopbk_scope = bf_get(loopbk_scope, mbx_sli4_parameters);
8288         sli4_params->cqv = bf_get(cfg_cqv, mbx_sli4_parameters);
8289         sli4_params->mqv = bf_get(cfg_mqv, mbx_sli4_parameters);
8290         sli4_params->wqv = bf_get(cfg_wqv, mbx_sli4_parameters);
8291         sli4_params->rqv = bf_get(cfg_rqv, mbx_sli4_parameters);
8292         sli4_params->sgl_pages_max = bf_get(cfg_sgl_page_cnt,
8293                                             mbx_sli4_parameters);
8294         sli4_params->sgl_pp_align = bf_get(cfg_sgl_pp_align,
8295                                            mbx_sli4_parameters);
8296         phba->sli4_hba.extents_in_use = bf_get(cfg_ext, mbx_sli4_parameters);
8297         phba->sli4_hba.rpi_hdrs_in_use = bf_get(cfg_hdrr, mbx_sli4_parameters);
8298
8299         /* Make sure that sge_supp_len can be handled by the driver */
8300         if (sli4_params->sge_supp_len > LPFC_MAX_SGE_SIZE)
8301                 sli4_params->sge_supp_len = LPFC_MAX_SGE_SIZE;
8302
8303         return 0;
8304 }
8305
8306 /**
8307  * lpfc_pci_probe_one_s3 - PCI probe func to reg SLI-3 device to PCI subsystem.
8308  * @pdev: pointer to PCI device
8309  * @pid: pointer to PCI device identifier
8310  *
8311  * This routine is to be called to attach a device with SLI-3 interface spec
8312  * to the PCI subsystem. When an Emulex HBA with SLI-3 interface spec is
8313  * presented on PCI bus, the kernel PCI subsystem looks at PCI device-specific
8314  * information of the device and driver to see if the driver state that it can
8315  * support this kind of device. If the match is successful, the driver core
8316  * invokes this routine. If this routine determines it can claim the HBA, it
8317  * does all the initialization that it needs to do to handle the HBA properly.
8318  *
8319  * Return code
8320  *      0 - driver can claim the device
8321  *      negative value - driver can not claim the device
8322  **/
8323 static int __devinit
8324 lpfc_pci_probe_one_s3(struct pci_dev *pdev, const struct pci_device_id *pid)
8325 {
8326         struct lpfc_hba   *phba;
8327         struct lpfc_vport *vport = NULL;
8328         struct Scsi_Host  *shost = NULL;
8329         int error;
8330         uint32_t cfg_mode, intr_mode;
8331
8332         /* Allocate memory for HBA structure */
8333         phba = lpfc_hba_alloc(pdev);
8334         if (!phba)
8335                 return -ENOMEM;
8336
8337         /* Perform generic PCI device enabling operation */
8338         error = lpfc_enable_pci_dev(phba);
8339         if (error)
8340                 goto out_free_phba;
8341
8342         /* Set up SLI API function jump table for PCI-device group-0 HBAs */
8343         error = lpfc_api_table_setup(phba, LPFC_PCI_DEV_LP);
8344         if (error)
8345                 goto out_disable_pci_dev;
8346
8347         /* Set up SLI-3 specific device PCI memory space */
8348         error = lpfc_sli_pci_mem_setup(phba);
8349         if (error) {
8350                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8351                                 "1402 Failed to set up pci memory space.\n");
8352                 goto out_disable_pci_dev;
8353         }
8354
8355         /* Set up phase-1 common device driver resources */
8356         error = lpfc_setup_driver_resource_phase1(phba);
8357         if (error) {
8358                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8359                                 "1403 Failed to set up driver resource.\n");
8360                 goto out_unset_pci_mem_s3;
8361         }
8362
8363         /* Set up SLI-3 specific device driver resources */
8364         error = lpfc_sli_driver_resource_setup(phba);
8365         if (error) {
8366                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8367                                 "1404 Failed to set up driver resource.\n");
8368                 goto out_unset_pci_mem_s3;
8369         }
8370
8371         /* Initialize and populate the iocb list per host */
8372         error = lpfc_init_iocb_list(phba, LPFC_IOCB_LIST_CNT);
8373         if (error) {
8374                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8375                                 "1405 Failed to initialize iocb list.\n");
8376                 goto out_unset_driver_resource_s3;
8377         }
8378
8379         /* Set up common device driver resources */
8380         error = lpfc_setup_driver_resource_phase2(phba);
8381         if (error) {
8382                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8383                                 "1406 Failed to set up driver resource.\n");
8384                 goto out_free_iocb_list;
8385         }
8386
8387         /* Get the default values for Model Name and Description */
8388         lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
8389
8390         /* Create SCSI host to the physical port */
8391         error = lpfc_create_shost(phba);
8392         if (error) {
8393                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8394                                 "1407 Failed to create scsi host.\n");
8395                 goto out_unset_driver_resource;
8396         }
8397
8398         /* Configure sysfs attributes */
8399         vport = phba->pport;
8400         error = lpfc_alloc_sysfs_attr(vport);
8401         if (error) {
8402                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8403                                 "1476 Failed to allocate sysfs attr\n");
8404                 goto out_destroy_shost;
8405         }
8406
8407         shost = lpfc_shost_from_vport(vport); /* save shost for error cleanup */
8408         /* Now, trying to enable interrupt and bring up the device */
8409         cfg_mode = phba->cfg_use_msi;
8410         while (true) {
8411                 /* Put device to a known state before enabling interrupt */
8412                 lpfc_stop_port(phba);
8413                 /* Configure and enable interrupt */
8414                 intr_mode = lpfc_sli_enable_intr(phba, cfg_mode);
8415                 if (intr_mode == LPFC_INTR_ERROR) {
8416                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8417                                         "0431 Failed to enable interrupt.\n");
8418                         error = -ENODEV;
8419                         goto out_free_sysfs_attr;
8420                 }
8421                 /* SLI-3 HBA setup */
8422                 if (lpfc_sli_hba_setup(phba)) {
8423                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8424                                         "1477 Failed to set up hba\n");
8425                         error = -ENODEV;
8426                         goto out_remove_device;
8427                 }
8428
8429                 /* Wait 50ms for the interrupts of previous mailbox commands */
8430                 msleep(50);
8431                 /* Check active interrupts on message signaled interrupts */
8432                 if (intr_mode == 0 ||
8433                     phba->sli.slistat.sli_intr > LPFC_MSIX_VECTORS) {
8434                         /* Log the current active interrupt mode */
8435                         phba->intr_mode = intr_mode;
8436                         lpfc_log_intr_mode(phba, intr_mode);
8437                         break;
8438                 } else {
8439                         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8440                                         "0447 Configure interrupt mode (%d) "
8441                                         "failed active interrupt test.\n",
8442                                         intr_mode);
8443                         /* Disable the current interrupt mode */
8444                         lpfc_sli_disable_intr(phba);
8445                         /* Try next level of interrupt mode */
8446                         cfg_mode = --intr_mode;
8447                 }
8448         }
8449
8450         /* Perform post initialization setup */
8451         lpfc_post_init_setup(phba);
8452
8453         /* Check if there are static vports to be created. */
8454         lpfc_create_static_vport(phba);
8455
8456         return 0;
8457
8458 out_remove_device:
8459         lpfc_unset_hba(phba);
8460 out_free_sysfs_attr:
8461         lpfc_free_sysfs_attr(vport);
8462 out_destroy_shost:
8463         lpfc_destroy_shost(phba);
8464 out_unset_driver_resource:
8465         lpfc_unset_driver_resource_phase2(phba);
8466 out_free_iocb_list:
8467         lpfc_free_iocb_list(phba);
8468 out_unset_driver_resource_s3:
8469         lpfc_sli_driver_resource_unset(phba);
8470 out_unset_pci_mem_s3:
8471         lpfc_sli_pci_mem_unset(phba);
8472 out_disable_pci_dev:
8473         lpfc_disable_pci_dev(phba);
8474         if (shost)
8475                 scsi_host_put(shost);
8476 out_free_phba:
8477         lpfc_hba_free(phba);
8478         return error;
8479 }
8480
8481 /**
8482  * lpfc_pci_remove_one_s3 - PCI func to unreg SLI-3 device from PCI subsystem.
8483  * @pdev: pointer to PCI device
8484  *
8485  * This routine is to be called to disattach a device with SLI-3 interface
8486  * spec from PCI subsystem. When an Emulex HBA with SLI-3 interface spec is
8487  * removed from PCI bus, it performs all the necessary cleanup for the HBA
8488  * device to be removed from the PCI subsystem properly.
8489  **/
8490 static void __devexit
8491 lpfc_pci_remove_one_s3(struct pci_dev *pdev)
8492 {
8493         struct Scsi_Host  *shost = pci_get_drvdata(pdev);
8494         struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
8495         struct lpfc_vport **vports;
8496         struct lpfc_hba   *phba = vport->phba;
8497         int i;
8498         int bars = pci_select_bars(pdev, IORESOURCE_MEM);
8499
8500         spin_lock_irq(&phba->hbalock);
8501         vport->load_flag |= FC_UNLOADING;
8502         spin_unlock_irq(&phba->hbalock);
8503
8504         lpfc_free_sysfs_attr(vport);
8505
8506         /* Release all the vports against this physical port */
8507         vports = lpfc_create_vport_work_array(phba);
8508         if (vports != NULL)
8509                 for (i = 1; i <= phba->max_vports && vports[i] != NULL; i++)
8510                         fc_vport_terminate(vports[i]->fc_vport);
8511         lpfc_destroy_vport_work_array(phba, vports);
8512
8513         /* Remove FC host and then SCSI host with the physical port */
8514         fc_remove_host(shost);
8515         scsi_remove_host(shost);
8516         lpfc_cleanup(vport);
8517
8518         /*
8519          * Bring down the SLI Layer. This step disable all interrupts,
8520          * clears the rings, discards all mailbox commands, and resets
8521          * the HBA.
8522          */
8523
8524         /* HBA interrupt will be disabled after this call */
8525         lpfc_sli_hba_down(phba);
8526         /* Stop kthread signal shall trigger work_done one more time */
8527         kthread_stop(phba->worker_thread);
8528         /* Final cleanup of txcmplq and reset the HBA */
8529         lpfc_sli_brdrestart(phba);
8530
8531         lpfc_stop_hba_timers(phba);
8532         spin_lock_irq(&phba->hbalock);
8533         list_del_init(&vport->listentry);
8534         spin_unlock_irq(&phba->hbalock);
8535
8536         lpfc_debugfs_terminate(vport);
8537
8538         /* Disable SR-IOV if enabled */
8539         if (phba->cfg_sriov_nr_virtfn)
8540                 pci_disable_sriov(pdev);
8541
8542         /* Disable interrupt */
8543         lpfc_sli_disable_intr(phba);
8544
8545         pci_set_drvdata(pdev, NULL);
8546         scsi_host_put(shost);
8547
8548         /*
8549          * Call scsi_free before mem_free since scsi bufs are released to their
8550          * corresponding pools here.
8551          */
8552         lpfc_scsi_free(phba);
8553         lpfc_mem_free_all(phba);
8554
8555         dma_free_coherent(&pdev->dev, lpfc_sli_hbq_size(),
8556                           phba->hbqslimp.virt, phba->hbqslimp.phys);
8557
8558         /* Free resources associated with SLI2 interface */
8559         dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
8560                           phba->slim2p.virt, phba->slim2p.phys);
8561
8562         /* unmap adapter SLIM and Control Registers */
8563         iounmap(phba->ctrl_regs_memmap_p);
8564         iounmap(phba->slim_memmap_p);
8565
8566         lpfc_hba_free(phba);
8567
8568         pci_release_selected_regions(pdev, bars);
8569         pci_disable_device(pdev);
8570 }
8571
8572 /**
8573  * lpfc_pci_suspend_one_s3 - PCI func to suspend SLI-3 device for power mgmnt
8574  * @pdev: pointer to PCI device
8575  * @msg: power management message
8576  *
8577  * This routine is to be called from the kernel's PCI subsystem to support
8578  * system Power Management (PM) to device with SLI-3 interface spec. When
8579  * PM invokes this method, it quiesces the device by stopping the driver's
8580  * worker thread for the device, turning off device's interrupt and DMA,
8581  * and bring the device offline. Note that as the driver implements the
8582  * minimum PM requirements to a power-aware driver's PM support for the
8583  * suspend/resume -- all the possible PM messages (SUSPEND, HIBERNATE, FREEZE)
8584  * to the suspend() method call will be treated as SUSPEND and the driver will
8585  * fully reinitialize its device during resume() method call, the driver will
8586  * set device to PCI_D3hot state in PCI config space instead of setting it
8587  * according to the @msg provided by the PM.
8588  *
8589  * Return code
8590  *      0 - driver suspended the device
8591  *      Error otherwise
8592  **/
8593 static int
8594 lpfc_pci_suspend_one_s3(struct pci_dev *pdev, pm_message_t msg)
8595 {
8596         struct Scsi_Host *shost = pci_get_drvdata(pdev);
8597         struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
8598
8599         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8600                         "0473 PCI device Power Management suspend.\n");
8601
8602         /* Bring down the device */
8603         lpfc_offline_prep(phba);
8604         lpfc_offline(phba);
8605         kthread_stop(phba->worker_thread);
8606
8607         /* Disable interrupt from device */
8608         lpfc_sli_disable_intr(phba);
8609
8610         /* Save device state to PCI config space */
8611         pci_save_state(pdev);
8612         pci_set_power_state(pdev, PCI_D3hot);
8613
8614         return 0;
8615 }
8616
8617 /**
8618  * lpfc_pci_resume_one_s3 - PCI func to resume SLI-3 device for power mgmnt
8619  * @pdev: pointer to PCI device
8620  *
8621  * This routine is to be called from the kernel's PCI subsystem to support
8622  * system Power Management (PM) to device with SLI-3 interface spec. When PM
8623  * invokes this method, it restores the device's PCI config space state and
8624  * fully reinitializes the device and brings it online. Note that as the
8625  * driver implements the minimum PM requirements to a power-aware driver's
8626  * PM for suspend/resume -- all the possible PM messages (SUSPEND, HIBERNATE,
8627  * FREEZE) to the suspend() method call will be treated as SUSPEND and the
8628  * driver will fully reinitialize its device during resume() method call,
8629  * the device will be set to PCI_D0 directly in PCI config space before
8630  * restoring the state.
8631  *
8632  * Return code
8633  *      0 - driver suspended the device
8634  *      Error otherwise
8635  **/
8636 static int
8637 lpfc_pci_resume_one_s3(struct pci_dev *pdev)
8638 {
8639         struct Scsi_Host *shost = pci_get_drvdata(pdev);
8640         struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
8641         uint32_t intr_mode;
8642         int error;
8643
8644         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8645                         "0452 PCI device Power Management resume.\n");
8646
8647         /* Restore device state from PCI config space */
8648         pci_set_power_state(pdev, PCI_D0);
8649         pci_restore_state(pdev);
8650
8651         /*
8652          * As the new kernel behavior of pci_restore_state() API call clears
8653          * device saved_state flag, need to save the restored state again.
8654          */
8655         pci_save_state(pdev);
8656
8657         if (pdev->is_busmaster)
8658                 pci_set_master(pdev);
8659
8660         /* Startup the kernel thread for this host adapter. */
8661         phba->worker_thread = kthread_run(lpfc_do_work, phba,
8662                                         "lpfc_worker_%d", phba->brd_no);
8663         if (IS_ERR(phba->worker_thread)) {
8664                 error = PTR_ERR(phba->worker_thread);
8665                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8666                                 "0434 PM resume failed to start worker "
8667                                 "thread: error=x%x.\n", error);
8668                 return error;
8669         }
8670
8671         /* Configure and enable interrupt */
8672         intr_mode = lpfc_sli_enable_intr(phba, phba->intr_mode);
8673         if (intr_mode == LPFC_INTR_ERROR) {
8674                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8675                                 "0430 PM resume Failed to enable interrupt\n");
8676                 return -EIO;
8677         } else
8678                 phba->intr_mode = intr_mode;
8679
8680         /* Restart HBA and bring it online */
8681         lpfc_sli_brdrestart(phba);
8682         lpfc_online(phba);
8683
8684         /* Log the current active interrupt mode */
8685         lpfc_log_intr_mode(phba, phba->intr_mode);
8686
8687         return 0;
8688 }
8689
8690 /**
8691  * lpfc_sli_prep_dev_for_recover - Prepare SLI3 device for pci slot recover
8692  * @phba: pointer to lpfc hba data structure.
8693  *
8694  * This routine is called to prepare the SLI3 device for PCI slot recover. It
8695  * aborts all the outstanding SCSI I/Os to the pci device.
8696  **/
8697 static void
8698 lpfc_sli_prep_dev_for_recover(struct lpfc_hba *phba)
8699 {
8700         struct lpfc_sli *psli = &phba->sli;
8701         struct lpfc_sli_ring  *pring;
8702
8703         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8704                         "2723 PCI channel I/O abort preparing for recovery\n");
8705
8706         /*
8707          * There may be errored I/Os through HBA, abort all I/Os on txcmplq
8708          * and let the SCSI mid-layer to retry them to recover.
8709          */
8710         pring = &psli->ring[psli->fcp_ring];
8711         lpfc_sli_abort_iocb_ring(phba, pring);
8712 }
8713
8714 /**
8715  * lpfc_sli_prep_dev_for_reset - Prepare SLI3 device for pci slot reset
8716  * @phba: pointer to lpfc hba data structure.
8717  *
8718  * This routine is called to prepare the SLI3 device for PCI slot reset. It
8719  * disables the device interrupt and pci device, and aborts the internal FCP
8720  * pending I/Os.
8721  **/
8722 static void
8723 lpfc_sli_prep_dev_for_reset(struct lpfc_hba *phba)
8724 {
8725         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8726                         "2710 PCI channel disable preparing for reset\n");
8727
8728         /* Block any management I/Os to the device */
8729         lpfc_block_mgmt_io(phba);
8730
8731         /* Block all SCSI devices' I/Os on the host */
8732         lpfc_scsi_dev_block(phba);
8733
8734         /* stop all timers */
8735         lpfc_stop_hba_timers(phba);
8736
8737         /* Disable interrupt and pci device */
8738         lpfc_sli_disable_intr(phba);
8739         pci_disable_device(phba->pcidev);
8740
8741         /* Flush all driver's outstanding SCSI I/Os as we are to reset */
8742         lpfc_sli_flush_fcp_rings(phba);
8743 }
8744
8745 /**
8746  * lpfc_sli_prep_dev_for_perm_failure - Prepare SLI3 dev for pci slot disable
8747  * @phba: pointer to lpfc hba data structure.
8748  *
8749  * This routine is called to prepare the SLI3 device for PCI slot permanently
8750  * disabling. It blocks the SCSI transport layer traffic and flushes the FCP
8751  * pending I/Os.
8752  **/
8753 static void
8754 lpfc_sli_prep_dev_for_perm_failure(struct lpfc_hba *phba)
8755 {
8756         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8757                         "2711 PCI channel permanent disable for failure\n");
8758         /* Block all SCSI devices' I/Os on the host */
8759         lpfc_scsi_dev_block(phba);
8760
8761         /* stop all timers */
8762         lpfc_stop_hba_timers(phba);
8763
8764         /* Clean up all driver's outstanding SCSI I/Os */
8765         lpfc_sli_flush_fcp_rings(phba);
8766 }
8767
8768 /**
8769  * lpfc_io_error_detected_s3 - Method for handling SLI-3 device PCI I/O error
8770  * @pdev: pointer to PCI device.
8771  * @state: the current PCI connection state.
8772  *
8773  * This routine is called from the PCI subsystem for I/O error handling to
8774  * device with SLI-3 interface spec. This function is called by the PCI
8775  * subsystem after a PCI bus error affecting this device has been detected.
8776  * When this function is invoked, it will need to stop all the I/Os and
8777  * interrupt(s) to the device. Once that is done, it will return
8778  * PCI_ERS_RESULT_NEED_RESET for the PCI subsystem to perform proper recovery
8779  * as desired.
8780  *
8781  * Return codes
8782  *      PCI_ERS_RESULT_CAN_RECOVER - can be recovered with reset_link
8783  *      PCI_ERS_RESULT_NEED_RESET - need to reset before recovery
8784  *      PCI_ERS_RESULT_DISCONNECT - device could not be recovered
8785  **/
8786 static pci_ers_result_t
8787 lpfc_io_error_detected_s3(struct pci_dev *pdev, pci_channel_state_t state)
8788 {
8789         struct Scsi_Host *shost = pci_get_drvdata(pdev);
8790         struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
8791
8792         switch (state) {
8793         case pci_channel_io_normal:
8794                 /* Non-fatal error, prepare for recovery */
8795                 lpfc_sli_prep_dev_for_recover(phba);
8796                 return PCI_ERS_RESULT_CAN_RECOVER;
8797         case pci_channel_io_frozen:
8798                 /* Fatal error, prepare for slot reset */
8799                 lpfc_sli_prep_dev_for_reset(phba);
8800                 return PCI_ERS_RESULT_NEED_RESET;
8801         case pci_channel_io_perm_failure:
8802                 /* Permanent failure, prepare for device down */
8803                 lpfc_sli_prep_dev_for_perm_failure(phba);
8804                 return PCI_ERS_RESULT_DISCONNECT;
8805         default:
8806                 /* Unknown state, prepare and request slot reset */
8807                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8808                                 "0472 Unknown PCI error state: x%x\n", state);
8809                 lpfc_sli_prep_dev_for_reset(phba);
8810                 return PCI_ERS_RESULT_NEED_RESET;
8811         }
8812 }
8813
8814 /**
8815  * lpfc_io_slot_reset_s3 - Method for restarting PCI SLI-3 device from scratch.
8816  * @pdev: pointer to PCI device.
8817  *
8818  * This routine is called from the PCI subsystem for error handling to
8819  * device with SLI-3 interface spec. This is called after PCI bus has been
8820  * reset to restart the PCI card from scratch, as if from a cold-boot.
8821  * During the PCI subsystem error recovery, after driver returns
8822  * PCI_ERS_RESULT_NEED_RESET, the PCI subsystem will perform proper error
8823  * recovery and then call this routine before calling the .resume method
8824  * to recover the device. This function will initialize the HBA device,
8825  * enable the interrupt, but it will just put the HBA to offline state
8826  * without passing any I/O traffic.
8827  *
8828  * Return codes
8829  *      PCI_ERS_RESULT_RECOVERED - the device has been recovered
8830  *      PCI_ERS_RESULT_DISCONNECT - device could not be recovered
8831  */
8832 static pci_ers_result_t
8833 lpfc_io_slot_reset_s3(struct pci_dev *pdev)
8834 {
8835         struct Scsi_Host *shost = pci_get_drvdata(pdev);
8836         struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
8837         struct lpfc_sli *psli = &phba->sli;
8838         uint32_t intr_mode;
8839
8840         dev_printk(KERN_INFO, &pdev->dev, "recovering from a slot reset.\n");
8841         if (pci_enable_device_mem(pdev)) {
8842                 printk(KERN_ERR "lpfc: Cannot re-enable "
8843                         "PCI device after reset.\n");
8844                 return PCI_ERS_RESULT_DISCONNECT;
8845         }
8846
8847         pci_restore_state(pdev);
8848
8849         /*
8850          * As the new kernel behavior of pci_restore_state() API call clears
8851          * device saved_state flag, need to save the restored state again.
8852          */
8853         pci_save_state(pdev);
8854
8855         if (pdev->is_busmaster)
8856                 pci_set_master(pdev);
8857
8858         spin_lock_irq(&phba->hbalock);
8859         psli->sli_flag &= ~LPFC_SLI_ACTIVE;
8860         spin_unlock_irq(&phba->hbalock);
8861
8862         /* Configure and enable interrupt */
8863         intr_mode = lpfc_sli_enable_intr(phba, phba->intr_mode);
8864         if (intr_mode == LPFC_INTR_ERROR) {
8865                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8866                                 "0427 Cannot re-enable interrupt after "
8867                                 "slot reset.\n");
8868                 return PCI_ERS_RESULT_DISCONNECT;
8869         } else
8870                 phba->intr_mode = intr_mode;
8871
8872         /* Take device offline, it will perform cleanup */
8873         lpfc_offline_prep(phba);
8874         lpfc_offline(phba);
8875         lpfc_sli_brdrestart(phba);
8876
8877         /* Log the current active interrupt mode */
8878         lpfc_log_intr_mode(phba, phba->intr_mode);
8879
8880         return PCI_ERS_RESULT_RECOVERED;
8881 }
8882
8883 /**
8884  * lpfc_io_resume_s3 - Method for resuming PCI I/O operation on SLI-3 device.
8885  * @pdev: pointer to PCI device
8886  *
8887  * This routine is called from the PCI subsystem for error handling to device
8888  * with SLI-3 interface spec. It is called when kernel error recovery tells
8889  * the lpfc driver that it is ok to resume normal PCI operation after PCI bus
8890  * error recovery. After this call, traffic can start to flow from this device
8891  * again.
8892  */
8893 static void
8894 lpfc_io_resume_s3(struct pci_dev *pdev)
8895 {
8896         struct Scsi_Host *shost = pci_get_drvdata(pdev);
8897         struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
8898
8899         /* Bring device online, it will be no-op for non-fatal error resume */
8900         lpfc_online(phba);
8901
8902         /* Clean up Advanced Error Reporting (AER) if needed */
8903         if (phba->hba_flag & HBA_AER_ENABLED)
8904                 pci_cleanup_aer_uncorrect_error_status(pdev);
8905 }
8906
8907 /**
8908  * lpfc_sli4_get_els_iocb_cnt - Calculate the # of ELS IOCBs to reserve
8909  * @phba: pointer to lpfc hba data structure.
8910  *
8911  * returns the number of ELS/CT IOCBs to reserve
8912  **/
8913 int
8914 lpfc_sli4_get_els_iocb_cnt(struct lpfc_hba *phba)
8915 {
8916         int max_xri = phba->sli4_hba.max_cfg_param.max_xri;
8917
8918         if (phba->sli_rev == LPFC_SLI_REV4) {
8919                 if (max_xri <= 100)
8920                         return 10;
8921                 else if (max_xri <= 256)
8922                         return 25;
8923                 else if (max_xri <= 512)
8924                         return 50;
8925                 else if (max_xri <= 1024)
8926                         return 100;
8927                 else
8928                         return 150;
8929         } else
8930                 return 0;
8931 }
8932
8933 /**
8934  * lpfc_write_firmware - attempt to write a firmware image to the port
8935  * @phba: pointer to lpfc hba data structure.
8936  * @fw: pointer to firmware image returned from request_firmware.
8937  *
8938  * returns the number of bytes written if write is successful.
8939  * returns a negative error value if there were errors.
8940  * returns 0 if firmware matches currently active firmware on port.
8941  **/
8942 int
8943 lpfc_write_firmware(struct lpfc_hba *phba, const struct firmware *fw)
8944 {
8945         char fwrev[32];
8946         struct lpfc_grp_hdr *image = (struct lpfc_grp_hdr *)fw->data;
8947         struct list_head dma_buffer_list;
8948         int i, rc = 0;
8949         struct lpfc_dmabuf *dmabuf, *next;
8950         uint32_t offset = 0, temp_offset = 0;
8951
8952         INIT_LIST_HEAD(&dma_buffer_list);
8953         if ((be32_to_cpu(image->magic_number) != LPFC_GROUP_OJECT_MAGIC_NUM) ||
8954             (bf_get_be32(lpfc_grp_hdr_file_type, image) !=
8955              LPFC_FILE_TYPE_GROUP) ||
8956             (bf_get_be32(lpfc_grp_hdr_id, image) != LPFC_FILE_ID_GROUP) ||
8957             (be32_to_cpu(image->size) != fw->size)) {
8958                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8959                                 "3022 Invalid FW image found. "
8960                                 "Magic:%x Type:%x ID:%x\n",
8961                                 be32_to_cpu(image->magic_number),
8962                                 bf_get_be32(lpfc_grp_hdr_file_type, image),
8963                                 bf_get_be32(lpfc_grp_hdr_id, image));
8964                 return -EINVAL;
8965         }
8966         lpfc_decode_firmware_rev(phba, fwrev, 1);
8967         if (strncmp(fwrev, image->revision, strnlen(image->revision, 16))) {
8968                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8969                                 "3023 Updating Firmware. Current Version:%s "
8970                                 "New Version:%s\n",
8971                                 fwrev, image->revision);
8972                 for (i = 0; i < LPFC_MBX_WR_CONFIG_MAX_BDE; i++) {
8973                         dmabuf = kzalloc(sizeof(struct lpfc_dmabuf),
8974                                          GFP_KERNEL);
8975                         if (!dmabuf) {
8976                                 rc = -ENOMEM;
8977                                 goto out;
8978                         }
8979                         dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
8980                                                           SLI4_PAGE_SIZE,
8981                                                           &dmabuf->phys,
8982                                                           GFP_KERNEL);
8983                         if (!dmabuf->virt) {
8984                                 kfree(dmabuf);
8985                                 rc = -ENOMEM;
8986                                 goto out;
8987                         }
8988                         list_add_tail(&dmabuf->list, &dma_buffer_list);
8989                 }
8990                 while (offset < fw->size) {
8991                         temp_offset = offset;
8992                         list_for_each_entry(dmabuf, &dma_buffer_list, list) {
8993                                 if (temp_offset + SLI4_PAGE_SIZE > fw->size) {
8994                                         memcpy(dmabuf->virt,
8995                                                fw->data + temp_offset,
8996                                                fw->size - temp_offset);
8997                                         temp_offset = fw->size;
8998                                         break;
8999                                 }
9000                                 memcpy(dmabuf->virt, fw->data + temp_offset,
9001                                        SLI4_PAGE_SIZE);
9002                                 temp_offset += SLI4_PAGE_SIZE;
9003                         }
9004                         rc = lpfc_wr_object(phba, &dma_buffer_list,
9005                                     (fw->size - offset), &offset);
9006                         if (rc) {
9007                                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9008                                                 "3024 Firmware update failed. "
9009                                                 "%d\n", rc);
9010                                 goto out;
9011                         }
9012                 }
9013                 rc = offset;
9014         }
9015 out:
9016         list_for_each_entry_safe(dmabuf, next, &dma_buffer_list, list) {
9017                 list_del(&dmabuf->list);
9018                 dma_free_coherent(&phba->pcidev->dev, SLI4_PAGE_SIZE,
9019                                   dmabuf->virt, dmabuf->phys);
9020                 kfree(dmabuf);
9021         }
9022         return rc;
9023 }
9024
9025 /**
9026  * lpfc_pci_probe_one_s4 - PCI probe func to reg SLI-4 device to PCI subsys
9027  * @pdev: pointer to PCI device
9028  * @pid: pointer to PCI device identifier
9029  *
9030  * This routine is called from the kernel's PCI subsystem to device with
9031  * SLI-4 interface spec. When an Emulex HBA with SLI-4 interface spec is
9032  * presented on PCI bus, the kernel PCI subsystem looks at PCI device-specific
9033  * information of the device and driver to see if the driver state that it
9034  * can support this kind of device. If the match is successful, the driver
9035  * core invokes this routine. If this routine determines it can claim the HBA,
9036  * it does all the initialization that it needs to do to handle the HBA
9037  * properly.
9038  *
9039  * Return code
9040  *      0 - driver can claim the device
9041  *      negative value - driver can not claim the device
9042  **/
9043 static int __devinit
9044 lpfc_pci_probe_one_s4(struct pci_dev *pdev, const struct pci_device_id *pid)
9045 {
9046         struct lpfc_hba   *phba;
9047         struct lpfc_vport *vport = NULL;
9048         struct Scsi_Host  *shost = NULL;
9049         int error;
9050         uint32_t cfg_mode, intr_mode;
9051         int mcnt;
9052         int adjusted_fcp_eq_count;
9053         const struct firmware *fw;
9054         uint8_t file_name[16];
9055
9056         /* Allocate memory for HBA structure */
9057         phba = lpfc_hba_alloc(pdev);
9058         if (!phba)
9059                 return -ENOMEM;
9060
9061         /* Perform generic PCI device enabling operation */
9062         error = lpfc_enable_pci_dev(phba);
9063         if (error)
9064                 goto out_free_phba;
9065
9066         /* Set up SLI API function jump table for PCI-device group-1 HBAs */
9067         error = lpfc_api_table_setup(phba, LPFC_PCI_DEV_OC);
9068         if (error)
9069                 goto out_disable_pci_dev;
9070
9071         /* Set up SLI-4 specific device PCI memory space */
9072         error = lpfc_sli4_pci_mem_setup(phba);
9073         if (error) {
9074                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9075                                 "1410 Failed to set up pci memory space.\n");
9076                 goto out_disable_pci_dev;
9077         }
9078
9079         /* Set up phase-1 common device driver resources */
9080         error = lpfc_setup_driver_resource_phase1(phba);
9081         if (error) {
9082                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9083                                 "1411 Failed to set up driver resource.\n");
9084                 goto out_unset_pci_mem_s4;
9085         }
9086
9087         /* Set up SLI-4 Specific device driver resources */
9088         error = lpfc_sli4_driver_resource_setup(phba);
9089         if (error) {
9090                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9091                                 "1412 Failed to set up driver resource.\n");
9092                 goto out_unset_pci_mem_s4;
9093         }
9094
9095         /* Initialize and populate the iocb list per host */
9096
9097         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9098                         "2821 initialize iocb list %d.\n",
9099                         phba->cfg_iocb_cnt*1024);
9100         error = lpfc_init_iocb_list(phba, phba->cfg_iocb_cnt*1024);
9101
9102         if (error) {
9103                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9104                                 "1413 Failed to initialize iocb list.\n");
9105                 goto out_unset_driver_resource_s4;
9106         }
9107
9108         INIT_LIST_HEAD(&phba->active_rrq_list);
9109         INIT_LIST_HEAD(&phba->fcf.fcf_pri_list);
9110
9111         /* Set up common device driver resources */
9112         error = lpfc_setup_driver_resource_phase2(phba);
9113         if (error) {
9114                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9115                                 "1414 Failed to set up driver resource.\n");
9116                 goto out_free_iocb_list;
9117         }
9118
9119         /* Get the default values for Model Name and Description */
9120         lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
9121
9122         /* Create SCSI host to the physical port */
9123         error = lpfc_create_shost(phba);
9124         if (error) {
9125                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9126                                 "1415 Failed to create scsi host.\n");
9127                 goto out_unset_driver_resource;
9128         }
9129
9130         /* Configure sysfs attributes */
9131         vport = phba->pport;
9132         error = lpfc_alloc_sysfs_attr(vport);
9133         if (error) {
9134                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9135                                 "1416 Failed to allocate sysfs attr\n");
9136                 goto out_destroy_shost;
9137         }
9138
9139         shost = lpfc_shost_from_vport(vport); /* save shost for error cleanup */
9140         /* Now, trying to enable interrupt and bring up the device */
9141         cfg_mode = phba->cfg_use_msi;
9142         while (true) {
9143                 /* Put device to a known state before enabling interrupt */
9144                 lpfc_stop_port(phba);
9145                 /* Configure and enable interrupt */
9146                 intr_mode = lpfc_sli4_enable_intr(phba, cfg_mode);
9147                 if (intr_mode == LPFC_INTR_ERROR) {
9148                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9149                                         "0426 Failed to enable interrupt.\n");
9150                         error = -ENODEV;
9151                         goto out_free_sysfs_attr;
9152                 }
9153                 /* Default to single EQ for non-MSI-X */
9154                 if (phba->intr_type != MSIX)
9155                         adjusted_fcp_eq_count = 0;
9156                 else if (phba->sli4_hba.msix_vec_nr <
9157                                         phba->cfg_fcp_eq_count + 1)
9158                         adjusted_fcp_eq_count = phba->sli4_hba.msix_vec_nr - 1;
9159                 else
9160                         adjusted_fcp_eq_count = phba->cfg_fcp_eq_count;
9161                 phba->cfg_fcp_eq_count = adjusted_fcp_eq_count;
9162                 /* Set up SLI-4 HBA */
9163                 if (lpfc_sli4_hba_setup(phba)) {
9164                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9165                                         "1421 Failed to set up hba\n");
9166                         error = -ENODEV;
9167                         goto out_disable_intr;
9168                 }
9169
9170                 /* Send NOP mbx cmds for non-INTx mode active interrupt test */
9171                 if (intr_mode != 0)
9172                         mcnt = lpfc_sli4_send_nop_mbox_cmds(phba,
9173                                                             LPFC_ACT_INTR_CNT);
9174
9175                 /* Check active interrupts received only for MSI/MSI-X */
9176                 if (intr_mode == 0 ||
9177                     phba->sli.slistat.sli_intr >= LPFC_ACT_INTR_CNT) {
9178                         /* Log the current active interrupt mode */
9179                         phba->intr_mode = intr_mode;
9180                         lpfc_log_intr_mode(phba, intr_mode);
9181                         break;
9182                 }
9183                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9184                                 "0451 Configure interrupt mode (%d) "
9185                                 "failed active interrupt test.\n",
9186                                 intr_mode);
9187                 /* Unset the previous SLI-4 HBA setup. */
9188                 /*
9189                  * TODO:  Is this operation compatible with IF TYPE 2
9190                  * devices?  All port state is deleted and cleared.
9191                  */
9192                 lpfc_sli4_unset_hba(phba);
9193                 /* Try next level of interrupt mode */
9194                 cfg_mode = --intr_mode;
9195         }
9196
9197         /* Perform post initialization setup */
9198         lpfc_post_init_setup(phba);
9199
9200         /* check for firmware upgrade or downgrade */
9201         snprintf(file_name, 16, "%s.grp", phba->ModelName);
9202         error = request_firmware(&fw, file_name, &phba->pcidev->dev);
9203         if (!error) {
9204                 lpfc_write_firmware(phba, fw);
9205                 release_firmware(fw);
9206         }
9207
9208         /* Check if there are static vports to be created. */
9209         lpfc_create_static_vport(phba);
9210         return 0;
9211
9212 out_disable_intr:
9213         lpfc_sli4_disable_intr(phba);
9214 out_free_sysfs_attr:
9215         lpfc_free_sysfs_attr(vport);
9216 out_destroy_shost:
9217         lpfc_destroy_shost(phba);
9218 out_unset_driver_resource:
9219         lpfc_unset_driver_resource_phase2(phba);
9220 out_free_iocb_list:
9221         lpfc_free_iocb_list(phba);
9222 out_unset_driver_resource_s4:
9223         lpfc_sli4_driver_resource_unset(phba);
9224 out_unset_pci_mem_s4:
9225         lpfc_sli4_pci_mem_unset(phba);
9226 out_disable_pci_dev:
9227         lpfc_disable_pci_dev(phba);
9228         if (shost)
9229                 scsi_host_put(shost);
9230 out_free_phba:
9231         lpfc_hba_free(phba);
9232         return error;
9233 }
9234
9235 /**
9236  * lpfc_pci_remove_one_s4 - PCI func to unreg SLI-4 device from PCI subsystem
9237  * @pdev: pointer to PCI device
9238  *
9239  * This routine is called from the kernel's PCI subsystem to device with
9240  * SLI-4 interface spec. When an Emulex HBA with SLI-4 interface spec is
9241  * removed from PCI bus, it performs all the necessary cleanup for the HBA
9242  * device to be removed from the PCI subsystem properly.
9243  **/
9244 static void __devexit
9245 lpfc_pci_remove_one_s4(struct pci_dev *pdev)
9246 {
9247         struct Scsi_Host *shost = pci_get_drvdata(pdev);
9248         struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
9249         struct lpfc_vport **vports;
9250         struct lpfc_hba *phba = vport->phba;
9251         int i;
9252
9253         /* Mark the device unloading flag */
9254         spin_lock_irq(&phba->hbalock);
9255         vport->load_flag |= FC_UNLOADING;
9256         spin_unlock_irq(&phba->hbalock);
9257
9258         /* Free the HBA sysfs attributes */
9259         lpfc_free_sysfs_attr(vport);
9260
9261         /* Release all the vports against this physical port */
9262         vports = lpfc_create_vport_work_array(phba);
9263         if (vports != NULL)
9264                 for (i = 1; i <= phba->max_vports && vports[i] != NULL; i++)
9265                         fc_vport_terminate(vports[i]->fc_vport);
9266         lpfc_destroy_vport_work_array(phba, vports);
9267
9268         /* Remove FC host and then SCSI host with the physical port */
9269         fc_remove_host(shost);
9270         scsi_remove_host(shost);
9271
9272         /* Perform cleanup on the physical port */
9273         lpfc_cleanup(vport);
9274
9275         /*
9276          * Bring down the SLI Layer. This step disables all interrupts,
9277          * clears the rings, discards all mailbox commands, and resets
9278          * the HBA FCoE function.
9279          */
9280         lpfc_debugfs_terminate(vport);
9281         lpfc_sli4_hba_unset(phba);
9282
9283         spin_lock_irq(&phba->hbalock);
9284         list_del_init(&vport->listentry);
9285         spin_unlock_irq(&phba->hbalock);
9286
9287         /* Perform scsi free before driver resource_unset since scsi
9288          * buffers are released to their corresponding pools here.
9289          */
9290         lpfc_scsi_free(phba);
9291         lpfc_sli4_driver_resource_unset(phba);
9292
9293         /* Unmap adapter Control and Doorbell registers */
9294         lpfc_sli4_pci_mem_unset(phba);
9295
9296         /* Release PCI resources and disable device's PCI function */
9297         scsi_host_put(shost);
9298         lpfc_disable_pci_dev(phba);
9299
9300         /* Finally, free the driver's device data structure */
9301         lpfc_hba_free(phba);
9302
9303         return;
9304 }
9305
9306 /**
9307  * lpfc_pci_suspend_one_s4 - PCI func to suspend SLI-4 device for power mgmnt
9308  * @pdev: pointer to PCI device
9309  * @msg: power management message
9310  *
9311  * This routine is called from the kernel's PCI subsystem to support system
9312  * Power Management (PM) to device with SLI-4 interface spec. When PM invokes
9313  * this method, it quiesces the device by stopping the driver's worker
9314  * thread for the device, turning off device's interrupt and DMA, and bring
9315  * the device offline. Note that as the driver implements the minimum PM
9316  * requirements to a power-aware driver's PM support for suspend/resume -- all
9317  * the possible PM messages (SUSPEND, HIBERNATE, FREEZE) to the suspend()
9318  * method call will be treated as SUSPEND and the driver will fully
9319  * reinitialize its device during resume() method call, the driver will set
9320  * device to PCI_D3hot state in PCI config space instead of setting it
9321  * according to the @msg provided by the PM.
9322  *
9323  * Return code
9324  *      0 - driver suspended the device
9325  *      Error otherwise
9326  **/
9327 static int
9328 lpfc_pci_suspend_one_s4(struct pci_dev *pdev, pm_message_t msg)
9329 {
9330         struct Scsi_Host *shost = pci_get_drvdata(pdev);
9331         struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
9332
9333         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9334                         "2843 PCI device Power Management suspend.\n");
9335
9336         /* Bring down the device */
9337         lpfc_offline_prep(phba);
9338         lpfc_offline(phba);
9339         kthread_stop(phba->worker_thread);
9340
9341         /* Disable interrupt from device */
9342         lpfc_sli4_disable_intr(phba);
9343         lpfc_sli4_queue_destroy(phba);
9344
9345         /* Save device state to PCI config space */
9346         pci_save_state(pdev);
9347         pci_set_power_state(pdev, PCI_D3hot);
9348
9349         return 0;
9350 }
9351
9352 /**
9353  * lpfc_pci_resume_one_s4 - PCI func to resume SLI-4 device for power mgmnt
9354  * @pdev: pointer to PCI device
9355  *
9356  * This routine is called from the kernel's PCI subsystem to support system
9357  * Power Management (PM) to device with SLI-4 interface spac. When PM invokes
9358  * this method, it restores the device's PCI config space state and fully
9359  * reinitializes the device and brings it online. Note that as the driver
9360  * implements the minimum PM requirements to a power-aware driver's PM for
9361  * suspend/resume -- all the possible PM messages (SUSPEND, HIBERNATE, FREEZE)
9362  * to the suspend() method call will be treated as SUSPEND and the driver
9363  * will fully reinitialize its device during resume() method call, the device
9364  * will be set to PCI_D0 directly in PCI config space before restoring the
9365  * state.
9366  *
9367  * Return code
9368  *      0 - driver suspended the device
9369  *      Error otherwise
9370  **/
9371 static int
9372 lpfc_pci_resume_one_s4(struct pci_dev *pdev)
9373 {
9374         struct Scsi_Host *shost = pci_get_drvdata(pdev);
9375         struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
9376         uint32_t intr_mode;
9377         int error;
9378
9379         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9380                         "0292 PCI device Power Management resume.\n");
9381
9382         /* Restore device state from PCI config space */
9383         pci_set_power_state(pdev, PCI_D0);
9384         pci_restore_state(pdev);
9385
9386         /*
9387          * As the new kernel behavior of pci_restore_state() API call clears
9388          * device saved_state flag, need to save the restored state again.
9389          */
9390         pci_save_state(pdev);
9391
9392         if (pdev->is_busmaster)
9393                 pci_set_master(pdev);
9394
9395          /* Startup the kernel thread for this host adapter. */
9396         phba->worker_thread = kthread_run(lpfc_do_work, phba,
9397                                         "lpfc_worker_%d", phba->brd_no);
9398         if (IS_ERR(phba->worker_thread)) {
9399                 error = PTR_ERR(phba->worker_thread);
9400                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9401                                 "0293 PM resume failed to start worker "
9402                                 "thread: error=x%x.\n", error);
9403                 return error;
9404         }
9405
9406         /* Configure and enable interrupt */
9407         intr_mode = lpfc_sli4_enable_intr(phba, phba->intr_mode);
9408         if (intr_mode == LPFC_INTR_ERROR) {
9409                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9410                                 "0294 PM resume Failed to enable interrupt\n");
9411                 return -EIO;
9412         } else
9413                 phba->intr_mode = intr_mode;
9414
9415         /* Restart HBA and bring it online */
9416         lpfc_sli_brdrestart(phba);
9417         lpfc_online(phba);
9418
9419         /* Log the current active interrupt mode */
9420         lpfc_log_intr_mode(phba, phba->intr_mode);
9421
9422         return 0;
9423 }
9424
9425 /**
9426  * lpfc_sli4_prep_dev_for_recover - Prepare SLI4 device for pci slot recover
9427  * @phba: pointer to lpfc hba data structure.
9428  *
9429  * This routine is called to prepare the SLI4 device for PCI slot recover. It
9430  * aborts all the outstanding SCSI I/Os to the pci device.
9431  **/
9432 static void
9433 lpfc_sli4_prep_dev_for_recover(struct lpfc_hba *phba)
9434 {
9435         struct lpfc_sli *psli = &phba->sli;
9436         struct lpfc_sli_ring  *pring;
9437
9438         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9439                         "2828 PCI channel I/O abort preparing for recovery\n");
9440         /*
9441          * There may be errored I/Os through HBA, abort all I/Os on txcmplq
9442          * and let the SCSI mid-layer to retry them to recover.
9443          */
9444         pring = &psli->ring[psli->fcp_ring];
9445         lpfc_sli_abort_iocb_ring(phba, pring);
9446 }
9447
9448 /**
9449  * lpfc_sli4_prep_dev_for_reset - Prepare SLI4 device for pci slot reset
9450  * @phba: pointer to lpfc hba data structure.
9451  *
9452  * This routine is called to prepare the SLI4 device for PCI slot reset. It
9453  * disables the device interrupt and pci device, and aborts the internal FCP
9454  * pending I/Os.
9455  **/
9456 static void
9457 lpfc_sli4_prep_dev_for_reset(struct lpfc_hba *phba)
9458 {
9459         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9460                         "2826 PCI channel disable preparing for reset\n");
9461
9462         /* Block any management I/Os to the device */
9463         lpfc_block_mgmt_io(phba);
9464
9465         /* Block all SCSI devices' I/Os on the host */
9466         lpfc_scsi_dev_block(phba);
9467
9468         /* stop all timers */
9469         lpfc_stop_hba_timers(phba);
9470
9471         /* Disable interrupt and pci device */
9472         lpfc_sli4_disable_intr(phba);
9473         lpfc_sli4_queue_destroy(phba);
9474         pci_disable_device(phba->pcidev);
9475
9476         /* Flush all driver's outstanding SCSI I/Os as we are to reset */
9477         lpfc_sli_flush_fcp_rings(phba);
9478 }
9479
9480 /**
9481  * lpfc_sli4_prep_dev_for_perm_failure - Prepare SLI4 dev for pci slot disable
9482  * @phba: pointer to lpfc hba data structure.
9483  *
9484  * This routine is called to prepare the SLI4 device for PCI slot permanently
9485  * disabling. It blocks the SCSI transport layer traffic and flushes the FCP
9486  * pending I/Os.
9487  **/
9488 static void
9489 lpfc_sli4_prep_dev_for_perm_failure(struct lpfc_hba *phba)
9490 {
9491         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9492                         "2827 PCI channel permanent disable for failure\n");
9493
9494         /* Block all SCSI devices' I/Os on the host */
9495         lpfc_scsi_dev_block(phba);
9496
9497         /* stop all timers */
9498         lpfc_stop_hba_timers(phba);
9499
9500         /* Clean up all driver's outstanding SCSI I/Os */
9501         lpfc_sli_flush_fcp_rings(phba);
9502 }
9503
9504 /**
9505  * lpfc_io_error_detected_s4 - Method for handling PCI I/O error to SLI-4 device
9506  * @pdev: pointer to PCI device.
9507  * @state: the current PCI connection state.
9508  *
9509  * This routine is called from the PCI subsystem for error handling to device
9510  * with SLI-4 interface spec. This function is called by the PCI subsystem
9511  * after a PCI bus error affecting this device has been detected. When this
9512  * function is invoked, it will need to stop all the I/Os and interrupt(s)
9513  * to the device. Once that is done, it will return PCI_ERS_RESULT_NEED_RESET
9514  * for the PCI subsystem to perform proper recovery as desired.
9515  *
9516  * Return codes
9517  *      PCI_ERS_RESULT_NEED_RESET - need to reset before recovery
9518  *      PCI_ERS_RESULT_DISCONNECT - device could not be recovered
9519  **/
9520 static pci_ers_result_t
9521 lpfc_io_error_detected_s4(struct pci_dev *pdev, pci_channel_state_t state)
9522 {
9523         struct Scsi_Host *shost = pci_get_drvdata(pdev);
9524         struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
9525
9526         switch (state) {
9527         case pci_channel_io_normal:
9528                 /* Non-fatal error, prepare for recovery */
9529                 lpfc_sli4_prep_dev_for_recover(phba);
9530                 return PCI_ERS_RESULT_CAN_RECOVER;
9531         case pci_channel_io_frozen:
9532                 /* Fatal error, prepare for slot reset */
9533                 lpfc_sli4_prep_dev_for_reset(phba);
9534                 return PCI_ERS_RESULT_NEED_RESET;
9535         case pci_channel_io_perm_failure:
9536                 /* Permanent failure, prepare for device down */
9537                 lpfc_sli4_prep_dev_for_perm_failure(phba);
9538                 return PCI_ERS_RESULT_DISCONNECT;
9539         default:
9540                 /* Unknown state, prepare and request slot reset */
9541                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9542                                 "2825 Unknown PCI error state: x%x\n", state);
9543                 lpfc_sli4_prep_dev_for_reset(phba);
9544                 return PCI_ERS_RESULT_NEED_RESET;
9545         }
9546 }
9547
9548 /**
9549  * lpfc_io_slot_reset_s4 - Method for restart PCI SLI-4 device from scratch
9550  * @pdev: pointer to PCI device.
9551  *
9552  * This routine is called from the PCI subsystem for error handling to device
9553  * with SLI-4 interface spec. It is called after PCI bus has been reset to
9554  * restart the PCI card from scratch, as if from a cold-boot. During the
9555  * PCI subsystem error recovery, after the driver returns
9556  * PCI_ERS_RESULT_NEED_RESET, the PCI subsystem will perform proper error
9557  * recovery and then call this routine before calling the .resume method to
9558  * recover the device. This function will initialize the HBA device, enable
9559  * the interrupt, but it will just put the HBA to offline state without
9560  * passing any I/O traffic.
9561  *
9562  * Return codes
9563  *      PCI_ERS_RESULT_RECOVERED - the device has been recovered
9564  *      PCI_ERS_RESULT_DISCONNECT - device could not be recovered
9565  */
9566 static pci_ers_result_t
9567 lpfc_io_slot_reset_s4(struct pci_dev *pdev)
9568 {
9569         struct Scsi_Host *shost = pci_get_drvdata(pdev);
9570         struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
9571         struct lpfc_sli *psli = &phba->sli;
9572         uint32_t intr_mode;
9573
9574         dev_printk(KERN_INFO, &pdev->dev, "recovering from a slot reset.\n");
9575         if (pci_enable_device_mem(pdev)) {
9576                 printk(KERN_ERR "lpfc: Cannot re-enable "
9577                         "PCI device after reset.\n");
9578                 return PCI_ERS_RESULT_DISCONNECT;
9579         }
9580
9581         pci_restore_state(pdev);
9582
9583         /*
9584          * As the new kernel behavior of pci_restore_state() API call clears
9585          * device saved_state flag, need to save the restored state again.
9586          */
9587         pci_save_state(pdev);
9588
9589         if (pdev->is_busmaster)
9590                 pci_set_master(pdev);
9591
9592         spin_lock_irq(&phba->hbalock);
9593         psli->sli_flag &= ~LPFC_SLI_ACTIVE;
9594         spin_unlock_irq(&phba->hbalock);
9595
9596         /* Configure and enable interrupt */
9597         intr_mode = lpfc_sli4_enable_intr(phba, phba->intr_mode);
9598         if (intr_mode == LPFC_INTR_ERROR) {
9599                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9600                                 "2824 Cannot re-enable interrupt after "
9601                                 "slot reset.\n");
9602                 return PCI_ERS_RESULT_DISCONNECT;
9603         } else
9604                 phba->intr_mode = intr_mode;
9605
9606         /* Log the current active interrupt mode */
9607         lpfc_log_intr_mode(phba, phba->intr_mode);
9608
9609         return PCI_ERS_RESULT_RECOVERED;
9610 }
9611
9612 /**
9613  * lpfc_io_resume_s4 - Method for resuming PCI I/O operation to SLI-4 device
9614  * @pdev: pointer to PCI device
9615  *
9616  * This routine is called from the PCI subsystem for error handling to device
9617  * with SLI-4 interface spec. It is called when kernel error recovery tells
9618  * the lpfc driver that it is ok to resume normal PCI operation after PCI bus
9619  * error recovery. After this call, traffic can start to flow from this device
9620  * again.
9621  **/
9622 static void
9623 lpfc_io_resume_s4(struct pci_dev *pdev)
9624 {
9625         struct Scsi_Host *shost = pci_get_drvdata(pdev);
9626         struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
9627
9628         /*
9629          * In case of slot reset, as function reset is performed through
9630          * mailbox command which needs DMA to be enabled, this operation
9631          * has to be moved to the io resume phase. Taking device offline
9632          * will perform the necessary cleanup.
9633          */
9634         if (!(phba->sli.sli_flag & LPFC_SLI_ACTIVE)) {
9635                 /* Perform device reset */
9636                 lpfc_offline_prep(phba);
9637                 lpfc_offline(phba);
9638                 lpfc_sli_brdrestart(phba);
9639                 /* Bring the device back online */
9640                 lpfc_online(phba);
9641         }
9642
9643         /* Clean up Advanced Error Reporting (AER) if needed */
9644         if (phba->hba_flag & HBA_AER_ENABLED)
9645                 pci_cleanup_aer_uncorrect_error_status(pdev);
9646 }
9647
9648 /**
9649  * lpfc_pci_probe_one - lpfc PCI probe func to reg dev to PCI subsystem
9650  * @pdev: pointer to PCI device
9651  * @pid: pointer to PCI device identifier
9652  *
9653  * This routine is to be registered to the kernel's PCI subsystem. When an
9654  * Emulex HBA device is presented on PCI bus, the kernel PCI subsystem looks
9655  * at PCI device-specific information of the device and driver to see if the
9656  * driver state that it can support this kind of device. If the match is
9657  * successful, the driver core invokes this routine. This routine dispatches
9658  * the action to the proper SLI-3 or SLI-4 device probing routine, which will
9659  * do all the initialization that it needs to do to handle the HBA device
9660  * properly.
9661  *
9662  * Return code
9663  *      0 - driver can claim the device
9664  *      negative value - driver can not claim the device
9665  **/
9666 static int __devinit
9667 lpfc_pci_probe_one(struct pci_dev *pdev, const struct pci_device_id *pid)
9668 {
9669         int rc;
9670         struct lpfc_sli_intf intf;
9671
9672         if (pci_read_config_dword(pdev, LPFC_SLI_INTF, &intf.word0))
9673                 return -ENODEV;
9674
9675         if ((bf_get(lpfc_sli_intf_valid, &intf) == LPFC_SLI_INTF_VALID) &&
9676             (bf_get(lpfc_sli_intf_slirev, &intf) == LPFC_SLI_INTF_REV_SLI4))
9677                 rc = lpfc_pci_probe_one_s4(pdev, pid);
9678         else
9679                 rc = lpfc_pci_probe_one_s3(pdev, pid);
9680
9681         return rc;
9682 }
9683
9684 /**
9685  * lpfc_pci_remove_one - lpfc PCI func to unreg dev from PCI subsystem
9686  * @pdev: pointer to PCI device
9687  *
9688  * This routine is to be registered to the kernel's PCI subsystem. When an
9689  * Emulex HBA is removed from PCI bus, the driver core invokes this routine.
9690  * This routine dispatches the action to the proper SLI-3 or SLI-4 device
9691  * remove routine, which will perform all the necessary cleanup for the
9692  * device to be removed from the PCI subsystem properly.
9693  **/
9694 static void __devexit
9695 lpfc_pci_remove_one(struct pci_dev *pdev)
9696 {
9697         struct Scsi_Host *shost = pci_get_drvdata(pdev);
9698         struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
9699
9700         switch (phba->pci_dev_grp) {
9701         case LPFC_PCI_DEV_LP:
9702                 lpfc_pci_remove_one_s3(pdev);
9703                 break;
9704         case LPFC_PCI_DEV_OC:
9705                 lpfc_pci_remove_one_s4(pdev);
9706                 break;
9707         default:
9708                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9709                                 "1424 Invalid PCI device group: 0x%x\n",
9710                                 phba->pci_dev_grp);
9711                 break;
9712         }
9713         return;
9714 }
9715
9716 /**
9717  * lpfc_pci_suspend_one - lpfc PCI func to suspend dev for power management
9718  * @pdev: pointer to PCI device
9719  * @msg: power management message
9720  *
9721  * This routine is to be registered to the kernel's PCI subsystem to support
9722  * system Power Management (PM). When PM invokes this method, it dispatches
9723  * the action to the proper SLI-3 or SLI-4 device suspend routine, which will
9724  * suspend the device.
9725  *
9726  * Return code
9727  *      0 - driver suspended the device
9728  *      Error otherwise
9729  **/
9730 static int
9731 lpfc_pci_suspend_one(struct pci_dev *pdev, pm_message_t msg)
9732 {
9733         struct Scsi_Host *shost = pci_get_drvdata(pdev);
9734         struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
9735         int rc = -ENODEV;
9736
9737         switch (phba->pci_dev_grp) {
9738         case LPFC_PCI_DEV_LP:
9739                 rc = lpfc_pci_suspend_one_s3(pdev, msg);
9740                 break;
9741         case LPFC_PCI_DEV_OC:
9742                 rc = lpfc_pci_suspend_one_s4(pdev, msg);
9743                 break;
9744         default:
9745                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9746                                 "1425 Invalid PCI device group: 0x%x\n",
9747                                 phba->pci_dev_grp);
9748                 break;
9749         }
9750         return rc;
9751 }
9752
9753 /**
9754  * lpfc_pci_resume_one - lpfc PCI func to resume dev for power management
9755  * @pdev: pointer to PCI device
9756  *
9757  * This routine is to be registered to the kernel's PCI subsystem to support
9758  * system Power Management (PM). When PM invokes this method, it dispatches
9759  * the action to the proper SLI-3 or SLI-4 device resume routine, which will
9760  * resume the device.
9761  *
9762  * Return code
9763  *      0 - driver suspended the device
9764  *      Error otherwise
9765  **/
9766 static int
9767 lpfc_pci_resume_one(struct pci_dev *pdev)
9768 {
9769         struct Scsi_Host *shost = pci_get_drvdata(pdev);
9770         struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
9771         int rc = -ENODEV;
9772
9773         switch (phba->pci_dev_grp) {
9774         case LPFC_PCI_DEV_LP:
9775                 rc = lpfc_pci_resume_one_s3(pdev);
9776                 break;
9777         case LPFC_PCI_DEV_OC:
9778                 rc = lpfc_pci_resume_one_s4(pdev);
9779                 break;
9780         default:
9781                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9782                                 "1426 Invalid PCI device group: 0x%x\n",
9783                                 phba->pci_dev_grp);
9784                 break;
9785         }
9786         return rc;
9787 }
9788
9789 /**
9790  * lpfc_io_error_detected - lpfc method for handling PCI I/O error
9791  * @pdev: pointer to PCI device.
9792  * @state: the current PCI connection state.
9793  *
9794  * This routine is registered to the PCI subsystem for error handling. This
9795  * function is called by the PCI subsystem after a PCI bus error affecting
9796  * this device has been detected. When this routine is invoked, it dispatches
9797  * the action to the proper SLI-3 or SLI-4 device error detected handling
9798  * routine, which will perform the proper error detected operation.
9799  *
9800  * Return codes
9801  *      PCI_ERS_RESULT_NEED_RESET - need to reset before recovery
9802  *      PCI_ERS_RESULT_DISCONNECT - device could not be recovered
9803  **/
9804 static pci_ers_result_t
9805 lpfc_io_error_detected(struct pci_dev *pdev, pci_channel_state_t state)
9806 {
9807         struct Scsi_Host *shost = pci_get_drvdata(pdev);
9808         struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
9809         pci_ers_result_t rc = PCI_ERS_RESULT_DISCONNECT;
9810
9811         switch (phba->pci_dev_grp) {
9812         case LPFC_PCI_DEV_LP:
9813                 rc = lpfc_io_error_detected_s3(pdev, state);
9814                 break;
9815         case LPFC_PCI_DEV_OC:
9816                 rc = lpfc_io_error_detected_s4(pdev, state);
9817                 break;
9818         default:
9819                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9820                                 "1427 Invalid PCI device group: 0x%x\n",
9821                                 phba->pci_dev_grp);
9822                 break;
9823         }
9824         return rc;
9825 }
9826
9827 /**
9828  * lpfc_io_slot_reset - lpfc method for restart PCI dev from scratch
9829  * @pdev: pointer to PCI device.
9830  *
9831  * This routine is registered to the PCI subsystem for error handling. This
9832  * function is called after PCI bus has been reset to restart the PCI card
9833  * from scratch, as if from a cold-boot. When this routine is invoked, it
9834  * dispatches the action to the proper SLI-3 or SLI-4 device reset handling
9835  * routine, which will perform the proper device reset.
9836  *
9837  * Return codes
9838  *      PCI_ERS_RESULT_RECOVERED - the device has been recovered
9839  *      PCI_ERS_RESULT_DISCONNECT - device could not be recovered
9840  **/
9841 static pci_ers_result_t
9842 lpfc_io_slot_reset(struct pci_dev *pdev)
9843 {
9844         struct Scsi_Host *shost = pci_get_drvdata(pdev);
9845         struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
9846         pci_ers_result_t rc = PCI_ERS_RESULT_DISCONNECT;
9847
9848         switch (phba->pci_dev_grp) {
9849         case LPFC_PCI_DEV_LP:
9850                 rc = lpfc_io_slot_reset_s3(pdev);
9851                 break;
9852         case LPFC_PCI_DEV_OC:
9853                 rc = lpfc_io_slot_reset_s4(pdev);
9854                 break;
9855         default:
9856                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9857                                 "1428 Invalid PCI device group: 0x%x\n",
9858                                 phba->pci_dev_grp);
9859                 break;
9860         }
9861         return rc;
9862 }
9863
9864 /**
9865  * lpfc_io_resume - lpfc method for resuming PCI I/O operation
9866  * @pdev: pointer to PCI device
9867  *
9868  * This routine is registered to the PCI subsystem for error handling. It
9869  * is called when kernel error recovery tells the lpfc driver that it is
9870  * OK to resume normal PCI operation after PCI bus error recovery. When
9871  * this routine is invoked, it dispatches the action to the proper SLI-3
9872  * or SLI-4 device io_resume routine, which will resume the device operation.
9873  **/
9874 static void
9875 lpfc_io_resume(struct pci_dev *pdev)
9876 {
9877         struct Scsi_Host *shost = pci_get_drvdata(pdev);
9878         struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
9879
9880         switch (phba->pci_dev_grp) {
9881         case LPFC_PCI_DEV_LP:
9882                 lpfc_io_resume_s3(pdev);
9883                 break;
9884         case LPFC_PCI_DEV_OC:
9885                 lpfc_io_resume_s4(pdev);
9886                 break;
9887         default:
9888                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9889                                 "1429 Invalid PCI device group: 0x%x\n",
9890                                 phba->pci_dev_grp);
9891                 break;
9892         }
9893         return;
9894 }
9895
9896 static struct pci_device_id lpfc_id_table[] = {
9897         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_VIPER,
9898                 PCI_ANY_ID, PCI_ANY_ID, },
9899         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_FIREFLY,
9900                 PCI_ANY_ID, PCI_ANY_ID, },
9901         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_THOR,
9902                 PCI_ANY_ID, PCI_ANY_ID, },
9903         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_PEGASUS,
9904                 PCI_ANY_ID, PCI_ANY_ID, },
9905         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_CENTAUR,
9906                 PCI_ANY_ID, PCI_ANY_ID, },
9907         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_DRAGONFLY,
9908                 PCI_ANY_ID, PCI_ANY_ID, },
9909         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_SUPERFLY,
9910                 PCI_ANY_ID, PCI_ANY_ID, },
9911         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_RFLY,
9912                 PCI_ANY_ID, PCI_ANY_ID, },
9913         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_PFLY,
9914                 PCI_ANY_ID, PCI_ANY_ID, },
9915         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_NEPTUNE,
9916                 PCI_ANY_ID, PCI_ANY_ID, },
9917         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_NEPTUNE_SCSP,
9918                 PCI_ANY_ID, PCI_ANY_ID, },
9919         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_NEPTUNE_DCSP,
9920                 PCI_ANY_ID, PCI_ANY_ID, },
9921         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_HELIOS,
9922                 PCI_ANY_ID, PCI_ANY_ID, },
9923         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_HELIOS_SCSP,
9924                 PCI_ANY_ID, PCI_ANY_ID, },
9925         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_HELIOS_DCSP,
9926                 PCI_ANY_ID, PCI_ANY_ID, },
9927         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_BMID,
9928                 PCI_ANY_ID, PCI_ANY_ID, },
9929         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_BSMB,
9930                 PCI_ANY_ID, PCI_ANY_ID, },
9931         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_ZEPHYR,
9932                 PCI_ANY_ID, PCI_ANY_ID, },
9933         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_HORNET,
9934                 PCI_ANY_ID, PCI_ANY_ID, },
9935         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_ZEPHYR_SCSP,
9936                 PCI_ANY_ID, PCI_ANY_ID, },
9937         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_ZEPHYR_DCSP,
9938                 PCI_ANY_ID, PCI_ANY_ID, },
9939         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_ZMID,
9940                 PCI_ANY_ID, PCI_ANY_ID, },
9941         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_ZSMB,
9942                 PCI_ANY_ID, PCI_ANY_ID, },
9943         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_TFLY,
9944                 PCI_ANY_ID, PCI_ANY_ID, },
9945         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_LP101,
9946                 PCI_ANY_ID, PCI_ANY_ID, },
9947         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_LP10000S,
9948                 PCI_ANY_ID, PCI_ANY_ID, },
9949         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_LP11000S,
9950                 PCI_ANY_ID, PCI_ANY_ID, },
9951         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_LPE11000S,
9952                 PCI_ANY_ID, PCI_ANY_ID, },
9953         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_SAT,
9954                 PCI_ANY_ID, PCI_ANY_ID, },
9955         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_SAT_MID,
9956                 PCI_ANY_ID, PCI_ANY_ID, },
9957         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_SAT_SMB,
9958                 PCI_ANY_ID, PCI_ANY_ID, },
9959         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_SAT_DCSP,
9960                 PCI_ANY_ID, PCI_ANY_ID, },
9961         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_SAT_SCSP,
9962                 PCI_ANY_ID, PCI_ANY_ID, },
9963         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_SAT_S,
9964                 PCI_ANY_ID, PCI_ANY_ID, },
9965         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_PROTEUS_VF,
9966                 PCI_ANY_ID, PCI_ANY_ID, },
9967         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_PROTEUS_PF,
9968                 PCI_ANY_ID, PCI_ANY_ID, },
9969         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_PROTEUS_S,
9970                 PCI_ANY_ID, PCI_ANY_ID, },
9971         {PCI_VENDOR_ID_SERVERENGINE, PCI_DEVICE_ID_TIGERSHARK,
9972                 PCI_ANY_ID, PCI_ANY_ID, },
9973         {PCI_VENDOR_ID_SERVERENGINE, PCI_DEVICE_ID_TOMCAT,
9974                 PCI_ANY_ID, PCI_ANY_ID, },
9975         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_FALCON,
9976                 PCI_ANY_ID, PCI_ANY_ID, },
9977         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_BALIUS,
9978                 PCI_ANY_ID, PCI_ANY_ID, },
9979         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_LANCER_FC,
9980                 PCI_ANY_ID, PCI_ANY_ID, },
9981         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_LANCER_FCOE,
9982                 PCI_ANY_ID, PCI_ANY_ID, },
9983         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_LANCER_FC_VF,
9984                 PCI_ANY_ID, PCI_ANY_ID, },
9985         {PCI_VENDOR_ID_EMULEX, PCI_DEVICE_ID_LANCER_FCOE_VF,
9986                 PCI_ANY_ID, PCI_ANY_ID, },
9987         { 0 }
9988 };
9989
9990 MODULE_DEVICE_TABLE(pci, lpfc_id_table);
9991
9992 static struct pci_error_handlers lpfc_err_handler = {
9993         .error_detected = lpfc_io_error_detected,
9994         .slot_reset = lpfc_io_slot_reset,
9995         .resume = lpfc_io_resume,
9996 };
9997
9998 static struct pci_driver lpfc_driver = {
9999         .name           = LPFC_DRIVER_NAME,
10000         .id_table       = lpfc_id_table,
10001         .probe          = lpfc_pci_probe_one,
10002         .remove         = __devexit_p(lpfc_pci_remove_one),
10003         .suspend        = lpfc_pci_suspend_one,
10004         .resume         = lpfc_pci_resume_one,
10005         .err_handler    = &lpfc_err_handler,
10006 };
10007
10008 /**
10009  * lpfc_init - lpfc module initialization routine
10010  *
10011  * This routine is to be invoked when the lpfc module is loaded into the
10012  * kernel. The special kernel macro module_init() is used to indicate the
10013  * role of this routine to the kernel as lpfc module entry point.
10014  *
10015  * Return codes
10016  *   0 - successful
10017  *   -ENOMEM - FC attach transport failed
10018  *   all others - failed
10019  */
10020 static int __init
10021 lpfc_init(void)
10022 {
10023         int error = 0;
10024
10025         printk(LPFC_MODULE_DESC "\n");
10026         printk(LPFC_COPYRIGHT "\n");
10027
10028         if (lpfc_enable_npiv) {
10029                 lpfc_transport_functions.vport_create = lpfc_vport_create;
10030                 lpfc_transport_functions.vport_delete = lpfc_vport_delete;
10031         }
10032         lpfc_transport_template =
10033                                 fc_attach_transport(&lpfc_transport_functions);
10034         if (lpfc_transport_template == NULL)
10035                 return -ENOMEM;
10036         if (lpfc_enable_npiv) {
10037                 lpfc_vport_transport_template =
10038                         fc_attach_transport(&lpfc_vport_transport_functions);
10039                 if (lpfc_vport_transport_template == NULL) {
10040                         fc_release_transport(lpfc_transport_template);
10041                         return -ENOMEM;
10042                 }
10043         }
10044         error = pci_register_driver(&lpfc_driver);
10045         if (error) {
10046                 fc_release_transport(lpfc_transport_template);
10047                 if (lpfc_enable_npiv)
10048                         fc_release_transport(lpfc_vport_transport_template);
10049         }
10050
10051         return error;
10052 }
10053
10054 /**
10055  * lpfc_exit - lpfc module removal routine
10056  *
10057  * This routine is invoked when the lpfc module is removed from the kernel.
10058  * The special kernel macro module_exit() is used to indicate the role of
10059  * this routine to the kernel as lpfc module exit point.
10060  */
10061 static void __exit
10062 lpfc_exit(void)
10063 {
10064         pci_unregister_driver(&lpfc_driver);
10065         fc_release_transport(lpfc_transport_template);
10066         if (lpfc_enable_npiv)
10067                 fc_release_transport(lpfc_vport_transport_template);
10068         if (_dump_buf_data) {
10069                 printk(KERN_ERR "9062 BLKGRD: freeing %lu pages for "
10070                                 "_dump_buf_data at 0x%p\n",
10071                                 (1L << _dump_buf_data_order), _dump_buf_data);
10072                 free_pages((unsigned long)_dump_buf_data, _dump_buf_data_order);
10073         }
10074
10075         if (_dump_buf_dif) {
10076                 printk(KERN_ERR "9049 BLKGRD: freeing %lu pages for "
10077                                 "_dump_buf_dif at 0x%p\n",
10078                                 (1L << _dump_buf_dif_order), _dump_buf_dif);
10079                 free_pages((unsigned long)_dump_buf_dif, _dump_buf_dif_order);
10080         }
10081 }
10082
10083 module_init(lpfc_init);
10084 module_exit(lpfc_exit);
10085 MODULE_LICENSE("GPL");
10086 MODULE_DESCRIPTION(LPFC_MODULE_DESC);
10087 MODULE_AUTHOR("Emulex Corporation - tech.support@emulex.com");
10088 MODULE_VERSION("0:" LPFC_DRIVER_VERSION);