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