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