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