xref: /openbmc/linux/drivers/scsi/lpfc/lpfc_init.c (revision 547840bd)
1 /*******************************************************************
2  * This file is part of the Emulex Linux Device Driver for         *
3  * Fibre Channel Host Bus Adapters.                                *
4  * Copyright (C) 2017-2020 Broadcom. All Rights Reserved. The term *
5  * “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.  *
6  * Copyright (C) 2004-2016 Emulex.  All rights reserved.           *
7  * EMULEX and SLI are trademarks of Emulex.                        *
8  * www.broadcom.com                                                *
9  * Portions Copyright (C) 2004-2005 Christoph Hellwig              *
10  *                                                                 *
11  * This program is free software; you can redistribute it and/or   *
12  * modify it under the terms of version 2 of the GNU General       *
13  * Public License as published by the Free Software Foundation.    *
14  * This program is distributed in the hope that it will be useful. *
15  * ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND          *
16  * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,  *
17  * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE      *
18  * DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD *
19  * TO BE LEGALLY INVALID.  See the GNU General Public License for  *
20  * more details, a copy of which can be found in the file COPYING  *
21  * included with this package.                                     *
22  *******************************************************************/
23 
24 #include <linux/blkdev.h>
25 #include <linux/delay.h>
26 #include <linux/dma-mapping.h>
27 #include <linux/idr.h>
28 #include <linux/interrupt.h>
29 #include <linux/module.h>
30 #include <linux/kthread.h>
31 #include <linux/pci.h>
32 #include <linux/spinlock.h>
33 #include <linux/ctype.h>
34 #include <linux/aer.h>
35 #include <linux/slab.h>
36 #include <linux/firmware.h>
37 #include <linux/miscdevice.h>
38 #include <linux/percpu.h>
39 #include <linux/msi.h>
40 #include <linux/irq.h>
41 #include <linux/bitops.h>
42 #include <linux/crash_dump.h>
43 #include <linux/cpu.h>
44 #include <linux/cpuhotplug.h>
45 
46 #include <scsi/scsi.h>
47 #include <scsi/scsi_device.h>
48 #include <scsi/scsi_host.h>
49 #include <scsi/scsi_transport_fc.h>
50 #include <scsi/scsi_tcq.h>
51 #include <scsi/fc/fc_fs.h>
52 
53 #include "lpfc_hw4.h"
54 #include "lpfc_hw.h"
55 #include "lpfc_sli.h"
56 #include "lpfc_sli4.h"
57 #include "lpfc_nl.h"
58 #include "lpfc_disc.h"
59 #include "lpfc.h"
60 #include "lpfc_scsi.h"
61 #include "lpfc_nvme.h"
62 #include "lpfc_logmsg.h"
63 #include "lpfc_crtn.h"
64 #include "lpfc_vport.h"
65 #include "lpfc_version.h"
66 #include "lpfc_ids.h"
67 
68 static enum cpuhp_state lpfc_cpuhp_state;
69 /* Used when mapping IRQ vectors in a driver centric manner */
70 static uint32_t lpfc_present_cpu;
71 
72 static void __lpfc_cpuhp_remove(struct lpfc_hba *phba);
73 static void lpfc_cpuhp_remove(struct lpfc_hba *phba);
74 static void lpfc_cpuhp_add(struct lpfc_hba *phba);
75 static void lpfc_get_hba_model_desc(struct lpfc_hba *, uint8_t *, uint8_t *);
76 static int lpfc_post_rcv_buf(struct lpfc_hba *);
77 static int lpfc_sli4_queue_verify(struct lpfc_hba *);
78 static int lpfc_create_bootstrap_mbox(struct lpfc_hba *);
79 static int lpfc_setup_endian_order(struct lpfc_hba *);
80 static void lpfc_destroy_bootstrap_mbox(struct lpfc_hba *);
81 static void lpfc_free_els_sgl_list(struct lpfc_hba *);
82 static void lpfc_free_nvmet_sgl_list(struct lpfc_hba *);
83 static void lpfc_init_sgl_list(struct lpfc_hba *);
84 static int lpfc_init_active_sgl_array(struct lpfc_hba *);
85 static void lpfc_free_active_sgl(struct lpfc_hba *);
86 static int lpfc_hba_down_post_s3(struct lpfc_hba *phba);
87 static int lpfc_hba_down_post_s4(struct lpfc_hba *phba);
88 static int lpfc_sli4_cq_event_pool_create(struct lpfc_hba *);
89 static void lpfc_sli4_cq_event_pool_destroy(struct lpfc_hba *);
90 static void lpfc_sli4_cq_event_release_all(struct lpfc_hba *);
91 static void lpfc_sli4_disable_intr(struct lpfc_hba *);
92 static uint32_t lpfc_sli4_enable_intr(struct lpfc_hba *, uint32_t);
93 static void lpfc_sli4_oas_verify(struct lpfc_hba *phba);
94 static uint16_t lpfc_find_cpu_handle(struct lpfc_hba *, uint16_t, int);
95 static void lpfc_setup_bg(struct lpfc_hba *, struct Scsi_Host *);
96 
97 static struct scsi_transport_template *lpfc_transport_template = NULL;
98 static struct scsi_transport_template *lpfc_vport_transport_template = NULL;
99 static DEFINE_IDR(lpfc_hba_index);
100 #define LPFC_NVMET_BUF_POST 254
101 
102 /**
103  * lpfc_config_port_prep - Perform lpfc initialization prior to config port
104  * @phba: pointer to lpfc hba data structure.
105  *
106  * This routine will do LPFC initialization prior to issuing the CONFIG_PORT
107  * mailbox command. It retrieves the revision information from the HBA and
108  * collects the Vital Product Data (VPD) about the HBA for preparing the
109  * configuration of the HBA.
110  *
111  * Return codes:
112  *   0 - success.
113  *   -ERESTART - requests the SLI layer to reset the HBA and try again.
114  *   Any other value - indicates an error.
115  **/
116 int
117 lpfc_config_port_prep(struct lpfc_hba *phba)
118 {
119 	lpfc_vpd_t *vp = &phba->vpd;
120 	int i = 0, rc;
121 	LPFC_MBOXQ_t *pmb;
122 	MAILBOX_t *mb;
123 	char *lpfc_vpd_data = NULL;
124 	uint16_t offset = 0;
125 	static char licensed[56] =
126 		    "key unlock for use with gnu public licensed code only\0";
127 	static int init_key = 1;
128 
129 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
130 	if (!pmb) {
131 		phba->link_state = LPFC_HBA_ERROR;
132 		return -ENOMEM;
133 	}
134 
135 	mb = &pmb->u.mb;
136 	phba->link_state = LPFC_INIT_MBX_CMDS;
137 
138 	if (lpfc_is_LC_HBA(phba->pcidev->device)) {
139 		if (init_key) {
140 			uint32_t *ptext = (uint32_t *) licensed;
141 
142 			for (i = 0; i < 56; i += sizeof (uint32_t), ptext++)
143 				*ptext = cpu_to_be32(*ptext);
144 			init_key = 0;
145 		}
146 
147 		lpfc_read_nv(phba, pmb);
148 		memset((char*)mb->un.varRDnvp.rsvd3, 0,
149 			sizeof (mb->un.varRDnvp.rsvd3));
150 		memcpy((char*)mb->un.varRDnvp.rsvd3, licensed,
151 			 sizeof (licensed));
152 
153 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
154 
155 		if (rc != MBX_SUCCESS) {
156 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX,
157 					"0324 Config Port initialization "
158 					"error, mbxCmd x%x READ_NVPARM, "
159 					"mbxStatus x%x\n",
160 					mb->mbxCommand, mb->mbxStatus);
161 			mempool_free(pmb, phba->mbox_mem_pool);
162 			return -ERESTART;
163 		}
164 		memcpy(phba->wwnn, (char *)mb->un.varRDnvp.nodename,
165 		       sizeof(phba->wwnn));
166 		memcpy(phba->wwpn, (char *)mb->un.varRDnvp.portname,
167 		       sizeof(phba->wwpn));
168 	}
169 
170 	/*
171 	 * Clear all option bits except LPFC_SLI3_BG_ENABLED,
172 	 * which was already set in lpfc_get_cfgparam()
173 	 */
174 	phba->sli3_options &= (uint32_t)LPFC_SLI3_BG_ENABLED;
175 
176 	/* Setup and issue mailbox READ REV command */
177 	lpfc_read_rev(phba, pmb);
178 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
179 	if (rc != MBX_SUCCESS) {
180 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
181 				"0439 Adapter failed to init, mbxCmd x%x "
182 				"READ_REV, mbxStatus x%x\n",
183 				mb->mbxCommand, mb->mbxStatus);
184 		mempool_free( pmb, phba->mbox_mem_pool);
185 		return -ERESTART;
186 	}
187 
188 
189 	/*
190 	 * The value of rr must be 1 since the driver set the cv field to 1.
191 	 * This setting requires the FW to set all revision fields.
192 	 */
193 	if (mb->un.varRdRev.rr == 0) {
194 		vp->rev.rBit = 0;
195 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
196 				"0440 Adapter failed to init, READ_REV has "
197 				"missing revision information.\n");
198 		mempool_free(pmb, phba->mbox_mem_pool);
199 		return -ERESTART;
200 	}
201 
202 	if (phba->sli_rev == 3 && !mb->un.varRdRev.v3rsp) {
203 		mempool_free(pmb, phba->mbox_mem_pool);
204 		return -EINVAL;
205 	}
206 
207 	/* Save information as VPD data */
208 	vp->rev.rBit = 1;
209 	memcpy(&vp->sli3Feat, &mb->un.varRdRev.sli3Feat, sizeof(uint32_t));
210 	vp->rev.sli1FwRev = mb->un.varRdRev.sli1FwRev;
211 	memcpy(vp->rev.sli1FwName, (char*) mb->un.varRdRev.sli1FwName, 16);
212 	vp->rev.sli2FwRev = mb->un.varRdRev.sli2FwRev;
213 	memcpy(vp->rev.sli2FwName, (char *) mb->un.varRdRev.sli2FwName, 16);
214 	vp->rev.biuRev = mb->un.varRdRev.biuRev;
215 	vp->rev.smRev = mb->un.varRdRev.smRev;
216 	vp->rev.smFwRev = mb->un.varRdRev.un.smFwRev;
217 	vp->rev.endecRev = mb->un.varRdRev.endecRev;
218 	vp->rev.fcphHigh = mb->un.varRdRev.fcphHigh;
219 	vp->rev.fcphLow = mb->un.varRdRev.fcphLow;
220 	vp->rev.feaLevelHigh = mb->un.varRdRev.feaLevelHigh;
221 	vp->rev.feaLevelLow = mb->un.varRdRev.feaLevelLow;
222 	vp->rev.postKernRev = mb->un.varRdRev.postKernRev;
223 	vp->rev.opFwRev = mb->un.varRdRev.opFwRev;
224 
225 	/* If the sli feature level is less then 9, we must
226 	 * tear down all RPIs and VPIs on link down if NPIV
227 	 * is enabled.
228 	 */
229 	if (vp->rev.feaLevelHigh < 9)
230 		phba->sli3_options |= LPFC_SLI3_VPORT_TEARDOWN;
231 
232 	if (lpfc_is_LC_HBA(phba->pcidev->device))
233 		memcpy(phba->RandomData, (char *)&mb->un.varWords[24],
234 						sizeof (phba->RandomData));
235 
236 	/* Get adapter VPD information */
237 	lpfc_vpd_data = kmalloc(DMP_VPD_SIZE, GFP_KERNEL);
238 	if (!lpfc_vpd_data)
239 		goto out_free_mbox;
240 	do {
241 		lpfc_dump_mem(phba, pmb, offset, DMP_REGION_VPD);
242 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
243 
244 		if (rc != MBX_SUCCESS) {
245 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
246 					"0441 VPD not present on adapter, "
247 					"mbxCmd x%x DUMP VPD, mbxStatus x%x\n",
248 					mb->mbxCommand, mb->mbxStatus);
249 			mb->un.varDmp.word_cnt = 0;
250 		}
251 		/* dump mem may return a zero when finished or we got a
252 		 * mailbox error, either way we are done.
253 		 */
254 		if (mb->un.varDmp.word_cnt == 0)
255 			break;
256 		if (mb->un.varDmp.word_cnt > DMP_VPD_SIZE - offset)
257 			mb->un.varDmp.word_cnt = DMP_VPD_SIZE - offset;
258 		lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
259 				      lpfc_vpd_data + offset,
260 				      mb->un.varDmp.word_cnt);
261 		offset += mb->un.varDmp.word_cnt;
262 	} while (mb->un.varDmp.word_cnt && offset < DMP_VPD_SIZE);
263 	lpfc_parse_vpd(phba, lpfc_vpd_data, offset);
264 
265 	kfree(lpfc_vpd_data);
266 out_free_mbox:
267 	mempool_free(pmb, phba->mbox_mem_pool);
268 	return 0;
269 }
270 
271 /**
272  * lpfc_config_async_cmpl - Completion handler for config async event mbox cmd
273  * @phba: pointer to lpfc hba data structure.
274  * @pmboxq: pointer to the driver internal queue element for mailbox command.
275  *
276  * This is the completion handler for driver's configuring asynchronous event
277  * mailbox command to the device. If the mailbox command returns successfully,
278  * it will set internal async event support flag to 1; otherwise, it will
279  * set internal async event support flag to 0.
280  **/
281 static void
282 lpfc_config_async_cmpl(struct lpfc_hba * phba, LPFC_MBOXQ_t * pmboxq)
283 {
284 	if (pmboxq->u.mb.mbxStatus == MBX_SUCCESS)
285 		phba->temp_sensor_support = 1;
286 	else
287 		phba->temp_sensor_support = 0;
288 	mempool_free(pmboxq, phba->mbox_mem_pool);
289 	return;
290 }
291 
292 /**
293  * lpfc_dump_wakeup_param_cmpl - dump memory mailbox command completion handler
294  * @phba: pointer to lpfc hba data structure.
295  * @pmboxq: pointer to the driver internal queue element for mailbox command.
296  *
297  * This is the completion handler for dump mailbox command for getting
298  * wake up parameters. When this command complete, the response contain
299  * Option rom version of the HBA. This function translate the version number
300  * into a human readable string and store it in OptionROMVersion.
301  **/
302 static void
303 lpfc_dump_wakeup_param_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
304 {
305 	struct prog_id *prg;
306 	uint32_t prog_id_word;
307 	char dist = ' ';
308 	/* character array used for decoding dist type. */
309 	char dist_char[] = "nabx";
310 
311 	if (pmboxq->u.mb.mbxStatus != MBX_SUCCESS) {
312 		mempool_free(pmboxq, phba->mbox_mem_pool);
313 		return;
314 	}
315 
316 	prg = (struct prog_id *) &prog_id_word;
317 
318 	/* word 7 contain option rom version */
319 	prog_id_word = pmboxq->u.mb.un.varWords[7];
320 
321 	/* Decode the Option rom version word to a readable string */
322 	if (prg->dist < 4)
323 		dist = dist_char[prg->dist];
324 
325 	if ((prg->dist == 3) && (prg->num == 0))
326 		snprintf(phba->OptionROMVersion, 32, "%d.%d%d",
327 			prg->ver, prg->rev, prg->lev);
328 	else
329 		snprintf(phba->OptionROMVersion, 32, "%d.%d%d%c%d",
330 			prg->ver, prg->rev, prg->lev,
331 			dist, prg->num);
332 	mempool_free(pmboxq, phba->mbox_mem_pool);
333 	return;
334 }
335 
336 /**
337  * lpfc_update_vport_wwn - Updates the fc_nodename, fc_portname,
338  *	cfg_soft_wwnn, cfg_soft_wwpn
339  * @vport: pointer to lpfc vport data structure.
340  *
341  *
342  * Return codes
343  *   None.
344  **/
345 void
346 lpfc_update_vport_wwn(struct lpfc_vport *vport)
347 {
348 	uint8_t vvvl = vport->fc_sparam.cmn.valid_vendor_ver_level;
349 	u32 *fawwpn_key = (u32 *)&vport->fc_sparam.un.vendorVersion[0];
350 
351 	/* If the soft name exists then update it using the service params */
352 	if (vport->phba->cfg_soft_wwnn)
353 		u64_to_wwn(vport->phba->cfg_soft_wwnn,
354 			   vport->fc_sparam.nodeName.u.wwn);
355 	if (vport->phba->cfg_soft_wwpn)
356 		u64_to_wwn(vport->phba->cfg_soft_wwpn,
357 			   vport->fc_sparam.portName.u.wwn);
358 
359 	/*
360 	 * If the name is empty or there exists a soft name
361 	 * then copy the service params name, otherwise use the fc name
362 	 */
363 	if (vport->fc_nodename.u.wwn[0] == 0 || vport->phba->cfg_soft_wwnn)
364 		memcpy(&vport->fc_nodename, &vport->fc_sparam.nodeName,
365 			sizeof(struct lpfc_name));
366 	else
367 		memcpy(&vport->fc_sparam.nodeName, &vport->fc_nodename,
368 			sizeof(struct lpfc_name));
369 
370 	/*
371 	 * If the port name has changed, then set the Param changes flag
372 	 * to unreg the login
373 	 */
374 	if (vport->fc_portname.u.wwn[0] != 0 &&
375 		memcmp(&vport->fc_portname, &vport->fc_sparam.portName,
376 			sizeof(struct lpfc_name)))
377 		vport->vport_flag |= FAWWPN_PARAM_CHG;
378 
379 	if (vport->fc_portname.u.wwn[0] == 0 ||
380 	    vport->phba->cfg_soft_wwpn ||
381 	    (vvvl == 1 && cpu_to_be32(*fawwpn_key) == FAPWWN_KEY_VENDOR) ||
382 	    vport->vport_flag & FAWWPN_SET) {
383 		memcpy(&vport->fc_portname, &vport->fc_sparam.portName,
384 			sizeof(struct lpfc_name));
385 		vport->vport_flag &= ~FAWWPN_SET;
386 		if (vvvl == 1 && cpu_to_be32(*fawwpn_key) == FAPWWN_KEY_VENDOR)
387 			vport->vport_flag |= FAWWPN_SET;
388 	}
389 	else
390 		memcpy(&vport->fc_sparam.portName, &vport->fc_portname,
391 			sizeof(struct lpfc_name));
392 }
393 
394 /**
395  * lpfc_config_port_post - Perform lpfc initialization after config port
396  * @phba: pointer to lpfc hba data structure.
397  *
398  * This routine will do LPFC initialization after the CONFIG_PORT mailbox
399  * command call. It performs all internal resource and state setups on the
400  * port: post IOCB buffers, enable appropriate host interrupt attentions,
401  * ELS ring timers, etc.
402  *
403  * Return codes
404  *   0 - success.
405  *   Any other value - error.
406  **/
407 int
408 lpfc_config_port_post(struct lpfc_hba *phba)
409 {
410 	struct lpfc_vport *vport = phba->pport;
411 	struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
412 	LPFC_MBOXQ_t *pmb;
413 	MAILBOX_t *mb;
414 	struct lpfc_dmabuf *mp;
415 	struct lpfc_sli *psli = &phba->sli;
416 	uint32_t status, timeout;
417 	int i, j;
418 	int rc;
419 
420 	spin_lock_irq(&phba->hbalock);
421 	/*
422 	 * If the Config port completed correctly the HBA is not
423 	 * over heated any more.
424 	 */
425 	if (phba->over_temp_state == HBA_OVER_TEMP)
426 		phba->over_temp_state = HBA_NORMAL_TEMP;
427 	spin_unlock_irq(&phba->hbalock);
428 
429 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
430 	if (!pmb) {
431 		phba->link_state = LPFC_HBA_ERROR;
432 		return -ENOMEM;
433 	}
434 	mb = &pmb->u.mb;
435 
436 	/* Get login parameters for NID.  */
437 	rc = lpfc_read_sparam(phba, pmb, 0);
438 	if (rc) {
439 		mempool_free(pmb, phba->mbox_mem_pool);
440 		return -ENOMEM;
441 	}
442 
443 	pmb->vport = vport;
444 	if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
445 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
446 				"0448 Adapter failed init, mbxCmd x%x "
447 				"READ_SPARM mbxStatus x%x\n",
448 				mb->mbxCommand, mb->mbxStatus);
449 		phba->link_state = LPFC_HBA_ERROR;
450 		mp = (struct lpfc_dmabuf *)pmb->ctx_buf;
451 		mempool_free(pmb, phba->mbox_mem_pool);
452 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
453 		kfree(mp);
454 		return -EIO;
455 	}
456 
457 	mp = (struct lpfc_dmabuf *)pmb->ctx_buf;
458 
459 	memcpy(&vport->fc_sparam, mp->virt, sizeof (struct serv_parm));
460 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
461 	kfree(mp);
462 	pmb->ctx_buf = NULL;
463 	lpfc_update_vport_wwn(vport);
464 
465 	/* Update the fc_host data structures with new wwn. */
466 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
467 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
468 	fc_host_max_npiv_vports(shost) = phba->max_vpi;
469 
470 	/* If no serial number in VPD data, use low 6 bytes of WWNN */
471 	/* This should be consolidated into parse_vpd ? - mr */
472 	if (phba->SerialNumber[0] == 0) {
473 		uint8_t *outptr;
474 
475 		outptr = &vport->fc_nodename.u.s.IEEE[0];
476 		for (i = 0; i < 12; i++) {
477 			status = *outptr++;
478 			j = ((status & 0xf0) >> 4);
479 			if (j <= 9)
480 				phba->SerialNumber[i] =
481 				    (char)((uint8_t) 0x30 + (uint8_t) j);
482 			else
483 				phba->SerialNumber[i] =
484 				    (char)((uint8_t) 0x61 + (uint8_t) (j - 10));
485 			i++;
486 			j = (status & 0xf);
487 			if (j <= 9)
488 				phba->SerialNumber[i] =
489 				    (char)((uint8_t) 0x30 + (uint8_t) j);
490 			else
491 				phba->SerialNumber[i] =
492 				    (char)((uint8_t) 0x61 + (uint8_t) (j - 10));
493 		}
494 	}
495 
496 	lpfc_read_config(phba, pmb);
497 	pmb->vport = vport;
498 	if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
499 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
500 				"0453 Adapter failed to init, mbxCmd x%x "
501 				"READ_CONFIG, mbxStatus x%x\n",
502 				mb->mbxCommand, mb->mbxStatus);
503 		phba->link_state = LPFC_HBA_ERROR;
504 		mempool_free( pmb, phba->mbox_mem_pool);
505 		return -EIO;
506 	}
507 
508 	/* Check if the port is disabled */
509 	lpfc_sli_read_link_ste(phba);
510 
511 	/* Reset the DFT_HBA_Q_DEPTH to the max xri  */
512 	if (phba->cfg_hba_queue_depth > mb->un.varRdConfig.max_xri) {
513 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
514 				"3359 HBA queue depth changed from %d to %d\n",
515 				phba->cfg_hba_queue_depth,
516 				mb->un.varRdConfig.max_xri);
517 		phba->cfg_hba_queue_depth = mb->un.varRdConfig.max_xri;
518 	}
519 
520 	phba->lmt = mb->un.varRdConfig.lmt;
521 
522 	/* Get the default values for Model Name and Description */
523 	lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
524 
525 	phba->link_state = LPFC_LINK_DOWN;
526 
527 	/* Only process IOCBs on ELS ring till hba_state is READY */
528 	if (psli->sli3_ring[LPFC_EXTRA_RING].sli.sli3.cmdringaddr)
529 		psli->sli3_ring[LPFC_EXTRA_RING].flag |= LPFC_STOP_IOCB_EVENT;
530 	if (psli->sli3_ring[LPFC_FCP_RING].sli.sli3.cmdringaddr)
531 		psli->sli3_ring[LPFC_FCP_RING].flag |= LPFC_STOP_IOCB_EVENT;
532 
533 	/* Post receive buffers for desired rings */
534 	if (phba->sli_rev != 3)
535 		lpfc_post_rcv_buf(phba);
536 
537 	/*
538 	 * Configure HBA MSI-X attention conditions to messages if MSI-X mode
539 	 */
540 	if (phba->intr_type == MSIX) {
541 		rc = lpfc_config_msi(phba, pmb);
542 		if (rc) {
543 			mempool_free(pmb, phba->mbox_mem_pool);
544 			return -EIO;
545 		}
546 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
547 		if (rc != MBX_SUCCESS) {
548 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX,
549 					"0352 Config MSI mailbox command "
550 					"failed, mbxCmd x%x, mbxStatus x%x\n",
551 					pmb->u.mb.mbxCommand,
552 					pmb->u.mb.mbxStatus);
553 			mempool_free(pmb, phba->mbox_mem_pool);
554 			return -EIO;
555 		}
556 	}
557 
558 	spin_lock_irq(&phba->hbalock);
559 	/* Initialize ERATT handling flag */
560 	phba->hba_flag &= ~HBA_ERATT_HANDLED;
561 
562 	/* Enable appropriate host interrupts */
563 	if (lpfc_readl(phba->HCregaddr, &status)) {
564 		spin_unlock_irq(&phba->hbalock);
565 		return -EIO;
566 	}
567 	status |= HC_MBINT_ENA | HC_ERINT_ENA | HC_LAINT_ENA;
568 	if (psli->num_rings > 0)
569 		status |= HC_R0INT_ENA;
570 	if (psli->num_rings > 1)
571 		status |= HC_R1INT_ENA;
572 	if (psli->num_rings > 2)
573 		status |= HC_R2INT_ENA;
574 	if (psli->num_rings > 3)
575 		status |= HC_R3INT_ENA;
576 
577 	if ((phba->cfg_poll & ENABLE_FCP_RING_POLLING) &&
578 	    (phba->cfg_poll & DISABLE_FCP_RING_INT))
579 		status &= ~(HC_R0INT_ENA);
580 
581 	writel(status, phba->HCregaddr);
582 	readl(phba->HCregaddr); /* flush */
583 	spin_unlock_irq(&phba->hbalock);
584 
585 	/* Set up ring-0 (ELS) timer */
586 	timeout = phba->fc_ratov * 2;
587 	mod_timer(&vport->els_tmofunc,
588 		  jiffies + msecs_to_jiffies(1000 * timeout));
589 	/* Set up heart beat (HB) timer */
590 	mod_timer(&phba->hb_tmofunc,
591 		  jiffies + msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
592 	phba->hb_outstanding = 0;
593 	phba->last_completion_time = jiffies;
594 	/* Set up error attention (ERATT) polling timer */
595 	mod_timer(&phba->eratt_poll,
596 		  jiffies + msecs_to_jiffies(1000 * phba->eratt_poll_interval));
597 
598 	if (phba->hba_flag & LINK_DISABLED) {
599 		lpfc_printf_log(phba,
600 			KERN_ERR, LOG_INIT,
601 			"2598 Adapter Link is disabled.\n");
602 		lpfc_down_link(phba, pmb);
603 		pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
604 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
605 		if ((rc != MBX_SUCCESS) && (rc != MBX_BUSY)) {
606 			lpfc_printf_log(phba,
607 			KERN_ERR, LOG_INIT,
608 			"2599 Adapter failed to issue DOWN_LINK"
609 			" mbox command rc 0x%x\n", rc);
610 
611 			mempool_free(pmb, phba->mbox_mem_pool);
612 			return -EIO;
613 		}
614 	} else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
615 		mempool_free(pmb, phba->mbox_mem_pool);
616 		rc = phba->lpfc_hba_init_link(phba, MBX_NOWAIT);
617 		if (rc)
618 			return rc;
619 	}
620 	/* MBOX buffer will be freed in mbox compl */
621 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
622 	if (!pmb) {
623 		phba->link_state = LPFC_HBA_ERROR;
624 		return -ENOMEM;
625 	}
626 
627 	lpfc_config_async(phba, pmb, LPFC_ELS_RING);
628 	pmb->mbox_cmpl = lpfc_config_async_cmpl;
629 	pmb->vport = phba->pport;
630 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
631 
632 	if ((rc != MBX_BUSY) && (rc != MBX_SUCCESS)) {
633 		lpfc_printf_log(phba,
634 				KERN_ERR,
635 				LOG_INIT,
636 				"0456 Adapter failed to issue "
637 				"ASYNCEVT_ENABLE mbox status x%x\n",
638 				rc);
639 		mempool_free(pmb, phba->mbox_mem_pool);
640 	}
641 
642 	/* Get Option rom version */
643 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
644 	if (!pmb) {
645 		phba->link_state = LPFC_HBA_ERROR;
646 		return -ENOMEM;
647 	}
648 
649 	lpfc_dump_wakeup_param(phba, pmb);
650 	pmb->mbox_cmpl = lpfc_dump_wakeup_param_cmpl;
651 	pmb->vport = phba->pport;
652 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
653 
654 	if ((rc != MBX_BUSY) && (rc != MBX_SUCCESS)) {
655 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT, "0435 Adapter failed "
656 				"to get Option ROM version status x%x\n", rc);
657 		mempool_free(pmb, phba->mbox_mem_pool);
658 	}
659 
660 	return 0;
661 }
662 
663 /**
664  * lpfc_hba_init_link - Initialize the FC link
665  * @phba: pointer to lpfc hba data structure.
666  * @flag: mailbox command issue mode - either MBX_POLL or MBX_NOWAIT
667  *
668  * This routine will issue the INIT_LINK mailbox command call.
669  * It is available to other drivers through the lpfc_hba data
670  * structure for use as a delayed link up mechanism with the
671  * module parameter lpfc_suppress_link_up.
672  *
673  * Return code
674  *		0 - success
675  *		Any other value - error
676  **/
677 static int
678 lpfc_hba_init_link(struct lpfc_hba *phba, uint32_t flag)
679 {
680 	return lpfc_hba_init_link_fc_topology(phba, phba->cfg_topology, flag);
681 }
682 
683 /**
684  * lpfc_hba_init_link_fc_topology - Initialize FC link with desired topology
685  * @phba: pointer to lpfc hba data structure.
686  * @fc_topology: desired fc topology.
687  * @flag: mailbox command issue mode - either MBX_POLL or MBX_NOWAIT
688  *
689  * This routine will issue the INIT_LINK mailbox command call.
690  * It is available to other drivers through the lpfc_hba data
691  * structure for use as a delayed link up mechanism with the
692  * module parameter lpfc_suppress_link_up.
693  *
694  * Return code
695  *              0 - success
696  *              Any other value - error
697  **/
698 int
699 lpfc_hba_init_link_fc_topology(struct lpfc_hba *phba, uint32_t fc_topology,
700 			       uint32_t flag)
701 {
702 	struct lpfc_vport *vport = phba->pport;
703 	LPFC_MBOXQ_t *pmb;
704 	MAILBOX_t *mb;
705 	int rc;
706 
707 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
708 	if (!pmb) {
709 		phba->link_state = LPFC_HBA_ERROR;
710 		return -ENOMEM;
711 	}
712 	mb = &pmb->u.mb;
713 	pmb->vport = vport;
714 
715 	if ((phba->cfg_link_speed > LPFC_USER_LINK_SPEED_MAX) ||
716 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_1G) &&
717 	     !(phba->lmt & LMT_1Gb)) ||
718 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_2G) &&
719 	     !(phba->lmt & LMT_2Gb)) ||
720 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_4G) &&
721 	     !(phba->lmt & LMT_4Gb)) ||
722 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_8G) &&
723 	     !(phba->lmt & LMT_8Gb)) ||
724 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_10G) &&
725 	     !(phba->lmt & LMT_10Gb)) ||
726 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_16G) &&
727 	     !(phba->lmt & LMT_16Gb)) ||
728 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_32G) &&
729 	     !(phba->lmt & LMT_32Gb)) ||
730 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_64G) &&
731 	     !(phba->lmt & LMT_64Gb))) {
732 		/* Reset link speed to auto */
733 		lpfc_printf_log(phba, KERN_ERR, LOG_LINK_EVENT,
734 			"1302 Invalid speed for this board:%d "
735 			"Reset link speed to auto.\n",
736 			phba->cfg_link_speed);
737 			phba->cfg_link_speed = LPFC_USER_LINK_SPEED_AUTO;
738 	}
739 	lpfc_init_link(phba, pmb, fc_topology, phba->cfg_link_speed);
740 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
741 	if (phba->sli_rev < LPFC_SLI_REV4)
742 		lpfc_set_loopback_flag(phba);
743 	rc = lpfc_sli_issue_mbox(phba, pmb, flag);
744 	if ((rc != MBX_BUSY) && (rc != MBX_SUCCESS)) {
745 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
746 			"0498 Adapter failed to init, mbxCmd x%x "
747 			"INIT_LINK, mbxStatus x%x\n",
748 			mb->mbxCommand, mb->mbxStatus);
749 		if (phba->sli_rev <= LPFC_SLI_REV3) {
750 			/* Clear all interrupt enable conditions */
751 			writel(0, phba->HCregaddr);
752 			readl(phba->HCregaddr); /* flush */
753 			/* Clear all pending interrupts */
754 			writel(0xffffffff, phba->HAregaddr);
755 			readl(phba->HAregaddr); /* flush */
756 		}
757 		phba->link_state = LPFC_HBA_ERROR;
758 		if (rc != MBX_BUSY || flag == MBX_POLL)
759 			mempool_free(pmb, phba->mbox_mem_pool);
760 		return -EIO;
761 	}
762 	phba->cfg_suppress_link_up = LPFC_INITIALIZE_LINK;
763 	if (flag == MBX_POLL)
764 		mempool_free(pmb, phba->mbox_mem_pool);
765 
766 	return 0;
767 }
768 
769 /**
770  * lpfc_hba_down_link - this routine downs the FC link
771  * @phba: pointer to lpfc hba data structure.
772  * @flag: mailbox command issue mode - either MBX_POLL or MBX_NOWAIT
773  *
774  * This routine will issue the DOWN_LINK mailbox command call.
775  * It is available to other drivers through the lpfc_hba data
776  * structure for use to stop the link.
777  *
778  * Return code
779  *		0 - success
780  *		Any other value - error
781  **/
782 static int
783 lpfc_hba_down_link(struct lpfc_hba *phba, uint32_t flag)
784 {
785 	LPFC_MBOXQ_t *pmb;
786 	int rc;
787 
788 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
789 	if (!pmb) {
790 		phba->link_state = LPFC_HBA_ERROR;
791 		return -ENOMEM;
792 	}
793 
794 	lpfc_printf_log(phba,
795 		KERN_ERR, LOG_INIT,
796 		"0491 Adapter Link is disabled.\n");
797 	lpfc_down_link(phba, pmb);
798 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
799 	rc = lpfc_sli_issue_mbox(phba, pmb, flag);
800 	if ((rc != MBX_SUCCESS) && (rc != MBX_BUSY)) {
801 		lpfc_printf_log(phba,
802 		KERN_ERR, LOG_INIT,
803 		"2522 Adapter failed to issue DOWN_LINK"
804 		" mbox command rc 0x%x\n", rc);
805 
806 		mempool_free(pmb, phba->mbox_mem_pool);
807 		return -EIO;
808 	}
809 	if (flag == MBX_POLL)
810 		mempool_free(pmb, phba->mbox_mem_pool);
811 
812 	return 0;
813 }
814 
815 /**
816  * lpfc_hba_down_prep - Perform lpfc uninitialization prior to HBA reset
817  * @phba: pointer to lpfc HBA data structure.
818  *
819  * This routine will do LPFC uninitialization before the HBA is reset when
820  * bringing down the SLI Layer.
821  *
822  * Return codes
823  *   0 - success.
824  *   Any other value - error.
825  **/
826 int
827 lpfc_hba_down_prep(struct lpfc_hba *phba)
828 {
829 	struct lpfc_vport **vports;
830 	int i;
831 
832 	if (phba->sli_rev <= LPFC_SLI_REV3) {
833 		/* Disable interrupts */
834 		writel(0, phba->HCregaddr);
835 		readl(phba->HCregaddr); /* flush */
836 	}
837 
838 	if (phba->pport->load_flag & FC_UNLOADING)
839 		lpfc_cleanup_discovery_resources(phba->pport);
840 	else {
841 		vports = lpfc_create_vport_work_array(phba);
842 		if (vports != NULL)
843 			for (i = 0; i <= phba->max_vports &&
844 				vports[i] != NULL; i++)
845 				lpfc_cleanup_discovery_resources(vports[i]);
846 		lpfc_destroy_vport_work_array(phba, vports);
847 	}
848 	return 0;
849 }
850 
851 /**
852  * lpfc_sli4_free_sp_events - Cleanup sp_queue_events to free
853  * rspiocb which got deferred
854  *
855  * @phba: pointer to lpfc HBA data structure.
856  *
857  * This routine will cleanup completed slow path events after HBA is reset
858  * when bringing down the SLI Layer.
859  *
860  *
861  * Return codes
862  *   void.
863  **/
864 static void
865 lpfc_sli4_free_sp_events(struct lpfc_hba *phba)
866 {
867 	struct lpfc_iocbq *rspiocbq;
868 	struct hbq_dmabuf *dmabuf;
869 	struct lpfc_cq_event *cq_event;
870 
871 	spin_lock_irq(&phba->hbalock);
872 	phba->hba_flag &= ~HBA_SP_QUEUE_EVT;
873 	spin_unlock_irq(&phba->hbalock);
874 
875 	while (!list_empty(&phba->sli4_hba.sp_queue_event)) {
876 		/* Get the response iocb from the head of work queue */
877 		spin_lock_irq(&phba->hbalock);
878 		list_remove_head(&phba->sli4_hba.sp_queue_event,
879 				 cq_event, struct lpfc_cq_event, list);
880 		spin_unlock_irq(&phba->hbalock);
881 
882 		switch (bf_get(lpfc_wcqe_c_code, &cq_event->cqe.wcqe_cmpl)) {
883 		case CQE_CODE_COMPL_WQE:
884 			rspiocbq = container_of(cq_event, struct lpfc_iocbq,
885 						 cq_event);
886 			lpfc_sli_release_iocbq(phba, rspiocbq);
887 			break;
888 		case CQE_CODE_RECEIVE:
889 		case CQE_CODE_RECEIVE_V1:
890 			dmabuf = container_of(cq_event, struct hbq_dmabuf,
891 					      cq_event);
892 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
893 		}
894 	}
895 }
896 
897 /**
898  * lpfc_hba_free_post_buf - Perform lpfc uninitialization after HBA reset
899  * @phba: pointer to lpfc HBA data structure.
900  *
901  * This routine will cleanup posted ELS buffers after the HBA is reset
902  * when bringing down the SLI Layer.
903  *
904  *
905  * Return codes
906  *   void.
907  **/
908 static void
909 lpfc_hba_free_post_buf(struct lpfc_hba *phba)
910 {
911 	struct lpfc_sli *psli = &phba->sli;
912 	struct lpfc_sli_ring *pring;
913 	struct lpfc_dmabuf *mp, *next_mp;
914 	LIST_HEAD(buflist);
915 	int count;
916 
917 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)
918 		lpfc_sli_hbqbuf_free_all(phba);
919 	else {
920 		/* Cleanup preposted buffers on the ELS ring */
921 		pring = &psli->sli3_ring[LPFC_ELS_RING];
922 		spin_lock_irq(&phba->hbalock);
923 		list_splice_init(&pring->postbufq, &buflist);
924 		spin_unlock_irq(&phba->hbalock);
925 
926 		count = 0;
927 		list_for_each_entry_safe(mp, next_mp, &buflist, list) {
928 			list_del(&mp->list);
929 			count++;
930 			lpfc_mbuf_free(phba, mp->virt, mp->phys);
931 			kfree(mp);
932 		}
933 
934 		spin_lock_irq(&phba->hbalock);
935 		pring->postbufq_cnt -= count;
936 		spin_unlock_irq(&phba->hbalock);
937 	}
938 }
939 
940 /**
941  * lpfc_hba_clean_txcmplq - Perform lpfc uninitialization after HBA reset
942  * @phba: pointer to lpfc HBA data structure.
943  *
944  * This routine will cleanup the txcmplq after the HBA is reset when bringing
945  * down the SLI Layer.
946  *
947  * Return codes
948  *   void
949  **/
950 static void
951 lpfc_hba_clean_txcmplq(struct lpfc_hba *phba)
952 {
953 	struct lpfc_sli *psli = &phba->sli;
954 	struct lpfc_queue *qp = NULL;
955 	struct lpfc_sli_ring *pring;
956 	LIST_HEAD(completions);
957 	int i;
958 	struct lpfc_iocbq *piocb, *next_iocb;
959 
960 	if (phba->sli_rev != LPFC_SLI_REV4) {
961 		for (i = 0; i < psli->num_rings; i++) {
962 			pring = &psli->sli3_ring[i];
963 			spin_lock_irq(&phba->hbalock);
964 			/* At this point in time the HBA is either reset or DOA
965 			 * Nothing should be on txcmplq as it will
966 			 * NEVER complete.
967 			 */
968 			list_splice_init(&pring->txcmplq, &completions);
969 			pring->txcmplq_cnt = 0;
970 			spin_unlock_irq(&phba->hbalock);
971 
972 			lpfc_sli_abort_iocb_ring(phba, pring);
973 		}
974 		/* Cancel all the IOCBs from the completions list */
975 		lpfc_sli_cancel_iocbs(phba, &completions,
976 				      IOSTAT_LOCAL_REJECT, IOERR_SLI_ABORTED);
977 		return;
978 	}
979 	list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
980 		pring = qp->pring;
981 		if (!pring)
982 			continue;
983 		spin_lock_irq(&pring->ring_lock);
984 		list_for_each_entry_safe(piocb, next_iocb,
985 					 &pring->txcmplq, list)
986 			piocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
987 		list_splice_init(&pring->txcmplq, &completions);
988 		pring->txcmplq_cnt = 0;
989 		spin_unlock_irq(&pring->ring_lock);
990 		lpfc_sli_abort_iocb_ring(phba, pring);
991 	}
992 	/* Cancel all the IOCBs from the completions list */
993 	lpfc_sli_cancel_iocbs(phba, &completions,
994 			      IOSTAT_LOCAL_REJECT, IOERR_SLI_ABORTED);
995 }
996 
997 /**
998  * lpfc_hba_down_post_s3 - Perform lpfc uninitialization after HBA reset
999 	int i;
1000  * @phba: pointer to lpfc HBA data structure.
1001  *
1002  * This routine will do uninitialization after the HBA is reset when bring
1003  * down the SLI Layer.
1004  *
1005  * Return codes
1006  *   0 - success.
1007  *   Any other value - error.
1008  **/
1009 static int
1010 lpfc_hba_down_post_s3(struct lpfc_hba *phba)
1011 {
1012 	lpfc_hba_free_post_buf(phba);
1013 	lpfc_hba_clean_txcmplq(phba);
1014 	return 0;
1015 }
1016 
1017 /**
1018  * lpfc_hba_down_post_s4 - Perform lpfc uninitialization after HBA reset
1019  * @phba: pointer to lpfc HBA data structure.
1020  *
1021  * This routine will do uninitialization after the HBA is reset when bring
1022  * down the SLI Layer.
1023  *
1024  * Return codes
1025  *   0 - success.
1026  *   Any other value - error.
1027  **/
1028 static int
1029 lpfc_hba_down_post_s4(struct lpfc_hba *phba)
1030 {
1031 	struct lpfc_io_buf *psb, *psb_next;
1032 	struct lpfc_async_xchg_ctx *ctxp, *ctxp_next;
1033 	struct lpfc_sli4_hdw_queue *qp;
1034 	LIST_HEAD(aborts);
1035 	LIST_HEAD(nvme_aborts);
1036 	LIST_HEAD(nvmet_aborts);
1037 	struct lpfc_sglq *sglq_entry = NULL;
1038 	int cnt, idx;
1039 
1040 
1041 	lpfc_sli_hbqbuf_free_all(phba);
1042 	lpfc_hba_clean_txcmplq(phba);
1043 
1044 	/* At this point in time the HBA is either reset or DOA. Either
1045 	 * way, nothing should be on lpfc_abts_els_sgl_list, it needs to be
1046 	 * on the lpfc_els_sgl_list so that it can either be freed if the
1047 	 * driver is unloading or reposted if the driver is restarting
1048 	 * the port.
1049 	 */
1050 	spin_lock_irq(&phba->hbalock);  /* required for lpfc_els_sgl_list and */
1051 					/* scsl_buf_list */
1052 	/* sgl_list_lock required because worker thread uses this
1053 	 * list.
1054 	 */
1055 	spin_lock(&phba->sli4_hba.sgl_list_lock);
1056 	list_for_each_entry(sglq_entry,
1057 		&phba->sli4_hba.lpfc_abts_els_sgl_list, list)
1058 		sglq_entry->state = SGL_FREED;
1059 
1060 	list_splice_init(&phba->sli4_hba.lpfc_abts_els_sgl_list,
1061 			&phba->sli4_hba.lpfc_els_sgl_list);
1062 
1063 
1064 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
1065 
1066 	/* abts_xxxx_buf_list_lock required because worker thread uses this
1067 	 * list.
1068 	 */
1069 	cnt = 0;
1070 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
1071 		qp = &phba->sli4_hba.hdwq[idx];
1072 
1073 		spin_lock(&qp->abts_io_buf_list_lock);
1074 		list_splice_init(&qp->lpfc_abts_io_buf_list,
1075 				 &aborts);
1076 
1077 		list_for_each_entry_safe(psb, psb_next, &aborts, list) {
1078 			psb->pCmd = NULL;
1079 			psb->status = IOSTAT_SUCCESS;
1080 			cnt++;
1081 		}
1082 		spin_lock(&qp->io_buf_list_put_lock);
1083 		list_splice_init(&aborts, &qp->lpfc_io_buf_list_put);
1084 		qp->put_io_bufs += qp->abts_scsi_io_bufs;
1085 		qp->put_io_bufs += qp->abts_nvme_io_bufs;
1086 		qp->abts_scsi_io_bufs = 0;
1087 		qp->abts_nvme_io_bufs = 0;
1088 		spin_unlock(&qp->io_buf_list_put_lock);
1089 		spin_unlock(&qp->abts_io_buf_list_lock);
1090 	}
1091 	spin_unlock_irq(&phba->hbalock);
1092 
1093 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
1094 		spin_lock_irq(&phba->sli4_hba.abts_nvmet_buf_list_lock);
1095 		list_splice_init(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list,
1096 				 &nvmet_aborts);
1097 		spin_unlock_irq(&phba->sli4_hba.abts_nvmet_buf_list_lock);
1098 		list_for_each_entry_safe(ctxp, ctxp_next, &nvmet_aborts, list) {
1099 			ctxp->flag &= ~(LPFC_NVME_XBUSY | LPFC_NVME_ABORT_OP);
1100 			lpfc_nvmet_ctxbuf_post(phba, ctxp->ctxbuf);
1101 		}
1102 	}
1103 
1104 	lpfc_sli4_free_sp_events(phba);
1105 	return cnt;
1106 }
1107 
1108 /**
1109  * lpfc_hba_down_post - Wrapper func for hba down post routine
1110  * @phba: pointer to lpfc HBA data structure.
1111  *
1112  * This routine wraps the actual SLI3 or SLI4 routine for performing
1113  * uninitialization after the HBA is reset when bring down the SLI Layer.
1114  *
1115  * Return codes
1116  *   0 - success.
1117  *   Any other value - error.
1118  **/
1119 int
1120 lpfc_hba_down_post(struct lpfc_hba *phba)
1121 {
1122 	return (*phba->lpfc_hba_down_post)(phba);
1123 }
1124 
1125 /**
1126  * lpfc_hb_timeout - The HBA-timer timeout handler
1127  * @ptr: unsigned long holds the pointer to lpfc hba data structure.
1128  *
1129  * This is the HBA-timer timeout handler registered to the lpfc driver. When
1130  * this timer fires, a HBA timeout event shall be posted to the lpfc driver
1131  * work-port-events bitmap and the worker thread is notified. This timeout
1132  * event will be used by the worker thread to invoke the actual timeout
1133  * handler routine, lpfc_hb_timeout_handler. Any periodical operations will
1134  * be performed in the timeout handler and the HBA timeout event bit shall
1135  * be cleared by the worker thread after it has taken the event bitmap out.
1136  **/
1137 static void
1138 lpfc_hb_timeout(struct timer_list *t)
1139 {
1140 	struct lpfc_hba *phba;
1141 	uint32_t tmo_posted;
1142 	unsigned long iflag;
1143 
1144 	phba = from_timer(phba, t, hb_tmofunc);
1145 
1146 	/* Check for heart beat timeout conditions */
1147 	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
1148 	tmo_posted = phba->pport->work_port_events & WORKER_HB_TMO;
1149 	if (!tmo_posted)
1150 		phba->pport->work_port_events |= WORKER_HB_TMO;
1151 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
1152 
1153 	/* Tell the worker thread there is work to do */
1154 	if (!tmo_posted)
1155 		lpfc_worker_wake_up(phba);
1156 	return;
1157 }
1158 
1159 /**
1160  * lpfc_rrq_timeout - The RRQ-timer timeout handler
1161  * @ptr: unsigned long holds the pointer to lpfc hba data structure.
1162  *
1163  * This is the RRQ-timer timeout handler registered to the lpfc driver. When
1164  * this timer fires, a RRQ timeout event shall be posted to the lpfc driver
1165  * work-port-events bitmap and the worker thread is notified. This timeout
1166  * event will be used by the worker thread to invoke the actual timeout
1167  * handler routine, lpfc_rrq_handler. Any periodical operations will
1168  * be performed in the timeout handler and the RRQ timeout event bit shall
1169  * be cleared by the worker thread after it has taken the event bitmap out.
1170  **/
1171 static void
1172 lpfc_rrq_timeout(struct timer_list *t)
1173 {
1174 	struct lpfc_hba *phba;
1175 	unsigned long iflag;
1176 
1177 	phba = from_timer(phba, t, rrq_tmr);
1178 	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
1179 	if (!(phba->pport->load_flag & FC_UNLOADING))
1180 		phba->hba_flag |= HBA_RRQ_ACTIVE;
1181 	else
1182 		phba->hba_flag &= ~HBA_RRQ_ACTIVE;
1183 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
1184 
1185 	if (!(phba->pport->load_flag & FC_UNLOADING))
1186 		lpfc_worker_wake_up(phba);
1187 }
1188 
1189 /**
1190  * lpfc_hb_mbox_cmpl - The lpfc heart-beat mailbox command callback function
1191  * @phba: pointer to lpfc hba data structure.
1192  * @pmboxq: pointer to the driver internal queue element for mailbox command.
1193  *
1194  * This is the callback function to the lpfc heart-beat mailbox command.
1195  * If configured, the lpfc driver issues the heart-beat mailbox command to
1196  * the HBA every LPFC_HB_MBOX_INTERVAL (current 5) seconds. At the time the
1197  * heart-beat mailbox command is issued, the driver shall set up heart-beat
1198  * timeout timer to LPFC_HB_MBOX_TIMEOUT (current 30) seconds and marks
1199  * heart-beat outstanding state. Once the mailbox command comes back and
1200  * no error conditions detected, the heart-beat mailbox command timer is
1201  * reset to LPFC_HB_MBOX_INTERVAL seconds and the heart-beat outstanding
1202  * state is cleared for the next heart-beat. If the timer expired with the
1203  * heart-beat outstanding state set, the driver will put the HBA offline.
1204  **/
1205 static void
1206 lpfc_hb_mbox_cmpl(struct lpfc_hba * phba, LPFC_MBOXQ_t * pmboxq)
1207 {
1208 	unsigned long drvr_flag;
1209 
1210 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
1211 	phba->hb_outstanding = 0;
1212 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
1213 
1214 	/* Check and reset heart-beat timer is necessary */
1215 	mempool_free(pmboxq, phba->mbox_mem_pool);
1216 	if (!(phba->pport->fc_flag & FC_OFFLINE_MODE) &&
1217 		!(phba->link_state == LPFC_HBA_ERROR) &&
1218 		!(phba->pport->load_flag & FC_UNLOADING))
1219 		mod_timer(&phba->hb_tmofunc,
1220 			  jiffies +
1221 			  msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
1222 	return;
1223 }
1224 
1225 static void
1226 lpfc_hb_eq_delay_work(struct work_struct *work)
1227 {
1228 	struct lpfc_hba *phba = container_of(to_delayed_work(work),
1229 					     struct lpfc_hba, eq_delay_work);
1230 	struct lpfc_eq_intr_info *eqi, *eqi_new;
1231 	struct lpfc_queue *eq, *eq_next;
1232 	unsigned char *ena_delay = NULL;
1233 	uint32_t usdelay;
1234 	int i;
1235 
1236 	if (!phba->cfg_auto_imax || phba->pport->load_flag & FC_UNLOADING)
1237 		return;
1238 
1239 	if (phba->link_state == LPFC_HBA_ERROR ||
1240 	    phba->pport->fc_flag & FC_OFFLINE_MODE)
1241 		goto requeue;
1242 
1243 	ena_delay = kcalloc(phba->sli4_hba.num_possible_cpu, sizeof(*ena_delay),
1244 			    GFP_KERNEL);
1245 	if (!ena_delay)
1246 		goto requeue;
1247 
1248 	for (i = 0; i < phba->cfg_irq_chann; i++) {
1249 		/* Get the EQ corresponding to the IRQ vector */
1250 		eq = phba->sli4_hba.hba_eq_hdl[i].eq;
1251 		if (!eq)
1252 			continue;
1253 		if (eq->q_mode || eq->q_flag & HBA_EQ_DELAY_CHK) {
1254 			eq->q_flag &= ~HBA_EQ_DELAY_CHK;
1255 			ena_delay[eq->last_cpu] = 1;
1256 		}
1257 	}
1258 
1259 	for_each_present_cpu(i) {
1260 		eqi = per_cpu_ptr(phba->sli4_hba.eq_info, i);
1261 		if (ena_delay[i]) {
1262 			usdelay = (eqi->icnt >> 10) * LPFC_EQ_DELAY_STEP;
1263 			if (usdelay > LPFC_MAX_AUTO_EQ_DELAY)
1264 				usdelay = LPFC_MAX_AUTO_EQ_DELAY;
1265 		} else {
1266 			usdelay = 0;
1267 		}
1268 
1269 		eqi->icnt = 0;
1270 
1271 		list_for_each_entry_safe(eq, eq_next, &eqi->list, cpu_list) {
1272 			if (unlikely(eq->last_cpu != i)) {
1273 				eqi_new = per_cpu_ptr(phba->sli4_hba.eq_info,
1274 						      eq->last_cpu);
1275 				list_move_tail(&eq->cpu_list, &eqi_new->list);
1276 				continue;
1277 			}
1278 			if (usdelay != eq->q_mode)
1279 				lpfc_modify_hba_eq_delay(phba, eq->hdwq, 1,
1280 							 usdelay);
1281 		}
1282 	}
1283 
1284 	kfree(ena_delay);
1285 
1286 requeue:
1287 	queue_delayed_work(phba->wq, &phba->eq_delay_work,
1288 			   msecs_to_jiffies(LPFC_EQ_DELAY_MSECS));
1289 }
1290 
1291 /**
1292  * lpfc_hb_mxp_handler - Multi-XRI pools handler to adjust XRI distribution
1293  * @phba: pointer to lpfc hba data structure.
1294  *
1295  * For each heartbeat, this routine does some heuristic methods to adjust
1296  * XRI distribution. The goal is to fully utilize free XRIs.
1297  **/
1298 static void lpfc_hb_mxp_handler(struct lpfc_hba *phba)
1299 {
1300 	u32 i;
1301 	u32 hwq_count;
1302 
1303 	hwq_count = phba->cfg_hdw_queue;
1304 	for (i = 0; i < hwq_count; i++) {
1305 		/* Adjust XRIs in private pool */
1306 		lpfc_adjust_pvt_pool_count(phba, i);
1307 
1308 		/* Adjust high watermark */
1309 		lpfc_adjust_high_watermark(phba, i);
1310 
1311 #ifdef LPFC_MXP_STAT
1312 		/* Snapshot pbl, pvt and busy count */
1313 		lpfc_snapshot_mxp(phba, i);
1314 #endif
1315 	}
1316 }
1317 
1318 /**
1319  * lpfc_hb_timeout_handler - The HBA-timer timeout handler
1320  * @phba: pointer to lpfc hba data structure.
1321  *
1322  * This is the actual HBA-timer timeout handler to be invoked by the worker
1323  * thread whenever the HBA timer fired and HBA-timeout event posted. This
1324  * handler performs any periodic operations needed for the device. If such
1325  * periodic event has already been attended to either in the interrupt handler
1326  * or by processing slow-ring or fast-ring events within the HBA-timer
1327  * timeout window (LPFC_HB_MBOX_INTERVAL), this handler just simply resets
1328  * the timer for the next timeout period. If lpfc heart-beat mailbox command
1329  * is configured and there is no heart-beat mailbox command outstanding, a
1330  * heart-beat mailbox is issued and timer set properly. Otherwise, if there
1331  * has been a heart-beat mailbox command outstanding, the HBA shall be put
1332  * to offline.
1333  **/
1334 void
1335 lpfc_hb_timeout_handler(struct lpfc_hba *phba)
1336 {
1337 	struct lpfc_vport **vports;
1338 	LPFC_MBOXQ_t *pmboxq;
1339 	struct lpfc_dmabuf *buf_ptr;
1340 	int retval, i;
1341 	struct lpfc_sli *psli = &phba->sli;
1342 	LIST_HEAD(completions);
1343 
1344 	if (phba->cfg_xri_rebalancing) {
1345 		/* Multi-XRI pools handler */
1346 		lpfc_hb_mxp_handler(phba);
1347 	}
1348 
1349 	vports = lpfc_create_vport_work_array(phba);
1350 	if (vports != NULL)
1351 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
1352 			lpfc_rcv_seq_check_edtov(vports[i]);
1353 			lpfc_fdmi_change_check(vports[i]);
1354 		}
1355 	lpfc_destroy_vport_work_array(phba, vports);
1356 
1357 	if ((phba->link_state == LPFC_HBA_ERROR) ||
1358 		(phba->pport->load_flag & FC_UNLOADING) ||
1359 		(phba->pport->fc_flag & FC_OFFLINE_MODE))
1360 		return;
1361 
1362 	spin_lock_irq(&phba->pport->work_port_lock);
1363 
1364 	if (time_after(phba->last_completion_time +
1365 			msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL),
1366 			jiffies)) {
1367 		spin_unlock_irq(&phba->pport->work_port_lock);
1368 		if (!phba->hb_outstanding)
1369 			mod_timer(&phba->hb_tmofunc,
1370 				jiffies +
1371 				msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
1372 		else
1373 			mod_timer(&phba->hb_tmofunc,
1374 				jiffies +
1375 				msecs_to_jiffies(1000 * LPFC_HB_MBOX_TIMEOUT));
1376 		return;
1377 	}
1378 	spin_unlock_irq(&phba->pport->work_port_lock);
1379 
1380 	if (phba->elsbuf_cnt &&
1381 		(phba->elsbuf_cnt == phba->elsbuf_prev_cnt)) {
1382 		spin_lock_irq(&phba->hbalock);
1383 		list_splice_init(&phba->elsbuf, &completions);
1384 		phba->elsbuf_cnt = 0;
1385 		phba->elsbuf_prev_cnt = 0;
1386 		spin_unlock_irq(&phba->hbalock);
1387 
1388 		while (!list_empty(&completions)) {
1389 			list_remove_head(&completions, buf_ptr,
1390 				struct lpfc_dmabuf, list);
1391 			lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
1392 			kfree(buf_ptr);
1393 		}
1394 	}
1395 	phba->elsbuf_prev_cnt = phba->elsbuf_cnt;
1396 
1397 	/* If there is no heart beat outstanding, issue a heartbeat command */
1398 	if (phba->cfg_enable_hba_heartbeat) {
1399 		if (!phba->hb_outstanding) {
1400 			if ((!(psli->sli_flag & LPFC_SLI_MBOX_ACTIVE)) &&
1401 				(list_empty(&psli->mboxq))) {
1402 				pmboxq = mempool_alloc(phba->mbox_mem_pool,
1403 							GFP_KERNEL);
1404 				if (!pmboxq) {
1405 					mod_timer(&phba->hb_tmofunc,
1406 						 jiffies +
1407 						 msecs_to_jiffies(1000 *
1408 						 LPFC_HB_MBOX_INTERVAL));
1409 					return;
1410 				}
1411 
1412 				lpfc_heart_beat(phba, pmboxq);
1413 				pmboxq->mbox_cmpl = lpfc_hb_mbox_cmpl;
1414 				pmboxq->vport = phba->pport;
1415 				retval = lpfc_sli_issue_mbox(phba, pmboxq,
1416 						MBX_NOWAIT);
1417 
1418 				if (retval != MBX_BUSY &&
1419 					retval != MBX_SUCCESS) {
1420 					mempool_free(pmboxq,
1421 							phba->mbox_mem_pool);
1422 					mod_timer(&phba->hb_tmofunc,
1423 						jiffies +
1424 						msecs_to_jiffies(1000 *
1425 						LPFC_HB_MBOX_INTERVAL));
1426 					return;
1427 				}
1428 				phba->skipped_hb = 0;
1429 				phba->hb_outstanding = 1;
1430 			} else if (time_before_eq(phba->last_completion_time,
1431 					phba->skipped_hb)) {
1432 				lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
1433 					"2857 Last completion time not "
1434 					" updated in %d ms\n",
1435 					jiffies_to_msecs(jiffies
1436 						 - phba->last_completion_time));
1437 			} else
1438 				phba->skipped_hb = jiffies;
1439 
1440 			mod_timer(&phba->hb_tmofunc,
1441 				 jiffies +
1442 				 msecs_to_jiffies(1000 * LPFC_HB_MBOX_TIMEOUT));
1443 			return;
1444 		} else {
1445 			/*
1446 			* If heart beat timeout called with hb_outstanding set
1447 			* we need to give the hb mailbox cmd a chance to
1448 			* complete or TMO.
1449 			*/
1450 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
1451 					"0459 Adapter heartbeat still out"
1452 					"standing:last compl time was %d ms.\n",
1453 					jiffies_to_msecs(jiffies
1454 						 - phba->last_completion_time));
1455 			mod_timer(&phba->hb_tmofunc,
1456 				jiffies +
1457 				msecs_to_jiffies(1000 * LPFC_HB_MBOX_TIMEOUT));
1458 		}
1459 	} else {
1460 			mod_timer(&phba->hb_tmofunc,
1461 				jiffies +
1462 				msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
1463 	}
1464 }
1465 
1466 /**
1467  * lpfc_offline_eratt - Bring lpfc offline on hardware error attention
1468  * @phba: pointer to lpfc hba data structure.
1469  *
1470  * This routine is called to bring the HBA offline when HBA hardware error
1471  * other than Port Error 6 has been detected.
1472  **/
1473 static void
1474 lpfc_offline_eratt(struct lpfc_hba *phba)
1475 {
1476 	struct lpfc_sli   *psli = &phba->sli;
1477 
1478 	spin_lock_irq(&phba->hbalock);
1479 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1480 	spin_unlock_irq(&phba->hbalock);
1481 	lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
1482 
1483 	lpfc_offline(phba);
1484 	lpfc_reset_barrier(phba);
1485 	spin_lock_irq(&phba->hbalock);
1486 	lpfc_sli_brdreset(phba);
1487 	spin_unlock_irq(&phba->hbalock);
1488 	lpfc_hba_down_post(phba);
1489 	lpfc_sli_brdready(phba, HS_MBRDY);
1490 	lpfc_unblock_mgmt_io(phba);
1491 	phba->link_state = LPFC_HBA_ERROR;
1492 	return;
1493 }
1494 
1495 /**
1496  * lpfc_sli4_offline_eratt - Bring lpfc offline on SLI4 hardware error attention
1497  * @phba: pointer to lpfc hba data structure.
1498  *
1499  * This routine is called to bring a SLI4 HBA offline when HBA hardware error
1500  * other than Port Error 6 has been detected.
1501  **/
1502 void
1503 lpfc_sli4_offline_eratt(struct lpfc_hba *phba)
1504 {
1505 	spin_lock_irq(&phba->hbalock);
1506 	phba->link_state = LPFC_HBA_ERROR;
1507 	spin_unlock_irq(&phba->hbalock);
1508 
1509 	lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
1510 	lpfc_sli_flush_io_rings(phba);
1511 	lpfc_offline(phba);
1512 	lpfc_hba_down_post(phba);
1513 	lpfc_unblock_mgmt_io(phba);
1514 }
1515 
1516 /**
1517  * lpfc_handle_deferred_eratt - The HBA hardware deferred error handler
1518  * @phba: pointer to lpfc hba data structure.
1519  *
1520  * This routine is invoked to handle the deferred HBA hardware error
1521  * conditions. This type of error is indicated by HBA by setting ER1
1522  * and another ER bit in the host status register. The driver will
1523  * wait until the ER1 bit clears before handling the error condition.
1524  **/
1525 static void
1526 lpfc_handle_deferred_eratt(struct lpfc_hba *phba)
1527 {
1528 	uint32_t old_host_status = phba->work_hs;
1529 	struct lpfc_sli *psli = &phba->sli;
1530 
1531 	/* If the pci channel is offline, ignore possible errors,
1532 	 * since we cannot communicate with the pci card anyway.
1533 	 */
1534 	if (pci_channel_offline(phba->pcidev)) {
1535 		spin_lock_irq(&phba->hbalock);
1536 		phba->hba_flag &= ~DEFER_ERATT;
1537 		spin_unlock_irq(&phba->hbalock);
1538 		return;
1539 	}
1540 
1541 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
1542 		"0479 Deferred Adapter Hardware Error "
1543 		"Data: x%x x%x x%x\n",
1544 		phba->work_hs,
1545 		phba->work_status[0], phba->work_status[1]);
1546 
1547 	spin_lock_irq(&phba->hbalock);
1548 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1549 	spin_unlock_irq(&phba->hbalock);
1550 
1551 
1552 	/*
1553 	 * Firmware stops when it triggred erratt. That could cause the I/Os
1554 	 * dropped by the firmware. Error iocb (I/O) on txcmplq and let the
1555 	 * SCSI layer retry it after re-establishing link.
1556 	 */
1557 	lpfc_sli_abort_fcp_rings(phba);
1558 
1559 	/*
1560 	 * There was a firmware error. Take the hba offline and then
1561 	 * attempt to restart it.
1562 	 */
1563 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
1564 	lpfc_offline(phba);
1565 
1566 	/* Wait for the ER1 bit to clear.*/
1567 	while (phba->work_hs & HS_FFER1) {
1568 		msleep(100);
1569 		if (lpfc_readl(phba->HSregaddr, &phba->work_hs)) {
1570 			phba->work_hs = UNPLUG_ERR ;
1571 			break;
1572 		}
1573 		/* If driver is unloading let the worker thread continue */
1574 		if (phba->pport->load_flag & FC_UNLOADING) {
1575 			phba->work_hs = 0;
1576 			break;
1577 		}
1578 	}
1579 
1580 	/*
1581 	 * This is to ptrotect against a race condition in which
1582 	 * first write to the host attention register clear the
1583 	 * host status register.
1584 	 */
1585 	if ((!phba->work_hs) && (!(phba->pport->load_flag & FC_UNLOADING)))
1586 		phba->work_hs = old_host_status & ~HS_FFER1;
1587 
1588 	spin_lock_irq(&phba->hbalock);
1589 	phba->hba_flag &= ~DEFER_ERATT;
1590 	spin_unlock_irq(&phba->hbalock);
1591 	phba->work_status[0] = readl(phba->MBslimaddr + 0xa8);
1592 	phba->work_status[1] = readl(phba->MBslimaddr + 0xac);
1593 }
1594 
1595 static void
1596 lpfc_board_errevt_to_mgmt(struct lpfc_hba *phba)
1597 {
1598 	struct lpfc_board_event_header board_event;
1599 	struct Scsi_Host *shost;
1600 
1601 	board_event.event_type = FC_REG_BOARD_EVENT;
1602 	board_event.subcategory = LPFC_EVENT_PORTINTERR;
1603 	shost = lpfc_shost_from_vport(phba->pport);
1604 	fc_host_post_vendor_event(shost, fc_get_event_number(),
1605 				  sizeof(board_event),
1606 				  (char *) &board_event,
1607 				  LPFC_NL_VENDOR_ID);
1608 }
1609 
1610 /**
1611  * lpfc_handle_eratt_s3 - The SLI3 HBA hardware error handler
1612  * @phba: pointer to lpfc hba data structure.
1613  *
1614  * This routine is invoked to handle the following HBA hardware error
1615  * conditions:
1616  * 1 - HBA error attention interrupt
1617  * 2 - DMA ring index out of range
1618  * 3 - Mailbox command came back as unknown
1619  **/
1620 static void
1621 lpfc_handle_eratt_s3(struct lpfc_hba *phba)
1622 {
1623 	struct lpfc_vport *vport = phba->pport;
1624 	struct lpfc_sli   *psli = &phba->sli;
1625 	uint32_t event_data;
1626 	unsigned long temperature;
1627 	struct temp_event temp_event_data;
1628 	struct Scsi_Host  *shost;
1629 
1630 	/* If the pci channel is offline, ignore possible errors,
1631 	 * since we cannot communicate with the pci card anyway.
1632 	 */
1633 	if (pci_channel_offline(phba->pcidev)) {
1634 		spin_lock_irq(&phba->hbalock);
1635 		phba->hba_flag &= ~DEFER_ERATT;
1636 		spin_unlock_irq(&phba->hbalock);
1637 		return;
1638 	}
1639 
1640 	/* If resets are disabled then leave the HBA alone and return */
1641 	if (!phba->cfg_enable_hba_reset)
1642 		return;
1643 
1644 	/* Send an internal error event to mgmt application */
1645 	lpfc_board_errevt_to_mgmt(phba);
1646 
1647 	if (phba->hba_flag & DEFER_ERATT)
1648 		lpfc_handle_deferred_eratt(phba);
1649 
1650 	if ((phba->work_hs & HS_FFER6) || (phba->work_hs & HS_FFER8)) {
1651 		if (phba->work_hs & HS_FFER6)
1652 			/* Re-establishing Link */
1653 			lpfc_printf_log(phba, KERN_INFO, LOG_LINK_EVENT,
1654 					"1301 Re-establishing Link "
1655 					"Data: x%x x%x x%x\n",
1656 					phba->work_hs, phba->work_status[0],
1657 					phba->work_status[1]);
1658 		if (phba->work_hs & HS_FFER8)
1659 			/* Device Zeroization */
1660 			lpfc_printf_log(phba, KERN_INFO, LOG_LINK_EVENT,
1661 					"2861 Host Authentication device "
1662 					"zeroization Data:x%x x%x x%x\n",
1663 					phba->work_hs, phba->work_status[0],
1664 					phba->work_status[1]);
1665 
1666 		spin_lock_irq(&phba->hbalock);
1667 		psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1668 		spin_unlock_irq(&phba->hbalock);
1669 
1670 		/*
1671 		* Firmware stops when it triggled erratt with HS_FFER6.
1672 		* That could cause the I/Os dropped by the firmware.
1673 		* Error iocb (I/O) on txcmplq and let the SCSI layer
1674 		* retry it after re-establishing link.
1675 		*/
1676 		lpfc_sli_abort_fcp_rings(phba);
1677 
1678 		/*
1679 		 * There was a firmware error.  Take the hba offline and then
1680 		 * attempt to restart it.
1681 		 */
1682 		lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
1683 		lpfc_offline(phba);
1684 		lpfc_sli_brdrestart(phba);
1685 		if (lpfc_online(phba) == 0) {	/* Initialize the HBA */
1686 			lpfc_unblock_mgmt_io(phba);
1687 			return;
1688 		}
1689 		lpfc_unblock_mgmt_io(phba);
1690 	} else if (phba->work_hs & HS_CRIT_TEMP) {
1691 		temperature = readl(phba->MBslimaddr + TEMPERATURE_OFFSET);
1692 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
1693 		temp_event_data.event_code = LPFC_CRIT_TEMP;
1694 		temp_event_data.data = (uint32_t)temperature;
1695 
1696 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
1697 				"0406 Adapter maximum temperature exceeded "
1698 				"(%ld), taking this port offline "
1699 				"Data: x%x x%x x%x\n",
1700 				temperature, phba->work_hs,
1701 				phba->work_status[0], phba->work_status[1]);
1702 
1703 		shost = lpfc_shost_from_vport(phba->pport);
1704 		fc_host_post_vendor_event(shost, fc_get_event_number(),
1705 					  sizeof(temp_event_data),
1706 					  (char *) &temp_event_data,
1707 					  SCSI_NL_VID_TYPE_PCI
1708 					  | PCI_VENDOR_ID_EMULEX);
1709 
1710 		spin_lock_irq(&phba->hbalock);
1711 		phba->over_temp_state = HBA_OVER_TEMP;
1712 		spin_unlock_irq(&phba->hbalock);
1713 		lpfc_offline_eratt(phba);
1714 
1715 	} else {
1716 		/* The if clause above forces this code path when the status
1717 		 * failure is a value other than FFER6. Do not call the offline
1718 		 * twice. This is the adapter hardware error path.
1719 		 */
1720 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
1721 				"0457 Adapter Hardware Error "
1722 				"Data: x%x x%x x%x\n",
1723 				phba->work_hs,
1724 				phba->work_status[0], phba->work_status[1]);
1725 
1726 		event_data = FC_REG_DUMP_EVENT;
1727 		shost = lpfc_shost_from_vport(vport);
1728 		fc_host_post_vendor_event(shost, fc_get_event_number(),
1729 				sizeof(event_data), (char *) &event_data,
1730 				SCSI_NL_VID_TYPE_PCI | PCI_VENDOR_ID_EMULEX);
1731 
1732 		lpfc_offline_eratt(phba);
1733 	}
1734 	return;
1735 }
1736 
1737 /**
1738  * lpfc_sli4_port_sta_fn_reset - The SLI4 function reset due to port status reg
1739  * @phba: pointer to lpfc hba data structure.
1740  * @mbx_action: flag for mailbox shutdown action.
1741  *
1742  * This routine is invoked to perform an SLI4 port PCI function reset in
1743  * response to port status register polling attention. It waits for port
1744  * status register (ERR, RDY, RN) bits before proceeding with function reset.
1745  * During this process, interrupt vectors are freed and later requested
1746  * for handling possible port resource change.
1747  **/
1748 static int
1749 lpfc_sli4_port_sta_fn_reset(struct lpfc_hba *phba, int mbx_action,
1750 			    bool en_rn_msg)
1751 {
1752 	int rc;
1753 	uint32_t intr_mode;
1754 
1755 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) >=
1756 	    LPFC_SLI_INTF_IF_TYPE_2) {
1757 		/*
1758 		 * On error status condition, driver need to wait for port
1759 		 * ready before performing reset.
1760 		 */
1761 		rc = lpfc_sli4_pdev_status_reg_wait(phba);
1762 		if (rc)
1763 			return rc;
1764 	}
1765 
1766 	/* need reset: attempt for port recovery */
1767 	if (en_rn_msg)
1768 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
1769 				"2887 Reset Needed: Attempting Port "
1770 				"Recovery...\n");
1771 	lpfc_offline_prep(phba, mbx_action);
1772 	lpfc_sli_flush_io_rings(phba);
1773 	lpfc_offline(phba);
1774 	/* release interrupt for possible resource change */
1775 	lpfc_sli4_disable_intr(phba);
1776 	rc = lpfc_sli_brdrestart(phba);
1777 	if (rc) {
1778 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
1779 				"6309 Failed to restart board\n");
1780 		return rc;
1781 	}
1782 	/* request and enable interrupt */
1783 	intr_mode = lpfc_sli4_enable_intr(phba, phba->intr_mode);
1784 	if (intr_mode == LPFC_INTR_ERROR) {
1785 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
1786 				"3175 Failed to enable interrupt\n");
1787 		return -EIO;
1788 	}
1789 	phba->intr_mode = intr_mode;
1790 	rc = lpfc_online(phba);
1791 	if (rc == 0)
1792 		lpfc_unblock_mgmt_io(phba);
1793 
1794 	return rc;
1795 }
1796 
1797 /**
1798  * lpfc_handle_eratt_s4 - The SLI4 HBA hardware error handler
1799  * @phba: pointer to lpfc hba data structure.
1800  *
1801  * This routine is invoked to handle the SLI4 HBA hardware error attention
1802  * conditions.
1803  **/
1804 static void
1805 lpfc_handle_eratt_s4(struct lpfc_hba *phba)
1806 {
1807 	struct lpfc_vport *vport = phba->pport;
1808 	uint32_t event_data;
1809 	struct Scsi_Host *shost;
1810 	uint32_t if_type;
1811 	struct lpfc_register portstat_reg = {0};
1812 	uint32_t reg_err1, reg_err2;
1813 	uint32_t uerrlo_reg, uemasklo_reg;
1814 	uint32_t smphr_port_status = 0, pci_rd_rc1, pci_rd_rc2;
1815 	bool en_rn_msg = true;
1816 	struct temp_event temp_event_data;
1817 	struct lpfc_register portsmphr_reg;
1818 	int rc, i;
1819 
1820 	/* If the pci channel is offline, ignore possible errors, since
1821 	 * we cannot communicate with the pci card anyway.
1822 	 */
1823 	if (pci_channel_offline(phba->pcidev)) {
1824 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
1825 				"3166 pci channel is offline\n");
1826 		lpfc_sli4_offline_eratt(phba);
1827 		return;
1828 	}
1829 
1830 	memset(&portsmphr_reg, 0, sizeof(portsmphr_reg));
1831 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
1832 	switch (if_type) {
1833 	case LPFC_SLI_INTF_IF_TYPE_0:
1834 		pci_rd_rc1 = lpfc_readl(
1835 				phba->sli4_hba.u.if_type0.UERRLOregaddr,
1836 				&uerrlo_reg);
1837 		pci_rd_rc2 = lpfc_readl(
1838 				phba->sli4_hba.u.if_type0.UEMASKLOregaddr,
1839 				&uemasklo_reg);
1840 		/* consider PCI bus read error as pci_channel_offline */
1841 		if (pci_rd_rc1 == -EIO && pci_rd_rc2 == -EIO)
1842 			return;
1843 		if (!(phba->hba_flag & HBA_RECOVERABLE_UE)) {
1844 			lpfc_sli4_offline_eratt(phba);
1845 			return;
1846 		}
1847 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
1848 				"7623 Checking UE recoverable");
1849 
1850 		for (i = 0; i < phba->sli4_hba.ue_to_sr / 1000; i++) {
1851 			if (lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
1852 				       &portsmphr_reg.word0))
1853 				continue;
1854 
1855 			smphr_port_status = bf_get(lpfc_port_smphr_port_status,
1856 						   &portsmphr_reg);
1857 			if ((smphr_port_status & LPFC_PORT_SEM_MASK) ==
1858 			    LPFC_PORT_SEM_UE_RECOVERABLE)
1859 				break;
1860 			/*Sleep for 1Sec, before checking SEMAPHORE */
1861 			msleep(1000);
1862 		}
1863 
1864 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
1865 				"4827 smphr_port_status x%x : Waited %dSec",
1866 				smphr_port_status, i);
1867 
1868 		/* Recoverable UE, reset the HBA device */
1869 		if ((smphr_port_status & LPFC_PORT_SEM_MASK) ==
1870 		    LPFC_PORT_SEM_UE_RECOVERABLE) {
1871 			for (i = 0; i < 20; i++) {
1872 				msleep(1000);
1873 				if (!lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
1874 				    &portsmphr_reg.word0) &&
1875 				    (LPFC_POST_STAGE_PORT_READY ==
1876 				     bf_get(lpfc_port_smphr_port_status,
1877 				     &portsmphr_reg))) {
1878 					rc = lpfc_sli4_port_sta_fn_reset(phba,
1879 						LPFC_MBX_NO_WAIT, en_rn_msg);
1880 					if (rc == 0)
1881 						return;
1882 					lpfc_printf_log(phba,
1883 						KERN_ERR, LOG_INIT,
1884 						"4215 Failed to recover UE");
1885 					break;
1886 				}
1887 			}
1888 		}
1889 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
1890 				"7624 Firmware not ready: Failing UE recovery,"
1891 				" waited %dSec", i);
1892 		phba->link_state = LPFC_HBA_ERROR;
1893 		break;
1894 
1895 	case LPFC_SLI_INTF_IF_TYPE_2:
1896 	case LPFC_SLI_INTF_IF_TYPE_6:
1897 		pci_rd_rc1 = lpfc_readl(
1898 				phba->sli4_hba.u.if_type2.STATUSregaddr,
1899 				&portstat_reg.word0);
1900 		/* consider PCI bus read error as pci_channel_offline */
1901 		if (pci_rd_rc1 == -EIO) {
1902 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
1903 				"3151 PCI bus read access failure: x%x\n",
1904 				readl(phba->sli4_hba.u.if_type2.STATUSregaddr));
1905 			lpfc_sli4_offline_eratt(phba);
1906 			return;
1907 		}
1908 		reg_err1 = readl(phba->sli4_hba.u.if_type2.ERR1regaddr);
1909 		reg_err2 = readl(phba->sli4_hba.u.if_type2.ERR2regaddr);
1910 		if (bf_get(lpfc_sliport_status_oti, &portstat_reg)) {
1911 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
1912 				"2889 Port Overtemperature event, "
1913 				"taking port offline Data: x%x x%x\n",
1914 				reg_err1, reg_err2);
1915 
1916 			phba->sfp_alarm |= LPFC_TRANSGRESSION_HIGH_TEMPERATURE;
1917 			temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
1918 			temp_event_data.event_code = LPFC_CRIT_TEMP;
1919 			temp_event_data.data = 0xFFFFFFFF;
1920 
1921 			shost = lpfc_shost_from_vport(phba->pport);
1922 			fc_host_post_vendor_event(shost, fc_get_event_number(),
1923 						  sizeof(temp_event_data),
1924 						  (char *)&temp_event_data,
1925 						  SCSI_NL_VID_TYPE_PCI
1926 						  | PCI_VENDOR_ID_EMULEX);
1927 
1928 			spin_lock_irq(&phba->hbalock);
1929 			phba->over_temp_state = HBA_OVER_TEMP;
1930 			spin_unlock_irq(&phba->hbalock);
1931 			lpfc_sli4_offline_eratt(phba);
1932 			return;
1933 		}
1934 		if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
1935 		    reg_err2 == SLIPORT_ERR2_REG_FW_RESTART) {
1936 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
1937 					"3143 Port Down: Firmware Update "
1938 					"Detected\n");
1939 			en_rn_msg = false;
1940 		} else if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
1941 			 reg_err2 == SLIPORT_ERR2_REG_FORCED_DUMP)
1942 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
1943 					"3144 Port Down: Debug Dump\n");
1944 		else if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
1945 			 reg_err2 == SLIPORT_ERR2_REG_FUNC_PROVISON)
1946 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
1947 					"3145 Port Down: Provisioning\n");
1948 
1949 		/* If resets are disabled then leave the HBA alone and return */
1950 		if (!phba->cfg_enable_hba_reset)
1951 			return;
1952 
1953 		/* Check port status register for function reset */
1954 		rc = lpfc_sli4_port_sta_fn_reset(phba, LPFC_MBX_NO_WAIT,
1955 				en_rn_msg);
1956 		if (rc == 0) {
1957 			/* don't report event on forced debug dump */
1958 			if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
1959 			    reg_err2 == SLIPORT_ERR2_REG_FORCED_DUMP)
1960 				return;
1961 			else
1962 				break;
1963 		}
1964 		/* fall through for not able to recover */
1965 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
1966 				"3152 Unrecoverable error\n");
1967 		phba->link_state = LPFC_HBA_ERROR;
1968 		break;
1969 	case LPFC_SLI_INTF_IF_TYPE_1:
1970 	default:
1971 		break;
1972 	}
1973 	lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
1974 			"3123 Report dump event to upper layer\n");
1975 	/* Send an internal error event to mgmt application */
1976 	lpfc_board_errevt_to_mgmt(phba);
1977 
1978 	event_data = FC_REG_DUMP_EVENT;
1979 	shost = lpfc_shost_from_vport(vport);
1980 	fc_host_post_vendor_event(shost, fc_get_event_number(),
1981 				  sizeof(event_data), (char *) &event_data,
1982 				  SCSI_NL_VID_TYPE_PCI | PCI_VENDOR_ID_EMULEX);
1983 }
1984 
1985 /**
1986  * lpfc_handle_eratt - Wrapper func for handling hba error attention
1987  * @phba: pointer to lpfc HBA data structure.
1988  *
1989  * This routine wraps the actual SLI3 or SLI4 hba error attention handling
1990  * routine from the API jump table function pointer from the lpfc_hba struct.
1991  *
1992  * Return codes
1993  *   0 - success.
1994  *   Any other value - error.
1995  **/
1996 void
1997 lpfc_handle_eratt(struct lpfc_hba *phba)
1998 {
1999 	(*phba->lpfc_handle_eratt)(phba);
2000 }
2001 
2002 /**
2003  * lpfc_handle_latt - The HBA link event handler
2004  * @phba: pointer to lpfc hba data structure.
2005  *
2006  * This routine is invoked from the worker thread to handle a HBA host
2007  * attention link event. SLI3 only.
2008  **/
2009 void
2010 lpfc_handle_latt(struct lpfc_hba *phba)
2011 {
2012 	struct lpfc_vport *vport = phba->pport;
2013 	struct lpfc_sli   *psli = &phba->sli;
2014 	LPFC_MBOXQ_t *pmb;
2015 	volatile uint32_t control;
2016 	struct lpfc_dmabuf *mp;
2017 	int rc = 0;
2018 
2019 	pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
2020 	if (!pmb) {
2021 		rc = 1;
2022 		goto lpfc_handle_latt_err_exit;
2023 	}
2024 
2025 	mp = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
2026 	if (!mp) {
2027 		rc = 2;
2028 		goto lpfc_handle_latt_free_pmb;
2029 	}
2030 
2031 	mp->virt = lpfc_mbuf_alloc(phba, 0, &mp->phys);
2032 	if (!mp->virt) {
2033 		rc = 3;
2034 		goto lpfc_handle_latt_free_mp;
2035 	}
2036 
2037 	/* Cleanup any outstanding ELS commands */
2038 	lpfc_els_flush_all_cmd(phba);
2039 
2040 	psli->slistat.link_event++;
2041 	lpfc_read_topology(phba, pmb, mp);
2042 	pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
2043 	pmb->vport = vport;
2044 	/* Block ELS IOCBs until we have processed this mbox command */
2045 	phba->sli.sli3_ring[LPFC_ELS_RING].flag |= LPFC_STOP_IOCB_EVENT;
2046 	rc = lpfc_sli_issue_mbox (phba, pmb, MBX_NOWAIT);
2047 	if (rc == MBX_NOT_FINISHED) {
2048 		rc = 4;
2049 		goto lpfc_handle_latt_free_mbuf;
2050 	}
2051 
2052 	/* Clear Link Attention in HA REG */
2053 	spin_lock_irq(&phba->hbalock);
2054 	writel(HA_LATT, phba->HAregaddr);
2055 	readl(phba->HAregaddr); /* flush */
2056 	spin_unlock_irq(&phba->hbalock);
2057 
2058 	return;
2059 
2060 lpfc_handle_latt_free_mbuf:
2061 	phba->sli.sli3_ring[LPFC_ELS_RING].flag &= ~LPFC_STOP_IOCB_EVENT;
2062 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
2063 lpfc_handle_latt_free_mp:
2064 	kfree(mp);
2065 lpfc_handle_latt_free_pmb:
2066 	mempool_free(pmb, phba->mbox_mem_pool);
2067 lpfc_handle_latt_err_exit:
2068 	/* Enable Link attention interrupts */
2069 	spin_lock_irq(&phba->hbalock);
2070 	psli->sli_flag |= LPFC_PROCESS_LA;
2071 	control = readl(phba->HCregaddr);
2072 	control |= HC_LAINT_ENA;
2073 	writel(control, phba->HCregaddr);
2074 	readl(phba->HCregaddr); /* flush */
2075 
2076 	/* Clear Link Attention in HA REG */
2077 	writel(HA_LATT, phba->HAregaddr);
2078 	readl(phba->HAregaddr); /* flush */
2079 	spin_unlock_irq(&phba->hbalock);
2080 	lpfc_linkdown(phba);
2081 	phba->link_state = LPFC_HBA_ERROR;
2082 
2083 	lpfc_printf_log(phba, KERN_ERR, LOG_MBOX,
2084 		     "0300 LATT: Cannot issue READ_LA: Data:%d\n", rc);
2085 
2086 	return;
2087 }
2088 
2089 /**
2090  * lpfc_parse_vpd - Parse VPD (Vital Product Data)
2091  * @phba: pointer to lpfc hba data structure.
2092  * @vpd: pointer to the vital product data.
2093  * @len: length of the vital product data in bytes.
2094  *
2095  * This routine parses the Vital Product Data (VPD). The VPD is treated as
2096  * an array of characters. In this routine, the ModelName, ProgramType, and
2097  * ModelDesc, etc. fields of the phba data structure will be populated.
2098  *
2099  * Return codes
2100  *   0 - pointer to the VPD passed in is NULL
2101  *   1 - success
2102  **/
2103 int
2104 lpfc_parse_vpd(struct lpfc_hba *phba, uint8_t *vpd, int len)
2105 {
2106 	uint8_t lenlo, lenhi;
2107 	int Length;
2108 	int i, j;
2109 	int finished = 0;
2110 	int index = 0;
2111 
2112 	if (!vpd)
2113 		return 0;
2114 
2115 	/* Vital Product */
2116 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
2117 			"0455 Vital Product Data: x%x x%x x%x x%x\n",
2118 			(uint32_t) vpd[0], (uint32_t) vpd[1], (uint32_t) vpd[2],
2119 			(uint32_t) vpd[3]);
2120 	while (!finished && (index < (len - 4))) {
2121 		switch (vpd[index]) {
2122 		case 0x82:
2123 		case 0x91:
2124 			index += 1;
2125 			lenlo = vpd[index];
2126 			index += 1;
2127 			lenhi = vpd[index];
2128 			index += 1;
2129 			i = ((((unsigned short)lenhi) << 8) + lenlo);
2130 			index += i;
2131 			break;
2132 		case 0x90:
2133 			index += 1;
2134 			lenlo = vpd[index];
2135 			index += 1;
2136 			lenhi = vpd[index];
2137 			index += 1;
2138 			Length = ((((unsigned short)lenhi) << 8) + lenlo);
2139 			if (Length > len - index)
2140 				Length = len - index;
2141 			while (Length > 0) {
2142 			/* Look for Serial Number */
2143 			if ((vpd[index] == 'S') && (vpd[index+1] == 'N')) {
2144 				index += 2;
2145 				i = vpd[index];
2146 				index += 1;
2147 				j = 0;
2148 				Length -= (3+i);
2149 				while(i--) {
2150 					phba->SerialNumber[j++] = vpd[index++];
2151 					if (j == 31)
2152 						break;
2153 				}
2154 				phba->SerialNumber[j] = 0;
2155 				continue;
2156 			}
2157 			else if ((vpd[index] == 'V') && (vpd[index+1] == '1')) {
2158 				phba->vpd_flag |= VPD_MODEL_DESC;
2159 				index += 2;
2160 				i = vpd[index];
2161 				index += 1;
2162 				j = 0;
2163 				Length -= (3+i);
2164 				while(i--) {
2165 					phba->ModelDesc[j++] = vpd[index++];
2166 					if (j == 255)
2167 						break;
2168 				}
2169 				phba->ModelDesc[j] = 0;
2170 				continue;
2171 			}
2172 			else if ((vpd[index] == 'V') && (vpd[index+1] == '2')) {
2173 				phba->vpd_flag |= VPD_MODEL_NAME;
2174 				index += 2;
2175 				i = vpd[index];
2176 				index += 1;
2177 				j = 0;
2178 				Length -= (3+i);
2179 				while(i--) {
2180 					phba->ModelName[j++] = vpd[index++];
2181 					if (j == 79)
2182 						break;
2183 				}
2184 				phba->ModelName[j] = 0;
2185 				continue;
2186 			}
2187 			else if ((vpd[index] == 'V') && (vpd[index+1] == '3')) {
2188 				phba->vpd_flag |= VPD_PROGRAM_TYPE;
2189 				index += 2;
2190 				i = vpd[index];
2191 				index += 1;
2192 				j = 0;
2193 				Length -= (3+i);
2194 				while(i--) {
2195 					phba->ProgramType[j++] = vpd[index++];
2196 					if (j == 255)
2197 						break;
2198 				}
2199 				phba->ProgramType[j] = 0;
2200 				continue;
2201 			}
2202 			else if ((vpd[index] == 'V') && (vpd[index+1] == '4')) {
2203 				phba->vpd_flag |= VPD_PORT;
2204 				index += 2;
2205 				i = vpd[index];
2206 				index += 1;
2207 				j = 0;
2208 				Length -= (3+i);
2209 				while(i--) {
2210 					if ((phba->sli_rev == LPFC_SLI_REV4) &&
2211 					    (phba->sli4_hba.pport_name_sta ==
2212 					     LPFC_SLI4_PPNAME_GET)) {
2213 						j++;
2214 						index++;
2215 					} else
2216 						phba->Port[j++] = vpd[index++];
2217 					if (j == 19)
2218 						break;
2219 				}
2220 				if ((phba->sli_rev != LPFC_SLI_REV4) ||
2221 				    (phba->sli4_hba.pport_name_sta ==
2222 				     LPFC_SLI4_PPNAME_NON))
2223 					phba->Port[j] = 0;
2224 				continue;
2225 			}
2226 			else {
2227 				index += 2;
2228 				i = vpd[index];
2229 				index += 1;
2230 				index += i;
2231 				Length -= (3 + i);
2232 			}
2233 		}
2234 		finished = 0;
2235 		break;
2236 		case 0x78:
2237 			finished = 1;
2238 			break;
2239 		default:
2240 			index ++;
2241 			break;
2242 		}
2243 	}
2244 
2245 	return(1);
2246 }
2247 
2248 /**
2249  * lpfc_get_hba_model_desc - Retrieve HBA device model name and description
2250  * @phba: pointer to lpfc hba data structure.
2251  * @mdp: pointer to the data structure to hold the derived model name.
2252  * @descp: pointer to the data structure to hold the derived description.
2253  *
2254  * This routine retrieves HBA's description based on its registered PCI device
2255  * ID. The @descp passed into this function points to an array of 256 chars. It
2256  * shall be returned with the model name, maximum speed, and the host bus type.
2257  * The @mdp passed into this function points to an array of 80 chars. When the
2258  * function returns, the @mdp will be filled with the model name.
2259  **/
2260 static void
2261 lpfc_get_hba_model_desc(struct lpfc_hba *phba, uint8_t *mdp, uint8_t *descp)
2262 {
2263 	lpfc_vpd_t *vp;
2264 	uint16_t dev_id = phba->pcidev->device;
2265 	int max_speed;
2266 	int GE = 0;
2267 	int oneConnect = 0; /* default is not a oneConnect */
2268 	struct {
2269 		char *name;
2270 		char *bus;
2271 		char *function;
2272 	} m = {"<Unknown>", "", ""};
2273 
2274 	if (mdp && mdp[0] != '\0'
2275 		&& descp && descp[0] != '\0')
2276 		return;
2277 
2278 	if (phba->lmt & LMT_64Gb)
2279 		max_speed = 64;
2280 	else if (phba->lmt & LMT_32Gb)
2281 		max_speed = 32;
2282 	else if (phba->lmt & LMT_16Gb)
2283 		max_speed = 16;
2284 	else if (phba->lmt & LMT_10Gb)
2285 		max_speed = 10;
2286 	else if (phba->lmt & LMT_8Gb)
2287 		max_speed = 8;
2288 	else if (phba->lmt & LMT_4Gb)
2289 		max_speed = 4;
2290 	else if (phba->lmt & LMT_2Gb)
2291 		max_speed = 2;
2292 	else if (phba->lmt & LMT_1Gb)
2293 		max_speed = 1;
2294 	else
2295 		max_speed = 0;
2296 
2297 	vp = &phba->vpd;
2298 
2299 	switch (dev_id) {
2300 	case PCI_DEVICE_ID_FIREFLY:
2301 		m = (typeof(m)){"LP6000", "PCI",
2302 				"Obsolete, Unsupported Fibre Channel Adapter"};
2303 		break;
2304 	case PCI_DEVICE_ID_SUPERFLY:
2305 		if (vp->rev.biuRev >= 1 && vp->rev.biuRev <= 3)
2306 			m = (typeof(m)){"LP7000", "PCI", ""};
2307 		else
2308 			m = (typeof(m)){"LP7000E", "PCI", ""};
2309 		m.function = "Obsolete, Unsupported Fibre Channel Adapter";
2310 		break;
2311 	case PCI_DEVICE_ID_DRAGONFLY:
2312 		m = (typeof(m)){"LP8000", "PCI",
2313 				"Obsolete, Unsupported Fibre Channel Adapter"};
2314 		break;
2315 	case PCI_DEVICE_ID_CENTAUR:
2316 		if (FC_JEDEC_ID(vp->rev.biuRev) == CENTAUR_2G_JEDEC_ID)
2317 			m = (typeof(m)){"LP9002", "PCI", ""};
2318 		else
2319 			m = (typeof(m)){"LP9000", "PCI", ""};
2320 		m.function = "Obsolete, Unsupported Fibre Channel Adapter";
2321 		break;
2322 	case PCI_DEVICE_ID_RFLY:
2323 		m = (typeof(m)){"LP952", "PCI",
2324 				"Obsolete, Unsupported Fibre Channel Adapter"};
2325 		break;
2326 	case PCI_DEVICE_ID_PEGASUS:
2327 		m = (typeof(m)){"LP9802", "PCI-X",
2328 				"Obsolete, Unsupported Fibre Channel Adapter"};
2329 		break;
2330 	case PCI_DEVICE_ID_THOR:
2331 		m = (typeof(m)){"LP10000", "PCI-X",
2332 				"Obsolete, Unsupported Fibre Channel Adapter"};
2333 		break;
2334 	case PCI_DEVICE_ID_VIPER:
2335 		m = (typeof(m)){"LPX1000",  "PCI-X",
2336 				"Obsolete, Unsupported Fibre Channel Adapter"};
2337 		break;
2338 	case PCI_DEVICE_ID_PFLY:
2339 		m = (typeof(m)){"LP982", "PCI-X",
2340 				"Obsolete, Unsupported Fibre Channel Adapter"};
2341 		break;
2342 	case PCI_DEVICE_ID_TFLY:
2343 		m = (typeof(m)){"LP1050", "PCI-X",
2344 				"Obsolete, Unsupported Fibre Channel Adapter"};
2345 		break;
2346 	case PCI_DEVICE_ID_HELIOS:
2347 		m = (typeof(m)){"LP11000", "PCI-X2",
2348 				"Obsolete, Unsupported Fibre Channel Adapter"};
2349 		break;
2350 	case PCI_DEVICE_ID_HELIOS_SCSP:
2351 		m = (typeof(m)){"LP11000-SP", "PCI-X2",
2352 				"Obsolete, Unsupported Fibre Channel Adapter"};
2353 		break;
2354 	case PCI_DEVICE_ID_HELIOS_DCSP:
2355 		m = (typeof(m)){"LP11002-SP",  "PCI-X2",
2356 				"Obsolete, Unsupported Fibre Channel Adapter"};
2357 		break;
2358 	case PCI_DEVICE_ID_NEPTUNE:
2359 		m = (typeof(m)){"LPe1000", "PCIe",
2360 				"Obsolete, Unsupported Fibre Channel Adapter"};
2361 		break;
2362 	case PCI_DEVICE_ID_NEPTUNE_SCSP:
2363 		m = (typeof(m)){"LPe1000-SP", "PCIe",
2364 				"Obsolete, Unsupported Fibre Channel Adapter"};
2365 		break;
2366 	case PCI_DEVICE_ID_NEPTUNE_DCSP:
2367 		m = (typeof(m)){"LPe1002-SP", "PCIe",
2368 				"Obsolete, Unsupported Fibre Channel Adapter"};
2369 		break;
2370 	case PCI_DEVICE_ID_BMID:
2371 		m = (typeof(m)){"LP1150", "PCI-X2", "Fibre Channel Adapter"};
2372 		break;
2373 	case PCI_DEVICE_ID_BSMB:
2374 		m = (typeof(m)){"LP111", "PCI-X2",
2375 				"Obsolete, Unsupported Fibre Channel Adapter"};
2376 		break;
2377 	case PCI_DEVICE_ID_ZEPHYR:
2378 		m = (typeof(m)){"LPe11000", "PCIe", "Fibre Channel Adapter"};
2379 		break;
2380 	case PCI_DEVICE_ID_ZEPHYR_SCSP:
2381 		m = (typeof(m)){"LPe11000", "PCIe", "Fibre Channel Adapter"};
2382 		break;
2383 	case PCI_DEVICE_ID_ZEPHYR_DCSP:
2384 		m = (typeof(m)){"LP2105", "PCIe", "FCoE Adapter"};
2385 		GE = 1;
2386 		break;
2387 	case PCI_DEVICE_ID_ZMID:
2388 		m = (typeof(m)){"LPe1150", "PCIe", "Fibre Channel Adapter"};
2389 		break;
2390 	case PCI_DEVICE_ID_ZSMB:
2391 		m = (typeof(m)){"LPe111", "PCIe", "Fibre Channel Adapter"};
2392 		break;
2393 	case PCI_DEVICE_ID_LP101:
2394 		m = (typeof(m)){"LP101", "PCI-X",
2395 				"Obsolete, Unsupported Fibre Channel Adapter"};
2396 		break;
2397 	case PCI_DEVICE_ID_LP10000S:
2398 		m = (typeof(m)){"LP10000-S", "PCI",
2399 				"Obsolete, Unsupported Fibre Channel Adapter"};
2400 		break;
2401 	case PCI_DEVICE_ID_LP11000S:
2402 		m = (typeof(m)){"LP11000-S", "PCI-X2",
2403 				"Obsolete, Unsupported Fibre Channel Adapter"};
2404 		break;
2405 	case PCI_DEVICE_ID_LPE11000S:
2406 		m = (typeof(m)){"LPe11000-S", "PCIe",
2407 				"Obsolete, Unsupported Fibre Channel Adapter"};
2408 		break;
2409 	case PCI_DEVICE_ID_SAT:
2410 		m = (typeof(m)){"LPe12000", "PCIe", "Fibre Channel Adapter"};
2411 		break;
2412 	case PCI_DEVICE_ID_SAT_MID:
2413 		m = (typeof(m)){"LPe1250", "PCIe", "Fibre Channel Adapter"};
2414 		break;
2415 	case PCI_DEVICE_ID_SAT_SMB:
2416 		m = (typeof(m)){"LPe121", "PCIe", "Fibre Channel Adapter"};
2417 		break;
2418 	case PCI_DEVICE_ID_SAT_DCSP:
2419 		m = (typeof(m)){"LPe12002-SP", "PCIe", "Fibre Channel Adapter"};
2420 		break;
2421 	case PCI_DEVICE_ID_SAT_SCSP:
2422 		m = (typeof(m)){"LPe12000-SP", "PCIe", "Fibre Channel Adapter"};
2423 		break;
2424 	case PCI_DEVICE_ID_SAT_S:
2425 		m = (typeof(m)){"LPe12000-S", "PCIe", "Fibre Channel Adapter"};
2426 		break;
2427 	case PCI_DEVICE_ID_HORNET:
2428 		m = (typeof(m)){"LP21000", "PCIe",
2429 				"Obsolete, Unsupported FCoE Adapter"};
2430 		GE = 1;
2431 		break;
2432 	case PCI_DEVICE_ID_PROTEUS_VF:
2433 		m = (typeof(m)){"LPev12000", "PCIe IOV",
2434 				"Obsolete, Unsupported Fibre Channel Adapter"};
2435 		break;
2436 	case PCI_DEVICE_ID_PROTEUS_PF:
2437 		m = (typeof(m)){"LPev12000", "PCIe IOV",
2438 				"Obsolete, Unsupported Fibre Channel Adapter"};
2439 		break;
2440 	case PCI_DEVICE_ID_PROTEUS_S:
2441 		m = (typeof(m)){"LPemv12002-S", "PCIe IOV",
2442 				"Obsolete, Unsupported Fibre Channel Adapter"};
2443 		break;
2444 	case PCI_DEVICE_ID_TIGERSHARK:
2445 		oneConnect = 1;
2446 		m = (typeof(m)){"OCe10100", "PCIe", "FCoE"};
2447 		break;
2448 	case PCI_DEVICE_ID_TOMCAT:
2449 		oneConnect = 1;
2450 		m = (typeof(m)){"OCe11100", "PCIe", "FCoE"};
2451 		break;
2452 	case PCI_DEVICE_ID_FALCON:
2453 		m = (typeof(m)){"LPSe12002-ML1-E", "PCIe",
2454 				"EmulexSecure Fibre"};
2455 		break;
2456 	case PCI_DEVICE_ID_BALIUS:
2457 		m = (typeof(m)){"LPVe12002", "PCIe Shared I/O",
2458 				"Obsolete, Unsupported Fibre Channel Adapter"};
2459 		break;
2460 	case PCI_DEVICE_ID_LANCER_FC:
2461 		m = (typeof(m)){"LPe16000", "PCIe", "Fibre Channel Adapter"};
2462 		break;
2463 	case PCI_DEVICE_ID_LANCER_FC_VF:
2464 		m = (typeof(m)){"LPe16000", "PCIe",
2465 				"Obsolete, Unsupported Fibre Channel Adapter"};
2466 		break;
2467 	case PCI_DEVICE_ID_LANCER_FCOE:
2468 		oneConnect = 1;
2469 		m = (typeof(m)){"OCe15100", "PCIe", "FCoE"};
2470 		break;
2471 	case PCI_DEVICE_ID_LANCER_FCOE_VF:
2472 		oneConnect = 1;
2473 		m = (typeof(m)){"OCe15100", "PCIe",
2474 				"Obsolete, Unsupported FCoE"};
2475 		break;
2476 	case PCI_DEVICE_ID_LANCER_G6_FC:
2477 		m = (typeof(m)){"LPe32000", "PCIe", "Fibre Channel Adapter"};
2478 		break;
2479 	case PCI_DEVICE_ID_LANCER_G7_FC:
2480 		m = (typeof(m)){"LPe36000", "PCIe", "Fibre Channel Adapter"};
2481 		break;
2482 	case PCI_DEVICE_ID_SKYHAWK:
2483 	case PCI_DEVICE_ID_SKYHAWK_VF:
2484 		oneConnect = 1;
2485 		m = (typeof(m)){"OCe14000", "PCIe", "FCoE"};
2486 		break;
2487 	default:
2488 		m = (typeof(m)){"Unknown", "", ""};
2489 		break;
2490 	}
2491 
2492 	if (mdp && mdp[0] == '\0')
2493 		snprintf(mdp, 79,"%s", m.name);
2494 	/*
2495 	 * oneConnect hba requires special processing, they are all initiators
2496 	 * and we put the port number on the end
2497 	 */
2498 	if (descp && descp[0] == '\0') {
2499 		if (oneConnect)
2500 			snprintf(descp, 255,
2501 				"Emulex OneConnect %s, %s Initiator %s",
2502 				m.name, m.function,
2503 				phba->Port);
2504 		else if (max_speed == 0)
2505 			snprintf(descp, 255,
2506 				"Emulex %s %s %s",
2507 				m.name, m.bus, m.function);
2508 		else
2509 			snprintf(descp, 255,
2510 				"Emulex %s %d%s %s %s",
2511 				m.name, max_speed, (GE) ? "GE" : "Gb",
2512 				m.bus, m.function);
2513 	}
2514 }
2515 
2516 /**
2517  * lpfc_post_buffer - Post IOCB(s) with DMA buffer descriptor(s) to a IOCB ring
2518  * @phba: pointer to lpfc hba data structure.
2519  * @pring: pointer to a IOCB ring.
2520  * @cnt: the number of IOCBs to be posted to the IOCB ring.
2521  *
2522  * This routine posts a given number of IOCBs with the associated DMA buffer
2523  * descriptors specified by the cnt argument to the given IOCB ring.
2524  *
2525  * Return codes
2526  *   The number of IOCBs NOT able to be posted to the IOCB ring.
2527  **/
2528 int
2529 lpfc_post_buffer(struct lpfc_hba *phba, struct lpfc_sli_ring *pring, int cnt)
2530 {
2531 	IOCB_t *icmd;
2532 	struct lpfc_iocbq *iocb;
2533 	struct lpfc_dmabuf *mp1, *mp2;
2534 
2535 	cnt += pring->missbufcnt;
2536 
2537 	/* While there are buffers to post */
2538 	while (cnt > 0) {
2539 		/* Allocate buffer for  command iocb */
2540 		iocb = lpfc_sli_get_iocbq(phba);
2541 		if (iocb == NULL) {
2542 			pring->missbufcnt = cnt;
2543 			return cnt;
2544 		}
2545 		icmd = &iocb->iocb;
2546 
2547 		/* 2 buffers can be posted per command */
2548 		/* Allocate buffer to post */
2549 		mp1 = kmalloc(sizeof (struct lpfc_dmabuf), GFP_KERNEL);
2550 		if (mp1)
2551 		    mp1->virt = lpfc_mbuf_alloc(phba, MEM_PRI, &mp1->phys);
2552 		if (!mp1 || !mp1->virt) {
2553 			kfree(mp1);
2554 			lpfc_sli_release_iocbq(phba, iocb);
2555 			pring->missbufcnt = cnt;
2556 			return cnt;
2557 		}
2558 
2559 		INIT_LIST_HEAD(&mp1->list);
2560 		/* Allocate buffer to post */
2561 		if (cnt > 1) {
2562 			mp2 = kmalloc(sizeof (struct lpfc_dmabuf), GFP_KERNEL);
2563 			if (mp2)
2564 				mp2->virt = lpfc_mbuf_alloc(phba, MEM_PRI,
2565 							    &mp2->phys);
2566 			if (!mp2 || !mp2->virt) {
2567 				kfree(mp2);
2568 				lpfc_mbuf_free(phba, mp1->virt, mp1->phys);
2569 				kfree(mp1);
2570 				lpfc_sli_release_iocbq(phba, iocb);
2571 				pring->missbufcnt = cnt;
2572 				return cnt;
2573 			}
2574 
2575 			INIT_LIST_HEAD(&mp2->list);
2576 		} else {
2577 			mp2 = NULL;
2578 		}
2579 
2580 		icmd->un.cont64[0].addrHigh = putPaddrHigh(mp1->phys);
2581 		icmd->un.cont64[0].addrLow = putPaddrLow(mp1->phys);
2582 		icmd->un.cont64[0].tus.f.bdeSize = FCELSSIZE;
2583 		icmd->ulpBdeCount = 1;
2584 		cnt--;
2585 		if (mp2) {
2586 			icmd->un.cont64[1].addrHigh = putPaddrHigh(mp2->phys);
2587 			icmd->un.cont64[1].addrLow = putPaddrLow(mp2->phys);
2588 			icmd->un.cont64[1].tus.f.bdeSize = FCELSSIZE;
2589 			cnt--;
2590 			icmd->ulpBdeCount = 2;
2591 		}
2592 
2593 		icmd->ulpCommand = CMD_QUE_RING_BUF64_CN;
2594 		icmd->ulpLe = 1;
2595 
2596 		if (lpfc_sli_issue_iocb(phba, pring->ringno, iocb, 0) ==
2597 		    IOCB_ERROR) {
2598 			lpfc_mbuf_free(phba, mp1->virt, mp1->phys);
2599 			kfree(mp1);
2600 			cnt++;
2601 			if (mp2) {
2602 				lpfc_mbuf_free(phba, mp2->virt, mp2->phys);
2603 				kfree(mp2);
2604 				cnt++;
2605 			}
2606 			lpfc_sli_release_iocbq(phba, iocb);
2607 			pring->missbufcnt = cnt;
2608 			return cnt;
2609 		}
2610 		lpfc_sli_ringpostbuf_put(phba, pring, mp1);
2611 		if (mp2)
2612 			lpfc_sli_ringpostbuf_put(phba, pring, mp2);
2613 	}
2614 	pring->missbufcnt = 0;
2615 	return 0;
2616 }
2617 
2618 /**
2619  * lpfc_post_rcv_buf - Post the initial receive IOCB buffers to ELS ring
2620  * @phba: pointer to lpfc hba data structure.
2621  *
2622  * This routine posts initial receive IOCB buffers to the ELS ring. The
2623  * current number of initial IOCB buffers specified by LPFC_BUF_RING0 is
2624  * set to 64 IOCBs. SLI3 only.
2625  *
2626  * Return codes
2627  *   0 - success (currently always success)
2628  **/
2629 static int
2630 lpfc_post_rcv_buf(struct lpfc_hba *phba)
2631 {
2632 	struct lpfc_sli *psli = &phba->sli;
2633 
2634 	/* Ring 0, ELS / CT buffers */
2635 	lpfc_post_buffer(phba, &psli->sli3_ring[LPFC_ELS_RING], LPFC_BUF_RING0);
2636 	/* Ring 2 - FCP no buffers needed */
2637 
2638 	return 0;
2639 }
2640 
2641 #define S(N,V) (((V)<<(N))|((V)>>(32-(N))))
2642 
2643 /**
2644  * lpfc_sha_init - Set up initial array of hash table entries
2645  * @HashResultPointer: pointer to an array as hash table.
2646  *
2647  * This routine sets up the initial values to the array of hash table entries
2648  * for the LC HBAs.
2649  **/
2650 static void
2651 lpfc_sha_init(uint32_t * HashResultPointer)
2652 {
2653 	HashResultPointer[0] = 0x67452301;
2654 	HashResultPointer[1] = 0xEFCDAB89;
2655 	HashResultPointer[2] = 0x98BADCFE;
2656 	HashResultPointer[3] = 0x10325476;
2657 	HashResultPointer[4] = 0xC3D2E1F0;
2658 }
2659 
2660 /**
2661  * lpfc_sha_iterate - Iterate initial hash table with the working hash table
2662  * @HashResultPointer: pointer to an initial/result hash table.
2663  * @HashWorkingPointer: pointer to an working hash table.
2664  *
2665  * This routine iterates an initial hash table pointed by @HashResultPointer
2666  * with the values from the working hash table pointeed by @HashWorkingPointer.
2667  * The results are putting back to the initial hash table, returned through
2668  * the @HashResultPointer as the result hash table.
2669  **/
2670 static void
2671 lpfc_sha_iterate(uint32_t * HashResultPointer, uint32_t * HashWorkingPointer)
2672 {
2673 	int t;
2674 	uint32_t TEMP;
2675 	uint32_t A, B, C, D, E;
2676 	t = 16;
2677 	do {
2678 		HashWorkingPointer[t] =
2679 		    S(1,
2680 		      HashWorkingPointer[t - 3] ^ HashWorkingPointer[t -
2681 								     8] ^
2682 		      HashWorkingPointer[t - 14] ^ HashWorkingPointer[t - 16]);
2683 	} while (++t <= 79);
2684 	t = 0;
2685 	A = HashResultPointer[0];
2686 	B = HashResultPointer[1];
2687 	C = HashResultPointer[2];
2688 	D = HashResultPointer[3];
2689 	E = HashResultPointer[4];
2690 
2691 	do {
2692 		if (t < 20) {
2693 			TEMP = ((B & C) | ((~B) & D)) + 0x5A827999;
2694 		} else if (t < 40) {
2695 			TEMP = (B ^ C ^ D) + 0x6ED9EBA1;
2696 		} else if (t < 60) {
2697 			TEMP = ((B & C) | (B & D) | (C & D)) + 0x8F1BBCDC;
2698 		} else {
2699 			TEMP = (B ^ C ^ D) + 0xCA62C1D6;
2700 		}
2701 		TEMP += S(5, A) + E + HashWorkingPointer[t];
2702 		E = D;
2703 		D = C;
2704 		C = S(30, B);
2705 		B = A;
2706 		A = TEMP;
2707 	} while (++t <= 79);
2708 
2709 	HashResultPointer[0] += A;
2710 	HashResultPointer[1] += B;
2711 	HashResultPointer[2] += C;
2712 	HashResultPointer[3] += D;
2713 	HashResultPointer[4] += E;
2714 
2715 }
2716 
2717 /**
2718  * lpfc_challenge_key - Create challenge key based on WWPN of the HBA
2719  * @RandomChallenge: pointer to the entry of host challenge random number array.
2720  * @HashWorking: pointer to the entry of the working hash array.
2721  *
2722  * This routine calculates the working hash array referred by @HashWorking
2723  * from the challenge random numbers associated with the host, referred by
2724  * @RandomChallenge. The result is put into the entry of the working hash
2725  * array and returned by reference through @HashWorking.
2726  **/
2727 static void
2728 lpfc_challenge_key(uint32_t * RandomChallenge, uint32_t * HashWorking)
2729 {
2730 	*HashWorking = (*RandomChallenge ^ *HashWorking);
2731 }
2732 
2733 /**
2734  * lpfc_hba_init - Perform special handling for LC HBA initialization
2735  * @phba: pointer to lpfc hba data structure.
2736  * @hbainit: pointer to an array of unsigned 32-bit integers.
2737  *
2738  * This routine performs the special handling for LC HBA initialization.
2739  **/
2740 void
2741 lpfc_hba_init(struct lpfc_hba *phba, uint32_t *hbainit)
2742 {
2743 	int t;
2744 	uint32_t *HashWorking;
2745 	uint32_t *pwwnn = (uint32_t *) phba->wwnn;
2746 
2747 	HashWorking = kcalloc(80, sizeof(uint32_t), GFP_KERNEL);
2748 	if (!HashWorking)
2749 		return;
2750 
2751 	HashWorking[0] = HashWorking[78] = *pwwnn++;
2752 	HashWorking[1] = HashWorking[79] = *pwwnn;
2753 
2754 	for (t = 0; t < 7; t++)
2755 		lpfc_challenge_key(phba->RandomData + t, HashWorking + t);
2756 
2757 	lpfc_sha_init(hbainit);
2758 	lpfc_sha_iterate(hbainit, HashWorking);
2759 	kfree(HashWorking);
2760 }
2761 
2762 /**
2763  * lpfc_cleanup - Performs vport cleanups before deleting a vport
2764  * @vport: pointer to a virtual N_Port data structure.
2765  *
2766  * This routine performs the necessary cleanups before deleting the @vport.
2767  * It invokes the discovery state machine to perform necessary state
2768  * transitions and to release the ndlps associated with the @vport. Note,
2769  * the physical port is treated as @vport 0.
2770  **/
2771 void
2772 lpfc_cleanup(struct lpfc_vport *vport)
2773 {
2774 	struct lpfc_hba   *phba = vport->phba;
2775 	struct lpfc_nodelist *ndlp, *next_ndlp;
2776 	int i = 0;
2777 
2778 	if (phba->link_state > LPFC_LINK_DOWN)
2779 		lpfc_port_link_failure(vport);
2780 
2781 	list_for_each_entry_safe(ndlp, next_ndlp, &vport->fc_nodes, nlp_listp) {
2782 		if (!NLP_CHK_NODE_ACT(ndlp)) {
2783 			ndlp = lpfc_enable_node(vport, ndlp,
2784 						NLP_STE_UNUSED_NODE);
2785 			if (!ndlp)
2786 				continue;
2787 			spin_lock_irq(&phba->ndlp_lock);
2788 			NLP_SET_FREE_REQ(ndlp);
2789 			spin_unlock_irq(&phba->ndlp_lock);
2790 			/* Trigger the release of the ndlp memory */
2791 			lpfc_nlp_put(ndlp);
2792 			continue;
2793 		}
2794 		spin_lock_irq(&phba->ndlp_lock);
2795 		if (NLP_CHK_FREE_REQ(ndlp)) {
2796 			/* The ndlp should not be in memory free mode already */
2797 			spin_unlock_irq(&phba->ndlp_lock);
2798 			continue;
2799 		} else
2800 			/* Indicate request for freeing ndlp memory */
2801 			NLP_SET_FREE_REQ(ndlp);
2802 		spin_unlock_irq(&phba->ndlp_lock);
2803 
2804 		if (vport->port_type != LPFC_PHYSICAL_PORT &&
2805 		    ndlp->nlp_DID == Fabric_DID) {
2806 			/* Just free up ndlp with Fabric_DID for vports */
2807 			lpfc_nlp_put(ndlp);
2808 			continue;
2809 		}
2810 
2811 		/* take care of nodes in unused state before the state
2812 		 * machine taking action.
2813 		 */
2814 		if (ndlp->nlp_state == NLP_STE_UNUSED_NODE) {
2815 			lpfc_nlp_put(ndlp);
2816 			continue;
2817 		}
2818 
2819 		if (ndlp->nlp_type & NLP_FABRIC)
2820 			lpfc_disc_state_machine(vport, ndlp, NULL,
2821 					NLP_EVT_DEVICE_RECOVERY);
2822 
2823 		lpfc_disc_state_machine(vport, ndlp, NULL,
2824 					     NLP_EVT_DEVICE_RM);
2825 	}
2826 
2827 	/* At this point, ALL ndlp's should be gone
2828 	 * because of the previous NLP_EVT_DEVICE_RM.
2829 	 * Lets wait for this to happen, if needed.
2830 	 */
2831 	while (!list_empty(&vport->fc_nodes)) {
2832 		if (i++ > 3000) {
2833 			lpfc_printf_vlog(vport, KERN_ERR, LOG_DISCOVERY,
2834 				"0233 Nodelist not empty\n");
2835 			list_for_each_entry_safe(ndlp, next_ndlp,
2836 						&vport->fc_nodes, nlp_listp) {
2837 				lpfc_printf_vlog(ndlp->vport, KERN_ERR,
2838 						LOG_NODE,
2839 						"0282 did:x%x ndlp:x%px "
2840 						"usgmap:x%x refcnt:%d\n",
2841 						ndlp->nlp_DID, (void *)ndlp,
2842 						ndlp->nlp_usg_map,
2843 						kref_read(&ndlp->kref));
2844 			}
2845 			break;
2846 		}
2847 
2848 		/* Wait for any activity on ndlps to settle */
2849 		msleep(10);
2850 	}
2851 	lpfc_cleanup_vports_rrqs(vport, NULL);
2852 }
2853 
2854 /**
2855  * lpfc_stop_vport_timers - Stop all the timers associated with a vport
2856  * @vport: pointer to a virtual N_Port data structure.
2857  *
2858  * This routine stops all the timers associated with a @vport. This function
2859  * is invoked before disabling or deleting a @vport. Note that the physical
2860  * port is treated as @vport 0.
2861  **/
2862 void
2863 lpfc_stop_vport_timers(struct lpfc_vport *vport)
2864 {
2865 	del_timer_sync(&vport->els_tmofunc);
2866 	del_timer_sync(&vport->delayed_disc_tmo);
2867 	lpfc_can_disctmo(vport);
2868 	return;
2869 }
2870 
2871 /**
2872  * __lpfc_sli4_stop_fcf_redisc_wait_timer - Stop FCF rediscovery wait timer
2873  * @phba: pointer to lpfc hba data structure.
2874  *
2875  * This routine stops the SLI4 FCF rediscover wait timer if it's on. The
2876  * caller of this routine should already hold the host lock.
2877  **/
2878 void
2879 __lpfc_sli4_stop_fcf_redisc_wait_timer(struct lpfc_hba *phba)
2880 {
2881 	/* Clear pending FCF rediscovery wait flag */
2882 	phba->fcf.fcf_flag &= ~FCF_REDISC_PEND;
2883 
2884 	/* Now, try to stop the timer */
2885 	del_timer(&phba->fcf.redisc_wait);
2886 }
2887 
2888 /**
2889  * lpfc_sli4_stop_fcf_redisc_wait_timer - Stop FCF rediscovery wait timer
2890  * @phba: pointer to lpfc hba data structure.
2891  *
2892  * This routine stops the SLI4 FCF rediscover wait timer if it's on. It
2893  * checks whether the FCF rediscovery wait timer is pending with the host
2894  * lock held before proceeding with disabling the timer and clearing the
2895  * wait timer pendig flag.
2896  **/
2897 void
2898 lpfc_sli4_stop_fcf_redisc_wait_timer(struct lpfc_hba *phba)
2899 {
2900 	spin_lock_irq(&phba->hbalock);
2901 	if (!(phba->fcf.fcf_flag & FCF_REDISC_PEND)) {
2902 		/* FCF rediscovery timer already fired or stopped */
2903 		spin_unlock_irq(&phba->hbalock);
2904 		return;
2905 	}
2906 	__lpfc_sli4_stop_fcf_redisc_wait_timer(phba);
2907 	/* Clear failover in progress flags */
2908 	phba->fcf.fcf_flag &= ~(FCF_DEAD_DISC | FCF_ACVL_DISC);
2909 	spin_unlock_irq(&phba->hbalock);
2910 }
2911 
2912 /**
2913  * lpfc_stop_hba_timers - Stop all the timers associated with an HBA
2914  * @phba: pointer to lpfc hba data structure.
2915  *
2916  * This routine stops all the timers associated with a HBA. This function is
2917  * invoked before either putting a HBA offline or unloading the driver.
2918  **/
2919 void
2920 lpfc_stop_hba_timers(struct lpfc_hba *phba)
2921 {
2922 	if (phba->pport)
2923 		lpfc_stop_vport_timers(phba->pport);
2924 	cancel_delayed_work_sync(&phba->eq_delay_work);
2925 	del_timer_sync(&phba->sli.mbox_tmo);
2926 	del_timer_sync(&phba->fabric_block_timer);
2927 	del_timer_sync(&phba->eratt_poll);
2928 	del_timer_sync(&phba->hb_tmofunc);
2929 	if (phba->sli_rev == LPFC_SLI_REV4) {
2930 		del_timer_sync(&phba->rrq_tmr);
2931 		phba->hba_flag &= ~HBA_RRQ_ACTIVE;
2932 	}
2933 	phba->hb_outstanding = 0;
2934 
2935 	switch (phba->pci_dev_grp) {
2936 	case LPFC_PCI_DEV_LP:
2937 		/* Stop any LightPulse device specific driver timers */
2938 		del_timer_sync(&phba->fcp_poll_timer);
2939 		break;
2940 	case LPFC_PCI_DEV_OC:
2941 		/* Stop any OneConnect device specific driver timers */
2942 		lpfc_sli4_stop_fcf_redisc_wait_timer(phba);
2943 		break;
2944 	default:
2945 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
2946 				"0297 Invalid device group (x%x)\n",
2947 				phba->pci_dev_grp);
2948 		break;
2949 	}
2950 	return;
2951 }
2952 
2953 /**
2954  * lpfc_block_mgmt_io - Mark a HBA's management interface as blocked
2955  * @phba: pointer to lpfc hba data structure.
2956  *
2957  * This routine marks a HBA's management interface as blocked. Once the HBA's
2958  * management interface is marked as blocked, all the user space access to
2959  * the HBA, whether they are from sysfs interface or libdfc interface will
2960  * all be blocked. The HBA is set to block the management interface when the
2961  * driver prepares the HBA interface for online or offline.
2962  **/
2963 static void
2964 lpfc_block_mgmt_io(struct lpfc_hba *phba, int mbx_action)
2965 {
2966 	unsigned long iflag;
2967 	uint8_t actcmd = MBX_HEARTBEAT;
2968 	unsigned long timeout;
2969 
2970 	spin_lock_irqsave(&phba->hbalock, iflag);
2971 	phba->sli.sli_flag |= LPFC_BLOCK_MGMT_IO;
2972 	spin_unlock_irqrestore(&phba->hbalock, iflag);
2973 	if (mbx_action == LPFC_MBX_NO_WAIT)
2974 		return;
2975 	timeout = msecs_to_jiffies(LPFC_MBOX_TMO * 1000) + jiffies;
2976 	spin_lock_irqsave(&phba->hbalock, iflag);
2977 	if (phba->sli.mbox_active) {
2978 		actcmd = phba->sli.mbox_active->u.mb.mbxCommand;
2979 		/* Determine how long we might wait for the active mailbox
2980 		 * command to be gracefully completed by firmware.
2981 		 */
2982 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
2983 				phba->sli.mbox_active) * 1000) + jiffies;
2984 	}
2985 	spin_unlock_irqrestore(&phba->hbalock, iflag);
2986 
2987 	/* Wait for the outstnading mailbox command to complete */
2988 	while (phba->sli.mbox_active) {
2989 		/* Check active mailbox complete status every 2ms */
2990 		msleep(2);
2991 		if (time_after(jiffies, timeout)) {
2992 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2993 				"2813 Mgmt IO is Blocked %x "
2994 				"- mbox cmd %x still active\n",
2995 				phba->sli.sli_flag, actcmd);
2996 			break;
2997 		}
2998 	}
2999 }
3000 
3001 /**
3002  * lpfc_sli4_node_prep - Assign RPIs for active nodes.
3003  * @phba: pointer to lpfc hba data structure.
3004  *
3005  * Allocate RPIs for all active remote nodes. This is needed whenever
3006  * an SLI4 adapter is reset and the driver is not unloading. Its purpose
3007  * is to fixup the temporary rpi assignments.
3008  **/
3009 void
3010 lpfc_sli4_node_prep(struct lpfc_hba *phba)
3011 {
3012 	struct lpfc_nodelist  *ndlp, *next_ndlp;
3013 	struct lpfc_vport **vports;
3014 	int i, rpi;
3015 	unsigned long flags;
3016 
3017 	if (phba->sli_rev != LPFC_SLI_REV4)
3018 		return;
3019 
3020 	vports = lpfc_create_vport_work_array(phba);
3021 	if (vports == NULL)
3022 		return;
3023 
3024 	for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3025 		if (vports[i]->load_flag & FC_UNLOADING)
3026 			continue;
3027 
3028 		list_for_each_entry_safe(ndlp, next_ndlp,
3029 					 &vports[i]->fc_nodes,
3030 					 nlp_listp) {
3031 			if (!NLP_CHK_NODE_ACT(ndlp))
3032 				continue;
3033 			rpi = lpfc_sli4_alloc_rpi(phba);
3034 			if (rpi == LPFC_RPI_ALLOC_ERROR) {
3035 				spin_lock_irqsave(&phba->ndlp_lock, flags);
3036 				NLP_CLR_NODE_ACT(ndlp);
3037 				spin_unlock_irqrestore(&phba->ndlp_lock, flags);
3038 				continue;
3039 			}
3040 			ndlp->nlp_rpi = rpi;
3041 			lpfc_printf_vlog(ndlp->vport, KERN_INFO,
3042 					 LOG_NODE | LOG_DISCOVERY,
3043 					 "0009 Assign RPI x%x to ndlp x%px "
3044 					 "DID:x%06x flg:x%x map:x%x\n",
3045 					 ndlp->nlp_rpi, ndlp, ndlp->nlp_DID,
3046 					 ndlp->nlp_flag, ndlp->nlp_usg_map);
3047 		}
3048 	}
3049 	lpfc_destroy_vport_work_array(phba, vports);
3050 }
3051 
3052 /**
3053  * lpfc_create_expedite_pool - create expedite pool
3054  * @phba: pointer to lpfc hba data structure.
3055  *
3056  * This routine moves a batch of XRIs from lpfc_io_buf_list_put of HWQ 0
3057  * to expedite pool. Mark them as expedite.
3058  **/
3059 static void lpfc_create_expedite_pool(struct lpfc_hba *phba)
3060 {
3061 	struct lpfc_sli4_hdw_queue *qp;
3062 	struct lpfc_io_buf *lpfc_ncmd;
3063 	struct lpfc_io_buf *lpfc_ncmd_next;
3064 	struct lpfc_epd_pool *epd_pool;
3065 	unsigned long iflag;
3066 
3067 	epd_pool = &phba->epd_pool;
3068 	qp = &phba->sli4_hba.hdwq[0];
3069 
3070 	spin_lock_init(&epd_pool->lock);
3071 	spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3072 	spin_lock(&epd_pool->lock);
3073 	INIT_LIST_HEAD(&epd_pool->list);
3074 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3075 				 &qp->lpfc_io_buf_list_put, list) {
3076 		list_move_tail(&lpfc_ncmd->list, &epd_pool->list);
3077 		lpfc_ncmd->expedite = true;
3078 		qp->put_io_bufs--;
3079 		epd_pool->count++;
3080 		if (epd_pool->count >= XRI_BATCH)
3081 			break;
3082 	}
3083 	spin_unlock(&epd_pool->lock);
3084 	spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3085 }
3086 
3087 /**
3088  * lpfc_destroy_expedite_pool - destroy expedite pool
3089  * @phba: pointer to lpfc hba data structure.
3090  *
3091  * This routine returns XRIs from expedite pool to lpfc_io_buf_list_put
3092  * of HWQ 0. Clear the mark.
3093  **/
3094 static void lpfc_destroy_expedite_pool(struct lpfc_hba *phba)
3095 {
3096 	struct lpfc_sli4_hdw_queue *qp;
3097 	struct lpfc_io_buf *lpfc_ncmd;
3098 	struct lpfc_io_buf *lpfc_ncmd_next;
3099 	struct lpfc_epd_pool *epd_pool;
3100 	unsigned long iflag;
3101 
3102 	epd_pool = &phba->epd_pool;
3103 	qp = &phba->sli4_hba.hdwq[0];
3104 
3105 	spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3106 	spin_lock(&epd_pool->lock);
3107 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3108 				 &epd_pool->list, list) {
3109 		list_move_tail(&lpfc_ncmd->list,
3110 			       &qp->lpfc_io_buf_list_put);
3111 		lpfc_ncmd->flags = false;
3112 		qp->put_io_bufs++;
3113 		epd_pool->count--;
3114 	}
3115 	spin_unlock(&epd_pool->lock);
3116 	spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3117 }
3118 
3119 /**
3120  * lpfc_create_multixri_pools - create multi-XRI pools
3121  * @phba: pointer to lpfc hba data structure.
3122  *
3123  * This routine initialize public, private per HWQ. Then, move XRIs from
3124  * lpfc_io_buf_list_put to public pool. High and low watermark are also
3125  * Initialized.
3126  **/
3127 void lpfc_create_multixri_pools(struct lpfc_hba *phba)
3128 {
3129 	u32 i, j;
3130 	u32 hwq_count;
3131 	u32 count_per_hwq;
3132 	struct lpfc_io_buf *lpfc_ncmd;
3133 	struct lpfc_io_buf *lpfc_ncmd_next;
3134 	unsigned long iflag;
3135 	struct lpfc_sli4_hdw_queue *qp;
3136 	struct lpfc_multixri_pool *multixri_pool;
3137 	struct lpfc_pbl_pool *pbl_pool;
3138 	struct lpfc_pvt_pool *pvt_pool;
3139 
3140 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3141 			"1234 num_hdw_queue=%d num_present_cpu=%d common_xri_cnt=%d\n",
3142 			phba->cfg_hdw_queue, phba->sli4_hba.num_present_cpu,
3143 			phba->sli4_hba.io_xri_cnt);
3144 
3145 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
3146 		lpfc_create_expedite_pool(phba);
3147 
3148 	hwq_count = phba->cfg_hdw_queue;
3149 	count_per_hwq = phba->sli4_hba.io_xri_cnt / hwq_count;
3150 
3151 	for (i = 0; i < hwq_count; i++) {
3152 		multixri_pool = kzalloc(sizeof(*multixri_pool), GFP_KERNEL);
3153 
3154 		if (!multixri_pool) {
3155 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3156 					"1238 Failed to allocate memory for "
3157 					"multixri_pool\n");
3158 
3159 			if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
3160 				lpfc_destroy_expedite_pool(phba);
3161 
3162 			j = 0;
3163 			while (j < i) {
3164 				qp = &phba->sli4_hba.hdwq[j];
3165 				kfree(qp->p_multixri_pool);
3166 				j++;
3167 			}
3168 			phba->cfg_xri_rebalancing = 0;
3169 			return;
3170 		}
3171 
3172 		qp = &phba->sli4_hba.hdwq[i];
3173 		qp->p_multixri_pool = multixri_pool;
3174 
3175 		multixri_pool->xri_limit = count_per_hwq;
3176 		multixri_pool->rrb_next_hwqid = i;
3177 
3178 		/* Deal with public free xri pool */
3179 		pbl_pool = &multixri_pool->pbl_pool;
3180 		spin_lock_init(&pbl_pool->lock);
3181 		spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3182 		spin_lock(&pbl_pool->lock);
3183 		INIT_LIST_HEAD(&pbl_pool->list);
3184 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3185 					 &qp->lpfc_io_buf_list_put, list) {
3186 			list_move_tail(&lpfc_ncmd->list, &pbl_pool->list);
3187 			qp->put_io_bufs--;
3188 			pbl_pool->count++;
3189 		}
3190 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3191 				"1235 Moved %d buffers from PUT list over to pbl_pool[%d]\n",
3192 				pbl_pool->count, i);
3193 		spin_unlock(&pbl_pool->lock);
3194 		spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3195 
3196 		/* Deal with private free xri pool */
3197 		pvt_pool = &multixri_pool->pvt_pool;
3198 		pvt_pool->high_watermark = multixri_pool->xri_limit / 2;
3199 		pvt_pool->low_watermark = XRI_BATCH;
3200 		spin_lock_init(&pvt_pool->lock);
3201 		spin_lock_irqsave(&pvt_pool->lock, iflag);
3202 		INIT_LIST_HEAD(&pvt_pool->list);
3203 		pvt_pool->count = 0;
3204 		spin_unlock_irqrestore(&pvt_pool->lock, iflag);
3205 	}
3206 }
3207 
3208 /**
3209  * lpfc_destroy_multixri_pools - destroy multi-XRI pools
3210  * @phba: pointer to lpfc hba data structure.
3211  *
3212  * This routine returns XRIs from public/private to lpfc_io_buf_list_put.
3213  **/
3214 static void lpfc_destroy_multixri_pools(struct lpfc_hba *phba)
3215 {
3216 	u32 i;
3217 	u32 hwq_count;
3218 	struct lpfc_io_buf *lpfc_ncmd;
3219 	struct lpfc_io_buf *lpfc_ncmd_next;
3220 	unsigned long iflag;
3221 	struct lpfc_sli4_hdw_queue *qp;
3222 	struct lpfc_multixri_pool *multixri_pool;
3223 	struct lpfc_pbl_pool *pbl_pool;
3224 	struct lpfc_pvt_pool *pvt_pool;
3225 
3226 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
3227 		lpfc_destroy_expedite_pool(phba);
3228 
3229 	if (!(phba->pport->load_flag & FC_UNLOADING))
3230 		lpfc_sli_flush_io_rings(phba);
3231 
3232 	hwq_count = phba->cfg_hdw_queue;
3233 
3234 	for (i = 0; i < hwq_count; i++) {
3235 		qp = &phba->sli4_hba.hdwq[i];
3236 		multixri_pool = qp->p_multixri_pool;
3237 		if (!multixri_pool)
3238 			continue;
3239 
3240 		qp->p_multixri_pool = NULL;
3241 
3242 		spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3243 
3244 		/* Deal with public free xri pool */
3245 		pbl_pool = &multixri_pool->pbl_pool;
3246 		spin_lock(&pbl_pool->lock);
3247 
3248 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3249 				"1236 Moving %d buffers from pbl_pool[%d] TO PUT list\n",
3250 				pbl_pool->count, i);
3251 
3252 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3253 					 &pbl_pool->list, list) {
3254 			list_move_tail(&lpfc_ncmd->list,
3255 				       &qp->lpfc_io_buf_list_put);
3256 			qp->put_io_bufs++;
3257 			pbl_pool->count--;
3258 		}
3259 
3260 		INIT_LIST_HEAD(&pbl_pool->list);
3261 		pbl_pool->count = 0;
3262 
3263 		spin_unlock(&pbl_pool->lock);
3264 
3265 		/* Deal with private free xri pool */
3266 		pvt_pool = &multixri_pool->pvt_pool;
3267 		spin_lock(&pvt_pool->lock);
3268 
3269 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3270 				"1237 Moving %d buffers from pvt_pool[%d] TO PUT list\n",
3271 				pvt_pool->count, i);
3272 
3273 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3274 					 &pvt_pool->list, list) {
3275 			list_move_tail(&lpfc_ncmd->list,
3276 				       &qp->lpfc_io_buf_list_put);
3277 			qp->put_io_bufs++;
3278 			pvt_pool->count--;
3279 		}
3280 
3281 		INIT_LIST_HEAD(&pvt_pool->list);
3282 		pvt_pool->count = 0;
3283 
3284 		spin_unlock(&pvt_pool->lock);
3285 		spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3286 
3287 		kfree(multixri_pool);
3288 	}
3289 }
3290 
3291 /**
3292  * lpfc_online - Initialize and bring a HBA online
3293  * @phba: pointer to lpfc hba data structure.
3294  *
3295  * This routine initializes the HBA and brings a HBA online. During this
3296  * process, the management interface is blocked to prevent user space access
3297  * to the HBA interfering with the driver initialization.
3298  *
3299  * Return codes
3300  *   0 - successful
3301  *   1 - failed
3302  **/
3303 int
3304 lpfc_online(struct lpfc_hba *phba)
3305 {
3306 	struct lpfc_vport *vport;
3307 	struct lpfc_vport **vports;
3308 	int i, error = 0;
3309 	bool vpis_cleared = false;
3310 
3311 	if (!phba)
3312 		return 0;
3313 	vport = phba->pport;
3314 
3315 	if (!(vport->fc_flag & FC_OFFLINE_MODE))
3316 		return 0;
3317 
3318 	lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
3319 			"0458 Bring Adapter online\n");
3320 
3321 	lpfc_block_mgmt_io(phba, LPFC_MBX_WAIT);
3322 
3323 	if (phba->sli_rev == LPFC_SLI_REV4) {
3324 		if (lpfc_sli4_hba_setup(phba)) { /* Initialize SLI4 HBA */
3325 			lpfc_unblock_mgmt_io(phba);
3326 			return 1;
3327 		}
3328 		spin_lock_irq(&phba->hbalock);
3329 		if (!phba->sli4_hba.max_cfg_param.vpi_used)
3330 			vpis_cleared = true;
3331 		spin_unlock_irq(&phba->hbalock);
3332 
3333 		/* Reestablish the local initiator port.
3334 		 * The offline process destroyed the previous lport.
3335 		 */
3336 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME &&
3337 				!phba->nvmet_support) {
3338 			error = lpfc_nvme_create_localport(phba->pport);
3339 			if (error)
3340 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
3341 					"6132 NVME restore reg failed "
3342 					"on nvmei error x%x\n", error);
3343 		}
3344 	} else {
3345 		lpfc_sli_queue_init(phba);
3346 		if (lpfc_sli_hba_setup(phba)) {	/* Initialize SLI2/SLI3 HBA */
3347 			lpfc_unblock_mgmt_io(phba);
3348 			return 1;
3349 		}
3350 	}
3351 
3352 	vports = lpfc_create_vport_work_array(phba);
3353 	if (vports != NULL) {
3354 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3355 			struct Scsi_Host *shost;
3356 			shost = lpfc_shost_from_vport(vports[i]);
3357 			spin_lock_irq(shost->host_lock);
3358 			vports[i]->fc_flag &= ~FC_OFFLINE_MODE;
3359 			if (phba->sli3_options & LPFC_SLI3_NPIV_ENABLED)
3360 				vports[i]->fc_flag |= FC_VPORT_NEEDS_REG_VPI;
3361 			if (phba->sli_rev == LPFC_SLI_REV4) {
3362 				vports[i]->fc_flag |= FC_VPORT_NEEDS_INIT_VPI;
3363 				if ((vpis_cleared) &&
3364 				    (vports[i]->port_type !=
3365 					LPFC_PHYSICAL_PORT))
3366 					vports[i]->vpi = 0;
3367 			}
3368 			spin_unlock_irq(shost->host_lock);
3369 		}
3370 	}
3371 	lpfc_destroy_vport_work_array(phba, vports);
3372 
3373 	if (phba->cfg_xri_rebalancing)
3374 		lpfc_create_multixri_pools(phba);
3375 
3376 	lpfc_cpuhp_add(phba);
3377 
3378 	lpfc_unblock_mgmt_io(phba);
3379 	return 0;
3380 }
3381 
3382 /**
3383  * lpfc_unblock_mgmt_io - Mark a HBA's management interface to be not blocked
3384  * @phba: pointer to lpfc hba data structure.
3385  *
3386  * This routine marks a HBA's management interface as not blocked. Once the
3387  * HBA's management interface is marked as not blocked, all the user space
3388  * access to the HBA, whether they are from sysfs interface or libdfc
3389  * interface will be allowed. The HBA is set to block the management interface
3390  * when the driver prepares the HBA interface for online or offline and then
3391  * set to unblock the management interface afterwards.
3392  **/
3393 void
3394 lpfc_unblock_mgmt_io(struct lpfc_hba * phba)
3395 {
3396 	unsigned long iflag;
3397 
3398 	spin_lock_irqsave(&phba->hbalock, iflag);
3399 	phba->sli.sli_flag &= ~LPFC_BLOCK_MGMT_IO;
3400 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3401 }
3402 
3403 /**
3404  * lpfc_offline_prep - Prepare a HBA to be brought offline
3405  * @phba: pointer to lpfc hba data structure.
3406  *
3407  * This routine is invoked to prepare a HBA to be brought offline. It performs
3408  * unregistration login to all the nodes on all vports and flushes the mailbox
3409  * queue to make it ready to be brought offline.
3410  **/
3411 void
3412 lpfc_offline_prep(struct lpfc_hba *phba, int mbx_action)
3413 {
3414 	struct lpfc_vport *vport = phba->pport;
3415 	struct lpfc_nodelist  *ndlp, *next_ndlp;
3416 	struct lpfc_vport **vports;
3417 	struct Scsi_Host *shost;
3418 	int i;
3419 
3420 	if (vport->fc_flag & FC_OFFLINE_MODE)
3421 		return;
3422 
3423 	lpfc_block_mgmt_io(phba, mbx_action);
3424 
3425 	lpfc_linkdown(phba);
3426 
3427 	/* Issue an unreg_login to all nodes on all vports */
3428 	vports = lpfc_create_vport_work_array(phba);
3429 	if (vports != NULL) {
3430 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3431 			if (vports[i]->load_flag & FC_UNLOADING)
3432 				continue;
3433 			shost = lpfc_shost_from_vport(vports[i]);
3434 			spin_lock_irq(shost->host_lock);
3435 			vports[i]->vpi_state &= ~LPFC_VPI_REGISTERED;
3436 			vports[i]->fc_flag |= FC_VPORT_NEEDS_REG_VPI;
3437 			vports[i]->fc_flag &= ~FC_VFI_REGISTERED;
3438 			spin_unlock_irq(shost->host_lock);
3439 
3440 			shost =	lpfc_shost_from_vport(vports[i]);
3441 			list_for_each_entry_safe(ndlp, next_ndlp,
3442 						 &vports[i]->fc_nodes,
3443 						 nlp_listp) {
3444 				if ((!NLP_CHK_NODE_ACT(ndlp)) ||
3445 				    ndlp->nlp_state == NLP_STE_UNUSED_NODE) {
3446 					/* Driver must assume RPI is invalid for
3447 					 * any unused or inactive node.
3448 					 */
3449 					ndlp->nlp_rpi = LPFC_RPI_ALLOC_ERROR;
3450 					continue;
3451 				}
3452 
3453 				if (ndlp->nlp_type & NLP_FABRIC) {
3454 					lpfc_disc_state_machine(vports[i], ndlp,
3455 						NULL, NLP_EVT_DEVICE_RECOVERY);
3456 					lpfc_disc_state_machine(vports[i], ndlp,
3457 						NULL, NLP_EVT_DEVICE_RM);
3458 				}
3459 				spin_lock_irq(shost->host_lock);
3460 				ndlp->nlp_flag &= ~NLP_NPR_ADISC;
3461 				spin_unlock_irq(shost->host_lock);
3462 				/*
3463 				 * Whenever an SLI4 port goes offline, free the
3464 				 * RPI. Get a new RPI when the adapter port
3465 				 * comes back online.
3466 				 */
3467 				if (phba->sli_rev == LPFC_SLI_REV4) {
3468 					lpfc_printf_vlog(ndlp->vport, KERN_INFO,
3469 						 LOG_NODE | LOG_DISCOVERY,
3470 						 "0011 Free RPI x%x on "
3471 						 "ndlp:x%px did x%x "
3472 						 "usgmap:x%x\n",
3473 						 ndlp->nlp_rpi, ndlp,
3474 						 ndlp->nlp_DID,
3475 						 ndlp->nlp_usg_map);
3476 					lpfc_sli4_free_rpi(phba, ndlp->nlp_rpi);
3477 					ndlp->nlp_rpi = LPFC_RPI_ALLOC_ERROR;
3478 				}
3479 				lpfc_unreg_rpi(vports[i], ndlp);
3480 			}
3481 		}
3482 	}
3483 	lpfc_destroy_vport_work_array(phba, vports);
3484 
3485 	lpfc_sli_mbox_sys_shutdown(phba, mbx_action);
3486 
3487 	if (phba->wq)
3488 		flush_workqueue(phba->wq);
3489 }
3490 
3491 /**
3492  * lpfc_offline - Bring a HBA offline
3493  * @phba: pointer to lpfc hba data structure.
3494  *
3495  * This routine actually brings a HBA offline. It stops all the timers
3496  * associated with the HBA, brings down the SLI layer, and eventually
3497  * marks the HBA as in offline state for the upper layer protocol.
3498  **/
3499 void
3500 lpfc_offline(struct lpfc_hba *phba)
3501 {
3502 	struct Scsi_Host  *shost;
3503 	struct lpfc_vport **vports;
3504 	int i;
3505 
3506 	if (phba->pport->fc_flag & FC_OFFLINE_MODE)
3507 		return;
3508 
3509 	/* stop port and all timers associated with this hba */
3510 	lpfc_stop_port(phba);
3511 
3512 	/* Tear down the local and target port registrations.  The
3513 	 * nvme transports need to cleanup.
3514 	 */
3515 	lpfc_nvmet_destroy_targetport(phba);
3516 	lpfc_nvme_destroy_localport(phba->pport);
3517 
3518 	vports = lpfc_create_vport_work_array(phba);
3519 	if (vports != NULL)
3520 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++)
3521 			lpfc_stop_vport_timers(vports[i]);
3522 	lpfc_destroy_vport_work_array(phba, vports);
3523 	lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
3524 			"0460 Bring Adapter offline\n");
3525 	/* Bring down the SLI Layer and cleanup.  The HBA is offline
3526 	   now.  */
3527 	lpfc_sli_hba_down(phba);
3528 	spin_lock_irq(&phba->hbalock);
3529 	phba->work_ha = 0;
3530 	spin_unlock_irq(&phba->hbalock);
3531 	vports = lpfc_create_vport_work_array(phba);
3532 	if (vports != NULL)
3533 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3534 			shost = lpfc_shost_from_vport(vports[i]);
3535 			spin_lock_irq(shost->host_lock);
3536 			vports[i]->work_port_events = 0;
3537 			vports[i]->fc_flag |= FC_OFFLINE_MODE;
3538 			spin_unlock_irq(shost->host_lock);
3539 		}
3540 	lpfc_destroy_vport_work_array(phba, vports);
3541 	__lpfc_cpuhp_remove(phba);
3542 
3543 	if (phba->cfg_xri_rebalancing)
3544 		lpfc_destroy_multixri_pools(phba);
3545 }
3546 
3547 /**
3548  * lpfc_scsi_free - Free all the SCSI buffers and IOCBs from driver lists
3549  * @phba: pointer to lpfc hba data structure.
3550  *
3551  * This routine is to free all the SCSI buffers and IOCBs from the driver
3552  * list back to kernel. It is called from lpfc_pci_remove_one to free
3553  * the internal resources before the device is removed from the system.
3554  **/
3555 static void
3556 lpfc_scsi_free(struct lpfc_hba *phba)
3557 {
3558 	struct lpfc_io_buf *sb, *sb_next;
3559 
3560 	if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP))
3561 		return;
3562 
3563 	spin_lock_irq(&phba->hbalock);
3564 
3565 	/* Release all the lpfc_scsi_bufs maintained by this host. */
3566 
3567 	spin_lock(&phba->scsi_buf_list_put_lock);
3568 	list_for_each_entry_safe(sb, sb_next, &phba->lpfc_scsi_buf_list_put,
3569 				 list) {
3570 		list_del(&sb->list);
3571 		dma_pool_free(phba->lpfc_sg_dma_buf_pool, sb->data,
3572 			      sb->dma_handle);
3573 		kfree(sb);
3574 		phba->total_scsi_bufs--;
3575 	}
3576 	spin_unlock(&phba->scsi_buf_list_put_lock);
3577 
3578 	spin_lock(&phba->scsi_buf_list_get_lock);
3579 	list_for_each_entry_safe(sb, sb_next, &phba->lpfc_scsi_buf_list_get,
3580 				 list) {
3581 		list_del(&sb->list);
3582 		dma_pool_free(phba->lpfc_sg_dma_buf_pool, sb->data,
3583 			      sb->dma_handle);
3584 		kfree(sb);
3585 		phba->total_scsi_bufs--;
3586 	}
3587 	spin_unlock(&phba->scsi_buf_list_get_lock);
3588 	spin_unlock_irq(&phba->hbalock);
3589 }
3590 
3591 /**
3592  * lpfc_io_free - Free all the IO buffers and IOCBs from driver lists
3593  * @phba: pointer to lpfc hba data structure.
3594  *
3595  * This routine is to free all the IO buffers and IOCBs from the driver
3596  * list back to kernel. It is called from lpfc_pci_remove_one to free
3597  * the internal resources before the device is removed from the system.
3598  **/
3599 void
3600 lpfc_io_free(struct lpfc_hba *phba)
3601 {
3602 	struct lpfc_io_buf *lpfc_ncmd, *lpfc_ncmd_next;
3603 	struct lpfc_sli4_hdw_queue *qp;
3604 	int idx;
3605 
3606 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
3607 		qp = &phba->sli4_hba.hdwq[idx];
3608 		/* Release all the lpfc_nvme_bufs maintained by this host. */
3609 		spin_lock(&qp->io_buf_list_put_lock);
3610 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3611 					 &qp->lpfc_io_buf_list_put,
3612 					 list) {
3613 			list_del(&lpfc_ncmd->list);
3614 			qp->put_io_bufs--;
3615 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
3616 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
3617 			if (phba->cfg_xpsgl && !phba->nvmet_support)
3618 				lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
3619 			lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
3620 			kfree(lpfc_ncmd);
3621 			qp->total_io_bufs--;
3622 		}
3623 		spin_unlock(&qp->io_buf_list_put_lock);
3624 
3625 		spin_lock(&qp->io_buf_list_get_lock);
3626 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3627 					 &qp->lpfc_io_buf_list_get,
3628 					 list) {
3629 			list_del(&lpfc_ncmd->list);
3630 			qp->get_io_bufs--;
3631 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
3632 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
3633 			if (phba->cfg_xpsgl && !phba->nvmet_support)
3634 				lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
3635 			lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
3636 			kfree(lpfc_ncmd);
3637 			qp->total_io_bufs--;
3638 		}
3639 		spin_unlock(&qp->io_buf_list_get_lock);
3640 	}
3641 }
3642 
3643 /**
3644  * lpfc_sli4_els_sgl_update - update ELS xri-sgl sizing and mapping
3645  * @phba: pointer to lpfc hba data structure.
3646  *
3647  * This routine first calculates the sizes of the current els and allocated
3648  * scsi sgl lists, and then goes through all sgls to updates the physical
3649  * XRIs assigned due to port function reset. During port initialization, the
3650  * current els and allocated scsi sgl lists are 0s.
3651  *
3652  * Return codes
3653  *   0 - successful (for now, it always returns 0)
3654  **/
3655 int
3656 lpfc_sli4_els_sgl_update(struct lpfc_hba *phba)
3657 {
3658 	struct lpfc_sglq *sglq_entry = NULL, *sglq_entry_next = NULL;
3659 	uint16_t i, lxri, xri_cnt, els_xri_cnt;
3660 	LIST_HEAD(els_sgl_list);
3661 	int rc;
3662 
3663 	/*
3664 	 * update on pci function's els xri-sgl list
3665 	 */
3666 	els_xri_cnt = lpfc_sli4_get_els_iocb_cnt(phba);
3667 
3668 	if (els_xri_cnt > phba->sli4_hba.els_xri_cnt) {
3669 		/* els xri-sgl expanded */
3670 		xri_cnt = els_xri_cnt - phba->sli4_hba.els_xri_cnt;
3671 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3672 				"3157 ELS xri-sgl count increased from "
3673 				"%d to %d\n", phba->sli4_hba.els_xri_cnt,
3674 				els_xri_cnt);
3675 		/* allocate the additional els sgls */
3676 		for (i = 0; i < xri_cnt; i++) {
3677 			sglq_entry = kzalloc(sizeof(struct lpfc_sglq),
3678 					     GFP_KERNEL);
3679 			if (sglq_entry == NULL) {
3680 				lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3681 						"2562 Failure to allocate an "
3682 						"ELS sgl entry:%d\n", i);
3683 				rc = -ENOMEM;
3684 				goto out_free_mem;
3685 			}
3686 			sglq_entry->buff_type = GEN_BUFF_TYPE;
3687 			sglq_entry->virt = lpfc_mbuf_alloc(phba, 0,
3688 							   &sglq_entry->phys);
3689 			if (sglq_entry->virt == NULL) {
3690 				kfree(sglq_entry);
3691 				lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3692 						"2563 Failure to allocate an "
3693 						"ELS mbuf:%d\n", i);
3694 				rc = -ENOMEM;
3695 				goto out_free_mem;
3696 			}
3697 			sglq_entry->sgl = sglq_entry->virt;
3698 			memset(sglq_entry->sgl, 0, LPFC_BPL_SIZE);
3699 			sglq_entry->state = SGL_FREED;
3700 			list_add_tail(&sglq_entry->list, &els_sgl_list);
3701 		}
3702 		spin_lock_irq(&phba->hbalock);
3703 		spin_lock(&phba->sli4_hba.sgl_list_lock);
3704 		list_splice_init(&els_sgl_list,
3705 				 &phba->sli4_hba.lpfc_els_sgl_list);
3706 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
3707 		spin_unlock_irq(&phba->hbalock);
3708 	} else if (els_xri_cnt < phba->sli4_hba.els_xri_cnt) {
3709 		/* els xri-sgl shrinked */
3710 		xri_cnt = phba->sli4_hba.els_xri_cnt - els_xri_cnt;
3711 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3712 				"3158 ELS xri-sgl count decreased from "
3713 				"%d to %d\n", phba->sli4_hba.els_xri_cnt,
3714 				els_xri_cnt);
3715 		spin_lock_irq(&phba->hbalock);
3716 		spin_lock(&phba->sli4_hba.sgl_list_lock);
3717 		list_splice_init(&phba->sli4_hba.lpfc_els_sgl_list,
3718 				 &els_sgl_list);
3719 		/* release extra els sgls from list */
3720 		for (i = 0; i < xri_cnt; i++) {
3721 			list_remove_head(&els_sgl_list,
3722 					 sglq_entry, struct lpfc_sglq, list);
3723 			if (sglq_entry) {
3724 				__lpfc_mbuf_free(phba, sglq_entry->virt,
3725 						 sglq_entry->phys);
3726 				kfree(sglq_entry);
3727 			}
3728 		}
3729 		list_splice_init(&els_sgl_list,
3730 				 &phba->sli4_hba.lpfc_els_sgl_list);
3731 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
3732 		spin_unlock_irq(&phba->hbalock);
3733 	} else
3734 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3735 				"3163 ELS xri-sgl count unchanged: %d\n",
3736 				els_xri_cnt);
3737 	phba->sli4_hba.els_xri_cnt = els_xri_cnt;
3738 
3739 	/* update xris to els sgls on the list */
3740 	sglq_entry = NULL;
3741 	sglq_entry_next = NULL;
3742 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
3743 				 &phba->sli4_hba.lpfc_els_sgl_list, list) {
3744 		lxri = lpfc_sli4_next_xritag(phba);
3745 		if (lxri == NO_XRI) {
3746 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3747 					"2400 Failed to allocate xri for "
3748 					"ELS sgl\n");
3749 			rc = -ENOMEM;
3750 			goto out_free_mem;
3751 		}
3752 		sglq_entry->sli4_lxritag = lxri;
3753 		sglq_entry->sli4_xritag = phba->sli4_hba.xri_ids[lxri];
3754 	}
3755 	return 0;
3756 
3757 out_free_mem:
3758 	lpfc_free_els_sgl_list(phba);
3759 	return rc;
3760 }
3761 
3762 /**
3763  * lpfc_sli4_nvmet_sgl_update - update xri-sgl sizing and mapping
3764  * @phba: pointer to lpfc hba data structure.
3765  *
3766  * This routine first calculates the sizes of the current els and allocated
3767  * scsi sgl lists, and then goes through all sgls to updates the physical
3768  * XRIs assigned due to port function reset. During port initialization, the
3769  * current els and allocated scsi sgl lists are 0s.
3770  *
3771  * Return codes
3772  *   0 - successful (for now, it always returns 0)
3773  **/
3774 int
3775 lpfc_sli4_nvmet_sgl_update(struct lpfc_hba *phba)
3776 {
3777 	struct lpfc_sglq *sglq_entry = NULL, *sglq_entry_next = NULL;
3778 	uint16_t i, lxri, xri_cnt, els_xri_cnt;
3779 	uint16_t nvmet_xri_cnt;
3780 	LIST_HEAD(nvmet_sgl_list);
3781 	int rc;
3782 
3783 	/*
3784 	 * update on pci function's nvmet xri-sgl list
3785 	 */
3786 	els_xri_cnt = lpfc_sli4_get_els_iocb_cnt(phba);
3787 
3788 	/* For NVMET, ALL remaining XRIs are dedicated for IO processing */
3789 	nvmet_xri_cnt = phba->sli4_hba.max_cfg_param.max_xri - els_xri_cnt;
3790 	if (nvmet_xri_cnt > phba->sli4_hba.nvmet_xri_cnt) {
3791 		/* els xri-sgl expanded */
3792 		xri_cnt = nvmet_xri_cnt - phba->sli4_hba.nvmet_xri_cnt;
3793 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3794 				"6302 NVMET xri-sgl cnt grew from %d to %d\n",
3795 				phba->sli4_hba.nvmet_xri_cnt, nvmet_xri_cnt);
3796 		/* allocate the additional nvmet sgls */
3797 		for (i = 0; i < xri_cnt; i++) {
3798 			sglq_entry = kzalloc(sizeof(struct lpfc_sglq),
3799 					     GFP_KERNEL);
3800 			if (sglq_entry == NULL) {
3801 				lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3802 						"6303 Failure to allocate an "
3803 						"NVMET sgl entry:%d\n", i);
3804 				rc = -ENOMEM;
3805 				goto out_free_mem;
3806 			}
3807 			sglq_entry->buff_type = NVMET_BUFF_TYPE;
3808 			sglq_entry->virt = lpfc_nvmet_buf_alloc(phba, 0,
3809 							   &sglq_entry->phys);
3810 			if (sglq_entry->virt == NULL) {
3811 				kfree(sglq_entry);
3812 				lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3813 						"6304 Failure to allocate an "
3814 						"NVMET buf:%d\n", i);
3815 				rc = -ENOMEM;
3816 				goto out_free_mem;
3817 			}
3818 			sglq_entry->sgl = sglq_entry->virt;
3819 			memset(sglq_entry->sgl, 0,
3820 			       phba->cfg_sg_dma_buf_size);
3821 			sglq_entry->state = SGL_FREED;
3822 			list_add_tail(&sglq_entry->list, &nvmet_sgl_list);
3823 		}
3824 		spin_lock_irq(&phba->hbalock);
3825 		spin_lock(&phba->sli4_hba.sgl_list_lock);
3826 		list_splice_init(&nvmet_sgl_list,
3827 				 &phba->sli4_hba.lpfc_nvmet_sgl_list);
3828 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
3829 		spin_unlock_irq(&phba->hbalock);
3830 	} else if (nvmet_xri_cnt < phba->sli4_hba.nvmet_xri_cnt) {
3831 		/* nvmet xri-sgl shrunk */
3832 		xri_cnt = phba->sli4_hba.nvmet_xri_cnt - nvmet_xri_cnt;
3833 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3834 				"6305 NVMET xri-sgl count decreased from "
3835 				"%d to %d\n", phba->sli4_hba.nvmet_xri_cnt,
3836 				nvmet_xri_cnt);
3837 		spin_lock_irq(&phba->hbalock);
3838 		spin_lock(&phba->sli4_hba.sgl_list_lock);
3839 		list_splice_init(&phba->sli4_hba.lpfc_nvmet_sgl_list,
3840 				 &nvmet_sgl_list);
3841 		/* release extra nvmet sgls from list */
3842 		for (i = 0; i < xri_cnt; i++) {
3843 			list_remove_head(&nvmet_sgl_list,
3844 					 sglq_entry, struct lpfc_sglq, list);
3845 			if (sglq_entry) {
3846 				lpfc_nvmet_buf_free(phba, sglq_entry->virt,
3847 						    sglq_entry->phys);
3848 				kfree(sglq_entry);
3849 			}
3850 		}
3851 		list_splice_init(&nvmet_sgl_list,
3852 				 &phba->sli4_hba.lpfc_nvmet_sgl_list);
3853 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
3854 		spin_unlock_irq(&phba->hbalock);
3855 	} else
3856 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3857 				"6306 NVMET xri-sgl count unchanged: %d\n",
3858 				nvmet_xri_cnt);
3859 	phba->sli4_hba.nvmet_xri_cnt = nvmet_xri_cnt;
3860 
3861 	/* update xris to nvmet sgls on the list */
3862 	sglq_entry = NULL;
3863 	sglq_entry_next = NULL;
3864 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
3865 				 &phba->sli4_hba.lpfc_nvmet_sgl_list, list) {
3866 		lxri = lpfc_sli4_next_xritag(phba);
3867 		if (lxri == NO_XRI) {
3868 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3869 					"6307 Failed to allocate xri for "
3870 					"NVMET sgl\n");
3871 			rc = -ENOMEM;
3872 			goto out_free_mem;
3873 		}
3874 		sglq_entry->sli4_lxritag = lxri;
3875 		sglq_entry->sli4_xritag = phba->sli4_hba.xri_ids[lxri];
3876 	}
3877 	return 0;
3878 
3879 out_free_mem:
3880 	lpfc_free_nvmet_sgl_list(phba);
3881 	return rc;
3882 }
3883 
3884 int
3885 lpfc_io_buf_flush(struct lpfc_hba *phba, struct list_head *cbuf)
3886 {
3887 	LIST_HEAD(blist);
3888 	struct lpfc_sli4_hdw_queue *qp;
3889 	struct lpfc_io_buf *lpfc_cmd;
3890 	struct lpfc_io_buf *iobufp, *prev_iobufp;
3891 	int idx, cnt, xri, inserted;
3892 
3893 	cnt = 0;
3894 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
3895 		qp = &phba->sli4_hba.hdwq[idx];
3896 		spin_lock_irq(&qp->io_buf_list_get_lock);
3897 		spin_lock(&qp->io_buf_list_put_lock);
3898 
3899 		/* Take everything off the get and put lists */
3900 		list_splice_init(&qp->lpfc_io_buf_list_get, &blist);
3901 		list_splice(&qp->lpfc_io_buf_list_put, &blist);
3902 		INIT_LIST_HEAD(&qp->lpfc_io_buf_list_get);
3903 		INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
3904 		cnt += qp->get_io_bufs + qp->put_io_bufs;
3905 		qp->get_io_bufs = 0;
3906 		qp->put_io_bufs = 0;
3907 		qp->total_io_bufs = 0;
3908 		spin_unlock(&qp->io_buf_list_put_lock);
3909 		spin_unlock_irq(&qp->io_buf_list_get_lock);
3910 	}
3911 
3912 	/*
3913 	 * Take IO buffers off blist and put on cbuf sorted by XRI.
3914 	 * This is because POST_SGL takes a sequential range of XRIs
3915 	 * to post to the firmware.
3916 	 */
3917 	for (idx = 0; idx < cnt; idx++) {
3918 		list_remove_head(&blist, lpfc_cmd, struct lpfc_io_buf, list);
3919 		if (!lpfc_cmd)
3920 			return cnt;
3921 		if (idx == 0) {
3922 			list_add_tail(&lpfc_cmd->list, cbuf);
3923 			continue;
3924 		}
3925 		xri = lpfc_cmd->cur_iocbq.sli4_xritag;
3926 		inserted = 0;
3927 		prev_iobufp = NULL;
3928 		list_for_each_entry(iobufp, cbuf, list) {
3929 			if (xri < iobufp->cur_iocbq.sli4_xritag) {
3930 				if (prev_iobufp)
3931 					list_add(&lpfc_cmd->list,
3932 						 &prev_iobufp->list);
3933 				else
3934 					list_add(&lpfc_cmd->list, cbuf);
3935 				inserted = 1;
3936 				break;
3937 			}
3938 			prev_iobufp = iobufp;
3939 		}
3940 		if (!inserted)
3941 			list_add_tail(&lpfc_cmd->list, cbuf);
3942 	}
3943 	return cnt;
3944 }
3945 
3946 int
3947 lpfc_io_buf_replenish(struct lpfc_hba *phba, struct list_head *cbuf)
3948 {
3949 	struct lpfc_sli4_hdw_queue *qp;
3950 	struct lpfc_io_buf *lpfc_cmd;
3951 	int idx, cnt;
3952 
3953 	qp = phba->sli4_hba.hdwq;
3954 	cnt = 0;
3955 	while (!list_empty(cbuf)) {
3956 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
3957 			list_remove_head(cbuf, lpfc_cmd,
3958 					 struct lpfc_io_buf, list);
3959 			if (!lpfc_cmd)
3960 				return cnt;
3961 			cnt++;
3962 			qp = &phba->sli4_hba.hdwq[idx];
3963 			lpfc_cmd->hdwq_no = idx;
3964 			lpfc_cmd->hdwq = qp;
3965 			lpfc_cmd->cur_iocbq.wqe_cmpl = NULL;
3966 			lpfc_cmd->cur_iocbq.iocb_cmpl = NULL;
3967 			spin_lock(&qp->io_buf_list_put_lock);
3968 			list_add_tail(&lpfc_cmd->list,
3969 				      &qp->lpfc_io_buf_list_put);
3970 			qp->put_io_bufs++;
3971 			qp->total_io_bufs++;
3972 			spin_unlock(&qp->io_buf_list_put_lock);
3973 		}
3974 	}
3975 	return cnt;
3976 }
3977 
3978 /**
3979  * lpfc_sli4_io_sgl_update - update xri-sgl sizing and mapping
3980  * @phba: pointer to lpfc hba data structure.
3981  *
3982  * This routine first calculates the sizes of the current els and allocated
3983  * scsi sgl lists, and then goes through all sgls to updates the physical
3984  * XRIs assigned due to port function reset. During port initialization, the
3985  * current els and allocated scsi sgl lists are 0s.
3986  *
3987  * Return codes
3988  *   0 - successful (for now, it always returns 0)
3989  **/
3990 int
3991 lpfc_sli4_io_sgl_update(struct lpfc_hba *phba)
3992 {
3993 	struct lpfc_io_buf *lpfc_ncmd = NULL, *lpfc_ncmd_next = NULL;
3994 	uint16_t i, lxri, els_xri_cnt;
3995 	uint16_t io_xri_cnt, io_xri_max;
3996 	LIST_HEAD(io_sgl_list);
3997 	int rc, cnt;
3998 
3999 	/*
4000 	 * update on pci function's allocated nvme xri-sgl list
4001 	 */
4002 
4003 	/* maximum number of xris available for nvme buffers */
4004 	els_xri_cnt = lpfc_sli4_get_els_iocb_cnt(phba);
4005 	io_xri_max = phba->sli4_hba.max_cfg_param.max_xri - els_xri_cnt;
4006 	phba->sli4_hba.io_xri_max = io_xri_max;
4007 
4008 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4009 			"6074 Current allocated XRI sgl count:%d, "
4010 			"maximum XRI count:%d\n",
4011 			phba->sli4_hba.io_xri_cnt,
4012 			phba->sli4_hba.io_xri_max);
4013 
4014 	cnt = lpfc_io_buf_flush(phba, &io_sgl_list);
4015 
4016 	if (phba->sli4_hba.io_xri_cnt > phba->sli4_hba.io_xri_max) {
4017 		/* max nvme xri shrunk below the allocated nvme buffers */
4018 		io_xri_cnt = phba->sli4_hba.io_xri_cnt -
4019 					phba->sli4_hba.io_xri_max;
4020 		/* release the extra allocated nvme buffers */
4021 		for (i = 0; i < io_xri_cnt; i++) {
4022 			list_remove_head(&io_sgl_list, lpfc_ncmd,
4023 					 struct lpfc_io_buf, list);
4024 			if (lpfc_ncmd) {
4025 				dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4026 					      lpfc_ncmd->data,
4027 					      lpfc_ncmd->dma_handle);
4028 				kfree(lpfc_ncmd);
4029 			}
4030 		}
4031 		phba->sli4_hba.io_xri_cnt -= io_xri_cnt;
4032 	}
4033 
4034 	/* update xris associated to remaining allocated nvme buffers */
4035 	lpfc_ncmd = NULL;
4036 	lpfc_ncmd_next = NULL;
4037 	phba->sli4_hba.io_xri_cnt = cnt;
4038 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
4039 				 &io_sgl_list, list) {
4040 		lxri = lpfc_sli4_next_xritag(phba);
4041 		if (lxri == NO_XRI) {
4042 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
4043 					"6075 Failed to allocate xri for "
4044 					"nvme buffer\n");
4045 			rc = -ENOMEM;
4046 			goto out_free_mem;
4047 		}
4048 		lpfc_ncmd->cur_iocbq.sli4_lxritag = lxri;
4049 		lpfc_ncmd->cur_iocbq.sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4050 	}
4051 	cnt = lpfc_io_buf_replenish(phba, &io_sgl_list);
4052 	return 0;
4053 
4054 out_free_mem:
4055 	lpfc_io_free(phba);
4056 	return rc;
4057 }
4058 
4059 /**
4060  * lpfc_new_io_buf - IO buffer allocator for HBA with SLI4 IF spec
4061  * @vport: The virtual port for which this call being executed.
4062  * @num_to_allocate: The requested number of buffers to allocate.
4063  *
4064  * This routine allocates nvme buffers for device with SLI-4 interface spec,
4065  * the nvme buffer contains all the necessary information needed to initiate
4066  * an I/O. After allocating up to @num_to_allocate IO buffers and put
4067  * them on a list, it post them to the port by using SGL block post.
4068  *
4069  * Return codes:
4070  *   int - number of IO buffers that were allocated and posted.
4071  *   0 = failure, less than num_to_alloc is a partial failure.
4072  **/
4073 int
4074 lpfc_new_io_buf(struct lpfc_hba *phba, int num_to_alloc)
4075 {
4076 	struct lpfc_io_buf *lpfc_ncmd;
4077 	struct lpfc_iocbq *pwqeq;
4078 	uint16_t iotag, lxri = 0;
4079 	int bcnt, num_posted;
4080 	LIST_HEAD(prep_nblist);
4081 	LIST_HEAD(post_nblist);
4082 	LIST_HEAD(nvme_nblist);
4083 
4084 	phba->sli4_hba.io_xri_cnt = 0;
4085 	for (bcnt = 0; bcnt < num_to_alloc; bcnt++) {
4086 		lpfc_ncmd = kzalloc(sizeof(*lpfc_ncmd), GFP_KERNEL);
4087 		if (!lpfc_ncmd)
4088 			break;
4089 		/*
4090 		 * Get memory from the pci pool to map the virt space to
4091 		 * pci bus space for an I/O. The DMA buffer includes the
4092 		 * number of SGE's necessary to support the sg_tablesize.
4093 		 */
4094 		lpfc_ncmd->data = dma_pool_zalloc(phba->lpfc_sg_dma_buf_pool,
4095 						  GFP_KERNEL,
4096 						  &lpfc_ncmd->dma_handle);
4097 		if (!lpfc_ncmd->data) {
4098 			kfree(lpfc_ncmd);
4099 			break;
4100 		}
4101 
4102 		if (phba->cfg_xpsgl && !phba->nvmet_support) {
4103 			INIT_LIST_HEAD(&lpfc_ncmd->dma_sgl_xtra_list);
4104 		} else {
4105 			/*
4106 			 * 4K Page alignment is CRITICAL to BlockGuard, double
4107 			 * check to be sure.
4108 			 */
4109 			if ((phba->sli3_options & LPFC_SLI3_BG_ENABLED) &&
4110 			    (((unsigned long)(lpfc_ncmd->data) &
4111 			    (unsigned long)(SLI4_PAGE_SIZE - 1)) != 0)) {
4112 				lpfc_printf_log(phba, KERN_ERR, LOG_FCP,
4113 						"3369 Memory alignment err: "
4114 						"addr=%lx\n",
4115 						(unsigned long)lpfc_ncmd->data);
4116 				dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4117 					      lpfc_ncmd->data,
4118 					      lpfc_ncmd->dma_handle);
4119 				kfree(lpfc_ncmd);
4120 				break;
4121 			}
4122 		}
4123 
4124 		INIT_LIST_HEAD(&lpfc_ncmd->dma_cmd_rsp_list);
4125 
4126 		lxri = lpfc_sli4_next_xritag(phba);
4127 		if (lxri == NO_XRI) {
4128 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4129 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4130 			kfree(lpfc_ncmd);
4131 			break;
4132 		}
4133 		pwqeq = &lpfc_ncmd->cur_iocbq;
4134 
4135 		/* Allocate iotag for lpfc_ncmd->cur_iocbq. */
4136 		iotag = lpfc_sli_next_iotag(phba, pwqeq);
4137 		if (iotag == 0) {
4138 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4139 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4140 			kfree(lpfc_ncmd);
4141 			lpfc_printf_log(phba, KERN_ERR, LOG_NVME_IOERR,
4142 					"6121 Failed to allocate IOTAG for"
4143 					" XRI:0x%x\n", lxri);
4144 			lpfc_sli4_free_xri(phba, lxri);
4145 			break;
4146 		}
4147 		pwqeq->sli4_lxritag = lxri;
4148 		pwqeq->sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4149 		pwqeq->context1 = lpfc_ncmd;
4150 
4151 		/* Initialize local short-hand pointers. */
4152 		lpfc_ncmd->dma_sgl = lpfc_ncmd->data;
4153 		lpfc_ncmd->dma_phys_sgl = lpfc_ncmd->dma_handle;
4154 		lpfc_ncmd->cur_iocbq.context1 = lpfc_ncmd;
4155 		spin_lock_init(&lpfc_ncmd->buf_lock);
4156 
4157 		/* add the nvme buffer to a post list */
4158 		list_add_tail(&lpfc_ncmd->list, &post_nblist);
4159 		phba->sli4_hba.io_xri_cnt++;
4160 	}
4161 	lpfc_printf_log(phba, KERN_INFO, LOG_NVME,
4162 			"6114 Allocate %d out of %d requested new NVME "
4163 			"buffers\n", bcnt, num_to_alloc);
4164 
4165 	/* post the list of nvme buffer sgls to port if available */
4166 	if (!list_empty(&post_nblist))
4167 		num_posted = lpfc_sli4_post_io_sgl_list(
4168 				phba, &post_nblist, bcnt);
4169 	else
4170 		num_posted = 0;
4171 
4172 	return num_posted;
4173 }
4174 
4175 static uint64_t
4176 lpfc_get_wwpn(struct lpfc_hba *phba)
4177 {
4178 	uint64_t wwn;
4179 	int rc;
4180 	LPFC_MBOXQ_t *mboxq;
4181 	MAILBOX_t *mb;
4182 
4183 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
4184 						GFP_KERNEL);
4185 	if (!mboxq)
4186 		return (uint64_t)-1;
4187 
4188 	/* First get WWN of HBA instance */
4189 	lpfc_read_nv(phba, mboxq);
4190 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
4191 	if (rc != MBX_SUCCESS) {
4192 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
4193 				"6019 Mailbox failed , mbxCmd x%x "
4194 				"READ_NV, mbxStatus x%x\n",
4195 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
4196 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
4197 		mempool_free(mboxq, phba->mbox_mem_pool);
4198 		return (uint64_t) -1;
4199 	}
4200 	mb = &mboxq->u.mb;
4201 	memcpy(&wwn, (char *)mb->un.varRDnvp.portname, sizeof(uint64_t));
4202 	/* wwn is WWPN of HBA instance */
4203 	mempool_free(mboxq, phba->mbox_mem_pool);
4204 	if (phba->sli_rev == LPFC_SLI_REV4)
4205 		return be64_to_cpu(wwn);
4206 	else
4207 		return rol64(wwn, 32);
4208 }
4209 
4210 /**
4211  * lpfc_create_port - Create an FC port
4212  * @phba: pointer to lpfc hba data structure.
4213  * @instance: a unique integer ID to this FC port.
4214  * @dev: pointer to the device data structure.
4215  *
4216  * This routine creates a FC port for the upper layer protocol. The FC port
4217  * can be created on top of either a physical port or a virtual port provided
4218  * by the HBA. This routine also allocates a SCSI host data structure (shost)
4219  * and associates the FC port created before adding the shost into the SCSI
4220  * layer.
4221  *
4222  * Return codes
4223  *   @vport - pointer to the virtual N_Port data structure.
4224  *   NULL - port create failed.
4225  **/
4226 struct lpfc_vport *
4227 lpfc_create_port(struct lpfc_hba *phba, int instance, struct device *dev)
4228 {
4229 	struct lpfc_vport *vport;
4230 	struct Scsi_Host  *shost = NULL;
4231 	struct scsi_host_template *template;
4232 	int error = 0;
4233 	int i;
4234 	uint64_t wwn;
4235 	bool use_no_reset_hba = false;
4236 	int rc;
4237 
4238 	if (lpfc_no_hba_reset_cnt) {
4239 		if (phba->sli_rev < LPFC_SLI_REV4 &&
4240 		    dev == &phba->pcidev->dev) {
4241 			/* Reset the port first */
4242 			lpfc_sli_brdrestart(phba);
4243 			rc = lpfc_sli_chipset_init(phba);
4244 			if (rc)
4245 				return NULL;
4246 		}
4247 		wwn = lpfc_get_wwpn(phba);
4248 	}
4249 
4250 	for (i = 0; i < lpfc_no_hba_reset_cnt; i++) {
4251 		if (wwn == lpfc_no_hba_reset[i]) {
4252 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
4253 					"6020 Setting use_no_reset port=%llx\n",
4254 					wwn);
4255 			use_no_reset_hba = true;
4256 			break;
4257 		}
4258 	}
4259 
4260 	/* Seed template for SCSI host registration */
4261 	if (dev == &phba->pcidev->dev) {
4262 		template = &phba->port_template;
4263 
4264 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP) {
4265 			/* Seed physical port template */
4266 			memcpy(template, &lpfc_template, sizeof(*template));
4267 
4268 			if (use_no_reset_hba) {
4269 				/* template is for a no reset SCSI Host */
4270 				template->max_sectors = 0xffff;
4271 				template->eh_host_reset_handler = NULL;
4272 			}
4273 
4274 			/* Template for all vports this physical port creates */
4275 			memcpy(&phba->vport_template, &lpfc_template,
4276 			       sizeof(*template));
4277 			phba->vport_template.max_sectors = 0xffff;
4278 			phba->vport_template.shost_attrs = lpfc_vport_attrs;
4279 			phba->vport_template.eh_bus_reset_handler = NULL;
4280 			phba->vport_template.eh_host_reset_handler = NULL;
4281 			phba->vport_template.vendor_id = 0;
4282 
4283 			/* Initialize the host templates with updated value */
4284 			if (phba->sli_rev == LPFC_SLI_REV4) {
4285 				template->sg_tablesize = phba->cfg_scsi_seg_cnt;
4286 				phba->vport_template.sg_tablesize =
4287 					phba->cfg_scsi_seg_cnt;
4288 			} else {
4289 				template->sg_tablesize = phba->cfg_sg_seg_cnt;
4290 				phba->vport_template.sg_tablesize =
4291 					phba->cfg_sg_seg_cnt;
4292 			}
4293 
4294 		} else {
4295 			/* NVMET is for physical port only */
4296 			memcpy(template, &lpfc_template_nvme,
4297 			       sizeof(*template));
4298 		}
4299 	} else {
4300 		template = &phba->vport_template;
4301 	}
4302 
4303 	shost = scsi_host_alloc(template, sizeof(struct lpfc_vport));
4304 	if (!shost)
4305 		goto out;
4306 
4307 	vport = (struct lpfc_vport *) shost->hostdata;
4308 	vport->phba = phba;
4309 	vport->load_flag |= FC_LOADING;
4310 	vport->fc_flag |= FC_VPORT_NEEDS_REG_VPI;
4311 	vport->fc_rscn_flush = 0;
4312 	lpfc_get_vport_cfgparam(vport);
4313 
4314 	/* Adjust value in vport */
4315 	vport->cfg_enable_fc4_type = phba->cfg_enable_fc4_type;
4316 
4317 	shost->unique_id = instance;
4318 	shost->max_id = LPFC_MAX_TARGET;
4319 	shost->max_lun = vport->cfg_max_luns;
4320 	shost->this_id = -1;
4321 	shost->max_cmd_len = 16;
4322 
4323 	if (phba->sli_rev == LPFC_SLI_REV4) {
4324 		if (!phba->cfg_fcp_mq_threshold ||
4325 		    phba->cfg_fcp_mq_threshold > phba->cfg_hdw_queue)
4326 			phba->cfg_fcp_mq_threshold = phba->cfg_hdw_queue;
4327 
4328 		shost->nr_hw_queues = min_t(int, 2 * num_possible_nodes(),
4329 					    phba->cfg_fcp_mq_threshold);
4330 
4331 		shost->dma_boundary =
4332 			phba->sli4_hba.pc_sli4_params.sge_supp_len-1;
4333 
4334 		if (phba->cfg_xpsgl && !phba->nvmet_support)
4335 			shost->sg_tablesize = LPFC_MAX_SG_TABLESIZE;
4336 		else
4337 			shost->sg_tablesize = phba->cfg_scsi_seg_cnt;
4338 	} else
4339 		/* SLI-3 has a limited number of hardware queues (3),
4340 		 * thus there is only one for FCP processing.
4341 		 */
4342 		shost->nr_hw_queues = 1;
4343 
4344 	/*
4345 	 * Set initial can_queue value since 0 is no longer supported and
4346 	 * scsi_add_host will fail. This will be adjusted later based on the
4347 	 * max xri value determined in hba setup.
4348 	 */
4349 	shost->can_queue = phba->cfg_hba_queue_depth - 10;
4350 	if (dev != &phba->pcidev->dev) {
4351 		shost->transportt = lpfc_vport_transport_template;
4352 		vport->port_type = LPFC_NPIV_PORT;
4353 	} else {
4354 		shost->transportt = lpfc_transport_template;
4355 		vport->port_type = LPFC_PHYSICAL_PORT;
4356 	}
4357 
4358 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP,
4359 			"9081 CreatePort TMPLATE type %x TBLsize %d "
4360 			"SEGcnt %d/%d\n",
4361 			vport->port_type, shost->sg_tablesize,
4362 			phba->cfg_scsi_seg_cnt, phba->cfg_sg_seg_cnt);
4363 
4364 	/* Initialize all internally managed lists. */
4365 	INIT_LIST_HEAD(&vport->fc_nodes);
4366 	INIT_LIST_HEAD(&vport->rcv_buffer_list);
4367 	spin_lock_init(&vport->work_port_lock);
4368 
4369 	timer_setup(&vport->fc_disctmo, lpfc_disc_timeout, 0);
4370 
4371 	timer_setup(&vport->els_tmofunc, lpfc_els_timeout, 0);
4372 
4373 	timer_setup(&vport->delayed_disc_tmo, lpfc_delayed_disc_tmo, 0);
4374 
4375 	if (phba->sli3_options & LPFC_SLI3_BG_ENABLED)
4376 		lpfc_setup_bg(phba, shost);
4377 
4378 	error = scsi_add_host_with_dma(shost, dev, &phba->pcidev->dev);
4379 	if (error)
4380 		goto out_put_shost;
4381 
4382 	spin_lock_irq(&phba->port_list_lock);
4383 	list_add_tail(&vport->listentry, &phba->port_list);
4384 	spin_unlock_irq(&phba->port_list_lock);
4385 	return vport;
4386 
4387 out_put_shost:
4388 	scsi_host_put(shost);
4389 out:
4390 	return NULL;
4391 }
4392 
4393 /**
4394  * destroy_port -  destroy an FC port
4395  * @vport: pointer to an lpfc virtual N_Port data structure.
4396  *
4397  * This routine destroys a FC port from the upper layer protocol. All the
4398  * resources associated with the port are released.
4399  **/
4400 void
4401 destroy_port(struct lpfc_vport *vport)
4402 {
4403 	struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
4404 	struct lpfc_hba  *phba = vport->phba;
4405 
4406 	lpfc_debugfs_terminate(vport);
4407 	fc_remove_host(shost);
4408 	scsi_remove_host(shost);
4409 
4410 	spin_lock_irq(&phba->port_list_lock);
4411 	list_del_init(&vport->listentry);
4412 	spin_unlock_irq(&phba->port_list_lock);
4413 
4414 	lpfc_cleanup(vport);
4415 	return;
4416 }
4417 
4418 /**
4419  * lpfc_get_instance - Get a unique integer ID
4420  *
4421  * This routine allocates a unique integer ID from lpfc_hba_index pool. It
4422  * uses the kernel idr facility to perform the task.
4423  *
4424  * Return codes:
4425  *   instance - a unique integer ID allocated as the new instance.
4426  *   -1 - lpfc get instance failed.
4427  **/
4428 int
4429 lpfc_get_instance(void)
4430 {
4431 	int ret;
4432 
4433 	ret = idr_alloc(&lpfc_hba_index, NULL, 0, 0, GFP_KERNEL);
4434 	return ret < 0 ? -1 : ret;
4435 }
4436 
4437 /**
4438  * lpfc_scan_finished - method for SCSI layer to detect whether scan is done
4439  * @shost: pointer to SCSI host data structure.
4440  * @time: elapsed time of the scan in jiffies.
4441  *
4442  * This routine is called by the SCSI layer with a SCSI host to determine
4443  * whether the scan host is finished.
4444  *
4445  * Note: there is no scan_start function as adapter initialization will have
4446  * asynchronously kicked off the link initialization.
4447  *
4448  * Return codes
4449  *   0 - SCSI host scan is not over yet.
4450  *   1 - SCSI host scan is over.
4451  **/
4452 int lpfc_scan_finished(struct Scsi_Host *shost, unsigned long time)
4453 {
4454 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
4455 	struct lpfc_hba   *phba = vport->phba;
4456 	int stat = 0;
4457 
4458 	spin_lock_irq(shost->host_lock);
4459 
4460 	if (vport->load_flag & FC_UNLOADING) {
4461 		stat = 1;
4462 		goto finished;
4463 	}
4464 	if (time >= msecs_to_jiffies(30 * 1000)) {
4465 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4466 				"0461 Scanning longer than 30 "
4467 				"seconds.  Continuing initialization\n");
4468 		stat = 1;
4469 		goto finished;
4470 	}
4471 	if (time >= msecs_to_jiffies(15 * 1000) &&
4472 	    phba->link_state <= LPFC_LINK_DOWN) {
4473 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4474 				"0465 Link down longer than 15 "
4475 				"seconds.  Continuing initialization\n");
4476 		stat = 1;
4477 		goto finished;
4478 	}
4479 
4480 	if (vport->port_state != LPFC_VPORT_READY)
4481 		goto finished;
4482 	if (vport->num_disc_nodes || vport->fc_prli_sent)
4483 		goto finished;
4484 	if (vport->fc_map_cnt == 0 && time < msecs_to_jiffies(2 * 1000))
4485 		goto finished;
4486 	if ((phba->sli.sli_flag & LPFC_SLI_MBOX_ACTIVE) != 0)
4487 		goto finished;
4488 
4489 	stat = 1;
4490 
4491 finished:
4492 	spin_unlock_irq(shost->host_lock);
4493 	return stat;
4494 }
4495 
4496 static void lpfc_host_supported_speeds_set(struct Scsi_Host *shost)
4497 {
4498 	struct lpfc_vport *vport = (struct lpfc_vport *)shost->hostdata;
4499 	struct lpfc_hba   *phba = vport->phba;
4500 
4501 	fc_host_supported_speeds(shost) = 0;
4502 	if (phba->lmt & LMT_128Gb)
4503 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_128GBIT;
4504 	if (phba->lmt & LMT_64Gb)
4505 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_64GBIT;
4506 	if (phba->lmt & LMT_32Gb)
4507 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_32GBIT;
4508 	if (phba->lmt & LMT_16Gb)
4509 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_16GBIT;
4510 	if (phba->lmt & LMT_10Gb)
4511 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_10GBIT;
4512 	if (phba->lmt & LMT_8Gb)
4513 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_8GBIT;
4514 	if (phba->lmt & LMT_4Gb)
4515 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_4GBIT;
4516 	if (phba->lmt & LMT_2Gb)
4517 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_2GBIT;
4518 	if (phba->lmt & LMT_1Gb)
4519 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_1GBIT;
4520 }
4521 
4522 /**
4523  * lpfc_host_attrib_init - Initialize SCSI host attributes on a FC port
4524  * @shost: pointer to SCSI host data structure.
4525  *
4526  * This routine initializes a given SCSI host attributes on a FC port. The
4527  * SCSI host can be either on top of a physical port or a virtual port.
4528  **/
4529 void lpfc_host_attrib_init(struct Scsi_Host *shost)
4530 {
4531 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
4532 	struct lpfc_hba   *phba = vport->phba;
4533 	/*
4534 	 * Set fixed host attributes.  Must done after lpfc_sli_hba_setup().
4535 	 */
4536 
4537 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
4538 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
4539 	fc_host_supported_classes(shost) = FC_COS_CLASS3;
4540 
4541 	memset(fc_host_supported_fc4s(shost), 0,
4542 	       sizeof(fc_host_supported_fc4s(shost)));
4543 	fc_host_supported_fc4s(shost)[2] = 1;
4544 	fc_host_supported_fc4s(shost)[7] = 1;
4545 
4546 	lpfc_vport_symbolic_node_name(vport, fc_host_symbolic_name(shost),
4547 				 sizeof fc_host_symbolic_name(shost));
4548 
4549 	lpfc_host_supported_speeds_set(shost);
4550 
4551 	fc_host_maxframe_size(shost) =
4552 		(((uint32_t) vport->fc_sparam.cmn.bbRcvSizeMsb & 0x0F) << 8) |
4553 		(uint32_t) vport->fc_sparam.cmn.bbRcvSizeLsb;
4554 
4555 	fc_host_dev_loss_tmo(shost) = vport->cfg_devloss_tmo;
4556 
4557 	/* This value is also unchanging */
4558 	memset(fc_host_active_fc4s(shost), 0,
4559 	       sizeof(fc_host_active_fc4s(shost)));
4560 	fc_host_active_fc4s(shost)[2] = 1;
4561 	fc_host_active_fc4s(shost)[7] = 1;
4562 
4563 	fc_host_max_npiv_vports(shost) = phba->max_vpi;
4564 	spin_lock_irq(shost->host_lock);
4565 	vport->load_flag &= ~FC_LOADING;
4566 	spin_unlock_irq(shost->host_lock);
4567 }
4568 
4569 /**
4570  * lpfc_stop_port_s3 - Stop SLI3 device port
4571  * @phba: pointer to lpfc hba data structure.
4572  *
4573  * This routine is invoked to stop an SLI3 device port, it stops the device
4574  * from generating interrupts and stops the device driver's timers for the
4575  * device.
4576  **/
4577 static void
4578 lpfc_stop_port_s3(struct lpfc_hba *phba)
4579 {
4580 	/* Clear all interrupt enable conditions */
4581 	writel(0, phba->HCregaddr);
4582 	readl(phba->HCregaddr); /* flush */
4583 	/* Clear all pending interrupts */
4584 	writel(0xffffffff, phba->HAregaddr);
4585 	readl(phba->HAregaddr); /* flush */
4586 
4587 	/* Reset some HBA SLI setup states */
4588 	lpfc_stop_hba_timers(phba);
4589 	phba->pport->work_port_events = 0;
4590 }
4591 
4592 /**
4593  * lpfc_stop_port_s4 - Stop SLI4 device port
4594  * @phba: pointer to lpfc hba data structure.
4595  *
4596  * This routine is invoked to stop an SLI4 device port, it stops the device
4597  * from generating interrupts and stops the device driver's timers for the
4598  * device.
4599  **/
4600 static void
4601 lpfc_stop_port_s4(struct lpfc_hba *phba)
4602 {
4603 	/* Reset some HBA SLI4 setup states */
4604 	lpfc_stop_hba_timers(phba);
4605 	if (phba->pport)
4606 		phba->pport->work_port_events = 0;
4607 	phba->sli4_hba.intr_enable = 0;
4608 }
4609 
4610 /**
4611  * lpfc_stop_port - Wrapper function for stopping hba port
4612  * @phba: Pointer to HBA context object.
4613  *
4614  * This routine wraps the actual SLI3 or SLI4 hba stop port routine from
4615  * the API jump table function pointer from the lpfc_hba struct.
4616  **/
4617 void
4618 lpfc_stop_port(struct lpfc_hba *phba)
4619 {
4620 	phba->lpfc_stop_port(phba);
4621 
4622 	if (phba->wq)
4623 		flush_workqueue(phba->wq);
4624 }
4625 
4626 /**
4627  * lpfc_fcf_redisc_wait_start_timer - Start fcf rediscover wait timer
4628  * @phba: Pointer to hba for which this call is being executed.
4629  *
4630  * This routine starts the timer waiting for the FCF rediscovery to complete.
4631  **/
4632 void
4633 lpfc_fcf_redisc_wait_start_timer(struct lpfc_hba *phba)
4634 {
4635 	unsigned long fcf_redisc_wait_tmo =
4636 		(jiffies + msecs_to_jiffies(LPFC_FCF_REDISCOVER_WAIT_TMO));
4637 	/* Start fcf rediscovery wait period timer */
4638 	mod_timer(&phba->fcf.redisc_wait, fcf_redisc_wait_tmo);
4639 	spin_lock_irq(&phba->hbalock);
4640 	/* Allow action to new fcf asynchronous event */
4641 	phba->fcf.fcf_flag &= ~(FCF_AVAILABLE | FCF_SCAN_DONE);
4642 	/* Mark the FCF rediscovery pending state */
4643 	phba->fcf.fcf_flag |= FCF_REDISC_PEND;
4644 	spin_unlock_irq(&phba->hbalock);
4645 }
4646 
4647 /**
4648  * lpfc_sli4_fcf_redisc_wait_tmo - FCF table rediscover wait timeout
4649  * @ptr: Map to lpfc_hba data structure pointer.
4650  *
4651  * This routine is invoked when waiting for FCF table rediscover has been
4652  * timed out. If new FCF record(s) has (have) been discovered during the
4653  * wait period, a new FCF event shall be added to the FCOE async event
4654  * list, and then worker thread shall be waked up for processing from the
4655  * worker thread context.
4656  **/
4657 static void
4658 lpfc_sli4_fcf_redisc_wait_tmo(struct timer_list *t)
4659 {
4660 	struct lpfc_hba *phba = from_timer(phba, t, fcf.redisc_wait);
4661 
4662 	/* Don't send FCF rediscovery event if timer cancelled */
4663 	spin_lock_irq(&phba->hbalock);
4664 	if (!(phba->fcf.fcf_flag & FCF_REDISC_PEND)) {
4665 		spin_unlock_irq(&phba->hbalock);
4666 		return;
4667 	}
4668 	/* Clear FCF rediscovery timer pending flag */
4669 	phba->fcf.fcf_flag &= ~FCF_REDISC_PEND;
4670 	/* FCF rediscovery event to worker thread */
4671 	phba->fcf.fcf_flag |= FCF_REDISC_EVT;
4672 	spin_unlock_irq(&phba->hbalock);
4673 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
4674 			"2776 FCF rediscover quiescent timer expired\n");
4675 	/* wake up worker thread */
4676 	lpfc_worker_wake_up(phba);
4677 }
4678 
4679 /**
4680  * lpfc_sli4_parse_latt_fault - Parse sli4 link-attention link fault code
4681  * @phba: pointer to lpfc hba data structure.
4682  * @acqe_link: pointer to the async link completion queue entry.
4683  *
4684  * This routine is to parse the SLI4 link-attention link fault code.
4685  **/
4686 static void
4687 lpfc_sli4_parse_latt_fault(struct lpfc_hba *phba,
4688 			   struct lpfc_acqe_link *acqe_link)
4689 {
4690 	switch (bf_get(lpfc_acqe_link_fault, acqe_link)) {
4691 	case LPFC_ASYNC_LINK_FAULT_NONE:
4692 	case LPFC_ASYNC_LINK_FAULT_LOCAL:
4693 	case LPFC_ASYNC_LINK_FAULT_REMOTE:
4694 	case LPFC_ASYNC_LINK_FAULT_LR_LRR:
4695 		break;
4696 	default:
4697 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4698 				"0398 Unknown link fault code: x%x\n",
4699 				bf_get(lpfc_acqe_link_fault, acqe_link));
4700 		break;
4701 	}
4702 }
4703 
4704 /**
4705  * lpfc_sli4_parse_latt_type - Parse sli4 link attention type
4706  * @phba: pointer to lpfc hba data structure.
4707  * @acqe_link: pointer to the async link completion queue entry.
4708  *
4709  * This routine is to parse the SLI4 link attention type and translate it
4710  * into the base driver's link attention type coding.
4711  *
4712  * Return: Link attention type in terms of base driver's coding.
4713  **/
4714 static uint8_t
4715 lpfc_sli4_parse_latt_type(struct lpfc_hba *phba,
4716 			  struct lpfc_acqe_link *acqe_link)
4717 {
4718 	uint8_t att_type;
4719 
4720 	switch (bf_get(lpfc_acqe_link_status, acqe_link)) {
4721 	case LPFC_ASYNC_LINK_STATUS_DOWN:
4722 	case LPFC_ASYNC_LINK_STATUS_LOGICAL_DOWN:
4723 		att_type = LPFC_ATT_LINK_DOWN;
4724 		break;
4725 	case LPFC_ASYNC_LINK_STATUS_UP:
4726 		/* Ignore physical link up events - wait for logical link up */
4727 		att_type = LPFC_ATT_RESERVED;
4728 		break;
4729 	case LPFC_ASYNC_LINK_STATUS_LOGICAL_UP:
4730 		att_type = LPFC_ATT_LINK_UP;
4731 		break;
4732 	default:
4733 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4734 				"0399 Invalid link attention type: x%x\n",
4735 				bf_get(lpfc_acqe_link_status, acqe_link));
4736 		att_type = LPFC_ATT_RESERVED;
4737 		break;
4738 	}
4739 	return att_type;
4740 }
4741 
4742 /**
4743  * lpfc_sli_port_speed_get - Get sli3 link speed code to link speed
4744  * @phba: pointer to lpfc hba data structure.
4745  *
4746  * This routine is to get an SLI3 FC port's link speed in Mbps.
4747  *
4748  * Return: link speed in terms of Mbps.
4749  **/
4750 uint32_t
4751 lpfc_sli_port_speed_get(struct lpfc_hba *phba)
4752 {
4753 	uint32_t link_speed;
4754 
4755 	if (!lpfc_is_link_up(phba))
4756 		return 0;
4757 
4758 	if (phba->sli_rev <= LPFC_SLI_REV3) {
4759 		switch (phba->fc_linkspeed) {
4760 		case LPFC_LINK_SPEED_1GHZ:
4761 			link_speed = 1000;
4762 			break;
4763 		case LPFC_LINK_SPEED_2GHZ:
4764 			link_speed = 2000;
4765 			break;
4766 		case LPFC_LINK_SPEED_4GHZ:
4767 			link_speed = 4000;
4768 			break;
4769 		case LPFC_LINK_SPEED_8GHZ:
4770 			link_speed = 8000;
4771 			break;
4772 		case LPFC_LINK_SPEED_10GHZ:
4773 			link_speed = 10000;
4774 			break;
4775 		case LPFC_LINK_SPEED_16GHZ:
4776 			link_speed = 16000;
4777 			break;
4778 		default:
4779 			link_speed = 0;
4780 		}
4781 	} else {
4782 		if (phba->sli4_hba.link_state.logical_speed)
4783 			link_speed =
4784 			      phba->sli4_hba.link_state.logical_speed;
4785 		else
4786 			link_speed = phba->sli4_hba.link_state.speed;
4787 	}
4788 	return link_speed;
4789 }
4790 
4791 /**
4792  * lpfc_sli4_port_speed_parse - Parse async evt link speed code to link speed
4793  * @phba: pointer to lpfc hba data structure.
4794  * @evt_code: asynchronous event code.
4795  * @speed_code: asynchronous event link speed code.
4796  *
4797  * This routine is to parse the giving SLI4 async event link speed code into
4798  * value of Mbps for the link speed.
4799  *
4800  * Return: link speed in terms of Mbps.
4801  **/
4802 static uint32_t
4803 lpfc_sli4_port_speed_parse(struct lpfc_hba *phba, uint32_t evt_code,
4804 			   uint8_t speed_code)
4805 {
4806 	uint32_t port_speed;
4807 
4808 	switch (evt_code) {
4809 	case LPFC_TRAILER_CODE_LINK:
4810 		switch (speed_code) {
4811 		case LPFC_ASYNC_LINK_SPEED_ZERO:
4812 			port_speed = 0;
4813 			break;
4814 		case LPFC_ASYNC_LINK_SPEED_10MBPS:
4815 			port_speed = 10;
4816 			break;
4817 		case LPFC_ASYNC_LINK_SPEED_100MBPS:
4818 			port_speed = 100;
4819 			break;
4820 		case LPFC_ASYNC_LINK_SPEED_1GBPS:
4821 			port_speed = 1000;
4822 			break;
4823 		case LPFC_ASYNC_LINK_SPEED_10GBPS:
4824 			port_speed = 10000;
4825 			break;
4826 		case LPFC_ASYNC_LINK_SPEED_20GBPS:
4827 			port_speed = 20000;
4828 			break;
4829 		case LPFC_ASYNC_LINK_SPEED_25GBPS:
4830 			port_speed = 25000;
4831 			break;
4832 		case LPFC_ASYNC_LINK_SPEED_40GBPS:
4833 			port_speed = 40000;
4834 			break;
4835 		default:
4836 			port_speed = 0;
4837 		}
4838 		break;
4839 	case LPFC_TRAILER_CODE_FC:
4840 		switch (speed_code) {
4841 		case LPFC_FC_LA_SPEED_UNKNOWN:
4842 			port_speed = 0;
4843 			break;
4844 		case LPFC_FC_LA_SPEED_1G:
4845 			port_speed = 1000;
4846 			break;
4847 		case LPFC_FC_LA_SPEED_2G:
4848 			port_speed = 2000;
4849 			break;
4850 		case LPFC_FC_LA_SPEED_4G:
4851 			port_speed = 4000;
4852 			break;
4853 		case LPFC_FC_LA_SPEED_8G:
4854 			port_speed = 8000;
4855 			break;
4856 		case LPFC_FC_LA_SPEED_10G:
4857 			port_speed = 10000;
4858 			break;
4859 		case LPFC_FC_LA_SPEED_16G:
4860 			port_speed = 16000;
4861 			break;
4862 		case LPFC_FC_LA_SPEED_32G:
4863 			port_speed = 32000;
4864 			break;
4865 		case LPFC_FC_LA_SPEED_64G:
4866 			port_speed = 64000;
4867 			break;
4868 		case LPFC_FC_LA_SPEED_128G:
4869 			port_speed = 128000;
4870 			break;
4871 		default:
4872 			port_speed = 0;
4873 		}
4874 		break;
4875 	default:
4876 		port_speed = 0;
4877 	}
4878 	return port_speed;
4879 }
4880 
4881 /**
4882  * lpfc_sli4_async_link_evt - Process the asynchronous FCoE link event
4883  * @phba: pointer to lpfc hba data structure.
4884  * @acqe_link: pointer to the async link completion queue entry.
4885  *
4886  * This routine is to handle the SLI4 asynchronous FCoE link event.
4887  **/
4888 static void
4889 lpfc_sli4_async_link_evt(struct lpfc_hba *phba,
4890 			 struct lpfc_acqe_link *acqe_link)
4891 {
4892 	struct lpfc_dmabuf *mp;
4893 	LPFC_MBOXQ_t *pmb;
4894 	MAILBOX_t *mb;
4895 	struct lpfc_mbx_read_top *la;
4896 	uint8_t att_type;
4897 	int rc;
4898 
4899 	att_type = lpfc_sli4_parse_latt_type(phba, acqe_link);
4900 	if (att_type != LPFC_ATT_LINK_DOWN && att_type != LPFC_ATT_LINK_UP)
4901 		return;
4902 	phba->fcoe_eventtag = acqe_link->event_tag;
4903 	pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4904 	if (!pmb) {
4905 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
4906 				"0395 The mboxq allocation failed\n");
4907 		return;
4908 	}
4909 	mp = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
4910 	if (!mp) {
4911 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
4912 				"0396 The lpfc_dmabuf allocation failed\n");
4913 		goto out_free_pmb;
4914 	}
4915 	mp->virt = lpfc_mbuf_alloc(phba, 0, &mp->phys);
4916 	if (!mp->virt) {
4917 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
4918 				"0397 The mbuf allocation failed\n");
4919 		goto out_free_dmabuf;
4920 	}
4921 
4922 	/* Cleanup any outstanding ELS commands */
4923 	lpfc_els_flush_all_cmd(phba);
4924 
4925 	/* Block ELS IOCBs until we have done process link event */
4926 	phba->sli4_hba.els_wq->pring->flag |= LPFC_STOP_IOCB_EVENT;
4927 
4928 	/* Update link event statistics */
4929 	phba->sli.slistat.link_event++;
4930 
4931 	/* Create lpfc_handle_latt mailbox command from link ACQE */
4932 	lpfc_read_topology(phba, pmb, mp);
4933 	pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
4934 	pmb->vport = phba->pport;
4935 
4936 	/* Keep the link status for extra SLI4 state machine reference */
4937 	phba->sli4_hba.link_state.speed =
4938 			lpfc_sli4_port_speed_parse(phba, LPFC_TRAILER_CODE_LINK,
4939 				bf_get(lpfc_acqe_link_speed, acqe_link));
4940 	phba->sli4_hba.link_state.duplex =
4941 				bf_get(lpfc_acqe_link_duplex, acqe_link);
4942 	phba->sli4_hba.link_state.status =
4943 				bf_get(lpfc_acqe_link_status, acqe_link);
4944 	phba->sli4_hba.link_state.type =
4945 				bf_get(lpfc_acqe_link_type, acqe_link);
4946 	phba->sli4_hba.link_state.number =
4947 				bf_get(lpfc_acqe_link_number, acqe_link);
4948 	phba->sli4_hba.link_state.fault =
4949 				bf_get(lpfc_acqe_link_fault, acqe_link);
4950 	phba->sli4_hba.link_state.logical_speed =
4951 			bf_get(lpfc_acqe_logical_link_speed, acqe_link) * 10;
4952 
4953 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4954 			"2900 Async FC/FCoE Link event - Speed:%dGBit "
4955 			"duplex:x%x LA Type:x%x Port Type:%d Port Number:%d "
4956 			"Logical speed:%dMbps Fault:%d\n",
4957 			phba->sli4_hba.link_state.speed,
4958 			phba->sli4_hba.link_state.topology,
4959 			phba->sli4_hba.link_state.status,
4960 			phba->sli4_hba.link_state.type,
4961 			phba->sli4_hba.link_state.number,
4962 			phba->sli4_hba.link_state.logical_speed,
4963 			phba->sli4_hba.link_state.fault);
4964 	/*
4965 	 * For FC Mode: issue the READ_TOPOLOGY mailbox command to fetch
4966 	 * topology info. Note: Optional for non FC-AL ports.
4967 	 */
4968 	if (!(phba->hba_flag & HBA_FCOE_MODE)) {
4969 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
4970 		if (rc == MBX_NOT_FINISHED)
4971 			goto out_free_dmabuf;
4972 		return;
4973 	}
4974 	/*
4975 	 * For FCoE Mode: fill in all the topology information we need and call
4976 	 * the READ_TOPOLOGY completion routine to continue without actually
4977 	 * sending the READ_TOPOLOGY mailbox command to the port.
4978 	 */
4979 	/* Initialize completion status */
4980 	mb = &pmb->u.mb;
4981 	mb->mbxStatus = MBX_SUCCESS;
4982 
4983 	/* Parse port fault information field */
4984 	lpfc_sli4_parse_latt_fault(phba, acqe_link);
4985 
4986 	/* Parse and translate link attention fields */
4987 	la = (struct lpfc_mbx_read_top *) &pmb->u.mb.un.varReadTop;
4988 	la->eventTag = acqe_link->event_tag;
4989 	bf_set(lpfc_mbx_read_top_att_type, la, att_type);
4990 	bf_set(lpfc_mbx_read_top_link_spd, la,
4991 	       (bf_get(lpfc_acqe_link_speed, acqe_link)));
4992 
4993 	/* Fake the the following irrelvant fields */
4994 	bf_set(lpfc_mbx_read_top_topology, la, LPFC_TOPOLOGY_PT_PT);
4995 	bf_set(lpfc_mbx_read_top_alpa_granted, la, 0);
4996 	bf_set(lpfc_mbx_read_top_il, la, 0);
4997 	bf_set(lpfc_mbx_read_top_pb, la, 0);
4998 	bf_set(lpfc_mbx_read_top_fa, la, 0);
4999 	bf_set(lpfc_mbx_read_top_mm, la, 0);
5000 
5001 	/* Invoke the lpfc_handle_latt mailbox command callback function */
5002 	lpfc_mbx_cmpl_read_topology(phba, pmb);
5003 
5004 	return;
5005 
5006 out_free_dmabuf:
5007 	kfree(mp);
5008 out_free_pmb:
5009 	mempool_free(pmb, phba->mbox_mem_pool);
5010 }
5011 
5012 /**
5013  * lpfc_async_link_speed_to_read_top - Parse async evt link speed code to read
5014  * topology.
5015  * @phba: pointer to lpfc hba data structure.
5016  * @evt_code: asynchronous event code.
5017  * @speed_code: asynchronous event link speed code.
5018  *
5019  * This routine is to parse the giving SLI4 async event link speed code into
5020  * value of Read topology link speed.
5021  *
5022  * Return: link speed in terms of Read topology.
5023  **/
5024 static uint8_t
5025 lpfc_async_link_speed_to_read_top(struct lpfc_hba *phba, uint8_t speed_code)
5026 {
5027 	uint8_t port_speed;
5028 
5029 	switch (speed_code) {
5030 	case LPFC_FC_LA_SPEED_1G:
5031 		port_speed = LPFC_LINK_SPEED_1GHZ;
5032 		break;
5033 	case LPFC_FC_LA_SPEED_2G:
5034 		port_speed = LPFC_LINK_SPEED_2GHZ;
5035 		break;
5036 	case LPFC_FC_LA_SPEED_4G:
5037 		port_speed = LPFC_LINK_SPEED_4GHZ;
5038 		break;
5039 	case LPFC_FC_LA_SPEED_8G:
5040 		port_speed = LPFC_LINK_SPEED_8GHZ;
5041 		break;
5042 	case LPFC_FC_LA_SPEED_16G:
5043 		port_speed = LPFC_LINK_SPEED_16GHZ;
5044 		break;
5045 	case LPFC_FC_LA_SPEED_32G:
5046 		port_speed = LPFC_LINK_SPEED_32GHZ;
5047 		break;
5048 	case LPFC_FC_LA_SPEED_64G:
5049 		port_speed = LPFC_LINK_SPEED_64GHZ;
5050 		break;
5051 	case LPFC_FC_LA_SPEED_128G:
5052 		port_speed = LPFC_LINK_SPEED_128GHZ;
5053 		break;
5054 	case LPFC_FC_LA_SPEED_256G:
5055 		port_speed = LPFC_LINK_SPEED_256GHZ;
5056 		break;
5057 	default:
5058 		port_speed = 0;
5059 		break;
5060 	}
5061 
5062 	return port_speed;
5063 }
5064 
5065 #define trunk_link_status(__idx)\
5066 	bf_get(lpfc_acqe_fc_la_trunk_config_port##__idx, acqe_fc) ?\
5067 	       ((phba->trunk_link.link##__idx.state == LPFC_LINK_UP) ?\
5068 		"Link up" : "Link down") : "NA"
5069 /* Did port __idx reported an error */
5070 #define trunk_port_fault(__idx)\
5071 	bf_get(lpfc_acqe_fc_la_trunk_config_port##__idx, acqe_fc) ?\
5072 	       (port_fault & (1 << __idx) ? "YES" : "NO") : "NA"
5073 
5074 static void
5075 lpfc_update_trunk_link_status(struct lpfc_hba *phba,
5076 			      struct lpfc_acqe_fc_la *acqe_fc)
5077 {
5078 	uint8_t port_fault = bf_get(lpfc_acqe_fc_la_trunk_linkmask, acqe_fc);
5079 	uint8_t err = bf_get(lpfc_acqe_fc_la_trunk_fault, acqe_fc);
5080 
5081 	phba->sli4_hba.link_state.speed =
5082 		lpfc_sli4_port_speed_parse(phba, LPFC_TRAILER_CODE_FC,
5083 				bf_get(lpfc_acqe_fc_la_speed, acqe_fc));
5084 
5085 	phba->sli4_hba.link_state.logical_speed =
5086 				bf_get(lpfc_acqe_fc_la_llink_spd, acqe_fc) * 10;
5087 	/* We got FC link speed, convert to fc_linkspeed (READ_TOPOLOGY) */
5088 	phba->fc_linkspeed =
5089 		 lpfc_async_link_speed_to_read_top(
5090 				phba,
5091 				bf_get(lpfc_acqe_fc_la_speed, acqe_fc));
5092 
5093 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port0, acqe_fc)) {
5094 		phba->trunk_link.link0.state =
5095 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port0, acqe_fc)
5096 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
5097 		phba->trunk_link.link0.fault = port_fault & 0x1 ? err : 0;
5098 	}
5099 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port1, acqe_fc)) {
5100 		phba->trunk_link.link1.state =
5101 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port1, acqe_fc)
5102 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
5103 		phba->trunk_link.link1.fault = port_fault & 0x2 ? err : 0;
5104 	}
5105 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port2, acqe_fc)) {
5106 		phba->trunk_link.link2.state =
5107 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port2, acqe_fc)
5108 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
5109 		phba->trunk_link.link2.fault = port_fault & 0x4 ? err : 0;
5110 	}
5111 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port3, acqe_fc)) {
5112 		phba->trunk_link.link3.state =
5113 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port3, acqe_fc)
5114 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
5115 		phba->trunk_link.link3.fault = port_fault & 0x8 ? err : 0;
5116 	}
5117 
5118 	lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5119 			"2910 Async FC Trunking Event - Speed:%d\n"
5120 			"\tLogical speed:%d "
5121 			"port0: %s port1: %s port2: %s port3: %s\n",
5122 			phba->sli4_hba.link_state.speed,
5123 			phba->sli4_hba.link_state.logical_speed,
5124 			trunk_link_status(0), trunk_link_status(1),
5125 			trunk_link_status(2), trunk_link_status(3));
5126 
5127 	if (port_fault)
5128 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5129 				"3202 trunk error:0x%x (%s) seen on port0:%s "
5130 				/*
5131 				 * SLI-4: We have only 0xA error codes
5132 				 * defined as of now. print an appropriate
5133 				 * message in case driver needs to be updated.
5134 				 */
5135 				"port1:%s port2:%s port3:%s\n", err, err > 0xA ?
5136 				"UNDEFINED. update driver." : trunk_errmsg[err],
5137 				trunk_port_fault(0), trunk_port_fault(1),
5138 				trunk_port_fault(2), trunk_port_fault(3));
5139 }
5140 
5141 
5142 /**
5143  * lpfc_sli4_async_fc_evt - Process the asynchronous FC link event
5144  * @phba: pointer to lpfc hba data structure.
5145  * @acqe_fc: pointer to the async fc completion queue entry.
5146  *
5147  * This routine is to handle the SLI4 asynchronous FC event. It will simply log
5148  * that the event was received and then issue a read_topology mailbox command so
5149  * that the rest of the driver will treat it the same as SLI3.
5150  **/
5151 static void
5152 lpfc_sli4_async_fc_evt(struct lpfc_hba *phba, struct lpfc_acqe_fc_la *acqe_fc)
5153 {
5154 	struct lpfc_dmabuf *mp;
5155 	LPFC_MBOXQ_t *pmb;
5156 	MAILBOX_t *mb;
5157 	struct lpfc_mbx_read_top *la;
5158 	int rc;
5159 
5160 	if (bf_get(lpfc_trailer_type, acqe_fc) !=
5161 	    LPFC_FC_LA_EVENT_TYPE_FC_LINK) {
5162 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5163 				"2895 Non FC link Event detected.(%d)\n",
5164 				bf_get(lpfc_trailer_type, acqe_fc));
5165 		return;
5166 	}
5167 
5168 	if (bf_get(lpfc_acqe_fc_la_att_type, acqe_fc) ==
5169 	    LPFC_FC_LA_TYPE_TRUNKING_EVENT) {
5170 		lpfc_update_trunk_link_status(phba, acqe_fc);
5171 		return;
5172 	}
5173 
5174 	/* Keep the link status for extra SLI4 state machine reference */
5175 	phba->sli4_hba.link_state.speed =
5176 			lpfc_sli4_port_speed_parse(phba, LPFC_TRAILER_CODE_FC,
5177 				bf_get(lpfc_acqe_fc_la_speed, acqe_fc));
5178 	phba->sli4_hba.link_state.duplex = LPFC_ASYNC_LINK_DUPLEX_FULL;
5179 	phba->sli4_hba.link_state.topology =
5180 				bf_get(lpfc_acqe_fc_la_topology, acqe_fc);
5181 	phba->sli4_hba.link_state.status =
5182 				bf_get(lpfc_acqe_fc_la_att_type, acqe_fc);
5183 	phba->sli4_hba.link_state.type =
5184 				bf_get(lpfc_acqe_fc_la_port_type, acqe_fc);
5185 	phba->sli4_hba.link_state.number =
5186 				bf_get(lpfc_acqe_fc_la_port_number, acqe_fc);
5187 	phba->sli4_hba.link_state.fault =
5188 				bf_get(lpfc_acqe_link_fault, acqe_fc);
5189 
5190 	if (bf_get(lpfc_acqe_fc_la_att_type, acqe_fc) ==
5191 	    LPFC_FC_LA_TYPE_LINK_DOWN)
5192 		phba->sli4_hba.link_state.logical_speed = 0;
5193 	else if	(!phba->sli4_hba.conf_trunk)
5194 		phba->sli4_hba.link_state.logical_speed =
5195 				bf_get(lpfc_acqe_fc_la_llink_spd, acqe_fc) * 10;
5196 
5197 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5198 			"2896 Async FC event - Speed:%dGBaud Topology:x%x "
5199 			"LA Type:x%x Port Type:%d Port Number:%d Logical speed:"
5200 			"%dMbps Fault:%d\n",
5201 			phba->sli4_hba.link_state.speed,
5202 			phba->sli4_hba.link_state.topology,
5203 			phba->sli4_hba.link_state.status,
5204 			phba->sli4_hba.link_state.type,
5205 			phba->sli4_hba.link_state.number,
5206 			phba->sli4_hba.link_state.logical_speed,
5207 			phba->sli4_hba.link_state.fault);
5208 	pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5209 	if (!pmb) {
5210 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5211 				"2897 The mboxq allocation failed\n");
5212 		return;
5213 	}
5214 	mp = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
5215 	if (!mp) {
5216 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5217 				"2898 The lpfc_dmabuf allocation failed\n");
5218 		goto out_free_pmb;
5219 	}
5220 	mp->virt = lpfc_mbuf_alloc(phba, 0, &mp->phys);
5221 	if (!mp->virt) {
5222 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5223 				"2899 The mbuf allocation failed\n");
5224 		goto out_free_dmabuf;
5225 	}
5226 
5227 	/* Cleanup any outstanding ELS commands */
5228 	lpfc_els_flush_all_cmd(phba);
5229 
5230 	/* Block ELS IOCBs until we have done process link event */
5231 	phba->sli4_hba.els_wq->pring->flag |= LPFC_STOP_IOCB_EVENT;
5232 
5233 	/* Update link event statistics */
5234 	phba->sli.slistat.link_event++;
5235 
5236 	/* Create lpfc_handle_latt mailbox command from link ACQE */
5237 	lpfc_read_topology(phba, pmb, mp);
5238 	pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
5239 	pmb->vport = phba->pport;
5240 
5241 	if (phba->sli4_hba.link_state.status != LPFC_FC_LA_TYPE_LINK_UP) {
5242 		phba->link_flag &= ~(LS_MDS_LINK_DOWN | LS_MDS_LOOPBACK);
5243 
5244 		switch (phba->sli4_hba.link_state.status) {
5245 		case LPFC_FC_LA_TYPE_MDS_LINK_DOWN:
5246 			phba->link_flag |= LS_MDS_LINK_DOWN;
5247 			break;
5248 		case LPFC_FC_LA_TYPE_MDS_LOOPBACK:
5249 			phba->link_flag |= LS_MDS_LOOPBACK;
5250 			break;
5251 		default:
5252 			break;
5253 		}
5254 
5255 		/* Initialize completion status */
5256 		mb = &pmb->u.mb;
5257 		mb->mbxStatus = MBX_SUCCESS;
5258 
5259 		/* Parse port fault information field */
5260 		lpfc_sli4_parse_latt_fault(phba, (void *)acqe_fc);
5261 
5262 		/* Parse and translate link attention fields */
5263 		la = (struct lpfc_mbx_read_top *)&pmb->u.mb.un.varReadTop;
5264 		la->eventTag = acqe_fc->event_tag;
5265 
5266 		if (phba->sli4_hba.link_state.status ==
5267 		    LPFC_FC_LA_TYPE_UNEXP_WWPN) {
5268 			bf_set(lpfc_mbx_read_top_att_type, la,
5269 			       LPFC_FC_LA_TYPE_UNEXP_WWPN);
5270 		} else {
5271 			bf_set(lpfc_mbx_read_top_att_type, la,
5272 			       LPFC_FC_LA_TYPE_LINK_DOWN);
5273 		}
5274 		/* Invoke the mailbox command callback function */
5275 		lpfc_mbx_cmpl_read_topology(phba, pmb);
5276 
5277 		return;
5278 	}
5279 
5280 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
5281 	if (rc == MBX_NOT_FINISHED)
5282 		goto out_free_dmabuf;
5283 	return;
5284 
5285 out_free_dmabuf:
5286 	kfree(mp);
5287 out_free_pmb:
5288 	mempool_free(pmb, phba->mbox_mem_pool);
5289 }
5290 
5291 /**
5292  * lpfc_sli4_async_sli_evt - Process the asynchronous SLI link event
5293  * @phba: pointer to lpfc hba data structure.
5294  * @acqe_fc: pointer to the async SLI completion queue entry.
5295  *
5296  * This routine is to handle the SLI4 asynchronous SLI events.
5297  **/
5298 static void
5299 lpfc_sli4_async_sli_evt(struct lpfc_hba *phba, struct lpfc_acqe_sli *acqe_sli)
5300 {
5301 	char port_name;
5302 	char message[128];
5303 	uint8_t status;
5304 	uint8_t evt_type;
5305 	uint8_t operational = 0;
5306 	struct temp_event temp_event_data;
5307 	struct lpfc_acqe_misconfigured_event *misconfigured;
5308 	struct Scsi_Host  *shost;
5309 	struct lpfc_vport **vports;
5310 	int rc, i;
5311 
5312 	evt_type = bf_get(lpfc_trailer_type, acqe_sli);
5313 
5314 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5315 			"2901 Async SLI event - Type:%d, Event Data: x%08x "
5316 			"x%08x x%08x x%08x\n", evt_type,
5317 			acqe_sli->event_data1, acqe_sli->event_data2,
5318 			acqe_sli->reserved, acqe_sli->trailer);
5319 
5320 	port_name = phba->Port[0];
5321 	if (port_name == 0x00)
5322 		port_name = '?'; /* get port name is empty */
5323 
5324 	switch (evt_type) {
5325 	case LPFC_SLI_EVENT_TYPE_OVER_TEMP:
5326 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
5327 		temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
5328 		temp_event_data.data = (uint32_t)acqe_sli->event_data1;
5329 
5330 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5331 				"3190 Over Temperature:%d Celsius- Port Name %c\n",
5332 				acqe_sli->event_data1, port_name);
5333 
5334 		phba->sfp_warning |= LPFC_TRANSGRESSION_HIGH_TEMPERATURE;
5335 		shost = lpfc_shost_from_vport(phba->pport);
5336 		fc_host_post_vendor_event(shost, fc_get_event_number(),
5337 					  sizeof(temp_event_data),
5338 					  (char *)&temp_event_data,
5339 					  SCSI_NL_VID_TYPE_PCI
5340 					  | PCI_VENDOR_ID_EMULEX);
5341 		break;
5342 	case LPFC_SLI_EVENT_TYPE_NORM_TEMP:
5343 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
5344 		temp_event_data.event_code = LPFC_NORMAL_TEMP;
5345 		temp_event_data.data = (uint32_t)acqe_sli->event_data1;
5346 
5347 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5348 				"3191 Normal Temperature:%d Celsius - Port Name %c\n",
5349 				acqe_sli->event_data1, port_name);
5350 
5351 		shost = lpfc_shost_from_vport(phba->pport);
5352 		fc_host_post_vendor_event(shost, fc_get_event_number(),
5353 					  sizeof(temp_event_data),
5354 					  (char *)&temp_event_data,
5355 					  SCSI_NL_VID_TYPE_PCI
5356 					  | PCI_VENDOR_ID_EMULEX);
5357 		break;
5358 	case LPFC_SLI_EVENT_TYPE_MISCONFIGURED:
5359 		misconfigured = (struct lpfc_acqe_misconfigured_event *)
5360 					&acqe_sli->event_data1;
5361 
5362 		/* fetch the status for this port */
5363 		switch (phba->sli4_hba.lnk_info.lnk_no) {
5364 		case LPFC_LINK_NUMBER_0:
5365 			status = bf_get(lpfc_sli_misconfigured_port0_state,
5366 					&misconfigured->theEvent);
5367 			operational = bf_get(lpfc_sli_misconfigured_port0_op,
5368 					&misconfigured->theEvent);
5369 			break;
5370 		case LPFC_LINK_NUMBER_1:
5371 			status = bf_get(lpfc_sli_misconfigured_port1_state,
5372 					&misconfigured->theEvent);
5373 			operational = bf_get(lpfc_sli_misconfigured_port1_op,
5374 					&misconfigured->theEvent);
5375 			break;
5376 		case LPFC_LINK_NUMBER_2:
5377 			status = bf_get(lpfc_sli_misconfigured_port2_state,
5378 					&misconfigured->theEvent);
5379 			operational = bf_get(lpfc_sli_misconfigured_port2_op,
5380 					&misconfigured->theEvent);
5381 			break;
5382 		case LPFC_LINK_NUMBER_3:
5383 			status = bf_get(lpfc_sli_misconfigured_port3_state,
5384 					&misconfigured->theEvent);
5385 			operational = bf_get(lpfc_sli_misconfigured_port3_op,
5386 					&misconfigured->theEvent);
5387 			break;
5388 		default:
5389 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5390 					"3296 "
5391 					"LPFC_SLI_EVENT_TYPE_MISCONFIGURED "
5392 					"event: Invalid link %d",
5393 					phba->sli4_hba.lnk_info.lnk_no);
5394 			return;
5395 		}
5396 
5397 		/* Skip if optic state unchanged */
5398 		if (phba->sli4_hba.lnk_info.optic_state == status)
5399 			return;
5400 
5401 		switch (status) {
5402 		case LPFC_SLI_EVENT_STATUS_VALID:
5403 			sprintf(message, "Physical Link is functional");
5404 			break;
5405 		case LPFC_SLI_EVENT_STATUS_NOT_PRESENT:
5406 			sprintf(message, "Optics faulted/incorrectly "
5407 				"installed/not installed - Reseat optics, "
5408 				"if issue not resolved, replace.");
5409 			break;
5410 		case LPFC_SLI_EVENT_STATUS_WRONG_TYPE:
5411 			sprintf(message,
5412 				"Optics of two types installed - Remove one "
5413 				"optic or install matching pair of optics.");
5414 			break;
5415 		case LPFC_SLI_EVENT_STATUS_UNSUPPORTED:
5416 			sprintf(message, "Incompatible optics - Replace with "
5417 				"compatible optics for card to function.");
5418 			break;
5419 		case LPFC_SLI_EVENT_STATUS_UNQUALIFIED:
5420 			sprintf(message, "Unqualified optics - Replace with "
5421 				"Avago optics for Warranty and Technical "
5422 				"Support - Link is%s operational",
5423 				(operational) ? " not" : "");
5424 			break;
5425 		case LPFC_SLI_EVENT_STATUS_UNCERTIFIED:
5426 			sprintf(message, "Uncertified optics - Replace with "
5427 				"Avago-certified optics to enable link "
5428 				"operation - Link is%s operational",
5429 				(operational) ? " not" : "");
5430 			break;
5431 		default:
5432 			/* firmware is reporting a status we don't know about */
5433 			sprintf(message, "Unknown event status x%02x", status);
5434 			break;
5435 		}
5436 
5437 		/* Issue READ_CONFIG mbox command to refresh supported speeds */
5438 		rc = lpfc_sli4_read_config(phba);
5439 		if (rc) {
5440 			phba->lmt = 0;
5441 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5442 					"3194 Unable to retrieve supported "
5443 					"speeds, rc = 0x%x\n", rc);
5444 		}
5445 		vports = lpfc_create_vport_work_array(phba);
5446 		if (vports != NULL) {
5447 			for (i = 0; i <= phba->max_vports && vports[i] != NULL;
5448 					i++) {
5449 				shost = lpfc_shost_from_vport(vports[i]);
5450 				lpfc_host_supported_speeds_set(shost);
5451 			}
5452 		}
5453 		lpfc_destroy_vport_work_array(phba, vports);
5454 
5455 		phba->sli4_hba.lnk_info.optic_state = status;
5456 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5457 				"3176 Port Name %c %s\n", port_name, message);
5458 		break;
5459 	case LPFC_SLI_EVENT_TYPE_REMOTE_DPORT:
5460 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5461 				"3192 Remote DPort Test Initiated - "
5462 				"Event Data1:x%08x Event Data2: x%08x\n",
5463 				acqe_sli->event_data1, acqe_sli->event_data2);
5464 		break;
5465 	case LPFC_SLI_EVENT_TYPE_MISCONF_FAWWN:
5466 		/* Misconfigured WWN. Reports that the SLI Port is configured
5467 		 * to use FA-WWN, but the attached device doesn’t support it.
5468 		 * No driver action is required.
5469 		 * Event Data1 - N.A, Event Data2 - N.A
5470 		 */
5471 		lpfc_log_msg(phba, KERN_WARNING, LOG_SLI,
5472 			     "2699 Misconfigured FA-WWN - Attached device does "
5473 			     "not support FA-WWN\n");
5474 		break;
5475 	case LPFC_SLI_EVENT_TYPE_EEPROM_FAILURE:
5476 		/* EEPROM failure. No driver action is required */
5477 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5478 			     "2518 EEPROM failure - "
5479 			     "Event Data1: x%08x Event Data2: x%08x\n",
5480 			     acqe_sli->event_data1, acqe_sli->event_data2);
5481 		break;
5482 	default:
5483 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5484 				"3193 Unrecognized SLI event, type: 0x%x",
5485 				evt_type);
5486 		break;
5487 	}
5488 }
5489 
5490 /**
5491  * lpfc_sli4_perform_vport_cvl - Perform clear virtual link on a vport
5492  * @vport: pointer to vport data structure.
5493  *
5494  * This routine is to perform Clear Virtual Link (CVL) on a vport in
5495  * response to a CVL event.
5496  *
5497  * Return the pointer to the ndlp with the vport if successful, otherwise
5498  * return NULL.
5499  **/
5500 static struct lpfc_nodelist *
5501 lpfc_sli4_perform_vport_cvl(struct lpfc_vport *vport)
5502 {
5503 	struct lpfc_nodelist *ndlp;
5504 	struct Scsi_Host *shost;
5505 	struct lpfc_hba *phba;
5506 
5507 	if (!vport)
5508 		return NULL;
5509 	phba = vport->phba;
5510 	if (!phba)
5511 		return NULL;
5512 	ndlp = lpfc_findnode_did(vport, Fabric_DID);
5513 	if (!ndlp) {
5514 		/* Cannot find existing Fabric ndlp, so allocate a new one */
5515 		ndlp = lpfc_nlp_init(vport, Fabric_DID);
5516 		if (!ndlp)
5517 			return 0;
5518 		/* Set the node type */
5519 		ndlp->nlp_type |= NLP_FABRIC;
5520 		/* Put ndlp onto node list */
5521 		lpfc_enqueue_node(vport, ndlp);
5522 	} else if (!NLP_CHK_NODE_ACT(ndlp)) {
5523 		/* re-setup ndlp without removing from node list */
5524 		ndlp = lpfc_enable_node(vport, ndlp, NLP_STE_UNUSED_NODE);
5525 		if (!ndlp)
5526 			return 0;
5527 	}
5528 	if ((phba->pport->port_state < LPFC_FLOGI) &&
5529 		(phba->pport->port_state != LPFC_VPORT_FAILED))
5530 		return NULL;
5531 	/* If virtual link is not yet instantiated ignore CVL */
5532 	if ((vport != phba->pport) && (vport->port_state < LPFC_FDISC)
5533 		&& (vport->port_state != LPFC_VPORT_FAILED))
5534 		return NULL;
5535 	shost = lpfc_shost_from_vport(vport);
5536 	if (!shost)
5537 		return NULL;
5538 	lpfc_linkdown_port(vport);
5539 	lpfc_cleanup_pending_mbox(vport);
5540 	spin_lock_irq(shost->host_lock);
5541 	vport->fc_flag |= FC_VPORT_CVL_RCVD;
5542 	spin_unlock_irq(shost->host_lock);
5543 
5544 	return ndlp;
5545 }
5546 
5547 /**
5548  * lpfc_sli4_perform_all_vport_cvl - Perform clear virtual link on all vports
5549  * @vport: pointer to lpfc hba data structure.
5550  *
5551  * This routine is to perform Clear Virtual Link (CVL) on all vports in
5552  * response to a FCF dead event.
5553  **/
5554 static void
5555 lpfc_sli4_perform_all_vport_cvl(struct lpfc_hba *phba)
5556 {
5557 	struct lpfc_vport **vports;
5558 	int i;
5559 
5560 	vports = lpfc_create_vport_work_array(phba);
5561 	if (vports)
5562 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++)
5563 			lpfc_sli4_perform_vport_cvl(vports[i]);
5564 	lpfc_destroy_vport_work_array(phba, vports);
5565 }
5566 
5567 /**
5568  * lpfc_sli4_async_fip_evt - Process the asynchronous FCoE FIP event
5569  * @phba: pointer to lpfc hba data structure.
5570  * @acqe_link: pointer to the async fcoe completion queue entry.
5571  *
5572  * This routine is to handle the SLI4 asynchronous fcoe event.
5573  **/
5574 static void
5575 lpfc_sli4_async_fip_evt(struct lpfc_hba *phba,
5576 			struct lpfc_acqe_fip *acqe_fip)
5577 {
5578 	uint8_t event_type = bf_get(lpfc_trailer_type, acqe_fip);
5579 	int rc;
5580 	struct lpfc_vport *vport;
5581 	struct lpfc_nodelist *ndlp;
5582 	struct Scsi_Host  *shost;
5583 	int active_vlink_present;
5584 	struct lpfc_vport **vports;
5585 	int i;
5586 
5587 	phba->fc_eventTag = acqe_fip->event_tag;
5588 	phba->fcoe_eventtag = acqe_fip->event_tag;
5589 	switch (event_type) {
5590 	case LPFC_FIP_EVENT_TYPE_NEW_FCF:
5591 	case LPFC_FIP_EVENT_TYPE_FCF_PARAM_MOD:
5592 		if (event_type == LPFC_FIP_EVENT_TYPE_NEW_FCF)
5593 			lpfc_printf_log(phba, KERN_ERR, LOG_FIP |
5594 					LOG_DISCOVERY,
5595 					"2546 New FCF event, evt_tag:x%x, "
5596 					"index:x%x\n",
5597 					acqe_fip->event_tag,
5598 					acqe_fip->index);
5599 		else
5600 			lpfc_printf_log(phba, KERN_WARNING, LOG_FIP |
5601 					LOG_DISCOVERY,
5602 					"2788 FCF param modified event, "
5603 					"evt_tag:x%x, index:x%x\n",
5604 					acqe_fip->event_tag,
5605 					acqe_fip->index);
5606 		if (phba->fcf.fcf_flag & FCF_DISCOVERY) {
5607 			/*
5608 			 * During period of FCF discovery, read the FCF
5609 			 * table record indexed by the event to update
5610 			 * FCF roundrobin failover eligible FCF bmask.
5611 			 */
5612 			lpfc_printf_log(phba, KERN_INFO, LOG_FIP |
5613 					LOG_DISCOVERY,
5614 					"2779 Read FCF (x%x) for updating "
5615 					"roundrobin FCF failover bmask\n",
5616 					acqe_fip->index);
5617 			rc = lpfc_sli4_read_fcf_rec(phba, acqe_fip->index);
5618 		}
5619 
5620 		/* If the FCF discovery is in progress, do nothing. */
5621 		spin_lock_irq(&phba->hbalock);
5622 		if (phba->hba_flag & FCF_TS_INPROG) {
5623 			spin_unlock_irq(&phba->hbalock);
5624 			break;
5625 		}
5626 		/* If fast FCF failover rescan event is pending, do nothing */
5627 		if (phba->fcf.fcf_flag & (FCF_REDISC_EVT | FCF_REDISC_PEND)) {
5628 			spin_unlock_irq(&phba->hbalock);
5629 			break;
5630 		}
5631 
5632 		/* If the FCF has been in discovered state, do nothing. */
5633 		if (phba->fcf.fcf_flag & FCF_SCAN_DONE) {
5634 			spin_unlock_irq(&phba->hbalock);
5635 			break;
5636 		}
5637 		spin_unlock_irq(&phba->hbalock);
5638 
5639 		/* Otherwise, scan the entire FCF table and re-discover SAN */
5640 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
5641 				"2770 Start FCF table scan per async FCF "
5642 				"event, evt_tag:x%x, index:x%x\n",
5643 				acqe_fip->event_tag, acqe_fip->index);
5644 		rc = lpfc_sli4_fcf_scan_read_fcf_rec(phba,
5645 						     LPFC_FCOE_FCF_GET_FIRST);
5646 		if (rc)
5647 			lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_DISCOVERY,
5648 					"2547 Issue FCF scan read FCF mailbox "
5649 					"command failed (x%x)\n", rc);
5650 		break;
5651 
5652 	case LPFC_FIP_EVENT_TYPE_FCF_TABLE_FULL:
5653 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5654 			"2548 FCF Table full count 0x%x tag 0x%x\n",
5655 			bf_get(lpfc_acqe_fip_fcf_count, acqe_fip),
5656 			acqe_fip->event_tag);
5657 		break;
5658 
5659 	case LPFC_FIP_EVENT_TYPE_FCF_DEAD:
5660 		phba->fcoe_cvl_eventtag = acqe_fip->event_tag;
5661 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_DISCOVERY,
5662 			"2549 FCF (x%x) disconnected from network, "
5663 			"tag:x%x\n", acqe_fip->index, acqe_fip->event_tag);
5664 		/*
5665 		 * If we are in the middle of FCF failover process, clear
5666 		 * the corresponding FCF bit in the roundrobin bitmap.
5667 		 */
5668 		spin_lock_irq(&phba->hbalock);
5669 		if ((phba->fcf.fcf_flag & FCF_DISCOVERY) &&
5670 		    (phba->fcf.current_rec.fcf_indx != acqe_fip->index)) {
5671 			spin_unlock_irq(&phba->hbalock);
5672 			/* Update FLOGI FCF failover eligible FCF bmask */
5673 			lpfc_sli4_fcf_rr_index_clear(phba, acqe_fip->index);
5674 			break;
5675 		}
5676 		spin_unlock_irq(&phba->hbalock);
5677 
5678 		/* If the event is not for currently used fcf do nothing */
5679 		if (phba->fcf.current_rec.fcf_indx != acqe_fip->index)
5680 			break;
5681 
5682 		/*
5683 		 * Otherwise, request the port to rediscover the entire FCF
5684 		 * table for a fast recovery from case that the current FCF
5685 		 * is no longer valid as we are not in the middle of FCF
5686 		 * failover process already.
5687 		 */
5688 		spin_lock_irq(&phba->hbalock);
5689 		/* Mark the fast failover process in progress */
5690 		phba->fcf.fcf_flag |= FCF_DEAD_DISC;
5691 		spin_unlock_irq(&phba->hbalock);
5692 
5693 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
5694 				"2771 Start FCF fast failover process due to "
5695 				"FCF DEAD event: evt_tag:x%x, fcf_index:x%x "
5696 				"\n", acqe_fip->event_tag, acqe_fip->index);
5697 		rc = lpfc_sli4_redisc_fcf_table(phba);
5698 		if (rc) {
5699 			lpfc_printf_log(phba, KERN_ERR, LOG_FIP |
5700 					LOG_DISCOVERY,
5701 					"2772 Issue FCF rediscover mailbox "
5702 					"command failed, fail through to FCF "
5703 					"dead event\n");
5704 			spin_lock_irq(&phba->hbalock);
5705 			phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
5706 			spin_unlock_irq(&phba->hbalock);
5707 			/*
5708 			 * Last resort will fail over by treating this
5709 			 * as a link down to FCF registration.
5710 			 */
5711 			lpfc_sli4_fcf_dead_failthrough(phba);
5712 		} else {
5713 			/* Reset FCF roundrobin bmask for new discovery */
5714 			lpfc_sli4_clear_fcf_rr_bmask(phba);
5715 			/*
5716 			 * Handling fast FCF failover to a DEAD FCF event is
5717 			 * considered equalivant to receiving CVL to all vports.
5718 			 */
5719 			lpfc_sli4_perform_all_vport_cvl(phba);
5720 		}
5721 		break;
5722 	case LPFC_FIP_EVENT_TYPE_CVL:
5723 		phba->fcoe_cvl_eventtag = acqe_fip->event_tag;
5724 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_DISCOVERY,
5725 			"2718 Clear Virtual Link Received for VPI 0x%x"
5726 			" tag 0x%x\n", acqe_fip->index, acqe_fip->event_tag);
5727 
5728 		vport = lpfc_find_vport_by_vpid(phba,
5729 						acqe_fip->index);
5730 		ndlp = lpfc_sli4_perform_vport_cvl(vport);
5731 		if (!ndlp)
5732 			break;
5733 		active_vlink_present = 0;
5734 
5735 		vports = lpfc_create_vport_work_array(phba);
5736 		if (vports) {
5737 			for (i = 0; i <= phba->max_vports && vports[i] != NULL;
5738 					i++) {
5739 				if ((!(vports[i]->fc_flag &
5740 					FC_VPORT_CVL_RCVD)) &&
5741 					(vports[i]->port_state > LPFC_FDISC)) {
5742 					active_vlink_present = 1;
5743 					break;
5744 				}
5745 			}
5746 			lpfc_destroy_vport_work_array(phba, vports);
5747 		}
5748 
5749 		/*
5750 		 * Don't re-instantiate if vport is marked for deletion.
5751 		 * If we are here first then vport_delete is going to wait
5752 		 * for discovery to complete.
5753 		 */
5754 		if (!(vport->load_flag & FC_UNLOADING) &&
5755 					active_vlink_present) {
5756 			/*
5757 			 * If there are other active VLinks present,
5758 			 * re-instantiate the Vlink using FDISC.
5759 			 */
5760 			mod_timer(&ndlp->nlp_delayfunc,
5761 				  jiffies + msecs_to_jiffies(1000));
5762 			shost = lpfc_shost_from_vport(vport);
5763 			spin_lock_irq(shost->host_lock);
5764 			ndlp->nlp_flag |= NLP_DELAY_TMO;
5765 			spin_unlock_irq(shost->host_lock);
5766 			ndlp->nlp_last_elscmd = ELS_CMD_FDISC;
5767 			vport->port_state = LPFC_FDISC;
5768 		} else {
5769 			/*
5770 			 * Otherwise, we request port to rediscover
5771 			 * the entire FCF table for a fast recovery
5772 			 * from possible case that the current FCF
5773 			 * is no longer valid if we are not already
5774 			 * in the FCF failover process.
5775 			 */
5776 			spin_lock_irq(&phba->hbalock);
5777 			if (phba->fcf.fcf_flag & FCF_DISCOVERY) {
5778 				spin_unlock_irq(&phba->hbalock);
5779 				break;
5780 			}
5781 			/* Mark the fast failover process in progress */
5782 			phba->fcf.fcf_flag |= FCF_ACVL_DISC;
5783 			spin_unlock_irq(&phba->hbalock);
5784 			lpfc_printf_log(phba, KERN_INFO, LOG_FIP |
5785 					LOG_DISCOVERY,
5786 					"2773 Start FCF failover per CVL, "
5787 					"evt_tag:x%x\n", acqe_fip->event_tag);
5788 			rc = lpfc_sli4_redisc_fcf_table(phba);
5789 			if (rc) {
5790 				lpfc_printf_log(phba, KERN_ERR, LOG_FIP |
5791 						LOG_DISCOVERY,
5792 						"2774 Issue FCF rediscover "
5793 						"mailbox command failed, "
5794 						"through to CVL event\n");
5795 				spin_lock_irq(&phba->hbalock);
5796 				phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
5797 				spin_unlock_irq(&phba->hbalock);
5798 				/*
5799 				 * Last resort will be re-try on the
5800 				 * the current registered FCF entry.
5801 				 */
5802 				lpfc_retry_pport_discovery(phba);
5803 			} else
5804 				/*
5805 				 * Reset FCF roundrobin bmask for new
5806 				 * discovery.
5807 				 */
5808 				lpfc_sli4_clear_fcf_rr_bmask(phba);
5809 		}
5810 		break;
5811 	default:
5812 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5813 			"0288 Unknown FCoE event type 0x%x event tag "
5814 			"0x%x\n", event_type, acqe_fip->event_tag);
5815 		break;
5816 	}
5817 }
5818 
5819 /**
5820  * lpfc_sli4_async_dcbx_evt - Process the asynchronous dcbx event
5821  * @phba: pointer to lpfc hba data structure.
5822  * @acqe_link: pointer to the async dcbx completion queue entry.
5823  *
5824  * This routine is to handle the SLI4 asynchronous dcbx event.
5825  **/
5826 static void
5827 lpfc_sli4_async_dcbx_evt(struct lpfc_hba *phba,
5828 			 struct lpfc_acqe_dcbx *acqe_dcbx)
5829 {
5830 	phba->fc_eventTag = acqe_dcbx->event_tag;
5831 	lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5832 			"0290 The SLI4 DCBX asynchronous event is not "
5833 			"handled yet\n");
5834 }
5835 
5836 /**
5837  * lpfc_sli4_async_grp5_evt - Process the asynchronous group5 event
5838  * @phba: pointer to lpfc hba data structure.
5839  * @acqe_link: pointer to the async grp5 completion queue entry.
5840  *
5841  * This routine is to handle the SLI4 asynchronous grp5 event. A grp5 event
5842  * is an asynchronous notified of a logical link speed change.  The Port
5843  * reports the logical link speed in units of 10Mbps.
5844  **/
5845 static void
5846 lpfc_sli4_async_grp5_evt(struct lpfc_hba *phba,
5847 			 struct lpfc_acqe_grp5 *acqe_grp5)
5848 {
5849 	uint16_t prev_ll_spd;
5850 
5851 	phba->fc_eventTag = acqe_grp5->event_tag;
5852 	phba->fcoe_eventtag = acqe_grp5->event_tag;
5853 	prev_ll_spd = phba->sli4_hba.link_state.logical_speed;
5854 	phba->sli4_hba.link_state.logical_speed =
5855 		(bf_get(lpfc_acqe_grp5_llink_spd, acqe_grp5)) * 10;
5856 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5857 			"2789 GRP5 Async Event: Updating logical link speed "
5858 			"from %dMbps to %dMbps\n", prev_ll_spd,
5859 			phba->sli4_hba.link_state.logical_speed);
5860 }
5861 
5862 /**
5863  * lpfc_sli4_async_event_proc - Process all the pending asynchronous event
5864  * @phba: pointer to lpfc hba data structure.
5865  *
5866  * This routine is invoked by the worker thread to process all the pending
5867  * SLI4 asynchronous events.
5868  **/
5869 void lpfc_sli4_async_event_proc(struct lpfc_hba *phba)
5870 {
5871 	struct lpfc_cq_event *cq_event;
5872 
5873 	/* First, declare the async event has been handled */
5874 	spin_lock_irq(&phba->hbalock);
5875 	phba->hba_flag &= ~ASYNC_EVENT;
5876 	spin_unlock_irq(&phba->hbalock);
5877 	/* Now, handle all the async events */
5878 	while (!list_empty(&phba->sli4_hba.sp_asynce_work_queue)) {
5879 		/* Get the first event from the head of the event queue */
5880 		spin_lock_irq(&phba->hbalock);
5881 		list_remove_head(&phba->sli4_hba.sp_asynce_work_queue,
5882 				 cq_event, struct lpfc_cq_event, list);
5883 		spin_unlock_irq(&phba->hbalock);
5884 		/* Process the asynchronous event */
5885 		switch (bf_get(lpfc_trailer_code, &cq_event->cqe.mcqe_cmpl)) {
5886 		case LPFC_TRAILER_CODE_LINK:
5887 			lpfc_sli4_async_link_evt(phba,
5888 						 &cq_event->cqe.acqe_link);
5889 			break;
5890 		case LPFC_TRAILER_CODE_FCOE:
5891 			lpfc_sli4_async_fip_evt(phba, &cq_event->cqe.acqe_fip);
5892 			break;
5893 		case LPFC_TRAILER_CODE_DCBX:
5894 			lpfc_sli4_async_dcbx_evt(phba,
5895 						 &cq_event->cqe.acqe_dcbx);
5896 			break;
5897 		case LPFC_TRAILER_CODE_GRP5:
5898 			lpfc_sli4_async_grp5_evt(phba,
5899 						 &cq_event->cqe.acqe_grp5);
5900 			break;
5901 		case LPFC_TRAILER_CODE_FC:
5902 			lpfc_sli4_async_fc_evt(phba, &cq_event->cqe.acqe_fc);
5903 			break;
5904 		case LPFC_TRAILER_CODE_SLI:
5905 			lpfc_sli4_async_sli_evt(phba, &cq_event->cqe.acqe_sli);
5906 			break;
5907 		default:
5908 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5909 					"1804 Invalid asynchronous event code: "
5910 					"x%x\n", bf_get(lpfc_trailer_code,
5911 					&cq_event->cqe.mcqe_cmpl));
5912 			break;
5913 		}
5914 		/* Free the completion event processed to the free pool */
5915 		lpfc_sli4_cq_event_release(phba, cq_event);
5916 	}
5917 }
5918 
5919 /**
5920  * lpfc_sli4_fcf_redisc_event_proc - Process fcf table rediscovery event
5921  * @phba: pointer to lpfc hba data structure.
5922  *
5923  * This routine is invoked by the worker thread to process FCF table
5924  * rediscovery pending completion event.
5925  **/
5926 void lpfc_sli4_fcf_redisc_event_proc(struct lpfc_hba *phba)
5927 {
5928 	int rc;
5929 
5930 	spin_lock_irq(&phba->hbalock);
5931 	/* Clear FCF rediscovery timeout event */
5932 	phba->fcf.fcf_flag &= ~FCF_REDISC_EVT;
5933 	/* Clear driver fast failover FCF record flag */
5934 	phba->fcf.failover_rec.flag = 0;
5935 	/* Set state for FCF fast failover */
5936 	phba->fcf.fcf_flag |= FCF_REDISC_FOV;
5937 	spin_unlock_irq(&phba->hbalock);
5938 
5939 	/* Scan FCF table from the first entry to re-discover SAN */
5940 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
5941 			"2777 Start post-quiescent FCF table scan\n");
5942 	rc = lpfc_sli4_fcf_scan_read_fcf_rec(phba, LPFC_FCOE_FCF_GET_FIRST);
5943 	if (rc)
5944 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_DISCOVERY,
5945 				"2747 Issue FCF scan read FCF mailbox "
5946 				"command failed 0x%x\n", rc);
5947 }
5948 
5949 /**
5950  * lpfc_api_table_setup - Set up per hba pci-device group func api jump table
5951  * @phba: pointer to lpfc hba data structure.
5952  * @dev_grp: The HBA PCI-Device group number.
5953  *
5954  * This routine is invoked to set up the per HBA PCI-Device group function
5955  * API jump table entries.
5956  *
5957  * Return: 0 if success, otherwise -ENODEV
5958  **/
5959 int
5960 lpfc_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
5961 {
5962 	int rc;
5963 
5964 	/* Set up lpfc PCI-device group */
5965 	phba->pci_dev_grp = dev_grp;
5966 
5967 	/* The LPFC_PCI_DEV_OC uses SLI4 */
5968 	if (dev_grp == LPFC_PCI_DEV_OC)
5969 		phba->sli_rev = LPFC_SLI_REV4;
5970 
5971 	/* Set up device INIT API function jump table */
5972 	rc = lpfc_init_api_table_setup(phba, dev_grp);
5973 	if (rc)
5974 		return -ENODEV;
5975 	/* Set up SCSI API function jump table */
5976 	rc = lpfc_scsi_api_table_setup(phba, dev_grp);
5977 	if (rc)
5978 		return -ENODEV;
5979 	/* Set up SLI API function jump table */
5980 	rc = lpfc_sli_api_table_setup(phba, dev_grp);
5981 	if (rc)
5982 		return -ENODEV;
5983 	/* Set up MBOX API function jump table */
5984 	rc = lpfc_mbox_api_table_setup(phba, dev_grp);
5985 	if (rc)
5986 		return -ENODEV;
5987 
5988 	return 0;
5989 }
5990 
5991 /**
5992  * lpfc_log_intr_mode - Log the active interrupt mode
5993  * @phba: pointer to lpfc hba data structure.
5994  * @intr_mode: active interrupt mode adopted.
5995  *
5996  * This routine it invoked to log the currently used active interrupt mode
5997  * to the device.
5998  **/
5999 static void lpfc_log_intr_mode(struct lpfc_hba *phba, uint32_t intr_mode)
6000 {
6001 	switch (intr_mode) {
6002 	case 0:
6003 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
6004 				"0470 Enable INTx interrupt mode.\n");
6005 		break;
6006 	case 1:
6007 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
6008 				"0481 Enabled MSI interrupt mode.\n");
6009 		break;
6010 	case 2:
6011 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
6012 				"0480 Enabled MSI-X interrupt mode.\n");
6013 		break;
6014 	default:
6015 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6016 				"0482 Illegal interrupt mode.\n");
6017 		break;
6018 	}
6019 	return;
6020 }
6021 
6022 /**
6023  * lpfc_cpumask_of_node_init - initalizes cpumask of phba's NUMA node
6024  * @phba: Pointer to HBA context object.
6025  *
6026  **/
6027 static void
6028 lpfc_cpumask_of_node_init(struct lpfc_hba *phba)
6029 {
6030 	unsigned int cpu, numa_node;
6031 	struct cpumask *numa_mask = &phba->sli4_hba.numa_mask;
6032 
6033 	cpumask_clear(numa_mask);
6034 
6035 	/* Check if we're a NUMA architecture */
6036 	numa_node = dev_to_node(&phba->pcidev->dev);
6037 	if (numa_node == NUMA_NO_NODE)
6038 		return;
6039 
6040 	for_each_possible_cpu(cpu)
6041 		if (cpu_to_node(cpu) == numa_node)
6042 			cpumask_set_cpu(cpu, numa_mask);
6043 }
6044 
6045 /**
6046  * lpfc_enable_pci_dev - Enable a generic PCI device.
6047  * @phba: pointer to lpfc hba data structure.
6048  *
6049  * This routine is invoked to enable the PCI device that is common to all
6050  * PCI devices.
6051  *
6052  * Return codes
6053  * 	0 - successful
6054  * 	other values - error
6055  **/
6056 static int
6057 lpfc_enable_pci_dev(struct lpfc_hba *phba)
6058 {
6059 	struct pci_dev *pdev;
6060 
6061 	/* Obtain PCI device reference */
6062 	if (!phba->pcidev)
6063 		goto out_error;
6064 	else
6065 		pdev = phba->pcidev;
6066 	/* Enable PCI device */
6067 	if (pci_enable_device_mem(pdev))
6068 		goto out_error;
6069 	/* Request PCI resource for the device */
6070 	if (pci_request_mem_regions(pdev, LPFC_DRIVER_NAME))
6071 		goto out_disable_device;
6072 	/* Set up device as PCI master and save state for EEH */
6073 	pci_set_master(pdev);
6074 	pci_try_set_mwi(pdev);
6075 	pci_save_state(pdev);
6076 
6077 	/* PCIe EEH recovery on powerpc platforms needs fundamental reset */
6078 	if (pci_is_pcie(pdev))
6079 		pdev->needs_freset = 1;
6080 
6081 	return 0;
6082 
6083 out_disable_device:
6084 	pci_disable_device(pdev);
6085 out_error:
6086 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6087 			"1401 Failed to enable pci device\n");
6088 	return -ENODEV;
6089 }
6090 
6091 /**
6092  * lpfc_disable_pci_dev - Disable a generic PCI device.
6093  * @phba: pointer to lpfc hba data structure.
6094  *
6095  * This routine is invoked to disable the PCI device that is common to all
6096  * PCI devices.
6097  **/
6098 static void
6099 lpfc_disable_pci_dev(struct lpfc_hba *phba)
6100 {
6101 	struct pci_dev *pdev;
6102 
6103 	/* Obtain PCI device reference */
6104 	if (!phba->pcidev)
6105 		return;
6106 	else
6107 		pdev = phba->pcidev;
6108 	/* Release PCI resource and disable PCI device */
6109 	pci_release_mem_regions(pdev);
6110 	pci_disable_device(pdev);
6111 
6112 	return;
6113 }
6114 
6115 /**
6116  * lpfc_reset_hba - Reset a hba
6117  * @phba: pointer to lpfc hba data structure.
6118  *
6119  * This routine is invoked to reset a hba device. It brings the HBA
6120  * offline, performs a board restart, and then brings the board back
6121  * online. The lpfc_offline calls lpfc_sli_hba_down which will clean up
6122  * on outstanding mailbox commands.
6123  **/
6124 void
6125 lpfc_reset_hba(struct lpfc_hba *phba)
6126 {
6127 	/* If resets are disabled then set error state and return. */
6128 	if (!phba->cfg_enable_hba_reset) {
6129 		phba->link_state = LPFC_HBA_ERROR;
6130 		return;
6131 	}
6132 	if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
6133 		lpfc_offline_prep(phba, LPFC_MBX_WAIT);
6134 	else
6135 		lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
6136 	lpfc_offline(phba);
6137 	lpfc_sli_brdrestart(phba);
6138 	lpfc_online(phba);
6139 	lpfc_unblock_mgmt_io(phba);
6140 }
6141 
6142 /**
6143  * lpfc_sli_sriov_nr_virtfn_get - Get the number of sr-iov virtual functions
6144  * @phba: pointer to lpfc hba data structure.
6145  *
6146  * This function enables the PCI SR-IOV virtual functions to a physical
6147  * function. It invokes the PCI SR-IOV api with the @nr_vfn provided to
6148  * enable the number of virtual functions to the physical function. As
6149  * not all devices support SR-IOV, the return code from the pci_enable_sriov()
6150  * API call does not considered as an error condition for most of the device.
6151  **/
6152 uint16_t
6153 lpfc_sli_sriov_nr_virtfn_get(struct lpfc_hba *phba)
6154 {
6155 	struct pci_dev *pdev = phba->pcidev;
6156 	uint16_t nr_virtfn;
6157 	int pos;
6158 
6159 	pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_SRIOV);
6160 	if (pos == 0)
6161 		return 0;
6162 
6163 	pci_read_config_word(pdev, pos + PCI_SRIOV_TOTAL_VF, &nr_virtfn);
6164 	return nr_virtfn;
6165 }
6166 
6167 /**
6168  * lpfc_sli_probe_sriov_nr_virtfn - Enable a number of sr-iov virtual functions
6169  * @phba: pointer to lpfc hba data structure.
6170  * @nr_vfn: number of virtual functions to be enabled.
6171  *
6172  * This function enables the PCI SR-IOV virtual functions to a physical
6173  * function. It invokes the PCI SR-IOV api with the @nr_vfn provided to
6174  * enable the number of virtual functions to the physical function. As
6175  * not all devices support SR-IOV, the return code from the pci_enable_sriov()
6176  * API call does not considered as an error condition for most of the device.
6177  **/
6178 int
6179 lpfc_sli_probe_sriov_nr_virtfn(struct lpfc_hba *phba, int nr_vfn)
6180 {
6181 	struct pci_dev *pdev = phba->pcidev;
6182 	uint16_t max_nr_vfn;
6183 	int rc;
6184 
6185 	max_nr_vfn = lpfc_sli_sriov_nr_virtfn_get(phba);
6186 	if (nr_vfn > max_nr_vfn) {
6187 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6188 				"3057 Requested vfs (%d) greater than "
6189 				"supported vfs (%d)", nr_vfn, max_nr_vfn);
6190 		return -EINVAL;
6191 	}
6192 
6193 	rc = pci_enable_sriov(pdev, nr_vfn);
6194 	if (rc) {
6195 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6196 				"2806 Failed to enable sriov on this device "
6197 				"with vfn number nr_vf:%d, rc:%d\n",
6198 				nr_vfn, rc);
6199 	} else
6200 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6201 				"2807 Successful enable sriov on this device "
6202 				"with vfn number nr_vf:%d\n", nr_vfn);
6203 	return rc;
6204 }
6205 
6206 /**
6207  * lpfc_setup_driver_resource_phase1 - Phase1 etup driver internal resources.
6208  * @phba: pointer to lpfc hba data structure.
6209  *
6210  * This routine is invoked to set up the driver internal resources before the
6211  * device specific resource setup to support the HBA device it attached to.
6212  *
6213  * Return codes
6214  *	0 - successful
6215  *	other values - error
6216  **/
6217 static int
6218 lpfc_setup_driver_resource_phase1(struct lpfc_hba *phba)
6219 {
6220 	struct lpfc_sli *psli = &phba->sli;
6221 
6222 	/*
6223 	 * Driver resources common to all SLI revisions
6224 	 */
6225 	atomic_set(&phba->fast_event_count, 0);
6226 	spin_lock_init(&phba->hbalock);
6227 
6228 	/* Initialize ndlp management spinlock */
6229 	spin_lock_init(&phba->ndlp_lock);
6230 
6231 	/* Initialize port_list spinlock */
6232 	spin_lock_init(&phba->port_list_lock);
6233 	INIT_LIST_HEAD(&phba->port_list);
6234 
6235 	INIT_LIST_HEAD(&phba->work_list);
6236 	init_waitqueue_head(&phba->wait_4_mlo_m_q);
6237 
6238 	/* Initialize the wait queue head for the kernel thread */
6239 	init_waitqueue_head(&phba->work_waitq);
6240 
6241 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
6242 			"1403 Protocols supported %s %s %s\n",
6243 			((phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP) ?
6244 				"SCSI" : " "),
6245 			((phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) ?
6246 				"NVME" : " "),
6247 			(phba->nvmet_support ? "NVMET" : " "));
6248 
6249 	/* Initialize the IO buffer list used by driver for SLI3 SCSI */
6250 	spin_lock_init(&phba->scsi_buf_list_get_lock);
6251 	INIT_LIST_HEAD(&phba->lpfc_scsi_buf_list_get);
6252 	spin_lock_init(&phba->scsi_buf_list_put_lock);
6253 	INIT_LIST_HEAD(&phba->lpfc_scsi_buf_list_put);
6254 
6255 	/* Initialize the fabric iocb list */
6256 	INIT_LIST_HEAD(&phba->fabric_iocb_list);
6257 
6258 	/* Initialize list to save ELS buffers */
6259 	INIT_LIST_HEAD(&phba->elsbuf);
6260 
6261 	/* Initialize FCF connection rec list */
6262 	INIT_LIST_HEAD(&phba->fcf_conn_rec_list);
6263 
6264 	/* Initialize OAS configuration list */
6265 	spin_lock_init(&phba->devicelock);
6266 	INIT_LIST_HEAD(&phba->luns);
6267 
6268 	/* MBOX heartbeat timer */
6269 	timer_setup(&psli->mbox_tmo, lpfc_mbox_timeout, 0);
6270 	/* Fabric block timer */
6271 	timer_setup(&phba->fabric_block_timer, lpfc_fabric_block_timeout, 0);
6272 	/* EA polling mode timer */
6273 	timer_setup(&phba->eratt_poll, lpfc_poll_eratt, 0);
6274 	/* Heartbeat timer */
6275 	timer_setup(&phba->hb_tmofunc, lpfc_hb_timeout, 0);
6276 
6277 	INIT_DELAYED_WORK(&phba->eq_delay_work, lpfc_hb_eq_delay_work);
6278 
6279 	return 0;
6280 }
6281 
6282 /**
6283  * lpfc_sli_driver_resource_setup - Setup driver internal resources for SLI3 dev
6284  * @phba: pointer to lpfc hba data structure.
6285  *
6286  * This routine is invoked to set up the driver internal resources specific to
6287  * support the SLI-3 HBA device it attached to.
6288  *
6289  * Return codes
6290  * 0 - successful
6291  * other values - error
6292  **/
6293 static int
6294 lpfc_sli_driver_resource_setup(struct lpfc_hba *phba)
6295 {
6296 	int rc, entry_sz;
6297 
6298 	/*
6299 	 * Initialize timers used by driver
6300 	 */
6301 
6302 	/* FCP polling mode timer */
6303 	timer_setup(&phba->fcp_poll_timer, lpfc_poll_timeout, 0);
6304 
6305 	/* Host attention work mask setup */
6306 	phba->work_ha_mask = (HA_ERATT | HA_MBATT | HA_LATT);
6307 	phba->work_ha_mask |= (HA_RXMASK << (LPFC_ELS_RING * 4));
6308 
6309 	/* Get all the module params for configuring this host */
6310 	lpfc_get_cfgparam(phba);
6311 	/* Set up phase-1 common device driver resources */
6312 
6313 	rc = lpfc_setup_driver_resource_phase1(phba);
6314 	if (rc)
6315 		return -ENODEV;
6316 
6317 	if (phba->pcidev->device == PCI_DEVICE_ID_HORNET) {
6318 		phba->menlo_flag |= HBA_MENLO_SUPPORT;
6319 		/* check for menlo minimum sg count */
6320 		if (phba->cfg_sg_seg_cnt < LPFC_DEFAULT_MENLO_SG_SEG_CNT)
6321 			phba->cfg_sg_seg_cnt = LPFC_DEFAULT_MENLO_SG_SEG_CNT;
6322 	}
6323 
6324 	if (!phba->sli.sli3_ring)
6325 		phba->sli.sli3_ring = kcalloc(LPFC_SLI3_MAX_RING,
6326 					      sizeof(struct lpfc_sli_ring),
6327 					      GFP_KERNEL);
6328 	if (!phba->sli.sli3_ring)
6329 		return -ENOMEM;
6330 
6331 	/*
6332 	 * Since lpfc_sg_seg_cnt is module parameter, the sg_dma_buf_size
6333 	 * used to create the sg_dma_buf_pool must be dynamically calculated.
6334 	 */
6335 
6336 	if (phba->sli_rev == LPFC_SLI_REV4)
6337 		entry_sz = sizeof(struct sli4_sge);
6338 	else
6339 		entry_sz = sizeof(struct ulp_bde64);
6340 
6341 	/* There are going to be 2 reserved BDEs: 1 FCP cmnd + 1 FCP rsp */
6342 	if (phba->cfg_enable_bg) {
6343 		/*
6344 		 * The scsi_buf for a T10-DIF I/O will hold the FCP cmnd,
6345 		 * the FCP rsp, and a BDE for each. Sice we have no control
6346 		 * over how many protection data segments the SCSI Layer
6347 		 * will hand us (ie: there could be one for every block
6348 		 * in the IO), we just allocate enough BDEs to accomidate
6349 		 * our max amount and we need to limit lpfc_sg_seg_cnt to
6350 		 * minimize the risk of running out.
6351 		 */
6352 		phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd) +
6353 			sizeof(struct fcp_rsp) +
6354 			(LPFC_MAX_SG_SEG_CNT * entry_sz);
6355 
6356 		if (phba->cfg_sg_seg_cnt > LPFC_MAX_SG_SEG_CNT_DIF)
6357 			phba->cfg_sg_seg_cnt = LPFC_MAX_SG_SEG_CNT_DIF;
6358 
6359 		/* Total BDEs in BPL for scsi_sg_list and scsi_sg_prot_list */
6360 		phba->cfg_total_seg_cnt = LPFC_MAX_SG_SEG_CNT;
6361 	} else {
6362 		/*
6363 		 * The scsi_buf for a regular I/O will hold the FCP cmnd,
6364 		 * the FCP rsp, a BDE for each, and a BDE for up to
6365 		 * cfg_sg_seg_cnt data segments.
6366 		 */
6367 		phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd) +
6368 			sizeof(struct fcp_rsp) +
6369 			((phba->cfg_sg_seg_cnt + 2) * entry_sz);
6370 
6371 		/* Total BDEs in BPL for scsi_sg_list */
6372 		phba->cfg_total_seg_cnt = phba->cfg_sg_seg_cnt + 2;
6373 	}
6374 
6375 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP,
6376 			"9088 INIT sg_tablesize:%d dmabuf_size:%d total_bde:%d\n",
6377 			phba->cfg_sg_seg_cnt, phba->cfg_sg_dma_buf_size,
6378 			phba->cfg_total_seg_cnt);
6379 
6380 	phba->max_vpi = LPFC_MAX_VPI;
6381 	/* This will be set to correct value after config_port mbox */
6382 	phba->max_vports = 0;
6383 
6384 	/*
6385 	 * Initialize the SLI Layer to run with lpfc HBAs.
6386 	 */
6387 	lpfc_sli_setup(phba);
6388 	lpfc_sli_queue_init(phba);
6389 
6390 	/* Allocate device driver memory */
6391 	if (lpfc_mem_alloc(phba, BPL_ALIGN_SZ))
6392 		return -ENOMEM;
6393 
6394 	phba->lpfc_sg_dma_buf_pool =
6395 		dma_pool_create("lpfc_sg_dma_buf_pool",
6396 				&phba->pcidev->dev, phba->cfg_sg_dma_buf_size,
6397 				BPL_ALIGN_SZ, 0);
6398 
6399 	if (!phba->lpfc_sg_dma_buf_pool)
6400 		goto fail_free_mem;
6401 
6402 	phba->lpfc_cmd_rsp_buf_pool =
6403 			dma_pool_create("lpfc_cmd_rsp_buf_pool",
6404 					&phba->pcidev->dev,
6405 					sizeof(struct fcp_cmnd) +
6406 					sizeof(struct fcp_rsp),
6407 					BPL_ALIGN_SZ, 0);
6408 
6409 	if (!phba->lpfc_cmd_rsp_buf_pool)
6410 		goto fail_free_dma_buf_pool;
6411 
6412 	/*
6413 	 * Enable sr-iov virtual functions if supported and configured
6414 	 * through the module parameter.
6415 	 */
6416 	if (phba->cfg_sriov_nr_virtfn > 0) {
6417 		rc = lpfc_sli_probe_sriov_nr_virtfn(phba,
6418 						 phba->cfg_sriov_nr_virtfn);
6419 		if (rc) {
6420 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6421 					"2808 Requested number of SR-IOV "
6422 					"virtual functions (%d) is not "
6423 					"supported\n",
6424 					phba->cfg_sriov_nr_virtfn);
6425 			phba->cfg_sriov_nr_virtfn = 0;
6426 		}
6427 	}
6428 
6429 	return 0;
6430 
6431 fail_free_dma_buf_pool:
6432 	dma_pool_destroy(phba->lpfc_sg_dma_buf_pool);
6433 	phba->lpfc_sg_dma_buf_pool = NULL;
6434 fail_free_mem:
6435 	lpfc_mem_free(phba);
6436 	return -ENOMEM;
6437 }
6438 
6439 /**
6440  * lpfc_sli_driver_resource_unset - Unset drvr internal resources for SLI3 dev
6441  * @phba: pointer to lpfc hba data structure.
6442  *
6443  * This routine is invoked to unset the driver internal resources set up
6444  * specific for supporting the SLI-3 HBA device it attached to.
6445  **/
6446 static void
6447 lpfc_sli_driver_resource_unset(struct lpfc_hba *phba)
6448 {
6449 	/* Free device driver memory allocated */
6450 	lpfc_mem_free_all(phba);
6451 
6452 	return;
6453 }
6454 
6455 /**
6456  * lpfc_sli4_driver_resource_setup - Setup drvr internal resources for SLI4 dev
6457  * @phba: pointer to lpfc hba data structure.
6458  *
6459  * This routine is invoked to set up the driver internal resources specific to
6460  * support the SLI-4 HBA device it attached to.
6461  *
6462  * Return codes
6463  * 	0 - successful
6464  * 	other values - error
6465  **/
6466 static int
6467 lpfc_sli4_driver_resource_setup(struct lpfc_hba *phba)
6468 {
6469 	LPFC_MBOXQ_t *mboxq;
6470 	MAILBOX_t *mb;
6471 	int rc, i, max_buf_size;
6472 	uint8_t pn_page[LPFC_MAX_SUPPORTED_PAGES] = {0};
6473 	struct lpfc_mqe *mqe;
6474 	int longs;
6475 	int extra;
6476 	uint64_t wwn;
6477 	u32 if_type;
6478 	u32 if_fam;
6479 
6480 	phba->sli4_hba.num_present_cpu = lpfc_present_cpu;
6481 	phba->sli4_hba.num_possible_cpu = cpumask_last(cpu_possible_mask) + 1;
6482 	phba->sli4_hba.curr_disp_cpu = 0;
6483 	lpfc_cpumask_of_node_init(phba);
6484 
6485 	/* Get all the module params for configuring this host */
6486 	lpfc_get_cfgparam(phba);
6487 
6488 	/* Set up phase-1 common device driver resources */
6489 	rc = lpfc_setup_driver_resource_phase1(phba);
6490 	if (rc)
6491 		return -ENODEV;
6492 
6493 	/* Before proceed, wait for POST done and device ready */
6494 	rc = lpfc_sli4_post_status_check(phba);
6495 	if (rc)
6496 		return -ENODEV;
6497 
6498 	/* Allocate all driver workqueues here */
6499 
6500 	/* The lpfc_wq workqueue for deferred irq use */
6501 	phba->wq = alloc_workqueue("lpfc_wq", WQ_MEM_RECLAIM, 0);
6502 
6503 	/*
6504 	 * Initialize timers used by driver
6505 	 */
6506 
6507 	timer_setup(&phba->rrq_tmr, lpfc_rrq_timeout, 0);
6508 
6509 	/* FCF rediscover timer */
6510 	timer_setup(&phba->fcf.redisc_wait, lpfc_sli4_fcf_redisc_wait_tmo, 0);
6511 
6512 	/*
6513 	 * Control structure for handling external multi-buffer mailbox
6514 	 * command pass-through.
6515 	 */
6516 	memset((uint8_t *)&phba->mbox_ext_buf_ctx, 0,
6517 		sizeof(struct lpfc_mbox_ext_buf_ctx));
6518 	INIT_LIST_HEAD(&phba->mbox_ext_buf_ctx.ext_dmabuf_list);
6519 
6520 	phba->max_vpi = LPFC_MAX_VPI;
6521 
6522 	/* This will be set to correct value after the read_config mbox */
6523 	phba->max_vports = 0;
6524 
6525 	/* Program the default value of vlan_id and fc_map */
6526 	phba->valid_vlan = 0;
6527 	phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
6528 	phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
6529 	phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
6530 
6531 	/*
6532 	 * For SLI4, instead of using ring 0 (LPFC_FCP_RING) for FCP commands
6533 	 * we will associate a new ring, for each EQ/CQ/WQ tuple.
6534 	 * The WQ create will allocate the ring.
6535 	 */
6536 
6537 	/* Initialize buffer queue management fields */
6538 	INIT_LIST_HEAD(&phba->hbqs[LPFC_ELS_HBQ].hbq_buffer_list);
6539 	phba->hbqs[LPFC_ELS_HBQ].hbq_alloc_buffer = lpfc_sli4_rb_alloc;
6540 	phba->hbqs[LPFC_ELS_HBQ].hbq_free_buffer = lpfc_sli4_rb_free;
6541 
6542 	/*
6543 	 * Initialize the SLI Layer to run with lpfc SLI4 HBAs.
6544 	 */
6545 	/* Initialize the Abort buffer list used by driver */
6546 	spin_lock_init(&phba->sli4_hba.abts_io_buf_list_lock);
6547 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_io_buf_list);
6548 
6549 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
6550 		/* Initialize the Abort nvme buffer list used by driver */
6551 		spin_lock_init(&phba->sli4_hba.abts_nvmet_buf_list_lock);
6552 		INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
6553 		INIT_LIST_HEAD(&phba->sli4_hba.lpfc_nvmet_io_wait_list);
6554 		spin_lock_init(&phba->sli4_hba.t_active_list_lock);
6555 		INIT_LIST_HEAD(&phba->sli4_hba.t_active_ctx_list);
6556 	}
6557 
6558 	/* This abort list used by worker thread */
6559 	spin_lock_init(&phba->sli4_hba.sgl_list_lock);
6560 	spin_lock_init(&phba->sli4_hba.nvmet_io_wait_lock);
6561 
6562 	/*
6563 	 * Initialize driver internal slow-path work queues
6564 	 */
6565 
6566 	/* Driver internel slow-path CQ Event pool */
6567 	INIT_LIST_HEAD(&phba->sli4_hba.sp_cqe_event_pool);
6568 	/* Response IOCB work queue list */
6569 	INIT_LIST_HEAD(&phba->sli4_hba.sp_queue_event);
6570 	/* Asynchronous event CQ Event work queue list */
6571 	INIT_LIST_HEAD(&phba->sli4_hba.sp_asynce_work_queue);
6572 	/* Fast-path XRI aborted CQ Event work queue list */
6573 	INIT_LIST_HEAD(&phba->sli4_hba.sp_fcp_xri_aborted_work_queue);
6574 	/* Slow-path XRI aborted CQ Event work queue list */
6575 	INIT_LIST_HEAD(&phba->sli4_hba.sp_els_xri_aborted_work_queue);
6576 	/* Receive queue CQ Event work queue list */
6577 	INIT_LIST_HEAD(&phba->sli4_hba.sp_unsol_work_queue);
6578 
6579 	/* Initialize extent block lists. */
6580 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_rpi_blk_list);
6581 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_xri_blk_list);
6582 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_vfi_blk_list);
6583 	INIT_LIST_HEAD(&phba->lpfc_vpi_blk_list);
6584 
6585 	/* Initialize mboxq lists. If the early init routines fail
6586 	 * these lists need to be correctly initialized.
6587 	 */
6588 	INIT_LIST_HEAD(&phba->sli.mboxq);
6589 	INIT_LIST_HEAD(&phba->sli.mboxq_cmpl);
6590 
6591 	/* initialize optic_state to 0xFF */
6592 	phba->sli4_hba.lnk_info.optic_state = 0xff;
6593 
6594 	/* Allocate device driver memory */
6595 	rc = lpfc_mem_alloc(phba, SGL_ALIGN_SZ);
6596 	if (rc)
6597 		return -ENOMEM;
6598 
6599 	/* IF Type 2 ports get initialized now. */
6600 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) >=
6601 	    LPFC_SLI_INTF_IF_TYPE_2) {
6602 		rc = lpfc_pci_function_reset(phba);
6603 		if (unlikely(rc)) {
6604 			rc = -ENODEV;
6605 			goto out_free_mem;
6606 		}
6607 		phba->temp_sensor_support = 1;
6608 	}
6609 
6610 	/* Create the bootstrap mailbox command */
6611 	rc = lpfc_create_bootstrap_mbox(phba);
6612 	if (unlikely(rc))
6613 		goto out_free_mem;
6614 
6615 	/* Set up the host's endian order with the device. */
6616 	rc = lpfc_setup_endian_order(phba);
6617 	if (unlikely(rc))
6618 		goto out_free_bsmbx;
6619 
6620 	/* Set up the hba's configuration parameters. */
6621 	rc = lpfc_sli4_read_config(phba);
6622 	if (unlikely(rc))
6623 		goto out_free_bsmbx;
6624 	rc = lpfc_mem_alloc_active_rrq_pool_s4(phba);
6625 	if (unlikely(rc))
6626 		goto out_free_bsmbx;
6627 
6628 	/* IF Type 0 ports get initialized now. */
6629 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
6630 	    LPFC_SLI_INTF_IF_TYPE_0) {
6631 		rc = lpfc_pci_function_reset(phba);
6632 		if (unlikely(rc))
6633 			goto out_free_bsmbx;
6634 	}
6635 
6636 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
6637 						       GFP_KERNEL);
6638 	if (!mboxq) {
6639 		rc = -ENOMEM;
6640 		goto out_free_bsmbx;
6641 	}
6642 
6643 	/* Check for NVMET being configured */
6644 	phba->nvmet_support = 0;
6645 	if (lpfc_enable_nvmet_cnt) {
6646 
6647 		/* First get WWN of HBA instance */
6648 		lpfc_read_nv(phba, mboxq);
6649 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6650 		if (rc != MBX_SUCCESS) {
6651 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6652 					"6016 Mailbox failed , mbxCmd x%x "
6653 					"READ_NV, mbxStatus x%x\n",
6654 					bf_get(lpfc_mqe_command, &mboxq->u.mqe),
6655 					bf_get(lpfc_mqe_status, &mboxq->u.mqe));
6656 			mempool_free(mboxq, phba->mbox_mem_pool);
6657 			rc = -EIO;
6658 			goto out_free_bsmbx;
6659 		}
6660 		mb = &mboxq->u.mb;
6661 		memcpy(&wwn, (char *)mb->un.varRDnvp.nodename,
6662 		       sizeof(uint64_t));
6663 		wwn = cpu_to_be64(wwn);
6664 		phba->sli4_hba.wwnn.u.name = wwn;
6665 		memcpy(&wwn, (char *)mb->un.varRDnvp.portname,
6666 		       sizeof(uint64_t));
6667 		/* wwn is WWPN of HBA instance */
6668 		wwn = cpu_to_be64(wwn);
6669 		phba->sli4_hba.wwpn.u.name = wwn;
6670 
6671 		/* Check to see if it matches any module parameter */
6672 		for (i = 0; i < lpfc_enable_nvmet_cnt; i++) {
6673 			if (wwn == lpfc_enable_nvmet[i]) {
6674 #if (IS_ENABLED(CONFIG_NVME_TARGET_FC))
6675 				if (lpfc_nvmet_mem_alloc(phba))
6676 					break;
6677 
6678 				phba->nvmet_support = 1; /* a match */
6679 
6680 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6681 						"6017 NVME Target %016llx\n",
6682 						wwn);
6683 #else
6684 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6685 						"6021 Can't enable NVME Target."
6686 						" NVME_TARGET_FC infrastructure"
6687 						" is not in kernel\n");
6688 #endif
6689 				/* Not supported for NVMET */
6690 				phba->cfg_xri_rebalancing = 0;
6691 				break;
6692 			}
6693 		}
6694 	}
6695 
6696 	lpfc_nvme_mod_param_dep(phba);
6697 
6698 	/* Get the Supported Pages if PORT_CAPABILITIES is supported by port. */
6699 	lpfc_supported_pages(mboxq);
6700 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6701 	if (!rc) {
6702 		mqe = &mboxq->u.mqe;
6703 		memcpy(&pn_page[0], ((uint8_t *)&mqe->un.supp_pages.word3),
6704 		       LPFC_MAX_SUPPORTED_PAGES);
6705 		for (i = 0; i < LPFC_MAX_SUPPORTED_PAGES; i++) {
6706 			switch (pn_page[i]) {
6707 			case LPFC_SLI4_PARAMETERS:
6708 				phba->sli4_hba.pc_sli4_params.supported = 1;
6709 				break;
6710 			default:
6711 				break;
6712 			}
6713 		}
6714 		/* Read the port's SLI4 Parameters capabilities if supported. */
6715 		if (phba->sli4_hba.pc_sli4_params.supported)
6716 			rc = lpfc_pc_sli4_params_get(phba, mboxq);
6717 		if (rc) {
6718 			mempool_free(mboxq, phba->mbox_mem_pool);
6719 			rc = -EIO;
6720 			goto out_free_bsmbx;
6721 		}
6722 	}
6723 
6724 	/*
6725 	 * Get sli4 parameters that override parameters from Port capabilities.
6726 	 * If this call fails, it isn't critical unless the SLI4 parameters come
6727 	 * back in conflict.
6728 	 */
6729 	rc = lpfc_get_sli4_parameters(phba, mboxq);
6730 	if (rc) {
6731 		if_type = bf_get(lpfc_sli_intf_if_type,
6732 				 &phba->sli4_hba.sli_intf);
6733 		if_fam = bf_get(lpfc_sli_intf_sli_family,
6734 				&phba->sli4_hba.sli_intf);
6735 		if (phba->sli4_hba.extents_in_use &&
6736 		    phba->sli4_hba.rpi_hdrs_in_use) {
6737 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6738 				"2999 Unsupported SLI4 Parameters "
6739 				"Extents and RPI headers enabled.\n");
6740 			if (if_type == LPFC_SLI_INTF_IF_TYPE_0 &&
6741 			    if_fam ==  LPFC_SLI_INTF_FAMILY_BE2) {
6742 				mempool_free(mboxq, phba->mbox_mem_pool);
6743 				rc = -EIO;
6744 				goto out_free_bsmbx;
6745 			}
6746 		}
6747 		if (!(if_type == LPFC_SLI_INTF_IF_TYPE_0 &&
6748 		      if_fam == LPFC_SLI_INTF_FAMILY_BE2)) {
6749 			mempool_free(mboxq, phba->mbox_mem_pool);
6750 			rc = -EIO;
6751 			goto out_free_bsmbx;
6752 		}
6753 	}
6754 
6755 	/*
6756 	 * 1 for cmd, 1 for rsp, NVME adds an extra one
6757 	 * for boundary conditions in its max_sgl_segment template.
6758 	 */
6759 	extra = 2;
6760 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
6761 		extra++;
6762 
6763 	/*
6764 	 * It doesn't matter what family our adapter is in, we are
6765 	 * limited to 2 Pages, 512 SGEs, for our SGL.
6766 	 * There are going to be 2 reserved SGEs: 1 FCP cmnd + 1 FCP rsp
6767 	 */
6768 	max_buf_size = (2 * SLI4_PAGE_SIZE);
6769 
6770 	/*
6771 	 * Since lpfc_sg_seg_cnt is module param, the sg_dma_buf_size
6772 	 * used to create the sg_dma_buf_pool must be calculated.
6773 	 */
6774 	if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
6775 		/* Both cfg_enable_bg and cfg_external_dif code paths */
6776 
6777 		/*
6778 		 * The scsi_buf for a T10-DIF I/O holds the FCP cmnd,
6779 		 * the FCP rsp, and a SGE. Sice we have no control
6780 		 * over how many protection segments the SCSI Layer
6781 		 * will hand us (ie: there could be one for every block
6782 		 * in the IO), just allocate enough SGEs to accomidate
6783 		 * our max amount and we need to limit lpfc_sg_seg_cnt
6784 		 * to minimize the risk of running out.
6785 		 */
6786 		phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd) +
6787 				sizeof(struct fcp_rsp) + max_buf_size;
6788 
6789 		/* Total SGEs for scsi_sg_list and scsi_sg_prot_list */
6790 		phba->cfg_total_seg_cnt = LPFC_MAX_SGL_SEG_CNT;
6791 
6792 		/*
6793 		 * If supporting DIF, reduce the seg count for scsi to
6794 		 * allow room for the DIF sges.
6795 		 */
6796 		if (phba->cfg_enable_bg &&
6797 		    phba->cfg_sg_seg_cnt > LPFC_MAX_BG_SLI4_SEG_CNT_DIF)
6798 			phba->cfg_scsi_seg_cnt = LPFC_MAX_BG_SLI4_SEG_CNT_DIF;
6799 		else
6800 			phba->cfg_scsi_seg_cnt = phba->cfg_sg_seg_cnt;
6801 
6802 	} else {
6803 		/*
6804 		 * The scsi_buf for a regular I/O holds the FCP cmnd,
6805 		 * the FCP rsp, a SGE for each, and a SGE for up to
6806 		 * cfg_sg_seg_cnt data segments.
6807 		 */
6808 		phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd) +
6809 				sizeof(struct fcp_rsp) +
6810 				((phba->cfg_sg_seg_cnt + extra) *
6811 				sizeof(struct sli4_sge));
6812 
6813 		/* Total SGEs for scsi_sg_list */
6814 		phba->cfg_total_seg_cnt = phba->cfg_sg_seg_cnt + extra;
6815 		phba->cfg_scsi_seg_cnt = phba->cfg_sg_seg_cnt;
6816 
6817 		/*
6818 		 * NOTE: if (phba->cfg_sg_seg_cnt + extra) <= 256 we only
6819 		 * need to post 1 page for the SGL.
6820 		 */
6821 	}
6822 
6823 	if (phba->cfg_xpsgl && !phba->nvmet_support)
6824 		phba->cfg_sg_dma_buf_size = LPFC_DEFAULT_XPSGL_SIZE;
6825 	else if (phba->cfg_sg_dma_buf_size  <= LPFC_MIN_SG_SLI4_BUF_SZ)
6826 		phba->cfg_sg_dma_buf_size = LPFC_MIN_SG_SLI4_BUF_SZ;
6827 	else
6828 		phba->cfg_sg_dma_buf_size =
6829 				SLI4_PAGE_ALIGN(phba->cfg_sg_dma_buf_size);
6830 
6831 	phba->border_sge_num = phba->cfg_sg_dma_buf_size /
6832 			       sizeof(struct sli4_sge);
6833 
6834 	/* Limit to LPFC_MAX_NVME_SEG_CNT for NVME. */
6835 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
6836 		if (phba->cfg_sg_seg_cnt > LPFC_MAX_NVME_SEG_CNT) {
6837 			lpfc_printf_log(phba, KERN_INFO, LOG_NVME | LOG_INIT,
6838 					"6300 Reducing NVME sg segment "
6839 					"cnt to %d\n",
6840 					LPFC_MAX_NVME_SEG_CNT);
6841 			phba->cfg_nvme_seg_cnt = LPFC_MAX_NVME_SEG_CNT;
6842 		} else
6843 			phba->cfg_nvme_seg_cnt = phba->cfg_sg_seg_cnt;
6844 	}
6845 
6846 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP,
6847 			"9087 sg_seg_cnt:%d dmabuf_size:%d "
6848 			"total:%d scsi:%d nvme:%d\n",
6849 			phba->cfg_sg_seg_cnt, phba->cfg_sg_dma_buf_size,
6850 			phba->cfg_total_seg_cnt,  phba->cfg_scsi_seg_cnt,
6851 			phba->cfg_nvme_seg_cnt);
6852 
6853 	if (phba->cfg_sg_dma_buf_size < SLI4_PAGE_SIZE)
6854 		i = phba->cfg_sg_dma_buf_size;
6855 	else
6856 		i = SLI4_PAGE_SIZE;
6857 
6858 	phba->lpfc_sg_dma_buf_pool =
6859 			dma_pool_create("lpfc_sg_dma_buf_pool",
6860 					&phba->pcidev->dev,
6861 					phba->cfg_sg_dma_buf_size,
6862 					i, 0);
6863 	if (!phba->lpfc_sg_dma_buf_pool)
6864 		goto out_free_bsmbx;
6865 
6866 	phba->lpfc_cmd_rsp_buf_pool =
6867 			dma_pool_create("lpfc_cmd_rsp_buf_pool",
6868 					&phba->pcidev->dev,
6869 					sizeof(struct fcp_cmnd) +
6870 					sizeof(struct fcp_rsp),
6871 					i, 0);
6872 	if (!phba->lpfc_cmd_rsp_buf_pool)
6873 		goto out_free_sg_dma_buf;
6874 
6875 	mempool_free(mboxq, phba->mbox_mem_pool);
6876 
6877 	/* Verify OAS is supported */
6878 	lpfc_sli4_oas_verify(phba);
6879 
6880 	/* Verify RAS support on adapter */
6881 	lpfc_sli4_ras_init(phba);
6882 
6883 	/* Verify all the SLI4 queues */
6884 	rc = lpfc_sli4_queue_verify(phba);
6885 	if (rc)
6886 		goto out_free_cmd_rsp_buf;
6887 
6888 	/* Create driver internal CQE event pool */
6889 	rc = lpfc_sli4_cq_event_pool_create(phba);
6890 	if (rc)
6891 		goto out_free_cmd_rsp_buf;
6892 
6893 	/* Initialize sgl lists per host */
6894 	lpfc_init_sgl_list(phba);
6895 
6896 	/* Allocate and initialize active sgl array */
6897 	rc = lpfc_init_active_sgl_array(phba);
6898 	if (rc) {
6899 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6900 				"1430 Failed to initialize sgl list.\n");
6901 		goto out_destroy_cq_event_pool;
6902 	}
6903 	rc = lpfc_sli4_init_rpi_hdrs(phba);
6904 	if (rc) {
6905 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6906 				"1432 Failed to initialize rpi headers.\n");
6907 		goto out_free_active_sgl;
6908 	}
6909 
6910 	/* Allocate eligible FCF bmask memory for FCF roundrobin failover */
6911 	longs = (LPFC_SLI4_FCF_TBL_INDX_MAX + BITS_PER_LONG - 1)/BITS_PER_LONG;
6912 	phba->fcf.fcf_rr_bmask = kcalloc(longs, sizeof(unsigned long),
6913 					 GFP_KERNEL);
6914 	if (!phba->fcf.fcf_rr_bmask) {
6915 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6916 				"2759 Failed allocate memory for FCF round "
6917 				"robin failover bmask\n");
6918 		rc = -ENOMEM;
6919 		goto out_remove_rpi_hdrs;
6920 	}
6921 
6922 	phba->sli4_hba.hba_eq_hdl = kcalloc(phba->cfg_irq_chann,
6923 					    sizeof(struct lpfc_hba_eq_hdl),
6924 					    GFP_KERNEL);
6925 	if (!phba->sli4_hba.hba_eq_hdl) {
6926 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6927 				"2572 Failed allocate memory for "
6928 				"fast-path per-EQ handle array\n");
6929 		rc = -ENOMEM;
6930 		goto out_free_fcf_rr_bmask;
6931 	}
6932 
6933 	phba->sli4_hba.cpu_map = kcalloc(phba->sli4_hba.num_possible_cpu,
6934 					sizeof(struct lpfc_vector_map_info),
6935 					GFP_KERNEL);
6936 	if (!phba->sli4_hba.cpu_map) {
6937 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6938 				"3327 Failed allocate memory for msi-x "
6939 				"interrupt vector mapping\n");
6940 		rc = -ENOMEM;
6941 		goto out_free_hba_eq_hdl;
6942 	}
6943 
6944 	phba->sli4_hba.eq_info = alloc_percpu(struct lpfc_eq_intr_info);
6945 	if (!phba->sli4_hba.eq_info) {
6946 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6947 				"3321 Failed allocation for per_cpu stats\n");
6948 		rc = -ENOMEM;
6949 		goto out_free_hba_cpu_map;
6950 	}
6951 
6952 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
6953 	phba->sli4_hba.c_stat = alloc_percpu(struct lpfc_hdwq_stat);
6954 	if (!phba->sli4_hba.c_stat) {
6955 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6956 				"3332 Failed allocating per cpu hdwq stats\n");
6957 		rc = -ENOMEM;
6958 		goto out_free_hba_eq_info;
6959 	}
6960 #endif
6961 
6962 	/*
6963 	 * Enable sr-iov virtual functions if supported and configured
6964 	 * through the module parameter.
6965 	 */
6966 	if (phba->cfg_sriov_nr_virtfn > 0) {
6967 		rc = lpfc_sli_probe_sriov_nr_virtfn(phba,
6968 						 phba->cfg_sriov_nr_virtfn);
6969 		if (rc) {
6970 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6971 					"3020 Requested number of SR-IOV "
6972 					"virtual functions (%d) is not "
6973 					"supported\n",
6974 					phba->cfg_sriov_nr_virtfn);
6975 			phba->cfg_sriov_nr_virtfn = 0;
6976 		}
6977 	}
6978 
6979 	return 0;
6980 
6981 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
6982 out_free_hba_eq_info:
6983 	free_percpu(phba->sli4_hba.eq_info);
6984 #endif
6985 out_free_hba_cpu_map:
6986 	kfree(phba->sli4_hba.cpu_map);
6987 out_free_hba_eq_hdl:
6988 	kfree(phba->sli4_hba.hba_eq_hdl);
6989 out_free_fcf_rr_bmask:
6990 	kfree(phba->fcf.fcf_rr_bmask);
6991 out_remove_rpi_hdrs:
6992 	lpfc_sli4_remove_rpi_hdrs(phba);
6993 out_free_active_sgl:
6994 	lpfc_free_active_sgl(phba);
6995 out_destroy_cq_event_pool:
6996 	lpfc_sli4_cq_event_pool_destroy(phba);
6997 out_free_cmd_rsp_buf:
6998 	dma_pool_destroy(phba->lpfc_cmd_rsp_buf_pool);
6999 	phba->lpfc_cmd_rsp_buf_pool = NULL;
7000 out_free_sg_dma_buf:
7001 	dma_pool_destroy(phba->lpfc_sg_dma_buf_pool);
7002 	phba->lpfc_sg_dma_buf_pool = NULL;
7003 out_free_bsmbx:
7004 	lpfc_destroy_bootstrap_mbox(phba);
7005 out_free_mem:
7006 	lpfc_mem_free(phba);
7007 	return rc;
7008 }
7009 
7010 /**
7011  * lpfc_sli4_driver_resource_unset - Unset drvr internal resources for SLI4 dev
7012  * @phba: pointer to lpfc hba data structure.
7013  *
7014  * This routine is invoked to unset the driver internal resources set up
7015  * specific for supporting the SLI-4 HBA device it attached to.
7016  **/
7017 static void
7018 lpfc_sli4_driver_resource_unset(struct lpfc_hba *phba)
7019 {
7020 	struct lpfc_fcf_conn_entry *conn_entry, *next_conn_entry;
7021 
7022 	free_percpu(phba->sli4_hba.eq_info);
7023 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
7024 	free_percpu(phba->sli4_hba.c_stat);
7025 #endif
7026 
7027 	/* Free memory allocated for msi-x interrupt vector to CPU mapping */
7028 	kfree(phba->sli4_hba.cpu_map);
7029 	phba->sli4_hba.num_possible_cpu = 0;
7030 	phba->sli4_hba.num_present_cpu = 0;
7031 	phba->sli4_hba.curr_disp_cpu = 0;
7032 	cpumask_clear(&phba->sli4_hba.numa_mask);
7033 
7034 	/* Free memory allocated for fast-path work queue handles */
7035 	kfree(phba->sli4_hba.hba_eq_hdl);
7036 
7037 	/* Free the allocated rpi headers. */
7038 	lpfc_sli4_remove_rpi_hdrs(phba);
7039 	lpfc_sli4_remove_rpis(phba);
7040 
7041 	/* Free eligible FCF index bmask */
7042 	kfree(phba->fcf.fcf_rr_bmask);
7043 
7044 	/* Free the ELS sgl list */
7045 	lpfc_free_active_sgl(phba);
7046 	lpfc_free_els_sgl_list(phba);
7047 	lpfc_free_nvmet_sgl_list(phba);
7048 
7049 	/* Free the completion queue EQ event pool */
7050 	lpfc_sli4_cq_event_release_all(phba);
7051 	lpfc_sli4_cq_event_pool_destroy(phba);
7052 
7053 	/* Release resource identifiers. */
7054 	lpfc_sli4_dealloc_resource_identifiers(phba);
7055 
7056 	/* Free the bsmbx region. */
7057 	lpfc_destroy_bootstrap_mbox(phba);
7058 
7059 	/* Free the SLI Layer memory with SLI4 HBAs */
7060 	lpfc_mem_free_all(phba);
7061 
7062 	/* Free the current connect table */
7063 	list_for_each_entry_safe(conn_entry, next_conn_entry,
7064 		&phba->fcf_conn_rec_list, list) {
7065 		list_del_init(&conn_entry->list);
7066 		kfree(conn_entry);
7067 	}
7068 
7069 	return;
7070 }
7071 
7072 /**
7073  * lpfc_init_api_table_setup - Set up init api function jump table
7074  * @phba: The hba struct for which this call is being executed.
7075  * @dev_grp: The HBA PCI-Device group number.
7076  *
7077  * This routine sets up the device INIT interface API function jump table
7078  * in @phba struct.
7079  *
7080  * Returns: 0 - success, -ENODEV - failure.
7081  **/
7082 int
7083 lpfc_init_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
7084 {
7085 	phba->lpfc_hba_init_link = lpfc_hba_init_link;
7086 	phba->lpfc_hba_down_link = lpfc_hba_down_link;
7087 	phba->lpfc_selective_reset = lpfc_selective_reset;
7088 	switch (dev_grp) {
7089 	case LPFC_PCI_DEV_LP:
7090 		phba->lpfc_hba_down_post = lpfc_hba_down_post_s3;
7091 		phba->lpfc_handle_eratt = lpfc_handle_eratt_s3;
7092 		phba->lpfc_stop_port = lpfc_stop_port_s3;
7093 		break;
7094 	case LPFC_PCI_DEV_OC:
7095 		phba->lpfc_hba_down_post = lpfc_hba_down_post_s4;
7096 		phba->lpfc_handle_eratt = lpfc_handle_eratt_s4;
7097 		phba->lpfc_stop_port = lpfc_stop_port_s4;
7098 		break;
7099 	default:
7100 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7101 				"1431 Invalid HBA PCI-device group: 0x%x\n",
7102 				dev_grp);
7103 		return -ENODEV;
7104 		break;
7105 	}
7106 	return 0;
7107 }
7108 
7109 /**
7110  * lpfc_setup_driver_resource_phase2 - Phase2 setup driver internal resources.
7111  * @phba: pointer to lpfc hba data structure.
7112  *
7113  * This routine is invoked to set up the driver internal resources after the
7114  * device specific resource setup to support the HBA device it attached to.
7115  *
7116  * Return codes
7117  * 	0 - successful
7118  * 	other values - error
7119  **/
7120 static int
7121 lpfc_setup_driver_resource_phase2(struct lpfc_hba *phba)
7122 {
7123 	int error;
7124 
7125 	/* Startup the kernel thread for this host adapter. */
7126 	phba->worker_thread = kthread_run(lpfc_do_work, phba,
7127 					  "lpfc_worker_%d", phba->brd_no);
7128 	if (IS_ERR(phba->worker_thread)) {
7129 		error = PTR_ERR(phba->worker_thread);
7130 		return error;
7131 	}
7132 
7133 	return 0;
7134 }
7135 
7136 /**
7137  * lpfc_unset_driver_resource_phase2 - Phase2 unset driver internal resources.
7138  * @phba: pointer to lpfc hba data structure.
7139  *
7140  * This routine is invoked to unset the driver internal resources set up after
7141  * the device specific resource setup for supporting the HBA device it
7142  * attached to.
7143  **/
7144 static void
7145 lpfc_unset_driver_resource_phase2(struct lpfc_hba *phba)
7146 {
7147 	if (phba->wq) {
7148 		flush_workqueue(phba->wq);
7149 		destroy_workqueue(phba->wq);
7150 		phba->wq = NULL;
7151 	}
7152 
7153 	/* Stop kernel worker thread */
7154 	if (phba->worker_thread)
7155 		kthread_stop(phba->worker_thread);
7156 }
7157 
7158 /**
7159  * lpfc_free_iocb_list - Free iocb list.
7160  * @phba: pointer to lpfc hba data structure.
7161  *
7162  * This routine is invoked to free the driver's IOCB list and memory.
7163  **/
7164 void
7165 lpfc_free_iocb_list(struct lpfc_hba *phba)
7166 {
7167 	struct lpfc_iocbq *iocbq_entry = NULL, *iocbq_next = NULL;
7168 
7169 	spin_lock_irq(&phba->hbalock);
7170 	list_for_each_entry_safe(iocbq_entry, iocbq_next,
7171 				 &phba->lpfc_iocb_list, list) {
7172 		list_del(&iocbq_entry->list);
7173 		kfree(iocbq_entry);
7174 		phba->total_iocbq_bufs--;
7175 	}
7176 	spin_unlock_irq(&phba->hbalock);
7177 
7178 	return;
7179 }
7180 
7181 /**
7182  * lpfc_init_iocb_list - Allocate and initialize iocb list.
7183  * @phba: pointer to lpfc hba data structure.
7184  *
7185  * This routine is invoked to allocate and initizlize the driver's IOCB
7186  * list and set up the IOCB tag array accordingly.
7187  *
7188  * Return codes
7189  *	0 - successful
7190  *	other values - error
7191  **/
7192 int
7193 lpfc_init_iocb_list(struct lpfc_hba *phba, int iocb_count)
7194 {
7195 	struct lpfc_iocbq *iocbq_entry = NULL;
7196 	uint16_t iotag;
7197 	int i;
7198 
7199 	/* Initialize and populate the iocb list per host.  */
7200 	INIT_LIST_HEAD(&phba->lpfc_iocb_list);
7201 	for (i = 0; i < iocb_count; i++) {
7202 		iocbq_entry = kzalloc(sizeof(struct lpfc_iocbq), GFP_KERNEL);
7203 		if (iocbq_entry == NULL) {
7204 			printk(KERN_ERR "%s: only allocated %d iocbs of "
7205 				"expected %d count. Unloading driver.\n",
7206 				__func__, i, iocb_count);
7207 			goto out_free_iocbq;
7208 		}
7209 
7210 		iotag = lpfc_sli_next_iotag(phba, iocbq_entry);
7211 		if (iotag == 0) {
7212 			kfree(iocbq_entry);
7213 			printk(KERN_ERR "%s: failed to allocate IOTAG. "
7214 				"Unloading driver.\n", __func__);
7215 			goto out_free_iocbq;
7216 		}
7217 		iocbq_entry->sli4_lxritag = NO_XRI;
7218 		iocbq_entry->sli4_xritag = NO_XRI;
7219 
7220 		spin_lock_irq(&phba->hbalock);
7221 		list_add(&iocbq_entry->list, &phba->lpfc_iocb_list);
7222 		phba->total_iocbq_bufs++;
7223 		spin_unlock_irq(&phba->hbalock);
7224 	}
7225 
7226 	return 0;
7227 
7228 out_free_iocbq:
7229 	lpfc_free_iocb_list(phba);
7230 
7231 	return -ENOMEM;
7232 }
7233 
7234 /**
7235  * lpfc_free_sgl_list - Free a given sgl list.
7236  * @phba: pointer to lpfc hba data structure.
7237  * @sglq_list: pointer to the head of sgl list.
7238  *
7239  * This routine is invoked to free a give sgl list and memory.
7240  **/
7241 void
7242 lpfc_free_sgl_list(struct lpfc_hba *phba, struct list_head *sglq_list)
7243 {
7244 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
7245 
7246 	list_for_each_entry_safe(sglq_entry, sglq_next, sglq_list, list) {
7247 		list_del(&sglq_entry->list);
7248 		lpfc_mbuf_free(phba, sglq_entry->virt, sglq_entry->phys);
7249 		kfree(sglq_entry);
7250 	}
7251 }
7252 
7253 /**
7254  * lpfc_free_els_sgl_list - Free els sgl list.
7255  * @phba: pointer to lpfc hba data structure.
7256  *
7257  * This routine is invoked to free the driver's els sgl list and memory.
7258  **/
7259 static void
7260 lpfc_free_els_sgl_list(struct lpfc_hba *phba)
7261 {
7262 	LIST_HEAD(sglq_list);
7263 
7264 	/* Retrieve all els sgls from driver list */
7265 	spin_lock_irq(&phba->hbalock);
7266 	spin_lock(&phba->sli4_hba.sgl_list_lock);
7267 	list_splice_init(&phba->sli4_hba.lpfc_els_sgl_list, &sglq_list);
7268 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
7269 	spin_unlock_irq(&phba->hbalock);
7270 
7271 	/* Now free the sgl list */
7272 	lpfc_free_sgl_list(phba, &sglq_list);
7273 }
7274 
7275 /**
7276  * lpfc_free_nvmet_sgl_list - Free nvmet sgl list.
7277  * @phba: pointer to lpfc hba data structure.
7278  *
7279  * This routine is invoked to free the driver's nvmet sgl list and memory.
7280  **/
7281 static void
7282 lpfc_free_nvmet_sgl_list(struct lpfc_hba *phba)
7283 {
7284 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
7285 	LIST_HEAD(sglq_list);
7286 
7287 	/* Retrieve all nvmet sgls from driver list */
7288 	spin_lock_irq(&phba->hbalock);
7289 	spin_lock(&phba->sli4_hba.sgl_list_lock);
7290 	list_splice_init(&phba->sli4_hba.lpfc_nvmet_sgl_list, &sglq_list);
7291 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
7292 	spin_unlock_irq(&phba->hbalock);
7293 
7294 	/* Now free the sgl list */
7295 	list_for_each_entry_safe(sglq_entry, sglq_next, &sglq_list, list) {
7296 		list_del(&sglq_entry->list);
7297 		lpfc_nvmet_buf_free(phba, sglq_entry->virt, sglq_entry->phys);
7298 		kfree(sglq_entry);
7299 	}
7300 
7301 	/* Update the nvmet_xri_cnt to reflect no current sgls.
7302 	 * The next initialization cycle sets the count and allocates
7303 	 * the sgls over again.
7304 	 */
7305 	phba->sli4_hba.nvmet_xri_cnt = 0;
7306 }
7307 
7308 /**
7309  * lpfc_init_active_sgl_array - Allocate the buf to track active ELS XRIs.
7310  * @phba: pointer to lpfc hba data structure.
7311  *
7312  * This routine is invoked to allocate the driver's active sgl memory.
7313  * This array will hold the sglq_entry's for active IOs.
7314  **/
7315 static int
7316 lpfc_init_active_sgl_array(struct lpfc_hba *phba)
7317 {
7318 	int size;
7319 	size = sizeof(struct lpfc_sglq *);
7320 	size *= phba->sli4_hba.max_cfg_param.max_xri;
7321 
7322 	phba->sli4_hba.lpfc_sglq_active_list =
7323 		kzalloc(size, GFP_KERNEL);
7324 	if (!phba->sli4_hba.lpfc_sglq_active_list)
7325 		return -ENOMEM;
7326 	return 0;
7327 }
7328 
7329 /**
7330  * lpfc_free_active_sgl - Free the buf that tracks active ELS XRIs.
7331  * @phba: pointer to lpfc hba data structure.
7332  *
7333  * This routine is invoked to walk through the array of active sglq entries
7334  * and free all of the resources.
7335  * This is just a place holder for now.
7336  **/
7337 static void
7338 lpfc_free_active_sgl(struct lpfc_hba *phba)
7339 {
7340 	kfree(phba->sli4_hba.lpfc_sglq_active_list);
7341 }
7342 
7343 /**
7344  * lpfc_init_sgl_list - Allocate and initialize sgl list.
7345  * @phba: pointer to lpfc hba data structure.
7346  *
7347  * This routine is invoked to allocate and initizlize the driver's sgl
7348  * list and set up the sgl xritag tag array accordingly.
7349  *
7350  **/
7351 static void
7352 lpfc_init_sgl_list(struct lpfc_hba *phba)
7353 {
7354 	/* Initialize and populate the sglq list per host/VF. */
7355 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_els_sgl_list);
7356 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_els_sgl_list);
7357 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_nvmet_sgl_list);
7358 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
7359 
7360 	/* els xri-sgl book keeping */
7361 	phba->sli4_hba.els_xri_cnt = 0;
7362 
7363 	/* nvme xri-buffer book keeping */
7364 	phba->sli4_hba.io_xri_cnt = 0;
7365 }
7366 
7367 /**
7368  * lpfc_sli4_init_rpi_hdrs - Post the rpi header memory region to the port
7369  * @phba: pointer to lpfc hba data structure.
7370  *
7371  * This routine is invoked to post rpi header templates to the
7372  * port for those SLI4 ports that do not support extents.  This routine
7373  * posts a PAGE_SIZE memory region to the port to hold up to
7374  * PAGE_SIZE modulo 64 rpi context headers.  This is an initialization routine
7375  * and should be called only when interrupts are disabled.
7376  *
7377  * Return codes
7378  * 	0 - successful
7379  *	-ERROR - otherwise.
7380  **/
7381 int
7382 lpfc_sli4_init_rpi_hdrs(struct lpfc_hba *phba)
7383 {
7384 	int rc = 0;
7385 	struct lpfc_rpi_hdr *rpi_hdr;
7386 
7387 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_rpi_hdr_list);
7388 	if (!phba->sli4_hba.rpi_hdrs_in_use)
7389 		return rc;
7390 	if (phba->sli4_hba.extents_in_use)
7391 		return -EIO;
7392 
7393 	rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
7394 	if (!rpi_hdr) {
7395 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7396 				"0391 Error during rpi post operation\n");
7397 		lpfc_sli4_remove_rpis(phba);
7398 		rc = -ENODEV;
7399 	}
7400 
7401 	return rc;
7402 }
7403 
7404 /**
7405  * lpfc_sli4_create_rpi_hdr - Allocate an rpi header memory region
7406  * @phba: pointer to lpfc hba data structure.
7407  *
7408  * This routine is invoked to allocate a single 4KB memory region to
7409  * support rpis and stores them in the phba.  This single region
7410  * provides support for up to 64 rpis.  The region is used globally
7411  * by the device.
7412  *
7413  * Returns:
7414  *   A valid rpi hdr on success.
7415  *   A NULL pointer on any failure.
7416  **/
7417 struct lpfc_rpi_hdr *
7418 lpfc_sli4_create_rpi_hdr(struct lpfc_hba *phba)
7419 {
7420 	uint16_t rpi_limit, curr_rpi_range;
7421 	struct lpfc_dmabuf *dmabuf;
7422 	struct lpfc_rpi_hdr *rpi_hdr;
7423 
7424 	/*
7425 	 * If the SLI4 port supports extents, posting the rpi header isn't
7426 	 * required.  Set the expected maximum count and let the actual value
7427 	 * get set when extents are fully allocated.
7428 	 */
7429 	if (!phba->sli4_hba.rpi_hdrs_in_use)
7430 		return NULL;
7431 	if (phba->sli4_hba.extents_in_use)
7432 		return NULL;
7433 
7434 	/* The limit on the logical index is just the max_rpi count. */
7435 	rpi_limit = phba->sli4_hba.max_cfg_param.max_rpi;
7436 
7437 	spin_lock_irq(&phba->hbalock);
7438 	/*
7439 	 * Establish the starting RPI in this header block.  The starting
7440 	 * rpi is normalized to a zero base because the physical rpi is
7441 	 * port based.
7442 	 */
7443 	curr_rpi_range = phba->sli4_hba.next_rpi;
7444 	spin_unlock_irq(&phba->hbalock);
7445 
7446 	/* Reached full RPI range */
7447 	if (curr_rpi_range == rpi_limit)
7448 		return NULL;
7449 
7450 	/*
7451 	 * First allocate the protocol header region for the port.  The
7452 	 * port expects a 4KB DMA-mapped memory region that is 4K aligned.
7453 	 */
7454 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
7455 	if (!dmabuf)
7456 		return NULL;
7457 
7458 	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
7459 					  LPFC_HDR_TEMPLATE_SIZE,
7460 					  &dmabuf->phys, GFP_KERNEL);
7461 	if (!dmabuf->virt) {
7462 		rpi_hdr = NULL;
7463 		goto err_free_dmabuf;
7464 	}
7465 
7466 	if (!IS_ALIGNED(dmabuf->phys, LPFC_HDR_TEMPLATE_SIZE)) {
7467 		rpi_hdr = NULL;
7468 		goto err_free_coherent;
7469 	}
7470 
7471 	/* Save the rpi header data for cleanup later. */
7472 	rpi_hdr = kzalloc(sizeof(struct lpfc_rpi_hdr), GFP_KERNEL);
7473 	if (!rpi_hdr)
7474 		goto err_free_coherent;
7475 
7476 	rpi_hdr->dmabuf = dmabuf;
7477 	rpi_hdr->len = LPFC_HDR_TEMPLATE_SIZE;
7478 	rpi_hdr->page_count = 1;
7479 	spin_lock_irq(&phba->hbalock);
7480 
7481 	/* The rpi_hdr stores the logical index only. */
7482 	rpi_hdr->start_rpi = curr_rpi_range;
7483 	rpi_hdr->next_rpi = phba->sli4_hba.next_rpi + LPFC_RPI_HDR_COUNT;
7484 	list_add_tail(&rpi_hdr->list, &phba->sli4_hba.lpfc_rpi_hdr_list);
7485 
7486 	spin_unlock_irq(&phba->hbalock);
7487 	return rpi_hdr;
7488 
7489  err_free_coherent:
7490 	dma_free_coherent(&phba->pcidev->dev, LPFC_HDR_TEMPLATE_SIZE,
7491 			  dmabuf->virt, dmabuf->phys);
7492  err_free_dmabuf:
7493 	kfree(dmabuf);
7494 	return NULL;
7495 }
7496 
7497 /**
7498  * lpfc_sli4_remove_rpi_hdrs - Remove all rpi header memory regions
7499  * @phba: pointer to lpfc hba data structure.
7500  *
7501  * This routine is invoked to remove all memory resources allocated
7502  * to support rpis for SLI4 ports not supporting extents. This routine
7503  * presumes the caller has released all rpis consumed by fabric or port
7504  * logins and is prepared to have the header pages removed.
7505  **/
7506 void
7507 lpfc_sli4_remove_rpi_hdrs(struct lpfc_hba *phba)
7508 {
7509 	struct lpfc_rpi_hdr *rpi_hdr, *next_rpi_hdr;
7510 
7511 	if (!phba->sli4_hba.rpi_hdrs_in_use)
7512 		goto exit;
7513 
7514 	list_for_each_entry_safe(rpi_hdr, next_rpi_hdr,
7515 				 &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
7516 		list_del(&rpi_hdr->list);
7517 		dma_free_coherent(&phba->pcidev->dev, rpi_hdr->len,
7518 				  rpi_hdr->dmabuf->virt, rpi_hdr->dmabuf->phys);
7519 		kfree(rpi_hdr->dmabuf);
7520 		kfree(rpi_hdr);
7521 	}
7522  exit:
7523 	/* There are no rpis available to the port now. */
7524 	phba->sli4_hba.next_rpi = 0;
7525 }
7526 
7527 /**
7528  * lpfc_hba_alloc - Allocate driver hba data structure for a device.
7529  * @pdev: pointer to pci device data structure.
7530  *
7531  * This routine is invoked to allocate the driver hba data structure for an
7532  * HBA device. If the allocation is successful, the phba reference to the
7533  * PCI device data structure is set.
7534  *
7535  * Return codes
7536  *      pointer to @phba - successful
7537  *      NULL - error
7538  **/
7539 static struct lpfc_hba *
7540 lpfc_hba_alloc(struct pci_dev *pdev)
7541 {
7542 	struct lpfc_hba *phba;
7543 
7544 	/* Allocate memory for HBA structure */
7545 	phba = kzalloc(sizeof(struct lpfc_hba), GFP_KERNEL);
7546 	if (!phba) {
7547 		dev_err(&pdev->dev, "failed to allocate hba struct\n");
7548 		return NULL;
7549 	}
7550 
7551 	/* Set reference to PCI device in HBA structure */
7552 	phba->pcidev = pdev;
7553 
7554 	/* Assign an unused board number */
7555 	phba->brd_no = lpfc_get_instance();
7556 	if (phba->brd_no < 0) {
7557 		kfree(phba);
7558 		return NULL;
7559 	}
7560 	phba->eratt_poll_interval = LPFC_ERATT_POLL_INTERVAL;
7561 
7562 	spin_lock_init(&phba->ct_ev_lock);
7563 	INIT_LIST_HEAD(&phba->ct_ev_waiters);
7564 
7565 	return phba;
7566 }
7567 
7568 /**
7569  * lpfc_hba_free - Free driver hba data structure with a device.
7570  * @phba: pointer to lpfc hba data structure.
7571  *
7572  * This routine is invoked to free the driver hba data structure with an
7573  * HBA device.
7574  **/
7575 static void
7576 lpfc_hba_free(struct lpfc_hba *phba)
7577 {
7578 	if (phba->sli_rev == LPFC_SLI_REV4)
7579 		kfree(phba->sli4_hba.hdwq);
7580 
7581 	/* Release the driver assigned board number */
7582 	idr_remove(&lpfc_hba_index, phba->brd_no);
7583 
7584 	/* Free memory allocated with sli3 rings */
7585 	kfree(phba->sli.sli3_ring);
7586 	phba->sli.sli3_ring = NULL;
7587 
7588 	kfree(phba);
7589 	return;
7590 }
7591 
7592 /**
7593  * lpfc_create_shost - Create hba physical port with associated scsi host.
7594  * @phba: pointer to lpfc hba data structure.
7595  *
7596  * This routine is invoked to create HBA physical port and associate a SCSI
7597  * host with it.
7598  *
7599  * Return codes
7600  *      0 - successful
7601  *      other values - error
7602  **/
7603 static int
7604 lpfc_create_shost(struct lpfc_hba *phba)
7605 {
7606 	struct lpfc_vport *vport;
7607 	struct Scsi_Host  *shost;
7608 
7609 	/* Initialize HBA FC structure */
7610 	phba->fc_edtov = FF_DEF_EDTOV;
7611 	phba->fc_ratov = FF_DEF_RATOV;
7612 	phba->fc_altov = FF_DEF_ALTOV;
7613 	phba->fc_arbtov = FF_DEF_ARBTOV;
7614 
7615 	atomic_set(&phba->sdev_cnt, 0);
7616 	vport = lpfc_create_port(phba, phba->brd_no, &phba->pcidev->dev);
7617 	if (!vport)
7618 		return -ENODEV;
7619 
7620 	shost = lpfc_shost_from_vport(vport);
7621 	phba->pport = vport;
7622 
7623 	if (phba->nvmet_support) {
7624 		/* Only 1 vport (pport) will support NVME target */
7625 		phba->targetport = NULL;
7626 		phba->cfg_enable_fc4_type = LPFC_ENABLE_NVME;
7627 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_NVME_DISC,
7628 				"6076 NVME Target Found\n");
7629 	}
7630 
7631 	lpfc_debugfs_initialize(vport);
7632 	/* Put reference to SCSI host to driver's device private data */
7633 	pci_set_drvdata(phba->pcidev, shost);
7634 
7635 	/*
7636 	 * At this point we are fully registered with PSA. In addition,
7637 	 * any initial discovery should be completed.
7638 	 */
7639 	vport->load_flag |= FC_ALLOW_FDMI;
7640 	if (phba->cfg_enable_SmartSAN ||
7641 	    (phba->cfg_fdmi_on == LPFC_FDMI_SUPPORT)) {
7642 
7643 		/* Setup appropriate attribute masks */
7644 		vport->fdmi_hba_mask = LPFC_FDMI2_HBA_ATTR;
7645 		if (phba->cfg_enable_SmartSAN)
7646 			vport->fdmi_port_mask = LPFC_FDMI2_SMART_ATTR;
7647 		else
7648 			vport->fdmi_port_mask = LPFC_FDMI2_PORT_ATTR;
7649 	}
7650 	return 0;
7651 }
7652 
7653 /**
7654  * lpfc_destroy_shost - Destroy hba physical port with associated scsi host.
7655  * @phba: pointer to lpfc hba data structure.
7656  *
7657  * This routine is invoked to destroy HBA physical port and the associated
7658  * SCSI host.
7659  **/
7660 static void
7661 lpfc_destroy_shost(struct lpfc_hba *phba)
7662 {
7663 	struct lpfc_vport *vport = phba->pport;
7664 
7665 	/* Destroy physical port that associated with the SCSI host */
7666 	destroy_port(vport);
7667 
7668 	return;
7669 }
7670 
7671 /**
7672  * lpfc_setup_bg - Setup Block guard structures and debug areas.
7673  * @phba: pointer to lpfc hba data structure.
7674  * @shost: the shost to be used to detect Block guard settings.
7675  *
7676  * This routine sets up the local Block guard protocol settings for @shost.
7677  * This routine also allocates memory for debugging bg buffers.
7678  **/
7679 static void
7680 lpfc_setup_bg(struct lpfc_hba *phba, struct Scsi_Host *shost)
7681 {
7682 	uint32_t old_mask;
7683 	uint32_t old_guard;
7684 
7685 	if (phba->cfg_prot_mask && phba->cfg_prot_guard) {
7686 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7687 				"1478 Registering BlockGuard with the "
7688 				"SCSI layer\n");
7689 
7690 		old_mask = phba->cfg_prot_mask;
7691 		old_guard = phba->cfg_prot_guard;
7692 
7693 		/* Only allow supported values */
7694 		phba->cfg_prot_mask &= (SHOST_DIF_TYPE1_PROTECTION |
7695 			SHOST_DIX_TYPE0_PROTECTION |
7696 			SHOST_DIX_TYPE1_PROTECTION);
7697 		phba->cfg_prot_guard &= (SHOST_DIX_GUARD_IP |
7698 					 SHOST_DIX_GUARD_CRC);
7699 
7700 		/* DIF Type 1 protection for profiles AST1/C1 is end to end */
7701 		if (phba->cfg_prot_mask == SHOST_DIX_TYPE1_PROTECTION)
7702 			phba->cfg_prot_mask |= SHOST_DIF_TYPE1_PROTECTION;
7703 
7704 		if (phba->cfg_prot_mask && phba->cfg_prot_guard) {
7705 			if ((old_mask != phba->cfg_prot_mask) ||
7706 				(old_guard != phba->cfg_prot_guard))
7707 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7708 					"1475 Registering BlockGuard with the "
7709 					"SCSI layer: mask %d  guard %d\n",
7710 					phba->cfg_prot_mask,
7711 					phba->cfg_prot_guard);
7712 
7713 			scsi_host_set_prot(shost, phba->cfg_prot_mask);
7714 			scsi_host_set_guard(shost, phba->cfg_prot_guard);
7715 		} else
7716 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7717 				"1479 Not Registering BlockGuard with the SCSI "
7718 				"layer, Bad protection parameters: %d %d\n",
7719 				old_mask, old_guard);
7720 	}
7721 }
7722 
7723 /**
7724  * lpfc_post_init_setup - Perform necessary device post initialization setup.
7725  * @phba: pointer to lpfc hba data structure.
7726  *
7727  * This routine is invoked to perform all the necessary post initialization
7728  * setup for the device.
7729  **/
7730 static void
7731 lpfc_post_init_setup(struct lpfc_hba *phba)
7732 {
7733 	struct Scsi_Host  *shost;
7734 	struct lpfc_adapter_event_header adapter_event;
7735 
7736 	/* Get the default values for Model Name and Description */
7737 	lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
7738 
7739 	/*
7740 	 * hba setup may have changed the hba_queue_depth so we need to
7741 	 * adjust the value of can_queue.
7742 	 */
7743 	shost = pci_get_drvdata(phba->pcidev);
7744 	shost->can_queue = phba->cfg_hba_queue_depth - 10;
7745 
7746 	lpfc_host_attrib_init(shost);
7747 
7748 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
7749 		spin_lock_irq(shost->host_lock);
7750 		lpfc_poll_start_timer(phba);
7751 		spin_unlock_irq(shost->host_lock);
7752 	}
7753 
7754 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7755 			"0428 Perform SCSI scan\n");
7756 	/* Send board arrival event to upper layer */
7757 	adapter_event.event_type = FC_REG_ADAPTER_EVENT;
7758 	adapter_event.subcategory = LPFC_EVENT_ARRIVAL;
7759 	fc_host_post_vendor_event(shost, fc_get_event_number(),
7760 				  sizeof(adapter_event),
7761 				  (char *) &adapter_event,
7762 				  LPFC_NL_VENDOR_ID);
7763 	return;
7764 }
7765 
7766 /**
7767  * lpfc_sli_pci_mem_setup - Setup SLI3 HBA PCI memory space.
7768  * @phba: pointer to lpfc hba data structure.
7769  *
7770  * This routine is invoked to set up the PCI device memory space for device
7771  * with SLI-3 interface spec.
7772  *
7773  * Return codes
7774  * 	0 - successful
7775  * 	other values - error
7776  **/
7777 static int
7778 lpfc_sli_pci_mem_setup(struct lpfc_hba *phba)
7779 {
7780 	struct pci_dev *pdev = phba->pcidev;
7781 	unsigned long bar0map_len, bar2map_len;
7782 	int i, hbq_count;
7783 	void *ptr;
7784 	int error;
7785 
7786 	if (!pdev)
7787 		return -ENODEV;
7788 
7789 	/* Set the device DMA mask size */
7790 	error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
7791 	if (error)
7792 		error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32));
7793 	if (error)
7794 		return error;
7795 	error = -ENODEV;
7796 
7797 	/* Get the bus address of Bar0 and Bar2 and the number of bytes
7798 	 * required by each mapping.
7799 	 */
7800 	phba->pci_bar0_map = pci_resource_start(pdev, 0);
7801 	bar0map_len = pci_resource_len(pdev, 0);
7802 
7803 	phba->pci_bar2_map = pci_resource_start(pdev, 2);
7804 	bar2map_len = pci_resource_len(pdev, 2);
7805 
7806 	/* Map HBA SLIM to a kernel virtual address. */
7807 	phba->slim_memmap_p = ioremap(phba->pci_bar0_map, bar0map_len);
7808 	if (!phba->slim_memmap_p) {
7809 		dev_printk(KERN_ERR, &pdev->dev,
7810 			   "ioremap failed for SLIM memory.\n");
7811 		goto out;
7812 	}
7813 
7814 	/* Map HBA Control Registers to a kernel virtual address. */
7815 	phba->ctrl_regs_memmap_p = ioremap(phba->pci_bar2_map, bar2map_len);
7816 	if (!phba->ctrl_regs_memmap_p) {
7817 		dev_printk(KERN_ERR, &pdev->dev,
7818 			   "ioremap failed for HBA control registers.\n");
7819 		goto out_iounmap_slim;
7820 	}
7821 
7822 	/* Allocate memory for SLI-2 structures */
7823 	phba->slim2p.virt = dma_alloc_coherent(&pdev->dev, SLI2_SLIM_SIZE,
7824 					       &phba->slim2p.phys, GFP_KERNEL);
7825 	if (!phba->slim2p.virt)
7826 		goto out_iounmap;
7827 
7828 	phba->mbox = phba->slim2p.virt + offsetof(struct lpfc_sli2_slim, mbx);
7829 	phba->mbox_ext = (phba->slim2p.virt +
7830 		offsetof(struct lpfc_sli2_slim, mbx_ext_words));
7831 	phba->pcb = (phba->slim2p.virt + offsetof(struct lpfc_sli2_slim, pcb));
7832 	phba->IOCBs = (phba->slim2p.virt +
7833 		       offsetof(struct lpfc_sli2_slim, IOCBs));
7834 
7835 	phba->hbqslimp.virt = dma_alloc_coherent(&pdev->dev,
7836 						 lpfc_sli_hbq_size(),
7837 						 &phba->hbqslimp.phys,
7838 						 GFP_KERNEL);
7839 	if (!phba->hbqslimp.virt)
7840 		goto out_free_slim;
7841 
7842 	hbq_count = lpfc_sli_hbq_count();
7843 	ptr = phba->hbqslimp.virt;
7844 	for (i = 0; i < hbq_count; ++i) {
7845 		phba->hbqs[i].hbq_virt = ptr;
7846 		INIT_LIST_HEAD(&phba->hbqs[i].hbq_buffer_list);
7847 		ptr += (lpfc_hbq_defs[i]->entry_count *
7848 			sizeof(struct lpfc_hbq_entry));
7849 	}
7850 	phba->hbqs[LPFC_ELS_HBQ].hbq_alloc_buffer = lpfc_els_hbq_alloc;
7851 	phba->hbqs[LPFC_ELS_HBQ].hbq_free_buffer = lpfc_els_hbq_free;
7852 
7853 	memset(phba->hbqslimp.virt, 0, lpfc_sli_hbq_size());
7854 
7855 	phba->MBslimaddr = phba->slim_memmap_p;
7856 	phba->HAregaddr = phba->ctrl_regs_memmap_p + HA_REG_OFFSET;
7857 	phba->CAregaddr = phba->ctrl_regs_memmap_p + CA_REG_OFFSET;
7858 	phba->HSregaddr = phba->ctrl_regs_memmap_p + HS_REG_OFFSET;
7859 	phba->HCregaddr = phba->ctrl_regs_memmap_p + HC_REG_OFFSET;
7860 
7861 	return 0;
7862 
7863 out_free_slim:
7864 	dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
7865 			  phba->slim2p.virt, phba->slim2p.phys);
7866 out_iounmap:
7867 	iounmap(phba->ctrl_regs_memmap_p);
7868 out_iounmap_slim:
7869 	iounmap(phba->slim_memmap_p);
7870 out:
7871 	return error;
7872 }
7873 
7874 /**
7875  * lpfc_sli_pci_mem_unset - Unset SLI3 HBA PCI memory space.
7876  * @phba: pointer to lpfc hba data structure.
7877  *
7878  * This routine is invoked to unset the PCI device memory space for device
7879  * with SLI-3 interface spec.
7880  **/
7881 static void
7882 lpfc_sli_pci_mem_unset(struct lpfc_hba *phba)
7883 {
7884 	struct pci_dev *pdev;
7885 
7886 	/* Obtain PCI device reference */
7887 	if (!phba->pcidev)
7888 		return;
7889 	else
7890 		pdev = phba->pcidev;
7891 
7892 	/* Free coherent DMA memory allocated */
7893 	dma_free_coherent(&pdev->dev, lpfc_sli_hbq_size(),
7894 			  phba->hbqslimp.virt, phba->hbqslimp.phys);
7895 	dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
7896 			  phba->slim2p.virt, phba->slim2p.phys);
7897 
7898 	/* I/O memory unmap */
7899 	iounmap(phba->ctrl_regs_memmap_p);
7900 	iounmap(phba->slim_memmap_p);
7901 
7902 	return;
7903 }
7904 
7905 /**
7906  * lpfc_sli4_post_status_check - Wait for SLI4 POST done and check status
7907  * @phba: pointer to lpfc hba data structure.
7908  *
7909  * This routine is invoked to wait for SLI4 device Power On Self Test (POST)
7910  * done and check status.
7911  *
7912  * Return 0 if successful, otherwise -ENODEV.
7913  **/
7914 int
7915 lpfc_sli4_post_status_check(struct lpfc_hba *phba)
7916 {
7917 	struct lpfc_register portsmphr_reg, uerrlo_reg, uerrhi_reg;
7918 	struct lpfc_register reg_data;
7919 	int i, port_error = 0;
7920 	uint32_t if_type;
7921 
7922 	memset(&portsmphr_reg, 0, sizeof(portsmphr_reg));
7923 	memset(&reg_data, 0, sizeof(reg_data));
7924 	if (!phba->sli4_hba.PSMPHRregaddr)
7925 		return -ENODEV;
7926 
7927 	/* Wait up to 30 seconds for the SLI Port POST done and ready */
7928 	for (i = 0; i < 3000; i++) {
7929 		if (lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
7930 			&portsmphr_reg.word0) ||
7931 			(bf_get(lpfc_port_smphr_perr, &portsmphr_reg))) {
7932 			/* Port has a fatal POST error, break out */
7933 			port_error = -ENODEV;
7934 			break;
7935 		}
7936 		if (LPFC_POST_STAGE_PORT_READY ==
7937 		    bf_get(lpfc_port_smphr_port_status, &portsmphr_reg))
7938 			break;
7939 		msleep(10);
7940 	}
7941 
7942 	/*
7943 	 * If there was a port error during POST, then don't proceed with
7944 	 * other register reads as the data may not be valid.  Just exit.
7945 	 */
7946 	if (port_error) {
7947 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7948 			"1408 Port Failed POST - portsmphr=0x%x, "
7949 			"perr=x%x, sfi=x%x, nip=x%x, ipc=x%x, scr1=x%x, "
7950 			"scr2=x%x, hscratch=x%x, pstatus=x%x\n",
7951 			portsmphr_reg.word0,
7952 			bf_get(lpfc_port_smphr_perr, &portsmphr_reg),
7953 			bf_get(lpfc_port_smphr_sfi, &portsmphr_reg),
7954 			bf_get(lpfc_port_smphr_nip, &portsmphr_reg),
7955 			bf_get(lpfc_port_smphr_ipc, &portsmphr_reg),
7956 			bf_get(lpfc_port_smphr_scr1, &portsmphr_reg),
7957 			bf_get(lpfc_port_smphr_scr2, &portsmphr_reg),
7958 			bf_get(lpfc_port_smphr_host_scratch, &portsmphr_reg),
7959 			bf_get(lpfc_port_smphr_port_status, &portsmphr_reg));
7960 	} else {
7961 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7962 				"2534 Device Info: SLIFamily=0x%x, "
7963 				"SLIRev=0x%x, IFType=0x%x, SLIHint_1=0x%x, "
7964 				"SLIHint_2=0x%x, FT=0x%x\n",
7965 				bf_get(lpfc_sli_intf_sli_family,
7966 				       &phba->sli4_hba.sli_intf),
7967 				bf_get(lpfc_sli_intf_slirev,
7968 				       &phba->sli4_hba.sli_intf),
7969 				bf_get(lpfc_sli_intf_if_type,
7970 				       &phba->sli4_hba.sli_intf),
7971 				bf_get(lpfc_sli_intf_sli_hint1,
7972 				       &phba->sli4_hba.sli_intf),
7973 				bf_get(lpfc_sli_intf_sli_hint2,
7974 				       &phba->sli4_hba.sli_intf),
7975 				bf_get(lpfc_sli_intf_func_type,
7976 				       &phba->sli4_hba.sli_intf));
7977 		/*
7978 		 * Check for other Port errors during the initialization
7979 		 * process.  Fail the load if the port did not come up
7980 		 * correctly.
7981 		 */
7982 		if_type = bf_get(lpfc_sli_intf_if_type,
7983 				 &phba->sli4_hba.sli_intf);
7984 		switch (if_type) {
7985 		case LPFC_SLI_INTF_IF_TYPE_0:
7986 			phba->sli4_hba.ue_mask_lo =
7987 			      readl(phba->sli4_hba.u.if_type0.UEMASKLOregaddr);
7988 			phba->sli4_hba.ue_mask_hi =
7989 			      readl(phba->sli4_hba.u.if_type0.UEMASKHIregaddr);
7990 			uerrlo_reg.word0 =
7991 			      readl(phba->sli4_hba.u.if_type0.UERRLOregaddr);
7992 			uerrhi_reg.word0 =
7993 				readl(phba->sli4_hba.u.if_type0.UERRHIregaddr);
7994 			if ((~phba->sli4_hba.ue_mask_lo & uerrlo_reg.word0) ||
7995 			    (~phba->sli4_hba.ue_mask_hi & uerrhi_reg.word0)) {
7996 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7997 						"1422 Unrecoverable Error "
7998 						"Detected during POST "
7999 						"uerr_lo_reg=0x%x, "
8000 						"uerr_hi_reg=0x%x, "
8001 						"ue_mask_lo_reg=0x%x, "
8002 						"ue_mask_hi_reg=0x%x\n",
8003 						uerrlo_reg.word0,
8004 						uerrhi_reg.word0,
8005 						phba->sli4_hba.ue_mask_lo,
8006 						phba->sli4_hba.ue_mask_hi);
8007 				port_error = -ENODEV;
8008 			}
8009 			break;
8010 		case LPFC_SLI_INTF_IF_TYPE_2:
8011 		case LPFC_SLI_INTF_IF_TYPE_6:
8012 			/* Final checks.  The port status should be clean. */
8013 			if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
8014 				&reg_data.word0) ||
8015 				(bf_get(lpfc_sliport_status_err, &reg_data) &&
8016 				 !bf_get(lpfc_sliport_status_rn, &reg_data))) {
8017 				phba->work_status[0] =
8018 					readl(phba->sli4_hba.u.if_type2.
8019 					      ERR1regaddr);
8020 				phba->work_status[1] =
8021 					readl(phba->sli4_hba.u.if_type2.
8022 					      ERR2regaddr);
8023 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8024 					"2888 Unrecoverable port error "
8025 					"following POST: port status reg "
8026 					"0x%x, port_smphr reg 0x%x, "
8027 					"error 1=0x%x, error 2=0x%x\n",
8028 					reg_data.word0,
8029 					portsmphr_reg.word0,
8030 					phba->work_status[0],
8031 					phba->work_status[1]);
8032 				port_error = -ENODEV;
8033 			}
8034 			break;
8035 		case LPFC_SLI_INTF_IF_TYPE_1:
8036 		default:
8037 			break;
8038 		}
8039 	}
8040 	return port_error;
8041 }
8042 
8043 /**
8044  * lpfc_sli4_bar0_register_memmap - Set up SLI4 BAR0 register memory map.
8045  * @phba: pointer to lpfc hba data structure.
8046  * @if_type:  The SLI4 interface type getting configured.
8047  *
8048  * This routine is invoked to set up SLI4 BAR0 PCI config space register
8049  * memory map.
8050  **/
8051 static void
8052 lpfc_sli4_bar0_register_memmap(struct lpfc_hba *phba, uint32_t if_type)
8053 {
8054 	switch (if_type) {
8055 	case LPFC_SLI_INTF_IF_TYPE_0:
8056 		phba->sli4_hba.u.if_type0.UERRLOregaddr =
8057 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UERR_STATUS_LO;
8058 		phba->sli4_hba.u.if_type0.UERRHIregaddr =
8059 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UERR_STATUS_HI;
8060 		phba->sli4_hba.u.if_type0.UEMASKLOregaddr =
8061 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UE_MASK_LO;
8062 		phba->sli4_hba.u.if_type0.UEMASKHIregaddr =
8063 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UE_MASK_HI;
8064 		phba->sli4_hba.SLIINTFregaddr =
8065 			phba->sli4_hba.conf_regs_memmap_p + LPFC_SLI_INTF;
8066 		break;
8067 	case LPFC_SLI_INTF_IF_TYPE_2:
8068 		phba->sli4_hba.u.if_type2.EQDregaddr =
8069 			phba->sli4_hba.conf_regs_memmap_p +
8070 						LPFC_CTL_PORT_EQ_DELAY_OFFSET;
8071 		phba->sli4_hba.u.if_type2.ERR1regaddr =
8072 			phba->sli4_hba.conf_regs_memmap_p +
8073 						LPFC_CTL_PORT_ER1_OFFSET;
8074 		phba->sli4_hba.u.if_type2.ERR2regaddr =
8075 			phba->sli4_hba.conf_regs_memmap_p +
8076 						LPFC_CTL_PORT_ER2_OFFSET;
8077 		phba->sli4_hba.u.if_type2.CTRLregaddr =
8078 			phba->sli4_hba.conf_regs_memmap_p +
8079 						LPFC_CTL_PORT_CTL_OFFSET;
8080 		phba->sli4_hba.u.if_type2.STATUSregaddr =
8081 			phba->sli4_hba.conf_regs_memmap_p +
8082 						LPFC_CTL_PORT_STA_OFFSET;
8083 		phba->sli4_hba.SLIINTFregaddr =
8084 			phba->sli4_hba.conf_regs_memmap_p + LPFC_SLI_INTF;
8085 		phba->sli4_hba.PSMPHRregaddr =
8086 			phba->sli4_hba.conf_regs_memmap_p +
8087 						LPFC_CTL_PORT_SEM_OFFSET;
8088 		phba->sli4_hba.RQDBregaddr =
8089 			phba->sli4_hba.conf_regs_memmap_p +
8090 						LPFC_ULP0_RQ_DOORBELL;
8091 		phba->sli4_hba.WQDBregaddr =
8092 			phba->sli4_hba.conf_regs_memmap_p +
8093 						LPFC_ULP0_WQ_DOORBELL;
8094 		phba->sli4_hba.CQDBregaddr =
8095 			phba->sli4_hba.conf_regs_memmap_p + LPFC_EQCQ_DOORBELL;
8096 		phba->sli4_hba.EQDBregaddr = phba->sli4_hba.CQDBregaddr;
8097 		phba->sli4_hba.MQDBregaddr =
8098 			phba->sli4_hba.conf_regs_memmap_p + LPFC_MQ_DOORBELL;
8099 		phba->sli4_hba.BMBXregaddr =
8100 			phba->sli4_hba.conf_regs_memmap_p + LPFC_BMBX;
8101 		break;
8102 	case LPFC_SLI_INTF_IF_TYPE_6:
8103 		phba->sli4_hba.u.if_type2.EQDregaddr =
8104 			phba->sli4_hba.conf_regs_memmap_p +
8105 						LPFC_CTL_PORT_EQ_DELAY_OFFSET;
8106 		phba->sli4_hba.u.if_type2.ERR1regaddr =
8107 			phba->sli4_hba.conf_regs_memmap_p +
8108 						LPFC_CTL_PORT_ER1_OFFSET;
8109 		phba->sli4_hba.u.if_type2.ERR2regaddr =
8110 			phba->sli4_hba.conf_regs_memmap_p +
8111 						LPFC_CTL_PORT_ER2_OFFSET;
8112 		phba->sli4_hba.u.if_type2.CTRLregaddr =
8113 			phba->sli4_hba.conf_regs_memmap_p +
8114 						LPFC_CTL_PORT_CTL_OFFSET;
8115 		phba->sli4_hba.u.if_type2.STATUSregaddr =
8116 			phba->sli4_hba.conf_regs_memmap_p +
8117 						LPFC_CTL_PORT_STA_OFFSET;
8118 		phba->sli4_hba.PSMPHRregaddr =
8119 			phba->sli4_hba.conf_regs_memmap_p +
8120 						LPFC_CTL_PORT_SEM_OFFSET;
8121 		phba->sli4_hba.BMBXregaddr =
8122 			phba->sli4_hba.conf_regs_memmap_p + LPFC_BMBX;
8123 		break;
8124 	case LPFC_SLI_INTF_IF_TYPE_1:
8125 	default:
8126 		dev_printk(KERN_ERR, &phba->pcidev->dev,
8127 			   "FATAL - unsupported SLI4 interface type - %d\n",
8128 			   if_type);
8129 		break;
8130 	}
8131 }
8132 
8133 /**
8134  * lpfc_sli4_bar1_register_memmap - Set up SLI4 BAR1 register memory map.
8135  * @phba: pointer to lpfc hba data structure.
8136  *
8137  * This routine is invoked to set up SLI4 BAR1 register memory map.
8138  **/
8139 static void
8140 lpfc_sli4_bar1_register_memmap(struct lpfc_hba *phba, uint32_t if_type)
8141 {
8142 	switch (if_type) {
8143 	case LPFC_SLI_INTF_IF_TYPE_0:
8144 		phba->sli4_hba.PSMPHRregaddr =
8145 			phba->sli4_hba.ctrl_regs_memmap_p +
8146 			LPFC_SLIPORT_IF0_SMPHR;
8147 		phba->sli4_hba.ISRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
8148 			LPFC_HST_ISR0;
8149 		phba->sli4_hba.IMRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
8150 			LPFC_HST_IMR0;
8151 		phba->sli4_hba.ISCRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
8152 			LPFC_HST_ISCR0;
8153 		break;
8154 	case LPFC_SLI_INTF_IF_TYPE_6:
8155 		phba->sli4_hba.RQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
8156 			LPFC_IF6_RQ_DOORBELL;
8157 		phba->sli4_hba.WQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
8158 			LPFC_IF6_WQ_DOORBELL;
8159 		phba->sli4_hba.CQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
8160 			LPFC_IF6_CQ_DOORBELL;
8161 		phba->sli4_hba.EQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
8162 			LPFC_IF6_EQ_DOORBELL;
8163 		phba->sli4_hba.MQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
8164 			LPFC_IF6_MQ_DOORBELL;
8165 		break;
8166 	case LPFC_SLI_INTF_IF_TYPE_2:
8167 	case LPFC_SLI_INTF_IF_TYPE_1:
8168 	default:
8169 		dev_err(&phba->pcidev->dev,
8170 			   "FATAL - unsupported SLI4 interface type - %d\n",
8171 			   if_type);
8172 		break;
8173 	}
8174 }
8175 
8176 /**
8177  * lpfc_sli4_bar2_register_memmap - Set up SLI4 BAR2 register memory map.
8178  * @phba: pointer to lpfc hba data structure.
8179  * @vf: virtual function number
8180  *
8181  * This routine is invoked to set up SLI4 BAR2 doorbell register memory map
8182  * based on the given viftual function number, @vf.
8183  *
8184  * Return 0 if successful, otherwise -ENODEV.
8185  **/
8186 static int
8187 lpfc_sli4_bar2_register_memmap(struct lpfc_hba *phba, uint32_t vf)
8188 {
8189 	if (vf > LPFC_VIR_FUNC_MAX)
8190 		return -ENODEV;
8191 
8192 	phba->sli4_hba.RQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
8193 				vf * LPFC_VFR_PAGE_SIZE +
8194 					LPFC_ULP0_RQ_DOORBELL);
8195 	phba->sli4_hba.WQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
8196 				vf * LPFC_VFR_PAGE_SIZE +
8197 					LPFC_ULP0_WQ_DOORBELL);
8198 	phba->sli4_hba.CQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
8199 				vf * LPFC_VFR_PAGE_SIZE +
8200 					LPFC_EQCQ_DOORBELL);
8201 	phba->sli4_hba.EQDBregaddr = phba->sli4_hba.CQDBregaddr;
8202 	phba->sli4_hba.MQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
8203 				vf * LPFC_VFR_PAGE_SIZE + LPFC_MQ_DOORBELL);
8204 	phba->sli4_hba.BMBXregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
8205 				vf * LPFC_VFR_PAGE_SIZE + LPFC_BMBX);
8206 	return 0;
8207 }
8208 
8209 /**
8210  * lpfc_create_bootstrap_mbox - Create the bootstrap mailbox
8211  * @phba: pointer to lpfc hba data structure.
8212  *
8213  * This routine is invoked to create the bootstrap mailbox
8214  * region consistent with the SLI-4 interface spec.  This
8215  * routine allocates all memory necessary to communicate
8216  * mailbox commands to the port and sets up all alignment
8217  * needs.  No locks are expected to be held when calling
8218  * this routine.
8219  *
8220  * Return codes
8221  * 	0 - successful
8222  * 	-ENOMEM - could not allocated memory.
8223  **/
8224 static int
8225 lpfc_create_bootstrap_mbox(struct lpfc_hba *phba)
8226 {
8227 	uint32_t bmbx_size;
8228 	struct lpfc_dmabuf *dmabuf;
8229 	struct dma_address *dma_address;
8230 	uint32_t pa_addr;
8231 	uint64_t phys_addr;
8232 
8233 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
8234 	if (!dmabuf)
8235 		return -ENOMEM;
8236 
8237 	/*
8238 	 * The bootstrap mailbox region is comprised of 2 parts
8239 	 * plus an alignment restriction of 16 bytes.
8240 	 */
8241 	bmbx_size = sizeof(struct lpfc_bmbx_create) + (LPFC_ALIGN_16_BYTE - 1);
8242 	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev, bmbx_size,
8243 					  &dmabuf->phys, GFP_KERNEL);
8244 	if (!dmabuf->virt) {
8245 		kfree(dmabuf);
8246 		return -ENOMEM;
8247 	}
8248 
8249 	/*
8250 	 * Initialize the bootstrap mailbox pointers now so that the register
8251 	 * operations are simple later.  The mailbox dma address is required
8252 	 * to be 16-byte aligned.  Also align the virtual memory as each
8253 	 * maibox is copied into the bmbx mailbox region before issuing the
8254 	 * command to the port.
8255 	 */
8256 	phba->sli4_hba.bmbx.dmabuf = dmabuf;
8257 	phba->sli4_hba.bmbx.bmbx_size = bmbx_size;
8258 
8259 	phba->sli4_hba.bmbx.avirt = PTR_ALIGN(dmabuf->virt,
8260 					      LPFC_ALIGN_16_BYTE);
8261 	phba->sli4_hba.bmbx.aphys = ALIGN(dmabuf->phys,
8262 					      LPFC_ALIGN_16_BYTE);
8263 
8264 	/*
8265 	 * Set the high and low physical addresses now.  The SLI4 alignment
8266 	 * requirement is 16 bytes and the mailbox is posted to the port
8267 	 * as two 30-bit addresses.  The other data is a bit marking whether
8268 	 * the 30-bit address is the high or low address.
8269 	 * Upcast bmbx aphys to 64bits so shift instruction compiles
8270 	 * clean on 32 bit machines.
8271 	 */
8272 	dma_address = &phba->sli4_hba.bmbx.dma_address;
8273 	phys_addr = (uint64_t)phba->sli4_hba.bmbx.aphys;
8274 	pa_addr = (uint32_t) ((phys_addr >> 34) & 0x3fffffff);
8275 	dma_address->addr_hi = (uint32_t) ((pa_addr << 2) |
8276 					   LPFC_BMBX_BIT1_ADDR_HI);
8277 
8278 	pa_addr = (uint32_t) ((phba->sli4_hba.bmbx.aphys >> 4) & 0x3fffffff);
8279 	dma_address->addr_lo = (uint32_t) ((pa_addr << 2) |
8280 					   LPFC_BMBX_BIT1_ADDR_LO);
8281 	return 0;
8282 }
8283 
8284 /**
8285  * lpfc_destroy_bootstrap_mbox - Destroy all bootstrap mailbox resources
8286  * @phba: pointer to lpfc hba data structure.
8287  *
8288  * This routine is invoked to teardown the bootstrap mailbox
8289  * region and release all host resources. This routine requires
8290  * the caller to ensure all mailbox commands recovered, no
8291  * additional mailbox comands are sent, and interrupts are disabled
8292  * before calling this routine.
8293  *
8294  **/
8295 static void
8296 lpfc_destroy_bootstrap_mbox(struct lpfc_hba *phba)
8297 {
8298 	dma_free_coherent(&phba->pcidev->dev,
8299 			  phba->sli4_hba.bmbx.bmbx_size,
8300 			  phba->sli4_hba.bmbx.dmabuf->virt,
8301 			  phba->sli4_hba.bmbx.dmabuf->phys);
8302 
8303 	kfree(phba->sli4_hba.bmbx.dmabuf);
8304 	memset(&phba->sli4_hba.bmbx, 0, sizeof(struct lpfc_bmbx));
8305 }
8306 
8307 static const char * const lpfc_topo_to_str[] = {
8308 	"Loop then P2P",
8309 	"Loopback",
8310 	"P2P Only",
8311 	"Unsupported",
8312 	"Loop Only",
8313 	"Unsupported",
8314 	"P2P then Loop",
8315 };
8316 
8317 /**
8318  * lpfc_map_topology - Map the topology read from READ_CONFIG
8319  * @phba: pointer to lpfc hba data structure.
8320  * @rdconf: pointer to read config data
8321  *
8322  * This routine is invoked to map the topology values as read
8323  * from the read config mailbox command. If the persistent
8324  * topology feature is supported, the firmware will provide the
8325  * saved topology information to be used in INIT_LINK
8326  *
8327  **/
8328 #define	LINK_FLAGS_DEF	0x0
8329 #define	LINK_FLAGS_P2P	0x1
8330 #define	LINK_FLAGS_LOOP	0x2
8331 static void
8332 lpfc_map_topology(struct lpfc_hba *phba, struct lpfc_mbx_read_config *rd_config)
8333 {
8334 	u8 ptv, tf, pt;
8335 
8336 	ptv = bf_get(lpfc_mbx_rd_conf_ptv, rd_config);
8337 	tf = bf_get(lpfc_mbx_rd_conf_tf, rd_config);
8338 	pt = bf_get(lpfc_mbx_rd_conf_pt, rd_config);
8339 
8340 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
8341 			"2027 Read Config Data : ptv:0x%x, tf:0x%x pt:0x%x",
8342 			 ptv, tf, pt);
8343 	if (!ptv) {
8344 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
8345 				"2019 FW does not support persistent topology "
8346 				"Using driver parameter defined value [%s]",
8347 				lpfc_topo_to_str[phba->cfg_topology]);
8348 		return;
8349 	}
8350 	/* FW supports persistent topology - override module parameter value */
8351 	phba->hba_flag |= HBA_PERSISTENT_TOPO;
8352 	switch (phba->pcidev->device) {
8353 	case PCI_DEVICE_ID_LANCER_G7_FC:
8354 	case PCI_DEVICE_ID_LANCER_G6_FC:
8355 		if (!tf) {
8356 			phba->cfg_topology = ((pt == LINK_FLAGS_LOOP)
8357 					? FLAGS_TOPOLOGY_MODE_LOOP
8358 					: FLAGS_TOPOLOGY_MODE_PT_PT);
8359 		} else {
8360 			phba->hba_flag &= ~HBA_PERSISTENT_TOPO;
8361 		}
8362 		break;
8363 	default:	/* G5 */
8364 		if (tf) {
8365 			/* If topology failover set - pt is '0' or '1' */
8366 			phba->cfg_topology = (pt ? FLAGS_TOPOLOGY_MODE_PT_LOOP :
8367 					      FLAGS_TOPOLOGY_MODE_LOOP_PT);
8368 		} else {
8369 			phba->cfg_topology = ((pt == LINK_FLAGS_P2P)
8370 					? FLAGS_TOPOLOGY_MODE_PT_PT
8371 					: FLAGS_TOPOLOGY_MODE_LOOP);
8372 		}
8373 		break;
8374 	}
8375 	if (phba->hba_flag & HBA_PERSISTENT_TOPO) {
8376 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
8377 				"2020 Using persistent topology value [%s]",
8378 				lpfc_topo_to_str[phba->cfg_topology]);
8379 	} else {
8380 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
8381 				"2021 Invalid topology values from FW "
8382 				"Using driver parameter defined value [%s]",
8383 				lpfc_topo_to_str[phba->cfg_topology]);
8384 	}
8385 }
8386 
8387 /**
8388  * lpfc_sli4_read_config - Get the config parameters.
8389  * @phba: pointer to lpfc hba data structure.
8390  *
8391  * This routine is invoked to read the configuration parameters from the HBA.
8392  * The configuration parameters are used to set the base and maximum values
8393  * for RPI's XRI's VPI's VFI's and FCFIs. These values also affect the resource
8394  * allocation for the port.
8395  *
8396  * Return codes
8397  * 	0 - successful
8398  * 	-ENOMEM - No available memory
8399  *      -EIO - The mailbox failed to complete successfully.
8400  **/
8401 int
8402 lpfc_sli4_read_config(struct lpfc_hba *phba)
8403 {
8404 	LPFC_MBOXQ_t *pmb;
8405 	struct lpfc_mbx_read_config *rd_config;
8406 	union  lpfc_sli4_cfg_shdr *shdr;
8407 	uint32_t shdr_status, shdr_add_status;
8408 	struct lpfc_mbx_get_func_cfg *get_func_cfg;
8409 	struct lpfc_rsrc_desc_fcfcoe *desc;
8410 	char *pdesc_0;
8411 	uint16_t forced_link_speed;
8412 	uint32_t if_type, qmin;
8413 	int length, i, rc = 0, rc2;
8414 
8415 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
8416 	if (!pmb) {
8417 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8418 				"2011 Unable to allocate memory for issuing "
8419 				"SLI_CONFIG_SPECIAL mailbox command\n");
8420 		return -ENOMEM;
8421 	}
8422 
8423 	lpfc_read_config(phba, pmb);
8424 
8425 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
8426 	if (rc != MBX_SUCCESS) {
8427 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8428 			"2012 Mailbox failed , mbxCmd x%x "
8429 			"READ_CONFIG, mbxStatus x%x\n",
8430 			bf_get(lpfc_mqe_command, &pmb->u.mqe),
8431 			bf_get(lpfc_mqe_status, &pmb->u.mqe));
8432 		rc = -EIO;
8433 	} else {
8434 		rd_config = &pmb->u.mqe.un.rd_config;
8435 		if (bf_get(lpfc_mbx_rd_conf_lnk_ldv, rd_config)) {
8436 			phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL;
8437 			phba->sli4_hba.lnk_info.lnk_tp =
8438 				bf_get(lpfc_mbx_rd_conf_lnk_type, rd_config);
8439 			phba->sli4_hba.lnk_info.lnk_no =
8440 				bf_get(lpfc_mbx_rd_conf_lnk_numb, rd_config);
8441 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
8442 					"3081 lnk_type:%d, lnk_numb:%d\n",
8443 					phba->sli4_hba.lnk_info.lnk_tp,
8444 					phba->sli4_hba.lnk_info.lnk_no);
8445 		} else
8446 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
8447 					"3082 Mailbox (x%x) returned ldv:x0\n",
8448 					bf_get(lpfc_mqe_command, &pmb->u.mqe));
8449 		if (bf_get(lpfc_mbx_rd_conf_bbscn_def, rd_config)) {
8450 			phba->bbcredit_support = 1;
8451 			phba->sli4_hba.bbscn_params.word0 = rd_config->word8;
8452 		}
8453 
8454 		phba->sli4_hba.conf_trunk =
8455 			bf_get(lpfc_mbx_rd_conf_trunk, rd_config);
8456 		phba->sli4_hba.extents_in_use =
8457 			bf_get(lpfc_mbx_rd_conf_extnts_inuse, rd_config);
8458 		phba->sli4_hba.max_cfg_param.max_xri =
8459 			bf_get(lpfc_mbx_rd_conf_xri_count, rd_config);
8460 		/* Reduce resource usage in kdump environment */
8461 		if (is_kdump_kernel() &&
8462 		    phba->sli4_hba.max_cfg_param.max_xri > 512)
8463 			phba->sli4_hba.max_cfg_param.max_xri = 512;
8464 		phba->sli4_hba.max_cfg_param.xri_base =
8465 			bf_get(lpfc_mbx_rd_conf_xri_base, rd_config);
8466 		phba->sli4_hba.max_cfg_param.max_vpi =
8467 			bf_get(lpfc_mbx_rd_conf_vpi_count, rd_config);
8468 		/* Limit the max we support */
8469 		if (phba->sli4_hba.max_cfg_param.max_vpi > LPFC_MAX_VPORTS)
8470 			phba->sli4_hba.max_cfg_param.max_vpi = LPFC_MAX_VPORTS;
8471 		phba->sli4_hba.max_cfg_param.vpi_base =
8472 			bf_get(lpfc_mbx_rd_conf_vpi_base, rd_config);
8473 		phba->sli4_hba.max_cfg_param.max_rpi =
8474 			bf_get(lpfc_mbx_rd_conf_rpi_count, rd_config);
8475 		phba->sli4_hba.max_cfg_param.rpi_base =
8476 			bf_get(lpfc_mbx_rd_conf_rpi_base, rd_config);
8477 		phba->sli4_hba.max_cfg_param.max_vfi =
8478 			bf_get(lpfc_mbx_rd_conf_vfi_count, rd_config);
8479 		phba->sli4_hba.max_cfg_param.vfi_base =
8480 			bf_get(lpfc_mbx_rd_conf_vfi_base, rd_config);
8481 		phba->sli4_hba.max_cfg_param.max_fcfi =
8482 			bf_get(lpfc_mbx_rd_conf_fcfi_count, rd_config);
8483 		phba->sli4_hba.max_cfg_param.max_eq =
8484 			bf_get(lpfc_mbx_rd_conf_eq_count, rd_config);
8485 		phba->sli4_hba.max_cfg_param.max_rq =
8486 			bf_get(lpfc_mbx_rd_conf_rq_count, rd_config);
8487 		phba->sli4_hba.max_cfg_param.max_wq =
8488 			bf_get(lpfc_mbx_rd_conf_wq_count, rd_config);
8489 		phba->sli4_hba.max_cfg_param.max_cq =
8490 			bf_get(lpfc_mbx_rd_conf_cq_count, rd_config);
8491 		phba->lmt = bf_get(lpfc_mbx_rd_conf_lmt, rd_config);
8492 		phba->sli4_hba.next_xri = phba->sli4_hba.max_cfg_param.xri_base;
8493 		phba->vpi_base = phba->sli4_hba.max_cfg_param.vpi_base;
8494 		phba->vfi_base = phba->sli4_hba.max_cfg_param.vfi_base;
8495 		phba->max_vpi = (phba->sli4_hba.max_cfg_param.max_vpi > 0) ?
8496 				(phba->sli4_hba.max_cfg_param.max_vpi - 1) : 0;
8497 		phba->max_vports = phba->max_vpi;
8498 		lpfc_map_topology(phba, rd_config);
8499 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
8500 				"2003 cfg params Extents? %d "
8501 				"XRI(B:%d M:%d), "
8502 				"VPI(B:%d M:%d) "
8503 				"VFI(B:%d M:%d) "
8504 				"RPI(B:%d M:%d) "
8505 				"FCFI:%d EQ:%d CQ:%d WQ:%d RQ:%d\n",
8506 				phba->sli4_hba.extents_in_use,
8507 				phba->sli4_hba.max_cfg_param.xri_base,
8508 				phba->sli4_hba.max_cfg_param.max_xri,
8509 				phba->sli4_hba.max_cfg_param.vpi_base,
8510 				phba->sli4_hba.max_cfg_param.max_vpi,
8511 				phba->sli4_hba.max_cfg_param.vfi_base,
8512 				phba->sli4_hba.max_cfg_param.max_vfi,
8513 				phba->sli4_hba.max_cfg_param.rpi_base,
8514 				phba->sli4_hba.max_cfg_param.max_rpi,
8515 				phba->sli4_hba.max_cfg_param.max_fcfi,
8516 				phba->sli4_hba.max_cfg_param.max_eq,
8517 				phba->sli4_hba.max_cfg_param.max_cq,
8518 				phba->sli4_hba.max_cfg_param.max_wq,
8519 				phba->sli4_hba.max_cfg_param.max_rq);
8520 
8521 		/*
8522 		 * Calculate queue resources based on how
8523 		 * many WQ/CQ/EQs are available.
8524 		 */
8525 		qmin = phba->sli4_hba.max_cfg_param.max_wq;
8526 		if (phba->sli4_hba.max_cfg_param.max_cq < qmin)
8527 			qmin = phba->sli4_hba.max_cfg_param.max_cq;
8528 		if (phba->sli4_hba.max_cfg_param.max_eq < qmin)
8529 			qmin = phba->sli4_hba.max_cfg_param.max_eq;
8530 		/*
8531 		 * Whats left after this can go toward NVME / FCP.
8532 		 * The minus 4 accounts for ELS, NVME LS, MBOX
8533 		 * plus one extra. When configured for
8534 		 * NVMET, FCP io channel WQs are not created.
8535 		 */
8536 		qmin -= 4;
8537 
8538 		/* Check to see if there is enough for NVME */
8539 		if ((phba->cfg_irq_chann > qmin) ||
8540 		    (phba->cfg_hdw_queue > qmin)) {
8541 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8542 					"2005 Reducing Queues: "
8543 					"WQ %d CQ %d EQ %d: min %d: "
8544 					"IRQ %d HDWQ %d\n",
8545 					phba->sli4_hba.max_cfg_param.max_wq,
8546 					phba->sli4_hba.max_cfg_param.max_cq,
8547 					phba->sli4_hba.max_cfg_param.max_eq,
8548 					qmin, phba->cfg_irq_chann,
8549 					phba->cfg_hdw_queue);
8550 
8551 			if (phba->cfg_irq_chann > qmin)
8552 				phba->cfg_irq_chann = qmin;
8553 			if (phba->cfg_hdw_queue > qmin)
8554 				phba->cfg_hdw_queue = qmin;
8555 		}
8556 	}
8557 
8558 	if (rc)
8559 		goto read_cfg_out;
8560 
8561 	/* Update link speed if forced link speed is supported */
8562 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
8563 	if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
8564 		forced_link_speed =
8565 			bf_get(lpfc_mbx_rd_conf_link_speed, rd_config);
8566 		if (forced_link_speed) {
8567 			phba->hba_flag |= HBA_FORCED_LINK_SPEED;
8568 
8569 			switch (forced_link_speed) {
8570 			case LINK_SPEED_1G:
8571 				phba->cfg_link_speed =
8572 					LPFC_USER_LINK_SPEED_1G;
8573 				break;
8574 			case LINK_SPEED_2G:
8575 				phba->cfg_link_speed =
8576 					LPFC_USER_LINK_SPEED_2G;
8577 				break;
8578 			case LINK_SPEED_4G:
8579 				phba->cfg_link_speed =
8580 					LPFC_USER_LINK_SPEED_4G;
8581 				break;
8582 			case LINK_SPEED_8G:
8583 				phba->cfg_link_speed =
8584 					LPFC_USER_LINK_SPEED_8G;
8585 				break;
8586 			case LINK_SPEED_10G:
8587 				phba->cfg_link_speed =
8588 					LPFC_USER_LINK_SPEED_10G;
8589 				break;
8590 			case LINK_SPEED_16G:
8591 				phba->cfg_link_speed =
8592 					LPFC_USER_LINK_SPEED_16G;
8593 				break;
8594 			case LINK_SPEED_32G:
8595 				phba->cfg_link_speed =
8596 					LPFC_USER_LINK_SPEED_32G;
8597 				break;
8598 			case LINK_SPEED_64G:
8599 				phba->cfg_link_speed =
8600 					LPFC_USER_LINK_SPEED_64G;
8601 				break;
8602 			case 0xffff:
8603 				phba->cfg_link_speed =
8604 					LPFC_USER_LINK_SPEED_AUTO;
8605 				break;
8606 			default:
8607 				lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8608 						"0047 Unrecognized link "
8609 						"speed : %d\n",
8610 						forced_link_speed);
8611 				phba->cfg_link_speed =
8612 					LPFC_USER_LINK_SPEED_AUTO;
8613 			}
8614 		}
8615 	}
8616 
8617 	/* Reset the DFT_HBA_Q_DEPTH to the max xri  */
8618 	length = phba->sli4_hba.max_cfg_param.max_xri -
8619 			lpfc_sli4_get_els_iocb_cnt(phba);
8620 	if (phba->cfg_hba_queue_depth > length) {
8621 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
8622 				"3361 HBA queue depth changed from %d to %d\n",
8623 				phba->cfg_hba_queue_depth, length);
8624 		phba->cfg_hba_queue_depth = length;
8625 	}
8626 
8627 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) <
8628 	    LPFC_SLI_INTF_IF_TYPE_2)
8629 		goto read_cfg_out;
8630 
8631 	/* get the pf# and vf# for SLI4 if_type 2 port */
8632 	length = (sizeof(struct lpfc_mbx_get_func_cfg) -
8633 		  sizeof(struct lpfc_sli4_cfg_mhdr));
8634 	lpfc_sli4_config(phba, pmb, LPFC_MBOX_SUBSYSTEM_COMMON,
8635 			 LPFC_MBOX_OPCODE_GET_FUNCTION_CONFIG,
8636 			 length, LPFC_SLI4_MBX_EMBED);
8637 
8638 	rc2 = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
8639 	shdr = (union lpfc_sli4_cfg_shdr *)
8640 				&pmb->u.mqe.un.sli4_config.header.cfg_shdr;
8641 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
8642 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
8643 	if (rc2 || shdr_status || shdr_add_status) {
8644 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8645 				"3026 Mailbox failed , mbxCmd x%x "
8646 				"GET_FUNCTION_CONFIG, mbxStatus x%x\n",
8647 				bf_get(lpfc_mqe_command, &pmb->u.mqe),
8648 				bf_get(lpfc_mqe_status, &pmb->u.mqe));
8649 		goto read_cfg_out;
8650 	}
8651 
8652 	/* search for fc_fcoe resrouce descriptor */
8653 	get_func_cfg = &pmb->u.mqe.un.get_func_cfg;
8654 
8655 	pdesc_0 = (char *)&get_func_cfg->func_cfg.desc[0];
8656 	desc = (struct lpfc_rsrc_desc_fcfcoe *)pdesc_0;
8657 	length = bf_get(lpfc_rsrc_desc_fcfcoe_length, desc);
8658 	if (length == LPFC_RSRC_DESC_TYPE_FCFCOE_V0_RSVD)
8659 		length = LPFC_RSRC_DESC_TYPE_FCFCOE_V0_LENGTH;
8660 	else if (length != LPFC_RSRC_DESC_TYPE_FCFCOE_V1_LENGTH)
8661 		goto read_cfg_out;
8662 
8663 	for (i = 0; i < LPFC_RSRC_DESC_MAX_NUM; i++) {
8664 		desc = (struct lpfc_rsrc_desc_fcfcoe *)(pdesc_0 + length * i);
8665 		if (LPFC_RSRC_DESC_TYPE_FCFCOE ==
8666 		    bf_get(lpfc_rsrc_desc_fcfcoe_type, desc)) {
8667 			phba->sli4_hba.iov.pf_number =
8668 				bf_get(lpfc_rsrc_desc_fcfcoe_pfnum, desc);
8669 			phba->sli4_hba.iov.vf_number =
8670 				bf_get(lpfc_rsrc_desc_fcfcoe_vfnum, desc);
8671 			break;
8672 		}
8673 	}
8674 
8675 	if (i < LPFC_RSRC_DESC_MAX_NUM)
8676 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
8677 				"3027 GET_FUNCTION_CONFIG: pf_number:%d, "
8678 				"vf_number:%d\n", phba->sli4_hba.iov.pf_number,
8679 				phba->sli4_hba.iov.vf_number);
8680 	else
8681 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8682 				"3028 GET_FUNCTION_CONFIG: failed to find "
8683 				"Resource Descriptor:x%x\n",
8684 				LPFC_RSRC_DESC_TYPE_FCFCOE);
8685 
8686 read_cfg_out:
8687 	mempool_free(pmb, phba->mbox_mem_pool);
8688 	return rc;
8689 }
8690 
8691 /**
8692  * lpfc_setup_endian_order - Write endian order to an SLI4 if_type 0 port.
8693  * @phba: pointer to lpfc hba data structure.
8694  *
8695  * This routine is invoked to setup the port-side endian order when
8696  * the port if_type is 0.  This routine has no function for other
8697  * if_types.
8698  *
8699  * Return codes
8700  * 	0 - successful
8701  * 	-ENOMEM - No available memory
8702  *      -EIO - The mailbox failed to complete successfully.
8703  **/
8704 static int
8705 lpfc_setup_endian_order(struct lpfc_hba *phba)
8706 {
8707 	LPFC_MBOXQ_t *mboxq;
8708 	uint32_t if_type, rc = 0;
8709 	uint32_t endian_mb_data[2] = {HOST_ENDIAN_LOW_WORD0,
8710 				      HOST_ENDIAN_HIGH_WORD1};
8711 
8712 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
8713 	switch (if_type) {
8714 	case LPFC_SLI_INTF_IF_TYPE_0:
8715 		mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
8716 						       GFP_KERNEL);
8717 		if (!mboxq) {
8718 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8719 					"0492 Unable to allocate memory for "
8720 					"issuing SLI_CONFIG_SPECIAL mailbox "
8721 					"command\n");
8722 			return -ENOMEM;
8723 		}
8724 
8725 		/*
8726 		 * The SLI4_CONFIG_SPECIAL mailbox command requires the first
8727 		 * two words to contain special data values and no other data.
8728 		 */
8729 		memset(mboxq, 0, sizeof(LPFC_MBOXQ_t));
8730 		memcpy(&mboxq->u.mqe, &endian_mb_data, sizeof(endian_mb_data));
8731 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8732 		if (rc != MBX_SUCCESS) {
8733 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8734 					"0493 SLI_CONFIG_SPECIAL mailbox "
8735 					"failed with status x%x\n",
8736 					rc);
8737 			rc = -EIO;
8738 		}
8739 		mempool_free(mboxq, phba->mbox_mem_pool);
8740 		break;
8741 	case LPFC_SLI_INTF_IF_TYPE_6:
8742 	case LPFC_SLI_INTF_IF_TYPE_2:
8743 	case LPFC_SLI_INTF_IF_TYPE_1:
8744 	default:
8745 		break;
8746 	}
8747 	return rc;
8748 }
8749 
8750 /**
8751  * lpfc_sli4_queue_verify - Verify and update EQ counts
8752  * @phba: pointer to lpfc hba data structure.
8753  *
8754  * This routine is invoked to check the user settable queue counts for EQs.
8755  * After this routine is called the counts will be set to valid values that
8756  * adhere to the constraints of the system's interrupt vectors and the port's
8757  * queue resources.
8758  *
8759  * Return codes
8760  *      0 - successful
8761  *      -ENOMEM - No available memory
8762  **/
8763 static int
8764 lpfc_sli4_queue_verify(struct lpfc_hba *phba)
8765 {
8766 	/*
8767 	 * Sanity check for configured queue parameters against the run-time
8768 	 * device parameters
8769 	 */
8770 
8771 	if (phba->nvmet_support) {
8772 		if (phba->cfg_hdw_queue < phba->cfg_nvmet_mrq)
8773 			phba->cfg_nvmet_mrq = phba->cfg_hdw_queue;
8774 		if (phba->cfg_nvmet_mrq > LPFC_NVMET_MRQ_MAX)
8775 			phba->cfg_nvmet_mrq = LPFC_NVMET_MRQ_MAX;
8776 	}
8777 
8778 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8779 			"2574 IO channels: hdwQ %d IRQ %d MRQ: %d\n",
8780 			phba->cfg_hdw_queue, phba->cfg_irq_chann,
8781 			phba->cfg_nvmet_mrq);
8782 
8783 	/* Get EQ depth from module parameter, fake the default for now */
8784 	phba->sli4_hba.eq_esize = LPFC_EQE_SIZE_4B;
8785 	phba->sli4_hba.eq_ecount = LPFC_EQE_DEF_COUNT;
8786 
8787 	/* Get CQ depth from module parameter, fake the default for now */
8788 	phba->sli4_hba.cq_esize = LPFC_CQE_SIZE;
8789 	phba->sli4_hba.cq_ecount = LPFC_CQE_DEF_COUNT;
8790 	return 0;
8791 }
8792 
8793 static int
8794 lpfc_alloc_io_wq_cq(struct lpfc_hba *phba, int idx)
8795 {
8796 	struct lpfc_queue *qdesc;
8797 	u32 wqesize;
8798 	int cpu;
8799 
8800 	cpu = lpfc_find_cpu_handle(phba, idx, LPFC_FIND_BY_HDWQ);
8801 	/* Create Fast Path IO CQs */
8802 	if (phba->enab_exp_wqcq_pages)
8803 		/* Increase the CQ size when WQEs contain an embedded cdb */
8804 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_EXPANDED_PAGE_SIZE,
8805 					      phba->sli4_hba.cq_esize,
8806 					      LPFC_CQE_EXP_COUNT, cpu);
8807 
8808 	else
8809 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
8810 					      phba->sli4_hba.cq_esize,
8811 					      phba->sli4_hba.cq_ecount, cpu);
8812 	if (!qdesc) {
8813 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8814 			"0499 Failed allocate fast-path IO CQ (%d)\n", idx);
8815 		return 1;
8816 	}
8817 	qdesc->qe_valid = 1;
8818 	qdesc->hdwq = idx;
8819 	qdesc->chann = cpu;
8820 	phba->sli4_hba.hdwq[idx].io_cq = qdesc;
8821 
8822 	/* Create Fast Path IO WQs */
8823 	if (phba->enab_exp_wqcq_pages) {
8824 		/* Increase the WQ size when WQEs contain an embedded cdb */
8825 		wqesize = (phba->fcp_embed_io) ?
8826 			LPFC_WQE128_SIZE : phba->sli4_hba.wq_esize;
8827 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_EXPANDED_PAGE_SIZE,
8828 					      wqesize,
8829 					      LPFC_WQE_EXP_COUNT, cpu);
8830 	} else
8831 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
8832 					      phba->sli4_hba.wq_esize,
8833 					      phba->sli4_hba.wq_ecount, cpu);
8834 
8835 	if (!qdesc) {
8836 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8837 				"0503 Failed allocate fast-path IO WQ (%d)\n",
8838 				idx);
8839 		return 1;
8840 	}
8841 	qdesc->hdwq = idx;
8842 	qdesc->chann = cpu;
8843 	phba->sli4_hba.hdwq[idx].io_wq = qdesc;
8844 	list_add_tail(&qdesc->wq_list, &phba->sli4_hba.lpfc_wq_list);
8845 	return 0;
8846 }
8847 
8848 /**
8849  * lpfc_sli4_queue_create - Create all the SLI4 queues
8850  * @phba: pointer to lpfc hba data structure.
8851  *
8852  * This routine is invoked to allocate all the SLI4 queues for the FCoE HBA
8853  * operation. For each SLI4 queue type, the parameters such as queue entry
8854  * count (queue depth) shall be taken from the module parameter. For now,
8855  * we just use some constant number as place holder.
8856  *
8857  * Return codes
8858  *      0 - successful
8859  *      -ENOMEM - No availble memory
8860  *      -EIO - The mailbox failed to complete successfully.
8861  **/
8862 int
8863 lpfc_sli4_queue_create(struct lpfc_hba *phba)
8864 {
8865 	struct lpfc_queue *qdesc;
8866 	int idx, cpu, eqcpu;
8867 	struct lpfc_sli4_hdw_queue *qp;
8868 	struct lpfc_vector_map_info *cpup;
8869 	struct lpfc_vector_map_info *eqcpup;
8870 	struct lpfc_eq_intr_info *eqi;
8871 
8872 	/*
8873 	 * Create HBA Record arrays.
8874 	 * Both NVME and FCP will share that same vectors / EQs
8875 	 */
8876 	phba->sli4_hba.mq_esize = LPFC_MQE_SIZE;
8877 	phba->sli4_hba.mq_ecount = LPFC_MQE_DEF_COUNT;
8878 	phba->sli4_hba.wq_esize = LPFC_WQE_SIZE;
8879 	phba->sli4_hba.wq_ecount = LPFC_WQE_DEF_COUNT;
8880 	phba->sli4_hba.rq_esize = LPFC_RQE_SIZE;
8881 	phba->sli4_hba.rq_ecount = LPFC_RQE_DEF_COUNT;
8882 	phba->sli4_hba.eq_esize = LPFC_EQE_SIZE_4B;
8883 	phba->sli4_hba.eq_ecount = LPFC_EQE_DEF_COUNT;
8884 	phba->sli4_hba.cq_esize = LPFC_CQE_SIZE;
8885 	phba->sli4_hba.cq_ecount = LPFC_CQE_DEF_COUNT;
8886 
8887 	if (!phba->sli4_hba.hdwq) {
8888 		phba->sli4_hba.hdwq = kcalloc(
8889 			phba->cfg_hdw_queue, sizeof(struct lpfc_sli4_hdw_queue),
8890 			GFP_KERNEL);
8891 		if (!phba->sli4_hba.hdwq) {
8892 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8893 					"6427 Failed allocate memory for "
8894 					"fast-path Hardware Queue array\n");
8895 			goto out_error;
8896 		}
8897 		/* Prepare hardware queues to take IO buffers */
8898 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
8899 			qp = &phba->sli4_hba.hdwq[idx];
8900 			spin_lock_init(&qp->io_buf_list_get_lock);
8901 			spin_lock_init(&qp->io_buf_list_put_lock);
8902 			INIT_LIST_HEAD(&qp->lpfc_io_buf_list_get);
8903 			INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
8904 			qp->get_io_bufs = 0;
8905 			qp->put_io_bufs = 0;
8906 			qp->total_io_bufs = 0;
8907 			spin_lock_init(&qp->abts_io_buf_list_lock);
8908 			INIT_LIST_HEAD(&qp->lpfc_abts_io_buf_list);
8909 			qp->abts_scsi_io_bufs = 0;
8910 			qp->abts_nvme_io_bufs = 0;
8911 			INIT_LIST_HEAD(&qp->sgl_list);
8912 			INIT_LIST_HEAD(&qp->cmd_rsp_buf_list);
8913 			spin_lock_init(&qp->hdwq_lock);
8914 		}
8915 	}
8916 
8917 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
8918 		if (phba->nvmet_support) {
8919 			phba->sli4_hba.nvmet_cqset = kcalloc(
8920 					phba->cfg_nvmet_mrq,
8921 					sizeof(struct lpfc_queue *),
8922 					GFP_KERNEL);
8923 			if (!phba->sli4_hba.nvmet_cqset) {
8924 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8925 					"3121 Fail allocate memory for "
8926 					"fast-path CQ set array\n");
8927 				goto out_error;
8928 			}
8929 			phba->sli4_hba.nvmet_mrq_hdr = kcalloc(
8930 					phba->cfg_nvmet_mrq,
8931 					sizeof(struct lpfc_queue *),
8932 					GFP_KERNEL);
8933 			if (!phba->sli4_hba.nvmet_mrq_hdr) {
8934 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8935 					"3122 Fail allocate memory for "
8936 					"fast-path RQ set hdr array\n");
8937 				goto out_error;
8938 			}
8939 			phba->sli4_hba.nvmet_mrq_data = kcalloc(
8940 					phba->cfg_nvmet_mrq,
8941 					sizeof(struct lpfc_queue *),
8942 					GFP_KERNEL);
8943 			if (!phba->sli4_hba.nvmet_mrq_data) {
8944 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8945 					"3124 Fail allocate memory for "
8946 					"fast-path RQ set data array\n");
8947 				goto out_error;
8948 			}
8949 		}
8950 	}
8951 
8952 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_wq_list);
8953 
8954 	/* Create HBA Event Queues (EQs) */
8955 	for_each_present_cpu(cpu) {
8956 		/* We only want to create 1 EQ per vector, even though
8957 		 * multiple CPUs might be using that vector. so only
8958 		 * selects the CPUs that are LPFC_CPU_FIRST_IRQ.
8959 		 */
8960 		cpup = &phba->sli4_hba.cpu_map[cpu];
8961 		if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
8962 			continue;
8963 
8964 		/* Get a ptr to the Hardware Queue associated with this CPU */
8965 		qp = &phba->sli4_hba.hdwq[cpup->hdwq];
8966 
8967 		/* Allocate an EQ */
8968 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
8969 					      phba->sli4_hba.eq_esize,
8970 					      phba->sli4_hba.eq_ecount, cpu);
8971 		if (!qdesc) {
8972 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8973 					"0497 Failed allocate EQ (%d)\n",
8974 					cpup->hdwq);
8975 			goto out_error;
8976 		}
8977 		qdesc->qe_valid = 1;
8978 		qdesc->hdwq = cpup->hdwq;
8979 		qdesc->chann = cpu; /* First CPU this EQ is affinitized to */
8980 		qdesc->last_cpu = qdesc->chann;
8981 
8982 		/* Save the allocated EQ in the Hardware Queue */
8983 		qp->hba_eq = qdesc;
8984 
8985 		eqi = per_cpu_ptr(phba->sli4_hba.eq_info, qdesc->last_cpu);
8986 		list_add(&qdesc->cpu_list, &eqi->list);
8987 	}
8988 
8989 	/* Now we need to populate the other Hardware Queues, that share
8990 	 * an IRQ vector, with the associated EQ ptr.
8991 	 */
8992 	for_each_present_cpu(cpu) {
8993 		cpup = &phba->sli4_hba.cpu_map[cpu];
8994 
8995 		/* Check for EQ already allocated in previous loop */
8996 		if (cpup->flag & LPFC_CPU_FIRST_IRQ)
8997 			continue;
8998 
8999 		/* Check for multiple CPUs per hdwq */
9000 		qp = &phba->sli4_hba.hdwq[cpup->hdwq];
9001 		if (qp->hba_eq)
9002 			continue;
9003 
9004 		/* We need to share an EQ for this hdwq */
9005 		eqcpu = lpfc_find_cpu_handle(phba, cpup->eq, LPFC_FIND_BY_EQ);
9006 		eqcpup = &phba->sli4_hba.cpu_map[eqcpu];
9007 		qp->hba_eq = phba->sli4_hba.hdwq[eqcpup->hdwq].hba_eq;
9008 	}
9009 
9010 	/* Allocate IO Path SLI4 CQ/WQs */
9011 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
9012 		if (lpfc_alloc_io_wq_cq(phba, idx))
9013 			goto out_error;
9014 	}
9015 
9016 	if (phba->nvmet_support) {
9017 		for (idx = 0; idx < phba->cfg_nvmet_mrq; idx++) {
9018 			cpu = lpfc_find_cpu_handle(phba, idx,
9019 						   LPFC_FIND_BY_HDWQ);
9020 			qdesc = lpfc_sli4_queue_alloc(phba,
9021 						      LPFC_DEFAULT_PAGE_SIZE,
9022 						      phba->sli4_hba.cq_esize,
9023 						      phba->sli4_hba.cq_ecount,
9024 						      cpu);
9025 			if (!qdesc) {
9026 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9027 						"3142 Failed allocate NVME "
9028 						"CQ Set (%d)\n", idx);
9029 				goto out_error;
9030 			}
9031 			qdesc->qe_valid = 1;
9032 			qdesc->hdwq = idx;
9033 			qdesc->chann = cpu;
9034 			phba->sli4_hba.nvmet_cqset[idx] = qdesc;
9035 		}
9036 	}
9037 
9038 	/*
9039 	 * Create Slow Path Completion Queues (CQs)
9040 	 */
9041 
9042 	cpu = lpfc_find_cpu_handle(phba, 0, LPFC_FIND_BY_EQ);
9043 	/* Create slow-path Mailbox Command Complete Queue */
9044 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
9045 				      phba->sli4_hba.cq_esize,
9046 				      phba->sli4_hba.cq_ecount, cpu);
9047 	if (!qdesc) {
9048 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9049 				"0500 Failed allocate slow-path mailbox CQ\n");
9050 		goto out_error;
9051 	}
9052 	qdesc->qe_valid = 1;
9053 	phba->sli4_hba.mbx_cq = qdesc;
9054 
9055 	/* Create slow-path ELS Complete Queue */
9056 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
9057 				      phba->sli4_hba.cq_esize,
9058 				      phba->sli4_hba.cq_ecount, cpu);
9059 	if (!qdesc) {
9060 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9061 				"0501 Failed allocate slow-path ELS CQ\n");
9062 		goto out_error;
9063 	}
9064 	qdesc->qe_valid = 1;
9065 	qdesc->chann = cpu;
9066 	phba->sli4_hba.els_cq = qdesc;
9067 
9068 
9069 	/*
9070 	 * Create Slow Path Work Queues (WQs)
9071 	 */
9072 
9073 	/* Create Mailbox Command Queue */
9074 
9075 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
9076 				      phba->sli4_hba.mq_esize,
9077 				      phba->sli4_hba.mq_ecount, cpu);
9078 	if (!qdesc) {
9079 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9080 				"0505 Failed allocate slow-path MQ\n");
9081 		goto out_error;
9082 	}
9083 	qdesc->chann = cpu;
9084 	phba->sli4_hba.mbx_wq = qdesc;
9085 
9086 	/*
9087 	 * Create ELS Work Queues
9088 	 */
9089 
9090 	/* Create slow-path ELS Work Queue */
9091 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
9092 				      phba->sli4_hba.wq_esize,
9093 				      phba->sli4_hba.wq_ecount, cpu);
9094 	if (!qdesc) {
9095 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9096 				"0504 Failed allocate slow-path ELS WQ\n");
9097 		goto out_error;
9098 	}
9099 	qdesc->chann = cpu;
9100 	phba->sli4_hba.els_wq = qdesc;
9101 	list_add_tail(&qdesc->wq_list, &phba->sli4_hba.lpfc_wq_list);
9102 
9103 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
9104 		/* Create NVME LS Complete Queue */
9105 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
9106 					      phba->sli4_hba.cq_esize,
9107 					      phba->sli4_hba.cq_ecount, cpu);
9108 		if (!qdesc) {
9109 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9110 					"6079 Failed allocate NVME LS CQ\n");
9111 			goto out_error;
9112 		}
9113 		qdesc->chann = cpu;
9114 		qdesc->qe_valid = 1;
9115 		phba->sli4_hba.nvmels_cq = qdesc;
9116 
9117 		/* Create NVME LS Work Queue */
9118 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
9119 					      phba->sli4_hba.wq_esize,
9120 					      phba->sli4_hba.wq_ecount, cpu);
9121 		if (!qdesc) {
9122 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9123 					"6080 Failed allocate NVME LS WQ\n");
9124 			goto out_error;
9125 		}
9126 		qdesc->chann = cpu;
9127 		phba->sli4_hba.nvmels_wq = qdesc;
9128 		list_add_tail(&qdesc->wq_list, &phba->sli4_hba.lpfc_wq_list);
9129 	}
9130 
9131 	/*
9132 	 * Create Receive Queue (RQ)
9133 	 */
9134 
9135 	/* Create Receive Queue for header */
9136 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
9137 				      phba->sli4_hba.rq_esize,
9138 				      phba->sli4_hba.rq_ecount, cpu);
9139 	if (!qdesc) {
9140 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9141 				"0506 Failed allocate receive HRQ\n");
9142 		goto out_error;
9143 	}
9144 	phba->sli4_hba.hdr_rq = qdesc;
9145 
9146 	/* Create Receive Queue for data */
9147 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
9148 				      phba->sli4_hba.rq_esize,
9149 				      phba->sli4_hba.rq_ecount, cpu);
9150 	if (!qdesc) {
9151 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9152 				"0507 Failed allocate receive DRQ\n");
9153 		goto out_error;
9154 	}
9155 	phba->sli4_hba.dat_rq = qdesc;
9156 
9157 	if ((phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) &&
9158 	    phba->nvmet_support) {
9159 		for (idx = 0; idx < phba->cfg_nvmet_mrq; idx++) {
9160 			cpu = lpfc_find_cpu_handle(phba, idx,
9161 						   LPFC_FIND_BY_HDWQ);
9162 			/* Create NVMET Receive Queue for header */
9163 			qdesc = lpfc_sli4_queue_alloc(phba,
9164 						      LPFC_DEFAULT_PAGE_SIZE,
9165 						      phba->sli4_hba.rq_esize,
9166 						      LPFC_NVMET_RQE_DEF_COUNT,
9167 						      cpu);
9168 			if (!qdesc) {
9169 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9170 						"3146 Failed allocate "
9171 						"receive HRQ\n");
9172 				goto out_error;
9173 			}
9174 			qdesc->hdwq = idx;
9175 			phba->sli4_hba.nvmet_mrq_hdr[idx] = qdesc;
9176 
9177 			/* Only needed for header of RQ pair */
9178 			qdesc->rqbp = kzalloc_node(sizeof(*qdesc->rqbp),
9179 						   GFP_KERNEL,
9180 						   cpu_to_node(cpu));
9181 			if (qdesc->rqbp == NULL) {
9182 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9183 						"6131 Failed allocate "
9184 						"Header RQBP\n");
9185 				goto out_error;
9186 			}
9187 
9188 			/* Put list in known state in case driver load fails. */
9189 			INIT_LIST_HEAD(&qdesc->rqbp->rqb_buffer_list);
9190 
9191 			/* Create NVMET Receive Queue for data */
9192 			qdesc = lpfc_sli4_queue_alloc(phba,
9193 						      LPFC_DEFAULT_PAGE_SIZE,
9194 						      phba->sli4_hba.rq_esize,
9195 						      LPFC_NVMET_RQE_DEF_COUNT,
9196 						      cpu);
9197 			if (!qdesc) {
9198 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9199 						"3156 Failed allocate "
9200 						"receive DRQ\n");
9201 				goto out_error;
9202 			}
9203 			qdesc->hdwq = idx;
9204 			phba->sli4_hba.nvmet_mrq_data[idx] = qdesc;
9205 		}
9206 	}
9207 
9208 	/* Clear NVME stats */
9209 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
9210 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
9211 			memset(&phba->sli4_hba.hdwq[idx].nvme_cstat, 0,
9212 			       sizeof(phba->sli4_hba.hdwq[idx].nvme_cstat));
9213 		}
9214 	}
9215 
9216 	/* Clear SCSI stats */
9217 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP) {
9218 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
9219 			memset(&phba->sli4_hba.hdwq[idx].scsi_cstat, 0,
9220 			       sizeof(phba->sli4_hba.hdwq[idx].scsi_cstat));
9221 		}
9222 	}
9223 
9224 	return 0;
9225 
9226 out_error:
9227 	lpfc_sli4_queue_destroy(phba);
9228 	return -ENOMEM;
9229 }
9230 
9231 static inline void
9232 __lpfc_sli4_release_queue(struct lpfc_queue **qp)
9233 {
9234 	if (*qp != NULL) {
9235 		lpfc_sli4_queue_free(*qp);
9236 		*qp = NULL;
9237 	}
9238 }
9239 
9240 static inline void
9241 lpfc_sli4_release_queues(struct lpfc_queue ***qs, int max)
9242 {
9243 	int idx;
9244 
9245 	if (*qs == NULL)
9246 		return;
9247 
9248 	for (idx = 0; idx < max; idx++)
9249 		__lpfc_sli4_release_queue(&(*qs)[idx]);
9250 
9251 	kfree(*qs);
9252 	*qs = NULL;
9253 }
9254 
9255 static inline void
9256 lpfc_sli4_release_hdwq(struct lpfc_hba *phba)
9257 {
9258 	struct lpfc_sli4_hdw_queue *hdwq;
9259 	struct lpfc_queue *eq;
9260 	uint32_t idx;
9261 
9262 	hdwq = phba->sli4_hba.hdwq;
9263 
9264 	/* Loop thru all Hardware Queues */
9265 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
9266 		/* Free the CQ/WQ corresponding to the Hardware Queue */
9267 		lpfc_sli4_queue_free(hdwq[idx].io_cq);
9268 		lpfc_sli4_queue_free(hdwq[idx].io_wq);
9269 		hdwq[idx].hba_eq = NULL;
9270 		hdwq[idx].io_cq = NULL;
9271 		hdwq[idx].io_wq = NULL;
9272 		if (phba->cfg_xpsgl && !phba->nvmet_support)
9273 			lpfc_free_sgl_per_hdwq(phba, &hdwq[idx]);
9274 		lpfc_free_cmd_rsp_buf_per_hdwq(phba, &hdwq[idx]);
9275 	}
9276 	/* Loop thru all IRQ vectors */
9277 	for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
9278 		/* Free the EQ corresponding to the IRQ vector */
9279 		eq = phba->sli4_hba.hba_eq_hdl[idx].eq;
9280 		lpfc_sli4_queue_free(eq);
9281 		phba->sli4_hba.hba_eq_hdl[idx].eq = NULL;
9282 	}
9283 }
9284 
9285 /**
9286  * lpfc_sli4_queue_destroy - Destroy all the SLI4 queues
9287  * @phba: pointer to lpfc hba data structure.
9288  *
9289  * This routine is invoked to release all the SLI4 queues with the FCoE HBA
9290  * operation.
9291  *
9292  * Return codes
9293  *      0 - successful
9294  *      -ENOMEM - No available memory
9295  *      -EIO - The mailbox failed to complete successfully.
9296  **/
9297 void
9298 lpfc_sli4_queue_destroy(struct lpfc_hba *phba)
9299 {
9300 	/*
9301 	 * Set FREE_INIT before beginning to free the queues.
9302 	 * Wait until the users of queues to acknowledge to
9303 	 * release queues by clearing FREE_WAIT.
9304 	 */
9305 	spin_lock_irq(&phba->hbalock);
9306 	phba->sli.sli_flag |= LPFC_QUEUE_FREE_INIT;
9307 	while (phba->sli.sli_flag & LPFC_QUEUE_FREE_WAIT) {
9308 		spin_unlock_irq(&phba->hbalock);
9309 		msleep(20);
9310 		spin_lock_irq(&phba->hbalock);
9311 	}
9312 	spin_unlock_irq(&phba->hbalock);
9313 
9314 	lpfc_sli4_cleanup_poll_list(phba);
9315 
9316 	/* Release HBA eqs */
9317 	if (phba->sli4_hba.hdwq)
9318 		lpfc_sli4_release_hdwq(phba);
9319 
9320 	if (phba->nvmet_support) {
9321 		lpfc_sli4_release_queues(&phba->sli4_hba.nvmet_cqset,
9322 					 phba->cfg_nvmet_mrq);
9323 
9324 		lpfc_sli4_release_queues(&phba->sli4_hba.nvmet_mrq_hdr,
9325 					 phba->cfg_nvmet_mrq);
9326 		lpfc_sli4_release_queues(&phba->sli4_hba.nvmet_mrq_data,
9327 					 phba->cfg_nvmet_mrq);
9328 	}
9329 
9330 	/* Release mailbox command work queue */
9331 	__lpfc_sli4_release_queue(&phba->sli4_hba.mbx_wq);
9332 
9333 	/* Release ELS work queue */
9334 	__lpfc_sli4_release_queue(&phba->sli4_hba.els_wq);
9335 
9336 	/* Release ELS work queue */
9337 	__lpfc_sli4_release_queue(&phba->sli4_hba.nvmels_wq);
9338 
9339 	/* Release unsolicited receive queue */
9340 	__lpfc_sli4_release_queue(&phba->sli4_hba.hdr_rq);
9341 	__lpfc_sli4_release_queue(&phba->sli4_hba.dat_rq);
9342 
9343 	/* Release ELS complete queue */
9344 	__lpfc_sli4_release_queue(&phba->sli4_hba.els_cq);
9345 
9346 	/* Release NVME LS complete queue */
9347 	__lpfc_sli4_release_queue(&phba->sli4_hba.nvmels_cq);
9348 
9349 	/* Release mailbox command complete queue */
9350 	__lpfc_sli4_release_queue(&phba->sli4_hba.mbx_cq);
9351 
9352 	/* Everything on this list has been freed */
9353 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_wq_list);
9354 
9355 	/* Done with freeing the queues */
9356 	spin_lock_irq(&phba->hbalock);
9357 	phba->sli.sli_flag &= ~LPFC_QUEUE_FREE_INIT;
9358 	spin_unlock_irq(&phba->hbalock);
9359 }
9360 
9361 int
9362 lpfc_free_rq_buffer(struct lpfc_hba *phba, struct lpfc_queue *rq)
9363 {
9364 	struct lpfc_rqb *rqbp;
9365 	struct lpfc_dmabuf *h_buf;
9366 	struct rqb_dmabuf *rqb_buffer;
9367 
9368 	rqbp = rq->rqbp;
9369 	while (!list_empty(&rqbp->rqb_buffer_list)) {
9370 		list_remove_head(&rqbp->rqb_buffer_list, h_buf,
9371 				 struct lpfc_dmabuf, list);
9372 
9373 		rqb_buffer = container_of(h_buf, struct rqb_dmabuf, hbuf);
9374 		(rqbp->rqb_free_buffer)(phba, rqb_buffer);
9375 		rqbp->buffer_count--;
9376 	}
9377 	return 1;
9378 }
9379 
9380 static int
9381 lpfc_create_wq_cq(struct lpfc_hba *phba, struct lpfc_queue *eq,
9382 	struct lpfc_queue *cq, struct lpfc_queue *wq, uint16_t *cq_map,
9383 	int qidx, uint32_t qtype)
9384 {
9385 	struct lpfc_sli_ring *pring;
9386 	int rc;
9387 
9388 	if (!eq || !cq || !wq) {
9389 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9390 			"6085 Fast-path %s (%d) not allocated\n",
9391 			((eq) ? ((cq) ? "WQ" : "CQ") : "EQ"), qidx);
9392 		return -ENOMEM;
9393 	}
9394 
9395 	/* create the Cq first */
9396 	rc = lpfc_cq_create(phba, cq, eq,
9397 			(qtype == LPFC_MBOX) ? LPFC_MCQ : LPFC_WCQ, qtype);
9398 	if (rc) {
9399 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9400 			"6086 Failed setup of CQ (%d), rc = 0x%x\n",
9401 			qidx, (uint32_t)rc);
9402 		return rc;
9403 	}
9404 
9405 	if (qtype != LPFC_MBOX) {
9406 		/* Setup cq_map for fast lookup */
9407 		if (cq_map)
9408 			*cq_map = cq->queue_id;
9409 
9410 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9411 			"6087 CQ setup: cq[%d]-id=%d, parent eq[%d]-id=%d\n",
9412 			qidx, cq->queue_id, qidx, eq->queue_id);
9413 
9414 		/* create the wq */
9415 		rc = lpfc_wq_create(phba, wq, cq, qtype);
9416 		if (rc) {
9417 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9418 				"4618 Fail setup fastpath WQ (%d), rc = 0x%x\n",
9419 				qidx, (uint32_t)rc);
9420 			/* no need to tear down cq - caller will do so */
9421 			return rc;
9422 		}
9423 
9424 		/* Bind this CQ/WQ to the NVME ring */
9425 		pring = wq->pring;
9426 		pring->sli.sli4.wqp = (void *)wq;
9427 		cq->pring = pring;
9428 
9429 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9430 			"2593 WQ setup: wq[%d]-id=%d assoc=%d, cq[%d]-id=%d\n",
9431 			qidx, wq->queue_id, wq->assoc_qid, qidx, cq->queue_id);
9432 	} else {
9433 		rc = lpfc_mq_create(phba, wq, cq, LPFC_MBOX);
9434 		if (rc) {
9435 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9436 				"0539 Failed setup of slow-path MQ: "
9437 				"rc = 0x%x\n", rc);
9438 			/* no need to tear down cq - caller will do so */
9439 			return rc;
9440 		}
9441 
9442 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9443 			"2589 MBX MQ setup: wq-id=%d, parent cq-id=%d\n",
9444 			phba->sli4_hba.mbx_wq->queue_id,
9445 			phba->sli4_hba.mbx_cq->queue_id);
9446 	}
9447 
9448 	return 0;
9449 }
9450 
9451 /**
9452  * lpfc_setup_cq_lookup - Setup the CQ lookup table
9453  * @phba: pointer to lpfc hba data structure.
9454  *
9455  * This routine will populate the cq_lookup table by all
9456  * available CQ queue_id's.
9457  **/
9458 static void
9459 lpfc_setup_cq_lookup(struct lpfc_hba *phba)
9460 {
9461 	struct lpfc_queue *eq, *childq;
9462 	int qidx;
9463 
9464 	memset(phba->sli4_hba.cq_lookup, 0,
9465 	       (sizeof(struct lpfc_queue *) * (phba->sli4_hba.cq_max + 1)));
9466 	/* Loop thru all IRQ vectors */
9467 	for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
9468 		/* Get the EQ corresponding to the IRQ vector */
9469 		eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
9470 		if (!eq)
9471 			continue;
9472 		/* Loop through all CQs associated with that EQ */
9473 		list_for_each_entry(childq, &eq->child_list, list) {
9474 			if (childq->queue_id > phba->sli4_hba.cq_max)
9475 				continue;
9476 			if (childq->subtype == LPFC_IO)
9477 				phba->sli4_hba.cq_lookup[childq->queue_id] =
9478 					childq;
9479 		}
9480 	}
9481 }
9482 
9483 /**
9484  * lpfc_sli4_queue_setup - Set up all the SLI4 queues
9485  * @phba: pointer to lpfc hba data structure.
9486  *
9487  * This routine is invoked to set up all the SLI4 queues for the FCoE HBA
9488  * operation.
9489  *
9490  * Return codes
9491  *      0 - successful
9492  *      -ENOMEM - No available memory
9493  *      -EIO - The mailbox failed to complete successfully.
9494  **/
9495 int
9496 lpfc_sli4_queue_setup(struct lpfc_hba *phba)
9497 {
9498 	uint32_t shdr_status, shdr_add_status;
9499 	union lpfc_sli4_cfg_shdr *shdr;
9500 	struct lpfc_vector_map_info *cpup;
9501 	struct lpfc_sli4_hdw_queue *qp;
9502 	LPFC_MBOXQ_t *mboxq;
9503 	int qidx, cpu;
9504 	uint32_t length, usdelay;
9505 	int rc = -ENOMEM;
9506 
9507 	/* Check for dual-ULP support */
9508 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
9509 	if (!mboxq) {
9510 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9511 				"3249 Unable to allocate memory for "
9512 				"QUERY_FW_CFG mailbox command\n");
9513 		return -ENOMEM;
9514 	}
9515 	length = (sizeof(struct lpfc_mbx_query_fw_config) -
9516 		  sizeof(struct lpfc_sli4_cfg_mhdr));
9517 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
9518 			 LPFC_MBOX_OPCODE_QUERY_FW_CFG,
9519 			 length, LPFC_SLI4_MBX_EMBED);
9520 
9521 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
9522 
9523 	shdr = (union lpfc_sli4_cfg_shdr *)
9524 			&mboxq->u.mqe.un.sli4_config.header.cfg_shdr;
9525 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
9526 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
9527 	if (shdr_status || shdr_add_status || rc) {
9528 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9529 				"3250 QUERY_FW_CFG mailbox failed with status "
9530 				"x%x add_status x%x, mbx status x%x\n",
9531 				shdr_status, shdr_add_status, rc);
9532 		if (rc != MBX_TIMEOUT)
9533 			mempool_free(mboxq, phba->mbox_mem_pool);
9534 		rc = -ENXIO;
9535 		goto out_error;
9536 	}
9537 
9538 	phba->sli4_hba.fw_func_mode =
9539 			mboxq->u.mqe.un.query_fw_cfg.rsp.function_mode;
9540 	phba->sli4_hba.ulp0_mode = mboxq->u.mqe.un.query_fw_cfg.rsp.ulp0_mode;
9541 	phba->sli4_hba.ulp1_mode = mboxq->u.mqe.un.query_fw_cfg.rsp.ulp1_mode;
9542 	phba->sli4_hba.physical_port =
9543 			mboxq->u.mqe.un.query_fw_cfg.rsp.physical_port;
9544 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9545 			"3251 QUERY_FW_CFG: func_mode:x%x, ulp0_mode:x%x, "
9546 			"ulp1_mode:x%x\n", phba->sli4_hba.fw_func_mode,
9547 			phba->sli4_hba.ulp0_mode, phba->sli4_hba.ulp1_mode);
9548 
9549 	if (rc != MBX_TIMEOUT)
9550 		mempool_free(mboxq, phba->mbox_mem_pool);
9551 
9552 	/*
9553 	 * Set up HBA Event Queues (EQs)
9554 	 */
9555 	qp = phba->sli4_hba.hdwq;
9556 
9557 	/* Set up HBA event queue */
9558 	if (!qp) {
9559 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9560 				"3147 Fast-path EQs not allocated\n");
9561 		rc = -ENOMEM;
9562 		goto out_error;
9563 	}
9564 
9565 	/* Loop thru all IRQ vectors */
9566 	for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
9567 		/* Create HBA Event Queues (EQs) in order */
9568 		for_each_present_cpu(cpu) {
9569 			cpup = &phba->sli4_hba.cpu_map[cpu];
9570 
9571 			/* Look for the CPU thats using that vector with
9572 			 * LPFC_CPU_FIRST_IRQ set.
9573 			 */
9574 			if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
9575 				continue;
9576 			if (qidx != cpup->eq)
9577 				continue;
9578 
9579 			/* Create an EQ for that vector */
9580 			rc = lpfc_eq_create(phba, qp[cpup->hdwq].hba_eq,
9581 					    phba->cfg_fcp_imax);
9582 			if (rc) {
9583 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9584 						"0523 Failed setup of fast-path"
9585 						" EQ (%d), rc = 0x%x\n",
9586 						cpup->eq, (uint32_t)rc);
9587 				goto out_destroy;
9588 			}
9589 
9590 			/* Save the EQ for that vector in the hba_eq_hdl */
9591 			phba->sli4_hba.hba_eq_hdl[cpup->eq].eq =
9592 				qp[cpup->hdwq].hba_eq;
9593 
9594 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9595 					"2584 HBA EQ setup: queue[%d]-id=%d\n",
9596 					cpup->eq,
9597 					qp[cpup->hdwq].hba_eq->queue_id);
9598 		}
9599 	}
9600 
9601 	/* Loop thru all Hardware Queues */
9602 	for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
9603 		cpu = lpfc_find_cpu_handle(phba, qidx, LPFC_FIND_BY_HDWQ);
9604 		cpup = &phba->sli4_hba.cpu_map[cpu];
9605 
9606 		/* Create the CQ/WQ corresponding to the Hardware Queue */
9607 		rc = lpfc_create_wq_cq(phba,
9608 				       phba->sli4_hba.hdwq[cpup->hdwq].hba_eq,
9609 				       qp[qidx].io_cq,
9610 				       qp[qidx].io_wq,
9611 				       &phba->sli4_hba.hdwq[qidx].io_cq_map,
9612 				       qidx,
9613 				       LPFC_IO);
9614 		if (rc) {
9615 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9616 					"0535 Failed to setup fastpath "
9617 					"IO WQ/CQ (%d), rc = 0x%x\n",
9618 					qidx, (uint32_t)rc);
9619 			goto out_destroy;
9620 		}
9621 	}
9622 
9623 	/*
9624 	 * Set up Slow Path Complete Queues (CQs)
9625 	 */
9626 
9627 	/* Set up slow-path MBOX CQ/MQ */
9628 
9629 	if (!phba->sli4_hba.mbx_cq || !phba->sli4_hba.mbx_wq) {
9630 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9631 				"0528 %s not allocated\n",
9632 				phba->sli4_hba.mbx_cq ?
9633 				"Mailbox WQ" : "Mailbox CQ");
9634 		rc = -ENOMEM;
9635 		goto out_destroy;
9636 	}
9637 
9638 	rc = lpfc_create_wq_cq(phba, qp[0].hba_eq,
9639 			       phba->sli4_hba.mbx_cq,
9640 			       phba->sli4_hba.mbx_wq,
9641 			       NULL, 0, LPFC_MBOX);
9642 	if (rc) {
9643 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9644 			"0529 Failed setup of mailbox WQ/CQ: rc = 0x%x\n",
9645 			(uint32_t)rc);
9646 		goto out_destroy;
9647 	}
9648 	if (phba->nvmet_support) {
9649 		if (!phba->sli4_hba.nvmet_cqset) {
9650 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9651 					"3165 Fast-path NVME CQ Set "
9652 					"array not allocated\n");
9653 			rc = -ENOMEM;
9654 			goto out_destroy;
9655 		}
9656 		if (phba->cfg_nvmet_mrq > 1) {
9657 			rc = lpfc_cq_create_set(phba,
9658 					phba->sli4_hba.nvmet_cqset,
9659 					qp,
9660 					LPFC_WCQ, LPFC_NVMET);
9661 			if (rc) {
9662 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9663 						"3164 Failed setup of NVME CQ "
9664 						"Set, rc = 0x%x\n",
9665 						(uint32_t)rc);
9666 				goto out_destroy;
9667 			}
9668 		} else {
9669 			/* Set up NVMET Receive Complete Queue */
9670 			rc = lpfc_cq_create(phba, phba->sli4_hba.nvmet_cqset[0],
9671 					    qp[0].hba_eq,
9672 					    LPFC_WCQ, LPFC_NVMET);
9673 			if (rc) {
9674 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9675 						"6089 Failed setup NVMET CQ: "
9676 						"rc = 0x%x\n", (uint32_t)rc);
9677 				goto out_destroy;
9678 			}
9679 			phba->sli4_hba.nvmet_cqset[0]->chann = 0;
9680 
9681 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9682 					"6090 NVMET CQ setup: cq-id=%d, "
9683 					"parent eq-id=%d\n",
9684 					phba->sli4_hba.nvmet_cqset[0]->queue_id,
9685 					qp[0].hba_eq->queue_id);
9686 		}
9687 	}
9688 
9689 	/* Set up slow-path ELS WQ/CQ */
9690 	if (!phba->sli4_hba.els_cq || !phba->sli4_hba.els_wq) {
9691 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9692 				"0530 ELS %s not allocated\n",
9693 				phba->sli4_hba.els_cq ? "WQ" : "CQ");
9694 		rc = -ENOMEM;
9695 		goto out_destroy;
9696 	}
9697 	rc = lpfc_create_wq_cq(phba, qp[0].hba_eq,
9698 			       phba->sli4_hba.els_cq,
9699 			       phba->sli4_hba.els_wq,
9700 			       NULL, 0, LPFC_ELS);
9701 	if (rc) {
9702 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9703 				"0525 Failed setup of ELS WQ/CQ: rc = 0x%x\n",
9704 				(uint32_t)rc);
9705 		goto out_destroy;
9706 	}
9707 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9708 			"2590 ELS WQ setup: wq-id=%d, parent cq-id=%d\n",
9709 			phba->sli4_hba.els_wq->queue_id,
9710 			phba->sli4_hba.els_cq->queue_id);
9711 
9712 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
9713 		/* Set up NVME LS Complete Queue */
9714 		if (!phba->sli4_hba.nvmels_cq || !phba->sli4_hba.nvmels_wq) {
9715 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9716 					"6091 LS %s not allocated\n",
9717 					phba->sli4_hba.nvmels_cq ? "WQ" : "CQ");
9718 			rc = -ENOMEM;
9719 			goto out_destroy;
9720 		}
9721 		rc = lpfc_create_wq_cq(phba, qp[0].hba_eq,
9722 				       phba->sli4_hba.nvmels_cq,
9723 				       phba->sli4_hba.nvmels_wq,
9724 				       NULL, 0, LPFC_NVME_LS);
9725 		if (rc) {
9726 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9727 					"0526 Failed setup of NVVME LS WQ/CQ: "
9728 					"rc = 0x%x\n", (uint32_t)rc);
9729 			goto out_destroy;
9730 		}
9731 
9732 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9733 				"6096 ELS WQ setup: wq-id=%d, "
9734 				"parent cq-id=%d\n",
9735 				phba->sli4_hba.nvmels_wq->queue_id,
9736 				phba->sli4_hba.nvmels_cq->queue_id);
9737 	}
9738 
9739 	/*
9740 	 * Create NVMET Receive Queue (RQ)
9741 	 */
9742 	if (phba->nvmet_support) {
9743 		if ((!phba->sli4_hba.nvmet_cqset) ||
9744 		    (!phba->sli4_hba.nvmet_mrq_hdr) ||
9745 		    (!phba->sli4_hba.nvmet_mrq_data)) {
9746 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9747 					"6130 MRQ CQ Queues not "
9748 					"allocated\n");
9749 			rc = -ENOMEM;
9750 			goto out_destroy;
9751 		}
9752 		if (phba->cfg_nvmet_mrq > 1) {
9753 			rc = lpfc_mrq_create(phba,
9754 					     phba->sli4_hba.nvmet_mrq_hdr,
9755 					     phba->sli4_hba.nvmet_mrq_data,
9756 					     phba->sli4_hba.nvmet_cqset,
9757 					     LPFC_NVMET);
9758 			if (rc) {
9759 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9760 						"6098 Failed setup of NVMET "
9761 						"MRQ: rc = 0x%x\n",
9762 						(uint32_t)rc);
9763 				goto out_destroy;
9764 			}
9765 
9766 		} else {
9767 			rc = lpfc_rq_create(phba,
9768 					    phba->sli4_hba.nvmet_mrq_hdr[0],
9769 					    phba->sli4_hba.nvmet_mrq_data[0],
9770 					    phba->sli4_hba.nvmet_cqset[0],
9771 					    LPFC_NVMET);
9772 			if (rc) {
9773 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9774 						"6057 Failed setup of NVMET "
9775 						"Receive Queue: rc = 0x%x\n",
9776 						(uint32_t)rc);
9777 				goto out_destroy;
9778 			}
9779 
9780 			lpfc_printf_log(
9781 				phba, KERN_INFO, LOG_INIT,
9782 				"6099 NVMET RQ setup: hdr-rq-id=%d, "
9783 				"dat-rq-id=%d parent cq-id=%d\n",
9784 				phba->sli4_hba.nvmet_mrq_hdr[0]->queue_id,
9785 				phba->sli4_hba.nvmet_mrq_data[0]->queue_id,
9786 				phba->sli4_hba.nvmet_cqset[0]->queue_id);
9787 
9788 		}
9789 	}
9790 
9791 	if (!phba->sli4_hba.hdr_rq || !phba->sli4_hba.dat_rq) {
9792 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9793 				"0540 Receive Queue not allocated\n");
9794 		rc = -ENOMEM;
9795 		goto out_destroy;
9796 	}
9797 
9798 	rc = lpfc_rq_create(phba, phba->sli4_hba.hdr_rq, phba->sli4_hba.dat_rq,
9799 			    phba->sli4_hba.els_cq, LPFC_USOL);
9800 	if (rc) {
9801 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9802 				"0541 Failed setup of Receive Queue: "
9803 				"rc = 0x%x\n", (uint32_t)rc);
9804 		goto out_destroy;
9805 	}
9806 
9807 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9808 			"2592 USL RQ setup: hdr-rq-id=%d, dat-rq-id=%d "
9809 			"parent cq-id=%d\n",
9810 			phba->sli4_hba.hdr_rq->queue_id,
9811 			phba->sli4_hba.dat_rq->queue_id,
9812 			phba->sli4_hba.els_cq->queue_id);
9813 
9814 	if (phba->cfg_fcp_imax)
9815 		usdelay = LPFC_SEC_TO_USEC / phba->cfg_fcp_imax;
9816 	else
9817 		usdelay = 0;
9818 
9819 	for (qidx = 0; qidx < phba->cfg_irq_chann;
9820 	     qidx += LPFC_MAX_EQ_DELAY_EQID_CNT)
9821 		lpfc_modify_hba_eq_delay(phba, qidx, LPFC_MAX_EQ_DELAY_EQID_CNT,
9822 					 usdelay);
9823 
9824 	if (phba->sli4_hba.cq_max) {
9825 		kfree(phba->sli4_hba.cq_lookup);
9826 		phba->sli4_hba.cq_lookup = kcalloc((phba->sli4_hba.cq_max + 1),
9827 			sizeof(struct lpfc_queue *), GFP_KERNEL);
9828 		if (!phba->sli4_hba.cq_lookup) {
9829 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9830 					"0549 Failed setup of CQ Lookup table: "
9831 					"size 0x%x\n", phba->sli4_hba.cq_max);
9832 			rc = -ENOMEM;
9833 			goto out_destroy;
9834 		}
9835 		lpfc_setup_cq_lookup(phba);
9836 	}
9837 	return 0;
9838 
9839 out_destroy:
9840 	lpfc_sli4_queue_unset(phba);
9841 out_error:
9842 	return rc;
9843 }
9844 
9845 /**
9846  * lpfc_sli4_queue_unset - Unset all the SLI4 queues
9847  * @phba: pointer to lpfc hba data structure.
9848  *
9849  * This routine is invoked to unset all the SLI4 queues with the FCoE HBA
9850  * operation.
9851  *
9852  * Return codes
9853  *      0 - successful
9854  *      -ENOMEM - No available memory
9855  *      -EIO - The mailbox failed to complete successfully.
9856  **/
9857 void
9858 lpfc_sli4_queue_unset(struct lpfc_hba *phba)
9859 {
9860 	struct lpfc_sli4_hdw_queue *qp;
9861 	struct lpfc_queue *eq;
9862 	int qidx;
9863 
9864 	/* Unset mailbox command work queue */
9865 	if (phba->sli4_hba.mbx_wq)
9866 		lpfc_mq_destroy(phba, phba->sli4_hba.mbx_wq);
9867 
9868 	/* Unset NVME LS work queue */
9869 	if (phba->sli4_hba.nvmels_wq)
9870 		lpfc_wq_destroy(phba, phba->sli4_hba.nvmels_wq);
9871 
9872 	/* Unset ELS work queue */
9873 	if (phba->sli4_hba.els_wq)
9874 		lpfc_wq_destroy(phba, phba->sli4_hba.els_wq);
9875 
9876 	/* Unset unsolicited receive queue */
9877 	if (phba->sli4_hba.hdr_rq)
9878 		lpfc_rq_destroy(phba, phba->sli4_hba.hdr_rq,
9879 				phba->sli4_hba.dat_rq);
9880 
9881 	/* Unset mailbox command complete queue */
9882 	if (phba->sli4_hba.mbx_cq)
9883 		lpfc_cq_destroy(phba, phba->sli4_hba.mbx_cq);
9884 
9885 	/* Unset ELS complete queue */
9886 	if (phba->sli4_hba.els_cq)
9887 		lpfc_cq_destroy(phba, phba->sli4_hba.els_cq);
9888 
9889 	/* Unset NVME LS complete queue */
9890 	if (phba->sli4_hba.nvmels_cq)
9891 		lpfc_cq_destroy(phba, phba->sli4_hba.nvmels_cq);
9892 
9893 	if (phba->nvmet_support) {
9894 		/* Unset NVMET MRQ queue */
9895 		if (phba->sli4_hba.nvmet_mrq_hdr) {
9896 			for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++)
9897 				lpfc_rq_destroy(
9898 					phba,
9899 					phba->sli4_hba.nvmet_mrq_hdr[qidx],
9900 					phba->sli4_hba.nvmet_mrq_data[qidx]);
9901 		}
9902 
9903 		/* Unset NVMET CQ Set complete queue */
9904 		if (phba->sli4_hba.nvmet_cqset) {
9905 			for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++)
9906 				lpfc_cq_destroy(
9907 					phba, phba->sli4_hba.nvmet_cqset[qidx]);
9908 		}
9909 	}
9910 
9911 	/* Unset fast-path SLI4 queues */
9912 	if (phba->sli4_hba.hdwq) {
9913 		/* Loop thru all Hardware Queues */
9914 		for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
9915 			/* Destroy the CQ/WQ corresponding to Hardware Queue */
9916 			qp = &phba->sli4_hba.hdwq[qidx];
9917 			lpfc_wq_destroy(phba, qp->io_wq);
9918 			lpfc_cq_destroy(phba, qp->io_cq);
9919 		}
9920 		/* Loop thru all IRQ vectors */
9921 		for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
9922 			/* Destroy the EQ corresponding to the IRQ vector */
9923 			eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
9924 			lpfc_eq_destroy(phba, eq);
9925 		}
9926 	}
9927 
9928 	kfree(phba->sli4_hba.cq_lookup);
9929 	phba->sli4_hba.cq_lookup = NULL;
9930 	phba->sli4_hba.cq_max = 0;
9931 }
9932 
9933 /**
9934  * lpfc_sli4_cq_event_pool_create - Create completion-queue event free pool
9935  * @phba: pointer to lpfc hba data structure.
9936  *
9937  * This routine is invoked to allocate and set up a pool of completion queue
9938  * events. The body of the completion queue event is a completion queue entry
9939  * CQE. For now, this pool is used for the interrupt service routine to queue
9940  * the following HBA completion queue events for the worker thread to process:
9941  *   - Mailbox asynchronous events
9942  *   - Receive queue completion unsolicited events
9943  * Later, this can be used for all the slow-path events.
9944  *
9945  * Return codes
9946  *      0 - successful
9947  *      -ENOMEM - No available memory
9948  **/
9949 static int
9950 lpfc_sli4_cq_event_pool_create(struct lpfc_hba *phba)
9951 {
9952 	struct lpfc_cq_event *cq_event;
9953 	int i;
9954 
9955 	for (i = 0; i < (4 * phba->sli4_hba.cq_ecount); i++) {
9956 		cq_event = kmalloc(sizeof(struct lpfc_cq_event), GFP_KERNEL);
9957 		if (!cq_event)
9958 			goto out_pool_create_fail;
9959 		list_add_tail(&cq_event->list,
9960 			      &phba->sli4_hba.sp_cqe_event_pool);
9961 	}
9962 	return 0;
9963 
9964 out_pool_create_fail:
9965 	lpfc_sli4_cq_event_pool_destroy(phba);
9966 	return -ENOMEM;
9967 }
9968 
9969 /**
9970  * lpfc_sli4_cq_event_pool_destroy - Free completion-queue event free pool
9971  * @phba: pointer to lpfc hba data structure.
9972  *
9973  * This routine is invoked to free the pool of completion queue events at
9974  * driver unload time. Note that, it is the responsibility of the driver
9975  * cleanup routine to free all the outstanding completion-queue events
9976  * allocated from this pool back into the pool before invoking this routine
9977  * to destroy the pool.
9978  **/
9979 static void
9980 lpfc_sli4_cq_event_pool_destroy(struct lpfc_hba *phba)
9981 {
9982 	struct lpfc_cq_event *cq_event, *next_cq_event;
9983 
9984 	list_for_each_entry_safe(cq_event, next_cq_event,
9985 				 &phba->sli4_hba.sp_cqe_event_pool, list) {
9986 		list_del(&cq_event->list);
9987 		kfree(cq_event);
9988 	}
9989 }
9990 
9991 /**
9992  * __lpfc_sli4_cq_event_alloc - Allocate a completion-queue event from free pool
9993  * @phba: pointer to lpfc hba data structure.
9994  *
9995  * This routine is the lock free version of the API invoked to allocate a
9996  * completion-queue event from the free pool.
9997  *
9998  * Return: Pointer to the newly allocated completion-queue event if successful
9999  *         NULL otherwise.
10000  **/
10001 struct lpfc_cq_event *
10002 __lpfc_sli4_cq_event_alloc(struct lpfc_hba *phba)
10003 {
10004 	struct lpfc_cq_event *cq_event = NULL;
10005 
10006 	list_remove_head(&phba->sli4_hba.sp_cqe_event_pool, cq_event,
10007 			 struct lpfc_cq_event, list);
10008 	return cq_event;
10009 }
10010 
10011 /**
10012  * lpfc_sli4_cq_event_alloc - Allocate a completion-queue event from free pool
10013  * @phba: pointer to lpfc hba data structure.
10014  *
10015  * This routine is the lock version of the API invoked to allocate a
10016  * completion-queue event from the free pool.
10017  *
10018  * Return: Pointer to the newly allocated completion-queue event if successful
10019  *         NULL otherwise.
10020  **/
10021 struct lpfc_cq_event *
10022 lpfc_sli4_cq_event_alloc(struct lpfc_hba *phba)
10023 {
10024 	struct lpfc_cq_event *cq_event;
10025 	unsigned long iflags;
10026 
10027 	spin_lock_irqsave(&phba->hbalock, iflags);
10028 	cq_event = __lpfc_sli4_cq_event_alloc(phba);
10029 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10030 	return cq_event;
10031 }
10032 
10033 /**
10034  * __lpfc_sli4_cq_event_release - Release a completion-queue event to free pool
10035  * @phba: pointer to lpfc hba data structure.
10036  * @cq_event: pointer to the completion queue event to be freed.
10037  *
10038  * This routine is the lock free version of the API invoked to release a
10039  * completion-queue event back into the free pool.
10040  **/
10041 void
10042 __lpfc_sli4_cq_event_release(struct lpfc_hba *phba,
10043 			     struct lpfc_cq_event *cq_event)
10044 {
10045 	list_add_tail(&cq_event->list, &phba->sli4_hba.sp_cqe_event_pool);
10046 }
10047 
10048 /**
10049  * lpfc_sli4_cq_event_release - Release a completion-queue event to free pool
10050  * @phba: pointer to lpfc hba data structure.
10051  * @cq_event: pointer to the completion queue event to be freed.
10052  *
10053  * This routine is the lock version of the API invoked to release a
10054  * completion-queue event back into the free pool.
10055  **/
10056 void
10057 lpfc_sli4_cq_event_release(struct lpfc_hba *phba,
10058 			   struct lpfc_cq_event *cq_event)
10059 {
10060 	unsigned long iflags;
10061 	spin_lock_irqsave(&phba->hbalock, iflags);
10062 	__lpfc_sli4_cq_event_release(phba, cq_event);
10063 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10064 }
10065 
10066 /**
10067  * lpfc_sli4_cq_event_release_all - Release all cq events to the free pool
10068  * @phba: pointer to lpfc hba data structure.
10069  *
10070  * This routine is to free all the pending completion-queue events to the
10071  * back into the free pool for device reset.
10072  **/
10073 static void
10074 lpfc_sli4_cq_event_release_all(struct lpfc_hba *phba)
10075 {
10076 	LIST_HEAD(cqelist);
10077 	struct lpfc_cq_event *cqe;
10078 	unsigned long iflags;
10079 
10080 	/* Retrieve all the pending WCQEs from pending WCQE lists */
10081 	spin_lock_irqsave(&phba->hbalock, iflags);
10082 	/* Pending FCP XRI abort events */
10083 	list_splice_init(&phba->sli4_hba.sp_fcp_xri_aborted_work_queue,
10084 			 &cqelist);
10085 	/* Pending ELS XRI abort events */
10086 	list_splice_init(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
10087 			 &cqelist);
10088 	/* Pending asynnc events */
10089 	list_splice_init(&phba->sli4_hba.sp_asynce_work_queue,
10090 			 &cqelist);
10091 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10092 
10093 	while (!list_empty(&cqelist)) {
10094 		list_remove_head(&cqelist, cqe, struct lpfc_cq_event, list);
10095 		lpfc_sli4_cq_event_release(phba, cqe);
10096 	}
10097 }
10098 
10099 /**
10100  * lpfc_pci_function_reset - Reset pci function.
10101  * @phba: pointer to lpfc hba data structure.
10102  *
10103  * This routine is invoked to request a PCI function reset. It will destroys
10104  * all resources assigned to the PCI function which originates this request.
10105  *
10106  * Return codes
10107  *      0 - successful
10108  *      -ENOMEM - No available memory
10109  *      -EIO - The mailbox failed to complete successfully.
10110  **/
10111 int
10112 lpfc_pci_function_reset(struct lpfc_hba *phba)
10113 {
10114 	LPFC_MBOXQ_t *mboxq;
10115 	uint32_t rc = 0, if_type;
10116 	uint32_t shdr_status, shdr_add_status;
10117 	uint32_t rdy_chk;
10118 	uint32_t port_reset = 0;
10119 	union lpfc_sli4_cfg_shdr *shdr;
10120 	struct lpfc_register reg_data;
10121 	uint16_t devid;
10122 
10123 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
10124 	switch (if_type) {
10125 	case LPFC_SLI_INTF_IF_TYPE_0:
10126 		mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
10127 						       GFP_KERNEL);
10128 		if (!mboxq) {
10129 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10130 					"0494 Unable to allocate memory for "
10131 					"issuing SLI_FUNCTION_RESET mailbox "
10132 					"command\n");
10133 			return -ENOMEM;
10134 		}
10135 
10136 		/* Setup PCI function reset mailbox-ioctl command */
10137 		lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
10138 				 LPFC_MBOX_OPCODE_FUNCTION_RESET, 0,
10139 				 LPFC_SLI4_MBX_EMBED);
10140 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
10141 		shdr = (union lpfc_sli4_cfg_shdr *)
10142 			&mboxq->u.mqe.un.sli4_config.header.cfg_shdr;
10143 		shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
10144 		shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
10145 					 &shdr->response);
10146 		if (rc != MBX_TIMEOUT)
10147 			mempool_free(mboxq, phba->mbox_mem_pool);
10148 		if (shdr_status || shdr_add_status || rc) {
10149 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10150 					"0495 SLI_FUNCTION_RESET mailbox "
10151 					"failed with status x%x add_status x%x,"
10152 					" mbx status x%x\n",
10153 					shdr_status, shdr_add_status, rc);
10154 			rc = -ENXIO;
10155 		}
10156 		break;
10157 	case LPFC_SLI_INTF_IF_TYPE_2:
10158 	case LPFC_SLI_INTF_IF_TYPE_6:
10159 wait:
10160 		/*
10161 		 * Poll the Port Status Register and wait for RDY for
10162 		 * up to 30 seconds. If the port doesn't respond, treat
10163 		 * it as an error.
10164 		 */
10165 		for (rdy_chk = 0; rdy_chk < 1500; rdy_chk++) {
10166 			if (lpfc_readl(phba->sli4_hba.u.if_type2.
10167 				STATUSregaddr, &reg_data.word0)) {
10168 				rc = -ENODEV;
10169 				goto out;
10170 			}
10171 			if (bf_get(lpfc_sliport_status_rdy, &reg_data))
10172 				break;
10173 			msleep(20);
10174 		}
10175 
10176 		if (!bf_get(lpfc_sliport_status_rdy, &reg_data)) {
10177 			phba->work_status[0] = readl(
10178 				phba->sli4_hba.u.if_type2.ERR1regaddr);
10179 			phba->work_status[1] = readl(
10180 				phba->sli4_hba.u.if_type2.ERR2regaddr);
10181 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10182 					"2890 Port not ready, port status reg "
10183 					"0x%x error 1=0x%x, error 2=0x%x\n",
10184 					reg_data.word0,
10185 					phba->work_status[0],
10186 					phba->work_status[1]);
10187 			rc = -ENODEV;
10188 			goto out;
10189 		}
10190 
10191 		if (!port_reset) {
10192 			/*
10193 			 * Reset the port now
10194 			 */
10195 			reg_data.word0 = 0;
10196 			bf_set(lpfc_sliport_ctrl_end, &reg_data,
10197 			       LPFC_SLIPORT_LITTLE_ENDIAN);
10198 			bf_set(lpfc_sliport_ctrl_ip, &reg_data,
10199 			       LPFC_SLIPORT_INIT_PORT);
10200 			writel(reg_data.word0, phba->sli4_hba.u.if_type2.
10201 			       CTRLregaddr);
10202 			/* flush */
10203 			pci_read_config_word(phba->pcidev,
10204 					     PCI_DEVICE_ID, &devid);
10205 
10206 			port_reset = 1;
10207 			msleep(20);
10208 			goto wait;
10209 		} else if (bf_get(lpfc_sliport_status_rn, &reg_data)) {
10210 			rc = -ENODEV;
10211 			goto out;
10212 		}
10213 		break;
10214 
10215 	case LPFC_SLI_INTF_IF_TYPE_1:
10216 	default:
10217 		break;
10218 	}
10219 
10220 out:
10221 	/* Catch the not-ready port failure after a port reset. */
10222 	if (rc) {
10223 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10224 				"3317 HBA not functional: IP Reset Failed "
10225 				"try: echo fw_reset > board_mode\n");
10226 		rc = -ENODEV;
10227 	}
10228 
10229 	return rc;
10230 }
10231 
10232 /**
10233  * lpfc_sli4_pci_mem_setup - Setup SLI4 HBA PCI memory space.
10234  * @phba: pointer to lpfc hba data structure.
10235  *
10236  * This routine is invoked to set up the PCI device memory space for device
10237  * with SLI-4 interface spec.
10238  *
10239  * Return codes
10240  * 	0 - successful
10241  * 	other values - error
10242  **/
10243 static int
10244 lpfc_sli4_pci_mem_setup(struct lpfc_hba *phba)
10245 {
10246 	struct pci_dev *pdev = phba->pcidev;
10247 	unsigned long bar0map_len, bar1map_len, bar2map_len;
10248 	int error;
10249 	uint32_t if_type;
10250 
10251 	if (!pdev)
10252 		return -ENODEV;
10253 
10254 	/* Set the device DMA mask size */
10255 	error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
10256 	if (error)
10257 		error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32));
10258 	if (error)
10259 		return error;
10260 
10261 	/*
10262 	 * The BARs and register set definitions and offset locations are
10263 	 * dependent on the if_type.
10264 	 */
10265 	if (pci_read_config_dword(pdev, LPFC_SLI_INTF,
10266 				  &phba->sli4_hba.sli_intf.word0)) {
10267 		return -ENODEV;
10268 	}
10269 
10270 	/* There is no SLI3 failback for SLI4 devices. */
10271 	if (bf_get(lpfc_sli_intf_valid, &phba->sli4_hba.sli_intf) !=
10272 	    LPFC_SLI_INTF_VALID) {
10273 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10274 				"2894 SLI_INTF reg contents invalid "
10275 				"sli_intf reg 0x%x\n",
10276 				phba->sli4_hba.sli_intf.word0);
10277 		return -ENODEV;
10278 	}
10279 
10280 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
10281 	/*
10282 	 * Get the bus address of SLI4 device Bar regions and the
10283 	 * number of bytes required by each mapping. The mapping of the
10284 	 * particular PCI BARs regions is dependent on the type of
10285 	 * SLI4 device.
10286 	 */
10287 	if (pci_resource_start(pdev, PCI_64BIT_BAR0)) {
10288 		phba->pci_bar0_map = pci_resource_start(pdev, PCI_64BIT_BAR0);
10289 		bar0map_len = pci_resource_len(pdev, PCI_64BIT_BAR0);
10290 
10291 		/*
10292 		 * Map SLI4 PCI Config Space Register base to a kernel virtual
10293 		 * addr
10294 		 */
10295 		phba->sli4_hba.conf_regs_memmap_p =
10296 			ioremap(phba->pci_bar0_map, bar0map_len);
10297 		if (!phba->sli4_hba.conf_regs_memmap_p) {
10298 			dev_printk(KERN_ERR, &pdev->dev,
10299 				   "ioremap failed for SLI4 PCI config "
10300 				   "registers.\n");
10301 			return -ENODEV;
10302 		}
10303 		phba->pci_bar0_memmap_p = phba->sli4_hba.conf_regs_memmap_p;
10304 		/* Set up BAR0 PCI config space register memory map */
10305 		lpfc_sli4_bar0_register_memmap(phba, if_type);
10306 	} else {
10307 		phba->pci_bar0_map = pci_resource_start(pdev, 1);
10308 		bar0map_len = pci_resource_len(pdev, 1);
10309 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
10310 			dev_printk(KERN_ERR, &pdev->dev,
10311 			   "FATAL - No BAR0 mapping for SLI4, if_type 2\n");
10312 			return -ENODEV;
10313 		}
10314 		phba->sli4_hba.conf_regs_memmap_p =
10315 				ioremap(phba->pci_bar0_map, bar0map_len);
10316 		if (!phba->sli4_hba.conf_regs_memmap_p) {
10317 			dev_printk(KERN_ERR, &pdev->dev,
10318 				"ioremap failed for SLI4 PCI config "
10319 				"registers.\n");
10320 			return -ENODEV;
10321 		}
10322 		lpfc_sli4_bar0_register_memmap(phba, if_type);
10323 	}
10324 
10325 	if (if_type == LPFC_SLI_INTF_IF_TYPE_0) {
10326 		if (pci_resource_start(pdev, PCI_64BIT_BAR2)) {
10327 			/*
10328 			 * Map SLI4 if type 0 HBA Control Register base to a
10329 			 * kernel virtual address and setup the registers.
10330 			 */
10331 			phba->pci_bar1_map = pci_resource_start(pdev,
10332 								PCI_64BIT_BAR2);
10333 			bar1map_len = pci_resource_len(pdev, PCI_64BIT_BAR2);
10334 			phba->sli4_hba.ctrl_regs_memmap_p =
10335 					ioremap(phba->pci_bar1_map,
10336 						bar1map_len);
10337 			if (!phba->sli4_hba.ctrl_regs_memmap_p) {
10338 				dev_err(&pdev->dev,
10339 					   "ioremap failed for SLI4 HBA "
10340 					    "control registers.\n");
10341 				error = -ENOMEM;
10342 				goto out_iounmap_conf;
10343 			}
10344 			phba->pci_bar2_memmap_p =
10345 					 phba->sli4_hba.ctrl_regs_memmap_p;
10346 			lpfc_sli4_bar1_register_memmap(phba, if_type);
10347 		} else {
10348 			error = -ENOMEM;
10349 			goto out_iounmap_conf;
10350 		}
10351 	}
10352 
10353 	if ((if_type == LPFC_SLI_INTF_IF_TYPE_6) &&
10354 	    (pci_resource_start(pdev, PCI_64BIT_BAR2))) {
10355 		/*
10356 		 * Map SLI4 if type 6 HBA Doorbell Register base to a kernel
10357 		 * virtual address and setup the registers.
10358 		 */
10359 		phba->pci_bar1_map = pci_resource_start(pdev, PCI_64BIT_BAR2);
10360 		bar1map_len = pci_resource_len(pdev, PCI_64BIT_BAR2);
10361 		phba->sli4_hba.drbl_regs_memmap_p =
10362 				ioremap(phba->pci_bar1_map, bar1map_len);
10363 		if (!phba->sli4_hba.drbl_regs_memmap_p) {
10364 			dev_err(&pdev->dev,
10365 			   "ioremap failed for SLI4 HBA doorbell registers.\n");
10366 			error = -ENOMEM;
10367 			goto out_iounmap_conf;
10368 		}
10369 		phba->pci_bar2_memmap_p = phba->sli4_hba.drbl_regs_memmap_p;
10370 		lpfc_sli4_bar1_register_memmap(phba, if_type);
10371 	}
10372 
10373 	if (if_type == LPFC_SLI_INTF_IF_TYPE_0) {
10374 		if (pci_resource_start(pdev, PCI_64BIT_BAR4)) {
10375 			/*
10376 			 * Map SLI4 if type 0 HBA Doorbell Register base to
10377 			 * a kernel virtual address and setup the registers.
10378 			 */
10379 			phba->pci_bar2_map = pci_resource_start(pdev,
10380 								PCI_64BIT_BAR4);
10381 			bar2map_len = pci_resource_len(pdev, PCI_64BIT_BAR4);
10382 			phba->sli4_hba.drbl_regs_memmap_p =
10383 					ioremap(phba->pci_bar2_map,
10384 						bar2map_len);
10385 			if (!phba->sli4_hba.drbl_regs_memmap_p) {
10386 				dev_err(&pdev->dev,
10387 					   "ioremap failed for SLI4 HBA"
10388 					   " doorbell registers.\n");
10389 				error = -ENOMEM;
10390 				goto out_iounmap_ctrl;
10391 			}
10392 			phba->pci_bar4_memmap_p =
10393 					phba->sli4_hba.drbl_regs_memmap_p;
10394 			error = lpfc_sli4_bar2_register_memmap(phba, LPFC_VF0);
10395 			if (error)
10396 				goto out_iounmap_all;
10397 		} else {
10398 			error = -ENOMEM;
10399 			goto out_iounmap_all;
10400 		}
10401 	}
10402 
10403 	if (if_type == LPFC_SLI_INTF_IF_TYPE_6 &&
10404 	    pci_resource_start(pdev, PCI_64BIT_BAR4)) {
10405 		/*
10406 		 * Map SLI4 if type 6 HBA DPP Register base to a kernel
10407 		 * virtual address and setup the registers.
10408 		 */
10409 		phba->pci_bar2_map = pci_resource_start(pdev, PCI_64BIT_BAR4);
10410 		bar2map_len = pci_resource_len(pdev, PCI_64BIT_BAR4);
10411 		phba->sli4_hba.dpp_regs_memmap_p =
10412 				ioremap(phba->pci_bar2_map, bar2map_len);
10413 		if (!phba->sli4_hba.dpp_regs_memmap_p) {
10414 			dev_err(&pdev->dev,
10415 			   "ioremap failed for SLI4 HBA dpp registers.\n");
10416 			error = -ENOMEM;
10417 			goto out_iounmap_ctrl;
10418 		}
10419 		phba->pci_bar4_memmap_p = phba->sli4_hba.dpp_regs_memmap_p;
10420 	}
10421 
10422 	/* Set up the EQ/CQ register handeling functions now */
10423 	switch (if_type) {
10424 	case LPFC_SLI_INTF_IF_TYPE_0:
10425 	case LPFC_SLI_INTF_IF_TYPE_2:
10426 		phba->sli4_hba.sli4_eq_clr_intr = lpfc_sli4_eq_clr_intr;
10427 		phba->sli4_hba.sli4_write_eq_db = lpfc_sli4_write_eq_db;
10428 		phba->sli4_hba.sli4_write_cq_db = lpfc_sli4_write_cq_db;
10429 		break;
10430 	case LPFC_SLI_INTF_IF_TYPE_6:
10431 		phba->sli4_hba.sli4_eq_clr_intr = lpfc_sli4_if6_eq_clr_intr;
10432 		phba->sli4_hba.sli4_write_eq_db = lpfc_sli4_if6_write_eq_db;
10433 		phba->sli4_hba.sli4_write_cq_db = lpfc_sli4_if6_write_cq_db;
10434 		break;
10435 	default:
10436 		break;
10437 	}
10438 
10439 	return 0;
10440 
10441 out_iounmap_all:
10442 	iounmap(phba->sli4_hba.drbl_regs_memmap_p);
10443 out_iounmap_ctrl:
10444 	iounmap(phba->sli4_hba.ctrl_regs_memmap_p);
10445 out_iounmap_conf:
10446 	iounmap(phba->sli4_hba.conf_regs_memmap_p);
10447 
10448 	return error;
10449 }
10450 
10451 /**
10452  * lpfc_sli4_pci_mem_unset - Unset SLI4 HBA PCI memory space.
10453  * @phba: pointer to lpfc hba data structure.
10454  *
10455  * This routine is invoked to unset the PCI device memory space for device
10456  * with SLI-4 interface spec.
10457  **/
10458 static void
10459 lpfc_sli4_pci_mem_unset(struct lpfc_hba *phba)
10460 {
10461 	uint32_t if_type;
10462 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
10463 
10464 	switch (if_type) {
10465 	case LPFC_SLI_INTF_IF_TYPE_0:
10466 		iounmap(phba->sli4_hba.drbl_regs_memmap_p);
10467 		iounmap(phba->sli4_hba.ctrl_regs_memmap_p);
10468 		iounmap(phba->sli4_hba.conf_regs_memmap_p);
10469 		break;
10470 	case LPFC_SLI_INTF_IF_TYPE_2:
10471 		iounmap(phba->sli4_hba.conf_regs_memmap_p);
10472 		break;
10473 	case LPFC_SLI_INTF_IF_TYPE_6:
10474 		iounmap(phba->sli4_hba.drbl_regs_memmap_p);
10475 		iounmap(phba->sli4_hba.conf_regs_memmap_p);
10476 		if (phba->sli4_hba.dpp_regs_memmap_p)
10477 			iounmap(phba->sli4_hba.dpp_regs_memmap_p);
10478 		break;
10479 	case LPFC_SLI_INTF_IF_TYPE_1:
10480 	default:
10481 		dev_printk(KERN_ERR, &phba->pcidev->dev,
10482 			   "FATAL - unsupported SLI4 interface type - %d\n",
10483 			   if_type);
10484 		break;
10485 	}
10486 }
10487 
10488 /**
10489  * lpfc_sli_enable_msix - Enable MSI-X interrupt mode on SLI-3 device
10490  * @phba: pointer to lpfc hba data structure.
10491  *
10492  * This routine is invoked to enable the MSI-X interrupt vectors to device
10493  * with SLI-3 interface specs.
10494  *
10495  * Return codes
10496  *   0 - successful
10497  *   other values - error
10498  **/
10499 static int
10500 lpfc_sli_enable_msix(struct lpfc_hba *phba)
10501 {
10502 	int rc;
10503 	LPFC_MBOXQ_t *pmb;
10504 
10505 	/* Set up MSI-X multi-message vectors */
10506 	rc = pci_alloc_irq_vectors(phba->pcidev,
10507 			LPFC_MSIX_VECTORS, LPFC_MSIX_VECTORS, PCI_IRQ_MSIX);
10508 	if (rc < 0) {
10509 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
10510 				"0420 PCI enable MSI-X failed (%d)\n", rc);
10511 		goto vec_fail_out;
10512 	}
10513 
10514 	/*
10515 	 * Assign MSI-X vectors to interrupt handlers
10516 	 */
10517 
10518 	/* vector-0 is associated to slow-path handler */
10519 	rc = request_irq(pci_irq_vector(phba->pcidev, 0),
10520 			 &lpfc_sli_sp_intr_handler, 0,
10521 			 LPFC_SP_DRIVER_HANDLER_NAME, phba);
10522 	if (rc) {
10523 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
10524 				"0421 MSI-X slow-path request_irq failed "
10525 				"(%d)\n", rc);
10526 		goto msi_fail_out;
10527 	}
10528 
10529 	/* vector-1 is associated to fast-path handler */
10530 	rc = request_irq(pci_irq_vector(phba->pcidev, 1),
10531 			 &lpfc_sli_fp_intr_handler, 0,
10532 			 LPFC_FP_DRIVER_HANDLER_NAME, phba);
10533 
10534 	if (rc) {
10535 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
10536 				"0429 MSI-X fast-path request_irq failed "
10537 				"(%d)\n", rc);
10538 		goto irq_fail_out;
10539 	}
10540 
10541 	/*
10542 	 * Configure HBA MSI-X attention conditions to messages
10543 	 */
10544 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
10545 
10546 	if (!pmb) {
10547 		rc = -ENOMEM;
10548 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10549 				"0474 Unable to allocate memory for issuing "
10550 				"MBOX_CONFIG_MSI command\n");
10551 		goto mem_fail_out;
10552 	}
10553 	rc = lpfc_config_msi(phba, pmb);
10554 	if (rc)
10555 		goto mbx_fail_out;
10556 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
10557 	if (rc != MBX_SUCCESS) {
10558 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX,
10559 				"0351 Config MSI mailbox command failed, "
10560 				"mbxCmd x%x, mbxStatus x%x\n",
10561 				pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus);
10562 		goto mbx_fail_out;
10563 	}
10564 
10565 	/* Free memory allocated for mailbox command */
10566 	mempool_free(pmb, phba->mbox_mem_pool);
10567 	return rc;
10568 
10569 mbx_fail_out:
10570 	/* Free memory allocated for mailbox command */
10571 	mempool_free(pmb, phba->mbox_mem_pool);
10572 
10573 mem_fail_out:
10574 	/* free the irq already requested */
10575 	free_irq(pci_irq_vector(phba->pcidev, 1), phba);
10576 
10577 irq_fail_out:
10578 	/* free the irq already requested */
10579 	free_irq(pci_irq_vector(phba->pcidev, 0), phba);
10580 
10581 msi_fail_out:
10582 	/* Unconfigure MSI-X capability structure */
10583 	pci_free_irq_vectors(phba->pcidev);
10584 
10585 vec_fail_out:
10586 	return rc;
10587 }
10588 
10589 /**
10590  * lpfc_sli_enable_msi - Enable MSI interrupt mode on SLI-3 device.
10591  * @phba: pointer to lpfc hba data structure.
10592  *
10593  * This routine is invoked to enable the MSI interrupt mode to device with
10594  * SLI-3 interface spec. The kernel function pci_enable_msi() is called to
10595  * enable the MSI vector. The device driver is responsible for calling the
10596  * request_irq() to register MSI vector with a interrupt the handler, which
10597  * is done in this function.
10598  *
10599  * Return codes
10600  * 	0 - successful
10601  * 	other values - error
10602  */
10603 static int
10604 lpfc_sli_enable_msi(struct lpfc_hba *phba)
10605 {
10606 	int rc;
10607 
10608 	rc = pci_enable_msi(phba->pcidev);
10609 	if (!rc)
10610 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
10611 				"0462 PCI enable MSI mode success.\n");
10612 	else {
10613 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
10614 				"0471 PCI enable MSI mode failed (%d)\n", rc);
10615 		return rc;
10616 	}
10617 
10618 	rc = request_irq(phba->pcidev->irq, lpfc_sli_intr_handler,
10619 			 0, LPFC_DRIVER_NAME, phba);
10620 	if (rc) {
10621 		pci_disable_msi(phba->pcidev);
10622 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
10623 				"0478 MSI request_irq failed (%d)\n", rc);
10624 	}
10625 	return rc;
10626 }
10627 
10628 /**
10629  * lpfc_sli_enable_intr - Enable device interrupt to SLI-3 device.
10630  * @phba: pointer to lpfc hba data structure.
10631  *
10632  * This routine is invoked to enable device interrupt and associate driver's
10633  * interrupt handler(s) to interrupt vector(s) to device with SLI-3 interface
10634  * spec. Depends on the interrupt mode configured to the driver, the driver
10635  * will try to fallback from the configured interrupt mode to an interrupt
10636  * mode which is supported by the platform, kernel, and device in the order
10637  * of:
10638  * MSI-X -> MSI -> IRQ.
10639  *
10640  * Return codes
10641  *   0 - successful
10642  *   other values - error
10643  **/
10644 static uint32_t
10645 lpfc_sli_enable_intr(struct lpfc_hba *phba, uint32_t cfg_mode)
10646 {
10647 	uint32_t intr_mode = LPFC_INTR_ERROR;
10648 	int retval;
10649 
10650 	if (cfg_mode == 2) {
10651 		/* Need to issue conf_port mbox cmd before conf_msi mbox cmd */
10652 		retval = lpfc_sli_config_port(phba, LPFC_SLI_REV3);
10653 		if (!retval) {
10654 			/* Now, try to enable MSI-X interrupt mode */
10655 			retval = lpfc_sli_enable_msix(phba);
10656 			if (!retval) {
10657 				/* Indicate initialization to MSI-X mode */
10658 				phba->intr_type = MSIX;
10659 				intr_mode = 2;
10660 			}
10661 		}
10662 	}
10663 
10664 	/* Fallback to MSI if MSI-X initialization failed */
10665 	if (cfg_mode >= 1 && phba->intr_type == NONE) {
10666 		retval = lpfc_sli_enable_msi(phba);
10667 		if (!retval) {
10668 			/* Indicate initialization to MSI mode */
10669 			phba->intr_type = MSI;
10670 			intr_mode = 1;
10671 		}
10672 	}
10673 
10674 	/* Fallback to INTx if both MSI-X/MSI initalization failed */
10675 	if (phba->intr_type == NONE) {
10676 		retval = request_irq(phba->pcidev->irq, lpfc_sli_intr_handler,
10677 				     IRQF_SHARED, LPFC_DRIVER_NAME, phba);
10678 		if (!retval) {
10679 			/* Indicate initialization to INTx mode */
10680 			phba->intr_type = INTx;
10681 			intr_mode = 0;
10682 		}
10683 	}
10684 	return intr_mode;
10685 }
10686 
10687 /**
10688  * lpfc_sli_disable_intr - Disable device interrupt to SLI-3 device.
10689  * @phba: pointer to lpfc hba data structure.
10690  *
10691  * This routine is invoked to disable device interrupt and disassociate the
10692  * driver's interrupt handler(s) from interrupt vector(s) to device with
10693  * SLI-3 interface spec. Depending on the interrupt mode, the driver will
10694  * release the interrupt vector(s) for the message signaled interrupt.
10695  **/
10696 static void
10697 lpfc_sli_disable_intr(struct lpfc_hba *phba)
10698 {
10699 	int nr_irqs, i;
10700 
10701 	if (phba->intr_type == MSIX)
10702 		nr_irqs = LPFC_MSIX_VECTORS;
10703 	else
10704 		nr_irqs = 1;
10705 
10706 	for (i = 0; i < nr_irqs; i++)
10707 		free_irq(pci_irq_vector(phba->pcidev, i), phba);
10708 	pci_free_irq_vectors(phba->pcidev);
10709 
10710 	/* Reset interrupt management states */
10711 	phba->intr_type = NONE;
10712 	phba->sli.slistat.sli_intr = 0;
10713 }
10714 
10715 /**
10716  * lpfc_find_cpu_handle - Find the CPU that corresponds to the specified Queue
10717  * @phba: pointer to lpfc hba data structure.
10718  * @id: EQ vector index or Hardware Queue index
10719  * @match: LPFC_FIND_BY_EQ = match by EQ
10720  *         LPFC_FIND_BY_HDWQ = match by Hardware Queue
10721  * Return the CPU that matches the selection criteria
10722  */
10723 static uint16_t
10724 lpfc_find_cpu_handle(struct lpfc_hba *phba, uint16_t id, int match)
10725 {
10726 	struct lpfc_vector_map_info *cpup;
10727 	int cpu;
10728 
10729 	/* Loop through all CPUs */
10730 	for_each_present_cpu(cpu) {
10731 		cpup = &phba->sli4_hba.cpu_map[cpu];
10732 
10733 		/* If we are matching by EQ, there may be multiple CPUs using
10734 		 * using the same vector, so select the one with
10735 		 * LPFC_CPU_FIRST_IRQ set.
10736 		 */
10737 		if ((match == LPFC_FIND_BY_EQ) &&
10738 		    (cpup->flag & LPFC_CPU_FIRST_IRQ) &&
10739 		    (cpup->eq == id))
10740 			return cpu;
10741 
10742 		/* If matching by HDWQ, select the first CPU that matches */
10743 		if ((match == LPFC_FIND_BY_HDWQ) && (cpup->hdwq == id))
10744 			return cpu;
10745 	}
10746 	return 0;
10747 }
10748 
10749 #ifdef CONFIG_X86
10750 /**
10751  * lpfc_find_hyper - Determine if the CPU map entry is hyper-threaded
10752  * @phba: pointer to lpfc hba data structure.
10753  * @cpu: CPU map index
10754  * @phys_id: CPU package physical id
10755  * @core_id: CPU core id
10756  */
10757 static int
10758 lpfc_find_hyper(struct lpfc_hba *phba, int cpu,
10759 		uint16_t phys_id, uint16_t core_id)
10760 {
10761 	struct lpfc_vector_map_info *cpup;
10762 	int idx;
10763 
10764 	for_each_present_cpu(idx) {
10765 		cpup = &phba->sli4_hba.cpu_map[idx];
10766 		/* Does the cpup match the one we are looking for */
10767 		if ((cpup->phys_id == phys_id) &&
10768 		    (cpup->core_id == core_id) &&
10769 		    (cpu != idx))
10770 			return 1;
10771 	}
10772 	return 0;
10773 }
10774 #endif
10775 
10776 /*
10777  * lpfc_assign_eq_map_info - Assigns eq for vector_map structure
10778  * @phba: pointer to lpfc hba data structure.
10779  * @eqidx: index for eq and irq vector
10780  * @flag: flags to set for vector_map structure
10781  * @cpu: cpu used to index vector_map structure
10782  *
10783  * The routine assigns eq info into vector_map structure
10784  */
10785 static inline void
10786 lpfc_assign_eq_map_info(struct lpfc_hba *phba, uint16_t eqidx, uint16_t flag,
10787 			unsigned int cpu)
10788 {
10789 	struct lpfc_vector_map_info *cpup = &phba->sli4_hba.cpu_map[cpu];
10790 	struct lpfc_hba_eq_hdl *eqhdl = lpfc_get_eq_hdl(eqidx);
10791 
10792 	cpup->eq = eqidx;
10793 	cpup->flag |= flag;
10794 
10795 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
10796 			"3336 Set Affinity: CPU %d irq %d eq %d flag x%x\n",
10797 			cpu, eqhdl->irq, cpup->eq, cpup->flag);
10798 }
10799 
10800 /**
10801  * lpfc_cpu_map_array_init - Initialize cpu_map structure
10802  * @phba: pointer to lpfc hba data structure.
10803  *
10804  * The routine initializes the cpu_map array structure
10805  */
10806 static void
10807 lpfc_cpu_map_array_init(struct lpfc_hba *phba)
10808 {
10809 	struct lpfc_vector_map_info *cpup;
10810 	struct lpfc_eq_intr_info *eqi;
10811 	int cpu;
10812 
10813 	for_each_possible_cpu(cpu) {
10814 		cpup = &phba->sli4_hba.cpu_map[cpu];
10815 		cpup->phys_id = LPFC_VECTOR_MAP_EMPTY;
10816 		cpup->core_id = LPFC_VECTOR_MAP_EMPTY;
10817 		cpup->hdwq = LPFC_VECTOR_MAP_EMPTY;
10818 		cpup->eq = LPFC_VECTOR_MAP_EMPTY;
10819 		cpup->flag = 0;
10820 		eqi = per_cpu_ptr(phba->sli4_hba.eq_info, cpu);
10821 		INIT_LIST_HEAD(&eqi->list);
10822 		eqi->icnt = 0;
10823 	}
10824 }
10825 
10826 /**
10827  * lpfc_hba_eq_hdl_array_init - Initialize hba_eq_hdl structure
10828  * @phba: pointer to lpfc hba data structure.
10829  *
10830  * The routine initializes the hba_eq_hdl array structure
10831  */
10832 static void
10833 lpfc_hba_eq_hdl_array_init(struct lpfc_hba *phba)
10834 {
10835 	struct lpfc_hba_eq_hdl *eqhdl;
10836 	int i;
10837 
10838 	for (i = 0; i < phba->cfg_irq_chann; i++) {
10839 		eqhdl = lpfc_get_eq_hdl(i);
10840 		eqhdl->irq = LPFC_VECTOR_MAP_EMPTY;
10841 		eqhdl->phba = phba;
10842 	}
10843 }
10844 
10845 /**
10846  * lpfc_cpu_affinity_check - Check vector CPU affinity mappings
10847  * @phba: pointer to lpfc hba data structure.
10848  * @vectors: number of msix vectors allocated.
10849  *
10850  * The routine will figure out the CPU affinity assignment for every
10851  * MSI-X vector allocated for the HBA.
10852  * In addition, the CPU to IO channel mapping will be calculated
10853  * and the phba->sli4_hba.cpu_map array will reflect this.
10854  */
10855 static void
10856 lpfc_cpu_affinity_check(struct lpfc_hba *phba, int vectors)
10857 {
10858 	int i, cpu, idx, next_idx, new_cpu, start_cpu, first_cpu;
10859 	int max_phys_id, min_phys_id;
10860 	int max_core_id, min_core_id;
10861 	struct lpfc_vector_map_info *cpup;
10862 	struct lpfc_vector_map_info *new_cpup;
10863 #ifdef CONFIG_X86
10864 	struct cpuinfo_x86 *cpuinfo;
10865 #endif
10866 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
10867 	struct lpfc_hdwq_stat *c_stat;
10868 #endif
10869 
10870 	max_phys_id = 0;
10871 	min_phys_id = LPFC_VECTOR_MAP_EMPTY;
10872 	max_core_id = 0;
10873 	min_core_id = LPFC_VECTOR_MAP_EMPTY;
10874 
10875 	/* Update CPU map with physical id and core id of each CPU */
10876 	for_each_present_cpu(cpu) {
10877 		cpup = &phba->sli4_hba.cpu_map[cpu];
10878 #ifdef CONFIG_X86
10879 		cpuinfo = &cpu_data(cpu);
10880 		cpup->phys_id = cpuinfo->phys_proc_id;
10881 		cpup->core_id = cpuinfo->cpu_core_id;
10882 		if (lpfc_find_hyper(phba, cpu, cpup->phys_id, cpup->core_id))
10883 			cpup->flag |= LPFC_CPU_MAP_HYPER;
10884 #else
10885 		/* No distinction between CPUs for other platforms */
10886 		cpup->phys_id = 0;
10887 		cpup->core_id = cpu;
10888 #endif
10889 
10890 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
10891 				"3328 CPU %d physid %d coreid %d flag x%x\n",
10892 				cpu, cpup->phys_id, cpup->core_id, cpup->flag);
10893 
10894 		if (cpup->phys_id > max_phys_id)
10895 			max_phys_id = cpup->phys_id;
10896 		if (cpup->phys_id < min_phys_id)
10897 			min_phys_id = cpup->phys_id;
10898 
10899 		if (cpup->core_id > max_core_id)
10900 			max_core_id = cpup->core_id;
10901 		if (cpup->core_id < min_core_id)
10902 			min_core_id = cpup->core_id;
10903 	}
10904 
10905 	/* After looking at each irq vector assigned to this pcidev, its
10906 	 * possible to see that not ALL CPUs have been accounted for.
10907 	 * Next we will set any unassigned (unaffinitized) cpu map
10908 	 * entries to a IRQ on the same phys_id.
10909 	 */
10910 	first_cpu = cpumask_first(cpu_present_mask);
10911 	start_cpu = first_cpu;
10912 
10913 	for_each_present_cpu(cpu) {
10914 		cpup = &phba->sli4_hba.cpu_map[cpu];
10915 
10916 		/* Is this CPU entry unassigned */
10917 		if (cpup->eq == LPFC_VECTOR_MAP_EMPTY) {
10918 			/* Mark CPU as IRQ not assigned by the kernel */
10919 			cpup->flag |= LPFC_CPU_MAP_UNASSIGN;
10920 
10921 			/* If so, find a new_cpup thats on the the SAME
10922 			 * phys_id as cpup. start_cpu will start where we
10923 			 * left off so all unassigned entries don't get assgined
10924 			 * the IRQ of the first entry.
10925 			 */
10926 			new_cpu = start_cpu;
10927 			for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
10928 				new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
10929 				if (!(new_cpup->flag & LPFC_CPU_MAP_UNASSIGN) &&
10930 				    (new_cpup->eq != LPFC_VECTOR_MAP_EMPTY) &&
10931 				    (new_cpup->phys_id == cpup->phys_id))
10932 					goto found_same;
10933 				new_cpu = cpumask_next(
10934 					new_cpu, cpu_present_mask);
10935 				if (new_cpu == nr_cpumask_bits)
10936 					new_cpu = first_cpu;
10937 			}
10938 			/* At this point, we leave the CPU as unassigned */
10939 			continue;
10940 found_same:
10941 			/* We found a matching phys_id, so copy the IRQ info */
10942 			cpup->eq = new_cpup->eq;
10943 
10944 			/* Bump start_cpu to the next slot to minmize the
10945 			 * chance of having multiple unassigned CPU entries
10946 			 * selecting the same IRQ.
10947 			 */
10948 			start_cpu = cpumask_next(new_cpu, cpu_present_mask);
10949 			if (start_cpu == nr_cpumask_bits)
10950 				start_cpu = first_cpu;
10951 
10952 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
10953 					"3337 Set Affinity: CPU %d "
10954 					"eq %d from peer cpu %d same "
10955 					"phys_id (%d)\n",
10956 					cpu, cpup->eq, new_cpu,
10957 					cpup->phys_id);
10958 		}
10959 	}
10960 
10961 	/* Set any unassigned cpu map entries to a IRQ on any phys_id */
10962 	start_cpu = first_cpu;
10963 
10964 	for_each_present_cpu(cpu) {
10965 		cpup = &phba->sli4_hba.cpu_map[cpu];
10966 
10967 		/* Is this entry unassigned */
10968 		if (cpup->eq == LPFC_VECTOR_MAP_EMPTY) {
10969 			/* Mark it as IRQ not assigned by the kernel */
10970 			cpup->flag |= LPFC_CPU_MAP_UNASSIGN;
10971 
10972 			/* If so, find a new_cpup thats on ANY phys_id
10973 			 * as the cpup. start_cpu will start where we
10974 			 * left off so all unassigned entries don't get
10975 			 * assigned the IRQ of the first entry.
10976 			 */
10977 			new_cpu = start_cpu;
10978 			for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
10979 				new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
10980 				if (!(new_cpup->flag & LPFC_CPU_MAP_UNASSIGN) &&
10981 				    (new_cpup->eq != LPFC_VECTOR_MAP_EMPTY))
10982 					goto found_any;
10983 				new_cpu = cpumask_next(
10984 					new_cpu, cpu_present_mask);
10985 				if (new_cpu == nr_cpumask_bits)
10986 					new_cpu = first_cpu;
10987 			}
10988 			/* We should never leave an entry unassigned */
10989 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10990 					"3339 Set Affinity: CPU %d "
10991 					"eq %d UNASSIGNED\n",
10992 					cpup->hdwq, cpup->eq);
10993 			continue;
10994 found_any:
10995 			/* We found an available entry, copy the IRQ info */
10996 			cpup->eq = new_cpup->eq;
10997 
10998 			/* Bump start_cpu to the next slot to minmize the
10999 			 * chance of having multiple unassigned CPU entries
11000 			 * selecting the same IRQ.
11001 			 */
11002 			start_cpu = cpumask_next(new_cpu, cpu_present_mask);
11003 			if (start_cpu == nr_cpumask_bits)
11004 				start_cpu = first_cpu;
11005 
11006 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11007 					"3338 Set Affinity: CPU %d "
11008 					"eq %d from peer cpu %d (%d/%d)\n",
11009 					cpu, cpup->eq, new_cpu,
11010 					new_cpup->phys_id, new_cpup->core_id);
11011 		}
11012 	}
11013 
11014 	/* Assign hdwq indices that are unique across all cpus in the map
11015 	 * that are also FIRST_CPUs.
11016 	 */
11017 	idx = 0;
11018 	for_each_present_cpu(cpu) {
11019 		cpup = &phba->sli4_hba.cpu_map[cpu];
11020 
11021 		/* Only FIRST IRQs get a hdwq index assignment. */
11022 		if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
11023 			continue;
11024 
11025 		/* 1 to 1, the first LPFC_CPU_FIRST_IRQ cpus to a unique hdwq */
11026 		cpup->hdwq = idx;
11027 		idx++;
11028 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11029 				"3333 Set Affinity: CPU %d (phys %d core %d): "
11030 				"hdwq %d eq %d flg x%x\n",
11031 				cpu, cpup->phys_id, cpup->core_id,
11032 				cpup->hdwq, cpup->eq, cpup->flag);
11033 	}
11034 	/* Associate a hdwq with each cpu_map entry
11035 	 * This will be 1 to 1 - hdwq to cpu, unless there are less
11036 	 * hardware queues then CPUs. For that case we will just round-robin
11037 	 * the available hardware queues as they get assigned to CPUs.
11038 	 * The next_idx is the idx from the FIRST_CPU loop above to account
11039 	 * for irq_chann < hdwq.  The idx is used for round-robin assignments
11040 	 * and needs to start at 0.
11041 	 */
11042 	next_idx = idx;
11043 	start_cpu = 0;
11044 	idx = 0;
11045 	for_each_present_cpu(cpu) {
11046 		cpup = &phba->sli4_hba.cpu_map[cpu];
11047 
11048 		/* FIRST cpus are already mapped. */
11049 		if (cpup->flag & LPFC_CPU_FIRST_IRQ)
11050 			continue;
11051 
11052 		/* If the cfg_irq_chann < cfg_hdw_queue, set the hdwq
11053 		 * of the unassigned cpus to the next idx so that all
11054 		 * hdw queues are fully utilized.
11055 		 */
11056 		if (next_idx < phba->cfg_hdw_queue) {
11057 			cpup->hdwq = next_idx;
11058 			next_idx++;
11059 			continue;
11060 		}
11061 
11062 		/* Not a First CPU and all hdw_queues are used.  Reuse a
11063 		 * Hardware Queue for another CPU, so be smart about it
11064 		 * and pick one that has its IRQ/EQ mapped to the same phys_id
11065 		 * (CPU package) and core_id.
11066 		 */
11067 		new_cpu = start_cpu;
11068 		for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
11069 			new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
11070 			if (new_cpup->hdwq != LPFC_VECTOR_MAP_EMPTY &&
11071 			    new_cpup->phys_id == cpup->phys_id &&
11072 			    new_cpup->core_id == cpup->core_id) {
11073 				goto found_hdwq;
11074 			}
11075 			new_cpu = cpumask_next(new_cpu, cpu_present_mask);
11076 			if (new_cpu == nr_cpumask_bits)
11077 				new_cpu = first_cpu;
11078 		}
11079 
11080 		/* If we can't match both phys_id and core_id,
11081 		 * settle for just a phys_id match.
11082 		 */
11083 		new_cpu = start_cpu;
11084 		for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
11085 			new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
11086 			if (new_cpup->hdwq != LPFC_VECTOR_MAP_EMPTY &&
11087 			    new_cpup->phys_id == cpup->phys_id)
11088 				goto found_hdwq;
11089 
11090 			new_cpu = cpumask_next(new_cpu, cpu_present_mask);
11091 			if (new_cpu == nr_cpumask_bits)
11092 				new_cpu = first_cpu;
11093 		}
11094 
11095 		/* Otherwise just round robin on cfg_hdw_queue */
11096 		cpup->hdwq = idx % phba->cfg_hdw_queue;
11097 		idx++;
11098 		goto logit;
11099  found_hdwq:
11100 		/* We found an available entry, copy the IRQ info */
11101 		start_cpu = cpumask_next(new_cpu, cpu_present_mask);
11102 		if (start_cpu == nr_cpumask_bits)
11103 			start_cpu = first_cpu;
11104 		cpup->hdwq = new_cpup->hdwq;
11105  logit:
11106 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11107 				"3335 Set Affinity: CPU %d (phys %d core %d): "
11108 				"hdwq %d eq %d flg x%x\n",
11109 				cpu, cpup->phys_id, cpup->core_id,
11110 				cpup->hdwq, cpup->eq, cpup->flag);
11111 	}
11112 
11113 	/*
11114 	 * Initialize the cpu_map slots for not-present cpus in case
11115 	 * a cpu is hot-added. Perform a simple hdwq round robin assignment.
11116 	 */
11117 	idx = 0;
11118 	for_each_possible_cpu(cpu) {
11119 		cpup = &phba->sli4_hba.cpu_map[cpu];
11120 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
11121 		c_stat = per_cpu_ptr(phba->sli4_hba.c_stat, cpu);
11122 		c_stat->hdwq_no = cpup->hdwq;
11123 #endif
11124 		if (cpup->hdwq != LPFC_VECTOR_MAP_EMPTY)
11125 			continue;
11126 
11127 		cpup->hdwq = idx++ % phba->cfg_hdw_queue;
11128 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
11129 		c_stat->hdwq_no = cpup->hdwq;
11130 #endif
11131 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11132 				"3340 Set Affinity: not present "
11133 				"CPU %d hdwq %d\n",
11134 				cpu, cpup->hdwq);
11135 	}
11136 
11137 	/* The cpu_map array will be used later during initialization
11138 	 * when EQ / CQ / WQs are allocated and configured.
11139 	 */
11140 	return;
11141 }
11142 
11143 /**
11144  * lpfc_cpuhp_get_eq
11145  *
11146  * @phba:   pointer to lpfc hba data structure.
11147  * @cpu:    cpu going offline
11148  * @eqlist:
11149  */
11150 static int
11151 lpfc_cpuhp_get_eq(struct lpfc_hba *phba, unsigned int cpu,
11152 		  struct list_head *eqlist)
11153 {
11154 	const struct cpumask *maskp;
11155 	struct lpfc_queue *eq;
11156 	struct cpumask *tmp;
11157 	u16 idx;
11158 
11159 	tmp = kzalloc(cpumask_size(), GFP_KERNEL);
11160 	if (!tmp)
11161 		return -ENOMEM;
11162 
11163 	for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
11164 		maskp = pci_irq_get_affinity(phba->pcidev, idx);
11165 		if (!maskp)
11166 			continue;
11167 		/*
11168 		 * if irq is not affinitized to the cpu going
11169 		 * then we don't need to poll the eq attached
11170 		 * to it.
11171 		 */
11172 		if (!cpumask_and(tmp, maskp, cpumask_of(cpu)))
11173 			continue;
11174 		/* get the cpus that are online and are affini-
11175 		 * tized to this irq vector.  If the count is
11176 		 * more than 1 then cpuhp is not going to shut-
11177 		 * down this vector.  Since this cpu has not
11178 		 * gone offline yet, we need >1.
11179 		 */
11180 		cpumask_and(tmp, maskp, cpu_online_mask);
11181 		if (cpumask_weight(tmp) > 1)
11182 			continue;
11183 
11184 		/* Now that we have an irq to shutdown, get the eq
11185 		 * mapped to this irq.  Note: multiple hdwq's in
11186 		 * the software can share an eq, but eventually
11187 		 * only eq will be mapped to this vector
11188 		 */
11189 		eq = phba->sli4_hba.hba_eq_hdl[idx].eq;
11190 		list_add(&eq->_poll_list, eqlist);
11191 	}
11192 	kfree(tmp);
11193 	return 0;
11194 }
11195 
11196 static void __lpfc_cpuhp_remove(struct lpfc_hba *phba)
11197 {
11198 	if (phba->sli_rev != LPFC_SLI_REV4)
11199 		return;
11200 
11201 	cpuhp_state_remove_instance_nocalls(lpfc_cpuhp_state,
11202 					    &phba->cpuhp);
11203 	/*
11204 	 * unregistering the instance doesn't stop the polling
11205 	 * timer. Wait for the poll timer to retire.
11206 	 */
11207 	synchronize_rcu();
11208 	del_timer_sync(&phba->cpuhp_poll_timer);
11209 }
11210 
11211 static void lpfc_cpuhp_remove(struct lpfc_hba *phba)
11212 {
11213 	if (phba->pport->fc_flag & FC_OFFLINE_MODE)
11214 		return;
11215 
11216 	__lpfc_cpuhp_remove(phba);
11217 }
11218 
11219 static void lpfc_cpuhp_add(struct lpfc_hba *phba)
11220 {
11221 	if (phba->sli_rev != LPFC_SLI_REV4)
11222 		return;
11223 
11224 	rcu_read_lock();
11225 
11226 	if (!list_empty(&phba->poll_list))
11227 		mod_timer(&phba->cpuhp_poll_timer,
11228 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
11229 
11230 	rcu_read_unlock();
11231 
11232 	cpuhp_state_add_instance_nocalls(lpfc_cpuhp_state,
11233 					 &phba->cpuhp);
11234 }
11235 
11236 static int __lpfc_cpuhp_checks(struct lpfc_hba *phba, int *retval)
11237 {
11238 	if (phba->pport->load_flag & FC_UNLOADING) {
11239 		*retval = -EAGAIN;
11240 		return true;
11241 	}
11242 
11243 	if (phba->sli_rev != LPFC_SLI_REV4) {
11244 		*retval = 0;
11245 		return true;
11246 	}
11247 
11248 	/* proceed with the hotplug */
11249 	return false;
11250 }
11251 
11252 /**
11253  * lpfc_irq_set_aff - set IRQ affinity
11254  * @eqhdl: EQ handle
11255  * @cpu: cpu to set affinity
11256  *
11257  **/
11258 static inline void
11259 lpfc_irq_set_aff(struct lpfc_hba_eq_hdl *eqhdl, unsigned int cpu)
11260 {
11261 	cpumask_clear(&eqhdl->aff_mask);
11262 	cpumask_set_cpu(cpu, &eqhdl->aff_mask);
11263 	irq_set_status_flags(eqhdl->irq, IRQ_NO_BALANCING);
11264 	irq_set_affinity_hint(eqhdl->irq, &eqhdl->aff_mask);
11265 }
11266 
11267 /**
11268  * lpfc_irq_clear_aff - clear IRQ affinity
11269  * @eqhdl: EQ handle
11270  *
11271  **/
11272 static inline void
11273 lpfc_irq_clear_aff(struct lpfc_hba_eq_hdl *eqhdl)
11274 {
11275 	cpumask_clear(&eqhdl->aff_mask);
11276 	irq_clear_status_flags(eqhdl->irq, IRQ_NO_BALANCING);
11277 	irq_set_affinity_hint(eqhdl->irq, &eqhdl->aff_mask);
11278 }
11279 
11280 /**
11281  * lpfc_irq_rebalance - rebalances IRQ affinity according to cpuhp event
11282  * @phba: pointer to HBA context object.
11283  * @cpu: cpu going offline/online
11284  * @offline: true, cpu is going offline. false, cpu is coming online.
11285  *
11286  * If cpu is going offline, we'll try our best effort to find the next
11287  * online cpu on the phba's NUMA node and migrate all offlining IRQ affinities.
11288  *
11289  * If cpu is coming online, reaffinitize the IRQ back to the onlineng cpu.
11290  *
11291  * Note: Call only if cfg_irq_numa is enabled, otherwise rely on
11292  *	 PCI_IRQ_AFFINITY to auto-manage IRQ affinity.
11293  *
11294  **/
11295 static void
11296 lpfc_irq_rebalance(struct lpfc_hba *phba, unsigned int cpu, bool offline)
11297 {
11298 	struct lpfc_vector_map_info *cpup;
11299 	struct cpumask *aff_mask;
11300 	unsigned int cpu_select, cpu_next, idx;
11301 	const struct cpumask *numa_mask;
11302 
11303 	if (!phba->cfg_irq_numa)
11304 		return;
11305 
11306 	numa_mask = &phba->sli4_hba.numa_mask;
11307 
11308 	if (!cpumask_test_cpu(cpu, numa_mask))
11309 		return;
11310 
11311 	cpup = &phba->sli4_hba.cpu_map[cpu];
11312 
11313 	if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
11314 		return;
11315 
11316 	if (offline) {
11317 		/* Find next online CPU on NUMA node */
11318 		cpu_next = cpumask_next_wrap(cpu, numa_mask, cpu, true);
11319 		cpu_select = lpfc_next_online_numa_cpu(numa_mask, cpu_next);
11320 
11321 		/* Found a valid CPU */
11322 		if ((cpu_select < nr_cpu_ids) && (cpu_select != cpu)) {
11323 			/* Go through each eqhdl and ensure offlining
11324 			 * cpu aff_mask is migrated
11325 			 */
11326 			for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
11327 				aff_mask = lpfc_get_aff_mask(idx);
11328 
11329 				/* Migrate affinity */
11330 				if (cpumask_test_cpu(cpu, aff_mask))
11331 					lpfc_irq_set_aff(lpfc_get_eq_hdl(idx),
11332 							 cpu_select);
11333 			}
11334 		} else {
11335 			/* Rely on irqbalance if no online CPUs left on NUMA */
11336 			for (idx = 0; idx < phba->cfg_irq_chann; idx++)
11337 				lpfc_irq_clear_aff(lpfc_get_eq_hdl(idx));
11338 		}
11339 	} else {
11340 		/* Migrate affinity back to this CPU */
11341 		lpfc_irq_set_aff(lpfc_get_eq_hdl(cpup->eq), cpu);
11342 	}
11343 }
11344 
11345 static int lpfc_cpu_offline(unsigned int cpu, struct hlist_node *node)
11346 {
11347 	struct lpfc_hba *phba = hlist_entry_safe(node, struct lpfc_hba, cpuhp);
11348 	struct lpfc_queue *eq, *next;
11349 	LIST_HEAD(eqlist);
11350 	int retval;
11351 
11352 	if (!phba) {
11353 		WARN_ONCE(!phba, "cpu: %u. phba:NULL", raw_smp_processor_id());
11354 		return 0;
11355 	}
11356 
11357 	if (__lpfc_cpuhp_checks(phba, &retval))
11358 		return retval;
11359 
11360 	lpfc_irq_rebalance(phba, cpu, true);
11361 
11362 	retval = lpfc_cpuhp_get_eq(phba, cpu, &eqlist);
11363 	if (retval)
11364 		return retval;
11365 
11366 	/* start polling on these eq's */
11367 	list_for_each_entry_safe(eq, next, &eqlist, _poll_list) {
11368 		list_del_init(&eq->_poll_list);
11369 		lpfc_sli4_start_polling(eq);
11370 	}
11371 
11372 	return 0;
11373 }
11374 
11375 static int lpfc_cpu_online(unsigned int cpu, struct hlist_node *node)
11376 {
11377 	struct lpfc_hba *phba = hlist_entry_safe(node, struct lpfc_hba, cpuhp);
11378 	struct lpfc_queue *eq, *next;
11379 	unsigned int n;
11380 	int retval;
11381 
11382 	if (!phba) {
11383 		WARN_ONCE(!phba, "cpu: %u. phba:NULL", raw_smp_processor_id());
11384 		return 0;
11385 	}
11386 
11387 	if (__lpfc_cpuhp_checks(phba, &retval))
11388 		return retval;
11389 
11390 	lpfc_irq_rebalance(phba, cpu, false);
11391 
11392 	list_for_each_entry_safe(eq, next, &phba->poll_list, _poll_list) {
11393 		n = lpfc_find_cpu_handle(phba, eq->hdwq, LPFC_FIND_BY_HDWQ);
11394 		if (n == cpu)
11395 			lpfc_sli4_stop_polling(eq);
11396 	}
11397 
11398 	return 0;
11399 }
11400 
11401 /**
11402  * lpfc_sli4_enable_msix - Enable MSI-X interrupt mode to SLI-4 device
11403  * @phba: pointer to lpfc hba data structure.
11404  *
11405  * This routine is invoked to enable the MSI-X interrupt vectors to device
11406  * with SLI-4 interface spec.  It also allocates MSI-X vectors and maps them
11407  * to cpus on the system.
11408  *
11409  * When cfg_irq_numa is enabled, the adapter will only allocate vectors for
11410  * the number of cpus on the same numa node as this adapter.  The vectors are
11411  * allocated without requesting OS affinity mapping.  A vector will be
11412  * allocated and assigned to each online and offline cpu.  If the cpu is
11413  * online, then affinity will be set to that cpu.  If the cpu is offline, then
11414  * affinity will be set to the nearest peer cpu within the numa node that is
11415  * online.  If there are no online cpus within the numa node, affinity is not
11416  * assigned and the OS may do as it pleases. Note: cpu vector affinity mapping
11417  * is consistent with the way cpu online/offline is handled when cfg_irq_numa is
11418  * configured.
11419  *
11420  * If numa mode is not enabled and there is more than 1 vector allocated, then
11421  * the driver relies on the managed irq interface where the OS assigns vector to
11422  * cpu affinity.  The driver will then use that affinity mapping to setup its
11423  * cpu mapping table.
11424  *
11425  * Return codes
11426  * 0 - successful
11427  * other values - error
11428  **/
11429 static int
11430 lpfc_sli4_enable_msix(struct lpfc_hba *phba)
11431 {
11432 	int vectors, rc, index;
11433 	char *name;
11434 	const struct cpumask *numa_mask = NULL;
11435 	unsigned int cpu = 0, cpu_cnt = 0, cpu_select = nr_cpu_ids;
11436 	struct lpfc_hba_eq_hdl *eqhdl;
11437 	const struct cpumask *maskp;
11438 	bool first;
11439 	unsigned int flags = PCI_IRQ_MSIX;
11440 
11441 	/* Set up MSI-X multi-message vectors */
11442 	vectors = phba->cfg_irq_chann;
11443 
11444 	if (phba->cfg_irq_numa) {
11445 		numa_mask = &phba->sli4_hba.numa_mask;
11446 		cpu_cnt = cpumask_weight(numa_mask);
11447 		vectors = min(phba->cfg_irq_chann, cpu_cnt);
11448 
11449 		/* cpu: iterates over numa_mask including offline or online
11450 		 * cpu_select: iterates over online numa_mask to set affinity
11451 		 */
11452 		cpu = cpumask_first(numa_mask);
11453 		cpu_select = lpfc_next_online_numa_cpu(numa_mask, cpu);
11454 	} else {
11455 		flags |= PCI_IRQ_AFFINITY;
11456 	}
11457 
11458 	rc = pci_alloc_irq_vectors(phba->pcidev, 1, vectors, flags);
11459 	if (rc < 0) {
11460 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11461 				"0484 PCI enable MSI-X failed (%d)\n", rc);
11462 		goto vec_fail_out;
11463 	}
11464 	vectors = rc;
11465 
11466 	/* Assign MSI-X vectors to interrupt handlers */
11467 	for (index = 0; index < vectors; index++) {
11468 		eqhdl = lpfc_get_eq_hdl(index);
11469 		name = eqhdl->handler_name;
11470 		memset(name, 0, LPFC_SLI4_HANDLER_NAME_SZ);
11471 		snprintf(name, LPFC_SLI4_HANDLER_NAME_SZ,
11472 			 LPFC_DRIVER_HANDLER_NAME"%d", index);
11473 
11474 		eqhdl->idx = index;
11475 		rc = request_irq(pci_irq_vector(phba->pcidev, index),
11476 			 &lpfc_sli4_hba_intr_handler, 0,
11477 			 name, eqhdl);
11478 		if (rc) {
11479 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
11480 					"0486 MSI-X fast-path (%d) "
11481 					"request_irq failed (%d)\n", index, rc);
11482 			goto cfg_fail_out;
11483 		}
11484 
11485 		eqhdl->irq = pci_irq_vector(phba->pcidev, index);
11486 
11487 		if (phba->cfg_irq_numa) {
11488 			/* If found a neighboring online cpu, set affinity */
11489 			if (cpu_select < nr_cpu_ids)
11490 				lpfc_irq_set_aff(eqhdl, cpu_select);
11491 
11492 			/* Assign EQ to cpu_map */
11493 			lpfc_assign_eq_map_info(phba, index,
11494 						LPFC_CPU_FIRST_IRQ,
11495 						cpu);
11496 
11497 			/* Iterate to next offline or online cpu in numa_mask */
11498 			cpu = cpumask_next(cpu, numa_mask);
11499 
11500 			/* Find next online cpu in numa_mask to set affinity */
11501 			cpu_select = lpfc_next_online_numa_cpu(numa_mask, cpu);
11502 		} else if (vectors == 1) {
11503 			cpu = cpumask_first(cpu_present_mask);
11504 			lpfc_assign_eq_map_info(phba, index, LPFC_CPU_FIRST_IRQ,
11505 						cpu);
11506 		} else {
11507 			maskp = pci_irq_get_affinity(phba->pcidev, index);
11508 
11509 			first = true;
11510 			/* Loop through all CPUs associated with vector index */
11511 			for_each_cpu_and(cpu, maskp, cpu_present_mask) {
11512 				/* If this is the first CPU thats assigned to
11513 				 * this vector, set LPFC_CPU_FIRST_IRQ.
11514 				 */
11515 				lpfc_assign_eq_map_info(phba, index,
11516 							first ?
11517 							LPFC_CPU_FIRST_IRQ : 0,
11518 							cpu);
11519 				if (first)
11520 					first = false;
11521 			}
11522 		}
11523 	}
11524 
11525 	if (vectors != phba->cfg_irq_chann) {
11526 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11527 				"3238 Reducing IO channels to match number of "
11528 				"MSI-X vectors, requested %d got %d\n",
11529 				phba->cfg_irq_chann, vectors);
11530 		if (phba->cfg_irq_chann > vectors)
11531 			phba->cfg_irq_chann = vectors;
11532 	}
11533 
11534 	return rc;
11535 
11536 cfg_fail_out:
11537 	/* free the irq already requested */
11538 	for (--index; index >= 0; index--) {
11539 		eqhdl = lpfc_get_eq_hdl(index);
11540 		lpfc_irq_clear_aff(eqhdl);
11541 		irq_set_affinity_hint(eqhdl->irq, NULL);
11542 		free_irq(eqhdl->irq, eqhdl);
11543 	}
11544 
11545 	/* Unconfigure MSI-X capability structure */
11546 	pci_free_irq_vectors(phba->pcidev);
11547 
11548 vec_fail_out:
11549 	return rc;
11550 }
11551 
11552 /**
11553  * lpfc_sli4_enable_msi - Enable MSI interrupt mode to SLI-4 device
11554  * @phba: pointer to lpfc hba data structure.
11555  *
11556  * This routine is invoked to enable the MSI interrupt mode to device with
11557  * SLI-4 interface spec. The kernel function pci_alloc_irq_vectors() is
11558  * called to enable the MSI vector. The device driver is responsible for
11559  * calling the request_irq() to register MSI vector with a interrupt the
11560  * handler, which is done in this function.
11561  *
11562  * Return codes
11563  * 	0 - successful
11564  * 	other values - error
11565  **/
11566 static int
11567 lpfc_sli4_enable_msi(struct lpfc_hba *phba)
11568 {
11569 	int rc, index;
11570 	unsigned int cpu;
11571 	struct lpfc_hba_eq_hdl *eqhdl;
11572 
11573 	rc = pci_alloc_irq_vectors(phba->pcidev, 1, 1,
11574 				   PCI_IRQ_MSI | PCI_IRQ_AFFINITY);
11575 	if (rc > 0)
11576 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11577 				"0487 PCI enable MSI mode success.\n");
11578 	else {
11579 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11580 				"0488 PCI enable MSI mode failed (%d)\n", rc);
11581 		return rc ? rc : -1;
11582 	}
11583 
11584 	rc = request_irq(phba->pcidev->irq, lpfc_sli4_intr_handler,
11585 			 0, LPFC_DRIVER_NAME, phba);
11586 	if (rc) {
11587 		pci_free_irq_vectors(phba->pcidev);
11588 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
11589 				"0490 MSI request_irq failed (%d)\n", rc);
11590 		return rc;
11591 	}
11592 
11593 	eqhdl = lpfc_get_eq_hdl(0);
11594 	eqhdl->irq = pci_irq_vector(phba->pcidev, 0);
11595 
11596 	cpu = cpumask_first(cpu_present_mask);
11597 	lpfc_assign_eq_map_info(phba, 0, LPFC_CPU_FIRST_IRQ, cpu);
11598 
11599 	for (index = 0; index < phba->cfg_irq_chann; index++) {
11600 		eqhdl = lpfc_get_eq_hdl(index);
11601 		eqhdl->idx = index;
11602 	}
11603 
11604 	return 0;
11605 }
11606 
11607 /**
11608  * lpfc_sli4_enable_intr - Enable device interrupt to SLI-4 device
11609  * @phba: pointer to lpfc hba data structure.
11610  *
11611  * This routine is invoked to enable device interrupt and associate driver's
11612  * interrupt handler(s) to interrupt vector(s) to device with SLI-4
11613  * interface spec. Depends on the interrupt mode configured to the driver,
11614  * the driver will try to fallback from the configured interrupt mode to an
11615  * interrupt mode which is supported by the platform, kernel, and device in
11616  * the order of:
11617  * MSI-X -> MSI -> IRQ.
11618  *
11619  * Return codes
11620  * 	0 - successful
11621  * 	other values - error
11622  **/
11623 static uint32_t
11624 lpfc_sli4_enable_intr(struct lpfc_hba *phba, uint32_t cfg_mode)
11625 {
11626 	uint32_t intr_mode = LPFC_INTR_ERROR;
11627 	int retval, idx;
11628 
11629 	if (cfg_mode == 2) {
11630 		/* Preparation before conf_msi mbox cmd */
11631 		retval = 0;
11632 		if (!retval) {
11633 			/* Now, try to enable MSI-X interrupt mode */
11634 			retval = lpfc_sli4_enable_msix(phba);
11635 			if (!retval) {
11636 				/* Indicate initialization to MSI-X mode */
11637 				phba->intr_type = MSIX;
11638 				intr_mode = 2;
11639 			}
11640 		}
11641 	}
11642 
11643 	/* Fallback to MSI if MSI-X initialization failed */
11644 	if (cfg_mode >= 1 && phba->intr_type == NONE) {
11645 		retval = lpfc_sli4_enable_msi(phba);
11646 		if (!retval) {
11647 			/* Indicate initialization to MSI mode */
11648 			phba->intr_type = MSI;
11649 			intr_mode = 1;
11650 		}
11651 	}
11652 
11653 	/* Fallback to INTx if both MSI-X/MSI initalization failed */
11654 	if (phba->intr_type == NONE) {
11655 		retval = request_irq(phba->pcidev->irq, lpfc_sli4_intr_handler,
11656 				     IRQF_SHARED, LPFC_DRIVER_NAME, phba);
11657 		if (!retval) {
11658 			struct lpfc_hba_eq_hdl *eqhdl;
11659 			unsigned int cpu;
11660 
11661 			/* Indicate initialization to INTx mode */
11662 			phba->intr_type = INTx;
11663 			intr_mode = 0;
11664 
11665 			eqhdl = lpfc_get_eq_hdl(0);
11666 			eqhdl->irq = pci_irq_vector(phba->pcidev, 0);
11667 
11668 			cpu = cpumask_first(cpu_present_mask);
11669 			lpfc_assign_eq_map_info(phba, 0, LPFC_CPU_FIRST_IRQ,
11670 						cpu);
11671 			for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
11672 				eqhdl = lpfc_get_eq_hdl(idx);
11673 				eqhdl->idx = idx;
11674 			}
11675 		}
11676 	}
11677 	return intr_mode;
11678 }
11679 
11680 /**
11681  * lpfc_sli4_disable_intr - Disable device interrupt to SLI-4 device
11682  * @phba: pointer to lpfc hba data structure.
11683  *
11684  * This routine is invoked to disable device interrupt and disassociate
11685  * the driver's interrupt handler(s) from interrupt vector(s) to device
11686  * with SLI-4 interface spec. Depending on the interrupt mode, the driver
11687  * will release the interrupt vector(s) for the message signaled interrupt.
11688  **/
11689 static void
11690 lpfc_sli4_disable_intr(struct lpfc_hba *phba)
11691 {
11692 	/* Disable the currently initialized interrupt mode */
11693 	if (phba->intr_type == MSIX) {
11694 		int index;
11695 		struct lpfc_hba_eq_hdl *eqhdl;
11696 
11697 		/* Free up MSI-X multi-message vectors */
11698 		for (index = 0; index < phba->cfg_irq_chann; index++) {
11699 			eqhdl = lpfc_get_eq_hdl(index);
11700 			lpfc_irq_clear_aff(eqhdl);
11701 			irq_set_affinity_hint(eqhdl->irq, NULL);
11702 			free_irq(eqhdl->irq, eqhdl);
11703 		}
11704 	} else {
11705 		free_irq(phba->pcidev->irq, phba);
11706 	}
11707 
11708 	pci_free_irq_vectors(phba->pcidev);
11709 
11710 	/* Reset interrupt management states */
11711 	phba->intr_type = NONE;
11712 	phba->sli.slistat.sli_intr = 0;
11713 }
11714 
11715 /**
11716  * lpfc_unset_hba - Unset SLI3 hba device initialization
11717  * @phba: pointer to lpfc hba data structure.
11718  *
11719  * This routine is invoked to unset the HBA device initialization steps to
11720  * a device with SLI-3 interface spec.
11721  **/
11722 static void
11723 lpfc_unset_hba(struct lpfc_hba *phba)
11724 {
11725 	struct lpfc_vport *vport = phba->pport;
11726 	struct Scsi_Host  *shost = lpfc_shost_from_vport(vport);
11727 
11728 	spin_lock_irq(shost->host_lock);
11729 	vport->load_flag |= FC_UNLOADING;
11730 	spin_unlock_irq(shost->host_lock);
11731 
11732 	kfree(phba->vpi_bmask);
11733 	kfree(phba->vpi_ids);
11734 
11735 	lpfc_stop_hba_timers(phba);
11736 
11737 	phba->pport->work_port_events = 0;
11738 
11739 	lpfc_sli_hba_down(phba);
11740 
11741 	lpfc_sli_brdrestart(phba);
11742 
11743 	lpfc_sli_disable_intr(phba);
11744 
11745 	return;
11746 }
11747 
11748 /**
11749  * lpfc_sli4_xri_exchange_busy_wait - Wait for device XRI exchange busy
11750  * @phba: Pointer to HBA context object.
11751  *
11752  * This function is called in the SLI4 code path to wait for completion
11753  * of device's XRIs exchange busy. It will check the XRI exchange busy
11754  * on outstanding FCP and ELS I/Os every 10ms for up to 10 seconds; after
11755  * that, it will check the XRI exchange busy on outstanding FCP and ELS
11756  * I/Os every 30 seconds, log error message, and wait forever. Only when
11757  * all XRI exchange busy complete, the driver unload shall proceed with
11758  * invoking the function reset ioctl mailbox command to the CNA and the
11759  * the rest of the driver unload resource release.
11760  **/
11761 static void
11762 lpfc_sli4_xri_exchange_busy_wait(struct lpfc_hba *phba)
11763 {
11764 	struct lpfc_sli4_hdw_queue *qp;
11765 	int idx, ccnt;
11766 	int wait_time = 0;
11767 	int io_xri_cmpl = 1;
11768 	int nvmet_xri_cmpl = 1;
11769 	int els_xri_cmpl = list_empty(&phba->sli4_hba.lpfc_abts_els_sgl_list);
11770 
11771 	/* Driver just aborted IOs during the hba_unset process.  Pause
11772 	 * here to give the HBA time to complete the IO and get entries
11773 	 * into the abts lists.
11774 	 */
11775 	msleep(LPFC_XRI_EXCH_BUSY_WAIT_T1 * 5);
11776 
11777 	/* Wait for NVME pending IO to flush back to transport. */
11778 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
11779 		lpfc_nvme_wait_for_io_drain(phba);
11780 
11781 	ccnt = 0;
11782 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
11783 		qp = &phba->sli4_hba.hdwq[idx];
11784 		io_xri_cmpl = list_empty(&qp->lpfc_abts_io_buf_list);
11785 		if (!io_xri_cmpl) /* if list is NOT empty */
11786 			ccnt++;
11787 	}
11788 	if (ccnt)
11789 		io_xri_cmpl = 0;
11790 
11791 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
11792 		nvmet_xri_cmpl =
11793 			list_empty(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
11794 	}
11795 
11796 	while (!els_xri_cmpl || !io_xri_cmpl || !nvmet_xri_cmpl) {
11797 		if (wait_time > LPFC_XRI_EXCH_BUSY_WAIT_TMO) {
11798 			if (!nvmet_xri_cmpl)
11799 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11800 						"6424 NVMET XRI exchange busy "
11801 						"wait time: %d seconds.\n",
11802 						wait_time/1000);
11803 			if (!io_xri_cmpl)
11804 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11805 						"6100 IO XRI exchange busy "
11806 						"wait time: %d seconds.\n",
11807 						wait_time/1000);
11808 			if (!els_xri_cmpl)
11809 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11810 						"2878 ELS XRI exchange busy "
11811 						"wait time: %d seconds.\n",
11812 						wait_time/1000);
11813 			msleep(LPFC_XRI_EXCH_BUSY_WAIT_T2);
11814 			wait_time += LPFC_XRI_EXCH_BUSY_WAIT_T2;
11815 		} else {
11816 			msleep(LPFC_XRI_EXCH_BUSY_WAIT_T1);
11817 			wait_time += LPFC_XRI_EXCH_BUSY_WAIT_T1;
11818 		}
11819 
11820 		ccnt = 0;
11821 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
11822 			qp = &phba->sli4_hba.hdwq[idx];
11823 			io_xri_cmpl = list_empty(
11824 			    &qp->lpfc_abts_io_buf_list);
11825 			if (!io_xri_cmpl) /* if list is NOT empty */
11826 				ccnt++;
11827 		}
11828 		if (ccnt)
11829 			io_xri_cmpl = 0;
11830 
11831 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
11832 			nvmet_xri_cmpl = list_empty(
11833 				&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
11834 		}
11835 		els_xri_cmpl =
11836 			list_empty(&phba->sli4_hba.lpfc_abts_els_sgl_list);
11837 
11838 	}
11839 }
11840 
11841 /**
11842  * lpfc_sli4_hba_unset - Unset the fcoe hba
11843  * @phba: Pointer to HBA context object.
11844  *
11845  * This function is called in the SLI4 code path to reset the HBA's FCoE
11846  * function. The caller is not required to hold any lock. This routine
11847  * issues PCI function reset mailbox command to reset the FCoE function.
11848  * At the end of the function, it calls lpfc_hba_down_post function to
11849  * free any pending commands.
11850  **/
11851 static void
11852 lpfc_sli4_hba_unset(struct lpfc_hba *phba)
11853 {
11854 	int wait_cnt = 0;
11855 	LPFC_MBOXQ_t *mboxq;
11856 	struct pci_dev *pdev = phba->pcidev;
11857 
11858 	lpfc_stop_hba_timers(phba);
11859 	if (phba->pport)
11860 		phba->sli4_hba.intr_enable = 0;
11861 
11862 	/*
11863 	 * Gracefully wait out the potential current outstanding asynchronous
11864 	 * mailbox command.
11865 	 */
11866 
11867 	/* First, block any pending async mailbox command from posted */
11868 	spin_lock_irq(&phba->hbalock);
11869 	phba->sli.sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
11870 	spin_unlock_irq(&phba->hbalock);
11871 	/* Now, trying to wait it out if we can */
11872 	while (phba->sli.sli_flag & LPFC_SLI_MBOX_ACTIVE) {
11873 		msleep(10);
11874 		if (++wait_cnt > LPFC_ACTIVE_MBOX_WAIT_CNT)
11875 			break;
11876 	}
11877 	/* Forcefully release the outstanding mailbox command if timed out */
11878 	if (phba->sli.sli_flag & LPFC_SLI_MBOX_ACTIVE) {
11879 		spin_lock_irq(&phba->hbalock);
11880 		mboxq = phba->sli.mbox_active;
11881 		mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
11882 		__lpfc_mbox_cmpl_put(phba, mboxq);
11883 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
11884 		phba->sli.mbox_active = NULL;
11885 		spin_unlock_irq(&phba->hbalock);
11886 	}
11887 
11888 	/* Abort all iocbs associated with the hba */
11889 	lpfc_sli_hba_iocb_abort(phba);
11890 
11891 	/* Wait for completion of device XRI exchange busy */
11892 	lpfc_sli4_xri_exchange_busy_wait(phba);
11893 
11894 	/* per-phba callback de-registration for hotplug event */
11895 	lpfc_cpuhp_remove(phba);
11896 
11897 	/* Disable PCI subsystem interrupt */
11898 	lpfc_sli4_disable_intr(phba);
11899 
11900 	/* Disable SR-IOV if enabled */
11901 	if (phba->cfg_sriov_nr_virtfn)
11902 		pci_disable_sriov(pdev);
11903 
11904 	/* Stop kthread signal shall trigger work_done one more time */
11905 	kthread_stop(phba->worker_thread);
11906 
11907 	/* Disable FW logging to host memory */
11908 	lpfc_ras_stop_fwlog(phba);
11909 
11910 	/* Unset the queues shared with the hardware then release all
11911 	 * allocated resources.
11912 	 */
11913 	lpfc_sli4_queue_unset(phba);
11914 	lpfc_sli4_queue_destroy(phba);
11915 
11916 	/* Reset SLI4 HBA FCoE function */
11917 	lpfc_pci_function_reset(phba);
11918 
11919 	/* Free RAS DMA memory */
11920 	if (phba->ras_fwlog.ras_enabled)
11921 		lpfc_sli4_ras_dma_free(phba);
11922 
11923 	/* Stop the SLI4 device port */
11924 	if (phba->pport)
11925 		phba->pport->work_port_events = 0;
11926 }
11927 
11928  /**
11929  * lpfc_pc_sli4_params_get - Get the SLI4_PARAMS port capabilities.
11930  * @phba: Pointer to HBA context object.
11931  * @mboxq: Pointer to the mailboxq memory for the mailbox command response.
11932  *
11933  * This function is called in the SLI4 code path to read the port's
11934  * sli4 capabilities.
11935  *
11936  * This function may be be called from any context that can block-wait
11937  * for the completion.  The expectation is that this routine is called
11938  * typically from probe_one or from the online routine.
11939  **/
11940 int
11941 lpfc_pc_sli4_params_get(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
11942 {
11943 	int rc;
11944 	struct lpfc_mqe *mqe;
11945 	struct lpfc_pc_sli4_params *sli4_params;
11946 	uint32_t mbox_tmo;
11947 
11948 	rc = 0;
11949 	mqe = &mboxq->u.mqe;
11950 
11951 	/* Read the port's SLI4 Parameters port capabilities */
11952 	lpfc_pc_sli4_params(mboxq);
11953 	if (!phba->sli4_hba.intr_enable)
11954 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
11955 	else {
11956 		mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
11957 		rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
11958 	}
11959 
11960 	if (unlikely(rc))
11961 		return 1;
11962 
11963 	sli4_params = &phba->sli4_hba.pc_sli4_params;
11964 	sli4_params->if_type = bf_get(if_type, &mqe->un.sli4_params);
11965 	sli4_params->sli_rev = bf_get(sli_rev, &mqe->un.sli4_params);
11966 	sli4_params->sli_family = bf_get(sli_family, &mqe->un.sli4_params);
11967 	sli4_params->featurelevel_1 = bf_get(featurelevel_1,
11968 					     &mqe->un.sli4_params);
11969 	sli4_params->featurelevel_2 = bf_get(featurelevel_2,
11970 					     &mqe->un.sli4_params);
11971 	sli4_params->proto_types = mqe->un.sli4_params.word3;
11972 	sli4_params->sge_supp_len = mqe->un.sli4_params.sge_supp_len;
11973 	sli4_params->if_page_sz = bf_get(if_page_sz, &mqe->un.sli4_params);
11974 	sli4_params->rq_db_window = bf_get(rq_db_window, &mqe->un.sli4_params);
11975 	sli4_params->loopbk_scope = bf_get(loopbk_scope, &mqe->un.sli4_params);
11976 	sli4_params->eq_pages_max = bf_get(eq_pages, &mqe->un.sli4_params);
11977 	sli4_params->eqe_size = bf_get(eqe_size, &mqe->un.sli4_params);
11978 	sli4_params->cq_pages_max = bf_get(cq_pages, &mqe->un.sli4_params);
11979 	sli4_params->cqe_size = bf_get(cqe_size, &mqe->un.sli4_params);
11980 	sli4_params->mq_pages_max = bf_get(mq_pages, &mqe->un.sli4_params);
11981 	sli4_params->mqe_size = bf_get(mqe_size, &mqe->un.sli4_params);
11982 	sli4_params->mq_elem_cnt = bf_get(mq_elem_cnt, &mqe->un.sli4_params);
11983 	sli4_params->wq_pages_max = bf_get(wq_pages, &mqe->un.sli4_params);
11984 	sli4_params->wqe_size = bf_get(wqe_size, &mqe->un.sli4_params);
11985 	sli4_params->rq_pages_max = bf_get(rq_pages, &mqe->un.sli4_params);
11986 	sli4_params->rqe_size = bf_get(rqe_size, &mqe->un.sli4_params);
11987 	sli4_params->hdr_pages_max = bf_get(hdr_pages, &mqe->un.sli4_params);
11988 	sli4_params->hdr_size = bf_get(hdr_size, &mqe->un.sli4_params);
11989 	sli4_params->hdr_pp_align = bf_get(hdr_pp_align, &mqe->un.sli4_params);
11990 	sli4_params->sgl_pages_max = bf_get(sgl_pages, &mqe->un.sli4_params);
11991 	sli4_params->sgl_pp_align = bf_get(sgl_pp_align, &mqe->un.sli4_params);
11992 
11993 	/* Make sure that sge_supp_len can be handled by the driver */
11994 	if (sli4_params->sge_supp_len > LPFC_MAX_SGE_SIZE)
11995 		sli4_params->sge_supp_len = LPFC_MAX_SGE_SIZE;
11996 
11997 	return rc;
11998 }
11999 
12000 /**
12001  * lpfc_get_sli4_parameters - Get the SLI4 Config PARAMETERS.
12002  * @phba: Pointer to HBA context object.
12003  * @mboxq: Pointer to the mailboxq memory for the mailbox command response.
12004  *
12005  * This function is called in the SLI4 code path to read the port's
12006  * sli4 capabilities.
12007  *
12008  * This function may be be called from any context that can block-wait
12009  * for the completion.  The expectation is that this routine is called
12010  * typically from probe_one or from the online routine.
12011  **/
12012 int
12013 lpfc_get_sli4_parameters(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
12014 {
12015 	int rc;
12016 	struct lpfc_mqe *mqe = &mboxq->u.mqe;
12017 	struct lpfc_pc_sli4_params *sli4_params;
12018 	uint32_t mbox_tmo;
12019 	int length;
12020 	bool exp_wqcq_pages = true;
12021 	struct lpfc_sli4_parameters *mbx_sli4_parameters;
12022 
12023 	/*
12024 	 * By default, the driver assumes the SLI4 port requires RPI
12025 	 * header postings.  The SLI4_PARAM response will correct this
12026 	 * assumption.
12027 	 */
12028 	phba->sli4_hba.rpi_hdrs_in_use = 1;
12029 
12030 	/* Read the port's SLI4 Config Parameters */
12031 	length = (sizeof(struct lpfc_mbx_get_sli4_parameters) -
12032 		  sizeof(struct lpfc_sli4_cfg_mhdr));
12033 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
12034 			 LPFC_MBOX_OPCODE_GET_SLI4_PARAMETERS,
12035 			 length, LPFC_SLI4_MBX_EMBED);
12036 	if (!phba->sli4_hba.intr_enable)
12037 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
12038 	else {
12039 		mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
12040 		rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
12041 	}
12042 	if (unlikely(rc))
12043 		return rc;
12044 	sli4_params = &phba->sli4_hba.pc_sli4_params;
12045 	mbx_sli4_parameters = &mqe->un.get_sli4_parameters.sli4_parameters;
12046 	sli4_params->if_type = bf_get(cfg_if_type, mbx_sli4_parameters);
12047 	sli4_params->sli_rev = bf_get(cfg_sli_rev, mbx_sli4_parameters);
12048 	sli4_params->sli_family = bf_get(cfg_sli_family, mbx_sli4_parameters);
12049 	sli4_params->featurelevel_1 = bf_get(cfg_sli_hint_1,
12050 					     mbx_sli4_parameters);
12051 	sli4_params->featurelevel_2 = bf_get(cfg_sli_hint_2,
12052 					     mbx_sli4_parameters);
12053 	if (bf_get(cfg_phwq, mbx_sli4_parameters))
12054 		phba->sli3_options |= LPFC_SLI4_PHWQ_ENABLED;
12055 	else
12056 		phba->sli3_options &= ~LPFC_SLI4_PHWQ_ENABLED;
12057 	sli4_params->sge_supp_len = mbx_sli4_parameters->sge_supp_len;
12058 	sli4_params->loopbk_scope = bf_get(loopbk_scope, mbx_sli4_parameters);
12059 	sli4_params->oas_supported = bf_get(cfg_oas, mbx_sli4_parameters);
12060 	sli4_params->cqv = bf_get(cfg_cqv, mbx_sli4_parameters);
12061 	sli4_params->mqv = bf_get(cfg_mqv, mbx_sli4_parameters);
12062 	sli4_params->wqv = bf_get(cfg_wqv, mbx_sli4_parameters);
12063 	sli4_params->rqv = bf_get(cfg_rqv, mbx_sli4_parameters);
12064 	sli4_params->eqav = bf_get(cfg_eqav, mbx_sli4_parameters);
12065 	sli4_params->cqav = bf_get(cfg_cqav, mbx_sli4_parameters);
12066 	sli4_params->wqsize = bf_get(cfg_wqsize, mbx_sli4_parameters);
12067 	sli4_params->bv1s = bf_get(cfg_bv1s, mbx_sli4_parameters);
12068 	sli4_params->pls = bf_get(cfg_pvl, mbx_sli4_parameters);
12069 	sli4_params->sgl_pages_max = bf_get(cfg_sgl_page_cnt,
12070 					    mbx_sli4_parameters);
12071 	sli4_params->wqpcnt = bf_get(cfg_wqpcnt, mbx_sli4_parameters);
12072 	sli4_params->sgl_pp_align = bf_get(cfg_sgl_pp_align,
12073 					   mbx_sli4_parameters);
12074 	phba->sli4_hba.extents_in_use = bf_get(cfg_ext, mbx_sli4_parameters);
12075 	phba->sli4_hba.rpi_hdrs_in_use = bf_get(cfg_hdrr, mbx_sli4_parameters);
12076 
12077 	/* Check for Extended Pre-Registered SGL support */
12078 	phba->cfg_xpsgl = bf_get(cfg_xpsgl, mbx_sli4_parameters);
12079 
12080 	/* Check for firmware nvme support */
12081 	rc = (bf_get(cfg_nvme, mbx_sli4_parameters) &&
12082 		     bf_get(cfg_xib, mbx_sli4_parameters));
12083 
12084 	if (rc) {
12085 		/* Save this to indicate the Firmware supports NVME */
12086 		sli4_params->nvme = 1;
12087 
12088 		/* Firmware NVME support, check driver FC4 NVME support */
12089 		if (phba->cfg_enable_fc4_type == LPFC_ENABLE_FCP) {
12090 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_NVME,
12091 					"6133 Disabling NVME support: "
12092 					"FC4 type not supported: x%x\n",
12093 					phba->cfg_enable_fc4_type);
12094 			goto fcponly;
12095 		}
12096 	} else {
12097 		/* No firmware NVME support, check driver FC4 NVME support */
12098 		sli4_params->nvme = 0;
12099 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
12100 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_NVME,
12101 					"6101 Disabling NVME support: Not "
12102 					"supported by firmware (%d %d) x%x\n",
12103 					bf_get(cfg_nvme, mbx_sli4_parameters),
12104 					bf_get(cfg_xib, mbx_sli4_parameters),
12105 					phba->cfg_enable_fc4_type);
12106 fcponly:
12107 			phba->nvme_support = 0;
12108 			phba->nvmet_support = 0;
12109 			phba->cfg_nvmet_mrq = 0;
12110 			phba->cfg_nvme_seg_cnt = 0;
12111 
12112 			/* If no FC4 type support, move to just SCSI support */
12113 			if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP))
12114 				return -ENODEV;
12115 			phba->cfg_enable_fc4_type = LPFC_ENABLE_FCP;
12116 		}
12117 	}
12118 
12119 	/* If the NVME FC4 type is enabled, scale the sg_seg_cnt to
12120 	 * accommodate 512K and 1M IOs in a single nvme buf.
12121 	 */
12122 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
12123 		phba->cfg_sg_seg_cnt = LPFC_MAX_NVME_SEG_CNT;
12124 
12125 	/* Only embed PBDE for if_type 6, PBDE support requires xib be set */
12126 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) !=
12127 	    LPFC_SLI_INTF_IF_TYPE_6) || (!bf_get(cfg_xib, mbx_sli4_parameters)))
12128 		phba->cfg_enable_pbde = 0;
12129 
12130 	/*
12131 	 * To support Suppress Response feature we must satisfy 3 conditions.
12132 	 * lpfc_suppress_rsp module parameter must be set (default).
12133 	 * In SLI4-Parameters Descriptor:
12134 	 * Extended Inline Buffers (XIB) must be supported.
12135 	 * Suppress Response IU Not Supported (SRIUNS) must NOT be supported
12136 	 * (double negative).
12137 	 */
12138 	if (phba->cfg_suppress_rsp && bf_get(cfg_xib, mbx_sli4_parameters) &&
12139 	    !(bf_get(cfg_nosr, mbx_sli4_parameters)))
12140 		phba->sli.sli_flag |= LPFC_SLI_SUPPRESS_RSP;
12141 	else
12142 		phba->cfg_suppress_rsp = 0;
12143 
12144 	if (bf_get(cfg_eqdr, mbx_sli4_parameters))
12145 		phba->sli.sli_flag |= LPFC_SLI_USE_EQDR;
12146 
12147 	/* Make sure that sge_supp_len can be handled by the driver */
12148 	if (sli4_params->sge_supp_len > LPFC_MAX_SGE_SIZE)
12149 		sli4_params->sge_supp_len = LPFC_MAX_SGE_SIZE;
12150 
12151 	/*
12152 	 * Check whether the adapter supports an embedded copy of the
12153 	 * FCP CMD IU within the WQE for FCP_Ixxx commands. In order
12154 	 * to use this option, 128-byte WQEs must be used.
12155 	 */
12156 	if (bf_get(cfg_ext_embed_cb, mbx_sli4_parameters))
12157 		phba->fcp_embed_io = 1;
12158 	else
12159 		phba->fcp_embed_io = 0;
12160 
12161 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_NVME,
12162 			"6422 XIB %d PBDE %d: FCP %d NVME %d %d %d\n",
12163 			bf_get(cfg_xib, mbx_sli4_parameters),
12164 			phba->cfg_enable_pbde,
12165 			phba->fcp_embed_io, phba->nvme_support,
12166 			phba->cfg_nvme_embed_cmd, phba->cfg_suppress_rsp);
12167 
12168 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
12169 	    LPFC_SLI_INTF_IF_TYPE_2) &&
12170 	    (bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf) ==
12171 		 LPFC_SLI_INTF_FAMILY_LNCR_A0))
12172 		exp_wqcq_pages = false;
12173 
12174 	if ((bf_get(cfg_cqpsize, mbx_sli4_parameters) & LPFC_CQ_16K_PAGE_SZ) &&
12175 	    (bf_get(cfg_wqpsize, mbx_sli4_parameters) & LPFC_WQ_16K_PAGE_SZ) &&
12176 	    exp_wqcq_pages &&
12177 	    (sli4_params->wqsize & LPFC_WQ_SZ128_SUPPORT))
12178 		phba->enab_exp_wqcq_pages = 1;
12179 	else
12180 		phba->enab_exp_wqcq_pages = 0;
12181 	/*
12182 	 * Check if the SLI port supports MDS Diagnostics
12183 	 */
12184 	if (bf_get(cfg_mds_diags, mbx_sli4_parameters))
12185 		phba->mds_diags_support = 1;
12186 	else
12187 		phba->mds_diags_support = 0;
12188 
12189 	/*
12190 	 * Check if the SLI port supports NSLER
12191 	 */
12192 	if (bf_get(cfg_nsler, mbx_sli4_parameters))
12193 		phba->nsler = 1;
12194 	else
12195 		phba->nsler = 0;
12196 
12197 	return 0;
12198 }
12199 
12200 /**
12201  * lpfc_pci_probe_one_s3 - PCI probe func to reg SLI-3 device to PCI subsystem.
12202  * @pdev: pointer to PCI device
12203  * @pid: pointer to PCI device identifier
12204  *
12205  * This routine is to be called to attach a device with SLI-3 interface spec
12206  * to the PCI subsystem. When an Emulex HBA with SLI-3 interface spec is
12207  * presented on PCI bus, the kernel PCI subsystem looks at PCI device-specific
12208  * information of the device and driver to see if the driver state that it can
12209  * support this kind of device. If the match is successful, the driver core
12210  * invokes this routine. If this routine determines it can claim the HBA, it
12211  * does all the initialization that it needs to do to handle the HBA properly.
12212  *
12213  * Return code
12214  * 	0 - driver can claim the device
12215  * 	negative value - driver can not claim the device
12216  **/
12217 static int
12218 lpfc_pci_probe_one_s3(struct pci_dev *pdev, const struct pci_device_id *pid)
12219 {
12220 	struct lpfc_hba   *phba;
12221 	struct lpfc_vport *vport = NULL;
12222 	struct Scsi_Host  *shost = NULL;
12223 	int error;
12224 	uint32_t cfg_mode, intr_mode;
12225 
12226 	/* Allocate memory for HBA structure */
12227 	phba = lpfc_hba_alloc(pdev);
12228 	if (!phba)
12229 		return -ENOMEM;
12230 
12231 	/* Perform generic PCI device enabling operation */
12232 	error = lpfc_enable_pci_dev(phba);
12233 	if (error)
12234 		goto out_free_phba;
12235 
12236 	/* Set up SLI API function jump table for PCI-device group-0 HBAs */
12237 	error = lpfc_api_table_setup(phba, LPFC_PCI_DEV_LP);
12238 	if (error)
12239 		goto out_disable_pci_dev;
12240 
12241 	/* Set up SLI-3 specific device PCI memory space */
12242 	error = lpfc_sli_pci_mem_setup(phba);
12243 	if (error) {
12244 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12245 				"1402 Failed to set up pci memory space.\n");
12246 		goto out_disable_pci_dev;
12247 	}
12248 
12249 	/* Set up SLI-3 specific device driver resources */
12250 	error = lpfc_sli_driver_resource_setup(phba);
12251 	if (error) {
12252 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12253 				"1404 Failed to set up driver resource.\n");
12254 		goto out_unset_pci_mem_s3;
12255 	}
12256 
12257 	/* Initialize and populate the iocb list per host */
12258 
12259 	error = lpfc_init_iocb_list(phba, LPFC_IOCB_LIST_CNT);
12260 	if (error) {
12261 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12262 				"1405 Failed to initialize iocb list.\n");
12263 		goto out_unset_driver_resource_s3;
12264 	}
12265 
12266 	/* Set up common device driver resources */
12267 	error = lpfc_setup_driver_resource_phase2(phba);
12268 	if (error) {
12269 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12270 				"1406 Failed to set up driver resource.\n");
12271 		goto out_free_iocb_list;
12272 	}
12273 
12274 	/* Get the default values for Model Name and Description */
12275 	lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
12276 
12277 	/* Create SCSI host to the physical port */
12278 	error = lpfc_create_shost(phba);
12279 	if (error) {
12280 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12281 				"1407 Failed to create scsi host.\n");
12282 		goto out_unset_driver_resource;
12283 	}
12284 
12285 	/* Configure sysfs attributes */
12286 	vport = phba->pport;
12287 	error = lpfc_alloc_sysfs_attr(vport);
12288 	if (error) {
12289 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12290 				"1476 Failed to allocate sysfs attr\n");
12291 		goto out_destroy_shost;
12292 	}
12293 
12294 	shost = lpfc_shost_from_vport(vport); /* save shost for error cleanup */
12295 	/* Now, trying to enable interrupt and bring up the device */
12296 	cfg_mode = phba->cfg_use_msi;
12297 	while (true) {
12298 		/* Put device to a known state before enabling interrupt */
12299 		lpfc_stop_port(phba);
12300 		/* Configure and enable interrupt */
12301 		intr_mode = lpfc_sli_enable_intr(phba, cfg_mode);
12302 		if (intr_mode == LPFC_INTR_ERROR) {
12303 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12304 					"0431 Failed to enable interrupt.\n");
12305 			error = -ENODEV;
12306 			goto out_free_sysfs_attr;
12307 		}
12308 		/* SLI-3 HBA setup */
12309 		if (lpfc_sli_hba_setup(phba)) {
12310 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12311 					"1477 Failed to set up hba\n");
12312 			error = -ENODEV;
12313 			goto out_remove_device;
12314 		}
12315 
12316 		/* Wait 50ms for the interrupts of previous mailbox commands */
12317 		msleep(50);
12318 		/* Check active interrupts on message signaled interrupts */
12319 		if (intr_mode == 0 ||
12320 		    phba->sli.slistat.sli_intr > LPFC_MSIX_VECTORS) {
12321 			/* Log the current active interrupt mode */
12322 			phba->intr_mode = intr_mode;
12323 			lpfc_log_intr_mode(phba, intr_mode);
12324 			break;
12325 		} else {
12326 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12327 					"0447 Configure interrupt mode (%d) "
12328 					"failed active interrupt test.\n",
12329 					intr_mode);
12330 			/* Disable the current interrupt mode */
12331 			lpfc_sli_disable_intr(phba);
12332 			/* Try next level of interrupt mode */
12333 			cfg_mode = --intr_mode;
12334 		}
12335 	}
12336 
12337 	/* Perform post initialization setup */
12338 	lpfc_post_init_setup(phba);
12339 
12340 	/* Check if there are static vports to be created. */
12341 	lpfc_create_static_vport(phba);
12342 
12343 	return 0;
12344 
12345 out_remove_device:
12346 	lpfc_unset_hba(phba);
12347 out_free_sysfs_attr:
12348 	lpfc_free_sysfs_attr(vport);
12349 out_destroy_shost:
12350 	lpfc_destroy_shost(phba);
12351 out_unset_driver_resource:
12352 	lpfc_unset_driver_resource_phase2(phba);
12353 out_free_iocb_list:
12354 	lpfc_free_iocb_list(phba);
12355 out_unset_driver_resource_s3:
12356 	lpfc_sli_driver_resource_unset(phba);
12357 out_unset_pci_mem_s3:
12358 	lpfc_sli_pci_mem_unset(phba);
12359 out_disable_pci_dev:
12360 	lpfc_disable_pci_dev(phba);
12361 	if (shost)
12362 		scsi_host_put(shost);
12363 out_free_phba:
12364 	lpfc_hba_free(phba);
12365 	return error;
12366 }
12367 
12368 /**
12369  * lpfc_pci_remove_one_s3 - PCI func to unreg SLI-3 device from PCI subsystem.
12370  * @pdev: pointer to PCI device
12371  *
12372  * This routine is to be called to disattach a device with SLI-3 interface
12373  * spec from PCI subsystem. When an Emulex HBA with SLI-3 interface spec is
12374  * removed from PCI bus, it performs all the necessary cleanup for the HBA
12375  * device to be removed from the PCI subsystem properly.
12376  **/
12377 static void
12378 lpfc_pci_remove_one_s3(struct pci_dev *pdev)
12379 {
12380 	struct Scsi_Host  *shost = pci_get_drvdata(pdev);
12381 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
12382 	struct lpfc_vport **vports;
12383 	struct lpfc_hba   *phba = vport->phba;
12384 	int i;
12385 
12386 	spin_lock_irq(&phba->hbalock);
12387 	vport->load_flag |= FC_UNLOADING;
12388 	spin_unlock_irq(&phba->hbalock);
12389 
12390 	lpfc_free_sysfs_attr(vport);
12391 
12392 	/* Release all the vports against this physical port */
12393 	vports = lpfc_create_vport_work_array(phba);
12394 	if (vports != NULL)
12395 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
12396 			if (vports[i]->port_type == LPFC_PHYSICAL_PORT)
12397 				continue;
12398 			fc_vport_terminate(vports[i]->fc_vport);
12399 		}
12400 	lpfc_destroy_vport_work_array(phba, vports);
12401 
12402 	/* Remove FC host and then SCSI host with the physical port */
12403 	fc_remove_host(shost);
12404 	scsi_remove_host(shost);
12405 
12406 	lpfc_cleanup(vport);
12407 
12408 	/*
12409 	 * Bring down the SLI Layer. This step disable all interrupts,
12410 	 * clears the rings, discards all mailbox commands, and resets
12411 	 * the HBA.
12412 	 */
12413 
12414 	/* HBA interrupt will be disabled after this call */
12415 	lpfc_sli_hba_down(phba);
12416 	/* Stop kthread signal shall trigger work_done one more time */
12417 	kthread_stop(phba->worker_thread);
12418 	/* Final cleanup of txcmplq and reset the HBA */
12419 	lpfc_sli_brdrestart(phba);
12420 
12421 	kfree(phba->vpi_bmask);
12422 	kfree(phba->vpi_ids);
12423 
12424 	lpfc_stop_hba_timers(phba);
12425 	spin_lock_irq(&phba->port_list_lock);
12426 	list_del_init(&vport->listentry);
12427 	spin_unlock_irq(&phba->port_list_lock);
12428 
12429 	lpfc_debugfs_terminate(vport);
12430 
12431 	/* Disable SR-IOV if enabled */
12432 	if (phba->cfg_sriov_nr_virtfn)
12433 		pci_disable_sriov(pdev);
12434 
12435 	/* Disable interrupt */
12436 	lpfc_sli_disable_intr(phba);
12437 
12438 	scsi_host_put(shost);
12439 
12440 	/*
12441 	 * Call scsi_free before mem_free since scsi bufs are released to their
12442 	 * corresponding pools here.
12443 	 */
12444 	lpfc_scsi_free(phba);
12445 	lpfc_free_iocb_list(phba);
12446 
12447 	lpfc_mem_free_all(phba);
12448 
12449 	dma_free_coherent(&pdev->dev, lpfc_sli_hbq_size(),
12450 			  phba->hbqslimp.virt, phba->hbqslimp.phys);
12451 
12452 	/* Free resources associated with SLI2 interface */
12453 	dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
12454 			  phba->slim2p.virt, phba->slim2p.phys);
12455 
12456 	/* unmap adapter SLIM and Control Registers */
12457 	iounmap(phba->ctrl_regs_memmap_p);
12458 	iounmap(phba->slim_memmap_p);
12459 
12460 	lpfc_hba_free(phba);
12461 
12462 	pci_release_mem_regions(pdev);
12463 	pci_disable_device(pdev);
12464 }
12465 
12466 /**
12467  * lpfc_pci_suspend_one_s3 - PCI func to suspend SLI-3 device for power mgmnt
12468  * @pdev: pointer to PCI device
12469  * @msg: power management message
12470  *
12471  * This routine is to be called from the kernel's PCI subsystem to support
12472  * system Power Management (PM) to device with SLI-3 interface spec. When
12473  * PM invokes this method, it quiesces the device by stopping the driver's
12474  * worker thread for the device, turning off device's interrupt and DMA,
12475  * and bring the device offline. Note that as the driver implements the
12476  * minimum PM requirements to a power-aware driver's PM support for the
12477  * suspend/resume -- all the possible PM messages (SUSPEND, HIBERNATE, FREEZE)
12478  * to the suspend() method call will be treated as SUSPEND and the driver will
12479  * fully reinitialize its device during resume() method call, the driver will
12480  * set device to PCI_D3hot state in PCI config space instead of setting it
12481  * according to the @msg provided by the PM.
12482  *
12483  * Return code
12484  * 	0 - driver suspended the device
12485  * 	Error otherwise
12486  **/
12487 static int
12488 lpfc_pci_suspend_one_s3(struct pci_dev *pdev, pm_message_t msg)
12489 {
12490 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
12491 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
12492 
12493 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12494 			"0473 PCI device Power Management suspend.\n");
12495 
12496 	/* Bring down the device */
12497 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
12498 	lpfc_offline(phba);
12499 	kthread_stop(phba->worker_thread);
12500 
12501 	/* Disable interrupt from device */
12502 	lpfc_sli_disable_intr(phba);
12503 
12504 	/* Save device state to PCI config space */
12505 	pci_save_state(pdev);
12506 	pci_set_power_state(pdev, PCI_D3hot);
12507 
12508 	return 0;
12509 }
12510 
12511 /**
12512  * lpfc_pci_resume_one_s3 - PCI func to resume SLI-3 device for power mgmnt
12513  * @pdev: pointer to PCI device
12514  *
12515  * This routine is to be called from the kernel's PCI subsystem to support
12516  * system Power Management (PM) to device with SLI-3 interface spec. When PM
12517  * invokes this method, it restores the device's PCI config space state and
12518  * fully reinitializes the device and brings it online. Note that as the
12519  * driver implements the minimum PM requirements to a power-aware driver's
12520  * PM for suspend/resume -- all the possible PM messages (SUSPEND, HIBERNATE,
12521  * FREEZE) to the suspend() method call will be treated as SUSPEND and the
12522  * driver will fully reinitialize its device during resume() method call,
12523  * the device will be set to PCI_D0 directly in PCI config space before
12524  * restoring the state.
12525  *
12526  * Return code
12527  * 	0 - driver suspended the device
12528  * 	Error otherwise
12529  **/
12530 static int
12531 lpfc_pci_resume_one_s3(struct pci_dev *pdev)
12532 {
12533 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
12534 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
12535 	uint32_t intr_mode;
12536 	int error;
12537 
12538 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12539 			"0452 PCI device Power Management resume.\n");
12540 
12541 	/* Restore device state from PCI config space */
12542 	pci_set_power_state(pdev, PCI_D0);
12543 	pci_restore_state(pdev);
12544 
12545 	/*
12546 	 * As the new kernel behavior of pci_restore_state() API call clears
12547 	 * device saved_state flag, need to save the restored state again.
12548 	 */
12549 	pci_save_state(pdev);
12550 
12551 	if (pdev->is_busmaster)
12552 		pci_set_master(pdev);
12553 
12554 	/* Startup the kernel thread for this host adapter. */
12555 	phba->worker_thread = kthread_run(lpfc_do_work, phba,
12556 					"lpfc_worker_%d", phba->brd_no);
12557 	if (IS_ERR(phba->worker_thread)) {
12558 		error = PTR_ERR(phba->worker_thread);
12559 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12560 				"0434 PM resume failed to start worker "
12561 				"thread: error=x%x.\n", error);
12562 		return error;
12563 	}
12564 
12565 	/* Configure and enable interrupt */
12566 	intr_mode = lpfc_sli_enable_intr(phba, phba->intr_mode);
12567 	if (intr_mode == LPFC_INTR_ERROR) {
12568 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12569 				"0430 PM resume Failed to enable interrupt\n");
12570 		return -EIO;
12571 	} else
12572 		phba->intr_mode = intr_mode;
12573 
12574 	/* Restart HBA and bring it online */
12575 	lpfc_sli_brdrestart(phba);
12576 	lpfc_online(phba);
12577 
12578 	/* Log the current active interrupt mode */
12579 	lpfc_log_intr_mode(phba, phba->intr_mode);
12580 
12581 	return 0;
12582 }
12583 
12584 /**
12585  * lpfc_sli_prep_dev_for_recover - Prepare SLI3 device for pci slot recover
12586  * @phba: pointer to lpfc hba data structure.
12587  *
12588  * This routine is called to prepare the SLI3 device for PCI slot recover. It
12589  * aborts all the outstanding SCSI I/Os to the pci device.
12590  **/
12591 static void
12592 lpfc_sli_prep_dev_for_recover(struct lpfc_hba *phba)
12593 {
12594 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12595 			"2723 PCI channel I/O abort preparing for recovery\n");
12596 
12597 	/*
12598 	 * There may be errored I/Os through HBA, abort all I/Os on txcmplq
12599 	 * and let the SCSI mid-layer to retry them to recover.
12600 	 */
12601 	lpfc_sli_abort_fcp_rings(phba);
12602 }
12603 
12604 /**
12605  * lpfc_sli_prep_dev_for_reset - Prepare SLI3 device for pci slot reset
12606  * @phba: pointer to lpfc hba data structure.
12607  *
12608  * This routine is called to prepare the SLI3 device for PCI slot reset. It
12609  * disables the device interrupt and pci device, and aborts the internal FCP
12610  * pending I/Os.
12611  **/
12612 static void
12613 lpfc_sli_prep_dev_for_reset(struct lpfc_hba *phba)
12614 {
12615 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12616 			"2710 PCI channel disable preparing for reset\n");
12617 
12618 	/* Block any management I/Os to the device */
12619 	lpfc_block_mgmt_io(phba, LPFC_MBX_WAIT);
12620 
12621 	/* Block all SCSI devices' I/Os on the host */
12622 	lpfc_scsi_dev_block(phba);
12623 
12624 	/* Flush all driver's outstanding SCSI I/Os as we are to reset */
12625 	lpfc_sli_flush_io_rings(phba);
12626 
12627 	/* stop all timers */
12628 	lpfc_stop_hba_timers(phba);
12629 
12630 	/* Disable interrupt and pci device */
12631 	lpfc_sli_disable_intr(phba);
12632 	pci_disable_device(phba->pcidev);
12633 }
12634 
12635 /**
12636  * lpfc_sli_prep_dev_for_perm_failure - Prepare SLI3 dev for pci slot disable
12637  * @phba: pointer to lpfc hba data structure.
12638  *
12639  * This routine is called to prepare the SLI3 device for PCI slot permanently
12640  * disabling. It blocks the SCSI transport layer traffic and flushes the FCP
12641  * pending I/Os.
12642  **/
12643 static void
12644 lpfc_sli_prep_dev_for_perm_failure(struct lpfc_hba *phba)
12645 {
12646 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12647 			"2711 PCI channel permanent disable for failure\n");
12648 	/* Block all SCSI devices' I/Os on the host */
12649 	lpfc_scsi_dev_block(phba);
12650 
12651 	/* stop all timers */
12652 	lpfc_stop_hba_timers(phba);
12653 
12654 	/* Clean up all driver's outstanding SCSI I/Os */
12655 	lpfc_sli_flush_io_rings(phba);
12656 }
12657 
12658 /**
12659  * lpfc_io_error_detected_s3 - Method for handling SLI-3 device PCI I/O error
12660  * @pdev: pointer to PCI device.
12661  * @state: the current PCI connection state.
12662  *
12663  * This routine is called from the PCI subsystem for I/O error handling to
12664  * device with SLI-3 interface spec. This function is called by the PCI
12665  * subsystem after a PCI bus error affecting this device has been detected.
12666  * When this function is invoked, it will need to stop all the I/Os and
12667  * interrupt(s) to the device. Once that is done, it will return
12668  * PCI_ERS_RESULT_NEED_RESET for the PCI subsystem to perform proper recovery
12669  * as desired.
12670  *
12671  * Return codes
12672  * 	PCI_ERS_RESULT_CAN_RECOVER - can be recovered with reset_link
12673  * 	PCI_ERS_RESULT_NEED_RESET - need to reset before recovery
12674  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
12675  **/
12676 static pci_ers_result_t
12677 lpfc_io_error_detected_s3(struct pci_dev *pdev, pci_channel_state_t state)
12678 {
12679 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
12680 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
12681 
12682 	switch (state) {
12683 	case pci_channel_io_normal:
12684 		/* Non-fatal error, prepare for recovery */
12685 		lpfc_sli_prep_dev_for_recover(phba);
12686 		return PCI_ERS_RESULT_CAN_RECOVER;
12687 	case pci_channel_io_frozen:
12688 		/* Fatal error, prepare for slot reset */
12689 		lpfc_sli_prep_dev_for_reset(phba);
12690 		return PCI_ERS_RESULT_NEED_RESET;
12691 	case pci_channel_io_perm_failure:
12692 		/* Permanent failure, prepare for device down */
12693 		lpfc_sli_prep_dev_for_perm_failure(phba);
12694 		return PCI_ERS_RESULT_DISCONNECT;
12695 	default:
12696 		/* Unknown state, prepare and request slot reset */
12697 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12698 				"0472 Unknown PCI error state: x%x\n", state);
12699 		lpfc_sli_prep_dev_for_reset(phba);
12700 		return PCI_ERS_RESULT_NEED_RESET;
12701 	}
12702 }
12703 
12704 /**
12705  * lpfc_io_slot_reset_s3 - Method for restarting PCI SLI-3 device from scratch.
12706  * @pdev: pointer to PCI device.
12707  *
12708  * This routine is called from the PCI subsystem for error handling to
12709  * device with SLI-3 interface spec. This is called after PCI bus has been
12710  * reset to restart the PCI card from scratch, as if from a cold-boot.
12711  * During the PCI subsystem error recovery, after driver returns
12712  * PCI_ERS_RESULT_NEED_RESET, the PCI subsystem will perform proper error
12713  * recovery and then call this routine before calling the .resume method
12714  * to recover the device. This function will initialize the HBA device,
12715  * enable the interrupt, but it will just put the HBA to offline state
12716  * without passing any I/O traffic.
12717  *
12718  * Return codes
12719  * 	PCI_ERS_RESULT_RECOVERED - the device has been recovered
12720  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
12721  */
12722 static pci_ers_result_t
12723 lpfc_io_slot_reset_s3(struct pci_dev *pdev)
12724 {
12725 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
12726 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
12727 	struct lpfc_sli *psli = &phba->sli;
12728 	uint32_t intr_mode;
12729 
12730 	dev_printk(KERN_INFO, &pdev->dev, "recovering from a slot reset.\n");
12731 	if (pci_enable_device_mem(pdev)) {
12732 		printk(KERN_ERR "lpfc: Cannot re-enable "
12733 			"PCI device after reset.\n");
12734 		return PCI_ERS_RESULT_DISCONNECT;
12735 	}
12736 
12737 	pci_restore_state(pdev);
12738 
12739 	/*
12740 	 * As the new kernel behavior of pci_restore_state() API call clears
12741 	 * device saved_state flag, need to save the restored state again.
12742 	 */
12743 	pci_save_state(pdev);
12744 
12745 	if (pdev->is_busmaster)
12746 		pci_set_master(pdev);
12747 
12748 	spin_lock_irq(&phba->hbalock);
12749 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
12750 	spin_unlock_irq(&phba->hbalock);
12751 
12752 	/* Configure and enable interrupt */
12753 	intr_mode = lpfc_sli_enable_intr(phba, phba->intr_mode);
12754 	if (intr_mode == LPFC_INTR_ERROR) {
12755 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12756 				"0427 Cannot re-enable interrupt after "
12757 				"slot reset.\n");
12758 		return PCI_ERS_RESULT_DISCONNECT;
12759 	} else
12760 		phba->intr_mode = intr_mode;
12761 
12762 	/* Take device offline, it will perform cleanup */
12763 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
12764 	lpfc_offline(phba);
12765 	lpfc_sli_brdrestart(phba);
12766 
12767 	/* Log the current active interrupt mode */
12768 	lpfc_log_intr_mode(phba, phba->intr_mode);
12769 
12770 	return PCI_ERS_RESULT_RECOVERED;
12771 }
12772 
12773 /**
12774  * lpfc_io_resume_s3 - Method for resuming PCI I/O operation on SLI-3 device.
12775  * @pdev: pointer to PCI device
12776  *
12777  * This routine is called from the PCI subsystem for error handling to device
12778  * with SLI-3 interface spec. It is called when kernel error recovery tells
12779  * the lpfc driver that it is ok to resume normal PCI operation after PCI bus
12780  * error recovery. After this call, traffic can start to flow from this device
12781  * again.
12782  */
12783 static void
12784 lpfc_io_resume_s3(struct pci_dev *pdev)
12785 {
12786 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
12787 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
12788 
12789 	/* Bring device online, it will be no-op for non-fatal error resume */
12790 	lpfc_online(phba);
12791 }
12792 
12793 /**
12794  * lpfc_sli4_get_els_iocb_cnt - Calculate the # of ELS IOCBs to reserve
12795  * @phba: pointer to lpfc hba data structure.
12796  *
12797  * returns the number of ELS/CT IOCBs to reserve
12798  **/
12799 int
12800 lpfc_sli4_get_els_iocb_cnt(struct lpfc_hba *phba)
12801 {
12802 	int max_xri = phba->sli4_hba.max_cfg_param.max_xri;
12803 
12804 	if (phba->sli_rev == LPFC_SLI_REV4) {
12805 		if (max_xri <= 100)
12806 			return 10;
12807 		else if (max_xri <= 256)
12808 			return 25;
12809 		else if (max_xri <= 512)
12810 			return 50;
12811 		else if (max_xri <= 1024)
12812 			return 100;
12813 		else if (max_xri <= 1536)
12814 			return 150;
12815 		else if (max_xri <= 2048)
12816 			return 200;
12817 		else
12818 			return 250;
12819 	} else
12820 		return 0;
12821 }
12822 
12823 /**
12824  * lpfc_sli4_get_iocb_cnt - Calculate the # of total IOCBs to reserve
12825  * @phba: pointer to lpfc hba data structure.
12826  *
12827  * returns the number of ELS/CT + NVMET IOCBs to reserve
12828  **/
12829 int
12830 lpfc_sli4_get_iocb_cnt(struct lpfc_hba *phba)
12831 {
12832 	int max_xri = lpfc_sli4_get_els_iocb_cnt(phba);
12833 
12834 	if (phba->nvmet_support)
12835 		max_xri += LPFC_NVMET_BUF_POST;
12836 	return max_xri;
12837 }
12838 
12839 
12840 static int
12841 lpfc_log_write_firmware_error(struct lpfc_hba *phba, uint32_t offset,
12842 	uint32_t magic_number, uint32_t ftype, uint32_t fid, uint32_t fsize,
12843 	const struct firmware *fw)
12844 {
12845 	int rc;
12846 
12847 	/* Three cases:  (1) FW was not supported on the detected adapter.
12848 	 * (2) FW update has been locked out administratively.
12849 	 * (3) Some other error during FW update.
12850 	 * In each case, an unmaskable message is written to the console
12851 	 * for admin diagnosis.
12852 	 */
12853 	if (offset == ADD_STATUS_FW_NOT_SUPPORTED ||
12854 	    (phba->pcidev->device == PCI_DEVICE_ID_LANCER_G6_FC &&
12855 	     magic_number != MAGIC_NUMBER_G6) ||
12856 	    (phba->pcidev->device == PCI_DEVICE_ID_LANCER_G7_FC &&
12857 	     magic_number != MAGIC_NUMBER_G7)) {
12858 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12859 				"3030 This firmware version is not supported on"
12860 				" this HBA model. Device:%x Magic:%x Type:%x "
12861 				"ID:%x Size %d %zd\n",
12862 				phba->pcidev->device, magic_number, ftype, fid,
12863 				fsize, fw->size);
12864 		rc = -EINVAL;
12865 	} else if (offset == ADD_STATUS_FW_DOWNLOAD_HW_DISABLED) {
12866 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12867 				"3021 Firmware downloads have been prohibited "
12868 				"by a system configuration setting on "
12869 				"Device:%x Magic:%x Type:%x ID:%x Size %d "
12870 				"%zd\n",
12871 				phba->pcidev->device, magic_number, ftype, fid,
12872 				fsize, fw->size);
12873 		rc = -EACCES;
12874 	} else {
12875 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12876 				"3022 FW Download failed. Add Status x%x "
12877 				"Device:%x Magic:%x Type:%x ID:%x Size %d "
12878 				"%zd\n",
12879 				offset, phba->pcidev->device, magic_number,
12880 				ftype, fid, fsize, fw->size);
12881 		rc = -EIO;
12882 	}
12883 	return rc;
12884 }
12885 
12886 /**
12887  * lpfc_write_firmware - attempt to write a firmware image to the port
12888  * @fw: pointer to firmware image returned from request_firmware.
12889  * @context: pointer to firmware image returned from request_firmware.
12890  * @ret: return value this routine provides to the caller.
12891  *
12892  **/
12893 static void
12894 lpfc_write_firmware(const struct firmware *fw, void *context)
12895 {
12896 	struct lpfc_hba *phba = (struct lpfc_hba *)context;
12897 	char fwrev[FW_REV_STR_SIZE];
12898 	struct lpfc_grp_hdr *image;
12899 	struct list_head dma_buffer_list;
12900 	int i, rc = 0;
12901 	struct lpfc_dmabuf *dmabuf, *next;
12902 	uint32_t offset = 0, temp_offset = 0;
12903 	uint32_t magic_number, ftype, fid, fsize;
12904 
12905 	/* It can be null in no-wait mode, sanity check */
12906 	if (!fw) {
12907 		rc = -ENXIO;
12908 		goto out;
12909 	}
12910 	image = (struct lpfc_grp_hdr *)fw->data;
12911 
12912 	magic_number = be32_to_cpu(image->magic_number);
12913 	ftype = bf_get_be32(lpfc_grp_hdr_file_type, image);
12914 	fid = bf_get_be32(lpfc_grp_hdr_id, image);
12915 	fsize = be32_to_cpu(image->size);
12916 
12917 	INIT_LIST_HEAD(&dma_buffer_list);
12918 	lpfc_decode_firmware_rev(phba, fwrev, 1);
12919 	if (strncmp(fwrev, image->revision, strnlen(image->revision, 16))) {
12920 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12921 				"3023 Updating Firmware, Current Version:%s "
12922 				"New Version:%s\n",
12923 				fwrev, image->revision);
12924 		for (i = 0; i < LPFC_MBX_WR_CONFIG_MAX_BDE; i++) {
12925 			dmabuf = kzalloc(sizeof(struct lpfc_dmabuf),
12926 					 GFP_KERNEL);
12927 			if (!dmabuf) {
12928 				rc = -ENOMEM;
12929 				goto release_out;
12930 			}
12931 			dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
12932 							  SLI4_PAGE_SIZE,
12933 							  &dmabuf->phys,
12934 							  GFP_KERNEL);
12935 			if (!dmabuf->virt) {
12936 				kfree(dmabuf);
12937 				rc = -ENOMEM;
12938 				goto release_out;
12939 			}
12940 			list_add_tail(&dmabuf->list, &dma_buffer_list);
12941 		}
12942 		while (offset < fw->size) {
12943 			temp_offset = offset;
12944 			list_for_each_entry(dmabuf, &dma_buffer_list, list) {
12945 				if (temp_offset + SLI4_PAGE_SIZE > fw->size) {
12946 					memcpy(dmabuf->virt,
12947 					       fw->data + temp_offset,
12948 					       fw->size - temp_offset);
12949 					temp_offset = fw->size;
12950 					break;
12951 				}
12952 				memcpy(dmabuf->virt, fw->data + temp_offset,
12953 				       SLI4_PAGE_SIZE);
12954 				temp_offset += SLI4_PAGE_SIZE;
12955 			}
12956 			rc = lpfc_wr_object(phba, &dma_buffer_list,
12957 				    (fw->size - offset), &offset);
12958 			if (rc) {
12959 				rc = lpfc_log_write_firmware_error(phba, offset,
12960 								   magic_number,
12961 								   ftype,
12962 								   fid,
12963 								   fsize,
12964 								   fw);
12965 				goto release_out;
12966 			}
12967 		}
12968 		rc = offset;
12969 	} else
12970 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12971 				"3029 Skipped Firmware update, Current "
12972 				"Version:%s New Version:%s\n",
12973 				fwrev, image->revision);
12974 
12975 release_out:
12976 	list_for_each_entry_safe(dmabuf, next, &dma_buffer_list, list) {
12977 		list_del(&dmabuf->list);
12978 		dma_free_coherent(&phba->pcidev->dev, SLI4_PAGE_SIZE,
12979 				  dmabuf->virt, dmabuf->phys);
12980 		kfree(dmabuf);
12981 	}
12982 	release_firmware(fw);
12983 out:
12984 	if (rc < 0)
12985 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12986 				"3062 Firmware update error, status %d.\n", rc);
12987 	else
12988 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12989 				"3024 Firmware update success: size %d.\n", rc);
12990 }
12991 
12992 /**
12993  * lpfc_sli4_request_firmware_update - Request linux generic firmware upgrade
12994  * @phba: pointer to lpfc hba data structure.
12995  *
12996  * This routine is called to perform Linux generic firmware upgrade on device
12997  * that supports such feature.
12998  **/
12999 int
13000 lpfc_sli4_request_firmware_update(struct lpfc_hba *phba, uint8_t fw_upgrade)
13001 {
13002 	uint8_t file_name[ELX_MODEL_NAME_SIZE];
13003 	int ret;
13004 	const struct firmware *fw;
13005 
13006 	/* Only supported on SLI4 interface type 2 for now */
13007 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) <
13008 	    LPFC_SLI_INTF_IF_TYPE_2)
13009 		return -EPERM;
13010 
13011 	snprintf(file_name, ELX_MODEL_NAME_SIZE, "%s.grp", phba->ModelName);
13012 
13013 	if (fw_upgrade == INT_FW_UPGRADE) {
13014 		ret = request_firmware_nowait(THIS_MODULE, FW_ACTION_HOTPLUG,
13015 					file_name, &phba->pcidev->dev,
13016 					GFP_KERNEL, (void *)phba,
13017 					lpfc_write_firmware);
13018 	} else if (fw_upgrade == RUN_FW_UPGRADE) {
13019 		ret = request_firmware(&fw, file_name, &phba->pcidev->dev);
13020 		if (!ret)
13021 			lpfc_write_firmware(fw, (void *)phba);
13022 	} else {
13023 		ret = -EINVAL;
13024 	}
13025 
13026 	return ret;
13027 }
13028 
13029 /**
13030  * lpfc_pci_probe_one_s4 - PCI probe func to reg SLI-4 device to PCI subsys
13031  * @pdev: pointer to PCI device
13032  * @pid: pointer to PCI device identifier
13033  *
13034  * This routine is called from the kernel's PCI subsystem to device with
13035  * SLI-4 interface spec. When an Emulex HBA with SLI-4 interface spec is
13036  * presented on PCI bus, the kernel PCI subsystem looks at PCI device-specific
13037  * information of the device and driver to see if the driver state that it
13038  * can support this kind of device. If the match is successful, the driver
13039  * core invokes this routine. If this routine determines it can claim the HBA,
13040  * it does all the initialization that it needs to do to handle the HBA
13041  * properly.
13042  *
13043  * Return code
13044  * 	0 - driver can claim the device
13045  * 	negative value - driver can not claim the device
13046  **/
13047 static int
13048 lpfc_pci_probe_one_s4(struct pci_dev *pdev, const struct pci_device_id *pid)
13049 {
13050 	struct lpfc_hba   *phba;
13051 	struct lpfc_vport *vport = NULL;
13052 	struct Scsi_Host  *shost = NULL;
13053 	int error;
13054 	uint32_t cfg_mode, intr_mode;
13055 
13056 	/* Allocate memory for HBA structure */
13057 	phba = lpfc_hba_alloc(pdev);
13058 	if (!phba)
13059 		return -ENOMEM;
13060 
13061 	/* Perform generic PCI device enabling operation */
13062 	error = lpfc_enable_pci_dev(phba);
13063 	if (error)
13064 		goto out_free_phba;
13065 
13066 	/* Set up SLI API function jump table for PCI-device group-1 HBAs */
13067 	error = lpfc_api_table_setup(phba, LPFC_PCI_DEV_OC);
13068 	if (error)
13069 		goto out_disable_pci_dev;
13070 
13071 	/* Set up SLI-4 specific device PCI memory space */
13072 	error = lpfc_sli4_pci_mem_setup(phba);
13073 	if (error) {
13074 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13075 				"1410 Failed to set up pci memory space.\n");
13076 		goto out_disable_pci_dev;
13077 	}
13078 
13079 	/* Set up SLI-4 Specific device driver resources */
13080 	error = lpfc_sli4_driver_resource_setup(phba);
13081 	if (error) {
13082 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13083 				"1412 Failed to set up driver resource.\n");
13084 		goto out_unset_pci_mem_s4;
13085 	}
13086 
13087 	INIT_LIST_HEAD(&phba->active_rrq_list);
13088 	INIT_LIST_HEAD(&phba->fcf.fcf_pri_list);
13089 
13090 	/* Set up common device driver resources */
13091 	error = lpfc_setup_driver_resource_phase2(phba);
13092 	if (error) {
13093 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13094 				"1414 Failed to set up driver resource.\n");
13095 		goto out_unset_driver_resource_s4;
13096 	}
13097 
13098 	/* Get the default values for Model Name and Description */
13099 	lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
13100 
13101 	/* Now, trying to enable interrupt and bring up the device */
13102 	cfg_mode = phba->cfg_use_msi;
13103 
13104 	/* Put device to a known state before enabling interrupt */
13105 	phba->pport = NULL;
13106 	lpfc_stop_port(phba);
13107 
13108 	/* Init cpu_map array */
13109 	lpfc_cpu_map_array_init(phba);
13110 
13111 	/* Init hba_eq_hdl array */
13112 	lpfc_hba_eq_hdl_array_init(phba);
13113 
13114 	/* Configure and enable interrupt */
13115 	intr_mode = lpfc_sli4_enable_intr(phba, cfg_mode);
13116 	if (intr_mode == LPFC_INTR_ERROR) {
13117 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13118 				"0426 Failed to enable interrupt.\n");
13119 		error = -ENODEV;
13120 		goto out_unset_driver_resource;
13121 	}
13122 	/* Default to single EQ for non-MSI-X */
13123 	if (phba->intr_type != MSIX) {
13124 		phba->cfg_irq_chann = 1;
13125 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13126 			if (phba->nvmet_support)
13127 				phba->cfg_nvmet_mrq = 1;
13128 		}
13129 	}
13130 	lpfc_cpu_affinity_check(phba, phba->cfg_irq_chann);
13131 
13132 	/* Create SCSI host to the physical port */
13133 	error = lpfc_create_shost(phba);
13134 	if (error) {
13135 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13136 				"1415 Failed to create scsi host.\n");
13137 		goto out_disable_intr;
13138 	}
13139 	vport = phba->pport;
13140 	shost = lpfc_shost_from_vport(vport); /* save shost for error cleanup */
13141 
13142 	/* Configure sysfs attributes */
13143 	error = lpfc_alloc_sysfs_attr(vport);
13144 	if (error) {
13145 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13146 				"1416 Failed to allocate sysfs attr\n");
13147 		goto out_destroy_shost;
13148 	}
13149 
13150 	/* Set up SLI-4 HBA */
13151 	if (lpfc_sli4_hba_setup(phba)) {
13152 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13153 				"1421 Failed to set up hba\n");
13154 		error = -ENODEV;
13155 		goto out_free_sysfs_attr;
13156 	}
13157 
13158 	/* Log the current active interrupt mode */
13159 	phba->intr_mode = intr_mode;
13160 	lpfc_log_intr_mode(phba, intr_mode);
13161 
13162 	/* Perform post initialization setup */
13163 	lpfc_post_init_setup(phba);
13164 
13165 	/* NVME support in FW earlier in the driver load corrects the
13166 	 * FC4 type making a check for nvme_support unnecessary.
13167 	 */
13168 	if (phba->nvmet_support == 0) {
13169 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13170 			/* Create NVME binding with nvme_fc_transport. This
13171 			 * ensures the vport is initialized.  If the localport
13172 			 * create fails, it should not unload the driver to
13173 			 * support field issues.
13174 			 */
13175 			error = lpfc_nvme_create_localport(vport);
13176 			if (error) {
13177 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13178 						"6004 NVME registration "
13179 						"failed, error x%x\n",
13180 						error);
13181 			}
13182 		}
13183 	}
13184 
13185 	/* check for firmware upgrade or downgrade */
13186 	if (phba->cfg_request_firmware_upgrade)
13187 		lpfc_sli4_request_firmware_update(phba, INT_FW_UPGRADE);
13188 
13189 	/* Check if there are static vports to be created. */
13190 	lpfc_create_static_vport(phba);
13191 
13192 	/* Enable RAS FW log support */
13193 	lpfc_sli4_ras_setup(phba);
13194 
13195 	INIT_LIST_HEAD(&phba->poll_list);
13196 	timer_setup(&phba->cpuhp_poll_timer, lpfc_sli4_poll_hbtimer, 0);
13197 	cpuhp_state_add_instance_nocalls(lpfc_cpuhp_state, &phba->cpuhp);
13198 
13199 	return 0;
13200 
13201 out_free_sysfs_attr:
13202 	lpfc_free_sysfs_attr(vport);
13203 out_destroy_shost:
13204 	lpfc_destroy_shost(phba);
13205 out_disable_intr:
13206 	lpfc_sli4_disable_intr(phba);
13207 out_unset_driver_resource:
13208 	lpfc_unset_driver_resource_phase2(phba);
13209 out_unset_driver_resource_s4:
13210 	lpfc_sli4_driver_resource_unset(phba);
13211 out_unset_pci_mem_s4:
13212 	lpfc_sli4_pci_mem_unset(phba);
13213 out_disable_pci_dev:
13214 	lpfc_disable_pci_dev(phba);
13215 	if (shost)
13216 		scsi_host_put(shost);
13217 out_free_phba:
13218 	lpfc_hba_free(phba);
13219 	return error;
13220 }
13221 
13222 /**
13223  * lpfc_pci_remove_one_s4 - PCI func to unreg SLI-4 device from PCI subsystem
13224  * @pdev: pointer to PCI device
13225  *
13226  * This routine is called from the kernel's PCI subsystem to device with
13227  * SLI-4 interface spec. When an Emulex HBA with SLI-4 interface spec is
13228  * removed from PCI bus, it performs all the necessary cleanup for the HBA
13229  * device to be removed from the PCI subsystem properly.
13230  **/
13231 static void
13232 lpfc_pci_remove_one_s4(struct pci_dev *pdev)
13233 {
13234 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
13235 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
13236 	struct lpfc_vport **vports;
13237 	struct lpfc_hba *phba = vport->phba;
13238 	int i;
13239 
13240 	/* Mark the device unloading flag */
13241 	spin_lock_irq(&phba->hbalock);
13242 	vport->load_flag |= FC_UNLOADING;
13243 	spin_unlock_irq(&phba->hbalock);
13244 
13245 	/* Free the HBA sysfs attributes */
13246 	lpfc_free_sysfs_attr(vport);
13247 
13248 	/* Release all the vports against this physical port */
13249 	vports = lpfc_create_vport_work_array(phba);
13250 	if (vports != NULL)
13251 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
13252 			if (vports[i]->port_type == LPFC_PHYSICAL_PORT)
13253 				continue;
13254 			fc_vport_terminate(vports[i]->fc_vport);
13255 		}
13256 	lpfc_destroy_vport_work_array(phba, vports);
13257 
13258 	/* Remove FC host and then SCSI host with the physical port */
13259 	fc_remove_host(shost);
13260 	scsi_remove_host(shost);
13261 
13262 	/* Perform ndlp cleanup on the physical port.  The nvme and nvmet
13263 	 * localports are destroyed after to cleanup all transport memory.
13264 	 */
13265 	lpfc_cleanup(vport);
13266 	lpfc_nvmet_destroy_targetport(phba);
13267 	lpfc_nvme_destroy_localport(vport);
13268 
13269 	/* De-allocate multi-XRI pools */
13270 	if (phba->cfg_xri_rebalancing)
13271 		lpfc_destroy_multixri_pools(phba);
13272 
13273 	/*
13274 	 * Bring down the SLI Layer. This step disables all interrupts,
13275 	 * clears the rings, discards all mailbox commands, and resets
13276 	 * the HBA FCoE function.
13277 	 */
13278 	lpfc_debugfs_terminate(vport);
13279 
13280 	lpfc_stop_hba_timers(phba);
13281 	spin_lock_irq(&phba->port_list_lock);
13282 	list_del_init(&vport->listentry);
13283 	spin_unlock_irq(&phba->port_list_lock);
13284 
13285 	/* Perform scsi free before driver resource_unset since scsi
13286 	 * buffers are released to their corresponding pools here.
13287 	 */
13288 	lpfc_io_free(phba);
13289 	lpfc_free_iocb_list(phba);
13290 	lpfc_sli4_hba_unset(phba);
13291 
13292 	lpfc_unset_driver_resource_phase2(phba);
13293 	lpfc_sli4_driver_resource_unset(phba);
13294 
13295 	/* Unmap adapter Control and Doorbell registers */
13296 	lpfc_sli4_pci_mem_unset(phba);
13297 
13298 	/* Release PCI resources and disable device's PCI function */
13299 	scsi_host_put(shost);
13300 	lpfc_disable_pci_dev(phba);
13301 
13302 	/* Finally, free the driver's device data structure */
13303 	lpfc_hba_free(phba);
13304 
13305 	return;
13306 }
13307 
13308 /**
13309  * lpfc_pci_suspend_one_s4 - PCI func to suspend SLI-4 device for power mgmnt
13310  * @pdev: pointer to PCI device
13311  * @msg: power management message
13312  *
13313  * This routine is called from the kernel's PCI subsystem to support system
13314  * Power Management (PM) to device with SLI-4 interface spec. When PM invokes
13315  * this method, it quiesces the device by stopping the driver's worker
13316  * thread for the device, turning off device's interrupt and DMA, and bring
13317  * the device offline. Note that as the driver implements the minimum PM
13318  * requirements to a power-aware driver's PM support for suspend/resume -- all
13319  * the possible PM messages (SUSPEND, HIBERNATE, FREEZE) to the suspend()
13320  * method call will be treated as SUSPEND and the driver will fully
13321  * reinitialize its device during resume() method call, the driver will set
13322  * device to PCI_D3hot state in PCI config space instead of setting it
13323  * according to the @msg provided by the PM.
13324  *
13325  * Return code
13326  * 	0 - driver suspended the device
13327  * 	Error otherwise
13328  **/
13329 static int
13330 lpfc_pci_suspend_one_s4(struct pci_dev *pdev, pm_message_t msg)
13331 {
13332 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
13333 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
13334 
13335 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13336 			"2843 PCI device Power Management suspend.\n");
13337 
13338 	/* Bring down the device */
13339 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
13340 	lpfc_offline(phba);
13341 	kthread_stop(phba->worker_thread);
13342 
13343 	/* Disable interrupt from device */
13344 	lpfc_sli4_disable_intr(phba);
13345 	lpfc_sli4_queue_destroy(phba);
13346 
13347 	/* Save device state to PCI config space */
13348 	pci_save_state(pdev);
13349 	pci_set_power_state(pdev, PCI_D3hot);
13350 
13351 	return 0;
13352 }
13353 
13354 /**
13355  * lpfc_pci_resume_one_s4 - PCI func to resume SLI-4 device for power mgmnt
13356  * @pdev: pointer to PCI device
13357  *
13358  * This routine is called from the kernel's PCI subsystem to support system
13359  * Power Management (PM) to device with SLI-4 interface spac. When PM invokes
13360  * this method, it restores the device's PCI config space state and fully
13361  * reinitializes the device and brings it online. Note that as the driver
13362  * implements the minimum PM requirements to a power-aware driver's PM for
13363  * suspend/resume -- all the possible PM messages (SUSPEND, HIBERNATE, FREEZE)
13364  * to the suspend() method call will be treated as SUSPEND and the driver
13365  * will fully reinitialize its device during resume() method call, the device
13366  * will be set to PCI_D0 directly in PCI config space before restoring the
13367  * state.
13368  *
13369  * Return code
13370  * 	0 - driver suspended the device
13371  * 	Error otherwise
13372  **/
13373 static int
13374 lpfc_pci_resume_one_s4(struct pci_dev *pdev)
13375 {
13376 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
13377 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
13378 	uint32_t intr_mode;
13379 	int error;
13380 
13381 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13382 			"0292 PCI device Power Management resume.\n");
13383 
13384 	/* Restore device state from PCI config space */
13385 	pci_set_power_state(pdev, PCI_D0);
13386 	pci_restore_state(pdev);
13387 
13388 	/*
13389 	 * As the new kernel behavior of pci_restore_state() API call clears
13390 	 * device saved_state flag, need to save the restored state again.
13391 	 */
13392 	pci_save_state(pdev);
13393 
13394 	if (pdev->is_busmaster)
13395 		pci_set_master(pdev);
13396 
13397 	 /* Startup the kernel thread for this host adapter. */
13398 	phba->worker_thread = kthread_run(lpfc_do_work, phba,
13399 					"lpfc_worker_%d", phba->brd_no);
13400 	if (IS_ERR(phba->worker_thread)) {
13401 		error = PTR_ERR(phba->worker_thread);
13402 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13403 				"0293 PM resume failed to start worker "
13404 				"thread: error=x%x.\n", error);
13405 		return error;
13406 	}
13407 
13408 	/* Configure and enable interrupt */
13409 	intr_mode = lpfc_sli4_enable_intr(phba, phba->intr_mode);
13410 	if (intr_mode == LPFC_INTR_ERROR) {
13411 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13412 				"0294 PM resume Failed to enable interrupt\n");
13413 		return -EIO;
13414 	} else
13415 		phba->intr_mode = intr_mode;
13416 
13417 	/* Restart HBA and bring it online */
13418 	lpfc_sli_brdrestart(phba);
13419 	lpfc_online(phba);
13420 
13421 	/* Log the current active interrupt mode */
13422 	lpfc_log_intr_mode(phba, phba->intr_mode);
13423 
13424 	return 0;
13425 }
13426 
13427 /**
13428  * lpfc_sli4_prep_dev_for_recover - Prepare SLI4 device for pci slot recover
13429  * @phba: pointer to lpfc hba data structure.
13430  *
13431  * This routine is called to prepare the SLI4 device for PCI slot recover. It
13432  * aborts all the outstanding SCSI I/Os to the pci device.
13433  **/
13434 static void
13435 lpfc_sli4_prep_dev_for_recover(struct lpfc_hba *phba)
13436 {
13437 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13438 			"2828 PCI channel I/O abort preparing for recovery\n");
13439 	/*
13440 	 * There may be errored I/Os through HBA, abort all I/Os on txcmplq
13441 	 * and let the SCSI mid-layer to retry them to recover.
13442 	 */
13443 	lpfc_sli_abort_fcp_rings(phba);
13444 }
13445 
13446 /**
13447  * lpfc_sli4_prep_dev_for_reset - Prepare SLI4 device for pci slot reset
13448  * @phba: pointer to lpfc hba data structure.
13449  *
13450  * This routine is called to prepare the SLI4 device for PCI slot reset. It
13451  * disables the device interrupt and pci device, and aborts the internal FCP
13452  * pending I/Os.
13453  **/
13454 static void
13455 lpfc_sli4_prep_dev_for_reset(struct lpfc_hba *phba)
13456 {
13457 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13458 			"2826 PCI channel disable preparing for reset\n");
13459 
13460 	/* Block any management I/Os to the device */
13461 	lpfc_block_mgmt_io(phba, LPFC_MBX_NO_WAIT);
13462 
13463 	/* Block all SCSI devices' I/Os on the host */
13464 	lpfc_scsi_dev_block(phba);
13465 
13466 	/* Flush all driver's outstanding I/Os as we are to reset */
13467 	lpfc_sli_flush_io_rings(phba);
13468 
13469 	/* stop all timers */
13470 	lpfc_stop_hba_timers(phba);
13471 
13472 	/* Disable interrupt and pci device */
13473 	lpfc_sli4_disable_intr(phba);
13474 	lpfc_sli4_queue_destroy(phba);
13475 	pci_disable_device(phba->pcidev);
13476 }
13477 
13478 /**
13479  * lpfc_sli4_prep_dev_for_perm_failure - Prepare SLI4 dev for pci slot disable
13480  * @phba: pointer to lpfc hba data structure.
13481  *
13482  * This routine is called to prepare the SLI4 device for PCI slot permanently
13483  * disabling. It blocks the SCSI transport layer traffic and flushes the FCP
13484  * pending I/Os.
13485  **/
13486 static void
13487 lpfc_sli4_prep_dev_for_perm_failure(struct lpfc_hba *phba)
13488 {
13489 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13490 			"2827 PCI channel permanent disable for failure\n");
13491 
13492 	/* Block all SCSI devices' I/Os on the host */
13493 	lpfc_scsi_dev_block(phba);
13494 
13495 	/* stop all timers */
13496 	lpfc_stop_hba_timers(phba);
13497 
13498 	/* Clean up all driver's outstanding I/Os */
13499 	lpfc_sli_flush_io_rings(phba);
13500 }
13501 
13502 /**
13503  * lpfc_io_error_detected_s4 - Method for handling PCI I/O error to SLI-4 device
13504  * @pdev: pointer to PCI device.
13505  * @state: the current PCI connection state.
13506  *
13507  * This routine is called from the PCI subsystem for error handling to device
13508  * with SLI-4 interface spec. This function is called by the PCI subsystem
13509  * after a PCI bus error affecting this device has been detected. When this
13510  * function is invoked, it will need to stop all the I/Os and interrupt(s)
13511  * to the device. Once that is done, it will return PCI_ERS_RESULT_NEED_RESET
13512  * for the PCI subsystem to perform proper recovery as desired.
13513  *
13514  * Return codes
13515  * 	PCI_ERS_RESULT_NEED_RESET - need to reset before recovery
13516  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
13517  **/
13518 static pci_ers_result_t
13519 lpfc_io_error_detected_s4(struct pci_dev *pdev, pci_channel_state_t state)
13520 {
13521 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
13522 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
13523 
13524 	switch (state) {
13525 	case pci_channel_io_normal:
13526 		/* Non-fatal error, prepare for recovery */
13527 		lpfc_sli4_prep_dev_for_recover(phba);
13528 		return PCI_ERS_RESULT_CAN_RECOVER;
13529 	case pci_channel_io_frozen:
13530 		/* Fatal error, prepare for slot reset */
13531 		lpfc_sli4_prep_dev_for_reset(phba);
13532 		return PCI_ERS_RESULT_NEED_RESET;
13533 	case pci_channel_io_perm_failure:
13534 		/* Permanent failure, prepare for device down */
13535 		lpfc_sli4_prep_dev_for_perm_failure(phba);
13536 		return PCI_ERS_RESULT_DISCONNECT;
13537 	default:
13538 		/* Unknown state, prepare and request slot reset */
13539 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13540 				"2825 Unknown PCI error state: x%x\n", state);
13541 		lpfc_sli4_prep_dev_for_reset(phba);
13542 		return PCI_ERS_RESULT_NEED_RESET;
13543 	}
13544 }
13545 
13546 /**
13547  * lpfc_io_slot_reset_s4 - Method for restart PCI SLI-4 device from scratch
13548  * @pdev: pointer to PCI device.
13549  *
13550  * This routine is called from the PCI subsystem for error handling to device
13551  * with SLI-4 interface spec. It is called after PCI bus has been reset to
13552  * restart the PCI card from scratch, as if from a cold-boot. During the
13553  * PCI subsystem error recovery, after the driver returns
13554  * PCI_ERS_RESULT_NEED_RESET, the PCI subsystem will perform proper error
13555  * recovery and then call this routine before calling the .resume method to
13556  * recover the device. This function will initialize the HBA device, enable
13557  * the interrupt, but it will just put the HBA to offline state without
13558  * passing any I/O traffic.
13559  *
13560  * Return codes
13561  * 	PCI_ERS_RESULT_RECOVERED - the device has been recovered
13562  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
13563  */
13564 static pci_ers_result_t
13565 lpfc_io_slot_reset_s4(struct pci_dev *pdev)
13566 {
13567 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
13568 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
13569 	struct lpfc_sli *psli = &phba->sli;
13570 	uint32_t intr_mode;
13571 
13572 	dev_printk(KERN_INFO, &pdev->dev, "recovering from a slot reset.\n");
13573 	if (pci_enable_device_mem(pdev)) {
13574 		printk(KERN_ERR "lpfc: Cannot re-enable "
13575 			"PCI device after reset.\n");
13576 		return PCI_ERS_RESULT_DISCONNECT;
13577 	}
13578 
13579 	pci_restore_state(pdev);
13580 
13581 	/*
13582 	 * As the new kernel behavior of pci_restore_state() API call clears
13583 	 * device saved_state flag, need to save the restored state again.
13584 	 */
13585 	pci_save_state(pdev);
13586 
13587 	if (pdev->is_busmaster)
13588 		pci_set_master(pdev);
13589 
13590 	spin_lock_irq(&phba->hbalock);
13591 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
13592 	spin_unlock_irq(&phba->hbalock);
13593 
13594 	/* Configure and enable interrupt */
13595 	intr_mode = lpfc_sli4_enable_intr(phba, phba->intr_mode);
13596 	if (intr_mode == LPFC_INTR_ERROR) {
13597 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13598 				"2824 Cannot re-enable interrupt after "
13599 				"slot reset.\n");
13600 		return PCI_ERS_RESULT_DISCONNECT;
13601 	} else
13602 		phba->intr_mode = intr_mode;
13603 
13604 	/* Log the current active interrupt mode */
13605 	lpfc_log_intr_mode(phba, phba->intr_mode);
13606 
13607 	return PCI_ERS_RESULT_RECOVERED;
13608 }
13609 
13610 /**
13611  * lpfc_io_resume_s4 - Method for resuming PCI I/O operation to SLI-4 device
13612  * @pdev: pointer to PCI device
13613  *
13614  * This routine is called from the PCI subsystem for error handling to device
13615  * with SLI-4 interface spec. It is called when kernel error recovery tells
13616  * the lpfc driver that it is ok to resume normal PCI operation after PCI bus
13617  * error recovery. After this call, traffic can start to flow from this device
13618  * again.
13619  **/
13620 static void
13621 lpfc_io_resume_s4(struct pci_dev *pdev)
13622 {
13623 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
13624 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
13625 
13626 	/*
13627 	 * In case of slot reset, as function reset is performed through
13628 	 * mailbox command which needs DMA to be enabled, this operation
13629 	 * has to be moved to the io resume phase. Taking device offline
13630 	 * will perform the necessary cleanup.
13631 	 */
13632 	if (!(phba->sli.sli_flag & LPFC_SLI_ACTIVE)) {
13633 		/* Perform device reset */
13634 		lpfc_offline_prep(phba, LPFC_MBX_WAIT);
13635 		lpfc_offline(phba);
13636 		lpfc_sli_brdrestart(phba);
13637 		/* Bring the device back online */
13638 		lpfc_online(phba);
13639 	}
13640 }
13641 
13642 /**
13643  * lpfc_pci_probe_one - lpfc PCI probe func to reg dev to PCI subsystem
13644  * @pdev: pointer to PCI device
13645  * @pid: pointer to PCI device identifier
13646  *
13647  * This routine is to be registered to the kernel's PCI subsystem. When an
13648  * Emulex HBA device is presented on PCI bus, the kernel PCI subsystem looks
13649  * at PCI device-specific information of the device and driver to see if the
13650  * driver state that it can support this kind of device. If the match is
13651  * successful, the driver core invokes this routine. This routine dispatches
13652  * the action to the proper SLI-3 or SLI-4 device probing routine, which will
13653  * do all the initialization that it needs to do to handle the HBA device
13654  * properly.
13655  *
13656  * Return code
13657  * 	0 - driver can claim the device
13658  * 	negative value - driver can not claim the device
13659  **/
13660 static int
13661 lpfc_pci_probe_one(struct pci_dev *pdev, const struct pci_device_id *pid)
13662 {
13663 	int rc;
13664 	struct lpfc_sli_intf intf;
13665 
13666 	if (pci_read_config_dword(pdev, LPFC_SLI_INTF, &intf.word0))
13667 		return -ENODEV;
13668 
13669 	if ((bf_get(lpfc_sli_intf_valid, &intf) == LPFC_SLI_INTF_VALID) &&
13670 	    (bf_get(lpfc_sli_intf_slirev, &intf) == LPFC_SLI_INTF_REV_SLI4))
13671 		rc = lpfc_pci_probe_one_s4(pdev, pid);
13672 	else
13673 		rc = lpfc_pci_probe_one_s3(pdev, pid);
13674 
13675 	return rc;
13676 }
13677 
13678 /**
13679  * lpfc_pci_remove_one - lpfc PCI func to unreg dev from PCI subsystem
13680  * @pdev: pointer to PCI device
13681  *
13682  * This routine is to be registered to the kernel's PCI subsystem. When an
13683  * Emulex HBA is removed from PCI bus, the driver core invokes this routine.
13684  * This routine dispatches the action to the proper SLI-3 or SLI-4 device
13685  * remove routine, which will perform all the necessary cleanup for the
13686  * device to be removed from the PCI subsystem properly.
13687  **/
13688 static void
13689 lpfc_pci_remove_one(struct pci_dev *pdev)
13690 {
13691 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
13692 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
13693 
13694 	switch (phba->pci_dev_grp) {
13695 	case LPFC_PCI_DEV_LP:
13696 		lpfc_pci_remove_one_s3(pdev);
13697 		break;
13698 	case LPFC_PCI_DEV_OC:
13699 		lpfc_pci_remove_one_s4(pdev);
13700 		break;
13701 	default:
13702 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13703 				"1424 Invalid PCI device group: 0x%x\n",
13704 				phba->pci_dev_grp);
13705 		break;
13706 	}
13707 	return;
13708 }
13709 
13710 /**
13711  * lpfc_pci_suspend_one - lpfc PCI func to suspend dev for power management
13712  * @pdev: pointer to PCI device
13713  * @msg: power management message
13714  *
13715  * This routine is to be registered to the kernel's PCI subsystem to support
13716  * system Power Management (PM). When PM invokes this method, it dispatches
13717  * the action to the proper SLI-3 or SLI-4 device suspend routine, which will
13718  * suspend the device.
13719  *
13720  * Return code
13721  * 	0 - driver suspended the device
13722  * 	Error otherwise
13723  **/
13724 static int
13725 lpfc_pci_suspend_one(struct pci_dev *pdev, pm_message_t msg)
13726 {
13727 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
13728 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
13729 	int rc = -ENODEV;
13730 
13731 	switch (phba->pci_dev_grp) {
13732 	case LPFC_PCI_DEV_LP:
13733 		rc = lpfc_pci_suspend_one_s3(pdev, msg);
13734 		break;
13735 	case LPFC_PCI_DEV_OC:
13736 		rc = lpfc_pci_suspend_one_s4(pdev, msg);
13737 		break;
13738 	default:
13739 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13740 				"1425 Invalid PCI device group: 0x%x\n",
13741 				phba->pci_dev_grp);
13742 		break;
13743 	}
13744 	return rc;
13745 }
13746 
13747 /**
13748  * lpfc_pci_resume_one - lpfc PCI func to resume dev for power management
13749  * @pdev: pointer to PCI device
13750  *
13751  * This routine is to be registered to the kernel's PCI subsystem to support
13752  * system Power Management (PM). When PM invokes this method, it dispatches
13753  * the action to the proper SLI-3 or SLI-4 device resume routine, which will
13754  * resume the device.
13755  *
13756  * Return code
13757  * 	0 - driver suspended the device
13758  * 	Error otherwise
13759  **/
13760 static int
13761 lpfc_pci_resume_one(struct pci_dev *pdev)
13762 {
13763 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
13764 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
13765 	int rc = -ENODEV;
13766 
13767 	switch (phba->pci_dev_grp) {
13768 	case LPFC_PCI_DEV_LP:
13769 		rc = lpfc_pci_resume_one_s3(pdev);
13770 		break;
13771 	case LPFC_PCI_DEV_OC:
13772 		rc = lpfc_pci_resume_one_s4(pdev);
13773 		break;
13774 	default:
13775 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13776 				"1426 Invalid PCI device group: 0x%x\n",
13777 				phba->pci_dev_grp);
13778 		break;
13779 	}
13780 	return rc;
13781 }
13782 
13783 /**
13784  * lpfc_io_error_detected - lpfc method for handling PCI I/O error
13785  * @pdev: pointer to PCI device.
13786  * @state: the current PCI connection state.
13787  *
13788  * This routine is registered to the PCI subsystem for error handling. This
13789  * function is called by the PCI subsystem after a PCI bus error affecting
13790  * this device has been detected. When this routine is invoked, it dispatches
13791  * the action to the proper SLI-3 or SLI-4 device error detected handling
13792  * routine, which will perform the proper error detected operation.
13793  *
13794  * Return codes
13795  * 	PCI_ERS_RESULT_NEED_RESET - need to reset before recovery
13796  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
13797  **/
13798 static pci_ers_result_t
13799 lpfc_io_error_detected(struct pci_dev *pdev, pci_channel_state_t state)
13800 {
13801 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
13802 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
13803 	pci_ers_result_t rc = PCI_ERS_RESULT_DISCONNECT;
13804 
13805 	switch (phba->pci_dev_grp) {
13806 	case LPFC_PCI_DEV_LP:
13807 		rc = lpfc_io_error_detected_s3(pdev, state);
13808 		break;
13809 	case LPFC_PCI_DEV_OC:
13810 		rc = lpfc_io_error_detected_s4(pdev, state);
13811 		break;
13812 	default:
13813 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13814 				"1427 Invalid PCI device group: 0x%x\n",
13815 				phba->pci_dev_grp);
13816 		break;
13817 	}
13818 	return rc;
13819 }
13820 
13821 /**
13822  * lpfc_io_slot_reset - lpfc method for restart PCI dev from scratch
13823  * @pdev: pointer to PCI device.
13824  *
13825  * This routine is registered to the PCI subsystem for error handling. This
13826  * function is called after PCI bus has been reset to restart the PCI card
13827  * from scratch, as if from a cold-boot. When this routine is invoked, it
13828  * dispatches the action to the proper SLI-3 or SLI-4 device reset handling
13829  * routine, which will perform the proper device reset.
13830  *
13831  * Return codes
13832  * 	PCI_ERS_RESULT_RECOVERED - the device has been recovered
13833  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
13834  **/
13835 static pci_ers_result_t
13836 lpfc_io_slot_reset(struct pci_dev *pdev)
13837 {
13838 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
13839 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
13840 	pci_ers_result_t rc = PCI_ERS_RESULT_DISCONNECT;
13841 
13842 	switch (phba->pci_dev_grp) {
13843 	case LPFC_PCI_DEV_LP:
13844 		rc = lpfc_io_slot_reset_s3(pdev);
13845 		break;
13846 	case LPFC_PCI_DEV_OC:
13847 		rc = lpfc_io_slot_reset_s4(pdev);
13848 		break;
13849 	default:
13850 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13851 				"1428 Invalid PCI device group: 0x%x\n",
13852 				phba->pci_dev_grp);
13853 		break;
13854 	}
13855 	return rc;
13856 }
13857 
13858 /**
13859  * lpfc_io_resume - lpfc method for resuming PCI I/O operation
13860  * @pdev: pointer to PCI device
13861  *
13862  * This routine is registered to the PCI subsystem for error handling. It
13863  * is called when kernel error recovery tells the lpfc driver that it is
13864  * OK to resume normal PCI operation after PCI bus error recovery. When
13865  * this routine is invoked, it dispatches the action to the proper SLI-3
13866  * or SLI-4 device io_resume routine, which will resume the device operation.
13867  **/
13868 static void
13869 lpfc_io_resume(struct pci_dev *pdev)
13870 {
13871 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
13872 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
13873 
13874 	switch (phba->pci_dev_grp) {
13875 	case LPFC_PCI_DEV_LP:
13876 		lpfc_io_resume_s3(pdev);
13877 		break;
13878 	case LPFC_PCI_DEV_OC:
13879 		lpfc_io_resume_s4(pdev);
13880 		break;
13881 	default:
13882 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13883 				"1429 Invalid PCI device group: 0x%x\n",
13884 				phba->pci_dev_grp);
13885 		break;
13886 	}
13887 	return;
13888 }
13889 
13890 /**
13891  * lpfc_sli4_oas_verify - Verify OAS is supported by this adapter
13892  * @phba: pointer to lpfc hba data structure.
13893  *
13894  * This routine checks to see if OAS is supported for this adapter. If
13895  * supported, the configure Flash Optimized Fabric flag is set.  Otherwise,
13896  * the enable oas flag is cleared and the pool created for OAS device data
13897  * is destroyed.
13898  *
13899  **/
13900 static void
13901 lpfc_sli4_oas_verify(struct lpfc_hba *phba)
13902 {
13903 
13904 	if (!phba->cfg_EnableXLane)
13905 		return;
13906 
13907 	if (phba->sli4_hba.pc_sli4_params.oas_supported) {
13908 		phba->cfg_fof = 1;
13909 	} else {
13910 		phba->cfg_fof = 0;
13911 		mempool_destroy(phba->device_data_mem_pool);
13912 		phba->device_data_mem_pool = NULL;
13913 	}
13914 
13915 	return;
13916 }
13917 
13918 /**
13919  * lpfc_sli4_ras_init - Verify RAS-FW log is supported by this adapter
13920  * @phba: pointer to lpfc hba data structure.
13921  *
13922  * This routine checks to see if RAS is supported by the adapter. Check the
13923  * function through which RAS support enablement is to be done.
13924  **/
13925 void
13926 lpfc_sli4_ras_init(struct lpfc_hba *phba)
13927 {
13928 	switch (phba->pcidev->device) {
13929 	case PCI_DEVICE_ID_LANCER_G6_FC:
13930 	case PCI_DEVICE_ID_LANCER_G7_FC:
13931 		phba->ras_fwlog.ras_hwsupport = true;
13932 		if (phba->cfg_ras_fwlog_func == PCI_FUNC(phba->pcidev->devfn) &&
13933 		    phba->cfg_ras_fwlog_buffsize)
13934 			phba->ras_fwlog.ras_enabled = true;
13935 		else
13936 			phba->ras_fwlog.ras_enabled = false;
13937 		break;
13938 	default:
13939 		phba->ras_fwlog.ras_hwsupport = false;
13940 	}
13941 }
13942 
13943 
13944 MODULE_DEVICE_TABLE(pci, lpfc_id_table);
13945 
13946 static const struct pci_error_handlers lpfc_err_handler = {
13947 	.error_detected = lpfc_io_error_detected,
13948 	.slot_reset = lpfc_io_slot_reset,
13949 	.resume = lpfc_io_resume,
13950 };
13951 
13952 static struct pci_driver lpfc_driver = {
13953 	.name		= LPFC_DRIVER_NAME,
13954 	.id_table	= lpfc_id_table,
13955 	.probe		= lpfc_pci_probe_one,
13956 	.remove		= lpfc_pci_remove_one,
13957 	.shutdown	= lpfc_pci_remove_one,
13958 	.suspend        = lpfc_pci_suspend_one,
13959 	.resume		= lpfc_pci_resume_one,
13960 	.err_handler    = &lpfc_err_handler,
13961 };
13962 
13963 static const struct file_operations lpfc_mgmt_fop = {
13964 	.owner = THIS_MODULE,
13965 };
13966 
13967 static struct miscdevice lpfc_mgmt_dev = {
13968 	.minor = MISC_DYNAMIC_MINOR,
13969 	.name = "lpfcmgmt",
13970 	.fops = &lpfc_mgmt_fop,
13971 };
13972 
13973 /**
13974  * lpfc_init - lpfc module initialization routine
13975  *
13976  * This routine is to be invoked when the lpfc module is loaded into the
13977  * kernel. The special kernel macro module_init() is used to indicate the
13978  * role of this routine to the kernel as lpfc module entry point.
13979  *
13980  * Return codes
13981  *   0 - successful
13982  *   -ENOMEM - FC attach transport failed
13983  *   all others - failed
13984  */
13985 static int __init
13986 lpfc_init(void)
13987 {
13988 	int error = 0;
13989 
13990 	printk(LPFC_MODULE_DESC "\n");
13991 	printk(LPFC_COPYRIGHT "\n");
13992 
13993 	error = misc_register(&lpfc_mgmt_dev);
13994 	if (error)
13995 		printk(KERN_ERR "Could not register lpfcmgmt device, "
13996 			"misc_register returned with status %d", error);
13997 
13998 	lpfc_transport_functions.vport_create = lpfc_vport_create;
13999 	lpfc_transport_functions.vport_delete = lpfc_vport_delete;
14000 	lpfc_transport_template =
14001 				fc_attach_transport(&lpfc_transport_functions);
14002 	if (lpfc_transport_template == NULL)
14003 		return -ENOMEM;
14004 	lpfc_vport_transport_template =
14005 		fc_attach_transport(&lpfc_vport_transport_functions);
14006 	if (lpfc_vport_transport_template == NULL) {
14007 		fc_release_transport(lpfc_transport_template);
14008 		return -ENOMEM;
14009 	}
14010 	lpfc_nvme_cmd_template();
14011 	lpfc_nvmet_cmd_template();
14012 
14013 	/* Initialize in case vector mapping is needed */
14014 	lpfc_present_cpu = num_present_cpus();
14015 
14016 	error = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN,
14017 					"lpfc/sli4:online",
14018 					lpfc_cpu_online, lpfc_cpu_offline);
14019 	if (error < 0)
14020 		goto cpuhp_failure;
14021 	lpfc_cpuhp_state = error;
14022 
14023 	error = pci_register_driver(&lpfc_driver);
14024 	if (error)
14025 		goto unwind;
14026 
14027 	return error;
14028 
14029 unwind:
14030 	cpuhp_remove_multi_state(lpfc_cpuhp_state);
14031 cpuhp_failure:
14032 	fc_release_transport(lpfc_transport_template);
14033 	fc_release_transport(lpfc_vport_transport_template);
14034 
14035 	return error;
14036 }
14037 
14038 /**
14039  * lpfc_exit - lpfc module removal routine
14040  *
14041  * This routine is invoked when the lpfc module is removed from the kernel.
14042  * The special kernel macro module_exit() is used to indicate the role of
14043  * this routine to the kernel as lpfc module exit point.
14044  */
14045 static void __exit
14046 lpfc_exit(void)
14047 {
14048 	misc_deregister(&lpfc_mgmt_dev);
14049 	pci_unregister_driver(&lpfc_driver);
14050 	cpuhp_remove_multi_state(lpfc_cpuhp_state);
14051 	fc_release_transport(lpfc_transport_template);
14052 	fc_release_transport(lpfc_vport_transport_template);
14053 	idr_destroy(&lpfc_hba_index);
14054 }
14055 
14056 module_init(lpfc_init);
14057 module_exit(lpfc_exit);
14058 MODULE_LICENSE("GPL");
14059 MODULE_DESCRIPTION(LPFC_MODULE_DESC);
14060 MODULE_AUTHOR("Broadcom");
14061 MODULE_VERSION("0:" LPFC_DRIVER_VERSION);
14062