xref: /openbmc/linux/drivers/scsi/lpfc/lpfc_init.c (revision 9ebc6e8a)
1 /*******************************************************************
2  * This file is part of the Emulex Linux Device Driver for         *
3  * Fibre Channel Host Bus Adapters.                                *
4  * Copyright (C) 2017-2021 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 static int lpfc_sli4_cgn_parm_chg_evt(struct lpfc_hba *);
97 
98 static struct scsi_transport_template *lpfc_transport_template = NULL;
99 static struct scsi_transport_template *lpfc_vport_transport_template = NULL;
100 static DEFINE_IDR(lpfc_hba_index);
101 #define LPFC_NVMET_BUF_POST 254
102 static int lpfc_vmid_res_alloc(struct lpfc_hba *phba, struct lpfc_vport *vport);
103 
104 /**
105  * lpfc_config_port_prep - Perform lpfc initialization prior to config port
106  * @phba: pointer to lpfc hba data structure.
107  *
108  * This routine will do LPFC initialization prior to issuing the CONFIG_PORT
109  * mailbox command. It retrieves the revision information from the HBA and
110  * collects the Vital Product Data (VPD) about the HBA for preparing the
111  * configuration of the HBA.
112  *
113  * Return codes:
114  *   0 - success.
115  *   -ERESTART - requests the SLI layer to reset the HBA and try again.
116  *   Any other value - indicates an error.
117  **/
118 int
119 lpfc_config_port_prep(struct lpfc_hba *phba)
120 {
121 	lpfc_vpd_t *vp = &phba->vpd;
122 	int i = 0, rc;
123 	LPFC_MBOXQ_t *pmb;
124 	MAILBOX_t *mb;
125 	char *lpfc_vpd_data = NULL;
126 	uint16_t offset = 0;
127 	static char licensed[56] =
128 		    "key unlock for use with gnu public licensed code only\0";
129 	static int init_key = 1;
130 
131 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
132 	if (!pmb) {
133 		phba->link_state = LPFC_HBA_ERROR;
134 		return -ENOMEM;
135 	}
136 
137 	mb = &pmb->u.mb;
138 	phba->link_state = LPFC_INIT_MBX_CMDS;
139 
140 	if (lpfc_is_LC_HBA(phba->pcidev->device)) {
141 		if (init_key) {
142 			uint32_t *ptext = (uint32_t *) licensed;
143 
144 			for (i = 0; i < 56; i += sizeof (uint32_t), ptext++)
145 				*ptext = cpu_to_be32(*ptext);
146 			init_key = 0;
147 		}
148 
149 		lpfc_read_nv(phba, pmb);
150 		memset((char*)mb->un.varRDnvp.rsvd3, 0,
151 			sizeof (mb->un.varRDnvp.rsvd3));
152 		memcpy((char*)mb->un.varRDnvp.rsvd3, licensed,
153 			 sizeof (licensed));
154 
155 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
156 
157 		if (rc != MBX_SUCCESS) {
158 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
159 					"0324 Config Port initialization "
160 					"error, mbxCmd x%x READ_NVPARM, "
161 					"mbxStatus x%x\n",
162 					mb->mbxCommand, mb->mbxStatus);
163 			mempool_free(pmb, phba->mbox_mem_pool);
164 			return -ERESTART;
165 		}
166 		memcpy(phba->wwnn, (char *)mb->un.varRDnvp.nodename,
167 		       sizeof(phba->wwnn));
168 		memcpy(phba->wwpn, (char *)mb->un.varRDnvp.portname,
169 		       sizeof(phba->wwpn));
170 	}
171 
172 	/*
173 	 * Clear all option bits except LPFC_SLI3_BG_ENABLED,
174 	 * which was already set in lpfc_get_cfgparam()
175 	 */
176 	phba->sli3_options &= (uint32_t)LPFC_SLI3_BG_ENABLED;
177 
178 	/* Setup and issue mailbox READ REV command */
179 	lpfc_read_rev(phba, pmb);
180 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
181 	if (rc != MBX_SUCCESS) {
182 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
183 				"0439 Adapter failed to init, mbxCmd x%x "
184 				"READ_REV, mbxStatus x%x\n",
185 				mb->mbxCommand, mb->mbxStatus);
186 		mempool_free( pmb, phba->mbox_mem_pool);
187 		return -ERESTART;
188 	}
189 
190 
191 	/*
192 	 * The value of rr must be 1 since the driver set the cv field to 1.
193 	 * This setting requires the FW to set all revision fields.
194 	 */
195 	if (mb->un.varRdRev.rr == 0) {
196 		vp->rev.rBit = 0;
197 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
198 				"0440 Adapter failed to init, READ_REV has "
199 				"missing revision information.\n");
200 		mempool_free(pmb, phba->mbox_mem_pool);
201 		return -ERESTART;
202 	}
203 
204 	if (phba->sli_rev == 3 && !mb->un.varRdRev.v3rsp) {
205 		mempool_free(pmb, phba->mbox_mem_pool);
206 		return -EINVAL;
207 	}
208 
209 	/* Save information as VPD data */
210 	vp->rev.rBit = 1;
211 	memcpy(&vp->sli3Feat, &mb->un.varRdRev.sli3Feat, sizeof(uint32_t));
212 	vp->rev.sli1FwRev = mb->un.varRdRev.sli1FwRev;
213 	memcpy(vp->rev.sli1FwName, (char*) mb->un.varRdRev.sli1FwName, 16);
214 	vp->rev.sli2FwRev = mb->un.varRdRev.sli2FwRev;
215 	memcpy(vp->rev.sli2FwName, (char *) mb->un.varRdRev.sli2FwName, 16);
216 	vp->rev.biuRev = mb->un.varRdRev.biuRev;
217 	vp->rev.smRev = mb->un.varRdRev.smRev;
218 	vp->rev.smFwRev = mb->un.varRdRev.un.smFwRev;
219 	vp->rev.endecRev = mb->un.varRdRev.endecRev;
220 	vp->rev.fcphHigh = mb->un.varRdRev.fcphHigh;
221 	vp->rev.fcphLow = mb->un.varRdRev.fcphLow;
222 	vp->rev.feaLevelHigh = mb->un.varRdRev.feaLevelHigh;
223 	vp->rev.feaLevelLow = mb->un.varRdRev.feaLevelLow;
224 	vp->rev.postKernRev = mb->un.varRdRev.postKernRev;
225 	vp->rev.opFwRev = mb->un.varRdRev.opFwRev;
226 
227 	/* If the sli feature level is less then 9, we must
228 	 * tear down all RPIs and VPIs on link down if NPIV
229 	 * is enabled.
230 	 */
231 	if (vp->rev.feaLevelHigh < 9)
232 		phba->sli3_options |= LPFC_SLI3_VPORT_TEARDOWN;
233 
234 	if (lpfc_is_LC_HBA(phba->pcidev->device))
235 		memcpy(phba->RandomData, (char *)&mb->un.varWords[24],
236 						sizeof (phba->RandomData));
237 
238 	/* Get adapter VPD information */
239 	lpfc_vpd_data = kmalloc(DMP_VPD_SIZE, GFP_KERNEL);
240 	if (!lpfc_vpd_data)
241 		goto out_free_mbox;
242 	do {
243 		lpfc_dump_mem(phba, pmb, offset, DMP_REGION_VPD);
244 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
245 
246 		if (rc != MBX_SUCCESS) {
247 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
248 					"0441 VPD not present on adapter, "
249 					"mbxCmd x%x DUMP VPD, mbxStatus x%x\n",
250 					mb->mbxCommand, mb->mbxStatus);
251 			mb->un.varDmp.word_cnt = 0;
252 		}
253 		/* dump mem may return a zero when finished or we got a
254 		 * mailbox error, either way we are done.
255 		 */
256 		if (mb->un.varDmp.word_cnt == 0)
257 			break;
258 
259 		if (mb->un.varDmp.word_cnt > DMP_VPD_SIZE - offset)
260 			mb->un.varDmp.word_cnt = DMP_VPD_SIZE - offset;
261 		lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
262 				      lpfc_vpd_data + offset,
263 				      mb->un.varDmp.word_cnt);
264 		offset += mb->un.varDmp.word_cnt;
265 	} while (mb->un.varDmp.word_cnt && offset < DMP_VPD_SIZE);
266 
267 	lpfc_parse_vpd(phba, lpfc_vpd_data, offset);
268 
269 	kfree(lpfc_vpd_data);
270 out_free_mbox:
271 	mempool_free(pmb, phba->mbox_mem_pool);
272 	return 0;
273 }
274 
275 /**
276  * lpfc_config_async_cmpl - Completion handler for config async event mbox cmd
277  * @phba: pointer to lpfc hba data structure.
278  * @pmboxq: pointer to the driver internal queue element for mailbox command.
279  *
280  * This is the completion handler for driver's configuring asynchronous event
281  * mailbox command to the device. If the mailbox command returns successfully,
282  * it will set internal async event support flag to 1; otherwise, it will
283  * set internal async event support flag to 0.
284  **/
285 static void
286 lpfc_config_async_cmpl(struct lpfc_hba * phba, LPFC_MBOXQ_t * pmboxq)
287 {
288 	if (pmboxq->u.mb.mbxStatus == MBX_SUCCESS)
289 		phba->temp_sensor_support = 1;
290 	else
291 		phba->temp_sensor_support = 0;
292 	mempool_free(pmboxq, phba->mbox_mem_pool);
293 	return;
294 }
295 
296 /**
297  * lpfc_dump_wakeup_param_cmpl - dump memory mailbox command completion handler
298  * @phba: pointer to lpfc hba data structure.
299  * @pmboxq: pointer to the driver internal queue element for mailbox command.
300  *
301  * This is the completion handler for dump mailbox command for getting
302  * wake up parameters. When this command complete, the response contain
303  * Option rom version of the HBA. This function translate the version number
304  * into a human readable string and store it in OptionROMVersion.
305  **/
306 static void
307 lpfc_dump_wakeup_param_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
308 {
309 	struct prog_id *prg;
310 	uint32_t prog_id_word;
311 	char dist = ' ';
312 	/* character array used for decoding dist type. */
313 	char dist_char[] = "nabx";
314 
315 	if (pmboxq->u.mb.mbxStatus != MBX_SUCCESS) {
316 		mempool_free(pmboxq, phba->mbox_mem_pool);
317 		return;
318 	}
319 
320 	prg = (struct prog_id *) &prog_id_word;
321 
322 	/* word 7 contain option rom version */
323 	prog_id_word = pmboxq->u.mb.un.varWords[7];
324 
325 	/* Decode the Option rom version word to a readable string */
326 	if (prg->dist < 4)
327 		dist = dist_char[prg->dist];
328 
329 	if ((prg->dist == 3) && (prg->num == 0))
330 		snprintf(phba->OptionROMVersion, 32, "%d.%d%d",
331 			prg->ver, prg->rev, prg->lev);
332 	else
333 		snprintf(phba->OptionROMVersion, 32, "%d.%d%d%c%d",
334 			prg->ver, prg->rev, prg->lev,
335 			dist, prg->num);
336 	mempool_free(pmboxq, phba->mbox_mem_pool);
337 	return;
338 }
339 
340 /**
341  * lpfc_update_vport_wwn - Updates the fc_nodename, fc_portname,
342  *	cfg_soft_wwnn, cfg_soft_wwpn
343  * @vport: pointer to lpfc vport data structure.
344  *
345  *
346  * Return codes
347  *   None.
348  **/
349 void
350 lpfc_update_vport_wwn(struct lpfc_vport *vport)
351 {
352 	uint8_t vvvl = vport->fc_sparam.cmn.valid_vendor_ver_level;
353 	u32 *fawwpn_key = (u32 *)&vport->fc_sparam.un.vendorVersion[0];
354 
355 	/* If the soft name exists then update it using the service params */
356 	if (vport->phba->cfg_soft_wwnn)
357 		u64_to_wwn(vport->phba->cfg_soft_wwnn,
358 			   vport->fc_sparam.nodeName.u.wwn);
359 	if (vport->phba->cfg_soft_wwpn)
360 		u64_to_wwn(vport->phba->cfg_soft_wwpn,
361 			   vport->fc_sparam.portName.u.wwn);
362 
363 	/*
364 	 * If the name is empty or there exists a soft name
365 	 * then copy the service params name, otherwise use the fc name
366 	 */
367 	if (vport->fc_nodename.u.wwn[0] == 0 || vport->phba->cfg_soft_wwnn)
368 		memcpy(&vport->fc_nodename, &vport->fc_sparam.nodeName,
369 			sizeof(struct lpfc_name));
370 	else
371 		memcpy(&vport->fc_sparam.nodeName, &vport->fc_nodename,
372 			sizeof(struct lpfc_name));
373 
374 	/*
375 	 * If the port name has changed, then set the Param changes flag
376 	 * to unreg the login
377 	 */
378 	if (vport->fc_portname.u.wwn[0] != 0 &&
379 		memcmp(&vport->fc_portname, &vport->fc_sparam.portName,
380 			sizeof(struct lpfc_name)))
381 		vport->vport_flag |= FAWWPN_PARAM_CHG;
382 
383 	if (vport->fc_portname.u.wwn[0] == 0 ||
384 	    vport->phba->cfg_soft_wwpn ||
385 	    (vvvl == 1 && cpu_to_be32(*fawwpn_key) == FAPWWN_KEY_VENDOR) ||
386 	    vport->vport_flag & FAWWPN_SET) {
387 		memcpy(&vport->fc_portname, &vport->fc_sparam.portName,
388 			sizeof(struct lpfc_name));
389 		vport->vport_flag &= ~FAWWPN_SET;
390 		if (vvvl == 1 && cpu_to_be32(*fawwpn_key) == FAPWWN_KEY_VENDOR)
391 			vport->vport_flag |= FAWWPN_SET;
392 	}
393 	else
394 		memcpy(&vport->fc_sparam.portName, &vport->fc_portname,
395 			sizeof(struct lpfc_name));
396 }
397 
398 /**
399  * lpfc_config_port_post - Perform lpfc initialization after config port
400  * @phba: pointer to lpfc hba data structure.
401  *
402  * This routine will do LPFC initialization after the CONFIG_PORT mailbox
403  * command call. It performs all internal resource and state setups on the
404  * port: post IOCB buffers, enable appropriate host interrupt attentions,
405  * ELS ring timers, etc.
406  *
407  * Return codes
408  *   0 - success.
409  *   Any other value - error.
410  **/
411 int
412 lpfc_config_port_post(struct lpfc_hba *phba)
413 {
414 	struct lpfc_vport *vport = phba->pport;
415 	struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
416 	LPFC_MBOXQ_t *pmb;
417 	MAILBOX_t *mb;
418 	struct lpfc_dmabuf *mp;
419 	struct lpfc_sli *psli = &phba->sli;
420 	uint32_t status, timeout;
421 	int i, j;
422 	int rc;
423 
424 	spin_lock_irq(&phba->hbalock);
425 	/*
426 	 * If the Config port completed correctly the HBA is not
427 	 * over heated any more.
428 	 */
429 	if (phba->over_temp_state == HBA_OVER_TEMP)
430 		phba->over_temp_state = HBA_NORMAL_TEMP;
431 	spin_unlock_irq(&phba->hbalock);
432 
433 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
434 	if (!pmb) {
435 		phba->link_state = LPFC_HBA_ERROR;
436 		return -ENOMEM;
437 	}
438 	mb = &pmb->u.mb;
439 
440 	/* Get login parameters for NID.  */
441 	rc = lpfc_read_sparam(phba, pmb, 0);
442 	if (rc) {
443 		mempool_free(pmb, phba->mbox_mem_pool);
444 		return -ENOMEM;
445 	}
446 
447 	pmb->vport = vport;
448 	if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
449 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
450 				"0448 Adapter failed init, mbxCmd x%x "
451 				"READ_SPARM mbxStatus x%x\n",
452 				mb->mbxCommand, mb->mbxStatus);
453 		phba->link_state = LPFC_HBA_ERROR;
454 		mp = (struct lpfc_dmabuf *)pmb->ctx_buf;
455 		mempool_free(pmb, phba->mbox_mem_pool);
456 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
457 		kfree(mp);
458 		return -EIO;
459 	}
460 
461 	mp = (struct lpfc_dmabuf *)pmb->ctx_buf;
462 
463 	memcpy(&vport->fc_sparam, mp->virt, sizeof (struct serv_parm));
464 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
465 	kfree(mp);
466 	pmb->ctx_buf = NULL;
467 	lpfc_update_vport_wwn(vport);
468 
469 	/* Update the fc_host data structures with new wwn. */
470 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
471 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
472 	fc_host_max_npiv_vports(shost) = phba->max_vpi;
473 
474 	/* If no serial number in VPD data, use low 6 bytes of WWNN */
475 	/* This should be consolidated into parse_vpd ? - mr */
476 	if (phba->SerialNumber[0] == 0) {
477 		uint8_t *outptr;
478 
479 		outptr = &vport->fc_nodename.u.s.IEEE[0];
480 		for (i = 0; i < 12; i++) {
481 			status = *outptr++;
482 			j = ((status & 0xf0) >> 4);
483 			if (j <= 9)
484 				phba->SerialNumber[i] =
485 				    (char)((uint8_t) 0x30 + (uint8_t) j);
486 			else
487 				phba->SerialNumber[i] =
488 				    (char)((uint8_t) 0x61 + (uint8_t) (j - 10));
489 			i++;
490 			j = (status & 0xf);
491 			if (j <= 9)
492 				phba->SerialNumber[i] =
493 				    (char)((uint8_t) 0x30 + (uint8_t) j);
494 			else
495 				phba->SerialNumber[i] =
496 				    (char)((uint8_t) 0x61 + (uint8_t) (j - 10));
497 		}
498 	}
499 
500 	lpfc_read_config(phba, pmb);
501 	pmb->vport = vport;
502 	if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
503 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
504 				"0453 Adapter failed to init, mbxCmd x%x "
505 				"READ_CONFIG, mbxStatus x%x\n",
506 				mb->mbxCommand, mb->mbxStatus);
507 		phba->link_state = LPFC_HBA_ERROR;
508 		mempool_free( pmb, phba->mbox_mem_pool);
509 		return -EIO;
510 	}
511 
512 	/* Check if the port is disabled */
513 	lpfc_sli_read_link_ste(phba);
514 
515 	/* Reset the DFT_HBA_Q_DEPTH to the max xri  */
516 	if (phba->cfg_hba_queue_depth > mb->un.varRdConfig.max_xri) {
517 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
518 				"3359 HBA queue depth changed from %d to %d\n",
519 				phba->cfg_hba_queue_depth,
520 				mb->un.varRdConfig.max_xri);
521 		phba->cfg_hba_queue_depth = mb->un.varRdConfig.max_xri;
522 	}
523 
524 	phba->lmt = mb->un.varRdConfig.lmt;
525 
526 	/* Get the default values for Model Name and Description */
527 	lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
528 
529 	phba->link_state = LPFC_LINK_DOWN;
530 
531 	/* Only process IOCBs on ELS ring till hba_state is READY */
532 	if (psli->sli3_ring[LPFC_EXTRA_RING].sli.sli3.cmdringaddr)
533 		psli->sli3_ring[LPFC_EXTRA_RING].flag |= LPFC_STOP_IOCB_EVENT;
534 	if (psli->sli3_ring[LPFC_FCP_RING].sli.sli3.cmdringaddr)
535 		psli->sli3_ring[LPFC_FCP_RING].flag |= LPFC_STOP_IOCB_EVENT;
536 
537 	/* Post receive buffers for desired rings */
538 	if (phba->sli_rev != 3)
539 		lpfc_post_rcv_buf(phba);
540 
541 	/*
542 	 * Configure HBA MSI-X attention conditions to messages if MSI-X mode
543 	 */
544 	if (phba->intr_type == MSIX) {
545 		rc = lpfc_config_msi(phba, pmb);
546 		if (rc) {
547 			mempool_free(pmb, phba->mbox_mem_pool);
548 			return -EIO;
549 		}
550 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
551 		if (rc != MBX_SUCCESS) {
552 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
553 					"0352 Config MSI mailbox command "
554 					"failed, mbxCmd x%x, mbxStatus x%x\n",
555 					pmb->u.mb.mbxCommand,
556 					pmb->u.mb.mbxStatus);
557 			mempool_free(pmb, phba->mbox_mem_pool);
558 			return -EIO;
559 		}
560 	}
561 
562 	spin_lock_irq(&phba->hbalock);
563 	/* Initialize ERATT handling flag */
564 	phba->hba_flag &= ~HBA_ERATT_HANDLED;
565 
566 	/* Enable appropriate host interrupts */
567 	if (lpfc_readl(phba->HCregaddr, &status)) {
568 		spin_unlock_irq(&phba->hbalock);
569 		return -EIO;
570 	}
571 	status |= HC_MBINT_ENA | HC_ERINT_ENA | HC_LAINT_ENA;
572 	if (psli->num_rings > 0)
573 		status |= HC_R0INT_ENA;
574 	if (psli->num_rings > 1)
575 		status |= HC_R1INT_ENA;
576 	if (psli->num_rings > 2)
577 		status |= HC_R2INT_ENA;
578 	if (psli->num_rings > 3)
579 		status |= HC_R3INT_ENA;
580 
581 	if ((phba->cfg_poll & ENABLE_FCP_RING_POLLING) &&
582 	    (phba->cfg_poll & DISABLE_FCP_RING_INT))
583 		status &= ~(HC_R0INT_ENA);
584 
585 	writel(status, phba->HCregaddr);
586 	readl(phba->HCregaddr); /* flush */
587 	spin_unlock_irq(&phba->hbalock);
588 
589 	/* Set up ring-0 (ELS) timer */
590 	timeout = phba->fc_ratov * 2;
591 	mod_timer(&vport->els_tmofunc,
592 		  jiffies + msecs_to_jiffies(1000 * timeout));
593 	/* Set up heart beat (HB) timer */
594 	mod_timer(&phba->hb_tmofunc,
595 		  jiffies + msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
596 	phba->hba_flag &= ~(HBA_HBEAT_INP | HBA_HBEAT_TMO);
597 	phba->last_completion_time = jiffies;
598 	/* Set up error attention (ERATT) polling timer */
599 	mod_timer(&phba->eratt_poll,
600 		  jiffies + msecs_to_jiffies(1000 * phba->eratt_poll_interval));
601 
602 	if (phba->hba_flag & LINK_DISABLED) {
603 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
604 				"2598 Adapter Link is disabled.\n");
605 		lpfc_down_link(phba, pmb);
606 		pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
607 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
608 		if ((rc != MBX_SUCCESS) && (rc != MBX_BUSY)) {
609 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
610 					"2599 Adapter failed to issue DOWN_LINK"
611 					" mbox command rc 0x%x\n", rc);
612 
613 			mempool_free(pmb, phba->mbox_mem_pool);
614 			return -EIO;
615 		}
616 	} else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
617 		mempool_free(pmb, phba->mbox_mem_pool);
618 		rc = phba->lpfc_hba_init_link(phba, MBX_NOWAIT);
619 		if (rc)
620 			return rc;
621 	}
622 	/* MBOX buffer will be freed in mbox compl */
623 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
624 	if (!pmb) {
625 		phba->link_state = LPFC_HBA_ERROR;
626 		return -ENOMEM;
627 	}
628 
629 	lpfc_config_async(phba, pmb, LPFC_ELS_RING);
630 	pmb->mbox_cmpl = lpfc_config_async_cmpl;
631 	pmb->vport = phba->pport;
632 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
633 
634 	if ((rc != MBX_BUSY) && (rc != MBX_SUCCESS)) {
635 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
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_TRACE_EVENT,
656 				"0435 Adapter failed "
657 				"to get Option ROM version status x%x\n", rc);
658 		mempool_free(pmb, phba->mbox_mem_pool);
659 	}
660 
661 	return 0;
662 }
663 
664 /**
665  * lpfc_hba_init_link - Initialize the FC link
666  * @phba: pointer to lpfc hba data structure.
667  * @flag: mailbox command issue mode - either MBX_POLL or MBX_NOWAIT
668  *
669  * This routine will issue the INIT_LINK mailbox command call.
670  * It is available to other drivers through the lpfc_hba data
671  * structure for use as a delayed link up mechanism with the
672  * module parameter lpfc_suppress_link_up.
673  *
674  * Return code
675  *		0 - success
676  *		Any other value - error
677  **/
678 static int
679 lpfc_hba_init_link(struct lpfc_hba *phba, uint32_t flag)
680 {
681 	return lpfc_hba_init_link_fc_topology(phba, phba->cfg_topology, flag);
682 }
683 
684 /**
685  * lpfc_hba_init_link_fc_topology - Initialize FC link with desired topology
686  * @phba: pointer to lpfc hba data structure.
687  * @fc_topology: desired fc topology.
688  * @flag: mailbox command issue mode - either MBX_POLL or MBX_NOWAIT
689  *
690  * This routine will issue the INIT_LINK mailbox command call.
691  * It is available to other drivers through the lpfc_hba data
692  * structure for use as a delayed link up mechanism with the
693  * module parameter lpfc_suppress_link_up.
694  *
695  * Return code
696  *              0 - success
697  *              Any other value - error
698  **/
699 int
700 lpfc_hba_init_link_fc_topology(struct lpfc_hba *phba, uint32_t fc_topology,
701 			       uint32_t flag)
702 {
703 	struct lpfc_vport *vport = phba->pport;
704 	LPFC_MBOXQ_t *pmb;
705 	MAILBOX_t *mb;
706 	int rc;
707 
708 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
709 	if (!pmb) {
710 		phba->link_state = LPFC_HBA_ERROR;
711 		return -ENOMEM;
712 	}
713 	mb = &pmb->u.mb;
714 	pmb->vport = vport;
715 
716 	if ((phba->cfg_link_speed > LPFC_USER_LINK_SPEED_MAX) ||
717 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_1G) &&
718 	     !(phba->lmt & LMT_1Gb)) ||
719 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_2G) &&
720 	     !(phba->lmt & LMT_2Gb)) ||
721 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_4G) &&
722 	     !(phba->lmt & LMT_4Gb)) ||
723 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_8G) &&
724 	     !(phba->lmt & LMT_8Gb)) ||
725 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_10G) &&
726 	     !(phba->lmt & LMT_10Gb)) ||
727 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_16G) &&
728 	     !(phba->lmt & LMT_16Gb)) ||
729 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_32G) &&
730 	     !(phba->lmt & LMT_32Gb)) ||
731 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_64G) &&
732 	     !(phba->lmt & LMT_64Gb))) {
733 		/* Reset link speed to auto */
734 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
735 				"1302 Invalid speed for this board:%d "
736 				"Reset link speed to auto.\n",
737 				phba->cfg_link_speed);
738 			phba->cfg_link_speed = LPFC_USER_LINK_SPEED_AUTO;
739 	}
740 	lpfc_init_link(phba, pmb, fc_topology, phba->cfg_link_speed);
741 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
742 	if (phba->sli_rev < LPFC_SLI_REV4)
743 		lpfc_set_loopback_flag(phba);
744 	rc = lpfc_sli_issue_mbox(phba, pmb, flag);
745 	if ((rc != MBX_BUSY) && (rc != MBX_SUCCESS)) {
746 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
747 				"0498 Adapter failed to init, mbxCmd x%x "
748 				"INIT_LINK, mbxStatus x%x\n",
749 				mb->mbxCommand, mb->mbxStatus);
750 		if (phba->sli_rev <= LPFC_SLI_REV3) {
751 			/* Clear all interrupt enable conditions */
752 			writel(0, phba->HCregaddr);
753 			readl(phba->HCregaddr); /* flush */
754 			/* Clear all pending interrupts */
755 			writel(0xffffffff, phba->HAregaddr);
756 			readl(phba->HAregaddr); /* flush */
757 		}
758 		phba->link_state = LPFC_HBA_ERROR;
759 		if (rc != MBX_BUSY || flag == MBX_POLL)
760 			mempool_free(pmb, phba->mbox_mem_pool);
761 		return -EIO;
762 	}
763 	phba->cfg_suppress_link_up = LPFC_INITIALIZE_LINK;
764 	if (flag == MBX_POLL)
765 		mempool_free(pmb, phba->mbox_mem_pool);
766 
767 	return 0;
768 }
769 
770 /**
771  * lpfc_hba_down_link - this routine downs the FC link
772  * @phba: pointer to lpfc hba data structure.
773  * @flag: mailbox command issue mode - either MBX_POLL or MBX_NOWAIT
774  *
775  * This routine will issue the DOWN_LINK mailbox command call.
776  * It is available to other drivers through the lpfc_hba data
777  * structure for use to stop the link.
778  *
779  * Return code
780  *		0 - success
781  *		Any other value - error
782  **/
783 static int
784 lpfc_hba_down_link(struct lpfc_hba *phba, uint32_t flag)
785 {
786 	LPFC_MBOXQ_t *pmb;
787 	int rc;
788 
789 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
790 	if (!pmb) {
791 		phba->link_state = LPFC_HBA_ERROR;
792 		return -ENOMEM;
793 	}
794 
795 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
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, KERN_ERR, LOG_TRACE_EVENT,
802 				"2522 Adapter failed to issue DOWN_LINK"
803 				" mbox command rc 0x%x\n", rc);
804 
805 		mempool_free(pmb, phba->mbox_mem_pool);
806 		return -EIO;
807 	}
808 	if (flag == MBX_POLL)
809 		mempool_free(pmb, phba->mbox_mem_pool);
810 
811 	return 0;
812 }
813 
814 /**
815  * lpfc_hba_down_prep - Perform lpfc uninitialization prior to HBA reset
816  * @phba: pointer to lpfc HBA data structure.
817  *
818  * This routine will do LPFC uninitialization before the HBA is reset when
819  * bringing down the SLI Layer.
820  *
821  * Return codes
822  *   0 - success.
823  *   Any other value - error.
824  **/
825 int
826 lpfc_hba_down_prep(struct lpfc_hba *phba)
827 {
828 	struct lpfc_vport **vports;
829 	int i;
830 
831 	if (phba->sli_rev <= LPFC_SLI_REV3) {
832 		/* Disable interrupts */
833 		writel(0, phba->HCregaddr);
834 		readl(phba->HCregaddr); /* flush */
835 	}
836 
837 	if (phba->pport->load_flag & FC_UNLOADING)
838 		lpfc_cleanup_discovery_resources(phba->pport);
839 	else {
840 		vports = lpfc_create_vport_work_array(phba);
841 		if (vports != NULL)
842 			for (i = 0; i <= phba->max_vports &&
843 				vports[i] != NULL; i++)
844 				lpfc_cleanup_discovery_resources(vports[i]);
845 		lpfc_destroy_vport_work_array(phba, vports);
846 	}
847 	return 0;
848 }
849 
850 /**
851  * lpfc_sli4_free_sp_events - Cleanup sp_queue_events to free
852  * rspiocb which got deferred
853  *
854  * @phba: pointer to lpfc HBA data structure.
855  *
856  * This routine will cleanup completed slow path events after HBA is reset
857  * when bringing down the SLI Layer.
858  *
859  *
860  * Return codes
861  *   void.
862  **/
863 static void
864 lpfc_sli4_free_sp_events(struct lpfc_hba *phba)
865 {
866 	struct lpfc_iocbq *rspiocbq;
867 	struct hbq_dmabuf *dmabuf;
868 	struct lpfc_cq_event *cq_event;
869 
870 	spin_lock_irq(&phba->hbalock);
871 	phba->hba_flag &= ~HBA_SP_QUEUE_EVT;
872 	spin_unlock_irq(&phba->hbalock);
873 
874 	while (!list_empty(&phba->sli4_hba.sp_queue_event)) {
875 		/* Get the response iocb from the head of work queue */
876 		spin_lock_irq(&phba->hbalock);
877 		list_remove_head(&phba->sli4_hba.sp_queue_event,
878 				 cq_event, struct lpfc_cq_event, list);
879 		spin_unlock_irq(&phba->hbalock);
880 
881 		switch (bf_get(lpfc_wcqe_c_code, &cq_event->cqe.wcqe_cmpl)) {
882 		case CQE_CODE_COMPL_WQE:
883 			rspiocbq = container_of(cq_event, struct lpfc_iocbq,
884 						 cq_event);
885 			lpfc_sli_release_iocbq(phba, rspiocbq);
886 			break;
887 		case CQE_CODE_RECEIVE:
888 		case CQE_CODE_RECEIVE_V1:
889 			dmabuf = container_of(cq_event, struct hbq_dmabuf,
890 					      cq_event);
891 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
892 		}
893 	}
894 }
895 
896 /**
897  * lpfc_hba_free_post_buf - Perform lpfc uninitialization after HBA reset
898  * @phba: pointer to lpfc HBA data structure.
899  *
900  * This routine will cleanup posted ELS buffers after the HBA is reset
901  * when bringing down the SLI Layer.
902  *
903  *
904  * Return codes
905  *   void.
906  **/
907 static void
908 lpfc_hba_free_post_buf(struct lpfc_hba *phba)
909 {
910 	struct lpfc_sli *psli = &phba->sli;
911 	struct lpfc_sli_ring *pring;
912 	struct lpfc_dmabuf *mp, *next_mp;
913 	LIST_HEAD(buflist);
914 	int count;
915 
916 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)
917 		lpfc_sli_hbqbuf_free_all(phba);
918 	else {
919 		/* Cleanup preposted buffers on the ELS ring */
920 		pring = &psli->sli3_ring[LPFC_ELS_RING];
921 		spin_lock_irq(&phba->hbalock);
922 		list_splice_init(&pring->postbufq, &buflist);
923 		spin_unlock_irq(&phba->hbalock);
924 
925 		count = 0;
926 		list_for_each_entry_safe(mp, next_mp, &buflist, list) {
927 			list_del(&mp->list);
928 			count++;
929 			lpfc_mbuf_free(phba, mp->virt, mp->phys);
930 			kfree(mp);
931 		}
932 
933 		spin_lock_irq(&phba->hbalock);
934 		pring->postbufq_cnt -= count;
935 		spin_unlock_irq(&phba->hbalock);
936 	}
937 }
938 
939 /**
940  * lpfc_hba_clean_txcmplq - Perform lpfc uninitialization after HBA reset
941  * @phba: pointer to lpfc HBA data structure.
942  *
943  * This routine will cleanup the txcmplq after the HBA is reset when bringing
944  * down the SLI Layer.
945  *
946  * Return codes
947  *   void
948  **/
949 static void
950 lpfc_hba_clean_txcmplq(struct lpfc_hba *phba)
951 {
952 	struct lpfc_sli *psli = &phba->sli;
953 	struct lpfc_queue *qp = NULL;
954 	struct lpfc_sli_ring *pring;
955 	LIST_HEAD(completions);
956 	int i;
957 	struct lpfc_iocbq *piocb, *next_iocb;
958 
959 	if (phba->sli_rev != LPFC_SLI_REV4) {
960 		for (i = 0; i < psli->num_rings; i++) {
961 			pring = &psli->sli3_ring[i];
962 			spin_lock_irq(&phba->hbalock);
963 			/* At this point in time the HBA is either reset or DOA
964 			 * Nothing should be on txcmplq as it will
965 			 * NEVER complete.
966 			 */
967 			list_splice_init(&pring->txcmplq, &completions);
968 			pring->txcmplq_cnt = 0;
969 			spin_unlock_irq(&phba->hbalock);
970 
971 			lpfc_sli_abort_iocb_ring(phba, pring);
972 		}
973 		/* Cancel all the IOCBs from the completions list */
974 		lpfc_sli_cancel_iocbs(phba, &completions,
975 				      IOSTAT_LOCAL_REJECT, IOERR_SLI_ABORTED);
976 		return;
977 	}
978 	list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
979 		pring = qp->pring;
980 		if (!pring)
981 			continue;
982 		spin_lock_irq(&pring->ring_lock);
983 		list_for_each_entry_safe(piocb, next_iocb,
984 					 &pring->txcmplq, list)
985 			piocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
986 		list_splice_init(&pring->txcmplq, &completions);
987 		pring->txcmplq_cnt = 0;
988 		spin_unlock_irq(&pring->ring_lock);
989 		lpfc_sli_abort_iocb_ring(phba, pring);
990 	}
991 	/* Cancel all the IOCBs from the completions list */
992 	lpfc_sli_cancel_iocbs(phba, &completions,
993 			      IOSTAT_LOCAL_REJECT, IOERR_SLI_ABORTED);
994 }
995 
996 /**
997  * lpfc_hba_down_post_s3 - Perform lpfc uninitialization after HBA reset
998  * @phba: pointer to lpfc HBA data structure.
999  *
1000  * This routine will do uninitialization after the HBA is reset when bring
1001  * down the SLI Layer.
1002  *
1003  * Return codes
1004  *   0 - success.
1005  *   Any other value - error.
1006  **/
1007 static int
1008 lpfc_hba_down_post_s3(struct lpfc_hba *phba)
1009 {
1010 	lpfc_hba_free_post_buf(phba);
1011 	lpfc_hba_clean_txcmplq(phba);
1012 	return 0;
1013 }
1014 
1015 /**
1016  * lpfc_hba_down_post_s4 - Perform lpfc uninitialization after HBA reset
1017  * @phba: pointer to lpfc HBA data structure.
1018  *
1019  * This routine will do uninitialization after the HBA is reset when bring
1020  * down the SLI Layer.
1021  *
1022  * Return codes
1023  *   0 - success.
1024  *   Any other value - error.
1025  **/
1026 static int
1027 lpfc_hba_down_post_s4(struct lpfc_hba *phba)
1028 {
1029 	struct lpfc_io_buf *psb, *psb_next;
1030 	struct lpfc_async_xchg_ctx *ctxp, *ctxp_next;
1031 	struct lpfc_sli4_hdw_queue *qp;
1032 	LIST_HEAD(aborts);
1033 	LIST_HEAD(nvme_aborts);
1034 	LIST_HEAD(nvmet_aborts);
1035 	struct lpfc_sglq *sglq_entry = NULL;
1036 	int cnt, idx;
1037 
1038 
1039 	lpfc_sli_hbqbuf_free_all(phba);
1040 	lpfc_hba_clean_txcmplq(phba);
1041 
1042 	/* At this point in time the HBA is either reset or DOA. Either
1043 	 * way, nothing should be on lpfc_abts_els_sgl_list, it needs to be
1044 	 * on the lpfc_els_sgl_list so that it can either be freed if the
1045 	 * driver is unloading or reposted if the driver is restarting
1046 	 * the port.
1047 	 */
1048 
1049 	/* sgl_list_lock required because worker thread uses this
1050 	 * list.
1051 	 */
1052 	spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
1053 	list_for_each_entry(sglq_entry,
1054 		&phba->sli4_hba.lpfc_abts_els_sgl_list, list)
1055 		sglq_entry->state = SGL_FREED;
1056 
1057 	list_splice_init(&phba->sli4_hba.lpfc_abts_els_sgl_list,
1058 			&phba->sli4_hba.lpfc_els_sgl_list);
1059 
1060 
1061 	spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
1062 
1063 	/* abts_xxxx_buf_list_lock required because worker thread uses this
1064 	 * list.
1065 	 */
1066 	spin_lock_irq(&phba->hbalock);
1067 	cnt = 0;
1068 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
1069 		qp = &phba->sli4_hba.hdwq[idx];
1070 
1071 		spin_lock(&qp->abts_io_buf_list_lock);
1072 		list_splice_init(&qp->lpfc_abts_io_buf_list,
1073 				 &aborts);
1074 
1075 		list_for_each_entry_safe(psb, psb_next, &aborts, list) {
1076 			psb->pCmd = NULL;
1077 			psb->status = IOSTAT_SUCCESS;
1078 			cnt++;
1079 		}
1080 		spin_lock(&qp->io_buf_list_put_lock);
1081 		list_splice_init(&aborts, &qp->lpfc_io_buf_list_put);
1082 		qp->put_io_bufs += qp->abts_scsi_io_bufs;
1083 		qp->put_io_bufs += qp->abts_nvme_io_bufs;
1084 		qp->abts_scsi_io_bufs = 0;
1085 		qp->abts_nvme_io_bufs = 0;
1086 		spin_unlock(&qp->io_buf_list_put_lock);
1087 		spin_unlock(&qp->abts_io_buf_list_lock);
1088 	}
1089 	spin_unlock_irq(&phba->hbalock);
1090 
1091 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
1092 		spin_lock_irq(&phba->sli4_hba.abts_nvmet_buf_list_lock);
1093 		list_splice_init(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list,
1094 				 &nvmet_aborts);
1095 		spin_unlock_irq(&phba->sli4_hba.abts_nvmet_buf_list_lock);
1096 		list_for_each_entry_safe(ctxp, ctxp_next, &nvmet_aborts, list) {
1097 			ctxp->flag &= ~(LPFC_NVME_XBUSY | LPFC_NVME_ABORT_OP);
1098 			lpfc_nvmet_ctxbuf_post(phba, ctxp->ctxbuf);
1099 		}
1100 	}
1101 
1102 	lpfc_sli4_free_sp_events(phba);
1103 	return cnt;
1104 }
1105 
1106 /**
1107  * lpfc_hba_down_post - Wrapper func for hba down post routine
1108  * @phba: pointer to lpfc HBA data structure.
1109  *
1110  * This routine wraps the actual SLI3 or SLI4 routine for performing
1111  * uninitialization after the HBA is reset when bring down the SLI Layer.
1112  *
1113  * Return codes
1114  *   0 - success.
1115  *   Any other value - error.
1116  **/
1117 int
1118 lpfc_hba_down_post(struct lpfc_hba *phba)
1119 {
1120 	return (*phba->lpfc_hba_down_post)(phba);
1121 }
1122 
1123 /**
1124  * lpfc_hb_timeout - The HBA-timer timeout handler
1125  * @t: timer context used to obtain the pointer to lpfc hba data structure.
1126  *
1127  * This is the HBA-timer timeout handler registered to the lpfc driver. When
1128  * this timer fires, a HBA timeout event shall be posted to the lpfc driver
1129  * work-port-events bitmap and the worker thread is notified. This timeout
1130  * event will be used by the worker thread to invoke the actual timeout
1131  * handler routine, lpfc_hb_timeout_handler. Any periodical operations will
1132  * be performed in the timeout handler and the HBA timeout event bit shall
1133  * be cleared by the worker thread after it has taken the event bitmap out.
1134  **/
1135 static void
1136 lpfc_hb_timeout(struct timer_list *t)
1137 {
1138 	struct lpfc_hba *phba;
1139 	uint32_t tmo_posted;
1140 	unsigned long iflag;
1141 
1142 	phba = from_timer(phba, t, hb_tmofunc);
1143 
1144 	/* Check for heart beat timeout conditions */
1145 	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
1146 	tmo_posted = phba->pport->work_port_events & WORKER_HB_TMO;
1147 	if (!tmo_posted)
1148 		phba->pport->work_port_events |= WORKER_HB_TMO;
1149 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
1150 
1151 	/* Tell the worker thread there is work to do */
1152 	if (!tmo_posted)
1153 		lpfc_worker_wake_up(phba);
1154 	return;
1155 }
1156 
1157 /**
1158  * lpfc_rrq_timeout - The RRQ-timer timeout handler
1159  * @t: timer context used to obtain the pointer to lpfc hba data structure.
1160  *
1161  * This is the RRQ-timer timeout handler registered to the lpfc driver. When
1162  * this timer fires, a RRQ timeout event shall be posted to the lpfc driver
1163  * work-port-events bitmap and the worker thread is notified. This timeout
1164  * event will be used by the worker thread to invoke the actual timeout
1165  * handler routine, lpfc_rrq_handler. Any periodical operations will
1166  * be performed in the timeout handler and the RRQ timeout event bit shall
1167  * be cleared by the worker thread after it has taken the event bitmap out.
1168  **/
1169 static void
1170 lpfc_rrq_timeout(struct timer_list *t)
1171 {
1172 	struct lpfc_hba *phba;
1173 	unsigned long iflag;
1174 
1175 	phba = from_timer(phba, t, rrq_tmr);
1176 	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
1177 	if (!(phba->pport->load_flag & FC_UNLOADING))
1178 		phba->hba_flag |= HBA_RRQ_ACTIVE;
1179 	else
1180 		phba->hba_flag &= ~HBA_RRQ_ACTIVE;
1181 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
1182 
1183 	if (!(phba->pport->load_flag & FC_UNLOADING))
1184 		lpfc_worker_wake_up(phba);
1185 }
1186 
1187 /**
1188  * lpfc_hb_mbox_cmpl - The lpfc heart-beat mailbox command callback function
1189  * @phba: pointer to lpfc hba data structure.
1190  * @pmboxq: pointer to the driver internal queue element for mailbox command.
1191  *
1192  * This is the callback function to the lpfc heart-beat mailbox command.
1193  * If configured, the lpfc driver issues the heart-beat mailbox command to
1194  * the HBA every LPFC_HB_MBOX_INTERVAL (current 5) seconds. At the time the
1195  * heart-beat mailbox command is issued, the driver shall set up heart-beat
1196  * timeout timer to LPFC_HB_MBOX_TIMEOUT (current 30) seconds and marks
1197  * heart-beat outstanding state. Once the mailbox command comes back and
1198  * no error conditions detected, the heart-beat mailbox command timer is
1199  * reset to LPFC_HB_MBOX_INTERVAL seconds and the heart-beat outstanding
1200  * state is cleared for the next heart-beat. If the timer expired with the
1201  * heart-beat outstanding state set, the driver will put the HBA offline.
1202  **/
1203 static void
1204 lpfc_hb_mbox_cmpl(struct lpfc_hba * phba, LPFC_MBOXQ_t * pmboxq)
1205 {
1206 	unsigned long drvr_flag;
1207 
1208 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
1209 	phba->hba_flag &= ~(HBA_HBEAT_INP | HBA_HBEAT_TMO);
1210 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
1211 
1212 	/* Check and reset heart-beat timer if necessary */
1213 	mempool_free(pmboxq, phba->mbox_mem_pool);
1214 	if (!(phba->pport->fc_flag & FC_OFFLINE_MODE) &&
1215 		!(phba->link_state == LPFC_HBA_ERROR) &&
1216 		!(phba->pport->load_flag & FC_UNLOADING))
1217 		mod_timer(&phba->hb_tmofunc,
1218 			  jiffies +
1219 			  msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
1220 	return;
1221 }
1222 
1223 /*
1224  * lpfc_idle_stat_delay_work - idle_stat tracking
1225  *
1226  * This routine tracks per-cq idle_stat and determines polling decisions.
1227  *
1228  * Return codes:
1229  *   None
1230  **/
1231 static void
1232 lpfc_idle_stat_delay_work(struct work_struct *work)
1233 {
1234 	struct lpfc_hba *phba = container_of(to_delayed_work(work),
1235 					     struct lpfc_hba,
1236 					     idle_stat_delay_work);
1237 	struct lpfc_queue *cq;
1238 	struct lpfc_sli4_hdw_queue *hdwq;
1239 	struct lpfc_idle_stat *idle_stat;
1240 	u32 i, idle_percent;
1241 	u64 wall, wall_idle, diff_wall, diff_idle, busy_time;
1242 
1243 	if (phba->pport->load_flag & FC_UNLOADING)
1244 		return;
1245 
1246 	if (phba->link_state == LPFC_HBA_ERROR ||
1247 	    phba->pport->fc_flag & FC_OFFLINE_MODE ||
1248 	    phba->cmf_active_mode != LPFC_CFG_OFF)
1249 		goto requeue;
1250 
1251 	for_each_present_cpu(i) {
1252 		hdwq = &phba->sli4_hba.hdwq[phba->sli4_hba.cpu_map[i].hdwq];
1253 		cq = hdwq->io_cq;
1254 
1255 		/* Skip if we've already handled this cq's primary CPU */
1256 		if (cq->chann != i)
1257 			continue;
1258 
1259 		idle_stat = &phba->sli4_hba.idle_stat[i];
1260 
1261 		/* get_cpu_idle_time returns values as running counters. Thus,
1262 		 * to know the amount for this period, the prior counter values
1263 		 * need to be subtracted from the current counter values.
1264 		 * From there, the idle time stat can be calculated as a
1265 		 * percentage of 100 - the sum of the other consumption times.
1266 		 */
1267 		wall_idle = get_cpu_idle_time(i, &wall, 1);
1268 		diff_idle = wall_idle - idle_stat->prev_idle;
1269 		diff_wall = wall - idle_stat->prev_wall;
1270 
1271 		if (diff_wall <= diff_idle)
1272 			busy_time = 0;
1273 		else
1274 			busy_time = diff_wall - diff_idle;
1275 
1276 		idle_percent = div64_u64(100 * busy_time, diff_wall);
1277 		idle_percent = 100 - idle_percent;
1278 
1279 		if (idle_percent < 15)
1280 			cq->poll_mode = LPFC_QUEUE_WORK;
1281 		else
1282 			cq->poll_mode = LPFC_IRQ_POLL;
1283 
1284 		idle_stat->prev_idle = wall_idle;
1285 		idle_stat->prev_wall = wall;
1286 	}
1287 
1288 requeue:
1289 	schedule_delayed_work(&phba->idle_stat_delay_work,
1290 			      msecs_to_jiffies(LPFC_IDLE_STAT_DELAY));
1291 }
1292 
1293 static void
1294 lpfc_hb_eq_delay_work(struct work_struct *work)
1295 {
1296 	struct lpfc_hba *phba = container_of(to_delayed_work(work),
1297 					     struct lpfc_hba, eq_delay_work);
1298 	struct lpfc_eq_intr_info *eqi, *eqi_new;
1299 	struct lpfc_queue *eq, *eq_next;
1300 	unsigned char *ena_delay = NULL;
1301 	uint32_t usdelay;
1302 	int i;
1303 
1304 	if (!phba->cfg_auto_imax || phba->pport->load_flag & FC_UNLOADING)
1305 		return;
1306 
1307 	if (phba->link_state == LPFC_HBA_ERROR ||
1308 	    phba->pport->fc_flag & FC_OFFLINE_MODE)
1309 		goto requeue;
1310 
1311 	ena_delay = kcalloc(phba->sli4_hba.num_possible_cpu, sizeof(*ena_delay),
1312 			    GFP_KERNEL);
1313 	if (!ena_delay)
1314 		goto requeue;
1315 
1316 	for (i = 0; i < phba->cfg_irq_chann; i++) {
1317 		/* Get the EQ corresponding to the IRQ vector */
1318 		eq = phba->sli4_hba.hba_eq_hdl[i].eq;
1319 		if (!eq)
1320 			continue;
1321 		if (eq->q_mode || eq->q_flag & HBA_EQ_DELAY_CHK) {
1322 			eq->q_flag &= ~HBA_EQ_DELAY_CHK;
1323 			ena_delay[eq->last_cpu] = 1;
1324 		}
1325 	}
1326 
1327 	for_each_present_cpu(i) {
1328 		eqi = per_cpu_ptr(phba->sli4_hba.eq_info, i);
1329 		if (ena_delay[i]) {
1330 			usdelay = (eqi->icnt >> 10) * LPFC_EQ_DELAY_STEP;
1331 			if (usdelay > LPFC_MAX_AUTO_EQ_DELAY)
1332 				usdelay = LPFC_MAX_AUTO_EQ_DELAY;
1333 		} else {
1334 			usdelay = 0;
1335 		}
1336 
1337 		eqi->icnt = 0;
1338 
1339 		list_for_each_entry_safe(eq, eq_next, &eqi->list, cpu_list) {
1340 			if (unlikely(eq->last_cpu != i)) {
1341 				eqi_new = per_cpu_ptr(phba->sli4_hba.eq_info,
1342 						      eq->last_cpu);
1343 				list_move_tail(&eq->cpu_list, &eqi_new->list);
1344 				continue;
1345 			}
1346 			if (usdelay != eq->q_mode)
1347 				lpfc_modify_hba_eq_delay(phba, eq->hdwq, 1,
1348 							 usdelay);
1349 		}
1350 	}
1351 
1352 	kfree(ena_delay);
1353 
1354 requeue:
1355 	queue_delayed_work(phba->wq, &phba->eq_delay_work,
1356 			   msecs_to_jiffies(LPFC_EQ_DELAY_MSECS));
1357 }
1358 
1359 /**
1360  * lpfc_hb_mxp_handler - Multi-XRI pools handler to adjust XRI distribution
1361  * @phba: pointer to lpfc hba data structure.
1362  *
1363  * For each heartbeat, this routine does some heuristic methods to adjust
1364  * XRI distribution. The goal is to fully utilize free XRIs.
1365  **/
1366 static void lpfc_hb_mxp_handler(struct lpfc_hba *phba)
1367 {
1368 	u32 i;
1369 	u32 hwq_count;
1370 
1371 	hwq_count = phba->cfg_hdw_queue;
1372 	for (i = 0; i < hwq_count; i++) {
1373 		/* Adjust XRIs in private pool */
1374 		lpfc_adjust_pvt_pool_count(phba, i);
1375 
1376 		/* Adjust high watermark */
1377 		lpfc_adjust_high_watermark(phba, i);
1378 
1379 #ifdef LPFC_MXP_STAT
1380 		/* Snapshot pbl, pvt and busy count */
1381 		lpfc_snapshot_mxp(phba, i);
1382 #endif
1383 	}
1384 }
1385 
1386 /**
1387  * lpfc_issue_hb_mbox - Issues heart-beat mailbox command
1388  * @phba: pointer to lpfc hba data structure.
1389  *
1390  * If a HB mbox is not already in progrees, this routine will allocate
1391  * a LPFC_MBOXQ_t, populate it with a MBX_HEARTBEAT (0x31) command,
1392  * and issue it. The HBA_HBEAT_INP flag means the command is in progress.
1393  **/
1394 int
1395 lpfc_issue_hb_mbox(struct lpfc_hba *phba)
1396 {
1397 	LPFC_MBOXQ_t *pmboxq;
1398 	int retval;
1399 
1400 	/* Is a Heartbeat mbox already in progress */
1401 	if (phba->hba_flag & HBA_HBEAT_INP)
1402 		return 0;
1403 
1404 	pmboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
1405 	if (!pmboxq)
1406 		return -ENOMEM;
1407 
1408 	lpfc_heart_beat(phba, pmboxq);
1409 	pmboxq->mbox_cmpl = lpfc_hb_mbox_cmpl;
1410 	pmboxq->vport = phba->pport;
1411 	retval = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
1412 
1413 	if (retval != MBX_BUSY && retval != MBX_SUCCESS) {
1414 		mempool_free(pmboxq, phba->mbox_mem_pool);
1415 		return -ENXIO;
1416 	}
1417 	phba->hba_flag |= HBA_HBEAT_INP;
1418 
1419 	return 0;
1420 }
1421 
1422 /**
1423  * lpfc_issue_hb_tmo - Signals heartbeat timer to issue mbox command
1424  * @phba: pointer to lpfc hba data structure.
1425  *
1426  * The heartbeat timer (every 5 sec) will fire. If the HBA_HBEAT_TMO
1427  * flag is set, it will force a MBX_HEARTBEAT mbox command, regardless
1428  * of the value of lpfc_enable_hba_heartbeat.
1429  * If lpfc_enable_hba_heartbeat is set, the timeout routine will always
1430  * try to issue a MBX_HEARTBEAT mbox command.
1431  **/
1432 void
1433 lpfc_issue_hb_tmo(struct lpfc_hba *phba)
1434 {
1435 	if (phba->cfg_enable_hba_heartbeat)
1436 		return;
1437 	phba->hba_flag |= HBA_HBEAT_TMO;
1438 }
1439 
1440 /**
1441  * lpfc_hb_timeout_handler - The HBA-timer timeout handler
1442  * @phba: pointer to lpfc hba data structure.
1443  *
1444  * This is the actual HBA-timer timeout handler to be invoked by the worker
1445  * thread whenever the HBA timer fired and HBA-timeout event posted. This
1446  * handler performs any periodic operations needed for the device. If such
1447  * periodic event has already been attended to either in the interrupt handler
1448  * or by processing slow-ring or fast-ring events within the HBA-timer
1449  * timeout window (LPFC_HB_MBOX_INTERVAL), this handler just simply resets
1450  * the timer for the next timeout period. If lpfc heart-beat mailbox command
1451  * is configured and there is no heart-beat mailbox command outstanding, a
1452  * heart-beat mailbox is issued and timer set properly. Otherwise, if there
1453  * has been a heart-beat mailbox command outstanding, the HBA shall be put
1454  * to offline.
1455  **/
1456 void
1457 lpfc_hb_timeout_handler(struct lpfc_hba *phba)
1458 {
1459 	struct lpfc_vport **vports;
1460 	struct lpfc_dmabuf *buf_ptr;
1461 	int retval = 0;
1462 	int i, tmo;
1463 	struct lpfc_sli *psli = &phba->sli;
1464 	LIST_HEAD(completions);
1465 
1466 	if (phba->cfg_xri_rebalancing) {
1467 		/* Multi-XRI pools handler */
1468 		lpfc_hb_mxp_handler(phba);
1469 	}
1470 
1471 	vports = lpfc_create_vport_work_array(phba);
1472 	if (vports != NULL)
1473 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
1474 			lpfc_rcv_seq_check_edtov(vports[i]);
1475 			lpfc_fdmi_change_check(vports[i]);
1476 		}
1477 	lpfc_destroy_vport_work_array(phba, vports);
1478 
1479 	if ((phba->link_state == LPFC_HBA_ERROR) ||
1480 		(phba->pport->load_flag & FC_UNLOADING) ||
1481 		(phba->pport->fc_flag & FC_OFFLINE_MODE))
1482 		return;
1483 
1484 	if (phba->elsbuf_cnt &&
1485 		(phba->elsbuf_cnt == phba->elsbuf_prev_cnt)) {
1486 		spin_lock_irq(&phba->hbalock);
1487 		list_splice_init(&phba->elsbuf, &completions);
1488 		phba->elsbuf_cnt = 0;
1489 		phba->elsbuf_prev_cnt = 0;
1490 		spin_unlock_irq(&phba->hbalock);
1491 
1492 		while (!list_empty(&completions)) {
1493 			list_remove_head(&completions, buf_ptr,
1494 				struct lpfc_dmabuf, list);
1495 			lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
1496 			kfree(buf_ptr);
1497 		}
1498 	}
1499 	phba->elsbuf_prev_cnt = phba->elsbuf_cnt;
1500 
1501 	/* If there is no heart beat outstanding, issue a heartbeat command */
1502 	if (phba->cfg_enable_hba_heartbeat) {
1503 		/* If IOs are completing, no need to issue a MBX_HEARTBEAT */
1504 		spin_lock_irq(&phba->pport->work_port_lock);
1505 		if (time_after(phba->last_completion_time +
1506 				msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL),
1507 				jiffies)) {
1508 			spin_unlock_irq(&phba->pport->work_port_lock);
1509 			if (phba->hba_flag & HBA_HBEAT_INP)
1510 				tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1511 			else
1512 				tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1513 			goto out;
1514 		}
1515 		spin_unlock_irq(&phba->pport->work_port_lock);
1516 
1517 		/* Check if a MBX_HEARTBEAT is already in progress */
1518 		if (phba->hba_flag & HBA_HBEAT_INP) {
1519 			/*
1520 			 * If heart beat timeout called with HBA_HBEAT_INP set
1521 			 * we need to give the hb mailbox cmd a chance to
1522 			 * complete or TMO.
1523 			 */
1524 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
1525 				"0459 Adapter heartbeat still outstanding: "
1526 				"last compl time was %d ms.\n",
1527 				jiffies_to_msecs(jiffies
1528 					 - phba->last_completion_time));
1529 			tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1530 		} else {
1531 			if ((!(psli->sli_flag & LPFC_SLI_MBOX_ACTIVE)) &&
1532 				(list_empty(&psli->mboxq))) {
1533 
1534 				retval = lpfc_issue_hb_mbox(phba);
1535 				if (retval) {
1536 					tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1537 					goto out;
1538 				}
1539 				phba->skipped_hb = 0;
1540 			} else if (time_before_eq(phba->last_completion_time,
1541 					phba->skipped_hb)) {
1542 				lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
1543 					"2857 Last completion time not "
1544 					" updated in %d ms\n",
1545 					jiffies_to_msecs(jiffies
1546 						 - phba->last_completion_time));
1547 			} else
1548 				phba->skipped_hb = jiffies;
1549 
1550 			tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1551 			goto out;
1552 		}
1553 	} else {
1554 		/* Check to see if we want to force a MBX_HEARTBEAT */
1555 		if (phba->hba_flag & HBA_HBEAT_TMO) {
1556 			retval = lpfc_issue_hb_mbox(phba);
1557 			if (retval)
1558 				tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1559 			else
1560 				tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1561 			goto out;
1562 		}
1563 		tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1564 	}
1565 out:
1566 	mod_timer(&phba->hb_tmofunc, jiffies + msecs_to_jiffies(tmo));
1567 }
1568 
1569 /**
1570  * lpfc_offline_eratt - Bring lpfc offline on hardware error attention
1571  * @phba: pointer to lpfc hba data structure.
1572  *
1573  * This routine is called to bring the HBA offline when HBA hardware error
1574  * other than Port Error 6 has been detected.
1575  **/
1576 static void
1577 lpfc_offline_eratt(struct lpfc_hba *phba)
1578 {
1579 	struct lpfc_sli   *psli = &phba->sli;
1580 
1581 	spin_lock_irq(&phba->hbalock);
1582 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1583 	spin_unlock_irq(&phba->hbalock);
1584 	lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
1585 
1586 	lpfc_offline(phba);
1587 	lpfc_reset_barrier(phba);
1588 	spin_lock_irq(&phba->hbalock);
1589 	lpfc_sli_brdreset(phba);
1590 	spin_unlock_irq(&phba->hbalock);
1591 	lpfc_hba_down_post(phba);
1592 	lpfc_sli_brdready(phba, HS_MBRDY);
1593 	lpfc_unblock_mgmt_io(phba);
1594 	phba->link_state = LPFC_HBA_ERROR;
1595 	return;
1596 }
1597 
1598 /**
1599  * lpfc_sli4_offline_eratt - Bring lpfc offline on SLI4 hardware error attention
1600  * @phba: pointer to lpfc hba data structure.
1601  *
1602  * This routine is called to bring a SLI4 HBA offline when HBA hardware error
1603  * other than Port Error 6 has been detected.
1604  **/
1605 void
1606 lpfc_sli4_offline_eratt(struct lpfc_hba *phba)
1607 {
1608 	spin_lock_irq(&phba->hbalock);
1609 	if (phba->link_state == LPFC_HBA_ERROR &&
1610 	    phba->hba_flag & HBA_PCI_ERR) {
1611 		spin_unlock_irq(&phba->hbalock);
1612 		return;
1613 	}
1614 	phba->link_state = LPFC_HBA_ERROR;
1615 	spin_unlock_irq(&phba->hbalock);
1616 
1617 	lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
1618 	lpfc_sli_flush_io_rings(phba);
1619 	lpfc_offline(phba);
1620 	lpfc_hba_down_post(phba);
1621 	lpfc_unblock_mgmt_io(phba);
1622 }
1623 
1624 /**
1625  * lpfc_handle_deferred_eratt - The HBA hardware deferred error handler
1626  * @phba: pointer to lpfc hba data structure.
1627  *
1628  * This routine is invoked to handle the deferred HBA hardware error
1629  * conditions. This type of error is indicated by HBA by setting ER1
1630  * and another ER bit in the host status register. The driver will
1631  * wait until the ER1 bit clears before handling the error condition.
1632  **/
1633 static void
1634 lpfc_handle_deferred_eratt(struct lpfc_hba *phba)
1635 {
1636 	uint32_t old_host_status = phba->work_hs;
1637 	struct lpfc_sli *psli = &phba->sli;
1638 
1639 	/* If the pci channel is offline, ignore possible errors,
1640 	 * since we cannot communicate with the pci card anyway.
1641 	 */
1642 	if (pci_channel_offline(phba->pcidev)) {
1643 		spin_lock_irq(&phba->hbalock);
1644 		phba->hba_flag &= ~DEFER_ERATT;
1645 		spin_unlock_irq(&phba->hbalock);
1646 		return;
1647 	}
1648 
1649 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1650 			"0479 Deferred Adapter Hardware Error "
1651 			"Data: x%x x%x x%x\n",
1652 			phba->work_hs, phba->work_status[0],
1653 			phba->work_status[1]);
1654 
1655 	spin_lock_irq(&phba->hbalock);
1656 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1657 	spin_unlock_irq(&phba->hbalock);
1658 
1659 
1660 	/*
1661 	 * Firmware stops when it triggred erratt. That could cause the I/Os
1662 	 * dropped by the firmware. Error iocb (I/O) on txcmplq and let the
1663 	 * SCSI layer retry it after re-establishing link.
1664 	 */
1665 	lpfc_sli_abort_fcp_rings(phba);
1666 
1667 	/*
1668 	 * There was a firmware error. Take the hba offline and then
1669 	 * attempt to restart it.
1670 	 */
1671 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
1672 	lpfc_offline(phba);
1673 
1674 	/* Wait for the ER1 bit to clear.*/
1675 	while (phba->work_hs & HS_FFER1) {
1676 		msleep(100);
1677 		if (lpfc_readl(phba->HSregaddr, &phba->work_hs)) {
1678 			phba->work_hs = UNPLUG_ERR ;
1679 			break;
1680 		}
1681 		/* If driver is unloading let the worker thread continue */
1682 		if (phba->pport->load_flag & FC_UNLOADING) {
1683 			phba->work_hs = 0;
1684 			break;
1685 		}
1686 	}
1687 
1688 	/*
1689 	 * This is to ptrotect against a race condition in which
1690 	 * first write to the host attention register clear the
1691 	 * host status register.
1692 	 */
1693 	if ((!phba->work_hs) && (!(phba->pport->load_flag & FC_UNLOADING)))
1694 		phba->work_hs = old_host_status & ~HS_FFER1;
1695 
1696 	spin_lock_irq(&phba->hbalock);
1697 	phba->hba_flag &= ~DEFER_ERATT;
1698 	spin_unlock_irq(&phba->hbalock);
1699 	phba->work_status[0] = readl(phba->MBslimaddr + 0xa8);
1700 	phba->work_status[1] = readl(phba->MBslimaddr + 0xac);
1701 }
1702 
1703 static void
1704 lpfc_board_errevt_to_mgmt(struct lpfc_hba *phba)
1705 {
1706 	struct lpfc_board_event_header board_event;
1707 	struct Scsi_Host *shost;
1708 
1709 	board_event.event_type = FC_REG_BOARD_EVENT;
1710 	board_event.subcategory = LPFC_EVENT_PORTINTERR;
1711 	shost = lpfc_shost_from_vport(phba->pport);
1712 	fc_host_post_vendor_event(shost, fc_get_event_number(),
1713 				  sizeof(board_event),
1714 				  (char *) &board_event,
1715 				  LPFC_NL_VENDOR_ID);
1716 }
1717 
1718 /**
1719  * lpfc_handle_eratt_s3 - The SLI3 HBA hardware error handler
1720  * @phba: pointer to lpfc hba data structure.
1721  *
1722  * This routine is invoked to handle the following HBA hardware error
1723  * conditions:
1724  * 1 - HBA error attention interrupt
1725  * 2 - DMA ring index out of range
1726  * 3 - Mailbox command came back as unknown
1727  **/
1728 static void
1729 lpfc_handle_eratt_s3(struct lpfc_hba *phba)
1730 {
1731 	struct lpfc_vport *vport = phba->pport;
1732 	struct lpfc_sli   *psli = &phba->sli;
1733 	uint32_t event_data;
1734 	unsigned long temperature;
1735 	struct temp_event temp_event_data;
1736 	struct Scsi_Host  *shost;
1737 
1738 	/* If the pci channel is offline, ignore possible errors,
1739 	 * since we cannot communicate with the pci card anyway.
1740 	 */
1741 	if (pci_channel_offline(phba->pcidev)) {
1742 		spin_lock_irq(&phba->hbalock);
1743 		phba->hba_flag &= ~DEFER_ERATT;
1744 		spin_unlock_irq(&phba->hbalock);
1745 		return;
1746 	}
1747 
1748 	/* If resets are disabled then leave the HBA alone and return */
1749 	if (!phba->cfg_enable_hba_reset)
1750 		return;
1751 
1752 	/* Send an internal error event to mgmt application */
1753 	lpfc_board_errevt_to_mgmt(phba);
1754 
1755 	if (phba->hba_flag & DEFER_ERATT)
1756 		lpfc_handle_deferred_eratt(phba);
1757 
1758 	if ((phba->work_hs & HS_FFER6) || (phba->work_hs & HS_FFER8)) {
1759 		if (phba->work_hs & HS_FFER6)
1760 			/* Re-establishing Link */
1761 			lpfc_printf_log(phba, KERN_INFO, LOG_LINK_EVENT,
1762 					"1301 Re-establishing Link "
1763 					"Data: x%x x%x x%x\n",
1764 					phba->work_hs, phba->work_status[0],
1765 					phba->work_status[1]);
1766 		if (phba->work_hs & HS_FFER8)
1767 			/* Device Zeroization */
1768 			lpfc_printf_log(phba, KERN_INFO, LOG_LINK_EVENT,
1769 					"2861 Host Authentication device "
1770 					"zeroization Data:x%x x%x x%x\n",
1771 					phba->work_hs, phba->work_status[0],
1772 					phba->work_status[1]);
1773 
1774 		spin_lock_irq(&phba->hbalock);
1775 		psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1776 		spin_unlock_irq(&phba->hbalock);
1777 
1778 		/*
1779 		* Firmware stops when it triggled erratt with HS_FFER6.
1780 		* That could cause the I/Os dropped by the firmware.
1781 		* Error iocb (I/O) on txcmplq and let the SCSI layer
1782 		* retry it after re-establishing link.
1783 		*/
1784 		lpfc_sli_abort_fcp_rings(phba);
1785 
1786 		/*
1787 		 * There was a firmware error.  Take the hba offline and then
1788 		 * attempt to restart it.
1789 		 */
1790 		lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
1791 		lpfc_offline(phba);
1792 		lpfc_sli_brdrestart(phba);
1793 		if (lpfc_online(phba) == 0) {	/* Initialize the HBA */
1794 			lpfc_unblock_mgmt_io(phba);
1795 			return;
1796 		}
1797 		lpfc_unblock_mgmt_io(phba);
1798 	} else if (phba->work_hs & HS_CRIT_TEMP) {
1799 		temperature = readl(phba->MBslimaddr + TEMPERATURE_OFFSET);
1800 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
1801 		temp_event_data.event_code = LPFC_CRIT_TEMP;
1802 		temp_event_data.data = (uint32_t)temperature;
1803 
1804 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1805 				"0406 Adapter maximum temperature exceeded "
1806 				"(%ld), taking this port offline "
1807 				"Data: x%x x%x x%x\n",
1808 				temperature, phba->work_hs,
1809 				phba->work_status[0], phba->work_status[1]);
1810 
1811 		shost = lpfc_shost_from_vport(phba->pport);
1812 		fc_host_post_vendor_event(shost, fc_get_event_number(),
1813 					  sizeof(temp_event_data),
1814 					  (char *) &temp_event_data,
1815 					  SCSI_NL_VID_TYPE_PCI
1816 					  | PCI_VENDOR_ID_EMULEX);
1817 
1818 		spin_lock_irq(&phba->hbalock);
1819 		phba->over_temp_state = HBA_OVER_TEMP;
1820 		spin_unlock_irq(&phba->hbalock);
1821 		lpfc_offline_eratt(phba);
1822 
1823 	} else {
1824 		/* The if clause above forces this code path when the status
1825 		 * failure is a value other than FFER6. Do not call the offline
1826 		 * twice. This is the adapter hardware error path.
1827 		 */
1828 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1829 				"0457 Adapter Hardware Error "
1830 				"Data: x%x x%x x%x\n",
1831 				phba->work_hs,
1832 				phba->work_status[0], phba->work_status[1]);
1833 
1834 		event_data = FC_REG_DUMP_EVENT;
1835 		shost = lpfc_shost_from_vport(vport);
1836 		fc_host_post_vendor_event(shost, fc_get_event_number(),
1837 				sizeof(event_data), (char *) &event_data,
1838 				SCSI_NL_VID_TYPE_PCI | PCI_VENDOR_ID_EMULEX);
1839 
1840 		lpfc_offline_eratt(phba);
1841 	}
1842 	return;
1843 }
1844 
1845 /**
1846  * lpfc_sli4_port_sta_fn_reset - The SLI4 function reset due to port status reg
1847  * @phba: pointer to lpfc hba data structure.
1848  * @mbx_action: flag for mailbox shutdown action.
1849  * @en_rn_msg: send reset/port recovery message.
1850  * This routine is invoked to perform an SLI4 port PCI function reset in
1851  * response to port status register polling attention. It waits for port
1852  * status register (ERR, RDY, RN) bits before proceeding with function reset.
1853  * During this process, interrupt vectors are freed and later requested
1854  * for handling possible port resource change.
1855  **/
1856 static int
1857 lpfc_sli4_port_sta_fn_reset(struct lpfc_hba *phba, int mbx_action,
1858 			    bool en_rn_msg)
1859 {
1860 	int rc;
1861 	uint32_t intr_mode;
1862 	LPFC_MBOXQ_t *mboxq;
1863 
1864 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) >=
1865 	    LPFC_SLI_INTF_IF_TYPE_2) {
1866 		/*
1867 		 * On error status condition, driver need to wait for port
1868 		 * ready before performing reset.
1869 		 */
1870 		rc = lpfc_sli4_pdev_status_reg_wait(phba);
1871 		if (rc)
1872 			return rc;
1873 	}
1874 
1875 	/* need reset: attempt for port recovery */
1876 	if (en_rn_msg)
1877 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
1878 				"2887 Reset Needed: Attempting Port "
1879 				"Recovery...\n");
1880 
1881 	/* If we are no wait, the HBA has been reset and is not
1882 	 * functional, thus we should clear
1883 	 * (LPFC_SLI_ACTIVE | LPFC_SLI_MBOX_ACTIVE) flags.
1884 	 */
1885 	if (mbx_action == LPFC_MBX_NO_WAIT) {
1886 		spin_lock_irq(&phba->hbalock);
1887 		phba->sli.sli_flag &= ~LPFC_SLI_ACTIVE;
1888 		if (phba->sli.mbox_active) {
1889 			mboxq = phba->sli.mbox_active;
1890 			mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
1891 			__lpfc_mbox_cmpl_put(phba, mboxq);
1892 			phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
1893 			phba->sli.mbox_active = NULL;
1894 		}
1895 		spin_unlock_irq(&phba->hbalock);
1896 	}
1897 
1898 	lpfc_offline_prep(phba, mbx_action);
1899 	lpfc_sli_flush_io_rings(phba);
1900 	lpfc_offline(phba);
1901 	/* release interrupt for possible resource change */
1902 	lpfc_sli4_disable_intr(phba);
1903 	rc = lpfc_sli_brdrestart(phba);
1904 	if (rc) {
1905 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1906 				"6309 Failed to restart board\n");
1907 		return rc;
1908 	}
1909 	/* request and enable interrupt */
1910 	intr_mode = lpfc_sli4_enable_intr(phba, phba->intr_mode);
1911 	if (intr_mode == LPFC_INTR_ERROR) {
1912 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1913 				"3175 Failed to enable interrupt\n");
1914 		return -EIO;
1915 	}
1916 	phba->intr_mode = intr_mode;
1917 	rc = lpfc_online(phba);
1918 	if (rc == 0)
1919 		lpfc_unblock_mgmt_io(phba);
1920 
1921 	return rc;
1922 }
1923 
1924 /**
1925  * lpfc_handle_eratt_s4 - The SLI4 HBA hardware error handler
1926  * @phba: pointer to lpfc hba data structure.
1927  *
1928  * This routine is invoked to handle the SLI4 HBA hardware error attention
1929  * conditions.
1930  **/
1931 static void
1932 lpfc_handle_eratt_s4(struct lpfc_hba *phba)
1933 {
1934 	struct lpfc_vport *vport = phba->pport;
1935 	uint32_t event_data;
1936 	struct Scsi_Host *shost;
1937 	uint32_t if_type;
1938 	struct lpfc_register portstat_reg = {0};
1939 	uint32_t reg_err1, reg_err2;
1940 	uint32_t uerrlo_reg, uemasklo_reg;
1941 	uint32_t smphr_port_status = 0, pci_rd_rc1, pci_rd_rc2;
1942 	bool en_rn_msg = true;
1943 	struct temp_event temp_event_data;
1944 	struct lpfc_register portsmphr_reg;
1945 	int rc, i;
1946 
1947 	/* If the pci channel is offline, ignore possible errors, since
1948 	 * we cannot communicate with the pci card anyway.
1949 	 */
1950 	if (pci_channel_offline(phba->pcidev)) {
1951 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1952 				"3166 pci channel is offline\n");
1953 		return;
1954 	}
1955 
1956 	memset(&portsmphr_reg, 0, sizeof(portsmphr_reg));
1957 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
1958 	switch (if_type) {
1959 	case LPFC_SLI_INTF_IF_TYPE_0:
1960 		pci_rd_rc1 = lpfc_readl(
1961 				phba->sli4_hba.u.if_type0.UERRLOregaddr,
1962 				&uerrlo_reg);
1963 		pci_rd_rc2 = lpfc_readl(
1964 				phba->sli4_hba.u.if_type0.UEMASKLOregaddr,
1965 				&uemasklo_reg);
1966 		/* consider PCI bus read error as pci_channel_offline */
1967 		if (pci_rd_rc1 == -EIO && pci_rd_rc2 == -EIO)
1968 			return;
1969 		if (!(phba->hba_flag & HBA_RECOVERABLE_UE)) {
1970 			lpfc_sli4_offline_eratt(phba);
1971 			return;
1972 		}
1973 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1974 				"7623 Checking UE recoverable");
1975 
1976 		for (i = 0; i < phba->sli4_hba.ue_to_sr / 1000; i++) {
1977 			if (lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
1978 				       &portsmphr_reg.word0))
1979 				continue;
1980 
1981 			smphr_port_status = bf_get(lpfc_port_smphr_port_status,
1982 						   &portsmphr_reg);
1983 			if ((smphr_port_status & LPFC_PORT_SEM_MASK) ==
1984 			    LPFC_PORT_SEM_UE_RECOVERABLE)
1985 				break;
1986 			/*Sleep for 1Sec, before checking SEMAPHORE */
1987 			msleep(1000);
1988 		}
1989 
1990 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1991 				"4827 smphr_port_status x%x : Waited %dSec",
1992 				smphr_port_status, i);
1993 
1994 		/* Recoverable UE, reset the HBA device */
1995 		if ((smphr_port_status & LPFC_PORT_SEM_MASK) ==
1996 		    LPFC_PORT_SEM_UE_RECOVERABLE) {
1997 			for (i = 0; i < 20; i++) {
1998 				msleep(1000);
1999 				if (!lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
2000 				    &portsmphr_reg.word0) &&
2001 				    (LPFC_POST_STAGE_PORT_READY ==
2002 				     bf_get(lpfc_port_smphr_port_status,
2003 				     &portsmphr_reg))) {
2004 					rc = lpfc_sli4_port_sta_fn_reset(phba,
2005 						LPFC_MBX_NO_WAIT, en_rn_msg);
2006 					if (rc == 0)
2007 						return;
2008 					lpfc_printf_log(phba, KERN_ERR,
2009 						LOG_TRACE_EVENT,
2010 						"4215 Failed to recover UE");
2011 					break;
2012 				}
2013 			}
2014 		}
2015 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2016 				"7624 Firmware not ready: Failing UE recovery,"
2017 				" waited %dSec", i);
2018 		phba->link_state = LPFC_HBA_ERROR;
2019 		break;
2020 
2021 	case LPFC_SLI_INTF_IF_TYPE_2:
2022 	case LPFC_SLI_INTF_IF_TYPE_6:
2023 		pci_rd_rc1 = lpfc_readl(
2024 				phba->sli4_hba.u.if_type2.STATUSregaddr,
2025 				&portstat_reg.word0);
2026 		/* consider PCI bus read error as pci_channel_offline */
2027 		if (pci_rd_rc1 == -EIO) {
2028 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2029 				"3151 PCI bus read access failure: x%x\n",
2030 				readl(phba->sli4_hba.u.if_type2.STATUSregaddr));
2031 			lpfc_sli4_offline_eratt(phba);
2032 			return;
2033 		}
2034 		reg_err1 = readl(phba->sli4_hba.u.if_type2.ERR1regaddr);
2035 		reg_err2 = readl(phba->sli4_hba.u.if_type2.ERR2regaddr);
2036 		if (bf_get(lpfc_sliport_status_oti, &portstat_reg)) {
2037 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2038 					"2889 Port Overtemperature event, "
2039 					"taking port offline Data: x%x x%x\n",
2040 					reg_err1, reg_err2);
2041 
2042 			phba->sfp_alarm |= LPFC_TRANSGRESSION_HIGH_TEMPERATURE;
2043 			temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
2044 			temp_event_data.event_code = LPFC_CRIT_TEMP;
2045 			temp_event_data.data = 0xFFFFFFFF;
2046 
2047 			shost = lpfc_shost_from_vport(phba->pport);
2048 			fc_host_post_vendor_event(shost, fc_get_event_number(),
2049 						  sizeof(temp_event_data),
2050 						  (char *)&temp_event_data,
2051 						  SCSI_NL_VID_TYPE_PCI
2052 						  | PCI_VENDOR_ID_EMULEX);
2053 
2054 			spin_lock_irq(&phba->hbalock);
2055 			phba->over_temp_state = HBA_OVER_TEMP;
2056 			spin_unlock_irq(&phba->hbalock);
2057 			lpfc_sli4_offline_eratt(phba);
2058 			return;
2059 		}
2060 		if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2061 		    reg_err2 == SLIPORT_ERR2_REG_FW_RESTART) {
2062 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2063 					"3143 Port Down: Firmware Update "
2064 					"Detected\n");
2065 			en_rn_msg = false;
2066 		} else if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2067 			 reg_err2 == SLIPORT_ERR2_REG_FORCED_DUMP)
2068 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2069 					"3144 Port Down: Debug Dump\n");
2070 		else if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2071 			 reg_err2 == SLIPORT_ERR2_REG_FUNC_PROVISON)
2072 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2073 					"3145 Port Down: Provisioning\n");
2074 
2075 		/* If resets are disabled then leave the HBA alone and return */
2076 		if (!phba->cfg_enable_hba_reset)
2077 			return;
2078 
2079 		/* Check port status register for function reset */
2080 		rc = lpfc_sli4_port_sta_fn_reset(phba, LPFC_MBX_NO_WAIT,
2081 				en_rn_msg);
2082 		if (rc == 0) {
2083 			/* don't report event on forced debug dump */
2084 			if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2085 			    reg_err2 == SLIPORT_ERR2_REG_FORCED_DUMP)
2086 				return;
2087 			else
2088 				break;
2089 		}
2090 		/* fall through for not able to recover */
2091 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2092 				"3152 Unrecoverable error\n");
2093 		phba->link_state = LPFC_HBA_ERROR;
2094 		break;
2095 	case LPFC_SLI_INTF_IF_TYPE_1:
2096 	default:
2097 		break;
2098 	}
2099 	lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
2100 			"3123 Report dump event to upper layer\n");
2101 	/* Send an internal error event to mgmt application */
2102 	lpfc_board_errevt_to_mgmt(phba);
2103 
2104 	event_data = FC_REG_DUMP_EVENT;
2105 	shost = lpfc_shost_from_vport(vport);
2106 	fc_host_post_vendor_event(shost, fc_get_event_number(),
2107 				  sizeof(event_data), (char *) &event_data,
2108 				  SCSI_NL_VID_TYPE_PCI | PCI_VENDOR_ID_EMULEX);
2109 }
2110 
2111 /**
2112  * lpfc_handle_eratt - Wrapper func for handling hba error attention
2113  * @phba: pointer to lpfc HBA data structure.
2114  *
2115  * This routine wraps the actual SLI3 or SLI4 hba error attention handling
2116  * routine from the API jump table function pointer from the lpfc_hba struct.
2117  *
2118  * Return codes
2119  *   0 - success.
2120  *   Any other value - error.
2121  **/
2122 void
2123 lpfc_handle_eratt(struct lpfc_hba *phba)
2124 {
2125 	(*phba->lpfc_handle_eratt)(phba);
2126 }
2127 
2128 /**
2129  * lpfc_handle_latt - The HBA link event handler
2130  * @phba: pointer to lpfc hba data structure.
2131  *
2132  * This routine is invoked from the worker thread to handle a HBA host
2133  * attention link event. SLI3 only.
2134  **/
2135 void
2136 lpfc_handle_latt(struct lpfc_hba *phba)
2137 {
2138 	struct lpfc_vport *vport = phba->pport;
2139 	struct lpfc_sli   *psli = &phba->sli;
2140 	LPFC_MBOXQ_t *pmb;
2141 	volatile uint32_t control;
2142 	struct lpfc_dmabuf *mp;
2143 	int rc = 0;
2144 
2145 	pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
2146 	if (!pmb) {
2147 		rc = 1;
2148 		goto lpfc_handle_latt_err_exit;
2149 	}
2150 
2151 	mp = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
2152 	if (!mp) {
2153 		rc = 2;
2154 		goto lpfc_handle_latt_free_pmb;
2155 	}
2156 
2157 	mp->virt = lpfc_mbuf_alloc(phba, 0, &mp->phys);
2158 	if (!mp->virt) {
2159 		rc = 3;
2160 		goto lpfc_handle_latt_free_mp;
2161 	}
2162 
2163 	/* Cleanup any outstanding ELS commands */
2164 	lpfc_els_flush_all_cmd(phba);
2165 
2166 	psli->slistat.link_event++;
2167 	lpfc_read_topology(phba, pmb, mp);
2168 	pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
2169 	pmb->vport = vport;
2170 	/* Block ELS IOCBs until we have processed this mbox command */
2171 	phba->sli.sli3_ring[LPFC_ELS_RING].flag |= LPFC_STOP_IOCB_EVENT;
2172 	rc = lpfc_sli_issue_mbox (phba, pmb, MBX_NOWAIT);
2173 	if (rc == MBX_NOT_FINISHED) {
2174 		rc = 4;
2175 		goto lpfc_handle_latt_free_mbuf;
2176 	}
2177 
2178 	/* Clear Link Attention in HA REG */
2179 	spin_lock_irq(&phba->hbalock);
2180 	writel(HA_LATT, phba->HAregaddr);
2181 	readl(phba->HAregaddr); /* flush */
2182 	spin_unlock_irq(&phba->hbalock);
2183 
2184 	return;
2185 
2186 lpfc_handle_latt_free_mbuf:
2187 	phba->sli.sli3_ring[LPFC_ELS_RING].flag &= ~LPFC_STOP_IOCB_EVENT;
2188 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
2189 lpfc_handle_latt_free_mp:
2190 	kfree(mp);
2191 lpfc_handle_latt_free_pmb:
2192 	mempool_free(pmb, phba->mbox_mem_pool);
2193 lpfc_handle_latt_err_exit:
2194 	/* Enable Link attention interrupts */
2195 	spin_lock_irq(&phba->hbalock);
2196 	psli->sli_flag |= LPFC_PROCESS_LA;
2197 	control = readl(phba->HCregaddr);
2198 	control |= HC_LAINT_ENA;
2199 	writel(control, phba->HCregaddr);
2200 	readl(phba->HCregaddr); /* flush */
2201 
2202 	/* Clear Link Attention in HA REG */
2203 	writel(HA_LATT, phba->HAregaddr);
2204 	readl(phba->HAregaddr); /* flush */
2205 	spin_unlock_irq(&phba->hbalock);
2206 	lpfc_linkdown(phba);
2207 	phba->link_state = LPFC_HBA_ERROR;
2208 
2209 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2210 			"0300 LATT: Cannot issue READ_LA: Data:%d\n", rc);
2211 
2212 	return;
2213 }
2214 
2215 /**
2216  * lpfc_parse_vpd - Parse VPD (Vital Product Data)
2217  * @phba: pointer to lpfc hba data structure.
2218  * @vpd: pointer to the vital product data.
2219  * @len: length of the vital product data in bytes.
2220  *
2221  * This routine parses the Vital Product Data (VPD). The VPD is treated as
2222  * an array of characters. In this routine, the ModelName, ProgramType, and
2223  * ModelDesc, etc. fields of the phba data structure will be populated.
2224  *
2225  * Return codes
2226  *   0 - pointer to the VPD passed in is NULL
2227  *   1 - success
2228  **/
2229 int
2230 lpfc_parse_vpd(struct lpfc_hba *phba, uint8_t *vpd, int len)
2231 {
2232 	uint8_t lenlo, lenhi;
2233 	int Length;
2234 	int i, j;
2235 	int finished = 0;
2236 	int index = 0;
2237 
2238 	if (!vpd)
2239 		return 0;
2240 
2241 	/* Vital Product */
2242 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
2243 			"0455 Vital Product Data: x%x x%x x%x x%x\n",
2244 			(uint32_t) vpd[0], (uint32_t) vpd[1], (uint32_t) vpd[2],
2245 			(uint32_t) vpd[3]);
2246 	while (!finished && (index < (len - 4))) {
2247 		switch (vpd[index]) {
2248 		case 0x82:
2249 		case 0x91:
2250 			index += 1;
2251 			lenlo = vpd[index];
2252 			index += 1;
2253 			lenhi = vpd[index];
2254 			index += 1;
2255 			i = ((((unsigned short)lenhi) << 8) + lenlo);
2256 			index += i;
2257 			break;
2258 		case 0x90:
2259 			index += 1;
2260 			lenlo = vpd[index];
2261 			index += 1;
2262 			lenhi = vpd[index];
2263 			index += 1;
2264 			Length = ((((unsigned short)lenhi) << 8) + lenlo);
2265 			if (Length > len - index)
2266 				Length = len - index;
2267 			while (Length > 0) {
2268 			/* Look for Serial Number */
2269 			if ((vpd[index] == 'S') && (vpd[index+1] == 'N')) {
2270 				index += 2;
2271 				i = vpd[index];
2272 				index += 1;
2273 				j = 0;
2274 				Length -= (3+i);
2275 				while(i--) {
2276 					phba->SerialNumber[j++] = vpd[index++];
2277 					if (j == 31)
2278 						break;
2279 				}
2280 				phba->SerialNumber[j] = 0;
2281 				continue;
2282 			}
2283 			else if ((vpd[index] == 'V') && (vpd[index+1] == '1')) {
2284 				phba->vpd_flag |= VPD_MODEL_DESC;
2285 				index += 2;
2286 				i = vpd[index];
2287 				index += 1;
2288 				j = 0;
2289 				Length -= (3+i);
2290 				while(i--) {
2291 					phba->ModelDesc[j++] = vpd[index++];
2292 					if (j == 255)
2293 						break;
2294 				}
2295 				phba->ModelDesc[j] = 0;
2296 				continue;
2297 			}
2298 			else if ((vpd[index] == 'V') && (vpd[index+1] == '2')) {
2299 				phba->vpd_flag |= VPD_MODEL_NAME;
2300 				index += 2;
2301 				i = vpd[index];
2302 				index += 1;
2303 				j = 0;
2304 				Length -= (3+i);
2305 				while(i--) {
2306 					phba->ModelName[j++] = vpd[index++];
2307 					if (j == 79)
2308 						break;
2309 				}
2310 				phba->ModelName[j] = 0;
2311 				continue;
2312 			}
2313 			else if ((vpd[index] == 'V') && (vpd[index+1] == '3')) {
2314 				phba->vpd_flag |= VPD_PROGRAM_TYPE;
2315 				index += 2;
2316 				i = vpd[index];
2317 				index += 1;
2318 				j = 0;
2319 				Length -= (3+i);
2320 				while(i--) {
2321 					phba->ProgramType[j++] = vpd[index++];
2322 					if (j == 255)
2323 						break;
2324 				}
2325 				phba->ProgramType[j] = 0;
2326 				continue;
2327 			}
2328 			else if ((vpd[index] == 'V') && (vpd[index+1] == '4')) {
2329 				phba->vpd_flag |= VPD_PORT;
2330 				index += 2;
2331 				i = vpd[index];
2332 				index += 1;
2333 				j = 0;
2334 				Length -= (3+i);
2335 				while(i--) {
2336 					if ((phba->sli_rev == LPFC_SLI_REV4) &&
2337 					    (phba->sli4_hba.pport_name_sta ==
2338 					     LPFC_SLI4_PPNAME_GET)) {
2339 						j++;
2340 						index++;
2341 					} else
2342 						phba->Port[j++] = vpd[index++];
2343 					if (j == 19)
2344 						break;
2345 				}
2346 				if ((phba->sli_rev != LPFC_SLI_REV4) ||
2347 				    (phba->sli4_hba.pport_name_sta ==
2348 				     LPFC_SLI4_PPNAME_NON))
2349 					phba->Port[j] = 0;
2350 				continue;
2351 			}
2352 			else {
2353 				index += 2;
2354 				i = vpd[index];
2355 				index += 1;
2356 				index += i;
2357 				Length -= (3 + i);
2358 			}
2359 		}
2360 		finished = 0;
2361 		break;
2362 		case 0x78:
2363 			finished = 1;
2364 			break;
2365 		default:
2366 			index ++;
2367 			break;
2368 		}
2369 	}
2370 
2371 	return(1);
2372 }
2373 
2374 /**
2375  * lpfc_get_hba_model_desc - Retrieve HBA device model name and description
2376  * @phba: pointer to lpfc hba data structure.
2377  * @mdp: pointer to the data structure to hold the derived model name.
2378  * @descp: pointer to the data structure to hold the derived description.
2379  *
2380  * This routine retrieves HBA's description based on its registered PCI device
2381  * ID. The @descp passed into this function points to an array of 256 chars. It
2382  * shall be returned with the model name, maximum speed, and the host bus type.
2383  * The @mdp passed into this function points to an array of 80 chars. When the
2384  * function returns, the @mdp will be filled with the model name.
2385  **/
2386 static void
2387 lpfc_get_hba_model_desc(struct lpfc_hba *phba, uint8_t *mdp, uint8_t *descp)
2388 {
2389 	lpfc_vpd_t *vp;
2390 	uint16_t dev_id = phba->pcidev->device;
2391 	int max_speed;
2392 	int GE = 0;
2393 	int oneConnect = 0; /* default is not a oneConnect */
2394 	struct {
2395 		char *name;
2396 		char *bus;
2397 		char *function;
2398 	} m = {"<Unknown>", "", ""};
2399 
2400 	if (mdp && mdp[0] != '\0'
2401 		&& descp && descp[0] != '\0')
2402 		return;
2403 
2404 	if (phba->lmt & LMT_64Gb)
2405 		max_speed = 64;
2406 	else if (phba->lmt & LMT_32Gb)
2407 		max_speed = 32;
2408 	else if (phba->lmt & LMT_16Gb)
2409 		max_speed = 16;
2410 	else if (phba->lmt & LMT_10Gb)
2411 		max_speed = 10;
2412 	else if (phba->lmt & LMT_8Gb)
2413 		max_speed = 8;
2414 	else if (phba->lmt & LMT_4Gb)
2415 		max_speed = 4;
2416 	else if (phba->lmt & LMT_2Gb)
2417 		max_speed = 2;
2418 	else if (phba->lmt & LMT_1Gb)
2419 		max_speed = 1;
2420 	else
2421 		max_speed = 0;
2422 
2423 	vp = &phba->vpd;
2424 
2425 	switch (dev_id) {
2426 	case PCI_DEVICE_ID_FIREFLY:
2427 		m = (typeof(m)){"LP6000", "PCI",
2428 				"Obsolete, Unsupported Fibre Channel Adapter"};
2429 		break;
2430 	case PCI_DEVICE_ID_SUPERFLY:
2431 		if (vp->rev.biuRev >= 1 && vp->rev.biuRev <= 3)
2432 			m = (typeof(m)){"LP7000", "PCI", ""};
2433 		else
2434 			m = (typeof(m)){"LP7000E", "PCI", ""};
2435 		m.function = "Obsolete, Unsupported Fibre Channel Adapter";
2436 		break;
2437 	case PCI_DEVICE_ID_DRAGONFLY:
2438 		m = (typeof(m)){"LP8000", "PCI",
2439 				"Obsolete, Unsupported Fibre Channel Adapter"};
2440 		break;
2441 	case PCI_DEVICE_ID_CENTAUR:
2442 		if (FC_JEDEC_ID(vp->rev.biuRev) == CENTAUR_2G_JEDEC_ID)
2443 			m = (typeof(m)){"LP9002", "PCI", ""};
2444 		else
2445 			m = (typeof(m)){"LP9000", "PCI", ""};
2446 		m.function = "Obsolete, Unsupported Fibre Channel Adapter";
2447 		break;
2448 	case PCI_DEVICE_ID_RFLY:
2449 		m = (typeof(m)){"LP952", "PCI",
2450 				"Obsolete, Unsupported Fibre Channel Adapter"};
2451 		break;
2452 	case PCI_DEVICE_ID_PEGASUS:
2453 		m = (typeof(m)){"LP9802", "PCI-X",
2454 				"Obsolete, Unsupported Fibre Channel Adapter"};
2455 		break;
2456 	case PCI_DEVICE_ID_THOR:
2457 		m = (typeof(m)){"LP10000", "PCI-X",
2458 				"Obsolete, Unsupported Fibre Channel Adapter"};
2459 		break;
2460 	case PCI_DEVICE_ID_VIPER:
2461 		m = (typeof(m)){"LPX1000",  "PCI-X",
2462 				"Obsolete, Unsupported Fibre Channel Adapter"};
2463 		break;
2464 	case PCI_DEVICE_ID_PFLY:
2465 		m = (typeof(m)){"LP982", "PCI-X",
2466 				"Obsolete, Unsupported Fibre Channel Adapter"};
2467 		break;
2468 	case PCI_DEVICE_ID_TFLY:
2469 		m = (typeof(m)){"LP1050", "PCI-X",
2470 				"Obsolete, Unsupported Fibre Channel Adapter"};
2471 		break;
2472 	case PCI_DEVICE_ID_HELIOS:
2473 		m = (typeof(m)){"LP11000", "PCI-X2",
2474 				"Obsolete, Unsupported Fibre Channel Adapter"};
2475 		break;
2476 	case PCI_DEVICE_ID_HELIOS_SCSP:
2477 		m = (typeof(m)){"LP11000-SP", "PCI-X2",
2478 				"Obsolete, Unsupported Fibre Channel Adapter"};
2479 		break;
2480 	case PCI_DEVICE_ID_HELIOS_DCSP:
2481 		m = (typeof(m)){"LP11002-SP",  "PCI-X2",
2482 				"Obsolete, Unsupported Fibre Channel Adapter"};
2483 		break;
2484 	case PCI_DEVICE_ID_NEPTUNE:
2485 		m = (typeof(m)){"LPe1000", "PCIe",
2486 				"Obsolete, Unsupported Fibre Channel Adapter"};
2487 		break;
2488 	case PCI_DEVICE_ID_NEPTUNE_SCSP:
2489 		m = (typeof(m)){"LPe1000-SP", "PCIe",
2490 				"Obsolete, Unsupported Fibre Channel Adapter"};
2491 		break;
2492 	case PCI_DEVICE_ID_NEPTUNE_DCSP:
2493 		m = (typeof(m)){"LPe1002-SP", "PCIe",
2494 				"Obsolete, Unsupported Fibre Channel Adapter"};
2495 		break;
2496 	case PCI_DEVICE_ID_BMID:
2497 		m = (typeof(m)){"LP1150", "PCI-X2", "Fibre Channel Adapter"};
2498 		break;
2499 	case PCI_DEVICE_ID_BSMB:
2500 		m = (typeof(m)){"LP111", "PCI-X2",
2501 				"Obsolete, Unsupported Fibre Channel Adapter"};
2502 		break;
2503 	case PCI_DEVICE_ID_ZEPHYR:
2504 		m = (typeof(m)){"LPe11000", "PCIe", "Fibre Channel Adapter"};
2505 		break;
2506 	case PCI_DEVICE_ID_ZEPHYR_SCSP:
2507 		m = (typeof(m)){"LPe11000", "PCIe", "Fibre Channel Adapter"};
2508 		break;
2509 	case PCI_DEVICE_ID_ZEPHYR_DCSP:
2510 		m = (typeof(m)){"LP2105", "PCIe", "FCoE Adapter"};
2511 		GE = 1;
2512 		break;
2513 	case PCI_DEVICE_ID_ZMID:
2514 		m = (typeof(m)){"LPe1150", "PCIe", "Fibre Channel Adapter"};
2515 		break;
2516 	case PCI_DEVICE_ID_ZSMB:
2517 		m = (typeof(m)){"LPe111", "PCIe", "Fibre Channel Adapter"};
2518 		break;
2519 	case PCI_DEVICE_ID_LP101:
2520 		m = (typeof(m)){"LP101", "PCI-X",
2521 				"Obsolete, Unsupported Fibre Channel Adapter"};
2522 		break;
2523 	case PCI_DEVICE_ID_LP10000S:
2524 		m = (typeof(m)){"LP10000-S", "PCI",
2525 				"Obsolete, Unsupported Fibre Channel Adapter"};
2526 		break;
2527 	case PCI_DEVICE_ID_LP11000S:
2528 		m = (typeof(m)){"LP11000-S", "PCI-X2",
2529 				"Obsolete, Unsupported Fibre Channel Adapter"};
2530 		break;
2531 	case PCI_DEVICE_ID_LPE11000S:
2532 		m = (typeof(m)){"LPe11000-S", "PCIe",
2533 				"Obsolete, Unsupported Fibre Channel Adapter"};
2534 		break;
2535 	case PCI_DEVICE_ID_SAT:
2536 		m = (typeof(m)){"LPe12000", "PCIe", "Fibre Channel Adapter"};
2537 		break;
2538 	case PCI_DEVICE_ID_SAT_MID:
2539 		m = (typeof(m)){"LPe1250", "PCIe", "Fibre Channel Adapter"};
2540 		break;
2541 	case PCI_DEVICE_ID_SAT_SMB:
2542 		m = (typeof(m)){"LPe121", "PCIe", "Fibre Channel Adapter"};
2543 		break;
2544 	case PCI_DEVICE_ID_SAT_DCSP:
2545 		m = (typeof(m)){"LPe12002-SP", "PCIe", "Fibre Channel Adapter"};
2546 		break;
2547 	case PCI_DEVICE_ID_SAT_SCSP:
2548 		m = (typeof(m)){"LPe12000-SP", "PCIe", "Fibre Channel Adapter"};
2549 		break;
2550 	case PCI_DEVICE_ID_SAT_S:
2551 		m = (typeof(m)){"LPe12000-S", "PCIe", "Fibre Channel Adapter"};
2552 		break;
2553 	case PCI_DEVICE_ID_HORNET:
2554 		m = (typeof(m)){"LP21000", "PCIe",
2555 				"Obsolete, Unsupported FCoE Adapter"};
2556 		GE = 1;
2557 		break;
2558 	case PCI_DEVICE_ID_PROTEUS_VF:
2559 		m = (typeof(m)){"LPev12000", "PCIe IOV",
2560 				"Obsolete, Unsupported Fibre Channel Adapter"};
2561 		break;
2562 	case PCI_DEVICE_ID_PROTEUS_PF:
2563 		m = (typeof(m)){"LPev12000", "PCIe IOV",
2564 				"Obsolete, Unsupported Fibre Channel Adapter"};
2565 		break;
2566 	case PCI_DEVICE_ID_PROTEUS_S:
2567 		m = (typeof(m)){"LPemv12002-S", "PCIe IOV",
2568 				"Obsolete, Unsupported Fibre Channel Adapter"};
2569 		break;
2570 	case PCI_DEVICE_ID_TIGERSHARK:
2571 		oneConnect = 1;
2572 		m = (typeof(m)){"OCe10100", "PCIe", "FCoE"};
2573 		break;
2574 	case PCI_DEVICE_ID_TOMCAT:
2575 		oneConnect = 1;
2576 		m = (typeof(m)){"OCe11100", "PCIe", "FCoE"};
2577 		break;
2578 	case PCI_DEVICE_ID_FALCON:
2579 		m = (typeof(m)){"LPSe12002-ML1-E", "PCIe",
2580 				"EmulexSecure Fibre"};
2581 		break;
2582 	case PCI_DEVICE_ID_BALIUS:
2583 		m = (typeof(m)){"LPVe12002", "PCIe Shared I/O",
2584 				"Obsolete, Unsupported Fibre Channel Adapter"};
2585 		break;
2586 	case PCI_DEVICE_ID_LANCER_FC:
2587 		m = (typeof(m)){"LPe16000", "PCIe", "Fibre Channel Adapter"};
2588 		break;
2589 	case PCI_DEVICE_ID_LANCER_FC_VF:
2590 		m = (typeof(m)){"LPe16000", "PCIe",
2591 				"Obsolete, Unsupported Fibre Channel Adapter"};
2592 		break;
2593 	case PCI_DEVICE_ID_LANCER_FCOE:
2594 		oneConnect = 1;
2595 		m = (typeof(m)){"OCe15100", "PCIe", "FCoE"};
2596 		break;
2597 	case PCI_DEVICE_ID_LANCER_FCOE_VF:
2598 		oneConnect = 1;
2599 		m = (typeof(m)){"OCe15100", "PCIe",
2600 				"Obsolete, Unsupported FCoE"};
2601 		break;
2602 	case PCI_DEVICE_ID_LANCER_G6_FC:
2603 		m = (typeof(m)){"LPe32000", "PCIe", "Fibre Channel Adapter"};
2604 		break;
2605 	case PCI_DEVICE_ID_LANCER_G7_FC:
2606 		m = (typeof(m)){"LPe36000", "PCIe", "Fibre Channel Adapter"};
2607 		break;
2608 	case PCI_DEVICE_ID_LANCER_G7P_FC:
2609 		m = (typeof(m)){"LPe38000", "PCIe", "Fibre Channel Adapter"};
2610 		break;
2611 	case PCI_DEVICE_ID_SKYHAWK:
2612 	case PCI_DEVICE_ID_SKYHAWK_VF:
2613 		oneConnect = 1;
2614 		m = (typeof(m)){"OCe14000", "PCIe", "FCoE"};
2615 		break;
2616 	default:
2617 		m = (typeof(m)){"Unknown", "", ""};
2618 		break;
2619 	}
2620 
2621 	if (mdp && mdp[0] == '\0')
2622 		snprintf(mdp, 79,"%s", m.name);
2623 	/*
2624 	 * oneConnect hba requires special processing, they are all initiators
2625 	 * and we put the port number on the end
2626 	 */
2627 	if (descp && descp[0] == '\0') {
2628 		if (oneConnect)
2629 			snprintf(descp, 255,
2630 				"Emulex OneConnect %s, %s Initiator %s",
2631 				m.name, m.function,
2632 				phba->Port);
2633 		else if (max_speed == 0)
2634 			snprintf(descp, 255,
2635 				"Emulex %s %s %s",
2636 				m.name, m.bus, m.function);
2637 		else
2638 			snprintf(descp, 255,
2639 				"Emulex %s %d%s %s %s",
2640 				m.name, max_speed, (GE) ? "GE" : "Gb",
2641 				m.bus, m.function);
2642 	}
2643 }
2644 
2645 /**
2646  * lpfc_post_buffer - Post IOCB(s) with DMA buffer descriptor(s) to a IOCB ring
2647  * @phba: pointer to lpfc hba data structure.
2648  * @pring: pointer to a IOCB ring.
2649  * @cnt: the number of IOCBs to be posted to the IOCB ring.
2650  *
2651  * This routine posts a given number of IOCBs with the associated DMA buffer
2652  * descriptors specified by the cnt argument to the given IOCB ring.
2653  *
2654  * Return codes
2655  *   The number of IOCBs NOT able to be posted to the IOCB ring.
2656  **/
2657 int
2658 lpfc_post_buffer(struct lpfc_hba *phba, struct lpfc_sli_ring *pring, int cnt)
2659 {
2660 	IOCB_t *icmd;
2661 	struct lpfc_iocbq *iocb;
2662 	struct lpfc_dmabuf *mp1, *mp2;
2663 
2664 	cnt += pring->missbufcnt;
2665 
2666 	/* While there are buffers to post */
2667 	while (cnt > 0) {
2668 		/* Allocate buffer for  command iocb */
2669 		iocb = lpfc_sli_get_iocbq(phba);
2670 		if (iocb == NULL) {
2671 			pring->missbufcnt = cnt;
2672 			return cnt;
2673 		}
2674 		icmd = &iocb->iocb;
2675 
2676 		/* 2 buffers can be posted per command */
2677 		/* Allocate buffer to post */
2678 		mp1 = kmalloc(sizeof (struct lpfc_dmabuf), GFP_KERNEL);
2679 		if (mp1)
2680 		    mp1->virt = lpfc_mbuf_alloc(phba, MEM_PRI, &mp1->phys);
2681 		if (!mp1 || !mp1->virt) {
2682 			kfree(mp1);
2683 			lpfc_sli_release_iocbq(phba, iocb);
2684 			pring->missbufcnt = cnt;
2685 			return cnt;
2686 		}
2687 
2688 		INIT_LIST_HEAD(&mp1->list);
2689 		/* Allocate buffer to post */
2690 		if (cnt > 1) {
2691 			mp2 = kmalloc(sizeof (struct lpfc_dmabuf), GFP_KERNEL);
2692 			if (mp2)
2693 				mp2->virt = lpfc_mbuf_alloc(phba, MEM_PRI,
2694 							    &mp2->phys);
2695 			if (!mp2 || !mp2->virt) {
2696 				kfree(mp2);
2697 				lpfc_mbuf_free(phba, mp1->virt, mp1->phys);
2698 				kfree(mp1);
2699 				lpfc_sli_release_iocbq(phba, iocb);
2700 				pring->missbufcnt = cnt;
2701 				return cnt;
2702 			}
2703 
2704 			INIT_LIST_HEAD(&mp2->list);
2705 		} else {
2706 			mp2 = NULL;
2707 		}
2708 
2709 		icmd->un.cont64[0].addrHigh = putPaddrHigh(mp1->phys);
2710 		icmd->un.cont64[0].addrLow = putPaddrLow(mp1->phys);
2711 		icmd->un.cont64[0].tus.f.bdeSize = FCELSSIZE;
2712 		icmd->ulpBdeCount = 1;
2713 		cnt--;
2714 		if (mp2) {
2715 			icmd->un.cont64[1].addrHigh = putPaddrHigh(mp2->phys);
2716 			icmd->un.cont64[1].addrLow = putPaddrLow(mp2->phys);
2717 			icmd->un.cont64[1].tus.f.bdeSize = FCELSSIZE;
2718 			cnt--;
2719 			icmd->ulpBdeCount = 2;
2720 		}
2721 
2722 		icmd->ulpCommand = CMD_QUE_RING_BUF64_CN;
2723 		icmd->ulpLe = 1;
2724 
2725 		if (lpfc_sli_issue_iocb(phba, pring->ringno, iocb, 0) ==
2726 		    IOCB_ERROR) {
2727 			lpfc_mbuf_free(phba, mp1->virt, mp1->phys);
2728 			kfree(mp1);
2729 			cnt++;
2730 			if (mp2) {
2731 				lpfc_mbuf_free(phba, mp2->virt, mp2->phys);
2732 				kfree(mp2);
2733 				cnt++;
2734 			}
2735 			lpfc_sli_release_iocbq(phba, iocb);
2736 			pring->missbufcnt = cnt;
2737 			return cnt;
2738 		}
2739 		lpfc_sli_ringpostbuf_put(phba, pring, mp1);
2740 		if (mp2)
2741 			lpfc_sli_ringpostbuf_put(phba, pring, mp2);
2742 	}
2743 	pring->missbufcnt = 0;
2744 	return 0;
2745 }
2746 
2747 /**
2748  * lpfc_post_rcv_buf - Post the initial receive IOCB buffers to ELS ring
2749  * @phba: pointer to lpfc hba data structure.
2750  *
2751  * This routine posts initial receive IOCB buffers to the ELS ring. The
2752  * current number of initial IOCB buffers specified by LPFC_BUF_RING0 is
2753  * set to 64 IOCBs. SLI3 only.
2754  *
2755  * Return codes
2756  *   0 - success (currently always success)
2757  **/
2758 static int
2759 lpfc_post_rcv_buf(struct lpfc_hba *phba)
2760 {
2761 	struct lpfc_sli *psli = &phba->sli;
2762 
2763 	/* Ring 0, ELS / CT buffers */
2764 	lpfc_post_buffer(phba, &psli->sli3_ring[LPFC_ELS_RING], LPFC_BUF_RING0);
2765 	/* Ring 2 - FCP no buffers needed */
2766 
2767 	return 0;
2768 }
2769 
2770 #define S(N,V) (((V)<<(N))|((V)>>(32-(N))))
2771 
2772 /**
2773  * lpfc_sha_init - Set up initial array of hash table entries
2774  * @HashResultPointer: pointer to an array as hash table.
2775  *
2776  * This routine sets up the initial values to the array of hash table entries
2777  * for the LC HBAs.
2778  **/
2779 static void
2780 lpfc_sha_init(uint32_t * HashResultPointer)
2781 {
2782 	HashResultPointer[0] = 0x67452301;
2783 	HashResultPointer[1] = 0xEFCDAB89;
2784 	HashResultPointer[2] = 0x98BADCFE;
2785 	HashResultPointer[3] = 0x10325476;
2786 	HashResultPointer[4] = 0xC3D2E1F0;
2787 }
2788 
2789 /**
2790  * lpfc_sha_iterate - Iterate initial hash table with the working hash table
2791  * @HashResultPointer: pointer to an initial/result hash table.
2792  * @HashWorkingPointer: pointer to an working hash table.
2793  *
2794  * This routine iterates an initial hash table pointed by @HashResultPointer
2795  * with the values from the working hash table pointeed by @HashWorkingPointer.
2796  * The results are putting back to the initial hash table, returned through
2797  * the @HashResultPointer as the result hash table.
2798  **/
2799 static void
2800 lpfc_sha_iterate(uint32_t * HashResultPointer, uint32_t * HashWorkingPointer)
2801 {
2802 	int t;
2803 	uint32_t TEMP;
2804 	uint32_t A, B, C, D, E;
2805 	t = 16;
2806 	do {
2807 		HashWorkingPointer[t] =
2808 		    S(1,
2809 		      HashWorkingPointer[t - 3] ^ HashWorkingPointer[t -
2810 								     8] ^
2811 		      HashWorkingPointer[t - 14] ^ HashWorkingPointer[t - 16]);
2812 	} while (++t <= 79);
2813 	t = 0;
2814 	A = HashResultPointer[0];
2815 	B = HashResultPointer[1];
2816 	C = HashResultPointer[2];
2817 	D = HashResultPointer[3];
2818 	E = HashResultPointer[4];
2819 
2820 	do {
2821 		if (t < 20) {
2822 			TEMP = ((B & C) | ((~B) & D)) + 0x5A827999;
2823 		} else if (t < 40) {
2824 			TEMP = (B ^ C ^ D) + 0x6ED9EBA1;
2825 		} else if (t < 60) {
2826 			TEMP = ((B & C) | (B & D) | (C & D)) + 0x8F1BBCDC;
2827 		} else {
2828 			TEMP = (B ^ C ^ D) + 0xCA62C1D6;
2829 		}
2830 		TEMP += S(5, A) + E + HashWorkingPointer[t];
2831 		E = D;
2832 		D = C;
2833 		C = S(30, B);
2834 		B = A;
2835 		A = TEMP;
2836 	} while (++t <= 79);
2837 
2838 	HashResultPointer[0] += A;
2839 	HashResultPointer[1] += B;
2840 	HashResultPointer[2] += C;
2841 	HashResultPointer[3] += D;
2842 	HashResultPointer[4] += E;
2843 
2844 }
2845 
2846 /**
2847  * lpfc_challenge_key - Create challenge key based on WWPN of the HBA
2848  * @RandomChallenge: pointer to the entry of host challenge random number array.
2849  * @HashWorking: pointer to the entry of the working hash array.
2850  *
2851  * This routine calculates the working hash array referred by @HashWorking
2852  * from the challenge random numbers associated with the host, referred by
2853  * @RandomChallenge. The result is put into the entry of the working hash
2854  * array and returned by reference through @HashWorking.
2855  **/
2856 static void
2857 lpfc_challenge_key(uint32_t * RandomChallenge, uint32_t * HashWorking)
2858 {
2859 	*HashWorking = (*RandomChallenge ^ *HashWorking);
2860 }
2861 
2862 /**
2863  * lpfc_hba_init - Perform special handling for LC HBA initialization
2864  * @phba: pointer to lpfc hba data structure.
2865  * @hbainit: pointer to an array of unsigned 32-bit integers.
2866  *
2867  * This routine performs the special handling for LC HBA initialization.
2868  **/
2869 void
2870 lpfc_hba_init(struct lpfc_hba *phba, uint32_t *hbainit)
2871 {
2872 	int t;
2873 	uint32_t *HashWorking;
2874 	uint32_t *pwwnn = (uint32_t *) phba->wwnn;
2875 
2876 	HashWorking = kcalloc(80, sizeof(uint32_t), GFP_KERNEL);
2877 	if (!HashWorking)
2878 		return;
2879 
2880 	HashWorking[0] = HashWorking[78] = *pwwnn++;
2881 	HashWorking[1] = HashWorking[79] = *pwwnn;
2882 
2883 	for (t = 0; t < 7; t++)
2884 		lpfc_challenge_key(phba->RandomData + t, HashWorking + t);
2885 
2886 	lpfc_sha_init(hbainit);
2887 	lpfc_sha_iterate(hbainit, HashWorking);
2888 	kfree(HashWorking);
2889 }
2890 
2891 /**
2892  * lpfc_cleanup - Performs vport cleanups before deleting a vport
2893  * @vport: pointer to a virtual N_Port data structure.
2894  *
2895  * This routine performs the necessary cleanups before deleting the @vport.
2896  * It invokes the discovery state machine to perform necessary state
2897  * transitions and to release the ndlps associated with the @vport. Note,
2898  * the physical port is treated as @vport 0.
2899  **/
2900 void
2901 lpfc_cleanup(struct lpfc_vport *vport)
2902 {
2903 	struct lpfc_hba   *phba = vport->phba;
2904 	struct lpfc_nodelist *ndlp, *next_ndlp;
2905 	int i = 0;
2906 
2907 	if (phba->link_state > LPFC_LINK_DOWN)
2908 		lpfc_port_link_failure(vport);
2909 
2910 	/* Clean up VMID resources */
2911 	if (lpfc_is_vmid_enabled(phba))
2912 		lpfc_vmid_vport_cleanup(vport);
2913 
2914 	list_for_each_entry_safe(ndlp, next_ndlp, &vport->fc_nodes, nlp_listp) {
2915 		if (vport->port_type != LPFC_PHYSICAL_PORT &&
2916 		    ndlp->nlp_DID == Fabric_DID) {
2917 			/* Just free up ndlp with Fabric_DID for vports */
2918 			lpfc_nlp_put(ndlp);
2919 			continue;
2920 		}
2921 
2922 		if (ndlp->nlp_DID == Fabric_Cntl_DID &&
2923 		    ndlp->nlp_state == NLP_STE_UNUSED_NODE) {
2924 			lpfc_nlp_put(ndlp);
2925 			continue;
2926 		}
2927 
2928 		/* Fabric Ports not in UNMAPPED state are cleaned up in the
2929 		 * DEVICE_RM event.
2930 		 */
2931 		if (ndlp->nlp_type & NLP_FABRIC &&
2932 		    ndlp->nlp_state == NLP_STE_UNMAPPED_NODE)
2933 			lpfc_disc_state_machine(vport, ndlp, NULL,
2934 					NLP_EVT_DEVICE_RECOVERY);
2935 
2936 		if (!(ndlp->fc4_xpt_flags & (NVME_XPT_REGD|SCSI_XPT_REGD)))
2937 			lpfc_disc_state_machine(vport, ndlp, NULL,
2938 					NLP_EVT_DEVICE_RM);
2939 	}
2940 
2941 	/* At this point, ALL ndlp's should be gone
2942 	 * because of the previous NLP_EVT_DEVICE_RM.
2943 	 * Lets wait for this to happen, if needed.
2944 	 */
2945 	while (!list_empty(&vport->fc_nodes)) {
2946 		if (i++ > 3000) {
2947 			lpfc_printf_vlog(vport, KERN_ERR,
2948 					 LOG_TRACE_EVENT,
2949 				"0233 Nodelist not empty\n");
2950 			list_for_each_entry_safe(ndlp, next_ndlp,
2951 						&vport->fc_nodes, nlp_listp) {
2952 				lpfc_printf_vlog(ndlp->vport, KERN_ERR,
2953 						 LOG_TRACE_EVENT,
2954 						 "0282 did:x%x ndlp:x%px "
2955 						 "refcnt:%d xflags x%x nflag x%x\n",
2956 						 ndlp->nlp_DID, (void *)ndlp,
2957 						 kref_read(&ndlp->kref),
2958 						 ndlp->fc4_xpt_flags,
2959 						 ndlp->nlp_flag);
2960 			}
2961 			break;
2962 		}
2963 
2964 		/* Wait for any activity on ndlps to settle */
2965 		msleep(10);
2966 	}
2967 	lpfc_cleanup_vports_rrqs(vport, NULL);
2968 }
2969 
2970 /**
2971  * lpfc_stop_vport_timers - Stop all the timers associated with a vport
2972  * @vport: pointer to a virtual N_Port data structure.
2973  *
2974  * This routine stops all the timers associated with a @vport. This function
2975  * is invoked before disabling or deleting a @vport. Note that the physical
2976  * port is treated as @vport 0.
2977  **/
2978 void
2979 lpfc_stop_vport_timers(struct lpfc_vport *vport)
2980 {
2981 	del_timer_sync(&vport->els_tmofunc);
2982 	del_timer_sync(&vport->delayed_disc_tmo);
2983 	lpfc_can_disctmo(vport);
2984 	return;
2985 }
2986 
2987 /**
2988  * __lpfc_sli4_stop_fcf_redisc_wait_timer - Stop FCF rediscovery wait timer
2989  * @phba: pointer to lpfc hba data structure.
2990  *
2991  * This routine stops the SLI4 FCF rediscover wait timer if it's on. The
2992  * caller of this routine should already hold the host lock.
2993  **/
2994 void
2995 __lpfc_sli4_stop_fcf_redisc_wait_timer(struct lpfc_hba *phba)
2996 {
2997 	/* Clear pending FCF rediscovery wait flag */
2998 	phba->fcf.fcf_flag &= ~FCF_REDISC_PEND;
2999 
3000 	/* Now, try to stop the timer */
3001 	del_timer(&phba->fcf.redisc_wait);
3002 }
3003 
3004 /**
3005  * lpfc_sli4_stop_fcf_redisc_wait_timer - Stop FCF rediscovery wait timer
3006  * @phba: pointer to lpfc hba data structure.
3007  *
3008  * This routine stops the SLI4 FCF rediscover wait timer if it's on. It
3009  * checks whether the FCF rediscovery wait timer is pending with the host
3010  * lock held before proceeding with disabling the timer and clearing the
3011  * wait timer pendig flag.
3012  **/
3013 void
3014 lpfc_sli4_stop_fcf_redisc_wait_timer(struct lpfc_hba *phba)
3015 {
3016 	spin_lock_irq(&phba->hbalock);
3017 	if (!(phba->fcf.fcf_flag & FCF_REDISC_PEND)) {
3018 		/* FCF rediscovery timer already fired or stopped */
3019 		spin_unlock_irq(&phba->hbalock);
3020 		return;
3021 	}
3022 	__lpfc_sli4_stop_fcf_redisc_wait_timer(phba);
3023 	/* Clear failover in progress flags */
3024 	phba->fcf.fcf_flag &= ~(FCF_DEAD_DISC | FCF_ACVL_DISC);
3025 	spin_unlock_irq(&phba->hbalock);
3026 }
3027 
3028 /**
3029  * lpfc_cmf_stop - Stop CMF processing
3030  * @phba: pointer to lpfc hba data structure.
3031  *
3032  * This is called when the link goes down or if CMF mode is turned OFF.
3033  * It is also called when going offline or unloaded just before the
3034  * congestion info buffer is unregistered.
3035  **/
3036 void
3037 lpfc_cmf_stop(struct lpfc_hba *phba)
3038 {
3039 	int cpu;
3040 	struct lpfc_cgn_stat *cgs;
3041 
3042 	/* We only do something if CMF is enabled */
3043 	if (!phba->sli4_hba.pc_sli4_params.cmf)
3044 		return;
3045 
3046 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
3047 			"6221 Stop CMF / Cancel Timer\n");
3048 
3049 	/* Cancel the CMF timer */
3050 	hrtimer_cancel(&phba->cmf_timer);
3051 
3052 	/* Zero CMF counters */
3053 	atomic_set(&phba->cmf_busy, 0);
3054 	for_each_present_cpu(cpu) {
3055 		cgs = per_cpu_ptr(phba->cmf_stat, cpu);
3056 		atomic64_set(&cgs->total_bytes, 0);
3057 		atomic64_set(&cgs->rcv_bytes, 0);
3058 		atomic_set(&cgs->rx_io_cnt, 0);
3059 		atomic64_set(&cgs->rx_latency, 0);
3060 	}
3061 	atomic_set(&phba->cmf_bw_wait, 0);
3062 
3063 	/* Resume any blocked IO - Queue unblock on workqueue */
3064 	queue_work(phba->wq, &phba->unblock_request_work);
3065 }
3066 
3067 static inline uint64_t
3068 lpfc_get_max_line_rate(struct lpfc_hba *phba)
3069 {
3070 	uint64_t rate = lpfc_sli_port_speed_get(phba);
3071 
3072 	return ((((unsigned long)rate) * 1024 * 1024) / 10);
3073 }
3074 
3075 void
3076 lpfc_cmf_signal_init(struct lpfc_hba *phba)
3077 {
3078 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
3079 			"6223 Signal CMF init\n");
3080 
3081 	/* Use the new fc_linkspeed to recalculate */
3082 	phba->cmf_interval_rate = LPFC_CMF_INTERVAL;
3083 	phba->cmf_max_line_rate = lpfc_get_max_line_rate(phba);
3084 	phba->cmf_link_byte_count = div_u64(phba->cmf_max_line_rate *
3085 					    phba->cmf_interval_rate, 1000);
3086 	phba->cmf_max_bytes_per_interval = phba->cmf_link_byte_count;
3087 
3088 	/* This is a signal to firmware to sync up CMF BW with link speed */
3089 	lpfc_issue_cmf_sync_wqe(phba, 0, 0);
3090 }
3091 
3092 /**
3093  * lpfc_cmf_start - Start CMF processing
3094  * @phba: pointer to lpfc hba data structure.
3095  *
3096  * This is called when the link comes up or if CMF mode is turned OFF
3097  * to Monitor or Managed.
3098  **/
3099 void
3100 lpfc_cmf_start(struct lpfc_hba *phba)
3101 {
3102 	struct lpfc_cgn_stat *cgs;
3103 	int cpu;
3104 
3105 	/* We only do something if CMF is enabled */
3106 	if (!phba->sli4_hba.pc_sli4_params.cmf ||
3107 	    phba->cmf_active_mode == LPFC_CFG_OFF)
3108 		return;
3109 
3110 	/* Reinitialize congestion buffer info */
3111 	lpfc_init_congestion_buf(phba);
3112 
3113 	atomic_set(&phba->cgn_fabric_warn_cnt, 0);
3114 	atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
3115 	atomic_set(&phba->cgn_sync_alarm_cnt, 0);
3116 	atomic_set(&phba->cgn_sync_warn_cnt, 0);
3117 
3118 	atomic_set(&phba->cmf_busy, 0);
3119 	for_each_present_cpu(cpu) {
3120 		cgs = per_cpu_ptr(phba->cmf_stat, cpu);
3121 		atomic64_set(&cgs->total_bytes, 0);
3122 		atomic64_set(&cgs->rcv_bytes, 0);
3123 		atomic_set(&cgs->rx_io_cnt, 0);
3124 		atomic64_set(&cgs->rx_latency, 0);
3125 	}
3126 	phba->cmf_latency.tv_sec = 0;
3127 	phba->cmf_latency.tv_nsec = 0;
3128 
3129 	lpfc_cmf_signal_init(phba);
3130 
3131 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
3132 			"6222 Start CMF / Timer\n");
3133 
3134 	phba->cmf_timer_cnt = 0;
3135 	hrtimer_start(&phba->cmf_timer,
3136 		      ktime_set(0, LPFC_CMF_INTERVAL * 1000000),
3137 		      HRTIMER_MODE_REL);
3138 	/* Setup for latency check in IO cmpl routines */
3139 	ktime_get_real_ts64(&phba->cmf_latency);
3140 
3141 	atomic_set(&phba->cmf_bw_wait, 0);
3142 	atomic_set(&phba->cmf_stop_io, 0);
3143 }
3144 
3145 /**
3146  * lpfc_stop_hba_timers - Stop all the timers associated with an HBA
3147  * @phba: pointer to lpfc hba data structure.
3148  *
3149  * This routine stops all the timers associated with a HBA. This function is
3150  * invoked before either putting a HBA offline or unloading the driver.
3151  **/
3152 void
3153 lpfc_stop_hba_timers(struct lpfc_hba *phba)
3154 {
3155 	if (phba->pport)
3156 		lpfc_stop_vport_timers(phba->pport);
3157 	cancel_delayed_work_sync(&phba->eq_delay_work);
3158 	cancel_delayed_work_sync(&phba->idle_stat_delay_work);
3159 	del_timer_sync(&phba->sli.mbox_tmo);
3160 	del_timer_sync(&phba->fabric_block_timer);
3161 	del_timer_sync(&phba->eratt_poll);
3162 	del_timer_sync(&phba->hb_tmofunc);
3163 	if (phba->sli_rev == LPFC_SLI_REV4) {
3164 		del_timer_sync(&phba->rrq_tmr);
3165 		phba->hba_flag &= ~HBA_RRQ_ACTIVE;
3166 	}
3167 	phba->hba_flag &= ~(HBA_HBEAT_INP | HBA_HBEAT_TMO);
3168 
3169 	switch (phba->pci_dev_grp) {
3170 	case LPFC_PCI_DEV_LP:
3171 		/* Stop any LightPulse device specific driver timers */
3172 		del_timer_sync(&phba->fcp_poll_timer);
3173 		break;
3174 	case LPFC_PCI_DEV_OC:
3175 		/* Stop any OneConnect device specific driver timers */
3176 		lpfc_sli4_stop_fcf_redisc_wait_timer(phba);
3177 		break;
3178 	default:
3179 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3180 				"0297 Invalid device group (x%x)\n",
3181 				phba->pci_dev_grp);
3182 		break;
3183 	}
3184 	return;
3185 }
3186 
3187 /**
3188  * lpfc_block_mgmt_io - Mark a HBA's management interface as blocked
3189  * @phba: pointer to lpfc hba data structure.
3190  * @mbx_action: flag for mailbox no wait action.
3191  *
3192  * This routine marks a HBA's management interface as blocked. Once the HBA's
3193  * management interface is marked as blocked, all the user space access to
3194  * the HBA, whether they are from sysfs interface or libdfc interface will
3195  * all be blocked. The HBA is set to block the management interface when the
3196  * driver prepares the HBA interface for online or offline.
3197  **/
3198 static void
3199 lpfc_block_mgmt_io(struct lpfc_hba *phba, int mbx_action)
3200 {
3201 	unsigned long iflag;
3202 	uint8_t actcmd = MBX_HEARTBEAT;
3203 	unsigned long timeout;
3204 
3205 	spin_lock_irqsave(&phba->hbalock, iflag);
3206 	phba->sli.sli_flag |= LPFC_BLOCK_MGMT_IO;
3207 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3208 	if (mbx_action == LPFC_MBX_NO_WAIT)
3209 		return;
3210 	timeout = msecs_to_jiffies(LPFC_MBOX_TMO * 1000) + jiffies;
3211 	spin_lock_irqsave(&phba->hbalock, iflag);
3212 	if (phba->sli.mbox_active) {
3213 		actcmd = phba->sli.mbox_active->u.mb.mbxCommand;
3214 		/* Determine how long we might wait for the active mailbox
3215 		 * command to be gracefully completed by firmware.
3216 		 */
3217 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
3218 				phba->sli.mbox_active) * 1000) + jiffies;
3219 	}
3220 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3221 
3222 	/* Wait for the outstnading mailbox command to complete */
3223 	while (phba->sli.mbox_active) {
3224 		/* Check active mailbox complete status every 2ms */
3225 		msleep(2);
3226 		if (time_after(jiffies, timeout)) {
3227 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3228 					"2813 Mgmt IO is Blocked %x "
3229 					"- mbox cmd %x still active\n",
3230 					phba->sli.sli_flag, actcmd);
3231 			break;
3232 		}
3233 	}
3234 }
3235 
3236 /**
3237  * lpfc_sli4_node_prep - Assign RPIs for active nodes.
3238  * @phba: pointer to lpfc hba data structure.
3239  *
3240  * Allocate RPIs for all active remote nodes. This is needed whenever
3241  * an SLI4 adapter is reset and the driver is not unloading. Its purpose
3242  * is to fixup the temporary rpi assignments.
3243  **/
3244 void
3245 lpfc_sli4_node_prep(struct lpfc_hba *phba)
3246 {
3247 	struct lpfc_nodelist  *ndlp, *next_ndlp;
3248 	struct lpfc_vport **vports;
3249 	int i, rpi;
3250 
3251 	if (phba->sli_rev != LPFC_SLI_REV4)
3252 		return;
3253 
3254 	vports = lpfc_create_vport_work_array(phba);
3255 	if (vports == NULL)
3256 		return;
3257 
3258 	for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3259 		if (vports[i]->load_flag & FC_UNLOADING)
3260 			continue;
3261 
3262 		list_for_each_entry_safe(ndlp, next_ndlp,
3263 					 &vports[i]->fc_nodes,
3264 					 nlp_listp) {
3265 			rpi = lpfc_sli4_alloc_rpi(phba);
3266 			if (rpi == LPFC_RPI_ALLOC_ERROR) {
3267 				/* TODO print log? */
3268 				continue;
3269 			}
3270 			ndlp->nlp_rpi = rpi;
3271 			lpfc_printf_vlog(ndlp->vport, KERN_INFO,
3272 					 LOG_NODE | LOG_DISCOVERY,
3273 					 "0009 Assign RPI x%x to ndlp x%px "
3274 					 "DID:x%06x flg:x%x\n",
3275 					 ndlp->nlp_rpi, ndlp, ndlp->nlp_DID,
3276 					 ndlp->nlp_flag);
3277 		}
3278 	}
3279 	lpfc_destroy_vport_work_array(phba, vports);
3280 }
3281 
3282 /**
3283  * lpfc_create_expedite_pool - create expedite pool
3284  * @phba: pointer to lpfc hba data structure.
3285  *
3286  * This routine moves a batch of XRIs from lpfc_io_buf_list_put of HWQ 0
3287  * to expedite pool. Mark them as expedite.
3288  **/
3289 static void lpfc_create_expedite_pool(struct lpfc_hba *phba)
3290 {
3291 	struct lpfc_sli4_hdw_queue *qp;
3292 	struct lpfc_io_buf *lpfc_ncmd;
3293 	struct lpfc_io_buf *lpfc_ncmd_next;
3294 	struct lpfc_epd_pool *epd_pool;
3295 	unsigned long iflag;
3296 
3297 	epd_pool = &phba->epd_pool;
3298 	qp = &phba->sli4_hba.hdwq[0];
3299 
3300 	spin_lock_init(&epd_pool->lock);
3301 	spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3302 	spin_lock(&epd_pool->lock);
3303 	INIT_LIST_HEAD(&epd_pool->list);
3304 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3305 				 &qp->lpfc_io_buf_list_put, list) {
3306 		list_move_tail(&lpfc_ncmd->list, &epd_pool->list);
3307 		lpfc_ncmd->expedite = true;
3308 		qp->put_io_bufs--;
3309 		epd_pool->count++;
3310 		if (epd_pool->count >= XRI_BATCH)
3311 			break;
3312 	}
3313 	spin_unlock(&epd_pool->lock);
3314 	spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3315 }
3316 
3317 /**
3318  * lpfc_destroy_expedite_pool - destroy expedite pool
3319  * @phba: pointer to lpfc hba data structure.
3320  *
3321  * This routine returns XRIs from expedite pool to lpfc_io_buf_list_put
3322  * of HWQ 0. Clear the mark.
3323  **/
3324 static void lpfc_destroy_expedite_pool(struct lpfc_hba *phba)
3325 {
3326 	struct lpfc_sli4_hdw_queue *qp;
3327 	struct lpfc_io_buf *lpfc_ncmd;
3328 	struct lpfc_io_buf *lpfc_ncmd_next;
3329 	struct lpfc_epd_pool *epd_pool;
3330 	unsigned long iflag;
3331 
3332 	epd_pool = &phba->epd_pool;
3333 	qp = &phba->sli4_hba.hdwq[0];
3334 
3335 	spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3336 	spin_lock(&epd_pool->lock);
3337 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3338 				 &epd_pool->list, list) {
3339 		list_move_tail(&lpfc_ncmd->list,
3340 			       &qp->lpfc_io_buf_list_put);
3341 		lpfc_ncmd->flags = false;
3342 		qp->put_io_bufs++;
3343 		epd_pool->count--;
3344 	}
3345 	spin_unlock(&epd_pool->lock);
3346 	spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3347 }
3348 
3349 /**
3350  * lpfc_create_multixri_pools - create multi-XRI pools
3351  * @phba: pointer to lpfc hba data structure.
3352  *
3353  * This routine initialize public, private per HWQ. Then, move XRIs from
3354  * lpfc_io_buf_list_put to public pool. High and low watermark are also
3355  * Initialized.
3356  **/
3357 void lpfc_create_multixri_pools(struct lpfc_hba *phba)
3358 {
3359 	u32 i, j;
3360 	u32 hwq_count;
3361 	u32 count_per_hwq;
3362 	struct lpfc_io_buf *lpfc_ncmd;
3363 	struct lpfc_io_buf *lpfc_ncmd_next;
3364 	unsigned long iflag;
3365 	struct lpfc_sli4_hdw_queue *qp;
3366 	struct lpfc_multixri_pool *multixri_pool;
3367 	struct lpfc_pbl_pool *pbl_pool;
3368 	struct lpfc_pvt_pool *pvt_pool;
3369 
3370 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3371 			"1234 num_hdw_queue=%d num_present_cpu=%d common_xri_cnt=%d\n",
3372 			phba->cfg_hdw_queue, phba->sli4_hba.num_present_cpu,
3373 			phba->sli4_hba.io_xri_cnt);
3374 
3375 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
3376 		lpfc_create_expedite_pool(phba);
3377 
3378 	hwq_count = phba->cfg_hdw_queue;
3379 	count_per_hwq = phba->sli4_hba.io_xri_cnt / hwq_count;
3380 
3381 	for (i = 0; i < hwq_count; i++) {
3382 		multixri_pool = kzalloc(sizeof(*multixri_pool), GFP_KERNEL);
3383 
3384 		if (!multixri_pool) {
3385 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3386 					"1238 Failed to allocate memory for "
3387 					"multixri_pool\n");
3388 
3389 			if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
3390 				lpfc_destroy_expedite_pool(phba);
3391 
3392 			j = 0;
3393 			while (j < i) {
3394 				qp = &phba->sli4_hba.hdwq[j];
3395 				kfree(qp->p_multixri_pool);
3396 				j++;
3397 			}
3398 			phba->cfg_xri_rebalancing = 0;
3399 			return;
3400 		}
3401 
3402 		qp = &phba->sli4_hba.hdwq[i];
3403 		qp->p_multixri_pool = multixri_pool;
3404 
3405 		multixri_pool->xri_limit = count_per_hwq;
3406 		multixri_pool->rrb_next_hwqid = i;
3407 
3408 		/* Deal with public free xri pool */
3409 		pbl_pool = &multixri_pool->pbl_pool;
3410 		spin_lock_init(&pbl_pool->lock);
3411 		spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3412 		spin_lock(&pbl_pool->lock);
3413 		INIT_LIST_HEAD(&pbl_pool->list);
3414 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3415 					 &qp->lpfc_io_buf_list_put, list) {
3416 			list_move_tail(&lpfc_ncmd->list, &pbl_pool->list);
3417 			qp->put_io_bufs--;
3418 			pbl_pool->count++;
3419 		}
3420 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3421 				"1235 Moved %d buffers from PUT list over to pbl_pool[%d]\n",
3422 				pbl_pool->count, i);
3423 		spin_unlock(&pbl_pool->lock);
3424 		spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3425 
3426 		/* Deal with private free xri pool */
3427 		pvt_pool = &multixri_pool->pvt_pool;
3428 		pvt_pool->high_watermark = multixri_pool->xri_limit / 2;
3429 		pvt_pool->low_watermark = XRI_BATCH;
3430 		spin_lock_init(&pvt_pool->lock);
3431 		spin_lock_irqsave(&pvt_pool->lock, iflag);
3432 		INIT_LIST_HEAD(&pvt_pool->list);
3433 		pvt_pool->count = 0;
3434 		spin_unlock_irqrestore(&pvt_pool->lock, iflag);
3435 	}
3436 }
3437 
3438 /**
3439  * lpfc_destroy_multixri_pools - destroy multi-XRI pools
3440  * @phba: pointer to lpfc hba data structure.
3441  *
3442  * This routine returns XRIs from public/private to lpfc_io_buf_list_put.
3443  **/
3444 static void lpfc_destroy_multixri_pools(struct lpfc_hba *phba)
3445 {
3446 	u32 i;
3447 	u32 hwq_count;
3448 	struct lpfc_io_buf *lpfc_ncmd;
3449 	struct lpfc_io_buf *lpfc_ncmd_next;
3450 	unsigned long iflag;
3451 	struct lpfc_sli4_hdw_queue *qp;
3452 	struct lpfc_multixri_pool *multixri_pool;
3453 	struct lpfc_pbl_pool *pbl_pool;
3454 	struct lpfc_pvt_pool *pvt_pool;
3455 
3456 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
3457 		lpfc_destroy_expedite_pool(phba);
3458 
3459 	if (!(phba->pport->load_flag & FC_UNLOADING))
3460 		lpfc_sli_flush_io_rings(phba);
3461 
3462 	hwq_count = phba->cfg_hdw_queue;
3463 
3464 	for (i = 0; i < hwq_count; i++) {
3465 		qp = &phba->sli4_hba.hdwq[i];
3466 		multixri_pool = qp->p_multixri_pool;
3467 		if (!multixri_pool)
3468 			continue;
3469 
3470 		qp->p_multixri_pool = NULL;
3471 
3472 		spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3473 
3474 		/* Deal with public free xri pool */
3475 		pbl_pool = &multixri_pool->pbl_pool;
3476 		spin_lock(&pbl_pool->lock);
3477 
3478 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3479 				"1236 Moving %d buffers from pbl_pool[%d] TO PUT list\n",
3480 				pbl_pool->count, i);
3481 
3482 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3483 					 &pbl_pool->list, list) {
3484 			list_move_tail(&lpfc_ncmd->list,
3485 				       &qp->lpfc_io_buf_list_put);
3486 			qp->put_io_bufs++;
3487 			pbl_pool->count--;
3488 		}
3489 
3490 		INIT_LIST_HEAD(&pbl_pool->list);
3491 		pbl_pool->count = 0;
3492 
3493 		spin_unlock(&pbl_pool->lock);
3494 
3495 		/* Deal with private free xri pool */
3496 		pvt_pool = &multixri_pool->pvt_pool;
3497 		spin_lock(&pvt_pool->lock);
3498 
3499 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3500 				"1237 Moving %d buffers from pvt_pool[%d] TO PUT list\n",
3501 				pvt_pool->count, i);
3502 
3503 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3504 					 &pvt_pool->list, list) {
3505 			list_move_tail(&lpfc_ncmd->list,
3506 				       &qp->lpfc_io_buf_list_put);
3507 			qp->put_io_bufs++;
3508 			pvt_pool->count--;
3509 		}
3510 
3511 		INIT_LIST_HEAD(&pvt_pool->list);
3512 		pvt_pool->count = 0;
3513 
3514 		spin_unlock(&pvt_pool->lock);
3515 		spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3516 
3517 		kfree(multixri_pool);
3518 	}
3519 }
3520 
3521 /**
3522  * lpfc_online - Initialize and bring a HBA online
3523  * @phba: pointer to lpfc hba data structure.
3524  *
3525  * This routine initializes the HBA and brings a HBA online. During this
3526  * process, the management interface is blocked to prevent user space access
3527  * to the HBA interfering with the driver initialization.
3528  *
3529  * Return codes
3530  *   0 - successful
3531  *   1 - failed
3532  **/
3533 int
3534 lpfc_online(struct lpfc_hba *phba)
3535 {
3536 	struct lpfc_vport *vport;
3537 	struct lpfc_vport **vports;
3538 	int i, error = 0;
3539 	bool vpis_cleared = false;
3540 
3541 	if (!phba)
3542 		return 0;
3543 	vport = phba->pport;
3544 
3545 	if (!(vport->fc_flag & FC_OFFLINE_MODE))
3546 		return 0;
3547 
3548 	lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
3549 			"0458 Bring Adapter online\n");
3550 
3551 	lpfc_block_mgmt_io(phba, LPFC_MBX_WAIT);
3552 
3553 	if (phba->sli_rev == LPFC_SLI_REV4) {
3554 		if (lpfc_sli4_hba_setup(phba)) { /* Initialize SLI4 HBA */
3555 			lpfc_unblock_mgmt_io(phba);
3556 			return 1;
3557 		}
3558 		spin_lock_irq(&phba->hbalock);
3559 		if (!phba->sli4_hba.max_cfg_param.vpi_used)
3560 			vpis_cleared = true;
3561 		spin_unlock_irq(&phba->hbalock);
3562 
3563 		/* Reestablish the local initiator port.
3564 		 * The offline process destroyed the previous lport.
3565 		 */
3566 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME &&
3567 				!phba->nvmet_support) {
3568 			error = lpfc_nvme_create_localport(phba->pport);
3569 			if (error)
3570 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3571 					"6132 NVME restore reg failed "
3572 					"on nvmei error x%x\n", error);
3573 		}
3574 	} else {
3575 		lpfc_sli_queue_init(phba);
3576 		if (lpfc_sli_hba_setup(phba)) {	/* Initialize SLI2/SLI3 HBA */
3577 			lpfc_unblock_mgmt_io(phba);
3578 			return 1;
3579 		}
3580 	}
3581 
3582 	vports = lpfc_create_vport_work_array(phba);
3583 	if (vports != NULL) {
3584 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3585 			struct Scsi_Host *shost;
3586 			shost = lpfc_shost_from_vport(vports[i]);
3587 			spin_lock_irq(shost->host_lock);
3588 			vports[i]->fc_flag &= ~FC_OFFLINE_MODE;
3589 			if (phba->sli3_options & LPFC_SLI3_NPIV_ENABLED)
3590 				vports[i]->fc_flag |= FC_VPORT_NEEDS_REG_VPI;
3591 			if (phba->sli_rev == LPFC_SLI_REV4) {
3592 				vports[i]->fc_flag |= FC_VPORT_NEEDS_INIT_VPI;
3593 				if ((vpis_cleared) &&
3594 				    (vports[i]->port_type !=
3595 					LPFC_PHYSICAL_PORT))
3596 					vports[i]->vpi = 0;
3597 			}
3598 			spin_unlock_irq(shost->host_lock);
3599 		}
3600 	}
3601 	lpfc_destroy_vport_work_array(phba, vports);
3602 
3603 	if (phba->cfg_xri_rebalancing)
3604 		lpfc_create_multixri_pools(phba);
3605 
3606 	lpfc_cpuhp_add(phba);
3607 
3608 	lpfc_unblock_mgmt_io(phba);
3609 	return 0;
3610 }
3611 
3612 /**
3613  * lpfc_unblock_mgmt_io - Mark a HBA's management interface to be not blocked
3614  * @phba: pointer to lpfc hba data structure.
3615  *
3616  * This routine marks a HBA's management interface as not blocked. Once the
3617  * HBA's management interface is marked as not blocked, all the user space
3618  * access to the HBA, whether they are from sysfs interface or libdfc
3619  * interface will be allowed. The HBA is set to block the management interface
3620  * when the driver prepares the HBA interface for online or offline and then
3621  * set to unblock the management interface afterwards.
3622  **/
3623 void
3624 lpfc_unblock_mgmt_io(struct lpfc_hba * phba)
3625 {
3626 	unsigned long iflag;
3627 
3628 	spin_lock_irqsave(&phba->hbalock, iflag);
3629 	phba->sli.sli_flag &= ~LPFC_BLOCK_MGMT_IO;
3630 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3631 }
3632 
3633 /**
3634  * lpfc_offline_prep - Prepare a HBA to be brought offline
3635  * @phba: pointer to lpfc hba data structure.
3636  * @mbx_action: flag for mailbox shutdown action.
3637  *
3638  * This routine is invoked to prepare a HBA to be brought offline. It performs
3639  * unregistration login to all the nodes on all vports and flushes the mailbox
3640  * queue to make it ready to be brought offline.
3641  **/
3642 void
3643 lpfc_offline_prep(struct lpfc_hba *phba, int mbx_action)
3644 {
3645 	struct lpfc_vport *vport = phba->pport;
3646 	struct lpfc_nodelist  *ndlp, *next_ndlp;
3647 	struct lpfc_vport **vports;
3648 	struct Scsi_Host *shost;
3649 	int i;
3650 	int offline = 0;
3651 
3652 	if (vport->fc_flag & FC_OFFLINE_MODE)
3653 		return;
3654 
3655 	lpfc_block_mgmt_io(phba, mbx_action);
3656 
3657 	lpfc_linkdown(phba);
3658 
3659 	offline =  pci_channel_offline(phba->pcidev);
3660 
3661 	/* Issue an unreg_login to all nodes on all vports */
3662 	vports = lpfc_create_vport_work_array(phba);
3663 	if (vports != NULL) {
3664 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3665 			if (vports[i]->load_flag & FC_UNLOADING)
3666 				continue;
3667 			shost = lpfc_shost_from_vport(vports[i]);
3668 			spin_lock_irq(shost->host_lock);
3669 			vports[i]->vpi_state &= ~LPFC_VPI_REGISTERED;
3670 			vports[i]->fc_flag |= FC_VPORT_NEEDS_REG_VPI;
3671 			vports[i]->fc_flag &= ~FC_VFI_REGISTERED;
3672 			spin_unlock_irq(shost->host_lock);
3673 
3674 			shost =	lpfc_shost_from_vport(vports[i]);
3675 			list_for_each_entry_safe(ndlp, next_ndlp,
3676 						 &vports[i]->fc_nodes,
3677 						 nlp_listp) {
3678 
3679 				spin_lock_irq(&ndlp->lock);
3680 				ndlp->nlp_flag &= ~NLP_NPR_ADISC;
3681 				spin_unlock_irq(&ndlp->lock);
3682 
3683 				if (offline) {
3684 					spin_lock_irq(&ndlp->lock);
3685 					ndlp->nlp_flag &= ~(NLP_UNREG_INP |
3686 							    NLP_RPI_REGISTERED);
3687 					spin_unlock_irq(&ndlp->lock);
3688 				} else {
3689 					lpfc_unreg_rpi(vports[i], ndlp);
3690 				}
3691 				/*
3692 				 * Whenever an SLI4 port goes offline, free the
3693 				 * RPI. Get a new RPI when the adapter port
3694 				 * comes back online.
3695 				 */
3696 				if (phba->sli_rev == LPFC_SLI_REV4) {
3697 					lpfc_printf_vlog(vports[i], KERN_INFO,
3698 						 LOG_NODE | LOG_DISCOVERY,
3699 						 "0011 Free RPI x%x on "
3700 						 "ndlp: x%px did x%x\n",
3701 						 ndlp->nlp_rpi, ndlp,
3702 						 ndlp->nlp_DID);
3703 					lpfc_sli4_free_rpi(phba, ndlp->nlp_rpi);
3704 					ndlp->nlp_rpi = LPFC_RPI_ALLOC_ERROR;
3705 				}
3706 
3707 				if (ndlp->nlp_type & NLP_FABRIC) {
3708 					lpfc_disc_state_machine(vports[i], ndlp,
3709 						NULL, NLP_EVT_DEVICE_RECOVERY);
3710 
3711 					/* Don't remove the node unless the node
3712 					 * has been unregistered with the
3713 					 * transport, and we're not in recovery
3714 					 * before dev_loss_tmo triggered.
3715 					 * Otherwise, let dev_loss take care of
3716 					 * the node.
3717 					 */
3718 					if (!(ndlp->save_flags &
3719 					      NLP_IN_RECOV_POST_DEV_LOSS) &&
3720 					    !(ndlp->fc4_xpt_flags &
3721 					      (NVME_XPT_REGD | SCSI_XPT_REGD)))
3722 						lpfc_disc_state_machine
3723 							(vports[i], ndlp,
3724 							 NULL,
3725 							 NLP_EVT_DEVICE_RM);
3726 				}
3727 			}
3728 		}
3729 	}
3730 	lpfc_destroy_vport_work_array(phba, vports);
3731 
3732 	lpfc_sli_mbox_sys_shutdown(phba, mbx_action);
3733 
3734 	if (phba->wq)
3735 		flush_workqueue(phba->wq);
3736 }
3737 
3738 /**
3739  * lpfc_offline - Bring a HBA offline
3740  * @phba: pointer to lpfc hba data structure.
3741  *
3742  * This routine actually brings a HBA offline. It stops all the timers
3743  * associated with the HBA, brings down the SLI layer, and eventually
3744  * marks the HBA as in offline state for the upper layer protocol.
3745  **/
3746 void
3747 lpfc_offline(struct lpfc_hba *phba)
3748 {
3749 	struct Scsi_Host  *shost;
3750 	struct lpfc_vport **vports;
3751 	int i;
3752 
3753 	if (phba->pport->fc_flag & FC_OFFLINE_MODE)
3754 		return;
3755 
3756 	/* stop port and all timers associated with this hba */
3757 	lpfc_stop_port(phba);
3758 
3759 	/* Tear down the local and target port registrations.  The
3760 	 * nvme transports need to cleanup.
3761 	 */
3762 	lpfc_nvmet_destroy_targetport(phba);
3763 	lpfc_nvme_destroy_localport(phba->pport);
3764 
3765 	vports = lpfc_create_vport_work_array(phba);
3766 	if (vports != NULL)
3767 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++)
3768 			lpfc_stop_vport_timers(vports[i]);
3769 	lpfc_destroy_vport_work_array(phba, vports);
3770 	lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
3771 			"0460 Bring Adapter offline\n");
3772 	/* Bring down the SLI Layer and cleanup.  The HBA is offline
3773 	   now.  */
3774 	lpfc_sli_hba_down(phba);
3775 	spin_lock_irq(&phba->hbalock);
3776 	phba->work_ha = 0;
3777 	spin_unlock_irq(&phba->hbalock);
3778 	vports = lpfc_create_vport_work_array(phba);
3779 	if (vports != NULL)
3780 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3781 			shost = lpfc_shost_from_vport(vports[i]);
3782 			spin_lock_irq(shost->host_lock);
3783 			vports[i]->work_port_events = 0;
3784 			vports[i]->fc_flag |= FC_OFFLINE_MODE;
3785 			spin_unlock_irq(shost->host_lock);
3786 		}
3787 	lpfc_destroy_vport_work_array(phba, vports);
3788 	/* If OFFLINE flag is clear (i.e. unloading), cpuhp removal is handled
3789 	 * in hba_unset
3790 	 */
3791 	if (phba->pport->fc_flag & FC_OFFLINE_MODE)
3792 		__lpfc_cpuhp_remove(phba);
3793 
3794 	if (phba->cfg_xri_rebalancing)
3795 		lpfc_destroy_multixri_pools(phba);
3796 }
3797 
3798 /**
3799  * lpfc_scsi_free - Free all the SCSI buffers and IOCBs from driver lists
3800  * @phba: pointer to lpfc hba data structure.
3801  *
3802  * This routine is to free all the SCSI buffers and IOCBs from the driver
3803  * list back to kernel. It is called from lpfc_pci_remove_one to free
3804  * the internal resources before the device is removed from the system.
3805  **/
3806 static void
3807 lpfc_scsi_free(struct lpfc_hba *phba)
3808 {
3809 	struct lpfc_io_buf *sb, *sb_next;
3810 
3811 	if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP))
3812 		return;
3813 
3814 	spin_lock_irq(&phba->hbalock);
3815 
3816 	/* Release all the lpfc_scsi_bufs maintained by this host. */
3817 
3818 	spin_lock(&phba->scsi_buf_list_put_lock);
3819 	list_for_each_entry_safe(sb, sb_next, &phba->lpfc_scsi_buf_list_put,
3820 				 list) {
3821 		list_del(&sb->list);
3822 		dma_pool_free(phba->lpfc_sg_dma_buf_pool, sb->data,
3823 			      sb->dma_handle);
3824 		kfree(sb);
3825 		phba->total_scsi_bufs--;
3826 	}
3827 	spin_unlock(&phba->scsi_buf_list_put_lock);
3828 
3829 	spin_lock(&phba->scsi_buf_list_get_lock);
3830 	list_for_each_entry_safe(sb, sb_next, &phba->lpfc_scsi_buf_list_get,
3831 				 list) {
3832 		list_del(&sb->list);
3833 		dma_pool_free(phba->lpfc_sg_dma_buf_pool, sb->data,
3834 			      sb->dma_handle);
3835 		kfree(sb);
3836 		phba->total_scsi_bufs--;
3837 	}
3838 	spin_unlock(&phba->scsi_buf_list_get_lock);
3839 	spin_unlock_irq(&phba->hbalock);
3840 }
3841 
3842 /**
3843  * lpfc_io_free - Free all the IO buffers and IOCBs from driver lists
3844  * @phba: pointer to lpfc hba data structure.
3845  *
3846  * This routine is to free all the IO buffers and IOCBs from the driver
3847  * list back to kernel. It is called from lpfc_pci_remove_one to free
3848  * the internal resources before the device is removed from the system.
3849  **/
3850 void
3851 lpfc_io_free(struct lpfc_hba *phba)
3852 {
3853 	struct lpfc_io_buf *lpfc_ncmd, *lpfc_ncmd_next;
3854 	struct lpfc_sli4_hdw_queue *qp;
3855 	int idx;
3856 
3857 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
3858 		qp = &phba->sli4_hba.hdwq[idx];
3859 		/* Release all the lpfc_nvme_bufs maintained by this host. */
3860 		spin_lock(&qp->io_buf_list_put_lock);
3861 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3862 					 &qp->lpfc_io_buf_list_put,
3863 					 list) {
3864 			list_del(&lpfc_ncmd->list);
3865 			qp->put_io_bufs--;
3866 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
3867 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
3868 			if (phba->cfg_xpsgl && !phba->nvmet_support)
3869 				lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
3870 			lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
3871 			kfree(lpfc_ncmd);
3872 			qp->total_io_bufs--;
3873 		}
3874 		spin_unlock(&qp->io_buf_list_put_lock);
3875 
3876 		spin_lock(&qp->io_buf_list_get_lock);
3877 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3878 					 &qp->lpfc_io_buf_list_get,
3879 					 list) {
3880 			list_del(&lpfc_ncmd->list);
3881 			qp->get_io_bufs--;
3882 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
3883 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
3884 			if (phba->cfg_xpsgl && !phba->nvmet_support)
3885 				lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
3886 			lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
3887 			kfree(lpfc_ncmd);
3888 			qp->total_io_bufs--;
3889 		}
3890 		spin_unlock(&qp->io_buf_list_get_lock);
3891 	}
3892 }
3893 
3894 /**
3895  * lpfc_sli4_els_sgl_update - update ELS xri-sgl sizing and mapping
3896  * @phba: pointer to lpfc hba data structure.
3897  *
3898  * This routine first calculates the sizes of the current els and allocated
3899  * scsi sgl lists, and then goes through all sgls to updates the physical
3900  * XRIs assigned due to port function reset. During port initialization, the
3901  * current els and allocated scsi sgl lists are 0s.
3902  *
3903  * Return codes
3904  *   0 - successful (for now, it always returns 0)
3905  **/
3906 int
3907 lpfc_sli4_els_sgl_update(struct lpfc_hba *phba)
3908 {
3909 	struct lpfc_sglq *sglq_entry = NULL, *sglq_entry_next = NULL;
3910 	uint16_t i, lxri, xri_cnt, els_xri_cnt;
3911 	LIST_HEAD(els_sgl_list);
3912 	int rc;
3913 
3914 	/*
3915 	 * update on pci function's els xri-sgl list
3916 	 */
3917 	els_xri_cnt = lpfc_sli4_get_els_iocb_cnt(phba);
3918 
3919 	if (els_xri_cnt > phba->sli4_hba.els_xri_cnt) {
3920 		/* els xri-sgl expanded */
3921 		xri_cnt = els_xri_cnt - phba->sli4_hba.els_xri_cnt;
3922 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3923 				"3157 ELS xri-sgl count increased from "
3924 				"%d to %d\n", phba->sli4_hba.els_xri_cnt,
3925 				els_xri_cnt);
3926 		/* allocate the additional els sgls */
3927 		for (i = 0; i < xri_cnt; i++) {
3928 			sglq_entry = kzalloc(sizeof(struct lpfc_sglq),
3929 					     GFP_KERNEL);
3930 			if (sglq_entry == NULL) {
3931 				lpfc_printf_log(phba, KERN_ERR,
3932 						LOG_TRACE_EVENT,
3933 						"2562 Failure to allocate an "
3934 						"ELS sgl entry:%d\n", i);
3935 				rc = -ENOMEM;
3936 				goto out_free_mem;
3937 			}
3938 			sglq_entry->buff_type = GEN_BUFF_TYPE;
3939 			sglq_entry->virt = lpfc_mbuf_alloc(phba, 0,
3940 							   &sglq_entry->phys);
3941 			if (sglq_entry->virt == NULL) {
3942 				kfree(sglq_entry);
3943 				lpfc_printf_log(phba, KERN_ERR,
3944 						LOG_TRACE_EVENT,
3945 						"2563 Failure to allocate an "
3946 						"ELS mbuf:%d\n", i);
3947 				rc = -ENOMEM;
3948 				goto out_free_mem;
3949 			}
3950 			sglq_entry->sgl = sglq_entry->virt;
3951 			memset(sglq_entry->sgl, 0, LPFC_BPL_SIZE);
3952 			sglq_entry->state = SGL_FREED;
3953 			list_add_tail(&sglq_entry->list, &els_sgl_list);
3954 		}
3955 		spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
3956 		list_splice_init(&els_sgl_list,
3957 				 &phba->sli4_hba.lpfc_els_sgl_list);
3958 		spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
3959 	} else if (els_xri_cnt < phba->sli4_hba.els_xri_cnt) {
3960 		/* els xri-sgl shrinked */
3961 		xri_cnt = phba->sli4_hba.els_xri_cnt - els_xri_cnt;
3962 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3963 				"3158 ELS xri-sgl count decreased from "
3964 				"%d to %d\n", phba->sli4_hba.els_xri_cnt,
3965 				els_xri_cnt);
3966 		spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
3967 		list_splice_init(&phba->sli4_hba.lpfc_els_sgl_list,
3968 				 &els_sgl_list);
3969 		/* release extra els sgls from list */
3970 		for (i = 0; i < xri_cnt; i++) {
3971 			list_remove_head(&els_sgl_list,
3972 					 sglq_entry, struct lpfc_sglq, list);
3973 			if (sglq_entry) {
3974 				__lpfc_mbuf_free(phba, sglq_entry->virt,
3975 						 sglq_entry->phys);
3976 				kfree(sglq_entry);
3977 			}
3978 		}
3979 		list_splice_init(&els_sgl_list,
3980 				 &phba->sli4_hba.lpfc_els_sgl_list);
3981 		spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
3982 	} else
3983 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3984 				"3163 ELS xri-sgl count unchanged: %d\n",
3985 				els_xri_cnt);
3986 	phba->sli4_hba.els_xri_cnt = els_xri_cnt;
3987 
3988 	/* update xris to els sgls on the list */
3989 	sglq_entry = NULL;
3990 	sglq_entry_next = NULL;
3991 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
3992 				 &phba->sli4_hba.lpfc_els_sgl_list, list) {
3993 		lxri = lpfc_sli4_next_xritag(phba);
3994 		if (lxri == NO_XRI) {
3995 			lpfc_printf_log(phba, KERN_ERR,
3996 					LOG_TRACE_EVENT,
3997 					"2400 Failed to allocate xri for "
3998 					"ELS sgl\n");
3999 			rc = -ENOMEM;
4000 			goto out_free_mem;
4001 		}
4002 		sglq_entry->sli4_lxritag = lxri;
4003 		sglq_entry->sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4004 	}
4005 	return 0;
4006 
4007 out_free_mem:
4008 	lpfc_free_els_sgl_list(phba);
4009 	return rc;
4010 }
4011 
4012 /**
4013  * lpfc_sli4_nvmet_sgl_update - update xri-sgl sizing and mapping
4014  * @phba: pointer to lpfc hba data structure.
4015  *
4016  * This routine first calculates the sizes of the current els and allocated
4017  * scsi sgl lists, and then goes through all sgls to updates the physical
4018  * XRIs assigned due to port function reset. During port initialization, the
4019  * current els and allocated scsi sgl lists are 0s.
4020  *
4021  * Return codes
4022  *   0 - successful (for now, it always returns 0)
4023  **/
4024 int
4025 lpfc_sli4_nvmet_sgl_update(struct lpfc_hba *phba)
4026 {
4027 	struct lpfc_sglq *sglq_entry = NULL, *sglq_entry_next = NULL;
4028 	uint16_t i, lxri, xri_cnt, els_xri_cnt;
4029 	uint16_t nvmet_xri_cnt;
4030 	LIST_HEAD(nvmet_sgl_list);
4031 	int rc;
4032 
4033 	/*
4034 	 * update on pci function's nvmet xri-sgl list
4035 	 */
4036 	els_xri_cnt = lpfc_sli4_get_els_iocb_cnt(phba);
4037 
4038 	/* For NVMET, ALL remaining XRIs are dedicated for IO processing */
4039 	nvmet_xri_cnt = phba->sli4_hba.max_cfg_param.max_xri - els_xri_cnt;
4040 	if (nvmet_xri_cnt > phba->sli4_hba.nvmet_xri_cnt) {
4041 		/* els xri-sgl expanded */
4042 		xri_cnt = nvmet_xri_cnt - phba->sli4_hba.nvmet_xri_cnt;
4043 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4044 				"6302 NVMET xri-sgl cnt grew from %d to %d\n",
4045 				phba->sli4_hba.nvmet_xri_cnt, nvmet_xri_cnt);
4046 		/* allocate the additional nvmet sgls */
4047 		for (i = 0; i < xri_cnt; i++) {
4048 			sglq_entry = kzalloc(sizeof(struct lpfc_sglq),
4049 					     GFP_KERNEL);
4050 			if (sglq_entry == NULL) {
4051 				lpfc_printf_log(phba, KERN_ERR,
4052 						LOG_TRACE_EVENT,
4053 						"6303 Failure to allocate an "
4054 						"NVMET sgl entry:%d\n", i);
4055 				rc = -ENOMEM;
4056 				goto out_free_mem;
4057 			}
4058 			sglq_entry->buff_type = NVMET_BUFF_TYPE;
4059 			sglq_entry->virt = lpfc_nvmet_buf_alloc(phba, 0,
4060 							   &sglq_entry->phys);
4061 			if (sglq_entry->virt == NULL) {
4062 				kfree(sglq_entry);
4063 				lpfc_printf_log(phba, KERN_ERR,
4064 						LOG_TRACE_EVENT,
4065 						"6304 Failure to allocate an "
4066 						"NVMET buf:%d\n", i);
4067 				rc = -ENOMEM;
4068 				goto out_free_mem;
4069 			}
4070 			sglq_entry->sgl = sglq_entry->virt;
4071 			memset(sglq_entry->sgl, 0,
4072 			       phba->cfg_sg_dma_buf_size);
4073 			sglq_entry->state = SGL_FREED;
4074 			list_add_tail(&sglq_entry->list, &nvmet_sgl_list);
4075 		}
4076 		spin_lock_irq(&phba->hbalock);
4077 		spin_lock(&phba->sli4_hba.sgl_list_lock);
4078 		list_splice_init(&nvmet_sgl_list,
4079 				 &phba->sli4_hba.lpfc_nvmet_sgl_list);
4080 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
4081 		spin_unlock_irq(&phba->hbalock);
4082 	} else if (nvmet_xri_cnt < phba->sli4_hba.nvmet_xri_cnt) {
4083 		/* nvmet xri-sgl shrunk */
4084 		xri_cnt = phba->sli4_hba.nvmet_xri_cnt - nvmet_xri_cnt;
4085 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4086 				"6305 NVMET xri-sgl count decreased from "
4087 				"%d to %d\n", phba->sli4_hba.nvmet_xri_cnt,
4088 				nvmet_xri_cnt);
4089 		spin_lock_irq(&phba->hbalock);
4090 		spin_lock(&phba->sli4_hba.sgl_list_lock);
4091 		list_splice_init(&phba->sli4_hba.lpfc_nvmet_sgl_list,
4092 				 &nvmet_sgl_list);
4093 		/* release extra nvmet sgls from list */
4094 		for (i = 0; i < xri_cnt; i++) {
4095 			list_remove_head(&nvmet_sgl_list,
4096 					 sglq_entry, struct lpfc_sglq, list);
4097 			if (sglq_entry) {
4098 				lpfc_nvmet_buf_free(phba, sglq_entry->virt,
4099 						    sglq_entry->phys);
4100 				kfree(sglq_entry);
4101 			}
4102 		}
4103 		list_splice_init(&nvmet_sgl_list,
4104 				 &phba->sli4_hba.lpfc_nvmet_sgl_list);
4105 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
4106 		spin_unlock_irq(&phba->hbalock);
4107 	} else
4108 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4109 				"6306 NVMET xri-sgl count unchanged: %d\n",
4110 				nvmet_xri_cnt);
4111 	phba->sli4_hba.nvmet_xri_cnt = nvmet_xri_cnt;
4112 
4113 	/* update xris to nvmet sgls on the list */
4114 	sglq_entry = NULL;
4115 	sglq_entry_next = NULL;
4116 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
4117 				 &phba->sli4_hba.lpfc_nvmet_sgl_list, list) {
4118 		lxri = lpfc_sli4_next_xritag(phba);
4119 		if (lxri == NO_XRI) {
4120 			lpfc_printf_log(phba, KERN_ERR,
4121 					LOG_TRACE_EVENT,
4122 					"6307 Failed to allocate xri for "
4123 					"NVMET sgl\n");
4124 			rc = -ENOMEM;
4125 			goto out_free_mem;
4126 		}
4127 		sglq_entry->sli4_lxritag = lxri;
4128 		sglq_entry->sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4129 	}
4130 	return 0;
4131 
4132 out_free_mem:
4133 	lpfc_free_nvmet_sgl_list(phba);
4134 	return rc;
4135 }
4136 
4137 int
4138 lpfc_io_buf_flush(struct lpfc_hba *phba, struct list_head *cbuf)
4139 {
4140 	LIST_HEAD(blist);
4141 	struct lpfc_sli4_hdw_queue *qp;
4142 	struct lpfc_io_buf *lpfc_cmd;
4143 	struct lpfc_io_buf *iobufp, *prev_iobufp;
4144 	int idx, cnt, xri, inserted;
4145 
4146 	cnt = 0;
4147 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
4148 		qp = &phba->sli4_hba.hdwq[idx];
4149 		spin_lock_irq(&qp->io_buf_list_get_lock);
4150 		spin_lock(&qp->io_buf_list_put_lock);
4151 
4152 		/* Take everything off the get and put lists */
4153 		list_splice_init(&qp->lpfc_io_buf_list_get, &blist);
4154 		list_splice(&qp->lpfc_io_buf_list_put, &blist);
4155 		INIT_LIST_HEAD(&qp->lpfc_io_buf_list_get);
4156 		INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
4157 		cnt += qp->get_io_bufs + qp->put_io_bufs;
4158 		qp->get_io_bufs = 0;
4159 		qp->put_io_bufs = 0;
4160 		qp->total_io_bufs = 0;
4161 		spin_unlock(&qp->io_buf_list_put_lock);
4162 		spin_unlock_irq(&qp->io_buf_list_get_lock);
4163 	}
4164 
4165 	/*
4166 	 * Take IO buffers off blist and put on cbuf sorted by XRI.
4167 	 * This is because POST_SGL takes a sequential range of XRIs
4168 	 * to post to the firmware.
4169 	 */
4170 	for (idx = 0; idx < cnt; idx++) {
4171 		list_remove_head(&blist, lpfc_cmd, struct lpfc_io_buf, list);
4172 		if (!lpfc_cmd)
4173 			return cnt;
4174 		if (idx == 0) {
4175 			list_add_tail(&lpfc_cmd->list, cbuf);
4176 			continue;
4177 		}
4178 		xri = lpfc_cmd->cur_iocbq.sli4_xritag;
4179 		inserted = 0;
4180 		prev_iobufp = NULL;
4181 		list_for_each_entry(iobufp, cbuf, list) {
4182 			if (xri < iobufp->cur_iocbq.sli4_xritag) {
4183 				if (prev_iobufp)
4184 					list_add(&lpfc_cmd->list,
4185 						 &prev_iobufp->list);
4186 				else
4187 					list_add(&lpfc_cmd->list, cbuf);
4188 				inserted = 1;
4189 				break;
4190 			}
4191 			prev_iobufp = iobufp;
4192 		}
4193 		if (!inserted)
4194 			list_add_tail(&lpfc_cmd->list, cbuf);
4195 	}
4196 	return cnt;
4197 }
4198 
4199 int
4200 lpfc_io_buf_replenish(struct lpfc_hba *phba, struct list_head *cbuf)
4201 {
4202 	struct lpfc_sli4_hdw_queue *qp;
4203 	struct lpfc_io_buf *lpfc_cmd;
4204 	int idx, cnt;
4205 
4206 	qp = phba->sli4_hba.hdwq;
4207 	cnt = 0;
4208 	while (!list_empty(cbuf)) {
4209 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
4210 			list_remove_head(cbuf, lpfc_cmd,
4211 					 struct lpfc_io_buf, list);
4212 			if (!lpfc_cmd)
4213 				return cnt;
4214 			cnt++;
4215 			qp = &phba->sli4_hba.hdwq[idx];
4216 			lpfc_cmd->hdwq_no = idx;
4217 			lpfc_cmd->hdwq = qp;
4218 			lpfc_cmd->cur_iocbq.wqe_cmpl = NULL;
4219 			lpfc_cmd->cur_iocbq.iocb_cmpl = NULL;
4220 			spin_lock(&qp->io_buf_list_put_lock);
4221 			list_add_tail(&lpfc_cmd->list,
4222 				      &qp->lpfc_io_buf_list_put);
4223 			qp->put_io_bufs++;
4224 			qp->total_io_bufs++;
4225 			spin_unlock(&qp->io_buf_list_put_lock);
4226 		}
4227 	}
4228 	return cnt;
4229 }
4230 
4231 /**
4232  * lpfc_sli4_io_sgl_update - update xri-sgl sizing and mapping
4233  * @phba: pointer to lpfc hba data structure.
4234  *
4235  * This routine first calculates the sizes of the current els and allocated
4236  * scsi sgl lists, and then goes through all sgls to updates the physical
4237  * XRIs assigned due to port function reset. During port initialization, the
4238  * current els and allocated scsi sgl lists are 0s.
4239  *
4240  * Return codes
4241  *   0 - successful (for now, it always returns 0)
4242  **/
4243 int
4244 lpfc_sli4_io_sgl_update(struct lpfc_hba *phba)
4245 {
4246 	struct lpfc_io_buf *lpfc_ncmd = NULL, *lpfc_ncmd_next = NULL;
4247 	uint16_t i, lxri, els_xri_cnt;
4248 	uint16_t io_xri_cnt, io_xri_max;
4249 	LIST_HEAD(io_sgl_list);
4250 	int rc, cnt;
4251 
4252 	/*
4253 	 * update on pci function's allocated nvme xri-sgl list
4254 	 */
4255 
4256 	/* maximum number of xris available for nvme buffers */
4257 	els_xri_cnt = lpfc_sli4_get_els_iocb_cnt(phba);
4258 	io_xri_max = phba->sli4_hba.max_cfg_param.max_xri - els_xri_cnt;
4259 	phba->sli4_hba.io_xri_max = io_xri_max;
4260 
4261 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4262 			"6074 Current allocated XRI sgl count:%d, "
4263 			"maximum XRI count:%d\n",
4264 			phba->sli4_hba.io_xri_cnt,
4265 			phba->sli4_hba.io_xri_max);
4266 
4267 	cnt = lpfc_io_buf_flush(phba, &io_sgl_list);
4268 
4269 	if (phba->sli4_hba.io_xri_cnt > phba->sli4_hba.io_xri_max) {
4270 		/* max nvme xri shrunk below the allocated nvme buffers */
4271 		io_xri_cnt = phba->sli4_hba.io_xri_cnt -
4272 					phba->sli4_hba.io_xri_max;
4273 		/* release the extra allocated nvme buffers */
4274 		for (i = 0; i < io_xri_cnt; i++) {
4275 			list_remove_head(&io_sgl_list, lpfc_ncmd,
4276 					 struct lpfc_io_buf, list);
4277 			if (lpfc_ncmd) {
4278 				dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4279 					      lpfc_ncmd->data,
4280 					      lpfc_ncmd->dma_handle);
4281 				kfree(lpfc_ncmd);
4282 			}
4283 		}
4284 		phba->sli4_hba.io_xri_cnt -= io_xri_cnt;
4285 	}
4286 
4287 	/* update xris associated to remaining allocated nvme buffers */
4288 	lpfc_ncmd = NULL;
4289 	lpfc_ncmd_next = NULL;
4290 	phba->sli4_hba.io_xri_cnt = cnt;
4291 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
4292 				 &io_sgl_list, list) {
4293 		lxri = lpfc_sli4_next_xritag(phba);
4294 		if (lxri == NO_XRI) {
4295 			lpfc_printf_log(phba, KERN_ERR,
4296 					LOG_TRACE_EVENT,
4297 					"6075 Failed to allocate xri for "
4298 					"nvme buffer\n");
4299 			rc = -ENOMEM;
4300 			goto out_free_mem;
4301 		}
4302 		lpfc_ncmd->cur_iocbq.sli4_lxritag = lxri;
4303 		lpfc_ncmd->cur_iocbq.sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4304 	}
4305 	cnt = lpfc_io_buf_replenish(phba, &io_sgl_list);
4306 	return 0;
4307 
4308 out_free_mem:
4309 	lpfc_io_free(phba);
4310 	return rc;
4311 }
4312 
4313 /**
4314  * lpfc_new_io_buf - IO buffer allocator for HBA with SLI4 IF spec
4315  * @phba: Pointer to lpfc hba data structure.
4316  * @num_to_alloc: The requested number of buffers to allocate.
4317  *
4318  * This routine allocates nvme buffers for device with SLI-4 interface spec,
4319  * the nvme buffer contains all the necessary information needed to initiate
4320  * an I/O. After allocating up to @num_to_allocate IO buffers and put
4321  * them on a list, it post them to the port by using SGL block post.
4322  *
4323  * Return codes:
4324  *   int - number of IO buffers that were allocated and posted.
4325  *   0 = failure, less than num_to_alloc is a partial failure.
4326  **/
4327 int
4328 lpfc_new_io_buf(struct lpfc_hba *phba, int num_to_alloc)
4329 {
4330 	struct lpfc_io_buf *lpfc_ncmd;
4331 	struct lpfc_iocbq *pwqeq;
4332 	uint16_t iotag, lxri = 0;
4333 	int bcnt, num_posted;
4334 	LIST_HEAD(prep_nblist);
4335 	LIST_HEAD(post_nblist);
4336 	LIST_HEAD(nvme_nblist);
4337 
4338 	phba->sli4_hba.io_xri_cnt = 0;
4339 	for (bcnt = 0; bcnt < num_to_alloc; bcnt++) {
4340 		lpfc_ncmd = kzalloc(sizeof(*lpfc_ncmd), GFP_KERNEL);
4341 		if (!lpfc_ncmd)
4342 			break;
4343 		/*
4344 		 * Get memory from the pci pool to map the virt space to
4345 		 * pci bus space for an I/O. The DMA buffer includes the
4346 		 * number of SGE's necessary to support the sg_tablesize.
4347 		 */
4348 		lpfc_ncmd->data = dma_pool_zalloc(phba->lpfc_sg_dma_buf_pool,
4349 						  GFP_KERNEL,
4350 						  &lpfc_ncmd->dma_handle);
4351 		if (!lpfc_ncmd->data) {
4352 			kfree(lpfc_ncmd);
4353 			break;
4354 		}
4355 
4356 		if (phba->cfg_xpsgl && !phba->nvmet_support) {
4357 			INIT_LIST_HEAD(&lpfc_ncmd->dma_sgl_xtra_list);
4358 		} else {
4359 			/*
4360 			 * 4K Page alignment is CRITICAL to BlockGuard, double
4361 			 * check to be sure.
4362 			 */
4363 			if ((phba->sli3_options & LPFC_SLI3_BG_ENABLED) &&
4364 			    (((unsigned long)(lpfc_ncmd->data) &
4365 			    (unsigned long)(SLI4_PAGE_SIZE - 1)) != 0)) {
4366 				lpfc_printf_log(phba, KERN_ERR,
4367 						LOG_TRACE_EVENT,
4368 						"3369 Memory alignment err: "
4369 						"addr=%lx\n",
4370 						(unsigned long)lpfc_ncmd->data);
4371 				dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4372 					      lpfc_ncmd->data,
4373 					      lpfc_ncmd->dma_handle);
4374 				kfree(lpfc_ncmd);
4375 				break;
4376 			}
4377 		}
4378 
4379 		INIT_LIST_HEAD(&lpfc_ncmd->dma_cmd_rsp_list);
4380 
4381 		lxri = lpfc_sli4_next_xritag(phba);
4382 		if (lxri == NO_XRI) {
4383 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4384 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4385 			kfree(lpfc_ncmd);
4386 			break;
4387 		}
4388 		pwqeq = &lpfc_ncmd->cur_iocbq;
4389 
4390 		/* Allocate iotag for lpfc_ncmd->cur_iocbq. */
4391 		iotag = lpfc_sli_next_iotag(phba, pwqeq);
4392 		if (iotag == 0) {
4393 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4394 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4395 			kfree(lpfc_ncmd);
4396 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4397 					"6121 Failed to allocate IOTAG for"
4398 					" XRI:0x%x\n", lxri);
4399 			lpfc_sli4_free_xri(phba, lxri);
4400 			break;
4401 		}
4402 		pwqeq->sli4_lxritag = lxri;
4403 		pwqeq->sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4404 		pwqeq->context1 = lpfc_ncmd;
4405 
4406 		/* Initialize local short-hand pointers. */
4407 		lpfc_ncmd->dma_sgl = lpfc_ncmd->data;
4408 		lpfc_ncmd->dma_phys_sgl = lpfc_ncmd->dma_handle;
4409 		lpfc_ncmd->cur_iocbq.context1 = lpfc_ncmd;
4410 		spin_lock_init(&lpfc_ncmd->buf_lock);
4411 
4412 		/* add the nvme buffer to a post list */
4413 		list_add_tail(&lpfc_ncmd->list, &post_nblist);
4414 		phba->sli4_hba.io_xri_cnt++;
4415 	}
4416 	lpfc_printf_log(phba, KERN_INFO, LOG_NVME,
4417 			"6114 Allocate %d out of %d requested new NVME "
4418 			"buffers\n", bcnt, num_to_alloc);
4419 
4420 	/* post the list of nvme buffer sgls to port if available */
4421 	if (!list_empty(&post_nblist))
4422 		num_posted = lpfc_sli4_post_io_sgl_list(
4423 				phba, &post_nblist, bcnt);
4424 	else
4425 		num_posted = 0;
4426 
4427 	return num_posted;
4428 }
4429 
4430 static uint64_t
4431 lpfc_get_wwpn(struct lpfc_hba *phba)
4432 {
4433 	uint64_t wwn;
4434 	int rc;
4435 	LPFC_MBOXQ_t *mboxq;
4436 	MAILBOX_t *mb;
4437 
4438 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
4439 						GFP_KERNEL);
4440 	if (!mboxq)
4441 		return (uint64_t)-1;
4442 
4443 	/* First get WWN of HBA instance */
4444 	lpfc_read_nv(phba, mboxq);
4445 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
4446 	if (rc != MBX_SUCCESS) {
4447 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4448 				"6019 Mailbox failed , mbxCmd x%x "
4449 				"READ_NV, mbxStatus x%x\n",
4450 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
4451 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
4452 		mempool_free(mboxq, phba->mbox_mem_pool);
4453 		return (uint64_t) -1;
4454 	}
4455 	mb = &mboxq->u.mb;
4456 	memcpy(&wwn, (char *)mb->un.varRDnvp.portname, sizeof(uint64_t));
4457 	/* wwn is WWPN of HBA instance */
4458 	mempool_free(mboxq, phba->mbox_mem_pool);
4459 	if (phba->sli_rev == LPFC_SLI_REV4)
4460 		return be64_to_cpu(wwn);
4461 	else
4462 		return rol64(wwn, 32);
4463 }
4464 
4465 /**
4466  * lpfc_vmid_res_alloc - Allocates resources for VMID
4467  * @phba: pointer to lpfc hba data structure.
4468  * @vport: pointer to vport data structure
4469  *
4470  * This routine allocated the resources needed for the VMID.
4471  *
4472  * Return codes
4473  *	0 on Success
4474  *	Non-0 on Failure
4475  */
4476 static int
4477 lpfc_vmid_res_alloc(struct lpfc_hba *phba, struct lpfc_vport *vport)
4478 {
4479 	/* VMID feature is supported only on SLI4 */
4480 	if (phba->sli_rev == LPFC_SLI_REV3) {
4481 		phba->cfg_vmid_app_header = 0;
4482 		phba->cfg_vmid_priority_tagging = 0;
4483 	}
4484 
4485 	if (lpfc_is_vmid_enabled(phba)) {
4486 		vport->vmid =
4487 		    kcalloc(phba->cfg_max_vmid, sizeof(struct lpfc_vmid),
4488 			    GFP_KERNEL);
4489 		if (!vport->vmid)
4490 			return -ENOMEM;
4491 
4492 		rwlock_init(&vport->vmid_lock);
4493 
4494 		/* Set the VMID parameters for the vport */
4495 		vport->vmid_priority_tagging = phba->cfg_vmid_priority_tagging;
4496 		vport->vmid_inactivity_timeout =
4497 		    phba->cfg_vmid_inactivity_timeout;
4498 		vport->max_vmid = phba->cfg_max_vmid;
4499 		vport->cur_vmid_cnt = 0;
4500 
4501 		vport->vmid_priority_range = bitmap_zalloc
4502 			(LPFC_VMID_MAX_PRIORITY_RANGE, GFP_KERNEL);
4503 
4504 		if (!vport->vmid_priority_range) {
4505 			kfree(vport->vmid);
4506 			return -ENOMEM;
4507 		}
4508 
4509 		hash_init(vport->hash_table);
4510 	}
4511 	return 0;
4512 }
4513 
4514 /**
4515  * lpfc_create_port - Create an FC port
4516  * @phba: pointer to lpfc hba data structure.
4517  * @instance: a unique integer ID to this FC port.
4518  * @dev: pointer to the device data structure.
4519  *
4520  * This routine creates a FC port for the upper layer protocol. The FC port
4521  * can be created on top of either a physical port or a virtual port provided
4522  * by the HBA. This routine also allocates a SCSI host data structure (shost)
4523  * and associates the FC port created before adding the shost into the SCSI
4524  * layer.
4525  *
4526  * Return codes
4527  *   @vport - pointer to the virtual N_Port data structure.
4528  *   NULL - port create failed.
4529  **/
4530 struct lpfc_vport *
4531 lpfc_create_port(struct lpfc_hba *phba, int instance, struct device *dev)
4532 {
4533 	struct lpfc_vport *vport;
4534 	struct Scsi_Host  *shost = NULL;
4535 	struct scsi_host_template *template;
4536 	int error = 0;
4537 	int i;
4538 	uint64_t wwn;
4539 	bool use_no_reset_hba = false;
4540 	int rc;
4541 
4542 	if (lpfc_no_hba_reset_cnt) {
4543 		if (phba->sli_rev < LPFC_SLI_REV4 &&
4544 		    dev == &phba->pcidev->dev) {
4545 			/* Reset the port first */
4546 			lpfc_sli_brdrestart(phba);
4547 			rc = lpfc_sli_chipset_init(phba);
4548 			if (rc)
4549 				return NULL;
4550 		}
4551 		wwn = lpfc_get_wwpn(phba);
4552 	}
4553 
4554 	for (i = 0; i < lpfc_no_hba_reset_cnt; i++) {
4555 		if (wwn == lpfc_no_hba_reset[i]) {
4556 			lpfc_printf_log(phba, KERN_ERR,
4557 					LOG_TRACE_EVENT,
4558 					"6020 Setting use_no_reset port=%llx\n",
4559 					wwn);
4560 			use_no_reset_hba = true;
4561 			break;
4562 		}
4563 	}
4564 
4565 	/* Seed template for SCSI host registration */
4566 	if (dev == &phba->pcidev->dev) {
4567 		template = &phba->port_template;
4568 
4569 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP) {
4570 			/* Seed physical port template */
4571 			memcpy(template, &lpfc_template, sizeof(*template));
4572 
4573 			if (use_no_reset_hba)
4574 				/* template is for a no reset SCSI Host */
4575 				template->eh_host_reset_handler = NULL;
4576 
4577 			/* Template for all vports this physical port creates */
4578 			memcpy(&phba->vport_template, &lpfc_template,
4579 			       sizeof(*template));
4580 			phba->vport_template.shost_attrs = lpfc_vport_attrs;
4581 			phba->vport_template.eh_bus_reset_handler = NULL;
4582 			phba->vport_template.eh_host_reset_handler = NULL;
4583 			phba->vport_template.vendor_id = 0;
4584 
4585 			/* Initialize the host templates with updated value */
4586 			if (phba->sli_rev == LPFC_SLI_REV4) {
4587 				template->sg_tablesize = phba->cfg_scsi_seg_cnt;
4588 				phba->vport_template.sg_tablesize =
4589 					phba->cfg_scsi_seg_cnt;
4590 			} else {
4591 				template->sg_tablesize = phba->cfg_sg_seg_cnt;
4592 				phba->vport_template.sg_tablesize =
4593 					phba->cfg_sg_seg_cnt;
4594 			}
4595 
4596 		} else {
4597 			/* NVMET is for physical port only */
4598 			memcpy(template, &lpfc_template_nvme,
4599 			       sizeof(*template));
4600 		}
4601 	} else {
4602 		template = &phba->vport_template;
4603 	}
4604 
4605 	shost = scsi_host_alloc(template, sizeof(struct lpfc_vport));
4606 	if (!shost)
4607 		goto out;
4608 
4609 	vport = (struct lpfc_vport *) shost->hostdata;
4610 	vport->phba = phba;
4611 	vport->load_flag |= FC_LOADING;
4612 	vport->fc_flag |= FC_VPORT_NEEDS_REG_VPI;
4613 	vport->fc_rscn_flush = 0;
4614 	lpfc_get_vport_cfgparam(vport);
4615 
4616 	/* Adjust value in vport */
4617 	vport->cfg_enable_fc4_type = phba->cfg_enable_fc4_type;
4618 
4619 	shost->unique_id = instance;
4620 	shost->max_id = LPFC_MAX_TARGET;
4621 	shost->max_lun = vport->cfg_max_luns;
4622 	shost->this_id = -1;
4623 	shost->max_cmd_len = 16;
4624 
4625 	if (phba->sli_rev == LPFC_SLI_REV4) {
4626 		if (!phba->cfg_fcp_mq_threshold ||
4627 		    phba->cfg_fcp_mq_threshold > phba->cfg_hdw_queue)
4628 			phba->cfg_fcp_mq_threshold = phba->cfg_hdw_queue;
4629 
4630 		shost->nr_hw_queues = min_t(int, 2 * num_possible_nodes(),
4631 					    phba->cfg_fcp_mq_threshold);
4632 
4633 		shost->dma_boundary =
4634 			phba->sli4_hba.pc_sli4_params.sge_supp_len-1;
4635 
4636 		if (phba->cfg_xpsgl && !phba->nvmet_support)
4637 			shost->sg_tablesize = LPFC_MAX_SG_TABLESIZE;
4638 		else
4639 			shost->sg_tablesize = phba->cfg_scsi_seg_cnt;
4640 	} else
4641 		/* SLI-3 has a limited number of hardware queues (3),
4642 		 * thus there is only one for FCP processing.
4643 		 */
4644 		shost->nr_hw_queues = 1;
4645 
4646 	/*
4647 	 * Set initial can_queue value since 0 is no longer supported and
4648 	 * scsi_add_host will fail. This will be adjusted later based on the
4649 	 * max xri value determined in hba setup.
4650 	 */
4651 	shost->can_queue = phba->cfg_hba_queue_depth - 10;
4652 	if (dev != &phba->pcidev->dev) {
4653 		shost->transportt = lpfc_vport_transport_template;
4654 		vport->port_type = LPFC_NPIV_PORT;
4655 	} else {
4656 		shost->transportt = lpfc_transport_template;
4657 		vport->port_type = LPFC_PHYSICAL_PORT;
4658 	}
4659 
4660 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP,
4661 			"9081 CreatePort TMPLATE type %x TBLsize %d "
4662 			"SEGcnt %d/%d\n",
4663 			vport->port_type, shost->sg_tablesize,
4664 			phba->cfg_scsi_seg_cnt, phba->cfg_sg_seg_cnt);
4665 
4666 	/* Allocate the resources for VMID */
4667 	rc = lpfc_vmid_res_alloc(phba, vport);
4668 
4669 	if (rc)
4670 		goto out_put_shost;
4671 
4672 	/* Initialize all internally managed lists. */
4673 	INIT_LIST_HEAD(&vport->fc_nodes);
4674 	INIT_LIST_HEAD(&vport->rcv_buffer_list);
4675 	spin_lock_init(&vport->work_port_lock);
4676 
4677 	timer_setup(&vport->fc_disctmo, lpfc_disc_timeout, 0);
4678 
4679 	timer_setup(&vport->els_tmofunc, lpfc_els_timeout, 0);
4680 
4681 	timer_setup(&vport->delayed_disc_tmo, lpfc_delayed_disc_tmo, 0);
4682 
4683 	if (phba->sli3_options & LPFC_SLI3_BG_ENABLED)
4684 		lpfc_setup_bg(phba, shost);
4685 
4686 	error = scsi_add_host_with_dma(shost, dev, &phba->pcidev->dev);
4687 	if (error)
4688 		goto out_free_vmid;
4689 
4690 	spin_lock_irq(&phba->port_list_lock);
4691 	list_add_tail(&vport->listentry, &phba->port_list);
4692 	spin_unlock_irq(&phba->port_list_lock);
4693 	return vport;
4694 
4695 out_free_vmid:
4696 	kfree(vport->vmid);
4697 	bitmap_free(vport->vmid_priority_range);
4698 out_put_shost:
4699 	scsi_host_put(shost);
4700 out:
4701 	return NULL;
4702 }
4703 
4704 /**
4705  * destroy_port -  destroy an FC port
4706  * @vport: pointer to an lpfc virtual N_Port data structure.
4707  *
4708  * This routine destroys a FC port from the upper layer protocol. All the
4709  * resources associated with the port are released.
4710  **/
4711 void
4712 destroy_port(struct lpfc_vport *vport)
4713 {
4714 	struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
4715 	struct lpfc_hba  *phba = vport->phba;
4716 
4717 	lpfc_debugfs_terminate(vport);
4718 	fc_remove_host(shost);
4719 	scsi_remove_host(shost);
4720 
4721 	spin_lock_irq(&phba->port_list_lock);
4722 	list_del_init(&vport->listentry);
4723 	spin_unlock_irq(&phba->port_list_lock);
4724 
4725 	lpfc_cleanup(vport);
4726 	return;
4727 }
4728 
4729 /**
4730  * lpfc_get_instance - Get a unique integer ID
4731  *
4732  * This routine allocates a unique integer ID from lpfc_hba_index pool. It
4733  * uses the kernel idr facility to perform the task.
4734  *
4735  * Return codes:
4736  *   instance - a unique integer ID allocated as the new instance.
4737  *   -1 - lpfc get instance failed.
4738  **/
4739 int
4740 lpfc_get_instance(void)
4741 {
4742 	int ret;
4743 
4744 	ret = idr_alloc(&lpfc_hba_index, NULL, 0, 0, GFP_KERNEL);
4745 	return ret < 0 ? -1 : ret;
4746 }
4747 
4748 /**
4749  * lpfc_scan_finished - method for SCSI layer to detect whether scan is done
4750  * @shost: pointer to SCSI host data structure.
4751  * @time: elapsed time of the scan in jiffies.
4752  *
4753  * This routine is called by the SCSI layer with a SCSI host to determine
4754  * whether the scan host is finished.
4755  *
4756  * Note: there is no scan_start function as adapter initialization will have
4757  * asynchronously kicked off the link initialization.
4758  *
4759  * Return codes
4760  *   0 - SCSI host scan is not over yet.
4761  *   1 - SCSI host scan is over.
4762  **/
4763 int lpfc_scan_finished(struct Scsi_Host *shost, unsigned long time)
4764 {
4765 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
4766 	struct lpfc_hba   *phba = vport->phba;
4767 	int stat = 0;
4768 
4769 	spin_lock_irq(shost->host_lock);
4770 
4771 	if (vport->load_flag & FC_UNLOADING) {
4772 		stat = 1;
4773 		goto finished;
4774 	}
4775 	if (time >= msecs_to_jiffies(30 * 1000)) {
4776 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4777 				"0461 Scanning longer than 30 "
4778 				"seconds.  Continuing initialization\n");
4779 		stat = 1;
4780 		goto finished;
4781 	}
4782 	if (time >= msecs_to_jiffies(15 * 1000) &&
4783 	    phba->link_state <= LPFC_LINK_DOWN) {
4784 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4785 				"0465 Link down longer than 15 "
4786 				"seconds.  Continuing initialization\n");
4787 		stat = 1;
4788 		goto finished;
4789 	}
4790 
4791 	if (vport->port_state != LPFC_VPORT_READY)
4792 		goto finished;
4793 	if (vport->num_disc_nodes || vport->fc_prli_sent)
4794 		goto finished;
4795 	if (vport->fc_map_cnt == 0 && time < msecs_to_jiffies(2 * 1000))
4796 		goto finished;
4797 	if ((phba->sli.sli_flag & LPFC_SLI_MBOX_ACTIVE) != 0)
4798 		goto finished;
4799 
4800 	stat = 1;
4801 
4802 finished:
4803 	spin_unlock_irq(shost->host_lock);
4804 	return stat;
4805 }
4806 
4807 static void lpfc_host_supported_speeds_set(struct Scsi_Host *shost)
4808 {
4809 	struct lpfc_vport *vport = (struct lpfc_vport *)shost->hostdata;
4810 	struct lpfc_hba   *phba = vport->phba;
4811 
4812 	fc_host_supported_speeds(shost) = 0;
4813 	/*
4814 	 * Avoid reporting supported link speed for FCoE as it can't be
4815 	 * controlled via FCoE.
4816 	 */
4817 	if (phba->hba_flag & HBA_FCOE_MODE)
4818 		return;
4819 
4820 	if (phba->lmt & LMT_256Gb)
4821 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_256GBIT;
4822 	if (phba->lmt & LMT_128Gb)
4823 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_128GBIT;
4824 	if (phba->lmt & LMT_64Gb)
4825 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_64GBIT;
4826 	if (phba->lmt & LMT_32Gb)
4827 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_32GBIT;
4828 	if (phba->lmt & LMT_16Gb)
4829 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_16GBIT;
4830 	if (phba->lmt & LMT_10Gb)
4831 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_10GBIT;
4832 	if (phba->lmt & LMT_8Gb)
4833 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_8GBIT;
4834 	if (phba->lmt & LMT_4Gb)
4835 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_4GBIT;
4836 	if (phba->lmt & LMT_2Gb)
4837 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_2GBIT;
4838 	if (phba->lmt & LMT_1Gb)
4839 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_1GBIT;
4840 }
4841 
4842 /**
4843  * lpfc_host_attrib_init - Initialize SCSI host attributes on a FC port
4844  * @shost: pointer to SCSI host data structure.
4845  *
4846  * This routine initializes a given SCSI host attributes on a FC port. The
4847  * SCSI host can be either on top of a physical port or a virtual port.
4848  **/
4849 void lpfc_host_attrib_init(struct Scsi_Host *shost)
4850 {
4851 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
4852 	struct lpfc_hba   *phba = vport->phba;
4853 	/*
4854 	 * Set fixed host attributes.  Must done after lpfc_sli_hba_setup().
4855 	 */
4856 
4857 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
4858 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
4859 	fc_host_supported_classes(shost) = FC_COS_CLASS3;
4860 
4861 	memset(fc_host_supported_fc4s(shost), 0,
4862 	       sizeof(fc_host_supported_fc4s(shost)));
4863 	fc_host_supported_fc4s(shost)[2] = 1;
4864 	fc_host_supported_fc4s(shost)[7] = 1;
4865 
4866 	lpfc_vport_symbolic_node_name(vport, fc_host_symbolic_name(shost),
4867 				 sizeof fc_host_symbolic_name(shost));
4868 
4869 	lpfc_host_supported_speeds_set(shost);
4870 
4871 	fc_host_maxframe_size(shost) =
4872 		(((uint32_t) vport->fc_sparam.cmn.bbRcvSizeMsb & 0x0F) << 8) |
4873 		(uint32_t) vport->fc_sparam.cmn.bbRcvSizeLsb;
4874 
4875 	fc_host_dev_loss_tmo(shost) = vport->cfg_devloss_tmo;
4876 
4877 	/* This value is also unchanging */
4878 	memset(fc_host_active_fc4s(shost), 0,
4879 	       sizeof(fc_host_active_fc4s(shost)));
4880 	fc_host_active_fc4s(shost)[2] = 1;
4881 	fc_host_active_fc4s(shost)[7] = 1;
4882 
4883 	fc_host_max_npiv_vports(shost) = phba->max_vpi;
4884 	spin_lock_irq(shost->host_lock);
4885 	vport->load_flag &= ~FC_LOADING;
4886 	spin_unlock_irq(shost->host_lock);
4887 }
4888 
4889 /**
4890  * lpfc_stop_port_s3 - Stop SLI3 device port
4891  * @phba: pointer to lpfc hba data structure.
4892  *
4893  * This routine is invoked to stop an SLI3 device port, it stops the device
4894  * from generating interrupts and stops the device driver's timers for the
4895  * device.
4896  **/
4897 static void
4898 lpfc_stop_port_s3(struct lpfc_hba *phba)
4899 {
4900 	/* Clear all interrupt enable conditions */
4901 	writel(0, phba->HCregaddr);
4902 	readl(phba->HCregaddr); /* flush */
4903 	/* Clear all pending interrupts */
4904 	writel(0xffffffff, phba->HAregaddr);
4905 	readl(phba->HAregaddr); /* flush */
4906 
4907 	/* Reset some HBA SLI setup states */
4908 	lpfc_stop_hba_timers(phba);
4909 	phba->pport->work_port_events = 0;
4910 }
4911 
4912 /**
4913  * lpfc_stop_port_s4 - Stop SLI4 device port
4914  * @phba: pointer to lpfc hba data structure.
4915  *
4916  * This routine is invoked to stop an SLI4 device port, it stops the device
4917  * from generating interrupts and stops the device driver's timers for the
4918  * device.
4919  **/
4920 static void
4921 lpfc_stop_port_s4(struct lpfc_hba *phba)
4922 {
4923 	/* Reset some HBA SLI4 setup states */
4924 	lpfc_stop_hba_timers(phba);
4925 	if (phba->pport)
4926 		phba->pport->work_port_events = 0;
4927 	phba->sli4_hba.intr_enable = 0;
4928 }
4929 
4930 /**
4931  * lpfc_stop_port - Wrapper function for stopping hba port
4932  * @phba: Pointer to HBA context object.
4933  *
4934  * This routine wraps the actual SLI3 or SLI4 hba stop port routine from
4935  * the API jump table function pointer from the lpfc_hba struct.
4936  **/
4937 void
4938 lpfc_stop_port(struct lpfc_hba *phba)
4939 {
4940 	phba->lpfc_stop_port(phba);
4941 
4942 	if (phba->wq)
4943 		flush_workqueue(phba->wq);
4944 }
4945 
4946 /**
4947  * lpfc_fcf_redisc_wait_start_timer - Start fcf rediscover wait timer
4948  * @phba: Pointer to hba for which this call is being executed.
4949  *
4950  * This routine starts the timer waiting for the FCF rediscovery to complete.
4951  **/
4952 void
4953 lpfc_fcf_redisc_wait_start_timer(struct lpfc_hba *phba)
4954 {
4955 	unsigned long fcf_redisc_wait_tmo =
4956 		(jiffies + msecs_to_jiffies(LPFC_FCF_REDISCOVER_WAIT_TMO));
4957 	/* Start fcf rediscovery wait period timer */
4958 	mod_timer(&phba->fcf.redisc_wait, fcf_redisc_wait_tmo);
4959 	spin_lock_irq(&phba->hbalock);
4960 	/* Allow action to new fcf asynchronous event */
4961 	phba->fcf.fcf_flag &= ~(FCF_AVAILABLE | FCF_SCAN_DONE);
4962 	/* Mark the FCF rediscovery pending state */
4963 	phba->fcf.fcf_flag |= FCF_REDISC_PEND;
4964 	spin_unlock_irq(&phba->hbalock);
4965 }
4966 
4967 /**
4968  * lpfc_sli4_fcf_redisc_wait_tmo - FCF table rediscover wait timeout
4969  * @t: Timer context used to obtain the pointer to lpfc hba data structure.
4970  *
4971  * This routine is invoked when waiting for FCF table rediscover has been
4972  * timed out. If new FCF record(s) has (have) been discovered during the
4973  * wait period, a new FCF event shall be added to the FCOE async event
4974  * list, and then worker thread shall be waked up for processing from the
4975  * worker thread context.
4976  **/
4977 static void
4978 lpfc_sli4_fcf_redisc_wait_tmo(struct timer_list *t)
4979 {
4980 	struct lpfc_hba *phba = from_timer(phba, t, fcf.redisc_wait);
4981 
4982 	/* Don't send FCF rediscovery event if timer cancelled */
4983 	spin_lock_irq(&phba->hbalock);
4984 	if (!(phba->fcf.fcf_flag & FCF_REDISC_PEND)) {
4985 		spin_unlock_irq(&phba->hbalock);
4986 		return;
4987 	}
4988 	/* Clear FCF rediscovery timer pending flag */
4989 	phba->fcf.fcf_flag &= ~FCF_REDISC_PEND;
4990 	/* FCF rediscovery event to worker thread */
4991 	phba->fcf.fcf_flag |= FCF_REDISC_EVT;
4992 	spin_unlock_irq(&phba->hbalock);
4993 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
4994 			"2776 FCF rediscover quiescent timer expired\n");
4995 	/* wake up worker thread */
4996 	lpfc_worker_wake_up(phba);
4997 }
4998 
4999 /**
5000  * lpfc_vmid_poll - VMID timeout detection
5001  * @t: Timer context used to obtain the pointer to lpfc hba data structure.
5002  *
5003  * This routine is invoked when there is no I/O on by a VM for the specified
5004  * amount of time. When this situation is detected, the VMID has to be
5005  * deregistered from the switch and all the local resources freed. The VMID
5006  * will be reassigned to the VM once the I/O begins.
5007  **/
5008 static void
5009 lpfc_vmid_poll(struct timer_list *t)
5010 {
5011 	struct lpfc_hba *phba = from_timer(phba, t, inactive_vmid_poll);
5012 	u32 wake_up = 0;
5013 
5014 	/* check if there is a need to issue QFPA */
5015 	if (phba->pport->vmid_priority_tagging) {
5016 		wake_up = 1;
5017 		phba->pport->work_port_events |= WORKER_CHECK_VMID_ISSUE_QFPA;
5018 	}
5019 
5020 	/* Is the vmid inactivity timer enabled */
5021 	if (phba->pport->vmid_inactivity_timeout ||
5022 	    phba->pport->load_flag & FC_DEREGISTER_ALL_APP_ID) {
5023 		wake_up = 1;
5024 		phba->pport->work_port_events |= WORKER_CHECK_INACTIVE_VMID;
5025 	}
5026 
5027 	if (wake_up)
5028 		lpfc_worker_wake_up(phba);
5029 
5030 	/* restart the timer for the next iteration */
5031 	mod_timer(&phba->inactive_vmid_poll, jiffies + msecs_to_jiffies(1000 *
5032 							LPFC_VMID_TIMER));
5033 }
5034 
5035 /**
5036  * lpfc_sli4_parse_latt_fault - Parse sli4 link-attention link fault code
5037  * @phba: pointer to lpfc hba data structure.
5038  * @acqe_link: pointer to the async link completion queue entry.
5039  *
5040  * This routine is to parse the SLI4 link-attention link fault code.
5041  **/
5042 static void
5043 lpfc_sli4_parse_latt_fault(struct lpfc_hba *phba,
5044 			   struct lpfc_acqe_link *acqe_link)
5045 {
5046 	switch (bf_get(lpfc_acqe_link_fault, acqe_link)) {
5047 	case LPFC_ASYNC_LINK_FAULT_NONE:
5048 	case LPFC_ASYNC_LINK_FAULT_LOCAL:
5049 	case LPFC_ASYNC_LINK_FAULT_REMOTE:
5050 	case LPFC_ASYNC_LINK_FAULT_LR_LRR:
5051 		break;
5052 	default:
5053 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5054 				"0398 Unknown link fault code: x%x\n",
5055 				bf_get(lpfc_acqe_link_fault, acqe_link));
5056 		break;
5057 	}
5058 }
5059 
5060 /**
5061  * lpfc_sli4_parse_latt_type - Parse sli4 link attention type
5062  * @phba: pointer to lpfc hba data structure.
5063  * @acqe_link: pointer to the async link completion queue entry.
5064  *
5065  * This routine is to parse the SLI4 link attention type and translate it
5066  * into the base driver's link attention type coding.
5067  *
5068  * Return: Link attention type in terms of base driver's coding.
5069  **/
5070 static uint8_t
5071 lpfc_sli4_parse_latt_type(struct lpfc_hba *phba,
5072 			  struct lpfc_acqe_link *acqe_link)
5073 {
5074 	uint8_t att_type;
5075 
5076 	switch (bf_get(lpfc_acqe_link_status, acqe_link)) {
5077 	case LPFC_ASYNC_LINK_STATUS_DOWN:
5078 	case LPFC_ASYNC_LINK_STATUS_LOGICAL_DOWN:
5079 		att_type = LPFC_ATT_LINK_DOWN;
5080 		break;
5081 	case LPFC_ASYNC_LINK_STATUS_UP:
5082 		/* Ignore physical link up events - wait for logical link up */
5083 		att_type = LPFC_ATT_RESERVED;
5084 		break;
5085 	case LPFC_ASYNC_LINK_STATUS_LOGICAL_UP:
5086 		att_type = LPFC_ATT_LINK_UP;
5087 		break;
5088 	default:
5089 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5090 				"0399 Invalid link attention type: x%x\n",
5091 				bf_get(lpfc_acqe_link_status, acqe_link));
5092 		att_type = LPFC_ATT_RESERVED;
5093 		break;
5094 	}
5095 	return att_type;
5096 }
5097 
5098 /**
5099  * lpfc_sli_port_speed_get - Get sli3 link speed code to link speed
5100  * @phba: pointer to lpfc hba data structure.
5101  *
5102  * This routine is to get an SLI3 FC port's link speed in Mbps.
5103  *
5104  * Return: link speed in terms of Mbps.
5105  **/
5106 uint32_t
5107 lpfc_sli_port_speed_get(struct lpfc_hba *phba)
5108 {
5109 	uint32_t link_speed;
5110 
5111 	if (!lpfc_is_link_up(phba))
5112 		return 0;
5113 
5114 	if (phba->sli_rev <= LPFC_SLI_REV3) {
5115 		switch (phba->fc_linkspeed) {
5116 		case LPFC_LINK_SPEED_1GHZ:
5117 			link_speed = 1000;
5118 			break;
5119 		case LPFC_LINK_SPEED_2GHZ:
5120 			link_speed = 2000;
5121 			break;
5122 		case LPFC_LINK_SPEED_4GHZ:
5123 			link_speed = 4000;
5124 			break;
5125 		case LPFC_LINK_SPEED_8GHZ:
5126 			link_speed = 8000;
5127 			break;
5128 		case LPFC_LINK_SPEED_10GHZ:
5129 			link_speed = 10000;
5130 			break;
5131 		case LPFC_LINK_SPEED_16GHZ:
5132 			link_speed = 16000;
5133 			break;
5134 		default:
5135 			link_speed = 0;
5136 		}
5137 	} else {
5138 		if (phba->sli4_hba.link_state.logical_speed)
5139 			link_speed =
5140 			      phba->sli4_hba.link_state.logical_speed;
5141 		else
5142 			link_speed = phba->sli4_hba.link_state.speed;
5143 	}
5144 	return link_speed;
5145 }
5146 
5147 /**
5148  * lpfc_sli4_port_speed_parse - Parse async evt link speed code to link speed
5149  * @phba: pointer to lpfc hba data structure.
5150  * @evt_code: asynchronous event code.
5151  * @speed_code: asynchronous event link speed code.
5152  *
5153  * This routine is to parse the giving SLI4 async event link speed code into
5154  * value of Mbps for the link speed.
5155  *
5156  * Return: link speed in terms of Mbps.
5157  **/
5158 static uint32_t
5159 lpfc_sli4_port_speed_parse(struct lpfc_hba *phba, uint32_t evt_code,
5160 			   uint8_t speed_code)
5161 {
5162 	uint32_t port_speed;
5163 
5164 	switch (evt_code) {
5165 	case LPFC_TRAILER_CODE_LINK:
5166 		switch (speed_code) {
5167 		case LPFC_ASYNC_LINK_SPEED_ZERO:
5168 			port_speed = 0;
5169 			break;
5170 		case LPFC_ASYNC_LINK_SPEED_10MBPS:
5171 			port_speed = 10;
5172 			break;
5173 		case LPFC_ASYNC_LINK_SPEED_100MBPS:
5174 			port_speed = 100;
5175 			break;
5176 		case LPFC_ASYNC_LINK_SPEED_1GBPS:
5177 			port_speed = 1000;
5178 			break;
5179 		case LPFC_ASYNC_LINK_SPEED_10GBPS:
5180 			port_speed = 10000;
5181 			break;
5182 		case LPFC_ASYNC_LINK_SPEED_20GBPS:
5183 			port_speed = 20000;
5184 			break;
5185 		case LPFC_ASYNC_LINK_SPEED_25GBPS:
5186 			port_speed = 25000;
5187 			break;
5188 		case LPFC_ASYNC_LINK_SPEED_40GBPS:
5189 			port_speed = 40000;
5190 			break;
5191 		case LPFC_ASYNC_LINK_SPEED_100GBPS:
5192 			port_speed = 100000;
5193 			break;
5194 		default:
5195 			port_speed = 0;
5196 		}
5197 		break;
5198 	case LPFC_TRAILER_CODE_FC:
5199 		switch (speed_code) {
5200 		case LPFC_FC_LA_SPEED_UNKNOWN:
5201 			port_speed = 0;
5202 			break;
5203 		case LPFC_FC_LA_SPEED_1G:
5204 			port_speed = 1000;
5205 			break;
5206 		case LPFC_FC_LA_SPEED_2G:
5207 			port_speed = 2000;
5208 			break;
5209 		case LPFC_FC_LA_SPEED_4G:
5210 			port_speed = 4000;
5211 			break;
5212 		case LPFC_FC_LA_SPEED_8G:
5213 			port_speed = 8000;
5214 			break;
5215 		case LPFC_FC_LA_SPEED_10G:
5216 			port_speed = 10000;
5217 			break;
5218 		case LPFC_FC_LA_SPEED_16G:
5219 			port_speed = 16000;
5220 			break;
5221 		case LPFC_FC_LA_SPEED_32G:
5222 			port_speed = 32000;
5223 			break;
5224 		case LPFC_FC_LA_SPEED_64G:
5225 			port_speed = 64000;
5226 			break;
5227 		case LPFC_FC_LA_SPEED_128G:
5228 			port_speed = 128000;
5229 			break;
5230 		case LPFC_FC_LA_SPEED_256G:
5231 			port_speed = 256000;
5232 			break;
5233 		default:
5234 			port_speed = 0;
5235 		}
5236 		break;
5237 	default:
5238 		port_speed = 0;
5239 	}
5240 	return port_speed;
5241 }
5242 
5243 /**
5244  * lpfc_sli4_async_link_evt - Process the asynchronous FCoE link event
5245  * @phba: pointer to lpfc hba data structure.
5246  * @acqe_link: pointer to the async link completion queue entry.
5247  *
5248  * This routine is to handle the SLI4 asynchronous FCoE link event.
5249  **/
5250 static void
5251 lpfc_sli4_async_link_evt(struct lpfc_hba *phba,
5252 			 struct lpfc_acqe_link *acqe_link)
5253 {
5254 	struct lpfc_dmabuf *mp;
5255 	LPFC_MBOXQ_t *pmb;
5256 	MAILBOX_t *mb;
5257 	struct lpfc_mbx_read_top *la;
5258 	uint8_t att_type;
5259 	int rc;
5260 
5261 	att_type = lpfc_sli4_parse_latt_type(phba, acqe_link);
5262 	if (att_type != LPFC_ATT_LINK_DOWN && att_type != LPFC_ATT_LINK_UP)
5263 		return;
5264 	phba->fcoe_eventtag = acqe_link->event_tag;
5265 	pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5266 	if (!pmb) {
5267 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5268 				"0395 The mboxq allocation failed\n");
5269 		return;
5270 	}
5271 	mp = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
5272 	if (!mp) {
5273 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5274 				"0396 The lpfc_dmabuf allocation failed\n");
5275 		goto out_free_pmb;
5276 	}
5277 	mp->virt = lpfc_mbuf_alloc(phba, 0, &mp->phys);
5278 	if (!mp->virt) {
5279 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5280 				"0397 The mbuf allocation failed\n");
5281 		goto out_free_dmabuf;
5282 	}
5283 
5284 	/* Cleanup any outstanding ELS commands */
5285 	lpfc_els_flush_all_cmd(phba);
5286 
5287 	/* Block ELS IOCBs until we have done process link event */
5288 	phba->sli4_hba.els_wq->pring->flag |= LPFC_STOP_IOCB_EVENT;
5289 
5290 	/* Update link event statistics */
5291 	phba->sli.slistat.link_event++;
5292 
5293 	/* Create lpfc_handle_latt mailbox command from link ACQE */
5294 	lpfc_read_topology(phba, pmb, mp);
5295 	pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
5296 	pmb->vport = phba->pport;
5297 
5298 	/* Keep the link status for extra SLI4 state machine reference */
5299 	phba->sli4_hba.link_state.speed =
5300 			lpfc_sli4_port_speed_parse(phba, LPFC_TRAILER_CODE_LINK,
5301 				bf_get(lpfc_acqe_link_speed, acqe_link));
5302 	phba->sli4_hba.link_state.duplex =
5303 				bf_get(lpfc_acqe_link_duplex, acqe_link);
5304 	phba->sli4_hba.link_state.status =
5305 				bf_get(lpfc_acqe_link_status, acqe_link);
5306 	phba->sli4_hba.link_state.type =
5307 				bf_get(lpfc_acqe_link_type, acqe_link);
5308 	phba->sli4_hba.link_state.number =
5309 				bf_get(lpfc_acqe_link_number, acqe_link);
5310 	phba->sli4_hba.link_state.fault =
5311 				bf_get(lpfc_acqe_link_fault, acqe_link);
5312 	phba->sli4_hba.link_state.logical_speed =
5313 			bf_get(lpfc_acqe_logical_link_speed, acqe_link) * 10;
5314 
5315 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5316 			"2900 Async FC/FCoE Link event - Speed:%dGBit "
5317 			"duplex:x%x LA Type:x%x Port Type:%d Port Number:%d "
5318 			"Logical speed:%dMbps Fault:%d\n",
5319 			phba->sli4_hba.link_state.speed,
5320 			phba->sli4_hba.link_state.topology,
5321 			phba->sli4_hba.link_state.status,
5322 			phba->sli4_hba.link_state.type,
5323 			phba->sli4_hba.link_state.number,
5324 			phba->sli4_hba.link_state.logical_speed,
5325 			phba->sli4_hba.link_state.fault);
5326 	/*
5327 	 * For FC Mode: issue the READ_TOPOLOGY mailbox command to fetch
5328 	 * topology info. Note: Optional for non FC-AL ports.
5329 	 */
5330 	if (!(phba->hba_flag & HBA_FCOE_MODE)) {
5331 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
5332 		if (rc == MBX_NOT_FINISHED) {
5333 			lpfc_mbuf_free(phba, mp->virt, mp->phys);
5334 			goto out_free_dmabuf;
5335 		}
5336 		return;
5337 	}
5338 	/*
5339 	 * For FCoE Mode: fill in all the topology information we need and call
5340 	 * the READ_TOPOLOGY completion routine to continue without actually
5341 	 * sending the READ_TOPOLOGY mailbox command to the port.
5342 	 */
5343 	/* Initialize completion status */
5344 	mb = &pmb->u.mb;
5345 	mb->mbxStatus = MBX_SUCCESS;
5346 
5347 	/* Parse port fault information field */
5348 	lpfc_sli4_parse_latt_fault(phba, acqe_link);
5349 
5350 	/* Parse and translate link attention fields */
5351 	la = (struct lpfc_mbx_read_top *) &pmb->u.mb.un.varReadTop;
5352 	la->eventTag = acqe_link->event_tag;
5353 	bf_set(lpfc_mbx_read_top_att_type, la, att_type);
5354 	bf_set(lpfc_mbx_read_top_link_spd, la,
5355 	       (bf_get(lpfc_acqe_link_speed, acqe_link)));
5356 
5357 	/* Fake the the following irrelvant fields */
5358 	bf_set(lpfc_mbx_read_top_topology, la, LPFC_TOPOLOGY_PT_PT);
5359 	bf_set(lpfc_mbx_read_top_alpa_granted, la, 0);
5360 	bf_set(lpfc_mbx_read_top_il, la, 0);
5361 	bf_set(lpfc_mbx_read_top_pb, la, 0);
5362 	bf_set(lpfc_mbx_read_top_fa, la, 0);
5363 	bf_set(lpfc_mbx_read_top_mm, la, 0);
5364 
5365 	/* Invoke the lpfc_handle_latt mailbox command callback function */
5366 	lpfc_mbx_cmpl_read_topology(phba, pmb);
5367 
5368 	return;
5369 
5370 out_free_dmabuf:
5371 	kfree(mp);
5372 out_free_pmb:
5373 	mempool_free(pmb, phba->mbox_mem_pool);
5374 }
5375 
5376 /**
5377  * lpfc_async_link_speed_to_read_top - Parse async evt link speed code to read
5378  * topology.
5379  * @phba: pointer to lpfc hba data structure.
5380  * @speed_code: asynchronous event link speed code.
5381  *
5382  * This routine is to parse the giving SLI4 async event link speed code into
5383  * value of Read topology link speed.
5384  *
5385  * Return: link speed in terms of Read topology.
5386  **/
5387 static uint8_t
5388 lpfc_async_link_speed_to_read_top(struct lpfc_hba *phba, uint8_t speed_code)
5389 {
5390 	uint8_t port_speed;
5391 
5392 	switch (speed_code) {
5393 	case LPFC_FC_LA_SPEED_1G:
5394 		port_speed = LPFC_LINK_SPEED_1GHZ;
5395 		break;
5396 	case LPFC_FC_LA_SPEED_2G:
5397 		port_speed = LPFC_LINK_SPEED_2GHZ;
5398 		break;
5399 	case LPFC_FC_LA_SPEED_4G:
5400 		port_speed = LPFC_LINK_SPEED_4GHZ;
5401 		break;
5402 	case LPFC_FC_LA_SPEED_8G:
5403 		port_speed = LPFC_LINK_SPEED_8GHZ;
5404 		break;
5405 	case LPFC_FC_LA_SPEED_16G:
5406 		port_speed = LPFC_LINK_SPEED_16GHZ;
5407 		break;
5408 	case LPFC_FC_LA_SPEED_32G:
5409 		port_speed = LPFC_LINK_SPEED_32GHZ;
5410 		break;
5411 	case LPFC_FC_LA_SPEED_64G:
5412 		port_speed = LPFC_LINK_SPEED_64GHZ;
5413 		break;
5414 	case LPFC_FC_LA_SPEED_128G:
5415 		port_speed = LPFC_LINK_SPEED_128GHZ;
5416 		break;
5417 	case LPFC_FC_LA_SPEED_256G:
5418 		port_speed = LPFC_LINK_SPEED_256GHZ;
5419 		break;
5420 	default:
5421 		port_speed = 0;
5422 		break;
5423 	}
5424 
5425 	return port_speed;
5426 }
5427 
5428 void
5429 lpfc_cgn_dump_rxmonitor(struct lpfc_hba *phba)
5430 {
5431 	struct rxtable_entry *entry;
5432 	int cnt = 0, head, tail, last, start;
5433 
5434 	head = atomic_read(&phba->rxtable_idx_head);
5435 	tail = atomic_read(&phba->rxtable_idx_tail);
5436 	if (!phba->rxtable || head == tail) {
5437 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT,
5438 				"4411 Rxtable is empty\n");
5439 		return;
5440 	}
5441 	last = tail;
5442 	start = head;
5443 
5444 	/* Display the last LPFC_MAX_RXMONITOR_DUMP entries from the rxtable */
5445 	while (start != last) {
5446 		if (start)
5447 			start--;
5448 		else
5449 			start = LPFC_MAX_RXMONITOR_ENTRY - 1;
5450 		entry = &phba->rxtable[start];
5451 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5452 				"4410 %02d: MBPI %lld Xmit %lld Cmpl %lld "
5453 				"Lat %lld ASz %lld Info %02d BWUtil %d "
5454 				"Int %d slot %d\n",
5455 				cnt, entry->max_bytes_per_interval,
5456 				entry->total_bytes, entry->rcv_bytes,
5457 				entry->avg_io_latency, entry->avg_io_size,
5458 				entry->cmf_info, entry->timer_utilization,
5459 				entry->timer_interval, start);
5460 		cnt++;
5461 		if (cnt >= LPFC_MAX_RXMONITOR_DUMP)
5462 			return;
5463 	}
5464 }
5465 
5466 /**
5467  * lpfc_cgn_update_stat - Save data into congestion stats buffer
5468  * @phba: pointer to lpfc hba data structure.
5469  * @dtag: FPIN descriptor received
5470  *
5471  * Increment the FPIN received counter/time when it happens.
5472  */
5473 void
5474 lpfc_cgn_update_stat(struct lpfc_hba *phba, uint32_t dtag)
5475 {
5476 	struct lpfc_cgn_info *cp;
5477 	struct tm broken;
5478 	struct timespec64 cur_time;
5479 	u32 cnt;
5480 	u16 value;
5481 
5482 	/* Make sure we have a congestion info buffer */
5483 	if (!phba->cgn_i)
5484 		return;
5485 	cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
5486 	ktime_get_real_ts64(&cur_time);
5487 	time64_to_tm(cur_time.tv_sec, 0, &broken);
5488 
5489 	/* Update congestion statistics */
5490 	switch (dtag) {
5491 	case ELS_DTAG_LNK_INTEGRITY:
5492 		cnt = le32_to_cpu(cp->link_integ_notification);
5493 		cnt++;
5494 		cp->link_integ_notification = cpu_to_le32(cnt);
5495 
5496 		cp->cgn_stat_lnk_month = broken.tm_mon + 1;
5497 		cp->cgn_stat_lnk_day = broken.tm_mday;
5498 		cp->cgn_stat_lnk_year = broken.tm_year - 100;
5499 		cp->cgn_stat_lnk_hour = broken.tm_hour;
5500 		cp->cgn_stat_lnk_min = broken.tm_min;
5501 		cp->cgn_stat_lnk_sec = broken.tm_sec;
5502 		break;
5503 	case ELS_DTAG_DELIVERY:
5504 		cnt = le32_to_cpu(cp->delivery_notification);
5505 		cnt++;
5506 		cp->delivery_notification = cpu_to_le32(cnt);
5507 
5508 		cp->cgn_stat_del_month = broken.tm_mon + 1;
5509 		cp->cgn_stat_del_day = broken.tm_mday;
5510 		cp->cgn_stat_del_year = broken.tm_year - 100;
5511 		cp->cgn_stat_del_hour = broken.tm_hour;
5512 		cp->cgn_stat_del_min = broken.tm_min;
5513 		cp->cgn_stat_del_sec = broken.tm_sec;
5514 		break;
5515 	case ELS_DTAG_PEER_CONGEST:
5516 		cnt = le32_to_cpu(cp->cgn_peer_notification);
5517 		cnt++;
5518 		cp->cgn_peer_notification = cpu_to_le32(cnt);
5519 
5520 		cp->cgn_stat_peer_month = broken.tm_mon + 1;
5521 		cp->cgn_stat_peer_day = broken.tm_mday;
5522 		cp->cgn_stat_peer_year = broken.tm_year - 100;
5523 		cp->cgn_stat_peer_hour = broken.tm_hour;
5524 		cp->cgn_stat_peer_min = broken.tm_min;
5525 		cp->cgn_stat_peer_sec = broken.tm_sec;
5526 		break;
5527 	case ELS_DTAG_CONGESTION:
5528 		cnt = le32_to_cpu(cp->cgn_notification);
5529 		cnt++;
5530 		cp->cgn_notification = cpu_to_le32(cnt);
5531 
5532 		cp->cgn_stat_cgn_month = broken.tm_mon + 1;
5533 		cp->cgn_stat_cgn_day = broken.tm_mday;
5534 		cp->cgn_stat_cgn_year = broken.tm_year - 100;
5535 		cp->cgn_stat_cgn_hour = broken.tm_hour;
5536 		cp->cgn_stat_cgn_min = broken.tm_min;
5537 		cp->cgn_stat_cgn_sec = broken.tm_sec;
5538 	}
5539 	if (phba->cgn_fpin_frequency &&
5540 	    phba->cgn_fpin_frequency != LPFC_FPIN_INIT_FREQ) {
5541 		value = LPFC_CGN_TIMER_TO_MIN / phba->cgn_fpin_frequency;
5542 		cp->cgn_stat_npm = value;
5543 	}
5544 	value = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ,
5545 				    LPFC_CGN_CRC32_SEED);
5546 	cp->cgn_info_crc = cpu_to_le32(value);
5547 }
5548 
5549 /**
5550  * lpfc_cgn_save_evt_cnt - Save data into registered congestion buffer
5551  * @phba: pointer to lpfc hba data structure.
5552  *
5553  * Save the congestion event data every minute.
5554  * On the hour collapse all the minute data into hour data. Every day
5555  * collapse all the hour data into daily data. Separate driver
5556  * and fabrc congestion event counters that will be saved out
5557  * to the registered congestion buffer every minute.
5558  */
5559 static void
5560 lpfc_cgn_save_evt_cnt(struct lpfc_hba *phba)
5561 {
5562 	struct lpfc_cgn_info *cp;
5563 	struct tm broken;
5564 	struct timespec64 cur_time;
5565 	uint32_t i, index;
5566 	uint16_t value, mvalue;
5567 	uint64_t bps;
5568 	uint32_t mbps;
5569 	uint32_t dvalue, wvalue, lvalue, avalue;
5570 	uint64_t latsum;
5571 	__le16 *ptr;
5572 	__le32 *lptr;
5573 	__le16 *mptr;
5574 
5575 	/* Make sure we have a congestion info buffer */
5576 	if (!phba->cgn_i)
5577 		return;
5578 	cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
5579 
5580 	if (time_before(jiffies, phba->cgn_evt_timestamp))
5581 		return;
5582 	phba->cgn_evt_timestamp = jiffies +
5583 			msecs_to_jiffies(LPFC_CGN_TIMER_TO_MIN);
5584 	phba->cgn_evt_minute++;
5585 
5586 	/* We should get to this point in the routine on 1 minute intervals */
5587 
5588 	ktime_get_real_ts64(&cur_time);
5589 	time64_to_tm(cur_time.tv_sec, 0, &broken);
5590 
5591 	if (phba->cgn_fpin_frequency &&
5592 	    phba->cgn_fpin_frequency != LPFC_FPIN_INIT_FREQ) {
5593 		value = LPFC_CGN_TIMER_TO_MIN / phba->cgn_fpin_frequency;
5594 		cp->cgn_stat_npm = value;
5595 	}
5596 
5597 	/* Read and clear the latency counters for this minute */
5598 	lvalue = atomic_read(&phba->cgn_latency_evt_cnt);
5599 	latsum = atomic64_read(&phba->cgn_latency_evt);
5600 	atomic_set(&phba->cgn_latency_evt_cnt, 0);
5601 	atomic64_set(&phba->cgn_latency_evt, 0);
5602 
5603 	/* We need to store MB/sec bandwidth in the congestion information.
5604 	 * block_cnt is count of 512 byte blocks for the entire minute,
5605 	 * bps will get bytes per sec before finally converting to MB/sec.
5606 	 */
5607 	bps = div_u64(phba->rx_block_cnt, LPFC_SEC_MIN) * 512;
5608 	phba->rx_block_cnt = 0;
5609 	mvalue = bps / (1024 * 1024); /* convert to MB/sec */
5610 
5611 	/* Every minute */
5612 	/* cgn parameters */
5613 	cp->cgn_info_mode = phba->cgn_p.cgn_param_mode;
5614 	cp->cgn_info_level0 = phba->cgn_p.cgn_param_level0;
5615 	cp->cgn_info_level1 = phba->cgn_p.cgn_param_level1;
5616 	cp->cgn_info_level2 = phba->cgn_p.cgn_param_level2;
5617 
5618 	/* Fill in default LUN qdepth */
5619 	value = (uint16_t)(phba->pport->cfg_lun_queue_depth);
5620 	cp->cgn_lunq = cpu_to_le16(value);
5621 
5622 	/* Record congestion buffer info - every minute
5623 	 * cgn_driver_evt_cnt (Driver events)
5624 	 * cgn_fabric_warn_cnt (Congestion Warnings)
5625 	 * cgn_latency_evt_cnt / cgn_latency_evt (IO Latency)
5626 	 * cgn_fabric_alarm_cnt (Congestion Alarms)
5627 	 */
5628 	index = ++cp->cgn_index_minute;
5629 	if (cp->cgn_index_minute == LPFC_MIN_HOUR) {
5630 		cp->cgn_index_minute = 0;
5631 		index = 0;
5632 	}
5633 
5634 	/* Get the number of driver events in this sample and reset counter */
5635 	dvalue = atomic_read(&phba->cgn_driver_evt_cnt);
5636 	atomic_set(&phba->cgn_driver_evt_cnt, 0);
5637 
5638 	/* Get the number of warning events - FPIN and Signal for this minute */
5639 	wvalue = 0;
5640 	if ((phba->cgn_reg_fpin & LPFC_CGN_FPIN_WARN) ||
5641 	    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY ||
5642 	    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM)
5643 		wvalue = atomic_read(&phba->cgn_fabric_warn_cnt);
5644 	atomic_set(&phba->cgn_fabric_warn_cnt, 0);
5645 
5646 	/* Get the number of alarm events - FPIN and Signal for this minute */
5647 	avalue = 0;
5648 	if ((phba->cgn_reg_fpin & LPFC_CGN_FPIN_ALARM) ||
5649 	    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM)
5650 		avalue = atomic_read(&phba->cgn_fabric_alarm_cnt);
5651 	atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
5652 
5653 	/* Collect the driver, warning, alarm and latency counts for this
5654 	 * minute into the driver congestion buffer.
5655 	 */
5656 	ptr = &cp->cgn_drvr_min[index];
5657 	value = (uint16_t)dvalue;
5658 	*ptr = cpu_to_le16(value);
5659 
5660 	ptr = &cp->cgn_warn_min[index];
5661 	value = (uint16_t)wvalue;
5662 	*ptr = cpu_to_le16(value);
5663 
5664 	ptr = &cp->cgn_alarm_min[index];
5665 	value = (uint16_t)avalue;
5666 	*ptr = cpu_to_le16(value);
5667 
5668 	lptr = &cp->cgn_latency_min[index];
5669 	if (lvalue) {
5670 		lvalue = (uint32_t)div_u64(latsum, lvalue);
5671 		*lptr = cpu_to_le32(lvalue);
5672 	} else {
5673 		*lptr = 0;
5674 	}
5675 
5676 	/* Collect the bandwidth value into the driver's congesion buffer. */
5677 	mptr = &cp->cgn_bw_min[index];
5678 	*mptr = cpu_to_le16(mvalue);
5679 
5680 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5681 			"2418 Congestion Info - minute (%d): %d %d %d %d %d\n",
5682 			index, dvalue, wvalue, *lptr, mvalue, avalue);
5683 
5684 	/* Every hour */
5685 	if ((phba->cgn_evt_minute % LPFC_MIN_HOUR) == 0) {
5686 		/* Record congestion buffer info - every hour
5687 		 * Collapse all minutes into an hour
5688 		 */
5689 		index = ++cp->cgn_index_hour;
5690 		if (cp->cgn_index_hour == LPFC_HOUR_DAY) {
5691 			cp->cgn_index_hour = 0;
5692 			index = 0;
5693 		}
5694 
5695 		dvalue = 0;
5696 		wvalue = 0;
5697 		lvalue = 0;
5698 		avalue = 0;
5699 		mvalue = 0;
5700 		mbps = 0;
5701 		for (i = 0; i < LPFC_MIN_HOUR; i++) {
5702 			dvalue += le16_to_cpu(cp->cgn_drvr_min[i]);
5703 			wvalue += le16_to_cpu(cp->cgn_warn_min[i]);
5704 			lvalue += le32_to_cpu(cp->cgn_latency_min[i]);
5705 			mbps += le16_to_cpu(cp->cgn_bw_min[i]);
5706 			avalue += le16_to_cpu(cp->cgn_alarm_min[i]);
5707 		}
5708 		if (lvalue)		/* Avg of latency averages */
5709 			lvalue /= LPFC_MIN_HOUR;
5710 		if (mbps)		/* Avg of Bandwidth averages */
5711 			mvalue = mbps / LPFC_MIN_HOUR;
5712 
5713 		lptr = &cp->cgn_drvr_hr[index];
5714 		*lptr = cpu_to_le32(dvalue);
5715 		lptr = &cp->cgn_warn_hr[index];
5716 		*lptr = cpu_to_le32(wvalue);
5717 		lptr = &cp->cgn_latency_hr[index];
5718 		*lptr = cpu_to_le32(lvalue);
5719 		mptr = &cp->cgn_bw_hr[index];
5720 		*mptr = cpu_to_le16(mvalue);
5721 		lptr = &cp->cgn_alarm_hr[index];
5722 		*lptr = cpu_to_le32(avalue);
5723 
5724 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5725 				"2419 Congestion Info - hour "
5726 				"(%d): %d %d %d %d %d\n",
5727 				index, dvalue, wvalue, lvalue, mvalue, avalue);
5728 	}
5729 
5730 	/* Every day */
5731 	if ((phba->cgn_evt_minute % LPFC_MIN_DAY) == 0) {
5732 		/* Record congestion buffer info - every hour
5733 		 * Collapse all hours into a day. Rotate days
5734 		 * after LPFC_MAX_CGN_DAYS.
5735 		 */
5736 		index = ++cp->cgn_index_day;
5737 		if (cp->cgn_index_day == LPFC_MAX_CGN_DAYS) {
5738 			cp->cgn_index_day = 0;
5739 			index = 0;
5740 		}
5741 
5742 		/* Anytime we overwrite daily index 0, after we wrap,
5743 		 * we will be overwriting the oldest day, so we must
5744 		 * update the congestion data start time for that day.
5745 		 * That start time should have previously been saved after
5746 		 * we wrote the last days worth of data.
5747 		 */
5748 		if ((phba->hba_flag & HBA_CGN_DAY_WRAP) && index == 0) {
5749 			time64_to_tm(phba->cgn_daily_ts.tv_sec, 0, &broken);
5750 
5751 			cp->cgn_info_month = broken.tm_mon + 1;
5752 			cp->cgn_info_day = broken.tm_mday;
5753 			cp->cgn_info_year = broken.tm_year - 100;
5754 			cp->cgn_info_hour = broken.tm_hour;
5755 			cp->cgn_info_minute = broken.tm_min;
5756 			cp->cgn_info_second = broken.tm_sec;
5757 
5758 			lpfc_printf_log
5759 				(phba, KERN_INFO, LOG_CGN_MGMT,
5760 				"2646 CGNInfo idx0 Start Time: "
5761 				"%d/%d/%d %d:%d:%d\n",
5762 				cp->cgn_info_day, cp->cgn_info_month,
5763 				cp->cgn_info_year, cp->cgn_info_hour,
5764 				cp->cgn_info_minute, cp->cgn_info_second);
5765 		}
5766 
5767 		dvalue = 0;
5768 		wvalue = 0;
5769 		lvalue = 0;
5770 		mvalue = 0;
5771 		mbps = 0;
5772 		avalue = 0;
5773 		for (i = 0; i < LPFC_HOUR_DAY; i++) {
5774 			dvalue += le32_to_cpu(cp->cgn_drvr_hr[i]);
5775 			wvalue += le32_to_cpu(cp->cgn_warn_hr[i]);
5776 			lvalue += le32_to_cpu(cp->cgn_latency_hr[i]);
5777 			mbps += le16_to_cpu(cp->cgn_bw_hr[i]);
5778 			avalue += le32_to_cpu(cp->cgn_alarm_hr[i]);
5779 		}
5780 		if (lvalue)		/* Avg of latency averages */
5781 			lvalue /= LPFC_HOUR_DAY;
5782 		if (mbps)		/* Avg of Bandwidth averages */
5783 			mvalue = mbps / LPFC_HOUR_DAY;
5784 
5785 		lptr = &cp->cgn_drvr_day[index];
5786 		*lptr = cpu_to_le32(dvalue);
5787 		lptr = &cp->cgn_warn_day[index];
5788 		*lptr = cpu_to_le32(wvalue);
5789 		lptr = &cp->cgn_latency_day[index];
5790 		*lptr = cpu_to_le32(lvalue);
5791 		mptr = &cp->cgn_bw_day[index];
5792 		*mptr = cpu_to_le16(mvalue);
5793 		lptr = &cp->cgn_alarm_day[index];
5794 		*lptr = cpu_to_le32(avalue);
5795 
5796 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5797 				"2420 Congestion Info - daily (%d): "
5798 				"%d %d %d %d %d\n",
5799 				index, dvalue, wvalue, lvalue, mvalue, avalue);
5800 
5801 		/* We just wrote LPFC_MAX_CGN_DAYS of data,
5802 		 * so we are wrapped on any data after this.
5803 		 * Save this as the start time for the next day.
5804 		 */
5805 		if (index == (LPFC_MAX_CGN_DAYS - 1)) {
5806 			phba->hba_flag |= HBA_CGN_DAY_WRAP;
5807 			ktime_get_real_ts64(&phba->cgn_daily_ts);
5808 		}
5809 	}
5810 
5811 	/* Use the frequency found in the last rcv'ed FPIN */
5812 	value = phba->cgn_fpin_frequency;
5813 	cp->cgn_warn_freq = cpu_to_le16(value);
5814 	cp->cgn_alarm_freq = cpu_to_le16(value);
5815 
5816 	lvalue = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ,
5817 				     LPFC_CGN_CRC32_SEED);
5818 	cp->cgn_info_crc = cpu_to_le32(lvalue);
5819 }
5820 
5821 /**
5822  * lpfc_calc_cmf_latency - latency from start of rxate timer interval
5823  * @phba: The Hba for which this call is being executed.
5824  *
5825  * The routine calculates the latency from the beginning of the CMF timer
5826  * interval to the current point in time. It is called from IO completion
5827  * when we exceed our Bandwidth limitation for the time interval.
5828  */
5829 uint32_t
5830 lpfc_calc_cmf_latency(struct lpfc_hba *phba)
5831 {
5832 	struct timespec64 cmpl_time;
5833 	uint32_t msec = 0;
5834 
5835 	ktime_get_real_ts64(&cmpl_time);
5836 
5837 	/* This routine works on a ms granularity so sec and usec are
5838 	 * converted accordingly.
5839 	 */
5840 	if (cmpl_time.tv_sec == phba->cmf_latency.tv_sec) {
5841 		msec = (cmpl_time.tv_nsec - phba->cmf_latency.tv_nsec) /
5842 			NSEC_PER_MSEC;
5843 	} else {
5844 		if (cmpl_time.tv_nsec >= phba->cmf_latency.tv_nsec) {
5845 			msec = (cmpl_time.tv_sec -
5846 				phba->cmf_latency.tv_sec) * MSEC_PER_SEC;
5847 			msec += ((cmpl_time.tv_nsec -
5848 				  phba->cmf_latency.tv_nsec) / NSEC_PER_MSEC);
5849 		} else {
5850 			msec = (cmpl_time.tv_sec - phba->cmf_latency.tv_sec -
5851 				1) * MSEC_PER_SEC;
5852 			msec += (((NSEC_PER_SEC - phba->cmf_latency.tv_nsec) +
5853 				 cmpl_time.tv_nsec) / NSEC_PER_MSEC);
5854 		}
5855 	}
5856 	return msec;
5857 }
5858 
5859 /**
5860  * lpfc_cmf_timer -  This is the timer function for one congestion
5861  * rate interval.
5862  * @timer: Pointer to the high resolution timer that expired
5863  */
5864 static enum hrtimer_restart
5865 lpfc_cmf_timer(struct hrtimer *timer)
5866 {
5867 	struct lpfc_hba *phba = container_of(timer, struct lpfc_hba,
5868 					     cmf_timer);
5869 	struct rxtable_entry *entry;
5870 	uint32_t io_cnt;
5871 	uint32_t head, tail;
5872 	uint32_t busy, max_read;
5873 	uint64_t total, rcv, lat, mbpi, extra;
5874 	int timer_interval = LPFC_CMF_INTERVAL;
5875 	uint32_t ms;
5876 	struct lpfc_cgn_stat *cgs;
5877 	int cpu;
5878 
5879 	/* Only restart the timer if congestion mgmt is on */
5880 	if (phba->cmf_active_mode == LPFC_CFG_OFF ||
5881 	    !phba->cmf_latency.tv_sec) {
5882 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5883 				"6224 CMF timer exit: %d %lld\n",
5884 				phba->cmf_active_mode,
5885 				(uint64_t)phba->cmf_latency.tv_sec);
5886 		return HRTIMER_NORESTART;
5887 	}
5888 
5889 	/* If pport is not ready yet, just exit and wait for
5890 	 * the next timer cycle to hit.
5891 	 */
5892 	if (!phba->pport)
5893 		goto skip;
5894 
5895 	/* Do not block SCSI IO while in the timer routine since
5896 	 * total_bytes will be cleared
5897 	 */
5898 	atomic_set(&phba->cmf_stop_io, 1);
5899 
5900 	/* First we need to calculate the actual ms between
5901 	 * the last timer interrupt and this one. We ask for
5902 	 * LPFC_CMF_INTERVAL, however the actual time may
5903 	 * vary depending on system overhead.
5904 	 */
5905 	ms = lpfc_calc_cmf_latency(phba);
5906 
5907 
5908 	/* Immediately after we calculate the time since the last
5909 	 * timer interrupt, set the start time for the next
5910 	 * interrupt
5911 	 */
5912 	ktime_get_real_ts64(&phba->cmf_latency);
5913 
5914 	phba->cmf_link_byte_count =
5915 		div_u64(phba->cmf_max_line_rate * LPFC_CMF_INTERVAL, 1000);
5916 
5917 	/* Collect all the stats from the prior timer interval */
5918 	total = 0;
5919 	io_cnt = 0;
5920 	lat = 0;
5921 	rcv = 0;
5922 	for_each_present_cpu(cpu) {
5923 		cgs = per_cpu_ptr(phba->cmf_stat, cpu);
5924 		total += atomic64_xchg(&cgs->total_bytes, 0);
5925 		io_cnt += atomic_xchg(&cgs->rx_io_cnt, 0);
5926 		lat += atomic64_xchg(&cgs->rx_latency, 0);
5927 		rcv += atomic64_xchg(&cgs->rcv_bytes, 0);
5928 	}
5929 
5930 	/* Before we issue another CMF_SYNC_WQE, retrieve the BW
5931 	 * returned from the last CMF_SYNC_WQE issued, from
5932 	 * cmf_last_sync_bw. This will be the target BW for
5933 	 * this next timer interval.
5934 	 */
5935 	if (phba->cmf_active_mode == LPFC_CFG_MANAGED &&
5936 	    phba->link_state != LPFC_LINK_DOWN &&
5937 	    phba->hba_flag & HBA_SETUP) {
5938 		mbpi = phba->cmf_last_sync_bw;
5939 		phba->cmf_last_sync_bw = 0;
5940 		extra = 0;
5941 
5942 		/* Calculate any extra bytes needed to account for the
5943 		 * timer accuracy. If we are less than LPFC_CMF_INTERVAL
5944 		 * add an extra 3% slop factor, equal to LPFC_CMF_INTERVAL
5945 		 * add an extra 2%. The goal is to equalize total with a
5946 		 * time > LPFC_CMF_INTERVAL or <= LPFC_CMF_INTERVAL + 1
5947 		 */
5948 		if (ms == LPFC_CMF_INTERVAL)
5949 			extra = div_u64(total, 50);
5950 		else if (ms < LPFC_CMF_INTERVAL)
5951 			extra = div_u64(total, 33);
5952 		lpfc_issue_cmf_sync_wqe(phba, LPFC_CMF_INTERVAL, total + extra);
5953 	} else {
5954 		/* For Monitor mode or link down we want mbpi
5955 		 * to be the full link speed
5956 		 */
5957 		mbpi = phba->cmf_link_byte_count;
5958 	}
5959 	phba->cmf_timer_cnt++;
5960 
5961 	if (io_cnt) {
5962 		/* Update congestion info buffer latency in us */
5963 		atomic_add(io_cnt, &phba->cgn_latency_evt_cnt);
5964 		atomic64_add(lat, &phba->cgn_latency_evt);
5965 	}
5966 	busy = atomic_xchg(&phba->cmf_busy, 0);
5967 	max_read = atomic_xchg(&phba->rx_max_read_cnt, 0);
5968 
5969 	/* Calculate MBPI for the next timer interval */
5970 	if (mbpi) {
5971 		if (mbpi > phba->cmf_link_byte_count ||
5972 		    phba->cmf_active_mode == LPFC_CFG_MONITOR)
5973 			mbpi = phba->cmf_link_byte_count;
5974 
5975 		/* Change max_bytes_per_interval to what the prior
5976 		 * CMF_SYNC_WQE cmpl indicated.
5977 		 */
5978 		if (mbpi != phba->cmf_max_bytes_per_interval)
5979 			phba->cmf_max_bytes_per_interval = mbpi;
5980 	}
5981 
5982 	/* Save rxmonitor information for debug */
5983 	if (phba->rxtable) {
5984 		head = atomic_xchg(&phba->rxtable_idx_head,
5985 				   LPFC_RXMONITOR_TABLE_IN_USE);
5986 		entry = &phba->rxtable[head];
5987 		entry->total_bytes = total;
5988 		entry->rcv_bytes = rcv;
5989 		entry->cmf_busy = busy;
5990 		entry->cmf_info = phba->cmf_active_info;
5991 		if (io_cnt) {
5992 			entry->avg_io_latency = div_u64(lat, io_cnt);
5993 			entry->avg_io_size = div_u64(rcv, io_cnt);
5994 		} else {
5995 			entry->avg_io_latency = 0;
5996 			entry->avg_io_size = 0;
5997 		}
5998 		entry->max_read_cnt = max_read;
5999 		entry->io_cnt = io_cnt;
6000 		entry->max_bytes_per_interval = mbpi;
6001 		if (phba->cmf_active_mode == LPFC_CFG_MANAGED)
6002 			entry->timer_utilization = phba->cmf_last_ts;
6003 		else
6004 			entry->timer_utilization = ms;
6005 		entry->timer_interval = ms;
6006 		phba->cmf_last_ts = 0;
6007 
6008 		/* Increment rxtable index */
6009 		head = (head + 1) % LPFC_MAX_RXMONITOR_ENTRY;
6010 		tail = atomic_read(&phba->rxtable_idx_tail);
6011 		if (head == tail) {
6012 			tail = (tail + 1) % LPFC_MAX_RXMONITOR_ENTRY;
6013 			atomic_set(&phba->rxtable_idx_tail, tail);
6014 		}
6015 		atomic_set(&phba->rxtable_idx_head, head);
6016 	}
6017 
6018 	if (phba->cmf_active_mode == LPFC_CFG_MONITOR) {
6019 		/* If Monitor mode, check if we are oversubscribed
6020 		 * against the full line rate.
6021 		 */
6022 		if (mbpi && total > mbpi)
6023 			atomic_inc(&phba->cgn_driver_evt_cnt);
6024 	}
6025 	phba->rx_block_cnt += div_u64(rcv, 512);  /* save 512 byte block cnt */
6026 
6027 	/* Each minute save Fabric and Driver congestion information */
6028 	lpfc_cgn_save_evt_cnt(phba);
6029 
6030 	/* Since we need to call lpfc_cgn_save_evt_cnt every minute, on the
6031 	 * minute, adjust our next timer interval, if needed, to ensure a
6032 	 * 1 minute granularity when we get the next timer interrupt.
6033 	 */
6034 	if (time_after(jiffies + msecs_to_jiffies(LPFC_CMF_INTERVAL),
6035 		       phba->cgn_evt_timestamp)) {
6036 		timer_interval = jiffies_to_msecs(phba->cgn_evt_timestamp -
6037 						  jiffies);
6038 		if (timer_interval <= 0)
6039 			timer_interval = LPFC_CMF_INTERVAL;
6040 
6041 		/* If we adjust timer_interval, max_bytes_per_interval
6042 		 * needs to be adjusted as well.
6043 		 */
6044 		phba->cmf_link_byte_count = div_u64(phba->cmf_max_line_rate *
6045 						    timer_interval, 1000);
6046 		if (phba->cmf_active_mode == LPFC_CFG_MONITOR)
6047 			phba->cmf_max_bytes_per_interval =
6048 				phba->cmf_link_byte_count;
6049 	}
6050 
6051 	/* Since total_bytes has already been zero'ed, its okay to unblock
6052 	 * after max_bytes_per_interval is setup.
6053 	 */
6054 	if (atomic_xchg(&phba->cmf_bw_wait, 0))
6055 		queue_work(phba->wq, &phba->unblock_request_work);
6056 
6057 	/* SCSI IO is now unblocked */
6058 	atomic_set(&phba->cmf_stop_io, 0);
6059 
6060 skip:
6061 	hrtimer_forward_now(timer,
6062 			    ktime_set(0, timer_interval * NSEC_PER_MSEC));
6063 	return HRTIMER_RESTART;
6064 }
6065 
6066 #define trunk_link_status(__idx)\
6067 	bf_get(lpfc_acqe_fc_la_trunk_config_port##__idx, acqe_fc) ?\
6068 	       ((phba->trunk_link.link##__idx.state == LPFC_LINK_UP) ?\
6069 		"Link up" : "Link down") : "NA"
6070 /* Did port __idx reported an error */
6071 #define trunk_port_fault(__idx)\
6072 	bf_get(lpfc_acqe_fc_la_trunk_config_port##__idx, acqe_fc) ?\
6073 	       (port_fault & (1 << __idx) ? "YES" : "NO") : "NA"
6074 
6075 static void
6076 lpfc_update_trunk_link_status(struct lpfc_hba *phba,
6077 			      struct lpfc_acqe_fc_la *acqe_fc)
6078 {
6079 	uint8_t port_fault = bf_get(lpfc_acqe_fc_la_trunk_linkmask, acqe_fc);
6080 	uint8_t err = bf_get(lpfc_acqe_fc_la_trunk_fault, acqe_fc);
6081 
6082 	phba->sli4_hba.link_state.speed =
6083 		lpfc_sli4_port_speed_parse(phba, LPFC_TRAILER_CODE_FC,
6084 				bf_get(lpfc_acqe_fc_la_speed, acqe_fc));
6085 
6086 	phba->sli4_hba.link_state.logical_speed =
6087 				bf_get(lpfc_acqe_fc_la_llink_spd, acqe_fc) * 10;
6088 	/* We got FC link speed, convert to fc_linkspeed (READ_TOPOLOGY) */
6089 	phba->fc_linkspeed =
6090 		 lpfc_async_link_speed_to_read_top(
6091 				phba,
6092 				bf_get(lpfc_acqe_fc_la_speed, acqe_fc));
6093 
6094 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port0, acqe_fc)) {
6095 		phba->trunk_link.link0.state =
6096 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port0, acqe_fc)
6097 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
6098 		phba->trunk_link.link0.fault = port_fault & 0x1 ? err : 0;
6099 	}
6100 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port1, acqe_fc)) {
6101 		phba->trunk_link.link1.state =
6102 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port1, acqe_fc)
6103 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
6104 		phba->trunk_link.link1.fault = port_fault & 0x2 ? err : 0;
6105 	}
6106 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port2, acqe_fc)) {
6107 		phba->trunk_link.link2.state =
6108 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port2, acqe_fc)
6109 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
6110 		phba->trunk_link.link2.fault = port_fault & 0x4 ? err : 0;
6111 	}
6112 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port3, acqe_fc)) {
6113 		phba->trunk_link.link3.state =
6114 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port3, acqe_fc)
6115 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
6116 		phba->trunk_link.link3.fault = port_fault & 0x8 ? err : 0;
6117 	}
6118 
6119 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6120 			"2910 Async FC Trunking Event - Speed:%d\n"
6121 			"\tLogical speed:%d "
6122 			"port0: %s port1: %s port2: %s port3: %s\n",
6123 			phba->sli4_hba.link_state.speed,
6124 			phba->sli4_hba.link_state.logical_speed,
6125 			trunk_link_status(0), trunk_link_status(1),
6126 			trunk_link_status(2), trunk_link_status(3));
6127 
6128 	if (phba->cmf_active_mode != LPFC_CFG_OFF)
6129 		lpfc_cmf_signal_init(phba);
6130 
6131 	if (port_fault)
6132 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6133 				"3202 trunk error:0x%x (%s) seen on port0:%s "
6134 				/*
6135 				 * SLI-4: We have only 0xA error codes
6136 				 * defined as of now. print an appropriate
6137 				 * message in case driver needs to be updated.
6138 				 */
6139 				"port1:%s port2:%s port3:%s\n", err, err > 0xA ?
6140 				"UNDEFINED. update driver." : trunk_errmsg[err],
6141 				trunk_port_fault(0), trunk_port_fault(1),
6142 				trunk_port_fault(2), trunk_port_fault(3));
6143 }
6144 
6145 
6146 /**
6147  * lpfc_sli4_async_fc_evt - Process the asynchronous FC link event
6148  * @phba: pointer to lpfc hba data structure.
6149  * @acqe_fc: pointer to the async fc completion queue entry.
6150  *
6151  * This routine is to handle the SLI4 asynchronous FC event. It will simply log
6152  * that the event was received and then issue a read_topology mailbox command so
6153  * that the rest of the driver will treat it the same as SLI3.
6154  **/
6155 static void
6156 lpfc_sli4_async_fc_evt(struct lpfc_hba *phba, struct lpfc_acqe_fc_la *acqe_fc)
6157 {
6158 	struct lpfc_dmabuf *mp;
6159 	LPFC_MBOXQ_t *pmb;
6160 	MAILBOX_t *mb;
6161 	struct lpfc_mbx_read_top *la;
6162 	int rc;
6163 
6164 	if (bf_get(lpfc_trailer_type, acqe_fc) !=
6165 	    LPFC_FC_LA_EVENT_TYPE_FC_LINK) {
6166 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6167 				"2895 Non FC link Event detected.(%d)\n",
6168 				bf_get(lpfc_trailer_type, acqe_fc));
6169 		return;
6170 	}
6171 
6172 	if (bf_get(lpfc_acqe_fc_la_att_type, acqe_fc) ==
6173 	    LPFC_FC_LA_TYPE_TRUNKING_EVENT) {
6174 		lpfc_update_trunk_link_status(phba, acqe_fc);
6175 		return;
6176 	}
6177 
6178 	/* Keep the link status for extra SLI4 state machine reference */
6179 	phba->sli4_hba.link_state.speed =
6180 			lpfc_sli4_port_speed_parse(phba, LPFC_TRAILER_CODE_FC,
6181 				bf_get(lpfc_acqe_fc_la_speed, acqe_fc));
6182 	phba->sli4_hba.link_state.duplex = LPFC_ASYNC_LINK_DUPLEX_FULL;
6183 	phba->sli4_hba.link_state.topology =
6184 				bf_get(lpfc_acqe_fc_la_topology, acqe_fc);
6185 	phba->sli4_hba.link_state.status =
6186 				bf_get(lpfc_acqe_fc_la_att_type, acqe_fc);
6187 	phba->sli4_hba.link_state.type =
6188 				bf_get(lpfc_acqe_fc_la_port_type, acqe_fc);
6189 	phba->sli4_hba.link_state.number =
6190 				bf_get(lpfc_acqe_fc_la_port_number, acqe_fc);
6191 	phba->sli4_hba.link_state.fault =
6192 				bf_get(lpfc_acqe_link_fault, acqe_fc);
6193 
6194 	if (bf_get(lpfc_acqe_fc_la_att_type, acqe_fc) ==
6195 	    LPFC_FC_LA_TYPE_LINK_DOWN)
6196 		phba->sli4_hba.link_state.logical_speed = 0;
6197 	else if	(!phba->sli4_hba.conf_trunk)
6198 		phba->sli4_hba.link_state.logical_speed =
6199 				bf_get(lpfc_acqe_fc_la_llink_spd, acqe_fc) * 10;
6200 
6201 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6202 			"2896 Async FC event - Speed:%dGBaud Topology:x%x "
6203 			"LA Type:x%x Port Type:%d Port Number:%d Logical speed:"
6204 			"%dMbps Fault:%d\n",
6205 			phba->sli4_hba.link_state.speed,
6206 			phba->sli4_hba.link_state.topology,
6207 			phba->sli4_hba.link_state.status,
6208 			phba->sli4_hba.link_state.type,
6209 			phba->sli4_hba.link_state.number,
6210 			phba->sli4_hba.link_state.logical_speed,
6211 			phba->sli4_hba.link_state.fault);
6212 	pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6213 	if (!pmb) {
6214 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6215 				"2897 The mboxq allocation failed\n");
6216 		return;
6217 	}
6218 	mp = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
6219 	if (!mp) {
6220 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6221 				"2898 The lpfc_dmabuf allocation failed\n");
6222 		goto out_free_pmb;
6223 	}
6224 	mp->virt = lpfc_mbuf_alloc(phba, 0, &mp->phys);
6225 	if (!mp->virt) {
6226 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6227 				"2899 The mbuf allocation failed\n");
6228 		goto out_free_dmabuf;
6229 	}
6230 
6231 	/* Cleanup any outstanding ELS commands */
6232 	lpfc_els_flush_all_cmd(phba);
6233 
6234 	/* Block ELS IOCBs until we have done process link event */
6235 	phba->sli4_hba.els_wq->pring->flag |= LPFC_STOP_IOCB_EVENT;
6236 
6237 	/* Update link event statistics */
6238 	phba->sli.slistat.link_event++;
6239 
6240 	/* Create lpfc_handle_latt mailbox command from link ACQE */
6241 	lpfc_read_topology(phba, pmb, mp);
6242 	pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
6243 	pmb->vport = phba->pport;
6244 
6245 	if (phba->sli4_hba.link_state.status != LPFC_FC_LA_TYPE_LINK_UP) {
6246 		phba->link_flag &= ~(LS_MDS_LINK_DOWN | LS_MDS_LOOPBACK);
6247 
6248 		switch (phba->sli4_hba.link_state.status) {
6249 		case LPFC_FC_LA_TYPE_MDS_LINK_DOWN:
6250 			phba->link_flag |= LS_MDS_LINK_DOWN;
6251 			break;
6252 		case LPFC_FC_LA_TYPE_MDS_LOOPBACK:
6253 			phba->link_flag |= LS_MDS_LOOPBACK;
6254 			break;
6255 		default:
6256 			break;
6257 		}
6258 
6259 		/* Initialize completion status */
6260 		mb = &pmb->u.mb;
6261 		mb->mbxStatus = MBX_SUCCESS;
6262 
6263 		/* Parse port fault information field */
6264 		lpfc_sli4_parse_latt_fault(phba, (void *)acqe_fc);
6265 
6266 		/* Parse and translate link attention fields */
6267 		la = (struct lpfc_mbx_read_top *)&pmb->u.mb.un.varReadTop;
6268 		la->eventTag = acqe_fc->event_tag;
6269 
6270 		if (phba->sli4_hba.link_state.status ==
6271 		    LPFC_FC_LA_TYPE_UNEXP_WWPN) {
6272 			bf_set(lpfc_mbx_read_top_att_type, la,
6273 			       LPFC_FC_LA_TYPE_UNEXP_WWPN);
6274 		} else {
6275 			bf_set(lpfc_mbx_read_top_att_type, la,
6276 			       LPFC_FC_LA_TYPE_LINK_DOWN);
6277 		}
6278 		/* Invoke the mailbox command callback function */
6279 		lpfc_mbx_cmpl_read_topology(phba, pmb);
6280 
6281 		return;
6282 	}
6283 
6284 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
6285 	if (rc == MBX_NOT_FINISHED) {
6286 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
6287 		goto out_free_dmabuf;
6288 	}
6289 	return;
6290 
6291 out_free_dmabuf:
6292 	kfree(mp);
6293 out_free_pmb:
6294 	mempool_free(pmb, phba->mbox_mem_pool);
6295 }
6296 
6297 /**
6298  * lpfc_sli4_async_sli_evt - Process the asynchronous SLI link event
6299  * @phba: pointer to lpfc hba data structure.
6300  * @acqe_sli: pointer to the async SLI completion queue entry.
6301  *
6302  * This routine is to handle the SLI4 asynchronous SLI events.
6303  **/
6304 static void
6305 lpfc_sli4_async_sli_evt(struct lpfc_hba *phba, struct lpfc_acqe_sli *acqe_sli)
6306 {
6307 	char port_name;
6308 	char message[128];
6309 	uint8_t status;
6310 	uint8_t evt_type;
6311 	uint8_t operational = 0;
6312 	struct temp_event temp_event_data;
6313 	struct lpfc_acqe_misconfigured_event *misconfigured;
6314 	struct lpfc_acqe_cgn_signal *cgn_signal;
6315 	struct Scsi_Host  *shost;
6316 	struct lpfc_vport **vports;
6317 	int rc, i, cnt;
6318 
6319 	evt_type = bf_get(lpfc_trailer_type, acqe_sli);
6320 
6321 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6322 			"2901 Async SLI event - Type:%d, Event Data: x%08x "
6323 			"x%08x x%08x x%08x\n", evt_type,
6324 			acqe_sli->event_data1, acqe_sli->event_data2,
6325 			acqe_sli->reserved, acqe_sli->trailer);
6326 
6327 	port_name = phba->Port[0];
6328 	if (port_name == 0x00)
6329 		port_name = '?'; /* get port name is empty */
6330 
6331 	switch (evt_type) {
6332 	case LPFC_SLI_EVENT_TYPE_OVER_TEMP:
6333 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
6334 		temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
6335 		temp_event_data.data = (uint32_t)acqe_sli->event_data1;
6336 
6337 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6338 				"3190 Over Temperature:%d Celsius- Port Name %c\n",
6339 				acqe_sli->event_data1, port_name);
6340 
6341 		phba->sfp_warning |= LPFC_TRANSGRESSION_HIGH_TEMPERATURE;
6342 		shost = lpfc_shost_from_vport(phba->pport);
6343 		fc_host_post_vendor_event(shost, fc_get_event_number(),
6344 					  sizeof(temp_event_data),
6345 					  (char *)&temp_event_data,
6346 					  SCSI_NL_VID_TYPE_PCI
6347 					  | PCI_VENDOR_ID_EMULEX);
6348 		break;
6349 	case LPFC_SLI_EVENT_TYPE_NORM_TEMP:
6350 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
6351 		temp_event_data.event_code = LPFC_NORMAL_TEMP;
6352 		temp_event_data.data = (uint32_t)acqe_sli->event_data1;
6353 
6354 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6355 				"3191 Normal Temperature:%d Celsius - Port Name %c\n",
6356 				acqe_sli->event_data1, port_name);
6357 
6358 		shost = lpfc_shost_from_vport(phba->pport);
6359 		fc_host_post_vendor_event(shost, fc_get_event_number(),
6360 					  sizeof(temp_event_data),
6361 					  (char *)&temp_event_data,
6362 					  SCSI_NL_VID_TYPE_PCI
6363 					  | PCI_VENDOR_ID_EMULEX);
6364 		break;
6365 	case LPFC_SLI_EVENT_TYPE_MISCONFIGURED:
6366 		misconfigured = (struct lpfc_acqe_misconfigured_event *)
6367 					&acqe_sli->event_data1;
6368 
6369 		/* fetch the status for this port */
6370 		switch (phba->sli4_hba.lnk_info.lnk_no) {
6371 		case LPFC_LINK_NUMBER_0:
6372 			status = bf_get(lpfc_sli_misconfigured_port0_state,
6373 					&misconfigured->theEvent);
6374 			operational = bf_get(lpfc_sli_misconfigured_port0_op,
6375 					&misconfigured->theEvent);
6376 			break;
6377 		case LPFC_LINK_NUMBER_1:
6378 			status = bf_get(lpfc_sli_misconfigured_port1_state,
6379 					&misconfigured->theEvent);
6380 			operational = bf_get(lpfc_sli_misconfigured_port1_op,
6381 					&misconfigured->theEvent);
6382 			break;
6383 		case LPFC_LINK_NUMBER_2:
6384 			status = bf_get(lpfc_sli_misconfigured_port2_state,
6385 					&misconfigured->theEvent);
6386 			operational = bf_get(lpfc_sli_misconfigured_port2_op,
6387 					&misconfigured->theEvent);
6388 			break;
6389 		case LPFC_LINK_NUMBER_3:
6390 			status = bf_get(lpfc_sli_misconfigured_port3_state,
6391 					&misconfigured->theEvent);
6392 			operational = bf_get(lpfc_sli_misconfigured_port3_op,
6393 					&misconfigured->theEvent);
6394 			break;
6395 		default:
6396 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6397 					"3296 "
6398 					"LPFC_SLI_EVENT_TYPE_MISCONFIGURED "
6399 					"event: Invalid link %d",
6400 					phba->sli4_hba.lnk_info.lnk_no);
6401 			return;
6402 		}
6403 
6404 		/* Skip if optic state unchanged */
6405 		if (phba->sli4_hba.lnk_info.optic_state == status)
6406 			return;
6407 
6408 		switch (status) {
6409 		case LPFC_SLI_EVENT_STATUS_VALID:
6410 			sprintf(message, "Physical Link is functional");
6411 			break;
6412 		case LPFC_SLI_EVENT_STATUS_NOT_PRESENT:
6413 			sprintf(message, "Optics faulted/incorrectly "
6414 				"installed/not installed - Reseat optics, "
6415 				"if issue not resolved, replace.");
6416 			break;
6417 		case LPFC_SLI_EVENT_STATUS_WRONG_TYPE:
6418 			sprintf(message,
6419 				"Optics of two types installed - Remove one "
6420 				"optic or install matching pair of optics.");
6421 			break;
6422 		case LPFC_SLI_EVENT_STATUS_UNSUPPORTED:
6423 			sprintf(message, "Incompatible optics - Replace with "
6424 				"compatible optics for card to function.");
6425 			break;
6426 		case LPFC_SLI_EVENT_STATUS_UNQUALIFIED:
6427 			sprintf(message, "Unqualified optics - Replace with "
6428 				"Avago optics for Warranty and Technical "
6429 				"Support - Link is%s operational",
6430 				(operational) ? " not" : "");
6431 			break;
6432 		case LPFC_SLI_EVENT_STATUS_UNCERTIFIED:
6433 			sprintf(message, "Uncertified optics - Replace with "
6434 				"Avago-certified optics to enable link "
6435 				"operation - Link is%s operational",
6436 				(operational) ? " not" : "");
6437 			break;
6438 		default:
6439 			/* firmware is reporting a status we don't know about */
6440 			sprintf(message, "Unknown event status x%02x", status);
6441 			break;
6442 		}
6443 
6444 		/* Issue READ_CONFIG mbox command to refresh supported speeds */
6445 		rc = lpfc_sli4_read_config(phba);
6446 		if (rc) {
6447 			phba->lmt = 0;
6448 			lpfc_printf_log(phba, KERN_ERR,
6449 					LOG_TRACE_EVENT,
6450 					"3194 Unable to retrieve supported "
6451 					"speeds, rc = 0x%x\n", rc);
6452 		}
6453 		vports = lpfc_create_vport_work_array(phba);
6454 		if (vports != NULL) {
6455 			for (i = 0; i <= phba->max_vports && vports[i] != NULL;
6456 					i++) {
6457 				shost = lpfc_shost_from_vport(vports[i]);
6458 				lpfc_host_supported_speeds_set(shost);
6459 			}
6460 		}
6461 		lpfc_destroy_vport_work_array(phba, vports);
6462 
6463 		phba->sli4_hba.lnk_info.optic_state = status;
6464 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6465 				"3176 Port Name %c %s\n", port_name, message);
6466 		break;
6467 	case LPFC_SLI_EVENT_TYPE_REMOTE_DPORT:
6468 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6469 				"3192 Remote DPort Test Initiated - "
6470 				"Event Data1:x%08x Event Data2: x%08x\n",
6471 				acqe_sli->event_data1, acqe_sli->event_data2);
6472 		break;
6473 	case LPFC_SLI_EVENT_TYPE_PORT_PARAMS_CHG:
6474 		/* Call FW to obtain active parms */
6475 		lpfc_sli4_cgn_parm_chg_evt(phba);
6476 		break;
6477 	case LPFC_SLI_EVENT_TYPE_MISCONF_FAWWN:
6478 		/* Misconfigured WWN. Reports that the SLI Port is configured
6479 		 * to use FA-WWN, but the attached device doesn’t support it.
6480 		 * No driver action is required.
6481 		 * Event Data1 - N.A, Event Data2 - N.A
6482 		 */
6483 		lpfc_log_msg(phba, KERN_WARNING, LOG_SLI,
6484 			     "2699 Misconfigured FA-WWN - Attached device does "
6485 			     "not support FA-WWN\n");
6486 		break;
6487 	case LPFC_SLI_EVENT_TYPE_EEPROM_FAILURE:
6488 		/* EEPROM failure. No driver action is required */
6489 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6490 			     "2518 EEPROM failure - "
6491 			     "Event Data1: x%08x Event Data2: x%08x\n",
6492 			     acqe_sli->event_data1, acqe_sli->event_data2);
6493 		break;
6494 	case LPFC_SLI_EVENT_TYPE_CGN_SIGNAL:
6495 		if (phba->cmf_active_mode == LPFC_CFG_OFF)
6496 			break;
6497 		cgn_signal = (struct lpfc_acqe_cgn_signal *)
6498 					&acqe_sli->event_data1;
6499 		phba->cgn_acqe_cnt++;
6500 
6501 		cnt = bf_get(lpfc_warn_acqe, cgn_signal);
6502 		atomic64_add(cnt, &phba->cgn_acqe_stat.warn);
6503 		atomic64_add(cgn_signal->alarm_cnt, &phba->cgn_acqe_stat.alarm);
6504 
6505 		/* no threshold for CMF, even 1 signal will trigger an event */
6506 
6507 		/* Alarm overrides warning, so check that first */
6508 		if (cgn_signal->alarm_cnt) {
6509 			if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
6510 				/* Keep track of alarm cnt for CMF_SYNC_WQE */
6511 				atomic_add(cgn_signal->alarm_cnt,
6512 					   &phba->cgn_sync_alarm_cnt);
6513 			}
6514 		} else if (cnt) {
6515 			/* signal action needs to be taken */
6516 			if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY ||
6517 			    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
6518 				/* Keep track of warning cnt for CMF_SYNC_WQE */
6519 				atomic_add(cnt, &phba->cgn_sync_warn_cnt);
6520 			}
6521 		}
6522 		break;
6523 	default:
6524 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6525 				"3193 Unrecognized SLI event, type: 0x%x",
6526 				evt_type);
6527 		break;
6528 	}
6529 }
6530 
6531 /**
6532  * lpfc_sli4_perform_vport_cvl - Perform clear virtual link on a vport
6533  * @vport: pointer to vport data structure.
6534  *
6535  * This routine is to perform Clear Virtual Link (CVL) on a vport in
6536  * response to a CVL event.
6537  *
6538  * Return the pointer to the ndlp with the vport if successful, otherwise
6539  * return NULL.
6540  **/
6541 static struct lpfc_nodelist *
6542 lpfc_sli4_perform_vport_cvl(struct lpfc_vport *vport)
6543 {
6544 	struct lpfc_nodelist *ndlp;
6545 	struct Scsi_Host *shost;
6546 	struct lpfc_hba *phba;
6547 
6548 	if (!vport)
6549 		return NULL;
6550 	phba = vport->phba;
6551 	if (!phba)
6552 		return NULL;
6553 	ndlp = lpfc_findnode_did(vport, Fabric_DID);
6554 	if (!ndlp) {
6555 		/* Cannot find existing Fabric ndlp, so allocate a new one */
6556 		ndlp = lpfc_nlp_init(vport, Fabric_DID);
6557 		if (!ndlp)
6558 			return 0;
6559 		/* Set the node type */
6560 		ndlp->nlp_type |= NLP_FABRIC;
6561 		/* Put ndlp onto node list */
6562 		lpfc_enqueue_node(vport, ndlp);
6563 	}
6564 	if ((phba->pport->port_state < LPFC_FLOGI) &&
6565 		(phba->pport->port_state != LPFC_VPORT_FAILED))
6566 		return NULL;
6567 	/* If virtual link is not yet instantiated ignore CVL */
6568 	if ((vport != phba->pport) && (vport->port_state < LPFC_FDISC)
6569 		&& (vport->port_state != LPFC_VPORT_FAILED))
6570 		return NULL;
6571 	shost = lpfc_shost_from_vport(vport);
6572 	if (!shost)
6573 		return NULL;
6574 	lpfc_linkdown_port(vport);
6575 	lpfc_cleanup_pending_mbox(vport);
6576 	spin_lock_irq(shost->host_lock);
6577 	vport->fc_flag |= FC_VPORT_CVL_RCVD;
6578 	spin_unlock_irq(shost->host_lock);
6579 
6580 	return ndlp;
6581 }
6582 
6583 /**
6584  * lpfc_sli4_perform_all_vport_cvl - Perform clear virtual link on all vports
6585  * @phba: pointer to lpfc hba data structure.
6586  *
6587  * This routine is to perform Clear Virtual Link (CVL) on all vports in
6588  * response to a FCF dead event.
6589  **/
6590 static void
6591 lpfc_sli4_perform_all_vport_cvl(struct lpfc_hba *phba)
6592 {
6593 	struct lpfc_vport **vports;
6594 	int i;
6595 
6596 	vports = lpfc_create_vport_work_array(phba);
6597 	if (vports)
6598 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++)
6599 			lpfc_sli4_perform_vport_cvl(vports[i]);
6600 	lpfc_destroy_vport_work_array(phba, vports);
6601 }
6602 
6603 /**
6604  * lpfc_sli4_async_fip_evt - Process the asynchronous FCoE FIP event
6605  * @phba: pointer to lpfc hba data structure.
6606  * @acqe_fip: pointer to the async fcoe completion queue entry.
6607  *
6608  * This routine is to handle the SLI4 asynchronous fcoe event.
6609  **/
6610 static void
6611 lpfc_sli4_async_fip_evt(struct lpfc_hba *phba,
6612 			struct lpfc_acqe_fip *acqe_fip)
6613 {
6614 	uint8_t event_type = bf_get(lpfc_trailer_type, acqe_fip);
6615 	int rc;
6616 	struct lpfc_vport *vport;
6617 	struct lpfc_nodelist *ndlp;
6618 	int active_vlink_present;
6619 	struct lpfc_vport **vports;
6620 	int i;
6621 
6622 	phba->fc_eventTag = acqe_fip->event_tag;
6623 	phba->fcoe_eventtag = acqe_fip->event_tag;
6624 	switch (event_type) {
6625 	case LPFC_FIP_EVENT_TYPE_NEW_FCF:
6626 	case LPFC_FIP_EVENT_TYPE_FCF_PARAM_MOD:
6627 		if (event_type == LPFC_FIP_EVENT_TYPE_NEW_FCF)
6628 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6629 					"2546 New FCF event, evt_tag:x%x, "
6630 					"index:x%x\n",
6631 					acqe_fip->event_tag,
6632 					acqe_fip->index);
6633 		else
6634 			lpfc_printf_log(phba, KERN_WARNING, LOG_FIP |
6635 					LOG_DISCOVERY,
6636 					"2788 FCF param modified event, "
6637 					"evt_tag:x%x, index:x%x\n",
6638 					acqe_fip->event_tag,
6639 					acqe_fip->index);
6640 		if (phba->fcf.fcf_flag & FCF_DISCOVERY) {
6641 			/*
6642 			 * During period of FCF discovery, read the FCF
6643 			 * table record indexed by the event to update
6644 			 * FCF roundrobin failover eligible FCF bmask.
6645 			 */
6646 			lpfc_printf_log(phba, KERN_INFO, LOG_FIP |
6647 					LOG_DISCOVERY,
6648 					"2779 Read FCF (x%x) for updating "
6649 					"roundrobin FCF failover bmask\n",
6650 					acqe_fip->index);
6651 			rc = lpfc_sli4_read_fcf_rec(phba, acqe_fip->index);
6652 		}
6653 
6654 		/* If the FCF discovery is in progress, do nothing. */
6655 		spin_lock_irq(&phba->hbalock);
6656 		if (phba->hba_flag & FCF_TS_INPROG) {
6657 			spin_unlock_irq(&phba->hbalock);
6658 			break;
6659 		}
6660 		/* If fast FCF failover rescan event is pending, do nothing */
6661 		if (phba->fcf.fcf_flag & (FCF_REDISC_EVT | FCF_REDISC_PEND)) {
6662 			spin_unlock_irq(&phba->hbalock);
6663 			break;
6664 		}
6665 
6666 		/* If the FCF has been in discovered state, do nothing. */
6667 		if (phba->fcf.fcf_flag & FCF_SCAN_DONE) {
6668 			spin_unlock_irq(&phba->hbalock);
6669 			break;
6670 		}
6671 		spin_unlock_irq(&phba->hbalock);
6672 
6673 		/* Otherwise, scan the entire FCF table and re-discover SAN */
6674 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
6675 				"2770 Start FCF table scan per async FCF "
6676 				"event, evt_tag:x%x, index:x%x\n",
6677 				acqe_fip->event_tag, acqe_fip->index);
6678 		rc = lpfc_sli4_fcf_scan_read_fcf_rec(phba,
6679 						     LPFC_FCOE_FCF_GET_FIRST);
6680 		if (rc)
6681 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6682 					"2547 Issue FCF scan read FCF mailbox "
6683 					"command failed (x%x)\n", rc);
6684 		break;
6685 
6686 	case LPFC_FIP_EVENT_TYPE_FCF_TABLE_FULL:
6687 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6688 				"2548 FCF Table full count 0x%x tag 0x%x\n",
6689 				bf_get(lpfc_acqe_fip_fcf_count, acqe_fip),
6690 				acqe_fip->event_tag);
6691 		break;
6692 
6693 	case LPFC_FIP_EVENT_TYPE_FCF_DEAD:
6694 		phba->fcoe_cvl_eventtag = acqe_fip->event_tag;
6695 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6696 				"2549 FCF (x%x) disconnected from network, "
6697 				 "tag:x%x\n", acqe_fip->index,
6698 				 acqe_fip->event_tag);
6699 		/*
6700 		 * If we are in the middle of FCF failover process, clear
6701 		 * the corresponding FCF bit in the roundrobin bitmap.
6702 		 */
6703 		spin_lock_irq(&phba->hbalock);
6704 		if ((phba->fcf.fcf_flag & FCF_DISCOVERY) &&
6705 		    (phba->fcf.current_rec.fcf_indx != acqe_fip->index)) {
6706 			spin_unlock_irq(&phba->hbalock);
6707 			/* Update FLOGI FCF failover eligible FCF bmask */
6708 			lpfc_sli4_fcf_rr_index_clear(phba, acqe_fip->index);
6709 			break;
6710 		}
6711 		spin_unlock_irq(&phba->hbalock);
6712 
6713 		/* If the event is not for currently used fcf do nothing */
6714 		if (phba->fcf.current_rec.fcf_indx != acqe_fip->index)
6715 			break;
6716 
6717 		/*
6718 		 * Otherwise, request the port to rediscover the entire FCF
6719 		 * table for a fast recovery from case that the current FCF
6720 		 * is no longer valid as we are not in the middle of FCF
6721 		 * failover process already.
6722 		 */
6723 		spin_lock_irq(&phba->hbalock);
6724 		/* Mark the fast failover process in progress */
6725 		phba->fcf.fcf_flag |= FCF_DEAD_DISC;
6726 		spin_unlock_irq(&phba->hbalock);
6727 
6728 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
6729 				"2771 Start FCF fast failover process due to "
6730 				"FCF DEAD event: evt_tag:x%x, fcf_index:x%x "
6731 				"\n", acqe_fip->event_tag, acqe_fip->index);
6732 		rc = lpfc_sli4_redisc_fcf_table(phba);
6733 		if (rc) {
6734 			lpfc_printf_log(phba, KERN_ERR, LOG_FIP |
6735 					LOG_TRACE_EVENT,
6736 					"2772 Issue FCF rediscover mailbox "
6737 					"command failed, fail through to FCF "
6738 					"dead event\n");
6739 			spin_lock_irq(&phba->hbalock);
6740 			phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
6741 			spin_unlock_irq(&phba->hbalock);
6742 			/*
6743 			 * Last resort will fail over by treating this
6744 			 * as a link down to FCF registration.
6745 			 */
6746 			lpfc_sli4_fcf_dead_failthrough(phba);
6747 		} else {
6748 			/* Reset FCF roundrobin bmask for new discovery */
6749 			lpfc_sli4_clear_fcf_rr_bmask(phba);
6750 			/*
6751 			 * Handling fast FCF failover to a DEAD FCF event is
6752 			 * considered equalivant to receiving CVL to all vports.
6753 			 */
6754 			lpfc_sli4_perform_all_vport_cvl(phba);
6755 		}
6756 		break;
6757 	case LPFC_FIP_EVENT_TYPE_CVL:
6758 		phba->fcoe_cvl_eventtag = acqe_fip->event_tag;
6759 		lpfc_printf_log(phba, KERN_ERR,
6760 				LOG_TRACE_EVENT,
6761 			"2718 Clear Virtual Link Received for VPI 0x%x"
6762 			" tag 0x%x\n", acqe_fip->index, acqe_fip->event_tag);
6763 
6764 		vport = lpfc_find_vport_by_vpid(phba,
6765 						acqe_fip->index);
6766 		ndlp = lpfc_sli4_perform_vport_cvl(vport);
6767 		if (!ndlp)
6768 			break;
6769 		active_vlink_present = 0;
6770 
6771 		vports = lpfc_create_vport_work_array(phba);
6772 		if (vports) {
6773 			for (i = 0; i <= phba->max_vports && vports[i] != NULL;
6774 					i++) {
6775 				if ((!(vports[i]->fc_flag &
6776 					FC_VPORT_CVL_RCVD)) &&
6777 					(vports[i]->port_state > LPFC_FDISC)) {
6778 					active_vlink_present = 1;
6779 					break;
6780 				}
6781 			}
6782 			lpfc_destroy_vport_work_array(phba, vports);
6783 		}
6784 
6785 		/*
6786 		 * Don't re-instantiate if vport is marked for deletion.
6787 		 * If we are here first then vport_delete is going to wait
6788 		 * for discovery to complete.
6789 		 */
6790 		if (!(vport->load_flag & FC_UNLOADING) &&
6791 					active_vlink_present) {
6792 			/*
6793 			 * If there are other active VLinks present,
6794 			 * re-instantiate the Vlink using FDISC.
6795 			 */
6796 			mod_timer(&ndlp->nlp_delayfunc,
6797 				  jiffies + msecs_to_jiffies(1000));
6798 			spin_lock_irq(&ndlp->lock);
6799 			ndlp->nlp_flag |= NLP_DELAY_TMO;
6800 			spin_unlock_irq(&ndlp->lock);
6801 			ndlp->nlp_last_elscmd = ELS_CMD_FDISC;
6802 			vport->port_state = LPFC_FDISC;
6803 		} else {
6804 			/*
6805 			 * Otherwise, we request port to rediscover
6806 			 * the entire FCF table for a fast recovery
6807 			 * from possible case that the current FCF
6808 			 * is no longer valid if we are not already
6809 			 * in the FCF failover process.
6810 			 */
6811 			spin_lock_irq(&phba->hbalock);
6812 			if (phba->fcf.fcf_flag & FCF_DISCOVERY) {
6813 				spin_unlock_irq(&phba->hbalock);
6814 				break;
6815 			}
6816 			/* Mark the fast failover process in progress */
6817 			phba->fcf.fcf_flag |= FCF_ACVL_DISC;
6818 			spin_unlock_irq(&phba->hbalock);
6819 			lpfc_printf_log(phba, KERN_INFO, LOG_FIP |
6820 					LOG_DISCOVERY,
6821 					"2773 Start FCF failover per CVL, "
6822 					"evt_tag:x%x\n", acqe_fip->event_tag);
6823 			rc = lpfc_sli4_redisc_fcf_table(phba);
6824 			if (rc) {
6825 				lpfc_printf_log(phba, KERN_ERR, LOG_FIP |
6826 						LOG_TRACE_EVENT,
6827 						"2774 Issue FCF rediscover "
6828 						"mailbox command failed, "
6829 						"through to CVL event\n");
6830 				spin_lock_irq(&phba->hbalock);
6831 				phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
6832 				spin_unlock_irq(&phba->hbalock);
6833 				/*
6834 				 * Last resort will be re-try on the
6835 				 * the current registered FCF entry.
6836 				 */
6837 				lpfc_retry_pport_discovery(phba);
6838 			} else
6839 				/*
6840 				 * Reset FCF roundrobin bmask for new
6841 				 * discovery.
6842 				 */
6843 				lpfc_sli4_clear_fcf_rr_bmask(phba);
6844 		}
6845 		break;
6846 	default:
6847 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6848 				"0288 Unknown FCoE event type 0x%x event tag "
6849 				"0x%x\n", event_type, acqe_fip->event_tag);
6850 		break;
6851 	}
6852 }
6853 
6854 /**
6855  * lpfc_sli4_async_dcbx_evt - Process the asynchronous dcbx event
6856  * @phba: pointer to lpfc hba data structure.
6857  * @acqe_dcbx: pointer to the async dcbx completion queue entry.
6858  *
6859  * This routine is to handle the SLI4 asynchronous dcbx event.
6860  **/
6861 static void
6862 lpfc_sli4_async_dcbx_evt(struct lpfc_hba *phba,
6863 			 struct lpfc_acqe_dcbx *acqe_dcbx)
6864 {
6865 	phba->fc_eventTag = acqe_dcbx->event_tag;
6866 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6867 			"0290 The SLI4 DCBX asynchronous event is not "
6868 			"handled yet\n");
6869 }
6870 
6871 /**
6872  * lpfc_sli4_async_grp5_evt - Process the asynchronous group5 event
6873  * @phba: pointer to lpfc hba data structure.
6874  * @acqe_grp5: pointer to the async grp5 completion queue entry.
6875  *
6876  * This routine is to handle the SLI4 asynchronous grp5 event. A grp5 event
6877  * is an asynchronous notified of a logical link speed change.  The Port
6878  * reports the logical link speed in units of 10Mbps.
6879  **/
6880 static void
6881 lpfc_sli4_async_grp5_evt(struct lpfc_hba *phba,
6882 			 struct lpfc_acqe_grp5 *acqe_grp5)
6883 {
6884 	uint16_t prev_ll_spd;
6885 
6886 	phba->fc_eventTag = acqe_grp5->event_tag;
6887 	phba->fcoe_eventtag = acqe_grp5->event_tag;
6888 	prev_ll_spd = phba->sli4_hba.link_state.logical_speed;
6889 	phba->sli4_hba.link_state.logical_speed =
6890 		(bf_get(lpfc_acqe_grp5_llink_spd, acqe_grp5)) * 10;
6891 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6892 			"2789 GRP5 Async Event: Updating logical link speed "
6893 			"from %dMbps to %dMbps\n", prev_ll_spd,
6894 			phba->sli4_hba.link_state.logical_speed);
6895 }
6896 
6897 /**
6898  * lpfc_sli4_async_cmstat_evt - Process the asynchronous cmstat event
6899  * @phba: pointer to lpfc hba data structure.
6900  *
6901  * This routine is to handle the SLI4 asynchronous cmstat event. A cmstat event
6902  * is an asynchronous notification of a request to reset CM stats.
6903  **/
6904 static void
6905 lpfc_sli4_async_cmstat_evt(struct lpfc_hba *phba)
6906 {
6907 	if (!phba->cgn_i)
6908 		return;
6909 	lpfc_init_congestion_stat(phba);
6910 }
6911 
6912 /**
6913  * lpfc_cgn_params_val - Validate FW congestion parameters.
6914  * @phba: pointer to lpfc hba data structure.
6915  * @p_cfg_param: pointer to FW provided congestion parameters.
6916  *
6917  * This routine validates the congestion parameters passed
6918  * by the FW to the driver via an ACQE event.
6919  **/
6920 static void
6921 lpfc_cgn_params_val(struct lpfc_hba *phba, struct lpfc_cgn_param *p_cfg_param)
6922 {
6923 	spin_lock_irq(&phba->hbalock);
6924 
6925 	if (!lpfc_rangecheck(p_cfg_param->cgn_param_mode, LPFC_CFG_OFF,
6926 			     LPFC_CFG_MONITOR)) {
6927 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT,
6928 				"6225 CMF mode param out of range: %d\n",
6929 				 p_cfg_param->cgn_param_mode);
6930 		p_cfg_param->cgn_param_mode = LPFC_CFG_OFF;
6931 	}
6932 
6933 	spin_unlock_irq(&phba->hbalock);
6934 }
6935 
6936 /**
6937  * lpfc_cgn_params_parse - Process a FW cong parm change event
6938  * @phba: pointer to lpfc hba data structure.
6939  * @p_cgn_param: pointer to a data buffer with the FW cong params.
6940  * @len: the size of pdata in bytes.
6941  *
6942  * This routine validates the congestion management buffer signature
6943  * from the FW, validates the contents and makes corrections for
6944  * valid, in-range values.  If the signature magic is correct and
6945  * after parameter validation, the contents are copied to the driver's
6946  * @phba structure. If the magic is incorrect, an error message is
6947  * logged.
6948  **/
6949 static void
6950 lpfc_cgn_params_parse(struct lpfc_hba *phba,
6951 		      struct lpfc_cgn_param *p_cgn_param, uint32_t len)
6952 {
6953 	struct lpfc_cgn_info *cp;
6954 	uint32_t crc, oldmode;
6955 
6956 	/* Make sure the FW has encoded the correct magic number to
6957 	 * validate the congestion parameter in FW memory.
6958 	 */
6959 	if (p_cgn_param->cgn_param_magic == LPFC_CFG_PARAM_MAGIC_NUM) {
6960 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT | LOG_INIT,
6961 				"4668 FW cgn parm buffer data: "
6962 				"magic 0x%x version %d mode %d "
6963 				"level0 %d level1 %d "
6964 				"level2 %d byte13 %d "
6965 				"byte14 %d byte15 %d "
6966 				"byte11 %d byte12 %d activeMode %d\n",
6967 				p_cgn_param->cgn_param_magic,
6968 				p_cgn_param->cgn_param_version,
6969 				p_cgn_param->cgn_param_mode,
6970 				p_cgn_param->cgn_param_level0,
6971 				p_cgn_param->cgn_param_level1,
6972 				p_cgn_param->cgn_param_level2,
6973 				p_cgn_param->byte13,
6974 				p_cgn_param->byte14,
6975 				p_cgn_param->byte15,
6976 				p_cgn_param->byte11,
6977 				p_cgn_param->byte12,
6978 				phba->cmf_active_mode);
6979 
6980 		oldmode = phba->cmf_active_mode;
6981 
6982 		/* Any parameters out of range are corrected to defaults
6983 		 * by this routine.  No need to fail.
6984 		 */
6985 		lpfc_cgn_params_val(phba, p_cgn_param);
6986 
6987 		/* Parameters are verified, move them into driver storage */
6988 		spin_lock_irq(&phba->hbalock);
6989 		memcpy(&phba->cgn_p, p_cgn_param,
6990 		       sizeof(struct lpfc_cgn_param));
6991 
6992 		/* Update parameters in congestion info buffer now */
6993 		if (phba->cgn_i) {
6994 			cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
6995 			cp->cgn_info_mode = phba->cgn_p.cgn_param_mode;
6996 			cp->cgn_info_level0 = phba->cgn_p.cgn_param_level0;
6997 			cp->cgn_info_level1 = phba->cgn_p.cgn_param_level1;
6998 			cp->cgn_info_level2 = phba->cgn_p.cgn_param_level2;
6999 			crc = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ,
7000 						  LPFC_CGN_CRC32_SEED);
7001 			cp->cgn_info_crc = cpu_to_le32(crc);
7002 		}
7003 		spin_unlock_irq(&phba->hbalock);
7004 
7005 		phba->cmf_active_mode = phba->cgn_p.cgn_param_mode;
7006 
7007 		switch (oldmode) {
7008 		case LPFC_CFG_OFF:
7009 			if (phba->cgn_p.cgn_param_mode != LPFC_CFG_OFF) {
7010 				/* Turning CMF on */
7011 				lpfc_cmf_start(phba);
7012 
7013 				if (phba->link_state >= LPFC_LINK_UP) {
7014 					phba->cgn_reg_fpin =
7015 						phba->cgn_init_reg_fpin;
7016 					phba->cgn_reg_signal =
7017 						phba->cgn_init_reg_signal;
7018 					lpfc_issue_els_edc(phba->pport, 0);
7019 				}
7020 			}
7021 			break;
7022 		case LPFC_CFG_MANAGED:
7023 			switch (phba->cgn_p.cgn_param_mode) {
7024 			case LPFC_CFG_OFF:
7025 				/* Turning CMF off */
7026 				lpfc_cmf_stop(phba);
7027 				if (phba->link_state >= LPFC_LINK_UP)
7028 					lpfc_issue_els_edc(phba->pport, 0);
7029 				break;
7030 			case LPFC_CFG_MONITOR:
7031 				lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
7032 						"4661 Switch from MANAGED to "
7033 						"`MONITOR mode\n");
7034 				phba->cmf_max_bytes_per_interval =
7035 					phba->cmf_link_byte_count;
7036 
7037 				/* Resume blocked IO - unblock on workqueue */
7038 				queue_work(phba->wq,
7039 					   &phba->unblock_request_work);
7040 				break;
7041 			}
7042 			break;
7043 		case LPFC_CFG_MONITOR:
7044 			switch (phba->cgn_p.cgn_param_mode) {
7045 			case LPFC_CFG_OFF:
7046 				/* Turning CMF off */
7047 				lpfc_cmf_stop(phba);
7048 				if (phba->link_state >= LPFC_LINK_UP)
7049 					lpfc_issue_els_edc(phba->pport, 0);
7050 				break;
7051 			case LPFC_CFG_MANAGED:
7052 				lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
7053 						"4662 Switch from MONITOR to "
7054 						"MANAGED mode\n");
7055 				lpfc_cmf_signal_init(phba);
7056 				break;
7057 			}
7058 			break;
7059 		}
7060 	} else {
7061 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7062 				"4669 FW cgn parm buf wrong magic 0x%x "
7063 				"version %d\n", p_cgn_param->cgn_param_magic,
7064 				p_cgn_param->cgn_param_version);
7065 	}
7066 }
7067 
7068 /**
7069  * lpfc_sli4_cgn_params_read - Read and Validate FW congestion parameters.
7070  * @phba: pointer to lpfc hba data structure.
7071  *
7072  * This routine issues a read_object mailbox command to
7073  * get the congestion management parameters from the FW
7074  * parses it and updates the driver maintained values.
7075  *
7076  * Returns
7077  *  0     if the object was empty
7078  *  -Eval if an error was encountered
7079  *  Count if bytes were read from object
7080  **/
7081 int
7082 lpfc_sli4_cgn_params_read(struct lpfc_hba *phba)
7083 {
7084 	int ret = 0;
7085 	struct lpfc_cgn_param *p_cgn_param = NULL;
7086 	u32 *pdata = NULL;
7087 	u32 len = 0;
7088 
7089 	/* Find out if the FW has a new set of congestion parameters. */
7090 	len = sizeof(struct lpfc_cgn_param);
7091 	pdata = kzalloc(len, GFP_KERNEL);
7092 	ret = lpfc_read_object(phba, (char *)LPFC_PORT_CFG_NAME,
7093 			       pdata, len);
7094 
7095 	/* 0 means no data.  A negative means error.  A positive means
7096 	 * bytes were copied.
7097 	 */
7098 	if (!ret) {
7099 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7100 				"4670 CGN RD OBJ returns no data\n");
7101 		goto rd_obj_err;
7102 	} else if (ret < 0) {
7103 		/* Some error.  Just exit and return it to the caller.*/
7104 		goto rd_obj_err;
7105 	}
7106 
7107 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT | LOG_INIT,
7108 			"6234 READ CGN PARAMS Successful %d\n", len);
7109 
7110 	/* Parse data pointer over len and update the phba congestion
7111 	 * parameters with values passed back.  The receive rate values
7112 	 * may have been altered in FW, but take no action here.
7113 	 */
7114 	p_cgn_param = (struct lpfc_cgn_param *)pdata;
7115 	lpfc_cgn_params_parse(phba, p_cgn_param, len);
7116 
7117  rd_obj_err:
7118 	kfree(pdata);
7119 	return ret;
7120 }
7121 
7122 /**
7123  * lpfc_sli4_cgn_parm_chg_evt - Process a FW congestion param change event
7124  * @phba: pointer to lpfc hba data structure.
7125  *
7126  * The FW generated Async ACQE SLI event calls this routine when
7127  * the event type is an SLI Internal Port Event and the Event Code
7128  * indicates a change to the FW maintained congestion parameters.
7129  *
7130  * This routine executes a Read_Object mailbox call to obtain the
7131  * current congestion parameters maintained in FW and corrects
7132  * the driver's active congestion parameters.
7133  *
7134  * The acqe event is not passed because there is no further data
7135  * required.
7136  *
7137  * Returns nonzero error if event processing encountered an error.
7138  * Zero otherwise for success.
7139  **/
7140 static int
7141 lpfc_sli4_cgn_parm_chg_evt(struct lpfc_hba *phba)
7142 {
7143 	int ret = 0;
7144 
7145 	if (!phba->sli4_hba.pc_sli4_params.cmf) {
7146 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7147 				"4664 Cgn Evt when E2E off. Drop event\n");
7148 		return -EACCES;
7149 	}
7150 
7151 	/* If the event is claiming an empty object, it's ok.  A write
7152 	 * could have cleared it.  Only error is a negative return
7153 	 * status.
7154 	 */
7155 	ret = lpfc_sli4_cgn_params_read(phba);
7156 	if (ret < 0) {
7157 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7158 				"4667 Error reading Cgn Params (%d)\n",
7159 				ret);
7160 	} else if (!ret) {
7161 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7162 				"4673 CGN Event empty object.\n");
7163 	}
7164 	return ret;
7165 }
7166 
7167 /**
7168  * lpfc_sli4_async_event_proc - Process all the pending asynchronous event
7169  * @phba: pointer to lpfc hba data structure.
7170  *
7171  * This routine is invoked by the worker thread to process all the pending
7172  * SLI4 asynchronous events.
7173  **/
7174 void lpfc_sli4_async_event_proc(struct lpfc_hba *phba)
7175 {
7176 	struct lpfc_cq_event *cq_event;
7177 	unsigned long iflags;
7178 
7179 	/* First, declare the async event has been handled */
7180 	spin_lock_irqsave(&phba->hbalock, iflags);
7181 	phba->hba_flag &= ~ASYNC_EVENT;
7182 	spin_unlock_irqrestore(&phba->hbalock, iflags);
7183 
7184 	/* Now, handle all the async events */
7185 	spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
7186 	while (!list_empty(&phba->sli4_hba.sp_asynce_work_queue)) {
7187 		list_remove_head(&phba->sli4_hba.sp_asynce_work_queue,
7188 				 cq_event, struct lpfc_cq_event, list);
7189 		spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock,
7190 				       iflags);
7191 
7192 		/* Process the asynchronous event */
7193 		switch (bf_get(lpfc_trailer_code, &cq_event->cqe.mcqe_cmpl)) {
7194 		case LPFC_TRAILER_CODE_LINK:
7195 			lpfc_sli4_async_link_evt(phba,
7196 						 &cq_event->cqe.acqe_link);
7197 			break;
7198 		case LPFC_TRAILER_CODE_FCOE:
7199 			lpfc_sli4_async_fip_evt(phba, &cq_event->cqe.acqe_fip);
7200 			break;
7201 		case LPFC_TRAILER_CODE_DCBX:
7202 			lpfc_sli4_async_dcbx_evt(phba,
7203 						 &cq_event->cqe.acqe_dcbx);
7204 			break;
7205 		case LPFC_TRAILER_CODE_GRP5:
7206 			lpfc_sli4_async_grp5_evt(phba,
7207 						 &cq_event->cqe.acqe_grp5);
7208 			break;
7209 		case LPFC_TRAILER_CODE_FC:
7210 			lpfc_sli4_async_fc_evt(phba, &cq_event->cqe.acqe_fc);
7211 			break;
7212 		case LPFC_TRAILER_CODE_SLI:
7213 			lpfc_sli4_async_sli_evt(phba, &cq_event->cqe.acqe_sli);
7214 			break;
7215 		case LPFC_TRAILER_CODE_CMSTAT:
7216 			lpfc_sli4_async_cmstat_evt(phba);
7217 			break;
7218 		default:
7219 			lpfc_printf_log(phba, KERN_ERR,
7220 					LOG_TRACE_EVENT,
7221 					"1804 Invalid asynchronous event code: "
7222 					"x%x\n", bf_get(lpfc_trailer_code,
7223 					&cq_event->cqe.mcqe_cmpl));
7224 			break;
7225 		}
7226 
7227 		/* Free the completion event processed to the free pool */
7228 		lpfc_sli4_cq_event_release(phba, cq_event);
7229 		spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
7230 	}
7231 	spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock, iflags);
7232 }
7233 
7234 /**
7235  * lpfc_sli4_fcf_redisc_event_proc - Process fcf table rediscovery event
7236  * @phba: pointer to lpfc hba data structure.
7237  *
7238  * This routine is invoked by the worker thread to process FCF table
7239  * rediscovery pending completion event.
7240  **/
7241 void lpfc_sli4_fcf_redisc_event_proc(struct lpfc_hba *phba)
7242 {
7243 	int rc;
7244 
7245 	spin_lock_irq(&phba->hbalock);
7246 	/* Clear FCF rediscovery timeout event */
7247 	phba->fcf.fcf_flag &= ~FCF_REDISC_EVT;
7248 	/* Clear driver fast failover FCF record flag */
7249 	phba->fcf.failover_rec.flag = 0;
7250 	/* Set state for FCF fast failover */
7251 	phba->fcf.fcf_flag |= FCF_REDISC_FOV;
7252 	spin_unlock_irq(&phba->hbalock);
7253 
7254 	/* Scan FCF table from the first entry to re-discover SAN */
7255 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
7256 			"2777 Start post-quiescent FCF table scan\n");
7257 	rc = lpfc_sli4_fcf_scan_read_fcf_rec(phba, LPFC_FCOE_FCF_GET_FIRST);
7258 	if (rc)
7259 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7260 				"2747 Issue FCF scan read FCF mailbox "
7261 				"command failed 0x%x\n", rc);
7262 }
7263 
7264 /**
7265  * lpfc_api_table_setup - Set up per hba pci-device group func api jump table
7266  * @phba: pointer to lpfc hba data structure.
7267  * @dev_grp: The HBA PCI-Device group number.
7268  *
7269  * This routine is invoked to set up the per HBA PCI-Device group function
7270  * API jump table entries.
7271  *
7272  * Return: 0 if success, otherwise -ENODEV
7273  **/
7274 int
7275 lpfc_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
7276 {
7277 	int rc;
7278 
7279 	/* Set up lpfc PCI-device group */
7280 	phba->pci_dev_grp = dev_grp;
7281 
7282 	/* The LPFC_PCI_DEV_OC uses SLI4 */
7283 	if (dev_grp == LPFC_PCI_DEV_OC)
7284 		phba->sli_rev = LPFC_SLI_REV4;
7285 
7286 	/* Set up device INIT API function jump table */
7287 	rc = lpfc_init_api_table_setup(phba, dev_grp);
7288 	if (rc)
7289 		return -ENODEV;
7290 	/* Set up SCSI API function jump table */
7291 	rc = lpfc_scsi_api_table_setup(phba, dev_grp);
7292 	if (rc)
7293 		return -ENODEV;
7294 	/* Set up SLI API function jump table */
7295 	rc = lpfc_sli_api_table_setup(phba, dev_grp);
7296 	if (rc)
7297 		return -ENODEV;
7298 	/* Set up MBOX API function jump table */
7299 	rc = lpfc_mbox_api_table_setup(phba, dev_grp);
7300 	if (rc)
7301 		return -ENODEV;
7302 
7303 	return 0;
7304 }
7305 
7306 /**
7307  * lpfc_log_intr_mode - Log the active interrupt mode
7308  * @phba: pointer to lpfc hba data structure.
7309  * @intr_mode: active interrupt mode adopted.
7310  *
7311  * This routine it invoked to log the currently used active interrupt mode
7312  * to the device.
7313  **/
7314 static void lpfc_log_intr_mode(struct lpfc_hba *phba, uint32_t intr_mode)
7315 {
7316 	switch (intr_mode) {
7317 	case 0:
7318 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7319 				"0470 Enable INTx interrupt mode.\n");
7320 		break;
7321 	case 1:
7322 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7323 				"0481 Enabled MSI interrupt mode.\n");
7324 		break;
7325 	case 2:
7326 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7327 				"0480 Enabled MSI-X interrupt mode.\n");
7328 		break;
7329 	default:
7330 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7331 				"0482 Illegal interrupt mode.\n");
7332 		break;
7333 	}
7334 	return;
7335 }
7336 
7337 /**
7338  * lpfc_enable_pci_dev - Enable a generic PCI device.
7339  * @phba: pointer to lpfc hba data structure.
7340  *
7341  * This routine is invoked to enable the PCI device that is common to all
7342  * PCI devices.
7343  *
7344  * Return codes
7345  * 	0 - successful
7346  * 	other values - error
7347  **/
7348 static int
7349 lpfc_enable_pci_dev(struct lpfc_hba *phba)
7350 {
7351 	struct pci_dev *pdev;
7352 
7353 	/* Obtain PCI device reference */
7354 	if (!phba->pcidev)
7355 		goto out_error;
7356 	else
7357 		pdev = phba->pcidev;
7358 	/* Enable PCI device */
7359 	if (pci_enable_device_mem(pdev))
7360 		goto out_error;
7361 	/* Request PCI resource for the device */
7362 	if (pci_request_mem_regions(pdev, LPFC_DRIVER_NAME))
7363 		goto out_disable_device;
7364 	/* Set up device as PCI master and save state for EEH */
7365 	pci_set_master(pdev);
7366 	pci_try_set_mwi(pdev);
7367 	pci_save_state(pdev);
7368 
7369 	/* PCIe EEH recovery on powerpc platforms needs fundamental reset */
7370 	if (pci_is_pcie(pdev))
7371 		pdev->needs_freset = 1;
7372 
7373 	return 0;
7374 
7375 out_disable_device:
7376 	pci_disable_device(pdev);
7377 out_error:
7378 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7379 			"1401 Failed to enable pci device\n");
7380 	return -ENODEV;
7381 }
7382 
7383 /**
7384  * lpfc_disable_pci_dev - Disable a generic PCI device.
7385  * @phba: pointer to lpfc hba data structure.
7386  *
7387  * This routine is invoked to disable the PCI device that is common to all
7388  * PCI devices.
7389  **/
7390 static void
7391 lpfc_disable_pci_dev(struct lpfc_hba *phba)
7392 {
7393 	struct pci_dev *pdev;
7394 
7395 	/* Obtain PCI device reference */
7396 	if (!phba->pcidev)
7397 		return;
7398 	else
7399 		pdev = phba->pcidev;
7400 	/* Release PCI resource and disable PCI device */
7401 	pci_release_mem_regions(pdev);
7402 	pci_disable_device(pdev);
7403 
7404 	return;
7405 }
7406 
7407 /**
7408  * lpfc_reset_hba - Reset a hba
7409  * @phba: pointer to lpfc hba data structure.
7410  *
7411  * This routine is invoked to reset a hba device. It brings the HBA
7412  * offline, performs a board restart, and then brings the board back
7413  * online. The lpfc_offline calls lpfc_sli_hba_down which will clean up
7414  * on outstanding mailbox commands.
7415  **/
7416 void
7417 lpfc_reset_hba(struct lpfc_hba *phba)
7418 {
7419 	/* If resets are disabled then set error state and return. */
7420 	if (!phba->cfg_enable_hba_reset) {
7421 		phba->link_state = LPFC_HBA_ERROR;
7422 		return;
7423 	}
7424 
7425 	/* If not LPFC_SLI_ACTIVE, force all IO to be flushed */
7426 	if (phba->sli.sli_flag & LPFC_SLI_ACTIVE) {
7427 		lpfc_offline_prep(phba, LPFC_MBX_WAIT);
7428 	} else {
7429 		lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
7430 		lpfc_sli_flush_io_rings(phba);
7431 	}
7432 	lpfc_offline(phba);
7433 	lpfc_sli_brdrestart(phba);
7434 	lpfc_online(phba);
7435 	lpfc_unblock_mgmt_io(phba);
7436 }
7437 
7438 /**
7439  * lpfc_sli_sriov_nr_virtfn_get - Get the number of sr-iov virtual functions
7440  * @phba: pointer to lpfc hba data structure.
7441  *
7442  * This function enables the PCI SR-IOV virtual functions to a physical
7443  * function. It invokes the PCI SR-IOV api with the @nr_vfn provided to
7444  * enable the number of virtual functions to the physical function. As
7445  * not all devices support SR-IOV, the return code from the pci_enable_sriov()
7446  * API call does not considered as an error condition for most of the device.
7447  **/
7448 uint16_t
7449 lpfc_sli_sriov_nr_virtfn_get(struct lpfc_hba *phba)
7450 {
7451 	struct pci_dev *pdev = phba->pcidev;
7452 	uint16_t nr_virtfn;
7453 	int pos;
7454 
7455 	pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_SRIOV);
7456 	if (pos == 0)
7457 		return 0;
7458 
7459 	pci_read_config_word(pdev, pos + PCI_SRIOV_TOTAL_VF, &nr_virtfn);
7460 	return nr_virtfn;
7461 }
7462 
7463 /**
7464  * lpfc_sli_probe_sriov_nr_virtfn - Enable a number of sr-iov virtual functions
7465  * @phba: pointer to lpfc hba data structure.
7466  * @nr_vfn: number of virtual functions to be enabled.
7467  *
7468  * This function enables the PCI SR-IOV virtual functions to a physical
7469  * function. It invokes the PCI SR-IOV api with the @nr_vfn provided to
7470  * enable the number of virtual functions to the physical function. As
7471  * not all devices support SR-IOV, the return code from the pci_enable_sriov()
7472  * API call does not considered as an error condition for most of the device.
7473  **/
7474 int
7475 lpfc_sli_probe_sriov_nr_virtfn(struct lpfc_hba *phba, int nr_vfn)
7476 {
7477 	struct pci_dev *pdev = phba->pcidev;
7478 	uint16_t max_nr_vfn;
7479 	int rc;
7480 
7481 	max_nr_vfn = lpfc_sli_sriov_nr_virtfn_get(phba);
7482 	if (nr_vfn > max_nr_vfn) {
7483 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7484 				"3057 Requested vfs (%d) greater than "
7485 				"supported vfs (%d)", nr_vfn, max_nr_vfn);
7486 		return -EINVAL;
7487 	}
7488 
7489 	rc = pci_enable_sriov(pdev, nr_vfn);
7490 	if (rc) {
7491 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7492 				"2806 Failed to enable sriov on this device "
7493 				"with vfn number nr_vf:%d, rc:%d\n",
7494 				nr_vfn, rc);
7495 	} else
7496 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7497 				"2807 Successful enable sriov on this device "
7498 				"with vfn number nr_vf:%d\n", nr_vfn);
7499 	return rc;
7500 }
7501 
7502 static void
7503 lpfc_unblock_requests_work(struct work_struct *work)
7504 {
7505 	struct lpfc_hba *phba = container_of(work, struct lpfc_hba,
7506 					     unblock_request_work);
7507 
7508 	lpfc_unblock_requests(phba);
7509 }
7510 
7511 /**
7512  * lpfc_setup_driver_resource_phase1 - Phase1 etup driver internal resources.
7513  * @phba: pointer to lpfc hba data structure.
7514  *
7515  * This routine is invoked to set up the driver internal resources before the
7516  * device specific resource setup to support the HBA device it attached to.
7517  *
7518  * Return codes
7519  *	0 - successful
7520  *	other values - error
7521  **/
7522 static int
7523 lpfc_setup_driver_resource_phase1(struct lpfc_hba *phba)
7524 {
7525 	struct lpfc_sli *psli = &phba->sli;
7526 
7527 	/*
7528 	 * Driver resources common to all SLI revisions
7529 	 */
7530 	atomic_set(&phba->fast_event_count, 0);
7531 	atomic_set(&phba->dbg_log_idx, 0);
7532 	atomic_set(&phba->dbg_log_cnt, 0);
7533 	atomic_set(&phba->dbg_log_dmping, 0);
7534 	spin_lock_init(&phba->hbalock);
7535 
7536 	/* Initialize port_list spinlock */
7537 	spin_lock_init(&phba->port_list_lock);
7538 	INIT_LIST_HEAD(&phba->port_list);
7539 
7540 	INIT_LIST_HEAD(&phba->work_list);
7541 	init_waitqueue_head(&phba->wait_4_mlo_m_q);
7542 
7543 	/* Initialize the wait queue head for the kernel thread */
7544 	init_waitqueue_head(&phba->work_waitq);
7545 
7546 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7547 			"1403 Protocols supported %s %s %s\n",
7548 			((phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP) ?
7549 				"SCSI" : " "),
7550 			((phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) ?
7551 				"NVME" : " "),
7552 			(phba->nvmet_support ? "NVMET" : " "));
7553 
7554 	/* Initialize the IO buffer list used by driver for SLI3 SCSI */
7555 	spin_lock_init(&phba->scsi_buf_list_get_lock);
7556 	INIT_LIST_HEAD(&phba->lpfc_scsi_buf_list_get);
7557 	spin_lock_init(&phba->scsi_buf_list_put_lock);
7558 	INIT_LIST_HEAD(&phba->lpfc_scsi_buf_list_put);
7559 
7560 	/* Initialize the fabric iocb list */
7561 	INIT_LIST_HEAD(&phba->fabric_iocb_list);
7562 
7563 	/* Initialize list to save ELS buffers */
7564 	INIT_LIST_HEAD(&phba->elsbuf);
7565 
7566 	/* Initialize FCF connection rec list */
7567 	INIT_LIST_HEAD(&phba->fcf_conn_rec_list);
7568 
7569 	/* Initialize OAS configuration list */
7570 	spin_lock_init(&phba->devicelock);
7571 	INIT_LIST_HEAD(&phba->luns);
7572 
7573 	/* MBOX heartbeat timer */
7574 	timer_setup(&psli->mbox_tmo, lpfc_mbox_timeout, 0);
7575 	/* Fabric block timer */
7576 	timer_setup(&phba->fabric_block_timer, lpfc_fabric_block_timeout, 0);
7577 	/* EA polling mode timer */
7578 	timer_setup(&phba->eratt_poll, lpfc_poll_eratt, 0);
7579 	/* Heartbeat timer */
7580 	timer_setup(&phba->hb_tmofunc, lpfc_hb_timeout, 0);
7581 
7582 	INIT_DELAYED_WORK(&phba->eq_delay_work, lpfc_hb_eq_delay_work);
7583 
7584 	INIT_DELAYED_WORK(&phba->idle_stat_delay_work,
7585 			  lpfc_idle_stat_delay_work);
7586 	INIT_WORK(&phba->unblock_request_work, lpfc_unblock_requests_work);
7587 	return 0;
7588 }
7589 
7590 /**
7591  * lpfc_sli_driver_resource_setup - Setup driver internal resources for SLI3 dev
7592  * @phba: pointer to lpfc hba data structure.
7593  *
7594  * This routine is invoked to set up the driver internal resources specific to
7595  * support the SLI-3 HBA device it attached to.
7596  *
7597  * Return codes
7598  * 0 - successful
7599  * other values - error
7600  **/
7601 static int
7602 lpfc_sli_driver_resource_setup(struct lpfc_hba *phba)
7603 {
7604 	int rc, entry_sz;
7605 
7606 	/*
7607 	 * Initialize timers used by driver
7608 	 */
7609 
7610 	/* FCP polling mode timer */
7611 	timer_setup(&phba->fcp_poll_timer, lpfc_poll_timeout, 0);
7612 
7613 	/* Host attention work mask setup */
7614 	phba->work_ha_mask = (HA_ERATT | HA_MBATT | HA_LATT);
7615 	phba->work_ha_mask |= (HA_RXMASK << (LPFC_ELS_RING * 4));
7616 
7617 	/* Get all the module params for configuring this host */
7618 	lpfc_get_cfgparam(phba);
7619 	/* Set up phase-1 common device driver resources */
7620 
7621 	rc = lpfc_setup_driver_resource_phase1(phba);
7622 	if (rc)
7623 		return -ENODEV;
7624 
7625 	if (phba->pcidev->device == PCI_DEVICE_ID_HORNET) {
7626 		phba->menlo_flag |= HBA_MENLO_SUPPORT;
7627 		/* check for menlo minimum sg count */
7628 		if (phba->cfg_sg_seg_cnt < LPFC_DEFAULT_MENLO_SG_SEG_CNT)
7629 			phba->cfg_sg_seg_cnt = LPFC_DEFAULT_MENLO_SG_SEG_CNT;
7630 	}
7631 
7632 	if (!phba->sli.sli3_ring)
7633 		phba->sli.sli3_ring = kcalloc(LPFC_SLI3_MAX_RING,
7634 					      sizeof(struct lpfc_sli_ring),
7635 					      GFP_KERNEL);
7636 	if (!phba->sli.sli3_ring)
7637 		return -ENOMEM;
7638 
7639 	/*
7640 	 * Since lpfc_sg_seg_cnt is module parameter, the sg_dma_buf_size
7641 	 * used to create the sg_dma_buf_pool must be dynamically calculated.
7642 	 */
7643 
7644 	if (phba->sli_rev == LPFC_SLI_REV4)
7645 		entry_sz = sizeof(struct sli4_sge);
7646 	else
7647 		entry_sz = sizeof(struct ulp_bde64);
7648 
7649 	/* There are going to be 2 reserved BDEs: 1 FCP cmnd + 1 FCP rsp */
7650 	if (phba->cfg_enable_bg) {
7651 		/*
7652 		 * The scsi_buf for a T10-DIF I/O will hold the FCP cmnd,
7653 		 * the FCP rsp, and a BDE for each. Sice we have no control
7654 		 * over how many protection data segments the SCSI Layer
7655 		 * will hand us (ie: there could be one for every block
7656 		 * in the IO), we just allocate enough BDEs to accomidate
7657 		 * our max amount and we need to limit lpfc_sg_seg_cnt to
7658 		 * minimize the risk of running out.
7659 		 */
7660 		phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd) +
7661 			sizeof(struct fcp_rsp) +
7662 			(LPFC_MAX_SG_SEG_CNT * entry_sz);
7663 
7664 		if (phba->cfg_sg_seg_cnt > LPFC_MAX_SG_SEG_CNT_DIF)
7665 			phba->cfg_sg_seg_cnt = LPFC_MAX_SG_SEG_CNT_DIF;
7666 
7667 		/* Total BDEs in BPL for scsi_sg_list and scsi_sg_prot_list */
7668 		phba->cfg_total_seg_cnt = LPFC_MAX_SG_SEG_CNT;
7669 	} else {
7670 		/*
7671 		 * The scsi_buf for a regular I/O will hold the FCP cmnd,
7672 		 * the FCP rsp, a BDE for each, and a BDE for up to
7673 		 * cfg_sg_seg_cnt data segments.
7674 		 */
7675 		phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd) +
7676 			sizeof(struct fcp_rsp) +
7677 			((phba->cfg_sg_seg_cnt + 2) * entry_sz);
7678 
7679 		/* Total BDEs in BPL for scsi_sg_list */
7680 		phba->cfg_total_seg_cnt = phba->cfg_sg_seg_cnt + 2;
7681 	}
7682 
7683 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP,
7684 			"9088 INIT sg_tablesize:%d dmabuf_size:%d total_bde:%d\n",
7685 			phba->cfg_sg_seg_cnt, phba->cfg_sg_dma_buf_size,
7686 			phba->cfg_total_seg_cnt);
7687 
7688 	phba->max_vpi = LPFC_MAX_VPI;
7689 	/* This will be set to correct value after config_port mbox */
7690 	phba->max_vports = 0;
7691 
7692 	/*
7693 	 * Initialize the SLI Layer to run with lpfc HBAs.
7694 	 */
7695 	lpfc_sli_setup(phba);
7696 	lpfc_sli_queue_init(phba);
7697 
7698 	/* Allocate device driver memory */
7699 	if (lpfc_mem_alloc(phba, BPL_ALIGN_SZ))
7700 		return -ENOMEM;
7701 
7702 	phba->lpfc_sg_dma_buf_pool =
7703 		dma_pool_create("lpfc_sg_dma_buf_pool",
7704 				&phba->pcidev->dev, phba->cfg_sg_dma_buf_size,
7705 				BPL_ALIGN_SZ, 0);
7706 
7707 	if (!phba->lpfc_sg_dma_buf_pool)
7708 		goto fail_free_mem;
7709 
7710 	phba->lpfc_cmd_rsp_buf_pool =
7711 			dma_pool_create("lpfc_cmd_rsp_buf_pool",
7712 					&phba->pcidev->dev,
7713 					sizeof(struct fcp_cmnd) +
7714 					sizeof(struct fcp_rsp),
7715 					BPL_ALIGN_SZ, 0);
7716 
7717 	if (!phba->lpfc_cmd_rsp_buf_pool)
7718 		goto fail_free_dma_buf_pool;
7719 
7720 	/*
7721 	 * Enable sr-iov virtual functions if supported and configured
7722 	 * through the module parameter.
7723 	 */
7724 	if (phba->cfg_sriov_nr_virtfn > 0) {
7725 		rc = lpfc_sli_probe_sriov_nr_virtfn(phba,
7726 						 phba->cfg_sriov_nr_virtfn);
7727 		if (rc) {
7728 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7729 					"2808 Requested number of SR-IOV "
7730 					"virtual functions (%d) is not "
7731 					"supported\n",
7732 					phba->cfg_sriov_nr_virtfn);
7733 			phba->cfg_sriov_nr_virtfn = 0;
7734 		}
7735 	}
7736 
7737 	return 0;
7738 
7739 fail_free_dma_buf_pool:
7740 	dma_pool_destroy(phba->lpfc_sg_dma_buf_pool);
7741 	phba->lpfc_sg_dma_buf_pool = NULL;
7742 fail_free_mem:
7743 	lpfc_mem_free(phba);
7744 	return -ENOMEM;
7745 }
7746 
7747 /**
7748  * lpfc_sli_driver_resource_unset - Unset drvr internal resources for SLI3 dev
7749  * @phba: pointer to lpfc hba data structure.
7750  *
7751  * This routine is invoked to unset the driver internal resources set up
7752  * specific for supporting the SLI-3 HBA device it attached to.
7753  **/
7754 static void
7755 lpfc_sli_driver_resource_unset(struct lpfc_hba *phba)
7756 {
7757 	/* Free device driver memory allocated */
7758 	lpfc_mem_free_all(phba);
7759 
7760 	return;
7761 }
7762 
7763 /**
7764  * lpfc_sli4_driver_resource_setup - Setup drvr internal resources for SLI4 dev
7765  * @phba: pointer to lpfc hba data structure.
7766  *
7767  * This routine is invoked to set up the driver internal resources specific to
7768  * support the SLI-4 HBA device it attached to.
7769  *
7770  * Return codes
7771  * 	0 - successful
7772  * 	other values - error
7773  **/
7774 static int
7775 lpfc_sli4_driver_resource_setup(struct lpfc_hba *phba)
7776 {
7777 	LPFC_MBOXQ_t *mboxq;
7778 	MAILBOX_t *mb;
7779 	int rc, i, max_buf_size;
7780 	int longs;
7781 	int extra;
7782 	uint64_t wwn;
7783 	u32 if_type;
7784 	u32 if_fam;
7785 
7786 	phba->sli4_hba.num_present_cpu = lpfc_present_cpu;
7787 	phba->sli4_hba.num_possible_cpu = cpumask_last(cpu_possible_mask) + 1;
7788 	phba->sli4_hba.curr_disp_cpu = 0;
7789 
7790 	/* Get all the module params for configuring this host */
7791 	lpfc_get_cfgparam(phba);
7792 
7793 	/* Set up phase-1 common device driver resources */
7794 	rc = lpfc_setup_driver_resource_phase1(phba);
7795 	if (rc)
7796 		return -ENODEV;
7797 
7798 	/* Before proceed, wait for POST done and device ready */
7799 	rc = lpfc_sli4_post_status_check(phba);
7800 	if (rc)
7801 		return -ENODEV;
7802 
7803 	/* Allocate all driver workqueues here */
7804 
7805 	/* The lpfc_wq workqueue for deferred irq use */
7806 	phba->wq = alloc_workqueue("lpfc_wq", WQ_MEM_RECLAIM, 0);
7807 
7808 	/*
7809 	 * Initialize timers used by driver
7810 	 */
7811 
7812 	timer_setup(&phba->rrq_tmr, lpfc_rrq_timeout, 0);
7813 
7814 	/* FCF rediscover timer */
7815 	timer_setup(&phba->fcf.redisc_wait, lpfc_sli4_fcf_redisc_wait_tmo, 0);
7816 
7817 	/* CMF congestion timer */
7818 	hrtimer_init(&phba->cmf_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
7819 	phba->cmf_timer.function = lpfc_cmf_timer;
7820 
7821 	/*
7822 	 * Control structure for handling external multi-buffer mailbox
7823 	 * command pass-through.
7824 	 */
7825 	memset((uint8_t *)&phba->mbox_ext_buf_ctx, 0,
7826 		sizeof(struct lpfc_mbox_ext_buf_ctx));
7827 	INIT_LIST_HEAD(&phba->mbox_ext_buf_ctx.ext_dmabuf_list);
7828 
7829 	phba->max_vpi = LPFC_MAX_VPI;
7830 
7831 	/* This will be set to correct value after the read_config mbox */
7832 	phba->max_vports = 0;
7833 
7834 	/* Program the default value of vlan_id and fc_map */
7835 	phba->valid_vlan = 0;
7836 	phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
7837 	phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
7838 	phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
7839 
7840 	/*
7841 	 * For SLI4, instead of using ring 0 (LPFC_FCP_RING) for FCP commands
7842 	 * we will associate a new ring, for each EQ/CQ/WQ tuple.
7843 	 * The WQ create will allocate the ring.
7844 	 */
7845 
7846 	/* Initialize buffer queue management fields */
7847 	INIT_LIST_HEAD(&phba->hbqs[LPFC_ELS_HBQ].hbq_buffer_list);
7848 	phba->hbqs[LPFC_ELS_HBQ].hbq_alloc_buffer = lpfc_sli4_rb_alloc;
7849 	phba->hbqs[LPFC_ELS_HBQ].hbq_free_buffer = lpfc_sli4_rb_free;
7850 
7851 	/* for VMID idle timeout if VMID is enabled */
7852 	if (lpfc_is_vmid_enabled(phba))
7853 		timer_setup(&phba->inactive_vmid_poll, lpfc_vmid_poll, 0);
7854 
7855 	/*
7856 	 * Initialize the SLI Layer to run with lpfc SLI4 HBAs.
7857 	 */
7858 	/* Initialize the Abort buffer list used by driver */
7859 	spin_lock_init(&phba->sli4_hba.abts_io_buf_list_lock);
7860 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_io_buf_list);
7861 
7862 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
7863 		/* Initialize the Abort nvme buffer list used by driver */
7864 		spin_lock_init(&phba->sli4_hba.abts_nvmet_buf_list_lock);
7865 		INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
7866 		INIT_LIST_HEAD(&phba->sli4_hba.lpfc_nvmet_io_wait_list);
7867 		spin_lock_init(&phba->sli4_hba.t_active_list_lock);
7868 		INIT_LIST_HEAD(&phba->sli4_hba.t_active_ctx_list);
7869 	}
7870 
7871 	/* This abort list used by worker thread */
7872 	spin_lock_init(&phba->sli4_hba.sgl_list_lock);
7873 	spin_lock_init(&phba->sli4_hba.nvmet_io_wait_lock);
7874 	spin_lock_init(&phba->sli4_hba.asynce_list_lock);
7875 	spin_lock_init(&phba->sli4_hba.els_xri_abrt_list_lock);
7876 
7877 	/*
7878 	 * Initialize driver internal slow-path work queues
7879 	 */
7880 
7881 	/* Driver internel slow-path CQ Event pool */
7882 	INIT_LIST_HEAD(&phba->sli4_hba.sp_cqe_event_pool);
7883 	/* Response IOCB work queue list */
7884 	INIT_LIST_HEAD(&phba->sli4_hba.sp_queue_event);
7885 	/* Asynchronous event CQ Event work queue list */
7886 	INIT_LIST_HEAD(&phba->sli4_hba.sp_asynce_work_queue);
7887 	/* Slow-path XRI aborted CQ Event work queue list */
7888 	INIT_LIST_HEAD(&phba->sli4_hba.sp_els_xri_aborted_work_queue);
7889 	/* Receive queue CQ Event work queue list */
7890 	INIT_LIST_HEAD(&phba->sli4_hba.sp_unsol_work_queue);
7891 
7892 	/* Initialize extent block lists. */
7893 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_rpi_blk_list);
7894 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_xri_blk_list);
7895 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_vfi_blk_list);
7896 	INIT_LIST_HEAD(&phba->lpfc_vpi_blk_list);
7897 
7898 	/* Initialize mboxq lists. If the early init routines fail
7899 	 * these lists need to be correctly initialized.
7900 	 */
7901 	INIT_LIST_HEAD(&phba->sli.mboxq);
7902 	INIT_LIST_HEAD(&phba->sli.mboxq_cmpl);
7903 
7904 	/* initialize optic_state to 0xFF */
7905 	phba->sli4_hba.lnk_info.optic_state = 0xff;
7906 
7907 	/* Allocate device driver memory */
7908 	rc = lpfc_mem_alloc(phba, SGL_ALIGN_SZ);
7909 	if (rc)
7910 		goto out_destroy_workqueue;
7911 
7912 	/* IF Type 2 ports get initialized now. */
7913 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) >=
7914 	    LPFC_SLI_INTF_IF_TYPE_2) {
7915 		rc = lpfc_pci_function_reset(phba);
7916 		if (unlikely(rc)) {
7917 			rc = -ENODEV;
7918 			goto out_free_mem;
7919 		}
7920 		phba->temp_sensor_support = 1;
7921 	}
7922 
7923 	/* Create the bootstrap mailbox command */
7924 	rc = lpfc_create_bootstrap_mbox(phba);
7925 	if (unlikely(rc))
7926 		goto out_free_mem;
7927 
7928 	/* Set up the host's endian order with the device. */
7929 	rc = lpfc_setup_endian_order(phba);
7930 	if (unlikely(rc))
7931 		goto out_free_bsmbx;
7932 
7933 	/* Set up the hba's configuration parameters. */
7934 	rc = lpfc_sli4_read_config(phba);
7935 	if (unlikely(rc))
7936 		goto out_free_bsmbx;
7937 	rc = lpfc_mem_alloc_active_rrq_pool_s4(phba);
7938 	if (unlikely(rc))
7939 		goto out_free_bsmbx;
7940 
7941 	/* IF Type 0 ports get initialized now. */
7942 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
7943 	    LPFC_SLI_INTF_IF_TYPE_0) {
7944 		rc = lpfc_pci_function_reset(phba);
7945 		if (unlikely(rc))
7946 			goto out_free_bsmbx;
7947 	}
7948 
7949 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
7950 						       GFP_KERNEL);
7951 	if (!mboxq) {
7952 		rc = -ENOMEM;
7953 		goto out_free_bsmbx;
7954 	}
7955 
7956 	/* Check for NVMET being configured */
7957 	phba->nvmet_support = 0;
7958 	if (lpfc_enable_nvmet_cnt) {
7959 
7960 		/* First get WWN of HBA instance */
7961 		lpfc_read_nv(phba, mboxq);
7962 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7963 		if (rc != MBX_SUCCESS) {
7964 			lpfc_printf_log(phba, KERN_ERR,
7965 					LOG_TRACE_EVENT,
7966 					"6016 Mailbox failed , mbxCmd x%x "
7967 					"READ_NV, mbxStatus x%x\n",
7968 					bf_get(lpfc_mqe_command, &mboxq->u.mqe),
7969 					bf_get(lpfc_mqe_status, &mboxq->u.mqe));
7970 			mempool_free(mboxq, phba->mbox_mem_pool);
7971 			rc = -EIO;
7972 			goto out_free_bsmbx;
7973 		}
7974 		mb = &mboxq->u.mb;
7975 		memcpy(&wwn, (char *)mb->un.varRDnvp.nodename,
7976 		       sizeof(uint64_t));
7977 		wwn = cpu_to_be64(wwn);
7978 		phba->sli4_hba.wwnn.u.name = wwn;
7979 		memcpy(&wwn, (char *)mb->un.varRDnvp.portname,
7980 		       sizeof(uint64_t));
7981 		/* wwn is WWPN of HBA instance */
7982 		wwn = cpu_to_be64(wwn);
7983 		phba->sli4_hba.wwpn.u.name = wwn;
7984 
7985 		/* Check to see if it matches any module parameter */
7986 		for (i = 0; i < lpfc_enable_nvmet_cnt; i++) {
7987 			if (wwn == lpfc_enable_nvmet[i]) {
7988 #if (IS_ENABLED(CONFIG_NVME_TARGET_FC))
7989 				if (lpfc_nvmet_mem_alloc(phba))
7990 					break;
7991 
7992 				phba->nvmet_support = 1; /* a match */
7993 
7994 				lpfc_printf_log(phba, KERN_ERR,
7995 						LOG_TRACE_EVENT,
7996 						"6017 NVME Target %016llx\n",
7997 						wwn);
7998 #else
7999 				lpfc_printf_log(phba, KERN_ERR,
8000 						LOG_TRACE_EVENT,
8001 						"6021 Can't enable NVME Target."
8002 						" NVME_TARGET_FC infrastructure"
8003 						" is not in kernel\n");
8004 #endif
8005 				/* Not supported for NVMET */
8006 				phba->cfg_xri_rebalancing = 0;
8007 				if (phba->irq_chann_mode == NHT_MODE) {
8008 					phba->cfg_irq_chann =
8009 						phba->sli4_hba.num_present_cpu;
8010 					phba->cfg_hdw_queue =
8011 						phba->sli4_hba.num_present_cpu;
8012 					phba->irq_chann_mode = NORMAL_MODE;
8013 				}
8014 				break;
8015 			}
8016 		}
8017 	}
8018 
8019 	lpfc_nvme_mod_param_dep(phba);
8020 
8021 	/*
8022 	 * Get sli4 parameters that override parameters from Port capabilities.
8023 	 * If this call fails, it isn't critical unless the SLI4 parameters come
8024 	 * back in conflict.
8025 	 */
8026 	rc = lpfc_get_sli4_parameters(phba, mboxq);
8027 	if (rc) {
8028 		if_type = bf_get(lpfc_sli_intf_if_type,
8029 				 &phba->sli4_hba.sli_intf);
8030 		if_fam = bf_get(lpfc_sli_intf_sli_family,
8031 				&phba->sli4_hba.sli_intf);
8032 		if (phba->sli4_hba.extents_in_use &&
8033 		    phba->sli4_hba.rpi_hdrs_in_use) {
8034 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8035 					"2999 Unsupported SLI4 Parameters "
8036 					"Extents and RPI headers enabled.\n");
8037 			if (if_type == LPFC_SLI_INTF_IF_TYPE_0 &&
8038 			    if_fam ==  LPFC_SLI_INTF_FAMILY_BE2) {
8039 				mempool_free(mboxq, phba->mbox_mem_pool);
8040 				rc = -EIO;
8041 				goto out_free_bsmbx;
8042 			}
8043 		}
8044 		if (!(if_type == LPFC_SLI_INTF_IF_TYPE_0 &&
8045 		      if_fam == LPFC_SLI_INTF_FAMILY_BE2)) {
8046 			mempool_free(mboxq, phba->mbox_mem_pool);
8047 			rc = -EIO;
8048 			goto out_free_bsmbx;
8049 		}
8050 	}
8051 
8052 	/*
8053 	 * 1 for cmd, 1 for rsp, NVME adds an extra one
8054 	 * for boundary conditions in its max_sgl_segment template.
8055 	 */
8056 	extra = 2;
8057 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
8058 		extra++;
8059 
8060 	/*
8061 	 * It doesn't matter what family our adapter is in, we are
8062 	 * limited to 2 Pages, 512 SGEs, for our SGL.
8063 	 * There are going to be 2 reserved SGEs: 1 FCP cmnd + 1 FCP rsp
8064 	 */
8065 	max_buf_size = (2 * SLI4_PAGE_SIZE);
8066 
8067 	/*
8068 	 * Since lpfc_sg_seg_cnt is module param, the sg_dma_buf_size
8069 	 * used to create the sg_dma_buf_pool must be calculated.
8070 	 */
8071 	if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
8072 		/* Both cfg_enable_bg and cfg_external_dif code paths */
8073 
8074 		/*
8075 		 * The scsi_buf for a T10-DIF I/O holds the FCP cmnd,
8076 		 * the FCP rsp, and a SGE. Sice we have no control
8077 		 * over how many protection segments the SCSI Layer
8078 		 * will hand us (ie: there could be one for every block
8079 		 * in the IO), just allocate enough SGEs to accomidate
8080 		 * our max amount and we need to limit lpfc_sg_seg_cnt
8081 		 * to minimize the risk of running out.
8082 		 */
8083 		phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd) +
8084 				sizeof(struct fcp_rsp) + max_buf_size;
8085 
8086 		/* Total SGEs for scsi_sg_list and scsi_sg_prot_list */
8087 		phba->cfg_total_seg_cnt = LPFC_MAX_SGL_SEG_CNT;
8088 
8089 		/*
8090 		 * If supporting DIF, reduce the seg count for scsi to
8091 		 * allow room for the DIF sges.
8092 		 */
8093 		if (phba->cfg_enable_bg &&
8094 		    phba->cfg_sg_seg_cnt > LPFC_MAX_BG_SLI4_SEG_CNT_DIF)
8095 			phba->cfg_scsi_seg_cnt = LPFC_MAX_BG_SLI4_SEG_CNT_DIF;
8096 		else
8097 			phba->cfg_scsi_seg_cnt = phba->cfg_sg_seg_cnt;
8098 
8099 	} else {
8100 		/*
8101 		 * The scsi_buf for a regular I/O holds the FCP cmnd,
8102 		 * the FCP rsp, a SGE for each, and a SGE for up to
8103 		 * cfg_sg_seg_cnt data segments.
8104 		 */
8105 		phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd) +
8106 				sizeof(struct fcp_rsp) +
8107 				((phba->cfg_sg_seg_cnt + extra) *
8108 				sizeof(struct sli4_sge));
8109 
8110 		/* Total SGEs for scsi_sg_list */
8111 		phba->cfg_total_seg_cnt = phba->cfg_sg_seg_cnt + extra;
8112 		phba->cfg_scsi_seg_cnt = phba->cfg_sg_seg_cnt;
8113 
8114 		/*
8115 		 * NOTE: if (phba->cfg_sg_seg_cnt + extra) <= 256 we only
8116 		 * need to post 1 page for the SGL.
8117 		 */
8118 	}
8119 
8120 	if (phba->cfg_xpsgl && !phba->nvmet_support)
8121 		phba->cfg_sg_dma_buf_size = LPFC_DEFAULT_XPSGL_SIZE;
8122 	else if (phba->cfg_sg_dma_buf_size  <= LPFC_MIN_SG_SLI4_BUF_SZ)
8123 		phba->cfg_sg_dma_buf_size = LPFC_MIN_SG_SLI4_BUF_SZ;
8124 	else
8125 		phba->cfg_sg_dma_buf_size =
8126 				SLI4_PAGE_ALIGN(phba->cfg_sg_dma_buf_size);
8127 
8128 	phba->border_sge_num = phba->cfg_sg_dma_buf_size /
8129 			       sizeof(struct sli4_sge);
8130 
8131 	/* Limit to LPFC_MAX_NVME_SEG_CNT for NVME. */
8132 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
8133 		if (phba->cfg_sg_seg_cnt > LPFC_MAX_NVME_SEG_CNT) {
8134 			lpfc_printf_log(phba, KERN_INFO, LOG_NVME | LOG_INIT,
8135 					"6300 Reducing NVME sg segment "
8136 					"cnt to %d\n",
8137 					LPFC_MAX_NVME_SEG_CNT);
8138 			phba->cfg_nvme_seg_cnt = LPFC_MAX_NVME_SEG_CNT;
8139 		} else
8140 			phba->cfg_nvme_seg_cnt = phba->cfg_sg_seg_cnt;
8141 	}
8142 
8143 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP,
8144 			"9087 sg_seg_cnt:%d dmabuf_size:%d "
8145 			"total:%d scsi:%d nvme:%d\n",
8146 			phba->cfg_sg_seg_cnt, phba->cfg_sg_dma_buf_size,
8147 			phba->cfg_total_seg_cnt,  phba->cfg_scsi_seg_cnt,
8148 			phba->cfg_nvme_seg_cnt);
8149 
8150 	if (phba->cfg_sg_dma_buf_size < SLI4_PAGE_SIZE)
8151 		i = phba->cfg_sg_dma_buf_size;
8152 	else
8153 		i = SLI4_PAGE_SIZE;
8154 
8155 	phba->lpfc_sg_dma_buf_pool =
8156 			dma_pool_create("lpfc_sg_dma_buf_pool",
8157 					&phba->pcidev->dev,
8158 					phba->cfg_sg_dma_buf_size,
8159 					i, 0);
8160 	if (!phba->lpfc_sg_dma_buf_pool)
8161 		goto out_free_bsmbx;
8162 
8163 	phba->lpfc_cmd_rsp_buf_pool =
8164 			dma_pool_create("lpfc_cmd_rsp_buf_pool",
8165 					&phba->pcidev->dev,
8166 					sizeof(struct fcp_cmnd) +
8167 					sizeof(struct fcp_rsp),
8168 					i, 0);
8169 	if (!phba->lpfc_cmd_rsp_buf_pool)
8170 		goto out_free_sg_dma_buf;
8171 
8172 	mempool_free(mboxq, phba->mbox_mem_pool);
8173 
8174 	/* Verify OAS is supported */
8175 	lpfc_sli4_oas_verify(phba);
8176 
8177 	/* Verify RAS support on adapter */
8178 	lpfc_sli4_ras_init(phba);
8179 
8180 	/* Verify all the SLI4 queues */
8181 	rc = lpfc_sli4_queue_verify(phba);
8182 	if (rc)
8183 		goto out_free_cmd_rsp_buf;
8184 
8185 	/* Create driver internal CQE event pool */
8186 	rc = lpfc_sli4_cq_event_pool_create(phba);
8187 	if (rc)
8188 		goto out_free_cmd_rsp_buf;
8189 
8190 	/* Initialize sgl lists per host */
8191 	lpfc_init_sgl_list(phba);
8192 
8193 	/* Allocate and initialize active sgl array */
8194 	rc = lpfc_init_active_sgl_array(phba);
8195 	if (rc) {
8196 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8197 				"1430 Failed to initialize sgl list.\n");
8198 		goto out_destroy_cq_event_pool;
8199 	}
8200 	rc = lpfc_sli4_init_rpi_hdrs(phba);
8201 	if (rc) {
8202 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8203 				"1432 Failed to initialize rpi headers.\n");
8204 		goto out_free_active_sgl;
8205 	}
8206 
8207 	/* Allocate eligible FCF bmask memory for FCF roundrobin failover */
8208 	longs = (LPFC_SLI4_FCF_TBL_INDX_MAX + BITS_PER_LONG - 1)/BITS_PER_LONG;
8209 	phba->fcf.fcf_rr_bmask = kcalloc(longs, sizeof(unsigned long),
8210 					 GFP_KERNEL);
8211 	if (!phba->fcf.fcf_rr_bmask) {
8212 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8213 				"2759 Failed allocate memory for FCF round "
8214 				"robin failover bmask\n");
8215 		rc = -ENOMEM;
8216 		goto out_remove_rpi_hdrs;
8217 	}
8218 
8219 	phba->sli4_hba.hba_eq_hdl = kcalloc(phba->cfg_irq_chann,
8220 					    sizeof(struct lpfc_hba_eq_hdl),
8221 					    GFP_KERNEL);
8222 	if (!phba->sli4_hba.hba_eq_hdl) {
8223 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8224 				"2572 Failed allocate memory for "
8225 				"fast-path per-EQ handle array\n");
8226 		rc = -ENOMEM;
8227 		goto out_free_fcf_rr_bmask;
8228 	}
8229 
8230 	phba->sli4_hba.cpu_map = kcalloc(phba->sli4_hba.num_possible_cpu,
8231 					sizeof(struct lpfc_vector_map_info),
8232 					GFP_KERNEL);
8233 	if (!phba->sli4_hba.cpu_map) {
8234 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8235 				"3327 Failed allocate memory for msi-x "
8236 				"interrupt vector mapping\n");
8237 		rc = -ENOMEM;
8238 		goto out_free_hba_eq_hdl;
8239 	}
8240 
8241 	phba->sli4_hba.eq_info = alloc_percpu(struct lpfc_eq_intr_info);
8242 	if (!phba->sli4_hba.eq_info) {
8243 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8244 				"3321 Failed allocation for per_cpu stats\n");
8245 		rc = -ENOMEM;
8246 		goto out_free_hba_cpu_map;
8247 	}
8248 
8249 	phba->sli4_hba.idle_stat = kcalloc(phba->sli4_hba.num_possible_cpu,
8250 					   sizeof(*phba->sli4_hba.idle_stat),
8251 					   GFP_KERNEL);
8252 	if (!phba->sli4_hba.idle_stat) {
8253 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8254 				"3390 Failed allocation for idle_stat\n");
8255 		rc = -ENOMEM;
8256 		goto out_free_hba_eq_info;
8257 	}
8258 
8259 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
8260 	phba->sli4_hba.c_stat = alloc_percpu(struct lpfc_hdwq_stat);
8261 	if (!phba->sli4_hba.c_stat) {
8262 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8263 				"3332 Failed allocating per cpu hdwq stats\n");
8264 		rc = -ENOMEM;
8265 		goto out_free_hba_idle_stat;
8266 	}
8267 #endif
8268 
8269 	phba->cmf_stat = alloc_percpu(struct lpfc_cgn_stat);
8270 	if (!phba->cmf_stat) {
8271 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8272 				"3331 Failed allocating per cpu cgn stats\n");
8273 		rc = -ENOMEM;
8274 		goto out_free_hba_hdwq_info;
8275 	}
8276 
8277 	/*
8278 	 * Enable sr-iov virtual functions if supported and configured
8279 	 * through the module parameter.
8280 	 */
8281 	if (phba->cfg_sriov_nr_virtfn > 0) {
8282 		rc = lpfc_sli_probe_sriov_nr_virtfn(phba,
8283 						 phba->cfg_sriov_nr_virtfn);
8284 		if (rc) {
8285 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
8286 					"3020 Requested number of SR-IOV "
8287 					"virtual functions (%d) is not "
8288 					"supported\n",
8289 					phba->cfg_sriov_nr_virtfn);
8290 			phba->cfg_sriov_nr_virtfn = 0;
8291 		}
8292 	}
8293 
8294 	return 0;
8295 
8296 out_free_hba_hdwq_info:
8297 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
8298 	free_percpu(phba->sli4_hba.c_stat);
8299 out_free_hba_idle_stat:
8300 #endif
8301 	kfree(phba->sli4_hba.idle_stat);
8302 out_free_hba_eq_info:
8303 	free_percpu(phba->sli4_hba.eq_info);
8304 out_free_hba_cpu_map:
8305 	kfree(phba->sli4_hba.cpu_map);
8306 out_free_hba_eq_hdl:
8307 	kfree(phba->sli4_hba.hba_eq_hdl);
8308 out_free_fcf_rr_bmask:
8309 	kfree(phba->fcf.fcf_rr_bmask);
8310 out_remove_rpi_hdrs:
8311 	lpfc_sli4_remove_rpi_hdrs(phba);
8312 out_free_active_sgl:
8313 	lpfc_free_active_sgl(phba);
8314 out_destroy_cq_event_pool:
8315 	lpfc_sli4_cq_event_pool_destroy(phba);
8316 out_free_cmd_rsp_buf:
8317 	dma_pool_destroy(phba->lpfc_cmd_rsp_buf_pool);
8318 	phba->lpfc_cmd_rsp_buf_pool = NULL;
8319 out_free_sg_dma_buf:
8320 	dma_pool_destroy(phba->lpfc_sg_dma_buf_pool);
8321 	phba->lpfc_sg_dma_buf_pool = NULL;
8322 out_free_bsmbx:
8323 	lpfc_destroy_bootstrap_mbox(phba);
8324 out_free_mem:
8325 	lpfc_mem_free(phba);
8326 out_destroy_workqueue:
8327 	destroy_workqueue(phba->wq);
8328 	phba->wq = NULL;
8329 	return rc;
8330 }
8331 
8332 /**
8333  * lpfc_sli4_driver_resource_unset - Unset drvr internal resources for SLI4 dev
8334  * @phba: pointer to lpfc hba data structure.
8335  *
8336  * This routine is invoked to unset the driver internal resources set up
8337  * specific for supporting the SLI-4 HBA device it attached to.
8338  **/
8339 static void
8340 lpfc_sli4_driver_resource_unset(struct lpfc_hba *phba)
8341 {
8342 	struct lpfc_fcf_conn_entry *conn_entry, *next_conn_entry;
8343 
8344 	free_percpu(phba->sli4_hba.eq_info);
8345 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
8346 	free_percpu(phba->sli4_hba.c_stat);
8347 #endif
8348 	free_percpu(phba->cmf_stat);
8349 	kfree(phba->sli4_hba.idle_stat);
8350 
8351 	/* Free memory allocated for msi-x interrupt vector to CPU mapping */
8352 	kfree(phba->sli4_hba.cpu_map);
8353 	phba->sli4_hba.num_possible_cpu = 0;
8354 	phba->sli4_hba.num_present_cpu = 0;
8355 	phba->sli4_hba.curr_disp_cpu = 0;
8356 	cpumask_clear(&phba->sli4_hba.irq_aff_mask);
8357 
8358 	/* Free memory allocated for fast-path work queue handles */
8359 	kfree(phba->sli4_hba.hba_eq_hdl);
8360 
8361 	/* Free the allocated rpi headers. */
8362 	lpfc_sli4_remove_rpi_hdrs(phba);
8363 	lpfc_sli4_remove_rpis(phba);
8364 
8365 	/* Free eligible FCF index bmask */
8366 	kfree(phba->fcf.fcf_rr_bmask);
8367 
8368 	/* Free the ELS sgl list */
8369 	lpfc_free_active_sgl(phba);
8370 	lpfc_free_els_sgl_list(phba);
8371 	lpfc_free_nvmet_sgl_list(phba);
8372 
8373 	/* Free the completion queue EQ event pool */
8374 	lpfc_sli4_cq_event_release_all(phba);
8375 	lpfc_sli4_cq_event_pool_destroy(phba);
8376 
8377 	/* Release resource identifiers. */
8378 	lpfc_sli4_dealloc_resource_identifiers(phba);
8379 
8380 	/* Free the bsmbx region. */
8381 	lpfc_destroy_bootstrap_mbox(phba);
8382 
8383 	/* Free the SLI Layer memory with SLI4 HBAs */
8384 	lpfc_mem_free_all(phba);
8385 
8386 	/* Free the current connect table */
8387 	list_for_each_entry_safe(conn_entry, next_conn_entry,
8388 		&phba->fcf_conn_rec_list, list) {
8389 		list_del_init(&conn_entry->list);
8390 		kfree(conn_entry);
8391 	}
8392 
8393 	return;
8394 }
8395 
8396 /**
8397  * lpfc_init_api_table_setup - Set up init api function jump table
8398  * @phba: The hba struct for which this call is being executed.
8399  * @dev_grp: The HBA PCI-Device group number.
8400  *
8401  * This routine sets up the device INIT interface API function jump table
8402  * in @phba struct.
8403  *
8404  * Returns: 0 - success, -ENODEV - failure.
8405  **/
8406 int
8407 lpfc_init_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
8408 {
8409 	phba->lpfc_hba_init_link = lpfc_hba_init_link;
8410 	phba->lpfc_hba_down_link = lpfc_hba_down_link;
8411 	phba->lpfc_selective_reset = lpfc_selective_reset;
8412 	switch (dev_grp) {
8413 	case LPFC_PCI_DEV_LP:
8414 		phba->lpfc_hba_down_post = lpfc_hba_down_post_s3;
8415 		phba->lpfc_handle_eratt = lpfc_handle_eratt_s3;
8416 		phba->lpfc_stop_port = lpfc_stop_port_s3;
8417 		break;
8418 	case LPFC_PCI_DEV_OC:
8419 		phba->lpfc_hba_down_post = lpfc_hba_down_post_s4;
8420 		phba->lpfc_handle_eratt = lpfc_handle_eratt_s4;
8421 		phba->lpfc_stop_port = lpfc_stop_port_s4;
8422 		break;
8423 	default:
8424 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8425 				"1431 Invalid HBA PCI-device group: 0x%x\n",
8426 				dev_grp);
8427 		return -ENODEV;
8428 	}
8429 	return 0;
8430 }
8431 
8432 /**
8433  * lpfc_setup_driver_resource_phase2 - Phase2 setup driver internal resources.
8434  * @phba: pointer to lpfc hba data structure.
8435  *
8436  * This routine is invoked to set up the driver internal resources after the
8437  * device specific resource setup to support the HBA device it attached to.
8438  *
8439  * Return codes
8440  * 	0 - successful
8441  * 	other values - error
8442  **/
8443 static int
8444 lpfc_setup_driver_resource_phase2(struct lpfc_hba *phba)
8445 {
8446 	int error;
8447 
8448 	/* Startup the kernel thread for this host adapter. */
8449 	phba->worker_thread = kthread_run(lpfc_do_work, phba,
8450 					  "lpfc_worker_%d", phba->brd_no);
8451 	if (IS_ERR(phba->worker_thread)) {
8452 		error = PTR_ERR(phba->worker_thread);
8453 		return error;
8454 	}
8455 
8456 	return 0;
8457 }
8458 
8459 /**
8460  * lpfc_unset_driver_resource_phase2 - Phase2 unset driver internal resources.
8461  * @phba: pointer to lpfc hba data structure.
8462  *
8463  * This routine is invoked to unset the driver internal resources set up after
8464  * the device specific resource setup for supporting the HBA device it
8465  * attached to.
8466  **/
8467 static void
8468 lpfc_unset_driver_resource_phase2(struct lpfc_hba *phba)
8469 {
8470 	if (phba->wq) {
8471 		flush_workqueue(phba->wq);
8472 		destroy_workqueue(phba->wq);
8473 		phba->wq = NULL;
8474 	}
8475 
8476 	/* Stop kernel worker thread */
8477 	if (phba->worker_thread)
8478 		kthread_stop(phba->worker_thread);
8479 }
8480 
8481 /**
8482  * lpfc_free_iocb_list - Free iocb list.
8483  * @phba: pointer to lpfc hba data structure.
8484  *
8485  * This routine is invoked to free the driver's IOCB list and memory.
8486  **/
8487 void
8488 lpfc_free_iocb_list(struct lpfc_hba *phba)
8489 {
8490 	struct lpfc_iocbq *iocbq_entry = NULL, *iocbq_next = NULL;
8491 
8492 	spin_lock_irq(&phba->hbalock);
8493 	list_for_each_entry_safe(iocbq_entry, iocbq_next,
8494 				 &phba->lpfc_iocb_list, list) {
8495 		list_del(&iocbq_entry->list);
8496 		kfree(iocbq_entry);
8497 		phba->total_iocbq_bufs--;
8498 	}
8499 	spin_unlock_irq(&phba->hbalock);
8500 
8501 	return;
8502 }
8503 
8504 /**
8505  * lpfc_init_iocb_list - Allocate and initialize iocb list.
8506  * @phba: pointer to lpfc hba data structure.
8507  * @iocb_count: number of requested iocbs
8508  *
8509  * This routine is invoked to allocate and initizlize the driver's IOCB
8510  * list and set up the IOCB tag array accordingly.
8511  *
8512  * Return codes
8513  *	0 - successful
8514  *	other values - error
8515  **/
8516 int
8517 lpfc_init_iocb_list(struct lpfc_hba *phba, int iocb_count)
8518 {
8519 	struct lpfc_iocbq *iocbq_entry = NULL;
8520 	uint16_t iotag;
8521 	int i;
8522 
8523 	/* Initialize and populate the iocb list per host.  */
8524 	INIT_LIST_HEAD(&phba->lpfc_iocb_list);
8525 	for (i = 0; i < iocb_count; i++) {
8526 		iocbq_entry = kzalloc(sizeof(struct lpfc_iocbq), GFP_KERNEL);
8527 		if (iocbq_entry == NULL) {
8528 			printk(KERN_ERR "%s: only allocated %d iocbs of "
8529 				"expected %d count. Unloading driver.\n",
8530 				__func__, i, iocb_count);
8531 			goto out_free_iocbq;
8532 		}
8533 
8534 		iotag = lpfc_sli_next_iotag(phba, iocbq_entry);
8535 		if (iotag == 0) {
8536 			kfree(iocbq_entry);
8537 			printk(KERN_ERR "%s: failed to allocate IOTAG. "
8538 				"Unloading driver.\n", __func__);
8539 			goto out_free_iocbq;
8540 		}
8541 		iocbq_entry->sli4_lxritag = NO_XRI;
8542 		iocbq_entry->sli4_xritag = NO_XRI;
8543 
8544 		spin_lock_irq(&phba->hbalock);
8545 		list_add(&iocbq_entry->list, &phba->lpfc_iocb_list);
8546 		phba->total_iocbq_bufs++;
8547 		spin_unlock_irq(&phba->hbalock);
8548 	}
8549 
8550 	return 0;
8551 
8552 out_free_iocbq:
8553 	lpfc_free_iocb_list(phba);
8554 
8555 	return -ENOMEM;
8556 }
8557 
8558 /**
8559  * lpfc_free_sgl_list - Free a given sgl list.
8560  * @phba: pointer to lpfc hba data structure.
8561  * @sglq_list: pointer to the head of sgl list.
8562  *
8563  * This routine is invoked to free a give sgl list and memory.
8564  **/
8565 void
8566 lpfc_free_sgl_list(struct lpfc_hba *phba, struct list_head *sglq_list)
8567 {
8568 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
8569 
8570 	list_for_each_entry_safe(sglq_entry, sglq_next, sglq_list, list) {
8571 		list_del(&sglq_entry->list);
8572 		lpfc_mbuf_free(phba, sglq_entry->virt, sglq_entry->phys);
8573 		kfree(sglq_entry);
8574 	}
8575 }
8576 
8577 /**
8578  * lpfc_free_els_sgl_list - Free els sgl list.
8579  * @phba: pointer to lpfc hba data structure.
8580  *
8581  * This routine is invoked to free the driver's els sgl list and memory.
8582  **/
8583 static void
8584 lpfc_free_els_sgl_list(struct lpfc_hba *phba)
8585 {
8586 	LIST_HEAD(sglq_list);
8587 
8588 	/* Retrieve all els sgls from driver list */
8589 	spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
8590 	list_splice_init(&phba->sli4_hba.lpfc_els_sgl_list, &sglq_list);
8591 	spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
8592 
8593 	/* Now free the sgl list */
8594 	lpfc_free_sgl_list(phba, &sglq_list);
8595 }
8596 
8597 /**
8598  * lpfc_free_nvmet_sgl_list - Free nvmet sgl list.
8599  * @phba: pointer to lpfc hba data structure.
8600  *
8601  * This routine is invoked to free the driver's nvmet sgl list and memory.
8602  **/
8603 static void
8604 lpfc_free_nvmet_sgl_list(struct lpfc_hba *phba)
8605 {
8606 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
8607 	LIST_HEAD(sglq_list);
8608 
8609 	/* Retrieve all nvmet sgls from driver list */
8610 	spin_lock_irq(&phba->hbalock);
8611 	spin_lock(&phba->sli4_hba.sgl_list_lock);
8612 	list_splice_init(&phba->sli4_hba.lpfc_nvmet_sgl_list, &sglq_list);
8613 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
8614 	spin_unlock_irq(&phba->hbalock);
8615 
8616 	/* Now free the sgl list */
8617 	list_for_each_entry_safe(sglq_entry, sglq_next, &sglq_list, list) {
8618 		list_del(&sglq_entry->list);
8619 		lpfc_nvmet_buf_free(phba, sglq_entry->virt, sglq_entry->phys);
8620 		kfree(sglq_entry);
8621 	}
8622 
8623 	/* Update the nvmet_xri_cnt to reflect no current sgls.
8624 	 * The next initialization cycle sets the count and allocates
8625 	 * the sgls over again.
8626 	 */
8627 	phba->sli4_hba.nvmet_xri_cnt = 0;
8628 }
8629 
8630 /**
8631  * lpfc_init_active_sgl_array - Allocate the buf to track active ELS XRIs.
8632  * @phba: pointer to lpfc hba data structure.
8633  *
8634  * This routine is invoked to allocate the driver's active sgl memory.
8635  * This array will hold the sglq_entry's for active IOs.
8636  **/
8637 static int
8638 lpfc_init_active_sgl_array(struct lpfc_hba *phba)
8639 {
8640 	int size;
8641 	size = sizeof(struct lpfc_sglq *);
8642 	size *= phba->sli4_hba.max_cfg_param.max_xri;
8643 
8644 	phba->sli4_hba.lpfc_sglq_active_list =
8645 		kzalloc(size, GFP_KERNEL);
8646 	if (!phba->sli4_hba.lpfc_sglq_active_list)
8647 		return -ENOMEM;
8648 	return 0;
8649 }
8650 
8651 /**
8652  * lpfc_free_active_sgl - Free the buf that tracks active ELS XRIs.
8653  * @phba: pointer to lpfc hba data structure.
8654  *
8655  * This routine is invoked to walk through the array of active sglq entries
8656  * and free all of the resources.
8657  * This is just a place holder for now.
8658  **/
8659 static void
8660 lpfc_free_active_sgl(struct lpfc_hba *phba)
8661 {
8662 	kfree(phba->sli4_hba.lpfc_sglq_active_list);
8663 }
8664 
8665 /**
8666  * lpfc_init_sgl_list - Allocate and initialize sgl list.
8667  * @phba: pointer to lpfc hba data structure.
8668  *
8669  * This routine is invoked to allocate and initizlize the driver's sgl
8670  * list and set up the sgl xritag tag array accordingly.
8671  *
8672  **/
8673 static void
8674 lpfc_init_sgl_list(struct lpfc_hba *phba)
8675 {
8676 	/* Initialize and populate the sglq list per host/VF. */
8677 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_els_sgl_list);
8678 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_els_sgl_list);
8679 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_nvmet_sgl_list);
8680 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
8681 
8682 	/* els xri-sgl book keeping */
8683 	phba->sli4_hba.els_xri_cnt = 0;
8684 
8685 	/* nvme xri-buffer book keeping */
8686 	phba->sli4_hba.io_xri_cnt = 0;
8687 }
8688 
8689 /**
8690  * lpfc_sli4_init_rpi_hdrs - Post the rpi header memory region to the port
8691  * @phba: pointer to lpfc hba data structure.
8692  *
8693  * This routine is invoked to post rpi header templates to the
8694  * port for those SLI4 ports that do not support extents.  This routine
8695  * posts a PAGE_SIZE memory region to the port to hold up to
8696  * PAGE_SIZE modulo 64 rpi context headers.  This is an initialization routine
8697  * and should be called only when interrupts are disabled.
8698  *
8699  * Return codes
8700  * 	0 - successful
8701  *	-ERROR - otherwise.
8702  **/
8703 int
8704 lpfc_sli4_init_rpi_hdrs(struct lpfc_hba *phba)
8705 {
8706 	int rc = 0;
8707 	struct lpfc_rpi_hdr *rpi_hdr;
8708 
8709 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_rpi_hdr_list);
8710 	if (!phba->sli4_hba.rpi_hdrs_in_use)
8711 		return rc;
8712 	if (phba->sli4_hba.extents_in_use)
8713 		return -EIO;
8714 
8715 	rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
8716 	if (!rpi_hdr) {
8717 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8718 				"0391 Error during rpi post operation\n");
8719 		lpfc_sli4_remove_rpis(phba);
8720 		rc = -ENODEV;
8721 	}
8722 
8723 	return rc;
8724 }
8725 
8726 /**
8727  * lpfc_sli4_create_rpi_hdr - Allocate an rpi header memory region
8728  * @phba: pointer to lpfc hba data structure.
8729  *
8730  * This routine is invoked to allocate a single 4KB memory region to
8731  * support rpis and stores them in the phba.  This single region
8732  * provides support for up to 64 rpis.  The region is used globally
8733  * by the device.
8734  *
8735  * Returns:
8736  *   A valid rpi hdr on success.
8737  *   A NULL pointer on any failure.
8738  **/
8739 struct lpfc_rpi_hdr *
8740 lpfc_sli4_create_rpi_hdr(struct lpfc_hba *phba)
8741 {
8742 	uint16_t rpi_limit, curr_rpi_range;
8743 	struct lpfc_dmabuf *dmabuf;
8744 	struct lpfc_rpi_hdr *rpi_hdr;
8745 
8746 	/*
8747 	 * If the SLI4 port supports extents, posting the rpi header isn't
8748 	 * required.  Set the expected maximum count and let the actual value
8749 	 * get set when extents are fully allocated.
8750 	 */
8751 	if (!phba->sli4_hba.rpi_hdrs_in_use)
8752 		return NULL;
8753 	if (phba->sli4_hba.extents_in_use)
8754 		return NULL;
8755 
8756 	/* The limit on the logical index is just the max_rpi count. */
8757 	rpi_limit = phba->sli4_hba.max_cfg_param.max_rpi;
8758 
8759 	spin_lock_irq(&phba->hbalock);
8760 	/*
8761 	 * Establish the starting RPI in this header block.  The starting
8762 	 * rpi is normalized to a zero base because the physical rpi is
8763 	 * port based.
8764 	 */
8765 	curr_rpi_range = phba->sli4_hba.next_rpi;
8766 	spin_unlock_irq(&phba->hbalock);
8767 
8768 	/* Reached full RPI range */
8769 	if (curr_rpi_range == rpi_limit)
8770 		return NULL;
8771 
8772 	/*
8773 	 * First allocate the protocol header region for the port.  The
8774 	 * port expects a 4KB DMA-mapped memory region that is 4K aligned.
8775 	 */
8776 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
8777 	if (!dmabuf)
8778 		return NULL;
8779 
8780 	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
8781 					  LPFC_HDR_TEMPLATE_SIZE,
8782 					  &dmabuf->phys, GFP_KERNEL);
8783 	if (!dmabuf->virt) {
8784 		rpi_hdr = NULL;
8785 		goto err_free_dmabuf;
8786 	}
8787 
8788 	if (!IS_ALIGNED(dmabuf->phys, LPFC_HDR_TEMPLATE_SIZE)) {
8789 		rpi_hdr = NULL;
8790 		goto err_free_coherent;
8791 	}
8792 
8793 	/* Save the rpi header data for cleanup later. */
8794 	rpi_hdr = kzalloc(sizeof(struct lpfc_rpi_hdr), GFP_KERNEL);
8795 	if (!rpi_hdr)
8796 		goto err_free_coherent;
8797 
8798 	rpi_hdr->dmabuf = dmabuf;
8799 	rpi_hdr->len = LPFC_HDR_TEMPLATE_SIZE;
8800 	rpi_hdr->page_count = 1;
8801 	spin_lock_irq(&phba->hbalock);
8802 
8803 	/* The rpi_hdr stores the logical index only. */
8804 	rpi_hdr->start_rpi = curr_rpi_range;
8805 	rpi_hdr->next_rpi = phba->sli4_hba.next_rpi + LPFC_RPI_HDR_COUNT;
8806 	list_add_tail(&rpi_hdr->list, &phba->sli4_hba.lpfc_rpi_hdr_list);
8807 
8808 	spin_unlock_irq(&phba->hbalock);
8809 	return rpi_hdr;
8810 
8811  err_free_coherent:
8812 	dma_free_coherent(&phba->pcidev->dev, LPFC_HDR_TEMPLATE_SIZE,
8813 			  dmabuf->virt, dmabuf->phys);
8814  err_free_dmabuf:
8815 	kfree(dmabuf);
8816 	return NULL;
8817 }
8818 
8819 /**
8820  * lpfc_sli4_remove_rpi_hdrs - Remove all rpi header memory regions
8821  * @phba: pointer to lpfc hba data structure.
8822  *
8823  * This routine is invoked to remove all memory resources allocated
8824  * to support rpis for SLI4 ports not supporting extents. This routine
8825  * presumes the caller has released all rpis consumed by fabric or port
8826  * logins and is prepared to have the header pages removed.
8827  **/
8828 void
8829 lpfc_sli4_remove_rpi_hdrs(struct lpfc_hba *phba)
8830 {
8831 	struct lpfc_rpi_hdr *rpi_hdr, *next_rpi_hdr;
8832 
8833 	if (!phba->sli4_hba.rpi_hdrs_in_use)
8834 		goto exit;
8835 
8836 	list_for_each_entry_safe(rpi_hdr, next_rpi_hdr,
8837 				 &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
8838 		list_del(&rpi_hdr->list);
8839 		dma_free_coherent(&phba->pcidev->dev, rpi_hdr->len,
8840 				  rpi_hdr->dmabuf->virt, rpi_hdr->dmabuf->phys);
8841 		kfree(rpi_hdr->dmabuf);
8842 		kfree(rpi_hdr);
8843 	}
8844  exit:
8845 	/* There are no rpis available to the port now. */
8846 	phba->sli4_hba.next_rpi = 0;
8847 }
8848 
8849 /**
8850  * lpfc_hba_alloc - Allocate driver hba data structure for a device.
8851  * @pdev: pointer to pci device data structure.
8852  *
8853  * This routine is invoked to allocate the driver hba data structure for an
8854  * HBA device. If the allocation is successful, the phba reference to the
8855  * PCI device data structure is set.
8856  *
8857  * Return codes
8858  *      pointer to @phba - successful
8859  *      NULL - error
8860  **/
8861 static struct lpfc_hba *
8862 lpfc_hba_alloc(struct pci_dev *pdev)
8863 {
8864 	struct lpfc_hba *phba;
8865 
8866 	/* Allocate memory for HBA structure */
8867 	phba = kzalloc(sizeof(struct lpfc_hba), GFP_KERNEL);
8868 	if (!phba) {
8869 		dev_err(&pdev->dev, "failed to allocate hba struct\n");
8870 		return NULL;
8871 	}
8872 
8873 	/* Set reference to PCI device in HBA structure */
8874 	phba->pcidev = pdev;
8875 
8876 	/* Assign an unused board number */
8877 	phba->brd_no = lpfc_get_instance();
8878 	if (phba->brd_no < 0) {
8879 		kfree(phba);
8880 		return NULL;
8881 	}
8882 	phba->eratt_poll_interval = LPFC_ERATT_POLL_INTERVAL;
8883 
8884 	spin_lock_init(&phba->ct_ev_lock);
8885 	INIT_LIST_HEAD(&phba->ct_ev_waiters);
8886 
8887 	return phba;
8888 }
8889 
8890 /**
8891  * lpfc_hba_free - Free driver hba data structure with a device.
8892  * @phba: pointer to lpfc hba data structure.
8893  *
8894  * This routine is invoked to free the driver hba data structure with an
8895  * HBA device.
8896  **/
8897 static void
8898 lpfc_hba_free(struct lpfc_hba *phba)
8899 {
8900 	if (phba->sli_rev == LPFC_SLI_REV4)
8901 		kfree(phba->sli4_hba.hdwq);
8902 
8903 	/* Release the driver assigned board number */
8904 	idr_remove(&lpfc_hba_index, phba->brd_no);
8905 
8906 	/* Free memory allocated with sli3 rings */
8907 	kfree(phba->sli.sli3_ring);
8908 	phba->sli.sli3_ring = NULL;
8909 
8910 	kfree(phba);
8911 	return;
8912 }
8913 
8914 /**
8915  * lpfc_create_shost - Create hba physical port with associated scsi host.
8916  * @phba: pointer to lpfc hba data structure.
8917  *
8918  * This routine is invoked to create HBA physical port and associate a SCSI
8919  * host with it.
8920  *
8921  * Return codes
8922  *      0 - successful
8923  *      other values - error
8924  **/
8925 static int
8926 lpfc_create_shost(struct lpfc_hba *phba)
8927 {
8928 	struct lpfc_vport *vport;
8929 	struct Scsi_Host  *shost;
8930 
8931 	/* Initialize HBA FC structure */
8932 	phba->fc_edtov = FF_DEF_EDTOV;
8933 	phba->fc_ratov = FF_DEF_RATOV;
8934 	phba->fc_altov = FF_DEF_ALTOV;
8935 	phba->fc_arbtov = FF_DEF_ARBTOV;
8936 
8937 	atomic_set(&phba->sdev_cnt, 0);
8938 	vport = lpfc_create_port(phba, phba->brd_no, &phba->pcidev->dev);
8939 	if (!vport)
8940 		return -ENODEV;
8941 
8942 	shost = lpfc_shost_from_vport(vport);
8943 	phba->pport = vport;
8944 
8945 	if (phba->nvmet_support) {
8946 		/* Only 1 vport (pport) will support NVME target */
8947 		phba->targetport = NULL;
8948 		phba->cfg_enable_fc4_type = LPFC_ENABLE_NVME;
8949 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_NVME_DISC,
8950 				"6076 NVME Target Found\n");
8951 	}
8952 
8953 	lpfc_debugfs_initialize(vport);
8954 	/* Put reference to SCSI host to driver's device private data */
8955 	pci_set_drvdata(phba->pcidev, shost);
8956 
8957 	/*
8958 	 * At this point we are fully registered with PSA. In addition,
8959 	 * any initial discovery should be completed.
8960 	 */
8961 	vport->load_flag |= FC_ALLOW_FDMI;
8962 	if (phba->cfg_enable_SmartSAN ||
8963 	    (phba->cfg_fdmi_on == LPFC_FDMI_SUPPORT)) {
8964 
8965 		/* Setup appropriate attribute masks */
8966 		vport->fdmi_hba_mask = LPFC_FDMI2_HBA_ATTR;
8967 		if (phba->cfg_enable_SmartSAN)
8968 			vport->fdmi_port_mask = LPFC_FDMI2_SMART_ATTR;
8969 		else
8970 			vport->fdmi_port_mask = LPFC_FDMI2_PORT_ATTR;
8971 	}
8972 	return 0;
8973 }
8974 
8975 /**
8976  * lpfc_destroy_shost - Destroy hba physical port with associated scsi host.
8977  * @phba: pointer to lpfc hba data structure.
8978  *
8979  * This routine is invoked to destroy HBA physical port and the associated
8980  * SCSI host.
8981  **/
8982 static void
8983 lpfc_destroy_shost(struct lpfc_hba *phba)
8984 {
8985 	struct lpfc_vport *vport = phba->pport;
8986 
8987 	/* Destroy physical port that associated with the SCSI host */
8988 	destroy_port(vport);
8989 
8990 	return;
8991 }
8992 
8993 /**
8994  * lpfc_setup_bg - Setup Block guard structures and debug areas.
8995  * @phba: pointer to lpfc hba data structure.
8996  * @shost: the shost to be used to detect Block guard settings.
8997  *
8998  * This routine sets up the local Block guard protocol settings for @shost.
8999  * This routine also allocates memory for debugging bg buffers.
9000  **/
9001 static void
9002 lpfc_setup_bg(struct lpfc_hba *phba, struct Scsi_Host *shost)
9003 {
9004 	uint32_t old_mask;
9005 	uint32_t old_guard;
9006 
9007 	if (phba->cfg_prot_mask && phba->cfg_prot_guard) {
9008 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9009 				"1478 Registering BlockGuard with the "
9010 				"SCSI layer\n");
9011 
9012 		old_mask = phba->cfg_prot_mask;
9013 		old_guard = phba->cfg_prot_guard;
9014 
9015 		/* Only allow supported values */
9016 		phba->cfg_prot_mask &= (SHOST_DIF_TYPE1_PROTECTION |
9017 			SHOST_DIX_TYPE0_PROTECTION |
9018 			SHOST_DIX_TYPE1_PROTECTION);
9019 		phba->cfg_prot_guard &= (SHOST_DIX_GUARD_IP |
9020 					 SHOST_DIX_GUARD_CRC);
9021 
9022 		/* DIF Type 1 protection for profiles AST1/C1 is end to end */
9023 		if (phba->cfg_prot_mask == SHOST_DIX_TYPE1_PROTECTION)
9024 			phba->cfg_prot_mask |= SHOST_DIF_TYPE1_PROTECTION;
9025 
9026 		if (phba->cfg_prot_mask && phba->cfg_prot_guard) {
9027 			if ((old_mask != phba->cfg_prot_mask) ||
9028 				(old_guard != phba->cfg_prot_guard))
9029 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9030 					"1475 Registering BlockGuard with the "
9031 					"SCSI layer: mask %d  guard %d\n",
9032 					phba->cfg_prot_mask,
9033 					phba->cfg_prot_guard);
9034 
9035 			scsi_host_set_prot(shost, phba->cfg_prot_mask);
9036 			scsi_host_set_guard(shost, phba->cfg_prot_guard);
9037 		} else
9038 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9039 				"1479 Not Registering BlockGuard with the SCSI "
9040 				"layer, Bad protection parameters: %d %d\n",
9041 				old_mask, old_guard);
9042 	}
9043 }
9044 
9045 /**
9046  * lpfc_post_init_setup - Perform necessary device post initialization setup.
9047  * @phba: pointer to lpfc hba data structure.
9048  *
9049  * This routine is invoked to perform all the necessary post initialization
9050  * setup for the device.
9051  **/
9052 static void
9053 lpfc_post_init_setup(struct lpfc_hba *phba)
9054 {
9055 	struct Scsi_Host  *shost;
9056 	struct lpfc_adapter_event_header adapter_event;
9057 
9058 	/* Get the default values for Model Name and Description */
9059 	lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
9060 
9061 	/*
9062 	 * hba setup may have changed the hba_queue_depth so we need to
9063 	 * adjust the value of can_queue.
9064 	 */
9065 	shost = pci_get_drvdata(phba->pcidev);
9066 	shost->can_queue = phba->cfg_hba_queue_depth - 10;
9067 
9068 	lpfc_host_attrib_init(shost);
9069 
9070 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
9071 		spin_lock_irq(shost->host_lock);
9072 		lpfc_poll_start_timer(phba);
9073 		spin_unlock_irq(shost->host_lock);
9074 	}
9075 
9076 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9077 			"0428 Perform SCSI scan\n");
9078 	/* Send board arrival event to upper layer */
9079 	adapter_event.event_type = FC_REG_ADAPTER_EVENT;
9080 	adapter_event.subcategory = LPFC_EVENT_ARRIVAL;
9081 	fc_host_post_vendor_event(shost, fc_get_event_number(),
9082 				  sizeof(adapter_event),
9083 				  (char *) &adapter_event,
9084 				  LPFC_NL_VENDOR_ID);
9085 	return;
9086 }
9087 
9088 /**
9089  * lpfc_sli_pci_mem_setup - Setup SLI3 HBA PCI memory space.
9090  * @phba: pointer to lpfc hba data structure.
9091  *
9092  * This routine is invoked to set up the PCI device memory space for device
9093  * with SLI-3 interface spec.
9094  *
9095  * Return codes
9096  * 	0 - successful
9097  * 	other values - error
9098  **/
9099 static int
9100 lpfc_sli_pci_mem_setup(struct lpfc_hba *phba)
9101 {
9102 	struct pci_dev *pdev = phba->pcidev;
9103 	unsigned long bar0map_len, bar2map_len;
9104 	int i, hbq_count;
9105 	void *ptr;
9106 	int error;
9107 
9108 	if (!pdev)
9109 		return -ENODEV;
9110 
9111 	/* Set the device DMA mask size */
9112 	error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
9113 	if (error)
9114 		error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32));
9115 	if (error)
9116 		return error;
9117 	error = -ENODEV;
9118 
9119 	/* Get the bus address of Bar0 and Bar2 and the number of bytes
9120 	 * required by each mapping.
9121 	 */
9122 	phba->pci_bar0_map = pci_resource_start(pdev, 0);
9123 	bar0map_len = pci_resource_len(pdev, 0);
9124 
9125 	phba->pci_bar2_map = pci_resource_start(pdev, 2);
9126 	bar2map_len = pci_resource_len(pdev, 2);
9127 
9128 	/* Map HBA SLIM to a kernel virtual address. */
9129 	phba->slim_memmap_p = ioremap(phba->pci_bar0_map, bar0map_len);
9130 	if (!phba->slim_memmap_p) {
9131 		dev_printk(KERN_ERR, &pdev->dev,
9132 			   "ioremap failed for SLIM memory.\n");
9133 		goto out;
9134 	}
9135 
9136 	/* Map HBA Control Registers to a kernel virtual address. */
9137 	phba->ctrl_regs_memmap_p = ioremap(phba->pci_bar2_map, bar2map_len);
9138 	if (!phba->ctrl_regs_memmap_p) {
9139 		dev_printk(KERN_ERR, &pdev->dev,
9140 			   "ioremap failed for HBA control registers.\n");
9141 		goto out_iounmap_slim;
9142 	}
9143 
9144 	/* Allocate memory for SLI-2 structures */
9145 	phba->slim2p.virt = dma_alloc_coherent(&pdev->dev, SLI2_SLIM_SIZE,
9146 					       &phba->slim2p.phys, GFP_KERNEL);
9147 	if (!phba->slim2p.virt)
9148 		goto out_iounmap;
9149 
9150 	phba->mbox = phba->slim2p.virt + offsetof(struct lpfc_sli2_slim, mbx);
9151 	phba->mbox_ext = (phba->slim2p.virt +
9152 		offsetof(struct lpfc_sli2_slim, mbx_ext_words));
9153 	phba->pcb = (phba->slim2p.virt + offsetof(struct lpfc_sli2_slim, pcb));
9154 	phba->IOCBs = (phba->slim2p.virt +
9155 		       offsetof(struct lpfc_sli2_slim, IOCBs));
9156 
9157 	phba->hbqslimp.virt = dma_alloc_coherent(&pdev->dev,
9158 						 lpfc_sli_hbq_size(),
9159 						 &phba->hbqslimp.phys,
9160 						 GFP_KERNEL);
9161 	if (!phba->hbqslimp.virt)
9162 		goto out_free_slim;
9163 
9164 	hbq_count = lpfc_sli_hbq_count();
9165 	ptr = phba->hbqslimp.virt;
9166 	for (i = 0; i < hbq_count; ++i) {
9167 		phba->hbqs[i].hbq_virt = ptr;
9168 		INIT_LIST_HEAD(&phba->hbqs[i].hbq_buffer_list);
9169 		ptr += (lpfc_hbq_defs[i]->entry_count *
9170 			sizeof(struct lpfc_hbq_entry));
9171 	}
9172 	phba->hbqs[LPFC_ELS_HBQ].hbq_alloc_buffer = lpfc_els_hbq_alloc;
9173 	phba->hbqs[LPFC_ELS_HBQ].hbq_free_buffer = lpfc_els_hbq_free;
9174 
9175 	memset(phba->hbqslimp.virt, 0, lpfc_sli_hbq_size());
9176 
9177 	phba->MBslimaddr = phba->slim_memmap_p;
9178 	phba->HAregaddr = phba->ctrl_regs_memmap_p + HA_REG_OFFSET;
9179 	phba->CAregaddr = phba->ctrl_regs_memmap_p + CA_REG_OFFSET;
9180 	phba->HSregaddr = phba->ctrl_regs_memmap_p + HS_REG_OFFSET;
9181 	phba->HCregaddr = phba->ctrl_regs_memmap_p + HC_REG_OFFSET;
9182 
9183 	return 0;
9184 
9185 out_free_slim:
9186 	dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
9187 			  phba->slim2p.virt, phba->slim2p.phys);
9188 out_iounmap:
9189 	iounmap(phba->ctrl_regs_memmap_p);
9190 out_iounmap_slim:
9191 	iounmap(phba->slim_memmap_p);
9192 out:
9193 	return error;
9194 }
9195 
9196 /**
9197  * lpfc_sli_pci_mem_unset - Unset SLI3 HBA PCI memory space.
9198  * @phba: pointer to lpfc hba data structure.
9199  *
9200  * This routine is invoked to unset the PCI device memory space for device
9201  * with SLI-3 interface spec.
9202  **/
9203 static void
9204 lpfc_sli_pci_mem_unset(struct lpfc_hba *phba)
9205 {
9206 	struct pci_dev *pdev;
9207 
9208 	/* Obtain PCI device reference */
9209 	if (!phba->pcidev)
9210 		return;
9211 	else
9212 		pdev = phba->pcidev;
9213 
9214 	/* Free coherent DMA memory allocated */
9215 	dma_free_coherent(&pdev->dev, lpfc_sli_hbq_size(),
9216 			  phba->hbqslimp.virt, phba->hbqslimp.phys);
9217 	dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
9218 			  phba->slim2p.virt, phba->slim2p.phys);
9219 
9220 	/* I/O memory unmap */
9221 	iounmap(phba->ctrl_regs_memmap_p);
9222 	iounmap(phba->slim_memmap_p);
9223 
9224 	return;
9225 }
9226 
9227 /**
9228  * lpfc_sli4_post_status_check - Wait for SLI4 POST done and check status
9229  * @phba: pointer to lpfc hba data structure.
9230  *
9231  * This routine is invoked to wait for SLI4 device Power On Self Test (POST)
9232  * done and check status.
9233  *
9234  * Return 0 if successful, otherwise -ENODEV.
9235  **/
9236 int
9237 lpfc_sli4_post_status_check(struct lpfc_hba *phba)
9238 {
9239 	struct lpfc_register portsmphr_reg, uerrlo_reg, uerrhi_reg;
9240 	struct lpfc_register reg_data;
9241 	int i, port_error = 0;
9242 	uint32_t if_type;
9243 
9244 	memset(&portsmphr_reg, 0, sizeof(portsmphr_reg));
9245 	memset(&reg_data, 0, sizeof(reg_data));
9246 	if (!phba->sli4_hba.PSMPHRregaddr)
9247 		return -ENODEV;
9248 
9249 	/* Wait up to 30 seconds for the SLI Port POST done and ready */
9250 	for (i = 0; i < 3000; i++) {
9251 		if (lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
9252 			&portsmphr_reg.word0) ||
9253 			(bf_get(lpfc_port_smphr_perr, &portsmphr_reg))) {
9254 			/* Port has a fatal POST error, break out */
9255 			port_error = -ENODEV;
9256 			break;
9257 		}
9258 		if (LPFC_POST_STAGE_PORT_READY ==
9259 		    bf_get(lpfc_port_smphr_port_status, &portsmphr_reg))
9260 			break;
9261 		msleep(10);
9262 	}
9263 
9264 	/*
9265 	 * If there was a port error during POST, then don't proceed with
9266 	 * other register reads as the data may not be valid.  Just exit.
9267 	 */
9268 	if (port_error) {
9269 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9270 			"1408 Port Failed POST - portsmphr=0x%x, "
9271 			"perr=x%x, sfi=x%x, nip=x%x, ipc=x%x, scr1=x%x, "
9272 			"scr2=x%x, hscratch=x%x, pstatus=x%x\n",
9273 			portsmphr_reg.word0,
9274 			bf_get(lpfc_port_smphr_perr, &portsmphr_reg),
9275 			bf_get(lpfc_port_smphr_sfi, &portsmphr_reg),
9276 			bf_get(lpfc_port_smphr_nip, &portsmphr_reg),
9277 			bf_get(lpfc_port_smphr_ipc, &portsmphr_reg),
9278 			bf_get(lpfc_port_smphr_scr1, &portsmphr_reg),
9279 			bf_get(lpfc_port_smphr_scr2, &portsmphr_reg),
9280 			bf_get(lpfc_port_smphr_host_scratch, &portsmphr_reg),
9281 			bf_get(lpfc_port_smphr_port_status, &portsmphr_reg));
9282 	} else {
9283 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9284 				"2534 Device Info: SLIFamily=0x%x, "
9285 				"SLIRev=0x%x, IFType=0x%x, SLIHint_1=0x%x, "
9286 				"SLIHint_2=0x%x, FT=0x%x\n",
9287 				bf_get(lpfc_sli_intf_sli_family,
9288 				       &phba->sli4_hba.sli_intf),
9289 				bf_get(lpfc_sli_intf_slirev,
9290 				       &phba->sli4_hba.sli_intf),
9291 				bf_get(lpfc_sli_intf_if_type,
9292 				       &phba->sli4_hba.sli_intf),
9293 				bf_get(lpfc_sli_intf_sli_hint1,
9294 				       &phba->sli4_hba.sli_intf),
9295 				bf_get(lpfc_sli_intf_sli_hint2,
9296 				       &phba->sli4_hba.sli_intf),
9297 				bf_get(lpfc_sli_intf_func_type,
9298 				       &phba->sli4_hba.sli_intf));
9299 		/*
9300 		 * Check for other Port errors during the initialization
9301 		 * process.  Fail the load if the port did not come up
9302 		 * correctly.
9303 		 */
9304 		if_type = bf_get(lpfc_sli_intf_if_type,
9305 				 &phba->sli4_hba.sli_intf);
9306 		switch (if_type) {
9307 		case LPFC_SLI_INTF_IF_TYPE_0:
9308 			phba->sli4_hba.ue_mask_lo =
9309 			      readl(phba->sli4_hba.u.if_type0.UEMASKLOregaddr);
9310 			phba->sli4_hba.ue_mask_hi =
9311 			      readl(phba->sli4_hba.u.if_type0.UEMASKHIregaddr);
9312 			uerrlo_reg.word0 =
9313 			      readl(phba->sli4_hba.u.if_type0.UERRLOregaddr);
9314 			uerrhi_reg.word0 =
9315 				readl(phba->sli4_hba.u.if_type0.UERRHIregaddr);
9316 			if ((~phba->sli4_hba.ue_mask_lo & uerrlo_reg.word0) ||
9317 			    (~phba->sli4_hba.ue_mask_hi & uerrhi_reg.word0)) {
9318 				lpfc_printf_log(phba, KERN_ERR,
9319 						LOG_TRACE_EVENT,
9320 						"1422 Unrecoverable Error "
9321 						"Detected during POST "
9322 						"uerr_lo_reg=0x%x, "
9323 						"uerr_hi_reg=0x%x, "
9324 						"ue_mask_lo_reg=0x%x, "
9325 						"ue_mask_hi_reg=0x%x\n",
9326 						uerrlo_reg.word0,
9327 						uerrhi_reg.word0,
9328 						phba->sli4_hba.ue_mask_lo,
9329 						phba->sli4_hba.ue_mask_hi);
9330 				port_error = -ENODEV;
9331 			}
9332 			break;
9333 		case LPFC_SLI_INTF_IF_TYPE_2:
9334 		case LPFC_SLI_INTF_IF_TYPE_6:
9335 			/* Final checks.  The port status should be clean. */
9336 			if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
9337 				&reg_data.word0) ||
9338 				(bf_get(lpfc_sliport_status_err, &reg_data) &&
9339 				 !bf_get(lpfc_sliport_status_rn, &reg_data))) {
9340 				phba->work_status[0] =
9341 					readl(phba->sli4_hba.u.if_type2.
9342 					      ERR1regaddr);
9343 				phba->work_status[1] =
9344 					readl(phba->sli4_hba.u.if_type2.
9345 					      ERR2regaddr);
9346 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9347 					"2888 Unrecoverable port error "
9348 					"following POST: port status reg "
9349 					"0x%x, port_smphr reg 0x%x, "
9350 					"error 1=0x%x, error 2=0x%x\n",
9351 					reg_data.word0,
9352 					portsmphr_reg.word0,
9353 					phba->work_status[0],
9354 					phba->work_status[1]);
9355 				port_error = -ENODEV;
9356 			}
9357 			break;
9358 		case LPFC_SLI_INTF_IF_TYPE_1:
9359 		default:
9360 			break;
9361 		}
9362 	}
9363 	return port_error;
9364 }
9365 
9366 /**
9367  * lpfc_sli4_bar0_register_memmap - Set up SLI4 BAR0 register memory map.
9368  * @phba: pointer to lpfc hba data structure.
9369  * @if_type:  The SLI4 interface type getting configured.
9370  *
9371  * This routine is invoked to set up SLI4 BAR0 PCI config space register
9372  * memory map.
9373  **/
9374 static void
9375 lpfc_sli4_bar0_register_memmap(struct lpfc_hba *phba, uint32_t if_type)
9376 {
9377 	switch (if_type) {
9378 	case LPFC_SLI_INTF_IF_TYPE_0:
9379 		phba->sli4_hba.u.if_type0.UERRLOregaddr =
9380 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UERR_STATUS_LO;
9381 		phba->sli4_hba.u.if_type0.UERRHIregaddr =
9382 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UERR_STATUS_HI;
9383 		phba->sli4_hba.u.if_type0.UEMASKLOregaddr =
9384 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UE_MASK_LO;
9385 		phba->sli4_hba.u.if_type0.UEMASKHIregaddr =
9386 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UE_MASK_HI;
9387 		phba->sli4_hba.SLIINTFregaddr =
9388 			phba->sli4_hba.conf_regs_memmap_p + LPFC_SLI_INTF;
9389 		break;
9390 	case LPFC_SLI_INTF_IF_TYPE_2:
9391 		phba->sli4_hba.u.if_type2.EQDregaddr =
9392 			phba->sli4_hba.conf_regs_memmap_p +
9393 						LPFC_CTL_PORT_EQ_DELAY_OFFSET;
9394 		phba->sli4_hba.u.if_type2.ERR1regaddr =
9395 			phba->sli4_hba.conf_regs_memmap_p +
9396 						LPFC_CTL_PORT_ER1_OFFSET;
9397 		phba->sli4_hba.u.if_type2.ERR2regaddr =
9398 			phba->sli4_hba.conf_regs_memmap_p +
9399 						LPFC_CTL_PORT_ER2_OFFSET;
9400 		phba->sli4_hba.u.if_type2.CTRLregaddr =
9401 			phba->sli4_hba.conf_regs_memmap_p +
9402 						LPFC_CTL_PORT_CTL_OFFSET;
9403 		phba->sli4_hba.u.if_type2.STATUSregaddr =
9404 			phba->sli4_hba.conf_regs_memmap_p +
9405 						LPFC_CTL_PORT_STA_OFFSET;
9406 		phba->sli4_hba.SLIINTFregaddr =
9407 			phba->sli4_hba.conf_regs_memmap_p + LPFC_SLI_INTF;
9408 		phba->sli4_hba.PSMPHRregaddr =
9409 			phba->sli4_hba.conf_regs_memmap_p +
9410 						LPFC_CTL_PORT_SEM_OFFSET;
9411 		phba->sli4_hba.RQDBregaddr =
9412 			phba->sli4_hba.conf_regs_memmap_p +
9413 						LPFC_ULP0_RQ_DOORBELL;
9414 		phba->sli4_hba.WQDBregaddr =
9415 			phba->sli4_hba.conf_regs_memmap_p +
9416 						LPFC_ULP0_WQ_DOORBELL;
9417 		phba->sli4_hba.CQDBregaddr =
9418 			phba->sli4_hba.conf_regs_memmap_p + LPFC_EQCQ_DOORBELL;
9419 		phba->sli4_hba.EQDBregaddr = phba->sli4_hba.CQDBregaddr;
9420 		phba->sli4_hba.MQDBregaddr =
9421 			phba->sli4_hba.conf_regs_memmap_p + LPFC_MQ_DOORBELL;
9422 		phba->sli4_hba.BMBXregaddr =
9423 			phba->sli4_hba.conf_regs_memmap_p + LPFC_BMBX;
9424 		break;
9425 	case LPFC_SLI_INTF_IF_TYPE_6:
9426 		phba->sli4_hba.u.if_type2.EQDregaddr =
9427 			phba->sli4_hba.conf_regs_memmap_p +
9428 						LPFC_CTL_PORT_EQ_DELAY_OFFSET;
9429 		phba->sli4_hba.u.if_type2.ERR1regaddr =
9430 			phba->sli4_hba.conf_regs_memmap_p +
9431 						LPFC_CTL_PORT_ER1_OFFSET;
9432 		phba->sli4_hba.u.if_type2.ERR2regaddr =
9433 			phba->sli4_hba.conf_regs_memmap_p +
9434 						LPFC_CTL_PORT_ER2_OFFSET;
9435 		phba->sli4_hba.u.if_type2.CTRLregaddr =
9436 			phba->sli4_hba.conf_regs_memmap_p +
9437 						LPFC_CTL_PORT_CTL_OFFSET;
9438 		phba->sli4_hba.u.if_type2.STATUSregaddr =
9439 			phba->sli4_hba.conf_regs_memmap_p +
9440 						LPFC_CTL_PORT_STA_OFFSET;
9441 		phba->sli4_hba.PSMPHRregaddr =
9442 			phba->sli4_hba.conf_regs_memmap_p +
9443 						LPFC_CTL_PORT_SEM_OFFSET;
9444 		phba->sli4_hba.BMBXregaddr =
9445 			phba->sli4_hba.conf_regs_memmap_p + LPFC_BMBX;
9446 		break;
9447 	case LPFC_SLI_INTF_IF_TYPE_1:
9448 	default:
9449 		dev_printk(KERN_ERR, &phba->pcidev->dev,
9450 			   "FATAL - unsupported SLI4 interface type - %d\n",
9451 			   if_type);
9452 		break;
9453 	}
9454 }
9455 
9456 /**
9457  * lpfc_sli4_bar1_register_memmap - Set up SLI4 BAR1 register memory map.
9458  * @phba: pointer to lpfc hba data structure.
9459  * @if_type: sli if type to operate on.
9460  *
9461  * This routine is invoked to set up SLI4 BAR1 register memory map.
9462  **/
9463 static void
9464 lpfc_sli4_bar1_register_memmap(struct lpfc_hba *phba, uint32_t if_type)
9465 {
9466 	switch (if_type) {
9467 	case LPFC_SLI_INTF_IF_TYPE_0:
9468 		phba->sli4_hba.PSMPHRregaddr =
9469 			phba->sli4_hba.ctrl_regs_memmap_p +
9470 			LPFC_SLIPORT_IF0_SMPHR;
9471 		phba->sli4_hba.ISRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
9472 			LPFC_HST_ISR0;
9473 		phba->sli4_hba.IMRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
9474 			LPFC_HST_IMR0;
9475 		phba->sli4_hba.ISCRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
9476 			LPFC_HST_ISCR0;
9477 		break;
9478 	case LPFC_SLI_INTF_IF_TYPE_6:
9479 		phba->sli4_hba.RQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9480 			LPFC_IF6_RQ_DOORBELL;
9481 		phba->sli4_hba.WQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9482 			LPFC_IF6_WQ_DOORBELL;
9483 		phba->sli4_hba.CQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9484 			LPFC_IF6_CQ_DOORBELL;
9485 		phba->sli4_hba.EQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9486 			LPFC_IF6_EQ_DOORBELL;
9487 		phba->sli4_hba.MQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9488 			LPFC_IF6_MQ_DOORBELL;
9489 		break;
9490 	case LPFC_SLI_INTF_IF_TYPE_2:
9491 	case LPFC_SLI_INTF_IF_TYPE_1:
9492 	default:
9493 		dev_err(&phba->pcidev->dev,
9494 			   "FATAL - unsupported SLI4 interface type - %d\n",
9495 			   if_type);
9496 		break;
9497 	}
9498 }
9499 
9500 /**
9501  * lpfc_sli4_bar2_register_memmap - Set up SLI4 BAR2 register memory map.
9502  * @phba: pointer to lpfc hba data structure.
9503  * @vf: virtual function number
9504  *
9505  * This routine is invoked to set up SLI4 BAR2 doorbell register memory map
9506  * based on the given viftual function number, @vf.
9507  *
9508  * Return 0 if successful, otherwise -ENODEV.
9509  **/
9510 static int
9511 lpfc_sli4_bar2_register_memmap(struct lpfc_hba *phba, uint32_t vf)
9512 {
9513 	if (vf > LPFC_VIR_FUNC_MAX)
9514 		return -ENODEV;
9515 
9516 	phba->sli4_hba.RQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9517 				vf * LPFC_VFR_PAGE_SIZE +
9518 					LPFC_ULP0_RQ_DOORBELL);
9519 	phba->sli4_hba.WQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9520 				vf * LPFC_VFR_PAGE_SIZE +
9521 					LPFC_ULP0_WQ_DOORBELL);
9522 	phba->sli4_hba.CQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9523 				vf * LPFC_VFR_PAGE_SIZE +
9524 					LPFC_EQCQ_DOORBELL);
9525 	phba->sli4_hba.EQDBregaddr = phba->sli4_hba.CQDBregaddr;
9526 	phba->sli4_hba.MQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9527 				vf * LPFC_VFR_PAGE_SIZE + LPFC_MQ_DOORBELL);
9528 	phba->sli4_hba.BMBXregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9529 				vf * LPFC_VFR_PAGE_SIZE + LPFC_BMBX);
9530 	return 0;
9531 }
9532 
9533 /**
9534  * lpfc_create_bootstrap_mbox - Create the bootstrap mailbox
9535  * @phba: pointer to lpfc hba data structure.
9536  *
9537  * This routine is invoked to create the bootstrap mailbox
9538  * region consistent with the SLI-4 interface spec.  This
9539  * routine allocates all memory necessary to communicate
9540  * mailbox commands to the port and sets up all alignment
9541  * needs.  No locks are expected to be held when calling
9542  * this routine.
9543  *
9544  * Return codes
9545  * 	0 - successful
9546  * 	-ENOMEM - could not allocated memory.
9547  **/
9548 static int
9549 lpfc_create_bootstrap_mbox(struct lpfc_hba *phba)
9550 {
9551 	uint32_t bmbx_size;
9552 	struct lpfc_dmabuf *dmabuf;
9553 	struct dma_address *dma_address;
9554 	uint32_t pa_addr;
9555 	uint64_t phys_addr;
9556 
9557 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
9558 	if (!dmabuf)
9559 		return -ENOMEM;
9560 
9561 	/*
9562 	 * The bootstrap mailbox region is comprised of 2 parts
9563 	 * plus an alignment restriction of 16 bytes.
9564 	 */
9565 	bmbx_size = sizeof(struct lpfc_bmbx_create) + (LPFC_ALIGN_16_BYTE - 1);
9566 	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev, bmbx_size,
9567 					  &dmabuf->phys, GFP_KERNEL);
9568 	if (!dmabuf->virt) {
9569 		kfree(dmabuf);
9570 		return -ENOMEM;
9571 	}
9572 
9573 	/*
9574 	 * Initialize the bootstrap mailbox pointers now so that the register
9575 	 * operations are simple later.  The mailbox dma address is required
9576 	 * to be 16-byte aligned.  Also align the virtual memory as each
9577 	 * maibox is copied into the bmbx mailbox region before issuing the
9578 	 * command to the port.
9579 	 */
9580 	phba->sli4_hba.bmbx.dmabuf = dmabuf;
9581 	phba->sli4_hba.bmbx.bmbx_size = bmbx_size;
9582 
9583 	phba->sli4_hba.bmbx.avirt = PTR_ALIGN(dmabuf->virt,
9584 					      LPFC_ALIGN_16_BYTE);
9585 	phba->sli4_hba.bmbx.aphys = ALIGN(dmabuf->phys,
9586 					      LPFC_ALIGN_16_BYTE);
9587 
9588 	/*
9589 	 * Set the high and low physical addresses now.  The SLI4 alignment
9590 	 * requirement is 16 bytes and the mailbox is posted to the port
9591 	 * as two 30-bit addresses.  The other data is a bit marking whether
9592 	 * the 30-bit address is the high or low address.
9593 	 * Upcast bmbx aphys to 64bits so shift instruction compiles
9594 	 * clean on 32 bit machines.
9595 	 */
9596 	dma_address = &phba->sli4_hba.bmbx.dma_address;
9597 	phys_addr = (uint64_t)phba->sli4_hba.bmbx.aphys;
9598 	pa_addr = (uint32_t) ((phys_addr >> 34) & 0x3fffffff);
9599 	dma_address->addr_hi = (uint32_t) ((pa_addr << 2) |
9600 					   LPFC_BMBX_BIT1_ADDR_HI);
9601 
9602 	pa_addr = (uint32_t) ((phba->sli4_hba.bmbx.aphys >> 4) & 0x3fffffff);
9603 	dma_address->addr_lo = (uint32_t) ((pa_addr << 2) |
9604 					   LPFC_BMBX_BIT1_ADDR_LO);
9605 	return 0;
9606 }
9607 
9608 /**
9609  * lpfc_destroy_bootstrap_mbox - Destroy all bootstrap mailbox resources
9610  * @phba: pointer to lpfc hba data structure.
9611  *
9612  * This routine is invoked to teardown the bootstrap mailbox
9613  * region and release all host resources. This routine requires
9614  * the caller to ensure all mailbox commands recovered, no
9615  * additional mailbox comands are sent, and interrupts are disabled
9616  * before calling this routine.
9617  *
9618  **/
9619 static void
9620 lpfc_destroy_bootstrap_mbox(struct lpfc_hba *phba)
9621 {
9622 	dma_free_coherent(&phba->pcidev->dev,
9623 			  phba->sli4_hba.bmbx.bmbx_size,
9624 			  phba->sli4_hba.bmbx.dmabuf->virt,
9625 			  phba->sli4_hba.bmbx.dmabuf->phys);
9626 
9627 	kfree(phba->sli4_hba.bmbx.dmabuf);
9628 	memset(&phba->sli4_hba.bmbx, 0, sizeof(struct lpfc_bmbx));
9629 }
9630 
9631 static const char * const lpfc_topo_to_str[] = {
9632 	"Loop then P2P",
9633 	"Loopback",
9634 	"P2P Only",
9635 	"Unsupported",
9636 	"Loop Only",
9637 	"Unsupported",
9638 	"P2P then Loop",
9639 };
9640 
9641 #define	LINK_FLAGS_DEF	0x0
9642 #define	LINK_FLAGS_P2P	0x1
9643 #define	LINK_FLAGS_LOOP	0x2
9644 /**
9645  * lpfc_map_topology - Map the topology read from READ_CONFIG
9646  * @phba: pointer to lpfc hba data structure.
9647  * @rd_config: pointer to read config data
9648  *
9649  * This routine is invoked to map the topology values as read
9650  * from the read config mailbox command. If the persistent
9651  * topology feature is supported, the firmware will provide the
9652  * saved topology information to be used in INIT_LINK
9653  **/
9654 static void
9655 lpfc_map_topology(struct lpfc_hba *phba, struct lpfc_mbx_read_config *rd_config)
9656 {
9657 	u8 ptv, tf, pt;
9658 
9659 	ptv = bf_get(lpfc_mbx_rd_conf_ptv, rd_config);
9660 	tf = bf_get(lpfc_mbx_rd_conf_tf, rd_config);
9661 	pt = bf_get(lpfc_mbx_rd_conf_pt, rd_config);
9662 
9663 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9664 			"2027 Read Config Data : ptv:0x%x, tf:0x%x pt:0x%x",
9665 			 ptv, tf, pt);
9666 	if (!ptv) {
9667 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9668 				"2019 FW does not support persistent topology "
9669 				"Using driver parameter defined value [%s]",
9670 				lpfc_topo_to_str[phba->cfg_topology]);
9671 		return;
9672 	}
9673 	/* FW supports persistent topology - override module parameter value */
9674 	phba->hba_flag |= HBA_PERSISTENT_TOPO;
9675 
9676 	/* if ASIC_GEN_NUM >= 0xC) */
9677 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
9678 		    LPFC_SLI_INTF_IF_TYPE_6) ||
9679 	    (bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf) ==
9680 		    LPFC_SLI_INTF_FAMILY_G6)) {
9681 		if (!tf) {
9682 			phba->cfg_topology = ((pt == LINK_FLAGS_LOOP)
9683 					? FLAGS_TOPOLOGY_MODE_LOOP
9684 					: FLAGS_TOPOLOGY_MODE_PT_PT);
9685 		} else {
9686 			phba->hba_flag &= ~HBA_PERSISTENT_TOPO;
9687 		}
9688 	} else { /* G5 */
9689 		if (tf) {
9690 			/* If topology failover set - pt is '0' or '1' */
9691 			phba->cfg_topology = (pt ? FLAGS_TOPOLOGY_MODE_PT_LOOP :
9692 					      FLAGS_TOPOLOGY_MODE_LOOP_PT);
9693 		} else {
9694 			phba->cfg_topology = ((pt == LINK_FLAGS_P2P)
9695 					? FLAGS_TOPOLOGY_MODE_PT_PT
9696 					: FLAGS_TOPOLOGY_MODE_LOOP);
9697 		}
9698 	}
9699 	if (phba->hba_flag & HBA_PERSISTENT_TOPO) {
9700 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9701 				"2020 Using persistent topology value [%s]",
9702 				lpfc_topo_to_str[phba->cfg_topology]);
9703 	} else {
9704 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9705 				"2021 Invalid topology values from FW "
9706 				"Using driver parameter defined value [%s]",
9707 				lpfc_topo_to_str[phba->cfg_topology]);
9708 	}
9709 }
9710 
9711 /**
9712  * lpfc_sli4_read_config - Get the config parameters.
9713  * @phba: pointer to lpfc hba data structure.
9714  *
9715  * This routine is invoked to read the configuration parameters from the HBA.
9716  * The configuration parameters are used to set the base and maximum values
9717  * for RPI's XRI's VPI's VFI's and FCFIs. These values also affect the resource
9718  * allocation for the port.
9719  *
9720  * Return codes
9721  * 	0 - successful
9722  * 	-ENOMEM - No available memory
9723  *      -EIO - The mailbox failed to complete successfully.
9724  **/
9725 int
9726 lpfc_sli4_read_config(struct lpfc_hba *phba)
9727 {
9728 	LPFC_MBOXQ_t *pmb;
9729 	struct lpfc_mbx_read_config *rd_config;
9730 	union  lpfc_sli4_cfg_shdr *shdr;
9731 	uint32_t shdr_status, shdr_add_status;
9732 	struct lpfc_mbx_get_func_cfg *get_func_cfg;
9733 	struct lpfc_rsrc_desc_fcfcoe *desc;
9734 	char *pdesc_0;
9735 	uint16_t forced_link_speed;
9736 	uint32_t if_type, qmin;
9737 	int length, i, rc = 0, rc2;
9738 
9739 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
9740 	if (!pmb) {
9741 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9742 				"2011 Unable to allocate memory for issuing "
9743 				"SLI_CONFIG_SPECIAL mailbox command\n");
9744 		return -ENOMEM;
9745 	}
9746 
9747 	lpfc_read_config(phba, pmb);
9748 
9749 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
9750 	if (rc != MBX_SUCCESS) {
9751 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9752 				"2012 Mailbox failed , mbxCmd x%x "
9753 				"READ_CONFIG, mbxStatus x%x\n",
9754 				bf_get(lpfc_mqe_command, &pmb->u.mqe),
9755 				bf_get(lpfc_mqe_status, &pmb->u.mqe));
9756 		rc = -EIO;
9757 	} else {
9758 		rd_config = &pmb->u.mqe.un.rd_config;
9759 		if (bf_get(lpfc_mbx_rd_conf_lnk_ldv, rd_config)) {
9760 			phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL;
9761 			phba->sli4_hba.lnk_info.lnk_tp =
9762 				bf_get(lpfc_mbx_rd_conf_lnk_type, rd_config);
9763 			phba->sli4_hba.lnk_info.lnk_no =
9764 				bf_get(lpfc_mbx_rd_conf_lnk_numb, rd_config);
9765 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9766 					"3081 lnk_type:%d, lnk_numb:%d\n",
9767 					phba->sli4_hba.lnk_info.lnk_tp,
9768 					phba->sli4_hba.lnk_info.lnk_no);
9769 		} else
9770 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9771 					"3082 Mailbox (x%x) returned ldv:x0\n",
9772 					bf_get(lpfc_mqe_command, &pmb->u.mqe));
9773 		if (bf_get(lpfc_mbx_rd_conf_bbscn_def, rd_config)) {
9774 			phba->bbcredit_support = 1;
9775 			phba->sli4_hba.bbscn_params.word0 = rd_config->word8;
9776 		}
9777 
9778 		phba->sli4_hba.conf_trunk =
9779 			bf_get(lpfc_mbx_rd_conf_trunk, rd_config);
9780 		phba->sli4_hba.extents_in_use =
9781 			bf_get(lpfc_mbx_rd_conf_extnts_inuse, rd_config);
9782 		phba->sli4_hba.max_cfg_param.max_xri =
9783 			bf_get(lpfc_mbx_rd_conf_xri_count, rd_config);
9784 		/* Reduce resource usage in kdump environment */
9785 		if (is_kdump_kernel() &&
9786 		    phba->sli4_hba.max_cfg_param.max_xri > 512)
9787 			phba->sli4_hba.max_cfg_param.max_xri = 512;
9788 		phba->sli4_hba.max_cfg_param.xri_base =
9789 			bf_get(lpfc_mbx_rd_conf_xri_base, rd_config);
9790 		phba->sli4_hba.max_cfg_param.max_vpi =
9791 			bf_get(lpfc_mbx_rd_conf_vpi_count, rd_config);
9792 		/* Limit the max we support */
9793 		if (phba->sli4_hba.max_cfg_param.max_vpi > LPFC_MAX_VPORTS)
9794 			phba->sli4_hba.max_cfg_param.max_vpi = LPFC_MAX_VPORTS;
9795 		phba->sli4_hba.max_cfg_param.vpi_base =
9796 			bf_get(lpfc_mbx_rd_conf_vpi_base, rd_config);
9797 		phba->sli4_hba.max_cfg_param.max_rpi =
9798 			bf_get(lpfc_mbx_rd_conf_rpi_count, rd_config);
9799 		phba->sli4_hba.max_cfg_param.rpi_base =
9800 			bf_get(lpfc_mbx_rd_conf_rpi_base, rd_config);
9801 		phba->sli4_hba.max_cfg_param.max_vfi =
9802 			bf_get(lpfc_mbx_rd_conf_vfi_count, rd_config);
9803 		phba->sli4_hba.max_cfg_param.vfi_base =
9804 			bf_get(lpfc_mbx_rd_conf_vfi_base, rd_config);
9805 		phba->sli4_hba.max_cfg_param.max_fcfi =
9806 			bf_get(lpfc_mbx_rd_conf_fcfi_count, rd_config);
9807 		phba->sli4_hba.max_cfg_param.max_eq =
9808 			bf_get(lpfc_mbx_rd_conf_eq_count, rd_config);
9809 		phba->sli4_hba.max_cfg_param.max_rq =
9810 			bf_get(lpfc_mbx_rd_conf_rq_count, rd_config);
9811 		phba->sli4_hba.max_cfg_param.max_wq =
9812 			bf_get(lpfc_mbx_rd_conf_wq_count, rd_config);
9813 		phba->sli4_hba.max_cfg_param.max_cq =
9814 			bf_get(lpfc_mbx_rd_conf_cq_count, rd_config);
9815 		phba->lmt = bf_get(lpfc_mbx_rd_conf_lmt, rd_config);
9816 		phba->sli4_hba.next_xri = phba->sli4_hba.max_cfg_param.xri_base;
9817 		phba->vpi_base = phba->sli4_hba.max_cfg_param.vpi_base;
9818 		phba->vfi_base = phba->sli4_hba.max_cfg_param.vfi_base;
9819 		phba->max_vpi = (phba->sli4_hba.max_cfg_param.max_vpi > 0) ?
9820 				(phba->sli4_hba.max_cfg_param.max_vpi - 1) : 0;
9821 		phba->max_vports = phba->max_vpi;
9822 
9823 		/* Next decide on FPIN or Signal E2E CGN support
9824 		 * For congestion alarms and warnings valid combination are:
9825 		 * 1. FPIN alarms / FPIN warnings
9826 		 * 2. Signal alarms / Signal warnings
9827 		 * 3. FPIN alarms / Signal warnings
9828 		 * 4. Signal alarms / FPIN warnings
9829 		 *
9830 		 * Initialize the adapter frequency to 100 mSecs
9831 		 */
9832 		phba->cgn_reg_fpin = LPFC_CGN_FPIN_BOTH;
9833 		phba->cgn_reg_signal = EDC_CG_SIG_NOTSUPPORTED;
9834 		phba->cgn_sig_freq = lpfc_fabric_cgn_frequency;
9835 
9836 		if (lpfc_use_cgn_signal) {
9837 			if (bf_get(lpfc_mbx_rd_conf_wcs, rd_config)) {
9838 				phba->cgn_reg_signal = EDC_CG_SIG_WARN_ONLY;
9839 				phba->cgn_reg_fpin &= ~LPFC_CGN_FPIN_WARN;
9840 			}
9841 			if (bf_get(lpfc_mbx_rd_conf_acs, rd_config)) {
9842 				/* MUST support both alarm and warning
9843 				 * because EDC does not support alarm alone.
9844 				 */
9845 				if (phba->cgn_reg_signal !=
9846 				    EDC_CG_SIG_WARN_ONLY) {
9847 					/* Must support both or none */
9848 					phba->cgn_reg_fpin = LPFC_CGN_FPIN_BOTH;
9849 					phba->cgn_reg_signal =
9850 						EDC_CG_SIG_NOTSUPPORTED;
9851 				} else {
9852 					phba->cgn_reg_signal =
9853 						EDC_CG_SIG_WARN_ALARM;
9854 					phba->cgn_reg_fpin =
9855 						LPFC_CGN_FPIN_NONE;
9856 				}
9857 			}
9858 		}
9859 
9860 		/* Set the congestion initial signal and fpin values. */
9861 		phba->cgn_init_reg_fpin = phba->cgn_reg_fpin;
9862 		phba->cgn_init_reg_signal = phba->cgn_reg_signal;
9863 
9864 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
9865 				"6446 READ_CONFIG reg_sig x%x reg_fpin:x%x\n",
9866 				phba->cgn_reg_signal, phba->cgn_reg_fpin);
9867 
9868 		lpfc_map_topology(phba, rd_config);
9869 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9870 				"2003 cfg params Extents? %d "
9871 				"XRI(B:%d M:%d), "
9872 				"VPI(B:%d M:%d) "
9873 				"VFI(B:%d M:%d) "
9874 				"RPI(B:%d M:%d) "
9875 				"FCFI:%d EQ:%d CQ:%d WQ:%d RQ:%d lmt:x%x\n",
9876 				phba->sli4_hba.extents_in_use,
9877 				phba->sli4_hba.max_cfg_param.xri_base,
9878 				phba->sli4_hba.max_cfg_param.max_xri,
9879 				phba->sli4_hba.max_cfg_param.vpi_base,
9880 				phba->sli4_hba.max_cfg_param.max_vpi,
9881 				phba->sli4_hba.max_cfg_param.vfi_base,
9882 				phba->sli4_hba.max_cfg_param.max_vfi,
9883 				phba->sli4_hba.max_cfg_param.rpi_base,
9884 				phba->sli4_hba.max_cfg_param.max_rpi,
9885 				phba->sli4_hba.max_cfg_param.max_fcfi,
9886 				phba->sli4_hba.max_cfg_param.max_eq,
9887 				phba->sli4_hba.max_cfg_param.max_cq,
9888 				phba->sli4_hba.max_cfg_param.max_wq,
9889 				phba->sli4_hba.max_cfg_param.max_rq,
9890 				phba->lmt);
9891 
9892 		/*
9893 		 * Calculate queue resources based on how
9894 		 * many WQ/CQ/EQs are available.
9895 		 */
9896 		qmin = phba->sli4_hba.max_cfg_param.max_wq;
9897 		if (phba->sli4_hba.max_cfg_param.max_cq < qmin)
9898 			qmin = phba->sli4_hba.max_cfg_param.max_cq;
9899 		if (phba->sli4_hba.max_cfg_param.max_eq < qmin)
9900 			qmin = phba->sli4_hba.max_cfg_param.max_eq;
9901 		/*
9902 		 * Whats left after this can go toward NVME / FCP.
9903 		 * The minus 4 accounts for ELS, NVME LS, MBOX
9904 		 * plus one extra. When configured for
9905 		 * NVMET, FCP io channel WQs are not created.
9906 		 */
9907 		qmin -= 4;
9908 
9909 		/* Check to see if there is enough for NVME */
9910 		if ((phba->cfg_irq_chann > qmin) ||
9911 		    (phba->cfg_hdw_queue > qmin)) {
9912 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9913 					"2005 Reducing Queues - "
9914 					"FW resource limitation: "
9915 					"WQ %d CQ %d EQ %d: min %d: "
9916 					"IRQ %d HDWQ %d\n",
9917 					phba->sli4_hba.max_cfg_param.max_wq,
9918 					phba->sli4_hba.max_cfg_param.max_cq,
9919 					phba->sli4_hba.max_cfg_param.max_eq,
9920 					qmin, phba->cfg_irq_chann,
9921 					phba->cfg_hdw_queue);
9922 
9923 			if (phba->cfg_irq_chann > qmin)
9924 				phba->cfg_irq_chann = qmin;
9925 			if (phba->cfg_hdw_queue > qmin)
9926 				phba->cfg_hdw_queue = qmin;
9927 		}
9928 	}
9929 
9930 	if (rc)
9931 		goto read_cfg_out;
9932 
9933 	/* Update link speed if forced link speed is supported */
9934 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
9935 	if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
9936 		forced_link_speed =
9937 			bf_get(lpfc_mbx_rd_conf_link_speed, rd_config);
9938 		if (forced_link_speed) {
9939 			phba->hba_flag |= HBA_FORCED_LINK_SPEED;
9940 
9941 			switch (forced_link_speed) {
9942 			case LINK_SPEED_1G:
9943 				phba->cfg_link_speed =
9944 					LPFC_USER_LINK_SPEED_1G;
9945 				break;
9946 			case LINK_SPEED_2G:
9947 				phba->cfg_link_speed =
9948 					LPFC_USER_LINK_SPEED_2G;
9949 				break;
9950 			case LINK_SPEED_4G:
9951 				phba->cfg_link_speed =
9952 					LPFC_USER_LINK_SPEED_4G;
9953 				break;
9954 			case LINK_SPEED_8G:
9955 				phba->cfg_link_speed =
9956 					LPFC_USER_LINK_SPEED_8G;
9957 				break;
9958 			case LINK_SPEED_10G:
9959 				phba->cfg_link_speed =
9960 					LPFC_USER_LINK_SPEED_10G;
9961 				break;
9962 			case LINK_SPEED_16G:
9963 				phba->cfg_link_speed =
9964 					LPFC_USER_LINK_SPEED_16G;
9965 				break;
9966 			case LINK_SPEED_32G:
9967 				phba->cfg_link_speed =
9968 					LPFC_USER_LINK_SPEED_32G;
9969 				break;
9970 			case LINK_SPEED_64G:
9971 				phba->cfg_link_speed =
9972 					LPFC_USER_LINK_SPEED_64G;
9973 				break;
9974 			case 0xffff:
9975 				phba->cfg_link_speed =
9976 					LPFC_USER_LINK_SPEED_AUTO;
9977 				break;
9978 			default:
9979 				lpfc_printf_log(phba, KERN_ERR,
9980 						LOG_TRACE_EVENT,
9981 						"0047 Unrecognized link "
9982 						"speed : %d\n",
9983 						forced_link_speed);
9984 				phba->cfg_link_speed =
9985 					LPFC_USER_LINK_SPEED_AUTO;
9986 			}
9987 		}
9988 	}
9989 
9990 	/* Reset the DFT_HBA_Q_DEPTH to the max xri  */
9991 	length = phba->sli4_hba.max_cfg_param.max_xri -
9992 			lpfc_sli4_get_els_iocb_cnt(phba);
9993 	if (phba->cfg_hba_queue_depth > length) {
9994 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
9995 				"3361 HBA queue depth changed from %d to %d\n",
9996 				phba->cfg_hba_queue_depth, length);
9997 		phba->cfg_hba_queue_depth = length;
9998 	}
9999 
10000 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) <
10001 	    LPFC_SLI_INTF_IF_TYPE_2)
10002 		goto read_cfg_out;
10003 
10004 	/* get the pf# and vf# for SLI4 if_type 2 port */
10005 	length = (sizeof(struct lpfc_mbx_get_func_cfg) -
10006 		  sizeof(struct lpfc_sli4_cfg_mhdr));
10007 	lpfc_sli4_config(phba, pmb, LPFC_MBOX_SUBSYSTEM_COMMON,
10008 			 LPFC_MBOX_OPCODE_GET_FUNCTION_CONFIG,
10009 			 length, LPFC_SLI4_MBX_EMBED);
10010 
10011 	rc2 = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
10012 	shdr = (union lpfc_sli4_cfg_shdr *)
10013 				&pmb->u.mqe.un.sli4_config.header.cfg_shdr;
10014 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
10015 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
10016 	if (rc2 || shdr_status || shdr_add_status) {
10017 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10018 				"3026 Mailbox failed , mbxCmd x%x "
10019 				"GET_FUNCTION_CONFIG, mbxStatus x%x\n",
10020 				bf_get(lpfc_mqe_command, &pmb->u.mqe),
10021 				bf_get(lpfc_mqe_status, &pmb->u.mqe));
10022 		goto read_cfg_out;
10023 	}
10024 
10025 	/* search for fc_fcoe resrouce descriptor */
10026 	get_func_cfg = &pmb->u.mqe.un.get_func_cfg;
10027 
10028 	pdesc_0 = (char *)&get_func_cfg->func_cfg.desc[0];
10029 	desc = (struct lpfc_rsrc_desc_fcfcoe *)pdesc_0;
10030 	length = bf_get(lpfc_rsrc_desc_fcfcoe_length, desc);
10031 	if (length == LPFC_RSRC_DESC_TYPE_FCFCOE_V0_RSVD)
10032 		length = LPFC_RSRC_DESC_TYPE_FCFCOE_V0_LENGTH;
10033 	else if (length != LPFC_RSRC_DESC_TYPE_FCFCOE_V1_LENGTH)
10034 		goto read_cfg_out;
10035 
10036 	for (i = 0; i < LPFC_RSRC_DESC_MAX_NUM; i++) {
10037 		desc = (struct lpfc_rsrc_desc_fcfcoe *)(pdesc_0 + length * i);
10038 		if (LPFC_RSRC_DESC_TYPE_FCFCOE ==
10039 		    bf_get(lpfc_rsrc_desc_fcfcoe_type, desc)) {
10040 			phba->sli4_hba.iov.pf_number =
10041 				bf_get(lpfc_rsrc_desc_fcfcoe_pfnum, desc);
10042 			phba->sli4_hba.iov.vf_number =
10043 				bf_get(lpfc_rsrc_desc_fcfcoe_vfnum, desc);
10044 			break;
10045 		}
10046 	}
10047 
10048 	if (i < LPFC_RSRC_DESC_MAX_NUM)
10049 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10050 				"3027 GET_FUNCTION_CONFIG: pf_number:%d, "
10051 				"vf_number:%d\n", phba->sli4_hba.iov.pf_number,
10052 				phba->sli4_hba.iov.vf_number);
10053 	else
10054 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10055 				"3028 GET_FUNCTION_CONFIG: failed to find "
10056 				"Resource Descriptor:x%x\n",
10057 				LPFC_RSRC_DESC_TYPE_FCFCOE);
10058 
10059 read_cfg_out:
10060 	mempool_free(pmb, phba->mbox_mem_pool);
10061 	return rc;
10062 }
10063 
10064 /**
10065  * lpfc_setup_endian_order - Write endian order to an SLI4 if_type 0 port.
10066  * @phba: pointer to lpfc hba data structure.
10067  *
10068  * This routine is invoked to setup the port-side endian order when
10069  * the port if_type is 0.  This routine has no function for other
10070  * if_types.
10071  *
10072  * Return codes
10073  * 	0 - successful
10074  * 	-ENOMEM - No available memory
10075  *      -EIO - The mailbox failed to complete successfully.
10076  **/
10077 static int
10078 lpfc_setup_endian_order(struct lpfc_hba *phba)
10079 {
10080 	LPFC_MBOXQ_t *mboxq;
10081 	uint32_t if_type, rc = 0;
10082 	uint32_t endian_mb_data[2] = {HOST_ENDIAN_LOW_WORD0,
10083 				      HOST_ENDIAN_HIGH_WORD1};
10084 
10085 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
10086 	switch (if_type) {
10087 	case LPFC_SLI_INTF_IF_TYPE_0:
10088 		mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
10089 						       GFP_KERNEL);
10090 		if (!mboxq) {
10091 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10092 					"0492 Unable to allocate memory for "
10093 					"issuing SLI_CONFIG_SPECIAL mailbox "
10094 					"command\n");
10095 			return -ENOMEM;
10096 		}
10097 
10098 		/*
10099 		 * The SLI4_CONFIG_SPECIAL mailbox command requires the first
10100 		 * two words to contain special data values and no other data.
10101 		 */
10102 		memset(mboxq, 0, sizeof(LPFC_MBOXQ_t));
10103 		memcpy(&mboxq->u.mqe, &endian_mb_data, sizeof(endian_mb_data));
10104 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
10105 		if (rc != MBX_SUCCESS) {
10106 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10107 					"0493 SLI_CONFIG_SPECIAL mailbox "
10108 					"failed with status x%x\n",
10109 					rc);
10110 			rc = -EIO;
10111 		}
10112 		mempool_free(mboxq, phba->mbox_mem_pool);
10113 		break;
10114 	case LPFC_SLI_INTF_IF_TYPE_6:
10115 	case LPFC_SLI_INTF_IF_TYPE_2:
10116 	case LPFC_SLI_INTF_IF_TYPE_1:
10117 	default:
10118 		break;
10119 	}
10120 	return rc;
10121 }
10122 
10123 /**
10124  * lpfc_sli4_queue_verify - Verify and update EQ counts
10125  * @phba: pointer to lpfc hba data structure.
10126  *
10127  * This routine is invoked to check the user settable queue counts for EQs.
10128  * After this routine is called the counts will be set to valid values that
10129  * adhere to the constraints of the system's interrupt vectors and the port's
10130  * queue resources.
10131  *
10132  * Return codes
10133  *      0 - successful
10134  *      -ENOMEM - No available memory
10135  **/
10136 static int
10137 lpfc_sli4_queue_verify(struct lpfc_hba *phba)
10138 {
10139 	/*
10140 	 * Sanity check for configured queue parameters against the run-time
10141 	 * device parameters
10142 	 */
10143 
10144 	if (phba->nvmet_support) {
10145 		if (phba->cfg_hdw_queue < phba->cfg_nvmet_mrq)
10146 			phba->cfg_nvmet_mrq = phba->cfg_hdw_queue;
10147 		if (phba->cfg_nvmet_mrq > LPFC_NVMET_MRQ_MAX)
10148 			phba->cfg_nvmet_mrq = LPFC_NVMET_MRQ_MAX;
10149 	}
10150 
10151 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10152 			"2574 IO channels: hdwQ %d IRQ %d MRQ: %d\n",
10153 			phba->cfg_hdw_queue, phba->cfg_irq_chann,
10154 			phba->cfg_nvmet_mrq);
10155 
10156 	/* Get EQ depth from module parameter, fake the default for now */
10157 	phba->sli4_hba.eq_esize = LPFC_EQE_SIZE_4B;
10158 	phba->sli4_hba.eq_ecount = LPFC_EQE_DEF_COUNT;
10159 
10160 	/* Get CQ depth from module parameter, fake the default for now */
10161 	phba->sli4_hba.cq_esize = LPFC_CQE_SIZE;
10162 	phba->sli4_hba.cq_ecount = LPFC_CQE_DEF_COUNT;
10163 	return 0;
10164 }
10165 
10166 static int
10167 lpfc_alloc_io_wq_cq(struct lpfc_hba *phba, int idx)
10168 {
10169 	struct lpfc_queue *qdesc;
10170 	u32 wqesize;
10171 	int cpu;
10172 
10173 	cpu = lpfc_find_cpu_handle(phba, idx, LPFC_FIND_BY_HDWQ);
10174 	/* Create Fast Path IO CQs */
10175 	if (phba->enab_exp_wqcq_pages)
10176 		/* Increase the CQ size when WQEs contain an embedded cdb */
10177 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_EXPANDED_PAGE_SIZE,
10178 					      phba->sli4_hba.cq_esize,
10179 					      LPFC_CQE_EXP_COUNT, cpu);
10180 
10181 	else
10182 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10183 					      phba->sli4_hba.cq_esize,
10184 					      phba->sli4_hba.cq_ecount, cpu);
10185 	if (!qdesc) {
10186 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10187 				"0499 Failed allocate fast-path IO CQ (%d)\n",
10188 				idx);
10189 		return 1;
10190 	}
10191 	qdesc->qe_valid = 1;
10192 	qdesc->hdwq = idx;
10193 	qdesc->chann = cpu;
10194 	phba->sli4_hba.hdwq[idx].io_cq = qdesc;
10195 
10196 	/* Create Fast Path IO WQs */
10197 	if (phba->enab_exp_wqcq_pages) {
10198 		/* Increase the WQ size when WQEs contain an embedded cdb */
10199 		wqesize = (phba->fcp_embed_io) ?
10200 			LPFC_WQE128_SIZE : phba->sli4_hba.wq_esize;
10201 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_EXPANDED_PAGE_SIZE,
10202 					      wqesize,
10203 					      LPFC_WQE_EXP_COUNT, cpu);
10204 	} else
10205 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10206 					      phba->sli4_hba.wq_esize,
10207 					      phba->sli4_hba.wq_ecount, cpu);
10208 
10209 	if (!qdesc) {
10210 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10211 				"0503 Failed allocate fast-path IO WQ (%d)\n",
10212 				idx);
10213 		return 1;
10214 	}
10215 	qdesc->hdwq = idx;
10216 	qdesc->chann = cpu;
10217 	phba->sli4_hba.hdwq[idx].io_wq = qdesc;
10218 	list_add_tail(&qdesc->wq_list, &phba->sli4_hba.lpfc_wq_list);
10219 	return 0;
10220 }
10221 
10222 /**
10223  * lpfc_sli4_queue_create - Create all the SLI4 queues
10224  * @phba: pointer to lpfc hba data structure.
10225  *
10226  * This routine is invoked to allocate all the SLI4 queues for the FCoE HBA
10227  * operation. For each SLI4 queue type, the parameters such as queue entry
10228  * count (queue depth) shall be taken from the module parameter. For now,
10229  * we just use some constant number as place holder.
10230  *
10231  * Return codes
10232  *      0 - successful
10233  *      -ENOMEM - No availble memory
10234  *      -EIO - The mailbox failed to complete successfully.
10235  **/
10236 int
10237 lpfc_sli4_queue_create(struct lpfc_hba *phba)
10238 {
10239 	struct lpfc_queue *qdesc;
10240 	int idx, cpu, eqcpu;
10241 	struct lpfc_sli4_hdw_queue *qp;
10242 	struct lpfc_vector_map_info *cpup;
10243 	struct lpfc_vector_map_info *eqcpup;
10244 	struct lpfc_eq_intr_info *eqi;
10245 
10246 	/*
10247 	 * Create HBA Record arrays.
10248 	 * Both NVME and FCP will share that same vectors / EQs
10249 	 */
10250 	phba->sli4_hba.mq_esize = LPFC_MQE_SIZE;
10251 	phba->sli4_hba.mq_ecount = LPFC_MQE_DEF_COUNT;
10252 	phba->sli4_hba.wq_esize = LPFC_WQE_SIZE;
10253 	phba->sli4_hba.wq_ecount = LPFC_WQE_DEF_COUNT;
10254 	phba->sli4_hba.rq_esize = LPFC_RQE_SIZE;
10255 	phba->sli4_hba.rq_ecount = LPFC_RQE_DEF_COUNT;
10256 	phba->sli4_hba.eq_esize = LPFC_EQE_SIZE_4B;
10257 	phba->sli4_hba.eq_ecount = LPFC_EQE_DEF_COUNT;
10258 	phba->sli4_hba.cq_esize = LPFC_CQE_SIZE;
10259 	phba->sli4_hba.cq_ecount = LPFC_CQE_DEF_COUNT;
10260 
10261 	if (!phba->sli4_hba.hdwq) {
10262 		phba->sli4_hba.hdwq = kcalloc(
10263 			phba->cfg_hdw_queue, sizeof(struct lpfc_sli4_hdw_queue),
10264 			GFP_KERNEL);
10265 		if (!phba->sli4_hba.hdwq) {
10266 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10267 					"6427 Failed allocate memory for "
10268 					"fast-path Hardware Queue array\n");
10269 			goto out_error;
10270 		}
10271 		/* Prepare hardware queues to take IO buffers */
10272 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10273 			qp = &phba->sli4_hba.hdwq[idx];
10274 			spin_lock_init(&qp->io_buf_list_get_lock);
10275 			spin_lock_init(&qp->io_buf_list_put_lock);
10276 			INIT_LIST_HEAD(&qp->lpfc_io_buf_list_get);
10277 			INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
10278 			qp->get_io_bufs = 0;
10279 			qp->put_io_bufs = 0;
10280 			qp->total_io_bufs = 0;
10281 			spin_lock_init(&qp->abts_io_buf_list_lock);
10282 			INIT_LIST_HEAD(&qp->lpfc_abts_io_buf_list);
10283 			qp->abts_scsi_io_bufs = 0;
10284 			qp->abts_nvme_io_bufs = 0;
10285 			INIT_LIST_HEAD(&qp->sgl_list);
10286 			INIT_LIST_HEAD(&qp->cmd_rsp_buf_list);
10287 			spin_lock_init(&qp->hdwq_lock);
10288 		}
10289 	}
10290 
10291 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
10292 		if (phba->nvmet_support) {
10293 			phba->sli4_hba.nvmet_cqset = kcalloc(
10294 					phba->cfg_nvmet_mrq,
10295 					sizeof(struct lpfc_queue *),
10296 					GFP_KERNEL);
10297 			if (!phba->sli4_hba.nvmet_cqset) {
10298 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10299 					"3121 Fail allocate memory for "
10300 					"fast-path CQ set array\n");
10301 				goto out_error;
10302 			}
10303 			phba->sli4_hba.nvmet_mrq_hdr = kcalloc(
10304 					phba->cfg_nvmet_mrq,
10305 					sizeof(struct lpfc_queue *),
10306 					GFP_KERNEL);
10307 			if (!phba->sli4_hba.nvmet_mrq_hdr) {
10308 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10309 					"3122 Fail allocate memory for "
10310 					"fast-path RQ set hdr array\n");
10311 				goto out_error;
10312 			}
10313 			phba->sli4_hba.nvmet_mrq_data = kcalloc(
10314 					phba->cfg_nvmet_mrq,
10315 					sizeof(struct lpfc_queue *),
10316 					GFP_KERNEL);
10317 			if (!phba->sli4_hba.nvmet_mrq_data) {
10318 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10319 					"3124 Fail allocate memory for "
10320 					"fast-path RQ set data array\n");
10321 				goto out_error;
10322 			}
10323 		}
10324 	}
10325 
10326 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_wq_list);
10327 
10328 	/* Create HBA Event Queues (EQs) */
10329 	for_each_present_cpu(cpu) {
10330 		/* We only want to create 1 EQ per vector, even though
10331 		 * multiple CPUs might be using that vector. so only
10332 		 * selects the CPUs that are LPFC_CPU_FIRST_IRQ.
10333 		 */
10334 		cpup = &phba->sli4_hba.cpu_map[cpu];
10335 		if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
10336 			continue;
10337 
10338 		/* Get a ptr to the Hardware Queue associated with this CPU */
10339 		qp = &phba->sli4_hba.hdwq[cpup->hdwq];
10340 
10341 		/* Allocate an EQ */
10342 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10343 					      phba->sli4_hba.eq_esize,
10344 					      phba->sli4_hba.eq_ecount, cpu);
10345 		if (!qdesc) {
10346 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10347 					"0497 Failed allocate EQ (%d)\n",
10348 					cpup->hdwq);
10349 			goto out_error;
10350 		}
10351 		qdesc->qe_valid = 1;
10352 		qdesc->hdwq = cpup->hdwq;
10353 		qdesc->chann = cpu; /* First CPU this EQ is affinitized to */
10354 		qdesc->last_cpu = qdesc->chann;
10355 
10356 		/* Save the allocated EQ in the Hardware Queue */
10357 		qp->hba_eq = qdesc;
10358 
10359 		eqi = per_cpu_ptr(phba->sli4_hba.eq_info, qdesc->last_cpu);
10360 		list_add(&qdesc->cpu_list, &eqi->list);
10361 	}
10362 
10363 	/* Now we need to populate the other Hardware Queues, that share
10364 	 * an IRQ vector, with the associated EQ ptr.
10365 	 */
10366 	for_each_present_cpu(cpu) {
10367 		cpup = &phba->sli4_hba.cpu_map[cpu];
10368 
10369 		/* Check for EQ already allocated in previous loop */
10370 		if (cpup->flag & LPFC_CPU_FIRST_IRQ)
10371 			continue;
10372 
10373 		/* Check for multiple CPUs per hdwq */
10374 		qp = &phba->sli4_hba.hdwq[cpup->hdwq];
10375 		if (qp->hba_eq)
10376 			continue;
10377 
10378 		/* We need to share an EQ for this hdwq */
10379 		eqcpu = lpfc_find_cpu_handle(phba, cpup->eq, LPFC_FIND_BY_EQ);
10380 		eqcpup = &phba->sli4_hba.cpu_map[eqcpu];
10381 		qp->hba_eq = phba->sli4_hba.hdwq[eqcpup->hdwq].hba_eq;
10382 	}
10383 
10384 	/* Allocate IO Path SLI4 CQ/WQs */
10385 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10386 		if (lpfc_alloc_io_wq_cq(phba, idx))
10387 			goto out_error;
10388 	}
10389 
10390 	if (phba->nvmet_support) {
10391 		for (idx = 0; idx < phba->cfg_nvmet_mrq; idx++) {
10392 			cpu = lpfc_find_cpu_handle(phba, idx,
10393 						   LPFC_FIND_BY_HDWQ);
10394 			qdesc = lpfc_sli4_queue_alloc(phba,
10395 						      LPFC_DEFAULT_PAGE_SIZE,
10396 						      phba->sli4_hba.cq_esize,
10397 						      phba->sli4_hba.cq_ecount,
10398 						      cpu);
10399 			if (!qdesc) {
10400 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10401 						"3142 Failed allocate NVME "
10402 						"CQ Set (%d)\n", idx);
10403 				goto out_error;
10404 			}
10405 			qdesc->qe_valid = 1;
10406 			qdesc->hdwq = idx;
10407 			qdesc->chann = cpu;
10408 			phba->sli4_hba.nvmet_cqset[idx] = qdesc;
10409 		}
10410 	}
10411 
10412 	/*
10413 	 * Create Slow Path Completion Queues (CQs)
10414 	 */
10415 
10416 	cpu = lpfc_find_cpu_handle(phba, 0, LPFC_FIND_BY_EQ);
10417 	/* Create slow-path Mailbox Command Complete Queue */
10418 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10419 				      phba->sli4_hba.cq_esize,
10420 				      phba->sli4_hba.cq_ecount, cpu);
10421 	if (!qdesc) {
10422 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10423 				"0500 Failed allocate slow-path mailbox CQ\n");
10424 		goto out_error;
10425 	}
10426 	qdesc->qe_valid = 1;
10427 	phba->sli4_hba.mbx_cq = qdesc;
10428 
10429 	/* Create slow-path ELS Complete Queue */
10430 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10431 				      phba->sli4_hba.cq_esize,
10432 				      phba->sli4_hba.cq_ecount, cpu);
10433 	if (!qdesc) {
10434 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10435 				"0501 Failed allocate slow-path ELS CQ\n");
10436 		goto out_error;
10437 	}
10438 	qdesc->qe_valid = 1;
10439 	qdesc->chann = cpu;
10440 	phba->sli4_hba.els_cq = qdesc;
10441 
10442 
10443 	/*
10444 	 * Create Slow Path Work Queues (WQs)
10445 	 */
10446 
10447 	/* Create Mailbox Command Queue */
10448 
10449 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10450 				      phba->sli4_hba.mq_esize,
10451 				      phba->sli4_hba.mq_ecount, cpu);
10452 	if (!qdesc) {
10453 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10454 				"0505 Failed allocate slow-path MQ\n");
10455 		goto out_error;
10456 	}
10457 	qdesc->chann = cpu;
10458 	phba->sli4_hba.mbx_wq = qdesc;
10459 
10460 	/*
10461 	 * Create ELS Work Queues
10462 	 */
10463 
10464 	/* Create slow-path ELS Work Queue */
10465 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10466 				      phba->sli4_hba.wq_esize,
10467 				      phba->sli4_hba.wq_ecount, cpu);
10468 	if (!qdesc) {
10469 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10470 				"0504 Failed allocate slow-path ELS WQ\n");
10471 		goto out_error;
10472 	}
10473 	qdesc->chann = cpu;
10474 	phba->sli4_hba.els_wq = qdesc;
10475 	list_add_tail(&qdesc->wq_list, &phba->sli4_hba.lpfc_wq_list);
10476 
10477 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
10478 		/* Create NVME LS Complete Queue */
10479 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10480 					      phba->sli4_hba.cq_esize,
10481 					      phba->sli4_hba.cq_ecount, cpu);
10482 		if (!qdesc) {
10483 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10484 					"6079 Failed allocate NVME LS CQ\n");
10485 			goto out_error;
10486 		}
10487 		qdesc->chann = cpu;
10488 		qdesc->qe_valid = 1;
10489 		phba->sli4_hba.nvmels_cq = qdesc;
10490 
10491 		/* Create NVME LS Work Queue */
10492 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10493 					      phba->sli4_hba.wq_esize,
10494 					      phba->sli4_hba.wq_ecount, cpu);
10495 		if (!qdesc) {
10496 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10497 					"6080 Failed allocate NVME LS WQ\n");
10498 			goto out_error;
10499 		}
10500 		qdesc->chann = cpu;
10501 		phba->sli4_hba.nvmels_wq = qdesc;
10502 		list_add_tail(&qdesc->wq_list, &phba->sli4_hba.lpfc_wq_list);
10503 	}
10504 
10505 	/*
10506 	 * Create Receive Queue (RQ)
10507 	 */
10508 
10509 	/* Create Receive Queue for header */
10510 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10511 				      phba->sli4_hba.rq_esize,
10512 				      phba->sli4_hba.rq_ecount, cpu);
10513 	if (!qdesc) {
10514 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10515 				"0506 Failed allocate receive HRQ\n");
10516 		goto out_error;
10517 	}
10518 	phba->sli4_hba.hdr_rq = qdesc;
10519 
10520 	/* Create Receive Queue for data */
10521 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10522 				      phba->sli4_hba.rq_esize,
10523 				      phba->sli4_hba.rq_ecount, cpu);
10524 	if (!qdesc) {
10525 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10526 				"0507 Failed allocate receive DRQ\n");
10527 		goto out_error;
10528 	}
10529 	phba->sli4_hba.dat_rq = qdesc;
10530 
10531 	if ((phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) &&
10532 	    phba->nvmet_support) {
10533 		for (idx = 0; idx < phba->cfg_nvmet_mrq; idx++) {
10534 			cpu = lpfc_find_cpu_handle(phba, idx,
10535 						   LPFC_FIND_BY_HDWQ);
10536 			/* Create NVMET Receive Queue for header */
10537 			qdesc = lpfc_sli4_queue_alloc(phba,
10538 						      LPFC_DEFAULT_PAGE_SIZE,
10539 						      phba->sli4_hba.rq_esize,
10540 						      LPFC_NVMET_RQE_DEF_COUNT,
10541 						      cpu);
10542 			if (!qdesc) {
10543 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10544 						"3146 Failed allocate "
10545 						"receive HRQ\n");
10546 				goto out_error;
10547 			}
10548 			qdesc->hdwq = idx;
10549 			phba->sli4_hba.nvmet_mrq_hdr[idx] = qdesc;
10550 
10551 			/* Only needed for header of RQ pair */
10552 			qdesc->rqbp = kzalloc_node(sizeof(*qdesc->rqbp),
10553 						   GFP_KERNEL,
10554 						   cpu_to_node(cpu));
10555 			if (qdesc->rqbp == NULL) {
10556 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10557 						"6131 Failed allocate "
10558 						"Header RQBP\n");
10559 				goto out_error;
10560 			}
10561 
10562 			/* Put list in known state in case driver load fails. */
10563 			INIT_LIST_HEAD(&qdesc->rqbp->rqb_buffer_list);
10564 
10565 			/* Create NVMET Receive Queue for data */
10566 			qdesc = lpfc_sli4_queue_alloc(phba,
10567 						      LPFC_DEFAULT_PAGE_SIZE,
10568 						      phba->sli4_hba.rq_esize,
10569 						      LPFC_NVMET_RQE_DEF_COUNT,
10570 						      cpu);
10571 			if (!qdesc) {
10572 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10573 						"3156 Failed allocate "
10574 						"receive DRQ\n");
10575 				goto out_error;
10576 			}
10577 			qdesc->hdwq = idx;
10578 			phba->sli4_hba.nvmet_mrq_data[idx] = qdesc;
10579 		}
10580 	}
10581 
10582 	/* Clear NVME stats */
10583 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
10584 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10585 			memset(&phba->sli4_hba.hdwq[idx].nvme_cstat, 0,
10586 			       sizeof(phba->sli4_hba.hdwq[idx].nvme_cstat));
10587 		}
10588 	}
10589 
10590 	/* Clear SCSI stats */
10591 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP) {
10592 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10593 			memset(&phba->sli4_hba.hdwq[idx].scsi_cstat, 0,
10594 			       sizeof(phba->sli4_hba.hdwq[idx].scsi_cstat));
10595 		}
10596 	}
10597 
10598 	return 0;
10599 
10600 out_error:
10601 	lpfc_sli4_queue_destroy(phba);
10602 	return -ENOMEM;
10603 }
10604 
10605 static inline void
10606 __lpfc_sli4_release_queue(struct lpfc_queue **qp)
10607 {
10608 	if (*qp != NULL) {
10609 		lpfc_sli4_queue_free(*qp);
10610 		*qp = NULL;
10611 	}
10612 }
10613 
10614 static inline void
10615 lpfc_sli4_release_queues(struct lpfc_queue ***qs, int max)
10616 {
10617 	int idx;
10618 
10619 	if (*qs == NULL)
10620 		return;
10621 
10622 	for (idx = 0; idx < max; idx++)
10623 		__lpfc_sli4_release_queue(&(*qs)[idx]);
10624 
10625 	kfree(*qs);
10626 	*qs = NULL;
10627 }
10628 
10629 static inline void
10630 lpfc_sli4_release_hdwq(struct lpfc_hba *phba)
10631 {
10632 	struct lpfc_sli4_hdw_queue *hdwq;
10633 	struct lpfc_queue *eq;
10634 	uint32_t idx;
10635 
10636 	hdwq = phba->sli4_hba.hdwq;
10637 
10638 	/* Loop thru all Hardware Queues */
10639 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10640 		/* Free the CQ/WQ corresponding to the Hardware Queue */
10641 		lpfc_sli4_queue_free(hdwq[idx].io_cq);
10642 		lpfc_sli4_queue_free(hdwq[idx].io_wq);
10643 		hdwq[idx].hba_eq = NULL;
10644 		hdwq[idx].io_cq = NULL;
10645 		hdwq[idx].io_wq = NULL;
10646 		if (phba->cfg_xpsgl && !phba->nvmet_support)
10647 			lpfc_free_sgl_per_hdwq(phba, &hdwq[idx]);
10648 		lpfc_free_cmd_rsp_buf_per_hdwq(phba, &hdwq[idx]);
10649 	}
10650 	/* Loop thru all IRQ vectors */
10651 	for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
10652 		/* Free the EQ corresponding to the IRQ vector */
10653 		eq = phba->sli4_hba.hba_eq_hdl[idx].eq;
10654 		lpfc_sli4_queue_free(eq);
10655 		phba->sli4_hba.hba_eq_hdl[idx].eq = NULL;
10656 	}
10657 }
10658 
10659 /**
10660  * lpfc_sli4_queue_destroy - Destroy all the SLI4 queues
10661  * @phba: pointer to lpfc hba data structure.
10662  *
10663  * This routine is invoked to release all the SLI4 queues with the FCoE HBA
10664  * operation.
10665  *
10666  * Return codes
10667  *      0 - successful
10668  *      -ENOMEM - No available memory
10669  *      -EIO - The mailbox failed to complete successfully.
10670  **/
10671 void
10672 lpfc_sli4_queue_destroy(struct lpfc_hba *phba)
10673 {
10674 	/*
10675 	 * Set FREE_INIT before beginning to free the queues.
10676 	 * Wait until the users of queues to acknowledge to
10677 	 * release queues by clearing FREE_WAIT.
10678 	 */
10679 	spin_lock_irq(&phba->hbalock);
10680 	phba->sli.sli_flag |= LPFC_QUEUE_FREE_INIT;
10681 	while (phba->sli.sli_flag & LPFC_QUEUE_FREE_WAIT) {
10682 		spin_unlock_irq(&phba->hbalock);
10683 		msleep(20);
10684 		spin_lock_irq(&phba->hbalock);
10685 	}
10686 	spin_unlock_irq(&phba->hbalock);
10687 
10688 	lpfc_sli4_cleanup_poll_list(phba);
10689 
10690 	/* Release HBA eqs */
10691 	if (phba->sli4_hba.hdwq)
10692 		lpfc_sli4_release_hdwq(phba);
10693 
10694 	if (phba->nvmet_support) {
10695 		lpfc_sli4_release_queues(&phba->sli4_hba.nvmet_cqset,
10696 					 phba->cfg_nvmet_mrq);
10697 
10698 		lpfc_sli4_release_queues(&phba->sli4_hba.nvmet_mrq_hdr,
10699 					 phba->cfg_nvmet_mrq);
10700 		lpfc_sli4_release_queues(&phba->sli4_hba.nvmet_mrq_data,
10701 					 phba->cfg_nvmet_mrq);
10702 	}
10703 
10704 	/* Release mailbox command work queue */
10705 	__lpfc_sli4_release_queue(&phba->sli4_hba.mbx_wq);
10706 
10707 	/* Release ELS work queue */
10708 	__lpfc_sli4_release_queue(&phba->sli4_hba.els_wq);
10709 
10710 	/* Release ELS work queue */
10711 	__lpfc_sli4_release_queue(&phba->sli4_hba.nvmels_wq);
10712 
10713 	/* Release unsolicited receive queue */
10714 	__lpfc_sli4_release_queue(&phba->sli4_hba.hdr_rq);
10715 	__lpfc_sli4_release_queue(&phba->sli4_hba.dat_rq);
10716 
10717 	/* Release ELS complete queue */
10718 	__lpfc_sli4_release_queue(&phba->sli4_hba.els_cq);
10719 
10720 	/* Release NVME LS complete queue */
10721 	__lpfc_sli4_release_queue(&phba->sli4_hba.nvmels_cq);
10722 
10723 	/* Release mailbox command complete queue */
10724 	__lpfc_sli4_release_queue(&phba->sli4_hba.mbx_cq);
10725 
10726 	/* Everything on this list has been freed */
10727 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_wq_list);
10728 
10729 	/* Done with freeing the queues */
10730 	spin_lock_irq(&phba->hbalock);
10731 	phba->sli.sli_flag &= ~LPFC_QUEUE_FREE_INIT;
10732 	spin_unlock_irq(&phba->hbalock);
10733 }
10734 
10735 int
10736 lpfc_free_rq_buffer(struct lpfc_hba *phba, struct lpfc_queue *rq)
10737 {
10738 	struct lpfc_rqb *rqbp;
10739 	struct lpfc_dmabuf *h_buf;
10740 	struct rqb_dmabuf *rqb_buffer;
10741 
10742 	rqbp = rq->rqbp;
10743 	while (!list_empty(&rqbp->rqb_buffer_list)) {
10744 		list_remove_head(&rqbp->rqb_buffer_list, h_buf,
10745 				 struct lpfc_dmabuf, list);
10746 
10747 		rqb_buffer = container_of(h_buf, struct rqb_dmabuf, hbuf);
10748 		(rqbp->rqb_free_buffer)(phba, rqb_buffer);
10749 		rqbp->buffer_count--;
10750 	}
10751 	return 1;
10752 }
10753 
10754 static int
10755 lpfc_create_wq_cq(struct lpfc_hba *phba, struct lpfc_queue *eq,
10756 	struct lpfc_queue *cq, struct lpfc_queue *wq, uint16_t *cq_map,
10757 	int qidx, uint32_t qtype)
10758 {
10759 	struct lpfc_sli_ring *pring;
10760 	int rc;
10761 
10762 	if (!eq || !cq || !wq) {
10763 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10764 			"6085 Fast-path %s (%d) not allocated\n",
10765 			((eq) ? ((cq) ? "WQ" : "CQ") : "EQ"), qidx);
10766 		return -ENOMEM;
10767 	}
10768 
10769 	/* create the Cq first */
10770 	rc = lpfc_cq_create(phba, cq, eq,
10771 			(qtype == LPFC_MBOX) ? LPFC_MCQ : LPFC_WCQ, qtype);
10772 	if (rc) {
10773 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10774 				"6086 Failed setup of CQ (%d), rc = 0x%x\n",
10775 				qidx, (uint32_t)rc);
10776 		return rc;
10777 	}
10778 
10779 	if (qtype != LPFC_MBOX) {
10780 		/* Setup cq_map for fast lookup */
10781 		if (cq_map)
10782 			*cq_map = cq->queue_id;
10783 
10784 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
10785 			"6087 CQ setup: cq[%d]-id=%d, parent eq[%d]-id=%d\n",
10786 			qidx, cq->queue_id, qidx, eq->queue_id);
10787 
10788 		/* create the wq */
10789 		rc = lpfc_wq_create(phba, wq, cq, qtype);
10790 		if (rc) {
10791 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10792 				"4618 Fail setup fastpath WQ (%d), rc = 0x%x\n",
10793 				qidx, (uint32_t)rc);
10794 			/* no need to tear down cq - caller will do so */
10795 			return rc;
10796 		}
10797 
10798 		/* Bind this CQ/WQ to the NVME ring */
10799 		pring = wq->pring;
10800 		pring->sli.sli4.wqp = (void *)wq;
10801 		cq->pring = pring;
10802 
10803 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
10804 			"2593 WQ setup: wq[%d]-id=%d assoc=%d, cq[%d]-id=%d\n",
10805 			qidx, wq->queue_id, wq->assoc_qid, qidx, cq->queue_id);
10806 	} else {
10807 		rc = lpfc_mq_create(phba, wq, cq, LPFC_MBOX);
10808 		if (rc) {
10809 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10810 					"0539 Failed setup of slow-path MQ: "
10811 					"rc = 0x%x\n", rc);
10812 			/* no need to tear down cq - caller will do so */
10813 			return rc;
10814 		}
10815 
10816 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
10817 			"2589 MBX MQ setup: wq-id=%d, parent cq-id=%d\n",
10818 			phba->sli4_hba.mbx_wq->queue_id,
10819 			phba->sli4_hba.mbx_cq->queue_id);
10820 	}
10821 
10822 	return 0;
10823 }
10824 
10825 /**
10826  * lpfc_setup_cq_lookup - Setup the CQ lookup table
10827  * @phba: pointer to lpfc hba data structure.
10828  *
10829  * This routine will populate the cq_lookup table by all
10830  * available CQ queue_id's.
10831  **/
10832 static void
10833 lpfc_setup_cq_lookup(struct lpfc_hba *phba)
10834 {
10835 	struct lpfc_queue *eq, *childq;
10836 	int qidx;
10837 
10838 	memset(phba->sli4_hba.cq_lookup, 0,
10839 	       (sizeof(struct lpfc_queue *) * (phba->sli4_hba.cq_max + 1)));
10840 	/* Loop thru all IRQ vectors */
10841 	for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
10842 		/* Get the EQ corresponding to the IRQ vector */
10843 		eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
10844 		if (!eq)
10845 			continue;
10846 		/* Loop through all CQs associated with that EQ */
10847 		list_for_each_entry(childq, &eq->child_list, list) {
10848 			if (childq->queue_id > phba->sli4_hba.cq_max)
10849 				continue;
10850 			if (childq->subtype == LPFC_IO)
10851 				phba->sli4_hba.cq_lookup[childq->queue_id] =
10852 					childq;
10853 		}
10854 	}
10855 }
10856 
10857 /**
10858  * lpfc_sli4_queue_setup - Set up all the SLI4 queues
10859  * @phba: pointer to lpfc hba data structure.
10860  *
10861  * This routine is invoked to set up all the SLI4 queues for the FCoE HBA
10862  * operation.
10863  *
10864  * Return codes
10865  *      0 - successful
10866  *      -ENOMEM - No available memory
10867  *      -EIO - The mailbox failed to complete successfully.
10868  **/
10869 int
10870 lpfc_sli4_queue_setup(struct lpfc_hba *phba)
10871 {
10872 	uint32_t shdr_status, shdr_add_status;
10873 	union lpfc_sli4_cfg_shdr *shdr;
10874 	struct lpfc_vector_map_info *cpup;
10875 	struct lpfc_sli4_hdw_queue *qp;
10876 	LPFC_MBOXQ_t *mboxq;
10877 	int qidx, cpu;
10878 	uint32_t length, usdelay;
10879 	int rc = -ENOMEM;
10880 
10881 	/* Check for dual-ULP support */
10882 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
10883 	if (!mboxq) {
10884 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10885 				"3249 Unable to allocate memory for "
10886 				"QUERY_FW_CFG mailbox command\n");
10887 		return -ENOMEM;
10888 	}
10889 	length = (sizeof(struct lpfc_mbx_query_fw_config) -
10890 		  sizeof(struct lpfc_sli4_cfg_mhdr));
10891 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
10892 			 LPFC_MBOX_OPCODE_QUERY_FW_CFG,
10893 			 length, LPFC_SLI4_MBX_EMBED);
10894 
10895 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
10896 
10897 	shdr = (union lpfc_sli4_cfg_shdr *)
10898 			&mboxq->u.mqe.un.sli4_config.header.cfg_shdr;
10899 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
10900 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
10901 	if (shdr_status || shdr_add_status || rc) {
10902 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10903 				"3250 QUERY_FW_CFG mailbox failed with status "
10904 				"x%x add_status x%x, mbx status x%x\n",
10905 				shdr_status, shdr_add_status, rc);
10906 		mempool_free(mboxq, phba->mbox_mem_pool);
10907 		rc = -ENXIO;
10908 		goto out_error;
10909 	}
10910 
10911 	phba->sli4_hba.fw_func_mode =
10912 			mboxq->u.mqe.un.query_fw_cfg.rsp.function_mode;
10913 	phba->sli4_hba.ulp0_mode = mboxq->u.mqe.un.query_fw_cfg.rsp.ulp0_mode;
10914 	phba->sli4_hba.ulp1_mode = mboxq->u.mqe.un.query_fw_cfg.rsp.ulp1_mode;
10915 	phba->sli4_hba.physical_port =
10916 			mboxq->u.mqe.un.query_fw_cfg.rsp.physical_port;
10917 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
10918 			"3251 QUERY_FW_CFG: func_mode:x%x, ulp0_mode:x%x, "
10919 			"ulp1_mode:x%x\n", phba->sli4_hba.fw_func_mode,
10920 			phba->sli4_hba.ulp0_mode, phba->sli4_hba.ulp1_mode);
10921 
10922 	mempool_free(mboxq, phba->mbox_mem_pool);
10923 
10924 	/*
10925 	 * Set up HBA Event Queues (EQs)
10926 	 */
10927 	qp = phba->sli4_hba.hdwq;
10928 
10929 	/* Set up HBA event queue */
10930 	if (!qp) {
10931 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10932 				"3147 Fast-path EQs not allocated\n");
10933 		rc = -ENOMEM;
10934 		goto out_error;
10935 	}
10936 
10937 	/* Loop thru all IRQ vectors */
10938 	for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
10939 		/* Create HBA Event Queues (EQs) in order */
10940 		for_each_present_cpu(cpu) {
10941 			cpup = &phba->sli4_hba.cpu_map[cpu];
10942 
10943 			/* Look for the CPU thats using that vector with
10944 			 * LPFC_CPU_FIRST_IRQ set.
10945 			 */
10946 			if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
10947 				continue;
10948 			if (qidx != cpup->eq)
10949 				continue;
10950 
10951 			/* Create an EQ for that vector */
10952 			rc = lpfc_eq_create(phba, qp[cpup->hdwq].hba_eq,
10953 					    phba->cfg_fcp_imax);
10954 			if (rc) {
10955 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10956 						"0523 Failed setup of fast-path"
10957 						" EQ (%d), rc = 0x%x\n",
10958 						cpup->eq, (uint32_t)rc);
10959 				goto out_destroy;
10960 			}
10961 
10962 			/* Save the EQ for that vector in the hba_eq_hdl */
10963 			phba->sli4_hba.hba_eq_hdl[cpup->eq].eq =
10964 				qp[cpup->hdwq].hba_eq;
10965 
10966 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
10967 					"2584 HBA EQ setup: queue[%d]-id=%d\n",
10968 					cpup->eq,
10969 					qp[cpup->hdwq].hba_eq->queue_id);
10970 		}
10971 	}
10972 
10973 	/* Loop thru all Hardware Queues */
10974 	for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
10975 		cpu = lpfc_find_cpu_handle(phba, qidx, LPFC_FIND_BY_HDWQ);
10976 		cpup = &phba->sli4_hba.cpu_map[cpu];
10977 
10978 		/* Create the CQ/WQ corresponding to the Hardware Queue */
10979 		rc = lpfc_create_wq_cq(phba,
10980 				       phba->sli4_hba.hdwq[cpup->hdwq].hba_eq,
10981 				       qp[qidx].io_cq,
10982 				       qp[qidx].io_wq,
10983 				       &phba->sli4_hba.hdwq[qidx].io_cq_map,
10984 				       qidx,
10985 				       LPFC_IO);
10986 		if (rc) {
10987 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10988 					"0535 Failed to setup fastpath "
10989 					"IO WQ/CQ (%d), rc = 0x%x\n",
10990 					qidx, (uint32_t)rc);
10991 			goto out_destroy;
10992 		}
10993 	}
10994 
10995 	/*
10996 	 * Set up Slow Path Complete Queues (CQs)
10997 	 */
10998 
10999 	/* Set up slow-path MBOX CQ/MQ */
11000 
11001 	if (!phba->sli4_hba.mbx_cq || !phba->sli4_hba.mbx_wq) {
11002 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11003 				"0528 %s not allocated\n",
11004 				phba->sli4_hba.mbx_cq ?
11005 				"Mailbox WQ" : "Mailbox CQ");
11006 		rc = -ENOMEM;
11007 		goto out_destroy;
11008 	}
11009 
11010 	rc = lpfc_create_wq_cq(phba, qp[0].hba_eq,
11011 			       phba->sli4_hba.mbx_cq,
11012 			       phba->sli4_hba.mbx_wq,
11013 			       NULL, 0, LPFC_MBOX);
11014 	if (rc) {
11015 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11016 			"0529 Failed setup of mailbox WQ/CQ: rc = 0x%x\n",
11017 			(uint32_t)rc);
11018 		goto out_destroy;
11019 	}
11020 	if (phba->nvmet_support) {
11021 		if (!phba->sli4_hba.nvmet_cqset) {
11022 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11023 					"3165 Fast-path NVME CQ Set "
11024 					"array not allocated\n");
11025 			rc = -ENOMEM;
11026 			goto out_destroy;
11027 		}
11028 		if (phba->cfg_nvmet_mrq > 1) {
11029 			rc = lpfc_cq_create_set(phba,
11030 					phba->sli4_hba.nvmet_cqset,
11031 					qp,
11032 					LPFC_WCQ, LPFC_NVMET);
11033 			if (rc) {
11034 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11035 						"3164 Failed setup of NVME CQ "
11036 						"Set, rc = 0x%x\n",
11037 						(uint32_t)rc);
11038 				goto out_destroy;
11039 			}
11040 		} else {
11041 			/* Set up NVMET Receive Complete Queue */
11042 			rc = lpfc_cq_create(phba, phba->sli4_hba.nvmet_cqset[0],
11043 					    qp[0].hba_eq,
11044 					    LPFC_WCQ, LPFC_NVMET);
11045 			if (rc) {
11046 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11047 						"6089 Failed setup NVMET CQ: "
11048 						"rc = 0x%x\n", (uint32_t)rc);
11049 				goto out_destroy;
11050 			}
11051 			phba->sli4_hba.nvmet_cqset[0]->chann = 0;
11052 
11053 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11054 					"6090 NVMET CQ setup: cq-id=%d, "
11055 					"parent eq-id=%d\n",
11056 					phba->sli4_hba.nvmet_cqset[0]->queue_id,
11057 					qp[0].hba_eq->queue_id);
11058 		}
11059 	}
11060 
11061 	/* Set up slow-path ELS WQ/CQ */
11062 	if (!phba->sli4_hba.els_cq || !phba->sli4_hba.els_wq) {
11063 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11064 				"0530 ELS %s not allocated\n",
11065 				phba->sli4_hba.els_cq ? "WQ" : "CQ");
11066 		rc = -ENOMEM;
11067 		goto out_destroy;
11068 	}
11069 	rc = lpfc_create_wq_cq(phba, qp[0].hba_eq,
11070 			       phba->sli4_hba.els_cq,
11071 			       phba->sli4_hba.els_wq,
11072 			       NULL, 0, LPFC_ELS);
11073 	if (rc) {
11074 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11075 				"0525 Failed setup of ELS WQ/CQ: rc = 0x%x\n",
11076 				(uint32_t)rc);
11077 		goto out_destroy;
11078 	}
11079 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11080 			"2590 ELS WQ setup: wq-id=%d, parent cq-id=%d\n",
11081 			phba->sli4_hba.els_wq->queue_id,
11082 			phba->sli4_hba.els_cq->queue_id);
11083 
11084 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
11085 		/* Set up NVME LS Complete Queue */
11086 		if (!phba->sli4_hba.nvmels_cq || !phba->sli4_hba.nvmels_wq) {
11087 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11088 					"6091 LS %s not allocated\n",
11089 					phba->sli4_hba.nvmels_cq ? "WQ" : "CQ");
11090 			rc = -ENOMEM;
11091 			goto out_destroy;
11092 		}
11093 		rc = lpfc_create_wq_cq(phba, qp[0].hba_eq,
11094 				       phba->sli4_hba.nvmels_cq,
11095 				       phba->sli4_hba.nvmels_wq,
11096 				       NULL, 0, LPFC_NVME_LS);
11097 		if (rc) {
11098 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11099 					"0526 Failed setup of NVVME LS WQ/CQ: "
11100 					"rc = 0x%x\n", (uint32_t)rc);
11101 			goto out_destroy;
11102 		}
11103 
11104 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11105 				"6096 ELS WQ setup: wq-id=%d, "
11106 				"parent cq-id=%d\n",
11107 				phba->sli4_hba.nvmels_wq->queue_id,
11108 				phba->sli4_hba.nvmels_cq->queue_id);
11109 	}
11110 
11111 	/*
11112 	 * Create NVMET Receive Queue (RQ)
11113 	 */
11114 	if (phba->nvmet_support) {
11115 		if ((!phba->sli4_hba.nvmet_cqset) ||
11116 		    (!phba->sli4_hba.nvmet_mrq_hdr) ||
11117 		    (!phba->sli4_hba.nvmet_mrq_data)) {
11118 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11119 					"6130 MRQ CQ Queues not "
11120 					"allocated\n");
11121 			rc = -ENOMEM;
11122 			goto out_destroy;
11123 		}
11124 		if (phba->cfg_nvmet_mrq > 1) {
11125 			rc = lpfc_mrq_create(phba,
11126 					     phba->sli4_hba.nvmet_mrq_hdr,
11127 					     phba->sli4_hba.nvmet_mrq_data,
11128 					     phba->sli4_hba.nvmet_cqset,
11129 					     LPFC_NVMET);
11130 			if (rc) {
11131 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11132 						"6098 Failed setup of NVMET "
11133 						"MRQ: rc = 0x%x\n",
11134 						(uint32_t)rc);
11135 				goto out_destroy;
11136 			}
11137 
11138 		} else {
11139 			rc = lpfc_rq_create(phba,
11140 					    phba->sli4_hba.nvmet_mrq_hdr[0],
11141 					    phba->sli4_hba.nvmet_mrq_data[0],
11142 					    phba->sli4_hba.nvmet_cqset[0],
11143 					    LPFC_NVMET);
11144 			if (rc) {
11145 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11146 						"6057 Failed setup of NVMET "
11147 						"Receive Queue: rc = 0x%x\n",
11148 						(uint32_t)rc);
11149 				goto out_destroy;
11150 			}
11151 
11152 			lpfc_printf_log(
11153 				phba, KERN_INFO, LOG_INIT,
11154 				"6099 NVMET RQ setup: hdr-rq-id=%d, "
11155 				"dat-rq-id=%d parent cq-id=%d\n",
11156 				phba->sli4_hba.nvmet_mrq_hdr[0]->queue_id,
11157 				phba->sli4_hba.nvmet_mrq_data[0]->queue_id,
11158 				phba->sli4_hba.nvmet_cqset[0]->queue_id);
11159 
11160 		}
11161 	}
11162 
11163 	if (!phba->sli4_hba.hdr_rq || !phba->sli4_hba.dat_rq) {
11164 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11165 				"0540 Receive Queue not allocated\n");
11166 		rc = -ENOMEM;
11167 		goto out_destroy;
11168 	}
11169 
11170 	rc = lpfc_rq_create(phba, phba->sli4_hba.hdr_rq, phba->sli4_hba.dat_rq,
11171 			    phba->sli4_hba.els_cq, LPFC_USOL);
11172 	if (rc) {
11173 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11174 				"0541 Failed setup of Receive Queue: "
11175 				"rc = 0x%x\n", (uint32_t)rc);
11176 		goto out_destroy;
11177 	}
11178 
11179 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11180 			"2592 USL RQ setup: hdr-rq-id=%d, dat-rq-id=%d "
11181 			"parent cq-id=%d\n",
11182 			phba->sli4_hba.hdr_rq->queue_id,
11183 			phba->sli4_hba.dat_rq->queue_id,
11184 			phba->sli4_hba.els_cq->queue_id);
11185 
11186 	if (phba->cfg_fcp_imax)
11187 		usdelay = LPFC_SEC_TO_USEC / phba->cfg_fcp_imax;
11188 	else
11189 		usdelay = 0;
11190 
11191 	for (qidx = 0; qidx < phba->cfg_irq_chann;
11192 	     qidx += LPFC_MAX_EQ_DELAY_EQID_CNT)
11193 		lpfc_modify_hba_eq_delay(phba, qidx, LPFC_MAX_EQ_DELAY_EQID_CNT,
11194 					 usdelay);
11195 
11196 	if (phba->sli4_hba.cq_max) {
11197 		kfree(phba->sli4_hba.cq_lookup);
11198 		phba->sli4_hba.cq_lookup = kcalloc((phba->sli4_hba.cq_max + 1),
11199 			sizeof(struct lpfc_queue *), GFP_KERNEL);
11200 		if (!phba->sli4_hba.cq_lookup) {
11201 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11202 					"0549 Failed setup of CQ Lookup table: "
11203 					"size 0x%x\n", phba->sli4_hba.cq_max);
11204 			rc = -ENOMEM;
11205 			goto out_destroy;
11206 		}
11207 		lpfc_setup_cq_lookup(phba);
11208 	}
11209 	return 0;
11210 
11211 out_destroy:
11212 	lpfc_sli4_queue_unset(phba);
11213 out_error:
11214 	return rc;
11215 }
11216 
11217 /**
11218  * lpfc_sli4_queue_unset - Unset all the SLI4 queues
11219  * @phba: pointer to lpfc hba data structure.
11220  *
11221  * This routine is invoked to unset all the SLI4 queues with the FCoE HBA
11222  * operation.
11223  *
11224  * Return codes
11225  *      0 - successful
11226  *      -ENOMEM - No available memory
11227  *      -EIO - The mailbox failed to complete successfully.
11228  **/
11229 void
11230 lpfc_sli4_queue_unset(struct lpfc_hba *phba)
11231 {
11232 	struct lpfc_sli4_hdw_queue *qp;
11233 	struct lpfc_queue *eq;
11234 	int qidx;
11235 
11236 	/* Unset mailbox command work queue */
11237 	if (phba->sli4_hba.mbx_wq)
11238 		lpfc_mq_destroy(phba, phba->sli4_hba.mbx_wq);
11239 
11240 	/* Unset NVME LS work queue */
11241 	if (phba->sli4_hba.nvmels_wq)
11242 		lpfc_wq_destroy(phba, phba->sli4_hba.nvmels_wq);
11243 
11244 	/* Unset ELS work queue */
11245 	if (phba->sli4_hba.els_wq)
11246 		lpfc_wq_destroy(phba, phba->sli4_hba.els_wq);
11247 
11248 	/* Unset unsolicited receive queue */
11249 	if (phba->sli4_hba.hdr_rq)
11250 		lpfc_rq_destroy(phba, phba->sli4_hba.hdr_rq,
11251 				phba->sli4_hba.dat_rq);
11252 
11253 	/* Unset mailbox command complete queue */
11254 	if (phba->sli4_hba.mbx_cq)
11255 		lpfc_cq_destroy(phba, phba->sli4_hba.mbx_cq);
11256 
11257 	/* Unset ELS complete queue */
11258 	if (phba->sli4_hba.els_cq)
11259 		lpfc_cq_destroy(phba, phba->sli4_hba.els_cq);
11260 
11261 	/* Unset NVME LS complete queue */
11262 	if (phba->sli4_hba.nvmels_cq)
11263 		lpfc_cq_destroy(phba, phba->sli4_hba.nvmels_cq);
11264 
11265 	if (phba->nvmet_support) {
11266 		/* Unset NVMET MRQ queue */
11267 		if (phba->sli4_hba.nvmet_mrq_hdr) {
11268 			for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++)
11269 				lpfc_rq_destroy(
11270 					phba,
11271 					phba->sli4_hba.nvmet_mrq_hdr[qidx],
11272 					phba->sli4_hba.nvmet_mrq_data[qidx]);
11273 		}
11274 
11275 		/* Unset NVMET CQ Set complete queue */
11276 		if (phba->sli4_hba.nvmet_cqset) {
11277 			for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++)
11278 				lpfc_cq_destroy(
11279 					phba, phba->sli4_hba.nvmet_cqset[qidx]);
11280 		}
11281 	}
11282 
11283 	/* Unset fast-path SLI4 queues */
11284 	if (phba->sli4_hba.hdwq) {
11285 		/* Loop thru all Hardware Queues */
11286 		for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
11287 			/* Destroy the CQ/WQ corresponding to Hardware Queue */
11288 			qp = &phba->sli4_hba.hdwq[qidx];
11289 			lpfc_wq_destroy(phba, qp->io_wq);
11290 			lpfc_cq_destroy(phba, qp->io_cq);
11291 		}
11292 		/* Loop thru all IRQ vectors */
11293 		for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
11294 			/* Destroy the EQ corresponding to the IRQ vector */
11295 			eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
11296 			lpfc_eq_destroy(phba, eq);
11297 		}
11298 	}
11299 
11300 	kfree(phba->sli4_hba.cq_lookup);
11301 	phba->sli4_hba.cq_lookup = NULL;
11302 	phba->sli4_hba.cq_max = 0;
11303 }
11304 
11305 /**
11306  * lpfc_sli4_cq_event_pool_create - Create completion-queue event free pool
11307  * @phba: pointer to lpfc hba data structure.
11308  *
11309  * This routine is invoked to allocate and set up a pool of completion queue
11310  * events. The body of the completion queue event is a completion queue entry
11311  * CQE. For now, this pool is used for the interrupt service routine to queue
11312  * the following HBA completion queue events for the worker thread to process:
11313  *   - Mailbox asynchronous events
11314  *   - Receive queue completion unsolicited events
11315  * Later, this can be used for all the slow-path events.
11316  *
11317  * Return codes
11318  *      0 - successful
11319  *      -ENOMEM - No available memory
11320  **/
11321 static int
11322 lpfc_sli4_cq_event_pool_create(struct lpfc_hba *phba)
11323 {
11324 	struct lpfc_cq_event *cq_event;
11325 	int i;
11326 
11327 	for (i = 0; i < (4 * phba->sli4_hba.cq_ecount); i++) {
11328 		cq_event = kmalloc(sizeof(struct lpfc_cq_event), GFP_KERNEL);
11329 		if (!cq_event)
11330 			goto out_pool_create_fail;
11331 		list_add_tail(&cq_event->list,
11332 			      &phba->sli4_hba.sp_cqe_event_pool);
11333 	}
11334 	return 0;
11335 
11336 out_pool_create_fail:
11337 	lpfc_sli4_cq_event_pool_destroy(phba);
11338 	return -ENOMEM;
11339 }
11340 
11341 /**
11342  * lpfc_sli4_cq_event_pool_destroy - Free completion-queue event free pool
11343  * @phba: pointer to lpfc hba data structure.
11344  *
11345  * This routine is invoked to free the pool of completion queue events at
11346  * driver unload time. Note that, it is the responsibility of the driver
11347  * cleanup routine to free all the outstanding completion-queue events
11348  * allocated from this pool back into the pool before invoking this routine
11349  * to destroy the pool.
11350  **/
11351 static void
11352 lpfc_sli4_cq_event_pool_destroy(struct lpfc_hba *phba)
11353 {
11354 	struct lpfc_cq_event *cq_event, *next_cq_event;
11355 
11356 	list_for_each_entry_safe(cq_event, next_cq_event,
11357 				 &phba->sli4_hba.sp_cqe_event_pool, list) {
11358 		list_del(&cq_event->list);
11359 		kfree(cq_event);
11360 	}
11361 }
11362 
11363 /**
11364  * __lpfc_sli4_cq_event_alloc - Allocate a completion-queue event from free pool
11365  * @phba: pointer to lpfc hba data structure.
11366  *
11367  * This routine is the lock free version of the API invoked to allocate a
11368  * completion-queue event from the free pool.
11369  *
11370  * Return: Pointer to the newly allocated completion-queue event if successful
11371  *         NULL otherwise.
11372  **/
11373 struct lpfc_cq_event *
11374 __lpfc_sli4_cq_event_alloc(struct lpfc_hba *phba)
11375 {
11376 	struct lpfc_cq_event *cq_event = NULL;
11377 
11378 	list_remove_head(&phba->sli4_hba.sp_cqe_event_pool, cq_event,
11379 			 struct lpfc_cq_event, list);
11380 	return cq_event;
11381 }
11382 
11383 /**
11384  * lpfc_sli4_cq_event_alloc - Allocate a completion-queue event from free pool
11385  * @phba: pointer to lpfc hba data structure.
11386  *
11387  * This routine is the lock version of the API invoked to allocate a
11388  * completion-queue event from the free pool.
11389  *
11390  * Return: Pointer to the newly allocated completion-queue event if successful
11391  *         NULL otherwise.
11392  **/
11393 struct lpfc_cq_event *
11394 lpfc_sli4_cq_event_alloc(struct lpfc_hba *phba)
11395 {
11396 	struct lpfc_cq_event *cq_event;
11397 	unsigned long iflags;
11398 
11399 	spin_lock_irqsave(&phba->hbalock, iflags);
11400 	cq_event = __lpfc_sli4_cq_event_alloc(phba);
11401 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11402 	return cq_event;
11403 }
11404 
11405 /**
11406  * __lpfc_sli4_cq_event_release - Release a completion-queue event to free pool
11407  * @phba: pointer to lpfc hba data structure.
11408  * @cq_event: pointer to the completion queue event to be freed.
11409  *
11410  * This routine is the lock free version of the API invoked to release a
11411  * completion-queue event back into the free pool.
11412  **/
11413 void
11414 __lpfc_sli4_cq_event_release(struct lpfc_hba *phba,
11415 			     struct lpfc_cq_event *cq_event)
11416 {
11417 	list_add_tail(&cq_event->list, &phba->sli4_hba.sp_cqe_event_pool);
11418 }
11419 
11420 /**
11421  * lpfc_sli4_cq_event_release - Release a completion-queue event to free pool
11422  * @phba: pointer to lpfc hba data structure.
11423  * @cq_event: pointer to the completion queue event to be freed.
11424  *
11425  * This routine is the lock version of the API invoked to release a
11426  * completion-queue event back into the free pool.
11427  **/
11428 void
11429 lpfc_sli4_cq_event_release(struct lpfc_hba *phba,
11430 			   struct lpfc_cq_event *cq_event)
11431 {
11432 	unsigned long iflags;
11433 	spin_lock_irqsave(&phba->hbalock, iflags);
11434 	__lpfc_sli4_cq_event_release(phba, cq_event);
11435 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11436 }
11437 
11438 /**
11439  * lpfc_sli4_cq_event_release_all - Release all cq events to the free pool
11440  * @phba: pointer to lpfc hba data structure.
11441  *
11442  * This routine is to free all the pending completion-queue events to the
11443  * back into the free pool for device reset.
11444  **/
11445 static void
11446 lpfc_sli4_cq_event_release_all(struct lpfc_hba *phba)
11447 {
11448 	LIST_HEAD(cq_event_list);
11449 	struct lpfc_cq_event *cq_event;
11450 	unsigned long iflags;
11451 
11452 	/* Retrieve all the pending WCQEs from pending WCQE lists */
11453 
11454 	/* Pending ELS XRI abort events */
11455 	spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
11456 	list_splice_init(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
11457 			 &cq_event_list);
11458 	spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
11459 
11460 	/* Pending asynnc events */
11461 	spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
11462 	list_splice_init(&phba->sli4_hba.sp_asynce_work_queue,
11463 			 &cq_event_list);
11464 	spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock, iflags);
11465 
11466 	while (!list_empty(&cq_event_list)) {
11467 		list_remove_head(&cq_event_list, cq_event,
11468 				 struct lpfc_cq_event, list);
11469 		lpfc_sli4_cq_event_release(phba, cq_event);
11470 	}
11471 }
11472 
11473 /**
11474  * lpfc_pci_function_reset - Reset pci function.
11475  * @phba: pointer to lpfc hba data structure.
11476  *
11477  * This routine is invoked to request a PCI function reset. It will destroys
11478  * all resources assigned to the PCI function which originates this request.
11479  *
11480  * Return codes
11481  *      0 - successful
11482  *      -ENOMEM - No available memory
11483  *      -EIO - The mailbox failed to complete successfully.
11484  **/
11485 int
11486 lpfc_pci_function_reset(struct lpfc_hba *phba)
11487 {
11488 	LPFC_MBOXQ_t *mboxq;
11489 	uint32_t rc = 0, if_type;
11490 	uint32_t shdr_status, shdr_add_status;
11491 	uint32_t rdy_chk;
11492 	uint32_t port_reset = 0;
11493 	union lpfc_sli4_cfg_shdr *shdr;
11494 	struct lpfc_register reg_data;
11495 	uint16_t devid;
11496 
11497 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
11498 	switch (if_type) {
11499 	case LPFC_SLI_INTF_IF_TYPE_0:
11500 		mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
11501 						       GFP_KERNEL);
11502 		if (!mboxq) {
11503 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11504 					"0494 Unable to allocate memory for "
11505 					"issuing SLI_FUNCTION_RESET mailbox "
11506 					"command\n");
11507 			return -ENOMEM;
11508 		}
11509 
11510 		/* Setup PCI function reset mailbox-ioctl command */
11511 		lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
11512 				 LPFC_MBOX_OPCODE_FUNCTION_RESET, 0,
11513 				 LPFC_SLI4_MBX_EMBED);
11514 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
11515 		shdr = (union lpfc_sli4_cfg_shdr *)
11516 			&mboxq->u.mqe.un.sli4_config.header.cfg_shdr;
11517 		shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
11518 		shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
11519 					 &shdr->response);
11520 		mempool_free(mboxq, phba->mbox_mem_pool);
11521 		if (shdr_status || shdr_add_status || rc) {
11522 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11523 					"0495 SLI_FUNCTION_RESET mailbox "
11524 					"failed with status x%x add_status x%x,"
11525 					" mbx status x%x\n",
11526 					shdr_status, shdr_add_status, rc);
11527 			rc = -ENXIO;
11528 		}
11529 		break;
11530 	case LPFC_SLI_INTF_IF_TYPE_2:
11531 	case LPFC_SLI_INTF_IF_TYPE_6:
11532 wait:
11533 		/*
11534 		 * Poll the Port Status Register and wait for RDY for
11535 		 * up to 30 seconds. If the port doesn't respond, treat
11536 		 * it as an error.
11537 		 */
11538 		for (rdy_chk = 0; rdy_chk < 1500; rdy_chk++) {
11539 			if (lpfc_readl(phba->sli4_hba.u.if_type2.
11540 				STATUSregaddr, &reg_data.word0)) {
11541 				rc = -ENODEV;
11542 				goto out;
11543 			}
11544 			if (bf_get(lpfc_sliport_status_rdy, &reg_data))
11545 				break;
11546 			msleep(20);
11547 		}
11548 
11549 		if (!bf_get(lpfc_sliport_status_rdy, &reg_data)) {
11550 			phba->work_status[0] = readl(
11551 				phba->sli4_hba.u.if_type2.ERR1regaddr);
11552 			phba->work_status[1] = readl(
11553 				phba->sli4_hba.u.if_type2.ERR2regaddr);
11554 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11555 					"2890 Port not ready, port status reg "
11556 					"0x%x error 1=0x%x, error 2=0x%x\n",
11557 					reg_data.word0,
11558 					phba->work_status[0],
11559 					phba->work_status[1]);
11560 			rc = -ENODEV;
11561 			goto out;
11562 		}
11563 
11564 		if (!port_reset) {
11565 			/*
11566 			 * Reset the port now
11567 			 */
11568 			reg_data.word0 = 0;
11569 			bf_set(lpfc_sliport_ctrl_end, &reg_data,
11570 			       LPFC_SLIPORT_LITTLE_ENDIAN);
11571 			bf_set(lpfc_sliport_ctrl_ip, &reg_data,
11572 			       LPFC_SLIPORT_INIT_PORT);
11573 			writel(reg_data.word0, phba->sli4_hba.u.if_type2.
11574 			       CTRLregaddr);
11575 			/* flush */
11576 			pci_read_config_word(phba->pcidev,
11577 					     PCI_DEVICE_ID, &devid);
11578 
11579 			port_reset = 1;
11580 			msleep(20);
11581 			goto wait;
11582 		} else if (bf_get(lpfc_sliport_status_rn, &reg_data)) {
11583 			rc = -ENODEV;
11584 			goto out;
11585 		}
11586 		break;
11587 
11588 	case LPFC_SLI_INTF_IF_TYPE_1:
11589 	default:
11590 		break;
11591 	}
11592 
11593 out:
11594 	/* Catch the not-ready port failure after a port reset. */
11595 	if (rc) {
11596 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11597 				"3317 HBA not functional: IP Reset Failed "
11598 				"try: echo fw_reset > board_mode\n");
11599 		rc = -ENODEV;
11600 	}
11601 
11602 	return rc;
11603 }
11604 
11605 /**
11606  * lpfc_sli4_pci_mem_setup - Setup SLI4 HBA PCI memory space.
11607  * @phba: pointer to lpfc hba data structure.
11608  *
11609  * This routine is invoked to set up the PCI device memory space for device
11610  * with SLI-4 interface spec.
11611  *
11612  * Return codes
11613  * 	0 - successful
11614  * 	other values - error
11615  **/
11616 static int
11617 lpfc_sli4_pci_mem_setup(struct lpfc_hba *phba)
11618 {
11619 	struct pci_dev *pdev = phba->pcidev;
11620 	unsigned long bar0map_len, bar1map_len, bar2map_len;
11621 	int error;
11622 	uint32_t if_type;
11623 
11624 	if (!pdev)
11625 		return -ENODEV;
11626 
11627 	/* Set the device DMA mask size */
11628 	error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
11629 	if (error)
11630 		error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32));
11631 	if (error)
11632 		return error;
11633 
11634 	/*
11635 	 * The BARs and register set definitions and offset locations are
11636 	 * dependent on the if_type.
11637 	 */
11638 	if (pci_read_config_dword(pdev, LPFC_SLI_INTF,
11639 				  &phba->sli4_hba.sli_intf.word0)) {
11640 		return -ENODEV;
11641 	}
11642 
11643 	/* There is no SLI3 failback for SLI4 devices. */
11644 	if (bf_get(lpfc_sli_intf_valid, &phba->sli4_hba.sli_intf) !=
11645 	    LPFC_SLI_INTF_VALID) {
11646 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11647 				"2894 SLI_INTF reg contents invalid "
11648 				"sli_intf reg 0x%x\n",
11649 				phba->sli4_hba.sli_intf.word0);
11650 		return -ENODEV;
11651 	}
11652 
11653 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
11654 	/*
11655 	 * Get the bus address of SLI4 device Bar regions and the
11656 	 * number of bytes required by each mapping. The mapping of the
11657 	 * particular PCI BARs regions is dependent on the type of
11658 	 * SLI4 device.
11659 	 */
11660 	if (pci_resource_start(pdev, PCI_64BIT_BAR0)) {
11661 		phba->pci_bar0_map = pci_resource_start(pdev, PCI_64BIT_BAR0);
11662 		bar0map_len = pci_resource_len(pdev, PCI_64BIT_BAR0);
11663 
11664 		/*
11665 		 * Map SLI4 PCI Config Space Register base to a kernel virtual
11666 		 * addr
11667 		 */
11668 		phba->sli4_hba.conf_regs_memmap_p =
11669 			ioremap(phba->pci_bar0_map, bar0map_len);
11670 		if (!phba->sli4_hba.conf_regs_memmap_p) {
11671 			dev_printk(KERN_ERR, &pdev->dev,
11672 				   "ioremap failed for SLI4 PCI config "
11673 				   "registers.\n");
11674 			return -ENODEV;
11675 		}
11676 		phba->pci_bar0_memmap_p = phba->sli4_hba.conf_regs_memmap_p;
11677 		/* Set up BAR0 PCI config space register memory map */
11678 		lpfc_sli4_bar0_register_memmap(phba, if_type);
11679 	} else {
11680 		phba->pci_bar0_map = pci_resource_start(pdev, 1);
11681 		bar0map_len = pci_resource_len(pdev, 1);
11682 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
11683 			dev_printk(KERN_ERR, &pdev->dev,
11684 			   "FATAL - No BAR0 mapping for SLI4, if_type 2\n");
11685 			return -ENODEV;
11686 		}
11687 		phba->sli4_hba.conf_regs_memmap_p =
11688 				ioremap(phba->pci_bar0_map, bar0map_len);
11689 		if (!phba->sli4_hba.conf_regs_memmap_p) {
11690 			dev_printk(KERN_ERR, &pdev->dev,
11691 				"ioremap failed for SLI4 PCI config "
11692 				"registers.\n");
11693 			return -ENODEV;
11694 		}
11695 		lpfc_sli4_bar0_register_memmap(phba, if_type);
11696 	}
11697 
11698 	if (if_type == LPFC_SLI_INTF_IF_TYPE_0) {
11699 		if (pci_resource_start(pdev, PCI_64BIT_BAR2)) {
11700 			/*
11701 			 * Map SLI4 if type 0 HBA Control Register base to a
11702 			 * kernel virtual address and setup the registers.
11703 			 */
11704 			phba->pci_bar1_map = pci_resource_start(pdev,
11705 								PCI_64BIT_BAR2);
11706 			bar1map_len = pci_resource_len(pdev, PCI_64BIT_BAR2);
11707 			phba->sli4_hba.ctrl_regs_memmap_p =
11708 					ioremap(phba->pci_bar1_map,
11709 						bar1map_len);
11710 			if (!phba->sli4_hba.ctrl_regs_memmap_p) {
11711 				dev_err(&pdev->dev,
11712 					   "ioremap failed for SLI4 HBA "
11713 					    "control registers.\n");
11714 				error = -ENOMEM;
11715 				goto out_iounmap_conf;
11716 			}
11717 			phba->pci_bar2_memmap_p =
11718 					 phba->sli4_hba.ctrl_regs_memmap_p;
11719 			lpfc_sli4_bar1_register_memmap(phba, if_type);
11720 		} else {
11721 			error = -ENOMEM;
11722 			goto out_iounmap_conf;
11723 		}
11724 	}
11725 
11726 	if ((if_type == LPFC_SLI_INTF_IF_TYPE_6) &&
11727 	    (pci_resource_start(pdev, PCI_64BIT_BAR2))) {
11728 		/*
11729 		 * Map SLI4 if type 6 HBA Doorbell Register base to a kernel
11730 		 * virtual address and setup the registers.
11731 		 */
11732 		phba->pci_bar1_map = pci_resource_start(pdev, PCI_64BIT_BAR2);
11733 		bar1map_len = pci_resource_len(pdev, PCI_64BIT_BAR2);
11734 		phba->sli4_hba.drbl_regs_memmap_p =
11735 				ioremap(phba->pci_bar1_map, bar1map_len);
11736 		if (!phba->sli4_hba.drbl_regs_memmap_p) {
11737 			dev_err(&pdev->dev,
11738 			   "ioremap failed for SLI4 HBA doorbell registers.\n");
11739 			error = -ENOMEM;
11740 			goto out_iounmap_conf;
11741 		}
11742 		phba->pci_bar2_memmap_p = phba->sli4_hba.drbl_regs_memmap_p;
11743 		lpfc_sli4_bar1_register_memmap(phba, if_type);
11744 	}
11745 
11746 	if (if_type == LPFC_SLI_INTF_IF_TYPE_0) {
11747 		if (pci_resource_start(pdev, PCI_64BIT_BAR4)) {
11748 			/*
11749 			 * Map SLI4 if type 0 HBA Doorbell Register base to
11750 			 * a kernel virtual address and setup the registers.
11751 			 */
11752 			phba->pci_bar2_map = pci_resource_start(pdev,
11753 								PCI_64BIT_BAR4);
11754 			bar2map_len = pci_resource_len(pdev, PCI_64BIT_BAR4);
11755 			phba->sli4_hba.drbl_regs_memmap_p =
11756 					ioremap(phba->pci_bar2_map,
11757 						bar2map_len);
11758 			if (!phba->sli4_hba.drbl_regs_memmap_p) {
11759 				dev_err(&pdev->dev,
11760 					   "ioremap failed for SLI4 HBA"
11761 					   " doorbell registers.\n");
11762 				error = -ENOMEM;
11763 				goto out_iounmap_ctrl;
11764 			}
11765 			phba->pci_bar4_memmap_p =
11766 					phba->sli4_hba.drbl_regs_memmap_p;
11767 			error = lpfc_sli4_bar2_register_memmap(phba, LPFC_VF0);
11768 			if (error)
11769 				goto out_iounmap_all;
11770 		} else {
11771 			error = -ENOMEM;
11772 			goto out_iounmap_all;
11773 		}
11774 	}
11775 
11776 	if (if_type == LPFC_SLI_INTF_IF_TYPE_6 &&
11777 	    pci_resource_start(pdev, PCI_64BIT_BAR4)) {
11778 		/*
11779 		 * Map SLI4 if type 6 HBA DPP Register base to a kernel
11780 		 * virtual address and setup the registers.
11781 		 */
11782 		phba->pci_bar2_map = pci_resource_start(pdev, PCI_64BIT_BAR4);
11783 		bar2map_len = pci_resource_len(pdev, PCI_64BIT_BAR4);
11784 		phba->sli4_hba.dpp_regs_memmap_p =
11785 				ioremap(phba->pci_bar2_map, bar2map_len);
11786 		if (!phba->sli4_hba.dpp_regs_memmap_p) {
11787 			dev_err(&pdev->dev,
11788 			   "ioremap failed for SLI4 HBA dpp registers.\n");
11789 			error = -ENOMEM;
11790 			goto out_iounmap_ctrl;
11791 		}
11792 		phba->pci_bar4_memmap_p = phba->sli4_hba.dpp_regs_memmap_p;
11793 	}
11794 
11795 	/* Set up the EQ/CQ register handeling functions now */
11796 	switch (if_type) {
11797 	case LPFC_SLI_INTF_IF_TYPE_0:
11798 	case LPFC_SLI_INTF_IF_TYPE_2:
11799 		phba->sli4_hba.sli4_eq_clr_intr = lpfc_sli4_eq_clr_intr;
11800 		phba->sli4_hba.sli4_write_eq_db = lpfc_sli4_write_eq_db;
11801 		phba->sli4_hba.sli4_write_cq_db = lpfc_sli4_write_cq_db;
11802 		break;
11803 	case LPFC_SLI_INTF_IF_TYPE_6:
11804 		phba->sli4_hba.sli4_eq_clr_intr = lpfc_sli4_if6_eq_clr_intr;
11805 		phba->sli4_hba.sli4_write_eq_db = lpfc_sli4_if6_write_eq_db;
11806 		phba->sli4_hba.sli4_write_cq_db = lpfc_sli4_if6_write_cq_db;
11807 		break;
11808 	default:
11809 		break;
11810 	}
11811 
11812 	return 0;
11813 
11814 out_iounmap_all:
11815 	iounmap(phba->sli4_hba.drbl_regs_memmap_p);
11816 out_iounmap_ctrl:
11817 	iounmap(phba->sli4_hba.ctrl_regs_memmap_p);
11818 out_iounmap_conf:
11819 	iounmap(phba->sli4_hba.conf_regs_memmap_p);
11820 
11821 	return error;
11822 }
11823 
11824 /**
11825  * lpfc_sli4_pci_mem_unset - Unset SLI4 HBA PCI memory space.
11826  * @phba: pointer to lpfc hba data structure.
11827  *
11828  * This routine is invoked to unset the PCI device memory space for device
11829  * with SLI-4 interface spec.
11830  **/
11831 static void
11832 lpfc_sli4_pci_mem_unset(struct lpfc_hba *phba)
11833 {
11834 	uint32_t if_type;
11835 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
11836 
11837 	switch (if_type) {
11838 	case LPFC_SLI_INTF_IF_TYPE_0:
11839 		iounmap(phba->sli4_hba.drbl_regs_memmap_p);
11840 		iounmap(phba->sli4_hba.ctrl_regs_memmap_p);
11841 		iounmap(phba->sli4_hba.conf_regs_memmap_p);
11842 		break;
11843 	case LPFC_SLI_INTF_IF_TYPE_2:
11844 		iounmap(phba->sli4_hba.conf_regs_memmap_p);
11845 		break;
11846 	case LPFC_SLI_INTF_IF_TYPE_6:
11847 		iounmap(phba->sli4_hba.drbl_regs_memmap_p);
11848 		iounmap(phba->sli4_hba.conf_regs_memmap_p);
11849 		if (phba->sli4_hba.dpp_regs_memmap_p)
11850 			iounmap(phba->sli4_hba.dpp_regs_memmap_p);
11851 		break;
11852 	case LPFC_SLI_INTF_IF_TYPE_1:
11853 	default:
11854 		dev_printk(KERN_ERR, &phba->pcidev->dev,
11855 			   "FATAL - unsupported SLI4 interface type - %d\n",
11856 			   if_type);
11857 		break;
11858 	}
11859 }
11860 
11861 /**
11862  * lpfc_sli_enable_msix - Enable MSI-X interrupt mode on SLI-3 device
11863  * @phba: pointer to lpfc hba data structure.
11864  *
11865  * This routine is invoked to enable the MSI-X interrupt vectors to device
11866  * with SLI-3 interface specs.
11867  *
11868  * Return codes
11869  *   0 - successful
11870  *   other values - error
11871  **/
11872 static int
11873 lpfc_sli_enable_msix(struct lpfc_hba *phba)
11874 {
11875 	int rc;
11876 	LPFC_MBOXQ_t *pmb;
11877 
11878 	/* Set up MSI-X multi-message vectors */
11879 	rc = pci_alloc_irq_vectors(phba->pcidev,
11880 			LPFC_MSIX_VECTORS, LPFC_MSIX_VECTORS, PCI_IRQ_MSIX);
11881 	if (rc < 0) {
11882 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11883 				"0420 PCI enable MSI-X failed (%d)\n", rc);
11884 		goto vec_fail_out;
11885 	}
11886 
11887 	/*
11888 	 * Assign MSI-X vectors to interrupt handlers
11889 	 */
11890 
11891 	/* vector-0 is associated to slow-path handler */
11892 	rc = request_irq(pci_irq_vector(phba->pcidev, 0),
11893 			 &lpfc_sli_sp_intr_handler, 0,
11894 			 LPFC_SP_DRIVER_HANDLER_NAME, phba);
11895 	if (rc) {
11896 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
11897 				"0421 MSI-X slow-path request_irq failed "
11898 				"(%d)\n", rc);
11899 		goto msi_fail_out;
11900 	}
11901 
11902 	/* vector-1 is associated to fast-path handler */
11903 	rc = request_irq(pci_irq_vector(phba->pcidev, 1),
11904 			 &lpfc_sli_fp_intr_handler, 0,
11905 			 LPFC_FP_DRIVER_HANDLER_NAME, phba);
11906 
11907 	if (rc) {
11908 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
11909 				"0429 MSI-X fast-path request_irq failed "
11910 				"(%d)\n", rc);
11911 		goto irq_fail_out;
11912 	}
11913 
11914 	/*
11915 	 * Configure HBA MSI-X attention conditions to messages
11916 	 */
11917 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
11918 
11919 	if (!pmb) {
11920 		rc = -ENOMEM;
11921 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11922 				"0474 Unable to allocate memory for issuing "
11923 				"MBOX_CONFIG_MSI command\n");
11924 		goto mem_fail_out;
11925 	}
11926 	rc = lpfc_config_msi(phba, pmb);
11927 	if (rc)
11928 		goto mbx_fail_out;
11929 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
11930 	if (rc != MBX_SUCCESS) {
11931 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX,
11932 				"0351 Config MSI mailbox command failed, "
11933 				"mbxCmd x%x, mbxStatus x%x\n",
11934 				pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus);
11935 		goto mbx_fail_out;
11936 	}
11937 
11938 	/* Free memory allocated for mailbox command */
11939 	mempool_free(pmb, phba->mbox_mem_pool);
11940 	return rc;
11941 
11942 mbx_fail_out:
11943 	/* Free memory allocated for mailbox command */
11944 	mempool_free(pmb, phba->mbox_mem_pool);
11945 
11946 mem_fail_out:
11947 	/* free the irq already requested */
11948 	free_irq(pci_irq_vector(phba->pcidev, 1), phba);
11949 
11950 irq_fail_out:
11951 	/* free the irq already requested */
11952 	free_irq(pci_irq_vector(phba->pcidev, 0), phba);
11953 
11954 msi_fail_out:
11955 	/* Unconfigure MSI-X capability structure */
11956 	pci_free_irq_vectors(phba->pcidev);
11957 
11958 vec_fail_out:
11959 	return rc;
11960 }
11961 
11962 /**
11963  * lpfc_sli_enable_msi - Enable MSI interrupt mode on SLI-3 device.
11964  * @phba: pointer to lpfc hba data structure.
11965  *
11966  * This routine is invoked to enable the MSI interrupt mode to device with
11967  * SLI-3 interface spec. The kernel function pci_enable_msi() is called to
11968  * enable the MSI vector. The device driver is responsible for calling the
11969  * request_irq() to register MSI vector with a interrupt the handler, which
11970  * is done in this function.
11971  *
11972  * Return codes
11973  * 	0 - successful
11974  * 	other values - error
11975  */
11976 static int
11977 lpfc_sli_enable_msi(struct lpfc_hba *phba)
11978 {
11979 	int rc;
11980 
11981 	rc = pci_enable_msi(phba->pcidev);
11982 	if (!rc)
11983 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11984 				"0462 PCI enable MSI mode success.\n");
11985 	else {
11986 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11987 				"0471 PCI enable MSI mode failed (%d)\n", rc);
11988 		return rc;
11989 	}
11990 
11991 	rc = request_irq(phba->pcidev->irq, lpfc_sli_intr_handler,
11992 			 0, LPFC_DRIVER_NAME, phba);
11993 	if (rc) {
11994 		pci_disable_msi(phba->pcidev);
11995 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
11996 				"0478 MSI request_irq failed (%d)\n", rc);
11997 	}
11998 	return rc;
11999 }
12000 
12001 /**
12002  * lpfc_sli_enable_intr - Enable device interrupt to SLI-3 device.
12003  * @phba: pointer to lpfc hba data structure.
12004  * @cfg_mode: Interrupt configuration mode (INTx, MSI or MSI-X).
12005  *
12006  * This routine is invoked to enable device interrupt and associate driver's
12007  * interrupt handler(s) to interrupt vector(s) to device with SLI-3 interface
12008  * spec. Depends on the interrupt mode configured to the driver, the driver
12009  * will try to fallback from the configured interrupt mode to an interrupt
12010  * mode which is supported by the platform, kernel, and device in the order
12011  * of:
12012  * MSI-X -> MSI -> IRQ.
12013  *
12014  * Return codes
12015  *   0 - successful
12016  *   other values - error
12017  **/
12018 static uint32_t
12019 lpfc_sli_enable_intr(struct lpfc_hba *phba, uint32_t cfg_mode)
12020 {
12021 	uint32_t intr_mode = LPFC_INTR_ERROR;
12022 	int retval;
12023 
12024 	/* Need to issue conf_port mbox cmd before conf_msi mbox cmd */
12025 	retval = lpfc_sli_config_port(phba, LPFC_SLI_REV3);
12026 	if (retval)
12027 		return intr_mode;
12028 	phba->hba_flag &= ~HBA_NEEDS_CFG_PORT;
12029 
12030 	if (cfg_mode == 2) {
12031 		/* Now, try to enable MSI-X interrupt mode */
12032 		retval = lpfc_sli_enable_msix(phba);
12033 		if (!retval) {
12034 			/* Indicate initialization to MSI-X mode */
12035 			phba->intr_type = MSIX;
12036 			intr_mode = 2;
12037 		}
12038 	}
12039 
12040 	/* Fallback to MSI if MSI-X initialization failed */
12041 	if (cfg_mode >= 1 && phba->intr_type == NONE) {
12042 		retval = lpfc_sli_enable_msi(phba);
12043 		if (!retval) {
12044 			/* Indicate initialization to MSI mode */
12045 			phba->intr_type = MSI;
12046 			intr_mode = 1;
12047 		}
12048 	}
12049 
12050 	/* Fallback to INTx if both MSI-X/MSI initalization failed */
12051 	if (phba->intr_type == NONE) {
12052 		retval = request_irq(phba->pcidev->irq, lpfc_sli_intr_handler,
12053 				     IRQF_SHARED, LPFC_DRIVER_NAME, phba);
12054 		if (!retval) {
12055 			/* Indicate initialization to INTx mode */
12056 			phba->intr_type = INTx;
12057 			intr_mode = 0;
12058 		}
12059 	}
12060 	return intr_mode;
12061 }
12062 
12063 /**
12064  * lpfc_sli_disable_intr - Disable device interrupt to SLI-3 device.
12065  * @phba: pointer to lpfc hba data structure.
12066  *
12067  * This routine is invoked to disable device interrupt and disassociate the
12068  * driver's interrupt handler(s) from interrupt vector(s) to device with
12069  * SLI-3 interface spec. Depending on the interrupt mode, the driver will
12070  * release the interrupt vector(s) for the message signaled interrupt.
12071  **/
12072 static void
12073 lpfc_sli_disable_intr(struct lpfc_hba *phba)
12074 {
12075 	int nr_irqs, i;
12076 
12077 	if (phba->intr_type == MSIX)
12078 		nr_irqs = LPFC_MSIX_VECTORS;
12079 	else
12080 		nr_irqs = 1;
12081 
12082 	for (i = 0; i < nr_irqs; i++)
12083 		free_irq(pci_irq_vector(phba->pcidev, i), phba);
12084 	pci_free_irq_vectors(phba->pcidev);
12085 
12086 	/* Reset interrupt management states */
12087 	phba->intr_type = NONE;
12088 	phba->sli.slistat.sli_intr = 0;
12089 }
12090 
12091 /**
12092  * lpfc_find_cpu_handle - Find the CPU that corresponds to the specified Queue
12093  * @phba: pointer to lpfc hba data structure.
12094  * @id: EQ vector index or Hardware Queue index
12095  * @match: LPFC_FIND_BY_EQ = match by EQ
12096  *         LPFC_FIND_BY_HDWQ = match by Hardware Queue
12097  * Return the CPU that matches the selection criteria
12098  */
12099 static uint16_t
12100 lpfc_find_cpu_handle(struct lpfc_hba *phba, uint16_t id, int match)
12101 {
12102 	struct lpfc_vector_map_info *cpup;
12103 	int cpu;
12104 
12105 	/* Loop through all CPUs */
12106 	for_each_present_cpu(cpu) {
12107 		cpup = &phba->sli4_hba.cpu_map[cpu];
12108 
12109 		/* If we are matching by EQ, there may be multiple CPUs using
12110 		 * using the same vector, so select the one with
12111 		 * LPFC_CPU_FIRST_IRQ set.
12112 		 */
12113 		if ((match == LPFC_FIND_BY_EQ) &&
12114 		    (cpup->flag & LPFC_CPU_FIRST_IRQ) &&
12115 		    (cpup->eq == id))
12116 			return cpu;
12117 
12118 		/* If matching by HDWQ, select the first CPU that matches */
12119 		if ((match == LPFC_FIND_BY_HDWQ) && (cpup->hdwq == id))
12120 			return cpu;
12121 	}
12122 	return 0;
12123 }
12124 
12125 #ifdef CONFIG_X86
12126 /**
12127  * lpfc_find_hyper - Determine if the CPU map entry is hyper-threaded
12128  * @phba: pointer to lpfc hba data structure.
12129  * @cpu: CPU map index
12130  * @phys_id: CPU package physical id
12131  * @core_id: CPU core id
12132  */
12133 static int
12134 lpfc_find_hyper(struct lpfc_hba *phba, int cpu,
12135 		uint16_t phys_id, uint16_t core_id)
12136 {
12137 	struct lpfc_vector_map_info *cpup;
12138 	int idx;
12139 
12140 	for_each_present_cpu(idx) {
12141 		cpup = &phba->sli4_hba.cpu_map[idx];
12142 		/* Does the cpup match the one we are looking for */
12143 		if ((cpup->phys_id == phys_id) &&
12144 		    (cpup->core_id == core_id) &&
12145 		    (cpu != idx))
12146 			return 1;
12147 	}
12148 	return 0;
12149 }
12150 #endif
12151 
12152 /*
12153  * lpfc_assign_eq_map_info - Assigns eq for vector_map structure
12154  * @phba: pointer to lpfc hba data structure.
12155  * @eqidx: index for eq and irq vector
12156  * @flag: flags to set for vector_map structure
12157  * @cpu: cpu used to index vector_map structure
12158  *
12159  * The routine assigns eq info into vector_map structure
12160  */
12161 static inline void
12162 lpfc_assign_eq_map_info(struct lpfc_hba *phba, uint16_t eqidx, uint16_t flag,
12163 			unsigned int cpu)
12164 {
12165 	struct lpfc_vector_map_info *cpup = &phba->sli4_hba.cpu_map[cpu];
12166 	struct lpfc_hba_eq_hdl *eqhdl = lpfc_get_eq_hdl(eqidx);
12167 
12168 	cpup->eq = eqidx;
12169 	cpup->flag |= flag;
12170 
12171 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12172 			"3336 Set Affinity: CPU %d irq %d eq %d flag x%x\n",
12173 			cpu, eqhdl->irq, cpup->eq, cpup->flag);
12174 }
12175 
12176 /**
12177  * lpfc_cpu_map_array_init - Initialize cpu_map structure
12178  * @phba: pointer to lpfc hba data structure.
12179  *
12180  * The routine initializes the cpu_map array structure
12181  */
12182 static void
12183 lpfc_cpu_map_array_init(struct lpfc_hba *phba)
12184 {
12185 	struct lpfc_vector_map_info *cpup;
12186 	struct lpfc_eq_intr_info *eqi;
12187 	int cpu;
12188 
12189 	for_each_possible_cpu(cpu) {
12190 		cpup = &phba->sli4_hba.cpu_map[cpu];
12191 		cpup->phys_id = LPFC_VECTOR_MAP_EMPTY;
12192 		cpup->core_id = LPFC_VECTOR_MAP_EMPTY;
12193 		cpup->hdwq = LPFC_VECTOR_MAP_EMPTY;
12194 		cpup->eq = LPFC_VECTOR_MAP_EMPTY;
12195 		cpup->flag = 0;
12196 		eqi = per_cpu_ptr(phba->sli4_hba.eq_info, cpu);
12197 		INIT_LIST_HEAD(&eqi->list);
12198 		eqi->icnt = 0;
12199 	}
12200 }
12201 
12202 /**
12203  * lpfc_hba_eq_hdl_array_init - Initialize hba_eq_hdl structure
12204  * @phba: pointer to lpfc hba data structure.
12205  *
12206  * The routine initializes the hba_eq_hdl array structure
12207  */
12208 static void
12209 lpfc_hba_eq_hdl_array_init(struct lpfc_hba *phba)
12210 {
12211 	struct lpfc_hba_eq_hdl *eqhdl;
12212 	int i;
12213 
12214 	for (i = 0; i < phba->cfg_irq_chann; i++) {
12215 		eqhdl = lpfc_get_eq_hdl(i);
12216 		eqhdl->irq = LPFC_VECTOR_MAP_EMPTY;
12217 		eqhdl->phba = phba;
12218 	}
12219 }
12220 
12221 /**
12222  * lpfc_cpu_affinity_check - Check vector CPU affinity mappings
12223  * @phba: pointer to lpfc hba data structure.
12224  * @vectors: number of msix vectors allocated.
12225  *
12226  * The routine will figure out the CPU affinity assignment for every
12227  * MSI-X vector allocated for the HBA.
12228  * In addition, the CPU to IO channel mapping will be calculated
12229  * and the phba->sli4_hba.cpu_map array will reflect this.
12230  */
12231 static void
12232 lpfc_cpu_affinity_check(struct lpfc_hba *phba, int vectors)
12233 {
12234 	int i, cpu, idx, next_idx, new_cpu, start_cpu, first_cpu;
12235 	int max_phys_id, min_phys_id;
12236 	int max_core_id, min_core_id;
12237 	struct lpfc_vector_map_info *cpup;
12238 	struct lpfc_vector_map_info *new_cpup;
12239 #ifdef CONFIG_X86
12240 	struct cpuinfo_x86 *cpuinfo;
12241 #endif
12242 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
12243 	struct lpfc_hdwq_stat *c_stat;
12244 #endif
12245 
12246 	max_phys_id = 0;
12247 	min_phys_id = LPFC_VECTOR_MAP_EMPTY;
12248 	max_core_id = 0;
12249 	min_core_id = LPFC_VECTOR_MAP_EMPTY;
12250 
12251 	/* Update CPU map with physical id and core id of each CPU */
12252 	for_each_present_cpu(cpu) {
12253 		cpup = &phba->sli4_hba.cpu_map[cpu];
12254 #ifdef CONFIG_X86
12255 		cpuinfo = &cpu_data(cpu);
12256 		cpup->phys_id = cpuinfo->phys_proc_id;
12257 		cpup->core_id = cpuinfo->cpu_core_id;
12258 		if (lpfc_find_hyper(phba, cpu, cpup->phys_id, cpup->core_id))
12259 			cpup->flag |= LPFC_CPU_MAP_HYPER;
12260 #else
12261 		/* No distinction between CPUs for other platforms */
12262 		cpup->phys_id = 0;
12263 		cpup->core_id = cpu;
12264 #endif
12265 
12266 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12267 				"3328 CPU %d physid %d coreid %d flag x%x\n",
12268 				cpu, cpup->phys_id, cpup->core_id, cpup->flag);
12269 
12270 		if (cpup->phys_id > max_phys_id)
12271 			max_phys_id = cpup->phys_id;
12272 		if (cpup->phys_id < min_phys_id)
12273 			min_phys_id = cpup->phys_id;
12274 
12275 		if (cpup->core_id > max_core_id)
12276 			max_core_id = cpup->core_id;
12277 		if (cpup->core_id < min_core_id)
12278 			min_core_id = cpup->core_id;
12279 	}
12280 
12281 	/* After looking at each irq vector assigned to this pcidev, its
12282 	 * possible to see that not ALL CPUs have been accounted for.
12283 	 * Next we will set any unassigned (unaffinitized) cpu map
12284 	 * entries to a IRQ on the same phys_id.
12285 	 */
12286 	first_cpu = cpumask_first(cpu_present_mask);
12287 	start_cpu = first_cpu;
12288 
12289 	for_each_present_cpu(cpu) {
12290 		cpup = &phba->sli4_hba.cpu_map[cpu];
12291 
12292 		/* Is this CPU entry unassigned */
12293 		if (cpup->eq == LPFC_VECTOR_MAP_EMPTY) {
12294 			/* Mark CPU as IRQ not assigned by the kernel */
12295 			cpup->flag |= LPFC_CPU_MAP_UNASSIGN;
12296 
12297 			/* If so, find a new_cpup thats on the the SAME
12298 			 * phys_id as cpup. start_cpu will start where we
12299 			 * left off so all unassigned entries don't get assgined
12300 			 * the IRQ of the first entry.
12301 			 */
12302 			new_cpu = start_cpu;
12303 			for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12304 				new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12305 				if (!(new_cpup->flag & LPFC_CPU_MAP_UNASSIGN) &&
12306 				    (new_cpup->eq != LPFC_VECTOR_MAP_EMPTY) &&
12307 				    (new_cpup->phys_id == cpup->phys_id))
12308 					goto found_same;
12309 				new_cpu = cpumask_next(
12310 					new_cpu, cpu_present_mask);
12311 				if (new_cpu == nr_cpumask_bits)
12312 					new_cpu = first_cpu;
12313 			}
12314 			/* At this point, we leave the CPU as unassigned */
12315 			continue;
12316 found_same:
12317 			/* We found a matching phys_id, so copy the IRQ info */
12318 			cpup->eq = new_cpup->eq;
12319 
12320 			/* Bump start_cpu to the next slot to minmize the
12321 			 * chance of having multiple unassigned CPU entries
12322 			 * selecting the same IRQ.
12323 			 */
12324 			start_cpu = cpumask_next(new_cpu, cpu_present_mask);
12325 			if (start_cpu == nr_cpumask_bits)
12326 				start_cpu = first_cpu;
12327 
12328 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12329 					"3337 Set Affinity: CPU %d "
12330 					"eq %d from peer cpu %d same "
12331 					"phys_id (%d)\n",
12332 					cpu, cpup->eq, new_cpu,
12333 					cpup->phys_id);
12334 		}
12335 	}
12336 
12337 	/* Set any unassigned cpu map entries to a IRQ on any phys_id */
12338 	start_cpu = first_cpu;
12339 
12340 	for_each_present_cpu(cpu) {
12341 		cpup = &phba->sli4_hba.cpu_map[cpu];
12342 
12343 		/* Is this entry unassigned */
12344 		if (cpup->eq == LPFC_VECTOR_MAP_EMPTY) {
12345 			/* Mark it as IRQ not assigned by the kernel */
12346 			cpup->flag |= LPFC_CPU_MAP_UNASSIGN;
12347 
12348 			/* If so, find a new_cpup thats on ANY phys_id
12349 			 * as the cpup. start_cpu will start where we
12350 			 * left off so all unassigned entries don't get
12351 			 * assigned the IRQ of the first entry.
12352 			 */
12353 			new_cpu = start_cpu;
12354 			for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12355 				new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12356 				if (!(new_cpup->flag & LPFC_CPU_MAP_UNASSIGN) &&
12357 				    (new_cpup->eq != LPFC_VECTOR_MAP_EMPTY))
12358 					goto found_any;
12359 				new_cpu = cpumask_next(
12360 					new_cpu, cpu_present_mask);
12361 				if (new_cpu == nr_cpumask_bits)
12362 					new_cpu = first_cpu;
12363 			}
12364 			/* We should never leave an entry unassigned */
12365 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12366 					"3339 Set Affinity: CPU %d "
12367 					"eq %d UNASSIGNED\n",
12368 					cpup->hdwq, cpup->eq);
12369 			continue;
12370 found_any:
12371 			/* We found an available entry, copy the IRQ info */
12372 			cpup->eq = new_cpup->eq;
12373 
12374 			/* Bump start_cpu to the next slot to minmize the
12375 			 * chance of having multiple unassigned CPU entries
12376 			 * selecting the same IRQ.
12377 			 */
12378 			start_cpu = cpumask_next(new_cpu, cpu_present_mask);
12379 			if (start_cpu == nr_cpumask_bits)
12380 				start_cpu = first_cpu;
12381 
12382 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12383 					"3338 Set Affinity: CPU %d "
12384 					"eq %d from peer cpu %d (%d/%d)\n",
12385 					cpu, cpup->eq, new_cpu,
12386 					new_cpup->phys_id, new_cpup->core_id);
12387 		}
12388 	}
12389 
12390 	/* Assign hdwq indices that are unique across all cpus in the map
12391 	 * that are also FIRST_CPUs.
12392 	 */
12393 	idx = 0;
12394 	for_each_present_cpu(cpu) {
12395 		cpup = &phba->sli4_hba.cpu_map[cpu];
12396 
12397 		/* Only FIRST IRQs get a hdwq index assignment. */
12398 		if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
12399 			continue;
12400 
12401 		/* 1 to 1, the first LPFC_CPU_FIRST_IRQ cpus to a unique hdwq */
12402 		cpup->hdwq = idx;
12403 		idx++;
12404 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12405 				"3333 Set Affinity: CPU %d (phys %d core %d): "
12406 				"hdwq %d eq %d flg x%x\n",
12407 				cpu, cpup->phys_id, cpup->core_id,
12408 				cpup->hdwq, cpup->eq, cpup->flag);
12409 	}
12410 	/* Associate a hdwq with each cpu_map entry
12411 	 * This will be 1 to 1 - hdwq to cpu, unless there are less
12412 	 * hardware queues then CPUs. For that case we will just round-robin
12413 	 * the available hardware queues as they get assigned to CPUs.
12414 	 * The next_idx is the idx from the FIRST_CPU loop above to account
12415 	 * for irq_chann < hdwq.  The idx is used for round-robin assignments
12416 	 * and needs to start at 0.
12417 	 */
12418 	next_idx = idx;
12419 	start_cpu = 0;
12420 	idx = 0;
12421 	for_each_present_cpu(cpu) {
12422 		cpup = &phba->sli4_hba.cpu_map[cpu];
12423 
12424 		/* FIRST cpus are already mapped. */
12425 		if (cpup->flag & LPFC_CPU_FIRST_IRQ)
12426 			continue;
12427 
12428 		/* If the cfg_irq_chann < cfg_hdw_queue, set the hdwq
12429 		 * of the unassigned cpus to the next idx so that all
12430 		 * hdw queues are fully utilized.
12431 		 */
12432 		if (next_idx < phba->cfg_hdw_queue) {
12433 			cpup->hdwq = next_idx;
12434 			next_idx++;
12435 			continue;
12436 		}
12437 
12438 		/* Not a First CPU and all hdw_queues are used.  Reuse a
12439 		 * Hardware Queue for another CPU, so be smart about it
12440 		 * and pick one that has its IRQ/EQ mapped to the same phys_id
12441 		 * (CPU package) and core_id.
12442 		 */
12443 		new_cpu = start_cpu;
12444 		for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12445 			new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12446 			if (new_cpup->hdwq != LPFC_VECTOR_MAP_EMPTY &&
12447 			    new_cpup->phys_id == cpup->phys_id &&
12448 			    new_cpup->core_id == cpup->core_id) {
12449 				goto found_hdwq;
12450 			}
12451 			new_cpu = cpumask_next(new_cpu, cpu_present_mask);
12452 			if (new_cpu == nr_cpumask_bits)
12453 				new_cpu = first_cpu;
12454 		}
12455 
12456 		/* If we can't match both phys_id and core_id,
12457 		 * settle for just a phys_id match.
12458 		 */
12459 		new_cpu = start_cpu;
12460 		for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12461 			new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12462 			if (new_cpup->hdwq != LPFC_VECTOR_MAP_EMPTY &&
12463 			    new_cpup->phys_id == cpup->phys_id)
12464 				goto found_hdwq;
12465 
12466 			new_cpu = cpumask_next(new_cpu, cpu_present_mask);
12467 			if (new_cpu == nr_cpumask_bits)
12468 				new_cpu = first_cpu;
12469 		}
12470 
12471 		/* Otherwise just round robin on cfg_hdw_queue */
12472 		cpup->hdwq = idx % phba->cfg_hdw_queue;
12473 		idx++;
12474 		goto logit;
12475  found_hdwq:
12476 		/* We found an available entry, copy the IRQ info */
12477 		start_cpu = cpumask_next(new_cpu, cpu_present_mask);
12478 		if (start_cpu == nr_cpumask_bits)
12479 			start_cpu = first_cpu;
12480 		cpup->hdwq = new_cpup->hdwq;
12481  logit:
12482 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12483 				"3335 Set Affinity: CPU %d (phys %d core %d): "
12484 				"hdwq %d eq %d flg x%x\n",
12485 				cpu, cpup->phys_id, cpup->core_id,
12486 				cpup->hdwq, cpup->eq, cpup->flag);
12487 	}
12488 
12489 	/*
12490 	 * Initialize the cpu_map slots for not-present cpus in case
12491 	 * a cpu is hot-added. Perform a simple hdwq round robin assignment.
12492 	 */
12493 	idx = 0;
12494 	for_each_possible_cpu(cpu) {
12495 		cpup = &phba->sli4_hba.cpu_map[cpu];
12496 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
12497 		c_stat = per_cpu_ptr(phba->sli4_hba.c_stat, cpu);
12498 		c_stat->hdwq_no = cpup->hdwq;
12499 #endif
12500 		if (cpup->hdwq != LPFC_VECTOR_MAP_EMPTY)
12501 			continue;
12502 
12503 		cpup->hdwq = idx++ % phba->cfg_hdw_queue;
12504 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
12505 		c_stat->hdwq_no = cpup->hdwq;
12506 #endif
12507 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12508 				"3340 Set Affinity: not present "
12509 				"CPU %d hdwq %d\n",
12510 				cpu, cpup->hdwq);
12511 	}
12512 
12513 	/* The cpu_map array will be used later during initialization
12514 	 * when EQ / CQ / WQs are allocated and configured.
12515 	 */
12516 	return;
12517 }
12518 
12519 /**
12520  * lpfc_cpuhp_get_eq
12521  *
12522  * @phba:   pointer to lpfc hba data structure.
12523  * @cpu:    cpu going offline
12524  * @eqlist: eq list to append to
12525  */
12526 static int
12527 lpfc_cpuhp_get_eq(struct lpfc_hba *phba, unsigned int cpu,
12528 		  struct list_head *eqlist)
12529 {
12530 	const struct cpumask *maskp;
12531 	struct lpfc_queue *eq;
12532 	struct cpumask *tmp;
12533 	u16 idx;
12534 
12535 	tmp = kzalloc(cpumask_size(), GFP_KERNEL);
12536 	if (!tmp)
12537 		return -ENOMEM;
12538 
12539 	for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
12540 		maskp = pci_irq_get_affinity(phba->pcidev, idx);
12541 		if (!maskp)
12542 			continue;
12543 		/*
12544 		 * if irq is not affinitized to the cpu going
12545 		 * then we don't need to poll the eq attached
12546 		 * to it.
12547 		 */
12548 		if (!cpumask_and(tmp, maskp, cpumask_of(cpu)))
12549 			continue;
12550 		/* get the cpus that are online and are affini-
12551 		 * tized to this irq vector.  If the count is
12552 		 * more than 1 then cpuhp is not going to shut-
12553 		 * down this vector.  Since this cpu has not
12554 		 * gone offline yet, we need >1.
12555 		 */
12556 		cpumask_and(tmp, maskp, cpu_online_mask);
12557 		if (cpumask_weight(tmp) > 1)
12558 			continue;
12559 
12560 		/* Now that we have an irq to shutdown, get the eq
12561 		 * mapped to this irq.  Note: multiple hdwq's in
12562 		 * the software can share an eq, but eventually
12563 		 * only eq will be mapped to this vector
12564 		 */
12565 		eq = phba->sli4_hba.hba_eq_hdl[idx].eq;
12566 		list_add(&eq->_poll_list, eqlist);
12567 	}
12568 	kfree(tmp);
12569 	return 0;
12570 }
12571 
12572 static void __lpfc_cpuhp_remove(struct lpfc_hba *phba)
12573 {
12574 	if (phba->sli_rev != LPFC_SLI_REV4)
12575 		return;
12576 
12577 	cpuhp_state_remove_instance_nocalls(lpfc_cpuhp_state,
12578 					    &phba->cpuhp);
12579 	/*
12580 	 * unregistering the instance doesn't stop the polling
12581 	 * timer. Wait for the poll timer to retire.
12582 	 */
12583 	synchronize_rcu();
12584 	del_timer_sync(&phba->cpuhp_poll_timer);
12585 }
12586 
12587 static void lpfc_cpuhp_remove(struct lpfc_hba *phba)
12588 {
12589 	if (phba->pport->fc_flag & FC_OFFLINE_MODE)
12590 		return;
12591 
12592 	__lpfc_cpuhp_remove(phba);
12593 }
12594 
12595 static void lpfc_cpuhp_add(struct lpfc_hba *phba)
12596 {
12597 	if (phba->sli_rev != LPFC_SLI_REV4)
12598 		return;
12599 
12600 	rcu_read_lock();
12601 
12602 	if (!list_empty(&phba->poll_list))
12603 		mod_timer(&phba->cpuhp_poll_timer,
12604 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
12605 
12606 	rcu_read_unlock();
12607 
12608 	cpuhp_state_add_instance_nocalls(lpfc_cpuhp_state,
12609 					 &phba->cpuhp);
12610 }
12611 
12612 static int __lpfc_cpuhp_checks(struct lpfc_hba *phba, int *retval)
12613 {
12614 	if (phba->pport->load_flag & FC_UNLOADING) {
12615 		*retval = -EAGAIN;
12616 		return true;
12617 	}
12618 
12619 	if (phba->sli_rev != LPFC_SLI_REV4) {
12620 		*retval = 0;
12621 		return true;
12622 	}
12623 
12624 	/* proceed with the hotplug */
12625 	return false;
12626 }
12627 
12628 /**
12629  * lpfc_irq_set_aff - set IRQ affinity
12630  * @eqhdl: EQ handle
12631  * @cpu: cpu to set affinity
12632  *
12633  **/
12634 static inline void
12635 lpfc_irq_set_aff(struct lpfc_hba_eq_hdl *eqhdl, unsigned int cpu)
12636 {
12637 	cpumask_clear(&eqhdl->aff_mask);
12638 	cpumask_set_cpu(cpu, &eqhdl->aff_mask);
12639 	irq_set_status_flags(eqhdl->irq, IRQ_NO_BALANCING);
12640 	irq_set_affinity_hint(eqhdl->irq, &eqhdl->aff_mask);
12641 }
12642 
12643 /**
12644  * lpfc_irq_clear_aff - clear IRQ affinity
12645  * @eqhdl: EQ handle
12646  *
12647  **/
12648 static inline void
12649 lpfc_irq_clear_aff(struct lpfc_hba_eq_hdl *eqhdl)
12650 {
12651 	cpumask_clear(&eqhdl->aff_mask);
12652 	irq_clear_status_flags(eqhdl->irq, IRQ_NO_BALANCING);
12653 }
12654 
12655 /**
12656  * lpfc_irq_rebalance - rebalances IRQ affinity according to cpuhp event
12657  * @phba: pointer to HBA context object.
12658  * @cpu: cpu going offline/online
12659  * @offline: true, cpu is going offline. false, cpu is coming online.
12660  *
12661  * If cpu is going offline, we'll try our best effort to find the next
12662  * online cpu on the phba's original_mask and migrate all offlining IRQ
12663  * affinities.
12664  *
12665  * If cpu is coming online, reaffinitize the IRQ back to the onlining cpu.
12666  *
12667  * Note: Call only if NUMA or NHT mode is enabled, otherwise rely on
12668  *	 PCI_IRQ_AFFINITY to auto-manage IRQ affinity.
12669  *
12670  **/
12671 static void
12672 lpfc_irq_rebalance(struct lpfc_hba *phba, unsigned int cpu, bool offline)
12673 {
12674 	struct lpfc_vector_map_info *cpup;
12675 	struct cpumask *aff_mask;
12676 	unsigned int cpu_select, cpu_next, idx;
12677 	const struct cpumask *orig_mask;
12678 
12679 	if (phba->irq_chann_mode == NORMAL_MODE)
12680 		return;
12681 
12682 	orig_mask = &phba->sli4_hba.irq_aff_mask;
12683 
12684 	if (!cpumask_test_cpu(cpu, orig_mask))
12685 		return;
12686 
12687 	cpup = &phba->sli4_hba.cpu_map[cpu];
12688 
12689 	if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
12690 		return;
12691 
12692 	if (offline) {
12693 		/* Find next online CPU on original mask */
12694 		cpu_next = cpumask_next_wrap(cpu, orig_mask, cpu, true);
12695 		cpu_select = lpfc_next_online_cpu(orig_mask, cpu_next);
12696 
12697 		/* Found a valid CPU */
12698 		if ((cpu_select < nr_cpu_ids) && (cpu_select != cpu)) {
12699 			/* Go through each eqhdl and ensure offlining
12700 			 * cpu aff_mask is migrated
12701 			 */
12702 			for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
12703 				aff_mask = lpfc_get_aff_mask(idx);
12704 
12705 				/* Migrate affinity */
12706 				if (cpumask_test_cpu(cpu, aff_mask))
12707 					lpfc_irq_set_aff(lpfc_get_eq_hdl(idx),
12708 							 cpu_select);
12709 			}
12710 		} else {
12711 			/* Rely on irqbalance if no online CPUs left on NUMA */
12712 			for (idx = 0; idx < phba->cfg_irq_chann; idx++)
12713 				lpfc_irq_clear_aff(lpfc_get_eq_hdl(idx));
12714 		}
12715 	} else {
12716 		/* Migrate affinity back to this CPU */
12717 		lpfc_irq_set_aff(lpfc_get_eq_hdl(cpup->eq), cpu);
12718 	}
12719 }
12720 
12721 static int lpfc_cpu_offline(unsigned int cpu, struct hlist_node *node)
12722 {
12723 	struct lpfc_hba *phba = hlist_entry_safe(node, struct lpfc_hba, cpuhp);
12724 	struct lpfc_queue *eq, *next;
12725 	LIST_HEAD(eqlist);
12726 	int retval;
12727 
12728 	if (!phba) {
12729 		WARN_ONCE(!phba, "cpu: %u. phba:NULL", raw_smp_processor_id());
12730 		return 0;
12731 	}
12732 
12733 	if (__lpfc_cpuhp_checks(phba, &retval))
12734 		return retval;
12735 
12736 	lpfc_irq_rebalance(phba, cpu, true);
12737 
12738 	retval = lpfc_cpuhp_get_eq(phba, cpu, &eqlist);
12739 	if (retval)
12740 		return retval;
12741 
12742 	/* start polling on these eq's */
12743 	list_for_each_entry_safe(eq, next, &eqlist, _poll_list) {
12744 		list_del_init(&eq->_poll_list);
12745 		lpfc_sli4_start_polling(eq);
12746 	}
12747 
12748 	return 0;
12749 }
12750 
12751 static int lpfc_cpu_online(unsigned int cpu, struct hlist_node *node)
12752 {
12753 	struct lpfc_hba *phba = hlist_entry_safe(node, struct lpfc_hba, cpuhp);
12754 	struct lpfc_queue *eq, *next;
12755 	unsigned int n;
12756 	int retval;
12757 
12758 	if (!phba) {
12759 		WARN_ONCE(!phba, "cpu: %u. phba:NULL", raw_smp_processor_id());
12760 		return 0;
12761 	}
12762 
12763 	if (__lpfc_cpuhp_checks(phba, &retval))
12764 		return retval;
12765 
12766 	lpfc_irq_rebalance(phba, cpu, false);
12767 
12768 	list_for_each_entry_safe(eq, next, &phba->poll_list, _poll_list) {
12769 		n = lpfc_find_cpu_handle(phba, eq->hdwq, LPFC_FIND_BY_HDWQ);
12770 		if (n == cpu)
12771 			lpfc_sli4_stop_polling(eq);
12772 	}
12773 
12774 	return 0;
12775 }
12776 
12777 /**
12778  * lpfc_sli4_enable_msix - Enable MSI-X interrupt mode to SLI-4 device
12779  * @phba: pointer to lpfc hba data structure.
12780  *
12781  * This routine is invoked to enable the MSI-X interrupt vectors to device
12782  * with SLI-4 interface spec.  It also allocates MSI-X vectors and maps them
12783  * to cpus on the system.
12784  *
12785  * When cfg_irq_numa is enabled, the adapter will only allocate vectors for
12786  * the number of cpus on the same numa node as this adapter.  The vectors are
12787  * allocated without requesting OS affinity mapping.  A vector will be
12788  * allocated and assigned to each online and offline cpu.  If the cpu is
12789  * online, then affinity will be set to that cpu.  If the cpu is offline, then
12790  * affinity will be set to the nearest peer cpu within the numa node that is
12791  * online.  If there are no online cpus within the numa node, affinity is not
12792  * assigned and the OS may do as it pleases. Note: cpu vector affinity mapping
12793  * is consistent with the way cpu online/offline is handled when cfg_irq_numa is
12794  * configured.
12795  *
12796  * If numa mode is not enabled and there is more than 1 vector allocated, then
12797  * the driver relies on the managed irq interface where the OS assigns vector to
12798  * cpu affinity.  The driver will then use that affinity mapping to setup its
12799  * cpu mapping table.
12800  *
12801  * Return codes
12802  * 0 - successful
12803  * other values - error
12804  **/
12805 static int
12806 lpfc_sli4_enable_msix(struct lpfc_hba *phba)
12807 {
12808 	int vectors, rc, index;
12809 	char *name;
12810 	const struct cpumask *aff_mask = NULL;
12811 	unsigned int cpu = 0, cpu_cnt = 0, cpu_select = nr_cpu_ids;
12812 	struct lpfc_vector_map_info *cpup;
12813 	struct lpfc_hba_eq_hdl *eqhdl;
12814 	const struct cpumask *maskp;
12815 	unsigned int flags = PCI_IRQ_MSIX;
12816 
12817 	/* Set up MSI-X multi-message vectors */
12818 	vectors = phba->cfg_irq_chann;
12819 
12820 	if (phba->irq_chann_mode != NORMAL_MODE)
12821 		aff_mask = &phba->sli4_hba.irq_aff_mask;
12822 
12823 	if (aff_mask) {
12824 		cpu_cnt = cpumask_weight(aff_mask);
12825 		vectors = min(phba->cfg_irq_chann, cpu_cnt);
12826 
12827 		/* cpu: iterates over aff_mask including offline or online
12828 		 * cpu_select: iterates over online aff_mask to set affinity
12829 		 */
12830 		cpu = cpumask_first(aff_mask);
12831 		cpu_select = lpfc_next_online_cpu(aff_mask, cpu);
12832 	} else {
12833 		flags |= PCI_IRQ_AFFINITY;
12834 	}
12835 
12836 	rc = pci_alloc_irq_vectors(phba->pcidev, 1, vectors, flags);
12837 	if (rc < 0) {
12838 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12839 				"0484 PCI enable MSI-X failed (%d)\n", rc);
12840 		goto vec_fail_out;
12841 	}
12842 	vectors = rc;
12843 
12844 	/* Assign MSI-X vectors to interrupt handlers */
12845 	for (index = 0; index < vectors; index++) {
12846 		eqhdl = lpfc_get_eq_hdl(index);
12847 		name = eqhdl->handler_name;
12848 		memset(name, 0, LPFC_SLI4_HANDLER_NAME_SZ);
12849 		snprintf(name, LPFC_SLI4_HANDLER_NAME_SZ,
12850 			 LPFC_DRIVER_HANDLER_NAME"%d", index);
12851 
12852 		eqhdl->idx = index;
12853 		rc = request_irq(pci_irq_vector(phba->pcidev, index),
12854 			 &lpfc_sli4_hba_intr_handler, 0,
12855 			 name, eqhdl);
12856 		if (rc) {
12857 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
12858 					"0486 MSI-X fast-path (%d) "
12859 					"request_irq failed (%d)\n", index, rc);
12860 			goto cfg_fail_out;
12861 		}
12862 
12863 		eqhdl->irq = pci_irq_vector(phba->pcidev, index);
12864 
12865 		if (aff_mask) {
12866 			/* If found a neighboring online cpu, set affinity */
12867 			if (cpu_select < nr_cpu_ids)
12868 				lpfc_irq_set_aff(eqhdl, cpu_select);
12869 
12870 			/* Assign EQ to cpu_map */
12871 			lpfc_assign_eq_map_info(phba, index,
12872 						LPFC_CPU_FIRST_IRQ,
12873 						cpu);
12874 
12875 			/* Iterate to next offline or online cpu in aff_mask */
12876 			cpu = cpumask_next(cpu, aff_mask);
12877 
12878 			/* Find next online cpu in aff_mask to set affinity */
12879 			cpu_select = lpfc_next_online_cpu(aff_mask, cpu);
12880 		} else if (vectors == 1) {
12881 			cpu = cpumask_first(cpu_present_mask);
12882 			lpfc_assign_eq_map_info(phba, index, LPFC_CPU_FIRST_IRQ,
12883 						cpu);
12884 		} else {
12885 			maskp = pci_irq_get_affinity(phba->pcidev, index);
12886 
12887 			/* Loop through all CPUs associated with vector index */
12888 			for_each_cpu_and(cpu, maskp, cpu_present_mask) {
12889 				cpup = &phba->sli4_hba.cpu_map[cpu];
12890 
12891 				/* If this is the first CPU thats assigned to
12892 				 * this vector, set LPFC_CPU_FIRST_IRQ.
12893 				 *
12894 				 * With certain platforms its possible that irq
12895 				 * vectors are affinitized to all the cpu's.
12896 				 * This can result in each cpu_map.eq to be set
12897 				 * to the last vector, resulting in overwrite
12898 				 * of all the previous cpu_map.eq.  Ensure that
12899 				 * each vector receives a place in cpu_map.
12900 				 * Later call to lpfc_cpu_affinity_check will
12901 				 * ensure we are nicely balanced out.
12902 				 */
12903 				if (cpup->eq != LPFC_VECTOR_MAP_EMPTY)
12904 					continue;
12905 				lpfc_assign_eq_map_info(phba, index,
12906 							LPFC_CPU_FIRST_IRQ,
12907 							cpu);
12908 				break;
12909 			}
12910 		}
12911 	}
12912 
12913 	if (vectors != phba->cfg_irq_chann) {
12914 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12915 				"3238 Reducing IO channels to match number of "
12916 				"MSI-X vectors, requested %d got %d\n",
12917 				phba->cfg_irq_chann, vectors);
12918 		if (phba->cfg_irq_chann > vectors)
12919 			phba->cfg_irq_chann = vectors;
12920 	}
12921 
12922 	return rc;
12923 
12924 cfg_fail_out:
12925 	/* free the irq already requested */
12926 	for (--index; index >= 0; index--) {
12927 		eqhdl = lpfc_get_eq_hdl(index);
12928 		lpfc_irq_clear_aff(eqhdl);
12929 		irq_set_affinity_hint(eqhdl->irq, NULL);
12930 		free_irq(eqhdl->irq, eqhdl);
12931 	}
12932 
12933 	/* Unconfigure MSI-X capability structure */
12934 	pci_free_irq_vectors(phba->pcidev);
12935 
12936 vec_fail_out:
12937 	return rc;
12938 }
12939 
12940 /**
12941  * lpfc_sli4_enable_msi - Enable MSI interrupt mode to SLI-4 device
12942  * @phba: pointer to lpfc hba data structure.
12943  *
12944  * This routine is invoked to enable the MSI interrupt mode to device with
12945  * SLI-4 interface spec. The kernel function pci_alloc_irq_vectors() is
12946  * called to enable the MSI vector. The device driver is responsible for
12947  * calling the request_irq() to register MSI vector with a interrupt the
12948  * handler, which is done in this function.
12949  *
12950  * Return codes
12951  * 	0 - successful
12952  * 	other values - error
12953  **/
12954 static int
12955 lpfc_sli4_enable_msi(struct lpfc_hba *phba)
12956 {
12957 	int rc, index;
12958 	unsigned int cpu;
12959 	struct lpfc_hba_eq_hdl *eqhdl;
12960 
12961 	rc = pci_alloc_irq_vectors(phba->pcidev, 1, 1,
12962 				   PCI_IRQ_MSI | PCI_IRQ_AFFINITY);
12963 	if (rc > 0)
12964 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12965 				"0487 PCI enable MSI mode success.\n");
12966 	else {
12967 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12968 				"0488 PCI enable MSI mode failed (%d)\n", rc);
12969 		return rc ? rc : -1;
12970 	}
12971 
12972 	rc = request_irq(phba->pcidev->irq, lpfc_sli4_intr_handler,
12973 			 0, LPFC_DRIVER_NAME, phba);
12974 	if (rc) {
12975 		pci_free_irq_vectors(phba->pcidev);
12976 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
12977 				"0490 MSI request_irq failed (%d)\n", rc);
12978 		return rc;
12979 	}
12980 
12981 	eqhdl = lpfc_get_eq_hdl(0);
12982 	eqhdl->irq = pci_irq_vector(phba->pcidev, 0);
12983 
12984 	cpu = cpumask_first(cpu_present_mask);
12985 	lpfc_assign_eq_map_info(phba, 0, LPFC_CPU_FIRST_IRQ, cpu);
12986 
12987 	for (index = 0; index < phba->cfg_irq_chann; index++) {
12988 		eqhdl = lpfc_get_eq_hdl(index);
12989 		eqhdl->idx = index;
12990 	}
12991 
12992 	return 0;
12993 }
12994 
12995 /**
12996  * lpfc_sli4_enable_intr - Enable device interrupt to SLI-4 device
12997  * @phba: pointer to lpfc hba data structure.
12998  * @cfg_mode: Interrupt configuration mode (INTx, MSI or MSI-X).
12999  *
13000  * This routine is invoked to enable device interrupt and associate driver's
13001  * interrupt handler(s) to interrupt vector(s) to device with SLI-4
13002  * interface spec. Depends on the interrupt mode configured to the driver,
13003  * the driver will try to fallback from the configured interrupt mode to an
13004  * interrupt mode which is supported by the platform, kernel, and device in
13005  * the order of:
13006  * MSI-X -> MSI -> IRQ.
13007  *
13008  * Return codes
13009  * 	0 - successful
13010  * 	other values - error
13011  **/
13012 static uint32_t
13013 lpfc_sli4_enable_intr(struct lpfc_hba *phba, uint32_t cfg_mode)
13014 {
13015 	uint32_t intr_mode = LPFC_INTR_ERROR;
13016 	int retval, idx;
13017 
13018 	if (cfg_mode == 2) {
13019 		/* Preparation before conf_msi mbox cmd */
13020 		retval = 0;
13021 		if (!retval) {
13022 			/* Now, try to enable MSI-X interrupt mode */
13023 			retval = lpfc_sli4_enable_msix(phba);
13024 			if (!retval) {
13025 				/* Indicate initialization to MSI-X mode */
13026 				phba->intr_type = MSIX;
13027 				intr_mode = 2;
13028 			}
13029 		}
13030 	}
13031 
13032 	/* Fallback to MSI if MSI-X initialization failed */
13033 	if (cfg_mode >= 1 && phba->intr_type == NONE) {
13034 		retval = lpfc_sli4_enable_msi(phba);
13035 		if (!retval) {
13036 			/* Indicate initialization to MSI mode */
13037 			phba->intr_type = MSI;
13038 			intr_mode = 1;
13039 		}
13040 	}
13041 
13042 	/* Fallback to INTx if both MSI-X/MSI initalization failed */
13043 	if (phba->intr_type == NONE) {
13044 		retval = request_irq(phba->pcidev->irq, lpfc_sli4_intr_handler,
13045 				     IRQF_SHARED, LPFC_DRIVER_NAME, phba);
13046 		if (!retval) {
13047 			struct lpfc_hba_eq_hdl *eqhdl;
13048 			unsigned int cpu;
13049 
13050 			/* Indicate initialization to INTx mode */
13051 			phba->intr_type = INTx;
13052 			intr_mode = 0;
13053 
13054 			eqhdl = lpfc_get_eq_hdl(0);
13055 			eqhdl->irq = pci_irq_vector(phba->pcidev, 0);
13056 
13057 			cpu = cpumask_first(cpu_present_mask);
13058 			lpfc_assign_eq_map_info(phba, 0, LPFC_CPU_FIRST_IRQ,
13059 						cpu);
13060 			for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
13061 				eqhdl = lpfc_get_eq_hdl(idx);
13062 				eqhdl->idx = idx;
13063 			}
13064 		}
13065 	}
13066 	return intr_mode;
13067 }
13068 
13069 /**
13070  * lpfc_sli4_disable_intr - Disable device interrupt to SLI-4 device
13071  * @phba: pointer to lpfc hba data structure.
13072  *
13073  * This routine is invoked to disable device interrupt and disassociate
13074  * the driver's interrupt handler(s) from interrupt vector(s) to device
13075  * with SLI-4 interface spec. Depending on the interrupt mode, the driver
13076  * will release the interrupt vector(s) for the message signaled interrupt.
13077  **/
13078 static void
13079 lpfc_sli4_disable_intr(struct lpfc_hba *phba)
13080 {
13081 	/* Disable the currently initialized interrupt mode */
13082 	if (phba->intr_type == MSIX) {
13083 		int index;
13084 		struct lpfc_hba_eq_hdl *eqhdl;
13085 
13086 		/* Free up MSI-X multi-message vectors */
13087 		for (index = 0; index < phba->cfg_irq_chann; index++) {
13088 			eqhdl = lpfc_get_eq_hdl(index);
13089 			lpfc_irq_clear_aff(eqhdl);
13090 			irq_set_affinity_hint(eqhdl->irq, NULL);
13091 			free_irq(eqhdl->irq, eqhdl);
13092 		}
13093 	} else {
13094 		free_irq(phba->pcidev->irq, phba);
13095 	}
13096 
13097 	pci_free_irq_vectors(phba->pcidev);
13098 
13099 	/* Reset interrupt management states */
13100 	phba->intr_type = NONE;
13101 	phba->sli.slistat.sli_intr = 0;
13102 }
13103 
13104 /**
13105  * lpfc_unset_hba - Unset SLI3 hba device initialization
13106  * @phba: pointer to lpfc hba data structure.
13107  *
13108  * This routine is invoked to unset the HBA device initialization steps to
13109  * a device with SLI-3 interface spec.
13110  **/
13111 static void
13112 lpfc_unset_hba(struct lpfc_hba *phba)
13113 {
13114 	struct lpfc_vport *vport = phba->pport;
13115 	struct Scsi_Host  *shost = lpfc_shost_from_vport(vport);
13116 
13117 	spin_lock_irq(shost->host_lock);
13118 	vport->load_flag |= FC_UNLOADING;
13119 	spin_unlock_irq(shost->host_lock);
13120 
13121 	kfree(phba->vpi_bmask);
13122 	kfree(phba->vpi_ids);
13123 
13124 	lpfc_stop_hba_timers(phba);
13125 
13126 	phba->pport->work_port_events = 0;
13127 
13128 	lpfc_sli_hba_down(phba);
13129 
13130 	lpfc_sli_brdrestart(phba);
13131 
13132 	lpfc_sli_disable_intr(phba);
13133 
13134 	return;
13135 }
13136 
13137 /**
13138  * lpfc_sli4_xri_exchange_busy_wait - Wait for device XRI exchange busy
13139  * @phba: Pointer to HBA context object.
13140  *
13141  * This function is called in the SLI4 code path to wait for completion
13142  * of device's XRIs exchange busy. It will check the XRI exchange busy
13143  * on outstanding FCP and ELS I/Os every 10ms for up to 10 seconds; after
13144  * that, it will check the XRI exchange busy on outstanding FCP and ELS
13145  * I/Os every 30 seconds, log error message, and wait forever. Only when
13146  * all XRI exchange busy complete, the driver unload shall proceed with
13147  * invoking the function reset ioctl mailbox command to the CNA and the
13148  * the rest of the driver unload resource release.
13149  **/
13150 static void
13151 lpfc_sli4_xri_exchange_busy_wait(struct lpfc_hba *phba)
13152 {
13153 	struct lpfc_sli4_hdw_queue *qp;
13154 	int idx, ccnt;
13155 	int wait_time = 0;
13156 	int io_xri_cmpl = 1;
13157 	int nvmet_xri_cmpl = 1;
13158 	int els_xri_cmpl = list_empty(&phba->sli4_hba.lpfc_abts_els_sgl_list);
13159 
13160 	/* Driver just aborted IOs during the hba_unset process.  Pause
13161 	 * here to give the HBA time to complete the IO and get entries
13162 	 * into the abts lists.
13163 	 */
13164 	msleep(LPFC_XRI_EXCH_BUSY_WAIT_T1 * 5);
13165 
13166 	/* Wait for NVME pending IO to flush back to transport. */
13167 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
13168 		lpfc_nvme_wait_for_io_drain(phba);
13169 
13170 	ccnt = 0;
13171 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
13172 		qp = &phba->sli4_hba.hdwq[idx];
13173 		io_xri_cmpl = list_empty(&qp->lpfc_abts_io_buf_list);
13174 		if (!io_xri_cmpl) /* if list is NOT empty */
13175 			ccnt++;
13176 	}
13177 	if (ccnt)
13178 		io_xri_cmpl = 0;
13179 
13180 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13181 		nvmet_xri_cmpl =
13182 			list_empty(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
13183 	}
13184 
13185 	while (!els_xri_cmpl || !io_xri_cmpl || !nvmet_xri_cmpl) {
13186 		if (wait_time > LPFC_XRI_EXCH_BUSY_WAIT_TMO) {
13187 			if (!nvmet_xri_cmpl)
13188 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13189 						"6424 NVMET XRI exchange busy "
13190 						"wait time: %d seconds.\n",
13191 						wait_time/1000);
13192 			if (!io_xri_cmpl)
13193 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13194 						"6100 IO XRI exchange busy "
13195 						"wait time: %d seconds.\n",
13196 						wait_time/1000);
13197 			if (!els_xri_cmpl)
13198 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13199 						"2878 ELS XRI exchange busy "
13200 						"wait time: %d seconds.\n",
13201 						wait_time/1000);
13202 			msleep(LPFC_XRI_EXCH_BUSY_WAIT_T2);
13203 			wait_time += LPFC_XRI_EXCH_BUSY_WAIT_T2;
13204 		} else {
13205 			msleep(LPFC_XRI_EXCH_BUSY_WAIT_T1);
13206 			wait_time += LPFC_XRI_EXCH_BUSY_WAIT_T1;
13207 		}
13208 
13209 		ccnt = 0;
13210 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
13211 			qp = &phba->sli4_hba.hdwq[idx];
13212 			io_xri_cmpl = list_empty(
13213 			    &qp->lpfc_abts_io_buf_list);
13214 			if (!io_xri_cmpl) /* if list is NOT empty */
13215 				ccnt++;
13216 		}
13217 		if (ccnt)
13218 			io_xri_cmpl = 0;
13219 
13220 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13221 			nvmet_xri_cmpl = list_empty(
13222 				&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
13223 		}
13224 		els_xri_cmpl =
13225 			list_empty(&phba->sli4_hba.lpfc_abts_els_sgl_list);
13226 
13227 	}
13228 }
13229 
13230 /**
13231  * lpfc_sli4_hba_unset - Unset the fcoe hba
13232  * @phba: Pointer to HBA context object.
13233  *
13234  * This function is called in the SLI4 code path to reset the HBA's FCoE
13235  * function. The caller is not required to hold any lock. This routine
13236  * issues PCI function reset mailbox command to reset the FCoE function.
13237  * At the end of the function, it calls lpfc_hba_down_post function to
13238  * free any pending commands.
13239  **/
13240 static void
13241 lpfc_sli4_hba_unset(struct lpfc_hba *phba)
13242 {
13243 	int wait_cnt = 0;
13244 	LPFC_MBOXQ_t *mboxq;
13245 	struct pci_dev *pdev = phba->pcidev;
13246 
13247 	lpfc_stop_hba_timers(phba);
13248 	hrtimer_cancel(&phba->cmf_timer);
13249 
13250 	if (phba->pport)
13251 		phba->sli4_hba.intr_enable = 0;
13252 
13253 	/*
13254 	 * Gracefully wait out the potential current outstanding asynchronous
13255 	 * mailbox command.
13256 	 */
13257 
13258 	/* First, block any pending async mailbox command from posted */
13259 	spin_lock_irq(&phba->hbalock);
13260 	phba->sli.sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
13261 	spin_unlock_irq(&phba->hbalock);
13262 	/* Now, trying to wait it out if we can */
13263 	while (phba->sli.sli_flag & LPFC_SLI_MBOX_ACTIVE) {
13264 		msleep(10);
13265 		if (++wait_cnt > LPFC_ACTIVE_MBOX_WAIT_CNT)
13266 			break;
13267 	}
13268 	/* Forcefully release the outstanding mailbox command if timed out */
13269 	if (phba->sli.sli_flag & LPFC_SLI_MBOX_ACTIVE) {
13270 		spin_lock_irq(&phba->hbalock);
13271 		mboxq = phba->sli.mbox_active;
13272 		mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
13273 		__lpfc_mbox_cmpl_put(phba, mboxq);
13274 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
13275 		phba->sli.mbox_active = NULL;
13276 		spin_unlock_irq(&phba->hbalock);
13277 	}
13278 
13279 	/* Abort all iocbs associated with the hba */
13280 	lpfc_sli_hba_iocb_abort(phba);
13281 
13282 	/* Wait for completion of device XRI exchange busy */
13283 	lpfc_sli4_xri_exchange_busy_wait(phba);
13284 
13285 	/* per-phba callback de-registration for hotplug event */
13286 	if (phba->pport)
13287 		lpfc_cpuhp_remove(phba);
13288 
13289 	/* Disable PCI subsystem interrupt */
13290 	lpfc_sli4_disable_intr(phba);
13291 
13292 	/* Disable SR-IOV if enabled */
13293 	if (phba->cfg_sriov_nr_virtfn)
13294 		pci_disable_sriov(pdev);
13295 
13296 	/* Stop kthread signal shall trigger work_done one more time */
13297 	kthread_stop(phba->worker_thread);
13298 
13299 	/* Disable FW logging to host memory */
13300 	lpfc_ras_stop_fwlog(phba);
13301 
13302 	/* Unset the queues shared with the hardware then release all
13303 	 * allocated resources.
13304 	 */
13305 	lpfc_sli4_queue_unset(phba);
13306 	lpfc_sli4_queue_destroy(phba);
13307 
13308 	/* Reset SLI4 HBA FCoE function */
13309 	lpfc_pci_function_reset(phba);
13310 
13311 	/* Free RAS DMA memory */
13312 	if (phba->ras_fwlog.ras_enabled)
13313 		lpfc_sli4_ras_dma_free(phba);
13314 
13315 	/* Stop the SLI4 device port */
13316 	if (phba->pport)
13317 		phba->pport->work_port_events = 0;
13318 }
13319 
13320 static uint32_t
13321 lpfc_cgn_crc32(uint32_t crc, u8 byte)
13322 {
13323 	uint32_t msb = 0;
13324 	uint32_t bit;
13325 
13326 	for (bit = 0; bit < 8; bit++) {
13327 		msb = (crc >> 31) & 1;
13328 		crc <<= 1;
13329 
13330 		if (msb ^ (byte & 1)) {
13331 			crc ^= LPFC_CGN_CRC32_MAGIC_NUMBER;
13332 			crc |= 1;
13333 		}
13334 		byte >>= 1;
13335 	}
13336 	return crc;
13337 }
13338 
13339 static uint32_t
13340 lpfc_cgn_reverse_bits(uint32_t wd)
13341 {
13342 	uint32_t result = 0;
13343 	uint32_t i;
13344 
13345 	for (i = 0; i < 32; i++) {
13346 		result <<= 1;
13347 		result |= (1 & (wd >> i));
13348 	}
13349 	return result;
13350 }
13351 
13352 /*
13353  * The routine corresponds with the algorithm the HBA firmware
13354  * uses to validate the data integrity.
13355  */
13356 uint32_t
13357 lpfc_cgn_calc_crc32(void *ptr, uint32_t byteLen, uint32_t crc)
13358 {
13359 	uint32_t  i;
13360 	uint32_t result;
13361 	uint8_t  *data = (uint8_t *)ptr;
13362 
13363 	for (i = 0; i < byteLen; ++i)
13364 		crc = lpfc_cgn_crc32(crc, data[i]);
13365 
13366 	result = ~lpfc_cgn_reverse_bits(crc);
13367 	return result;
13368 }
13369 
13370 void
13371 lpfc_init_congestion_buf(struct lpfc_hba *phba)
13372 {
13373 	struct lpfc_cgn_info *cp;
13374 	struct timespec64 cmpl_time;
13375 	struct tm broken;
13376 	uint16_t size;
13377 	uint32_t crc;
13378 
13379 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
13380 			"6235 INIT Congestion Buffer %p\n", phba->cgn_i);
13381 
13382 	if (!phba->cgn_i)
13383 		return;
13384 	cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
13385 
13386 	atomic_set(&phba->cgn_fabric_warn_cnt, 0);
13387 	atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
13388 	atomic_set(&phba->cgn_sync_alarm_cnt, 0);
13389 	atomic_set(&phba->cgn_sync_warn_cnt, 0);
13390 
13391 	atomic64_set(&phba->cgn_acqe_stat.alarm, 0);
13392 	atomic64_set(&phba->cgn_acqe_stat.warn, 0);
13393 	atomic_set(&phba->cgn_driver_evt_cnt, 0);
13394 	atomic_set(&phba->cgn_latency_evt_cnt, 0);
13395 	atomic64_set(&phba->cgn_latency_evt, 0);
13396 	phba->cgn_evt_minute = 0;
13397 	phba->hba_flag &= ~HBA_CGN_DAY_WRAP;
13398 
13399 	memset(cp, 0xff, LPFC_CGN_DATA_SIZE);
13400 	cp->cgn_info_size = cpu_to_le16(LPFC_CGN_INFO_SZ);
13401 	cp->cgn_info_version = LPFC_CGN_INFO_V3;
13402 
13403 	/* cgn parameters */
13404 	cp->cgn_info_mode = phba->cgn_p.cgn_param_mode;
13405 	cp->cgn_info_level0 = phba->cgn_p.cgn_param_level0;
13406 	cp->cgn_info_level1 = phba->cgn_p.cgn_param_level1;
13407 	cp->cgn_info_level2 = phba->cgn_p.cgn_param_level2;
13408 
13409 	ktime_get_real_ts64(&cmpl_time);
13410 	time64_to_tm(cmpl_time.tv_sec, 0, &broken);
13411 
13412 	cp->cgn_info_month = broken.tm_mon + 1;
13413 	cp->cgn_info_day = broken.tm_mday;
13414 	cp->cgn_info_year = broken.tm_year - 100; /* relative to 2000 */
13415 	cp->cgn_info_hour = broken.tm_hour;
13416 	cp->cgn_info_minute = broken.tm_min;
13417 	cp->cgn_info_second = broken.tm_sec;
13418 
13419 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT | LOG_INIT,
13420 			"2643 CGNInfo Init: Start Time "
13421 			"%d/%d/%d %d:%d:%d\n",
13422 			cp->cgn_info_day, cp->cgn_info_month,
13423 			cp->cgn_info_year, cp->cgn_info_hour,
13424 			cp->cgn_info_minute, cp->cgn_info_second);
13425 
13426 	/* Fill in default LUN qdepth */
13427 	if (phba->pport) {
13428 		size = (uint16_t)(phba->pport->cfg_lun_queue_depth);
13429 		cp->cgn_lunq = cpu_to_le16(size);
13430 	}
13431 
13432 	/* last used Index initialized to 0xff already */
13433 
13434 	cp->cgn_warn_freq = cpu_to_le16(LPFC_FPIN_INIT_FREQ);
13435 	cp->cgn_alarm_freq = cpu_to_le16(LPFC_FPIN_INIT_FREQ);
13436 	crc = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ, LPFC_CGN_CRC32_SEED);
13437 	cp->cgn_info_crc = cpu_to_le32(crc);
13438 
13439 	phba->cgn_evt_timestamp = jiffies +
13440 		msecs_to_jiffies(LPFC_CGN_TIMER_TO_MIN);
13441 }
13442 
13443 void
13444 lpfc_init_congestion_stat(struct lpfc_hba *phba)
13445 {
13446 	struct lpfc_cgn_info *cp;
13447 	struct timespec64 cmpl_time;
13448 	struct tm broken;
13449 	uint32_t crc;
13450 
13451 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
13452 			"6236 INIT Congestion Stat %p\n", phba->cgn_i);
13453 
13454 	if (!phba->cgn_i)
13455 		return;
13456 
13457 	cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
13458 	memset(&cp->cgn_stat_npm, 0, LPFC_CGN_STAT_SIZE);
13459 
13460 	ktime_get_real_ts64(&cmpl_time);
13461 	time64_to_tm(cmpl_time.tv_sec, 0, &broken);
13462 
13463 	cp->cgn_stat_month = broken.tm_mon + 1;
13464 	cp->cgn_stat_day = broken.tm_mday;
13465 	cp->cgn_stat_year = broken.tm_year - 100; /* relative to 2000 */
13466 	cp->cgn_stat_hour = broken.tm_hour;
13467 	cp->cgn_stat_minute = broken.tm_min;
13468 
13469 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT | LOG_INIT,
13470 			"2647 CGNstat Init: Start Time "
13471 			"%d/%d/%d %d:%d\n",
13472 			cp->cgn_stat_day, cp->cgn_stat_month,
13473 			cp->cgn_stat_year, cp->cgn_stat_hour,
13474 			cp->cgn_stat_minute);
13475 
13476 	crc = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ, LPFC_CGN_CRC32_SEED);
13477 	cp->cgn_info_crc = cpu_to_le32(crc);
13478 }
13479 
13480 /**
13481  * __lpfc_reg_congestion_buf - register congestion info buffer with HBA
13482  * @phba: Pointer to hba context object.
13483  * @reg: flag to determine register or unregister.
13484  */
13485 static int
13486 __lpfc_reg_congestion_buf(struct lpfc_hba *phba, int reg)
13487 {
13488 	struct lpfc_mbx_reg_congestion_buf *reg_congestion_buf;
13489 	union  lpfc_sli4_cfg_shdr *shdr;
13490 	uint32_t shdr_status, shdr_add_status;
13491 	LPFC_MBOXQ_t *mboxq;
13492 	int length, rc;
13493 
13494 	if (!phba->cgn_i)
13495 		return -ENXIO;
13496 
13497 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
13498 	if (!mboxq) {
13499 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX,
13500 				"2641 REG_CONGESTION_BUF mbox allocation fail: "
13501 				"HBA state x%x reg %d\n",
13502 				phba->pport->port_state, reg);
13503 		return -ENOMEM;
13504 	}
13505 
13506 	length = (sizeof(struct lpfc_mbx_reg_congestion_buf) -
13507 		sizeof(struct lpfc_sli4_cfg_mhdr));
13508 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
13509 			 LPFC_MBOX_OPCODE_REG_CONGESTION_BUF, length,
13510 			 LPFC_SLI4_MBX_EMBED);
13511 	reg_congestion_buf = &mboxq->u.mqe.un.reg_congestion_buf;
13512 	bf_set(lpfc_mbx_reg_cgn_buf_type, reg_congestion_buf, 1);
13513 	if (reg > 0)
13514 		bf_set(lpfc_mbx_reg_cgn_buf_cnt, reg_congestion_buf, 1);
13515 	else
13516 		bf_set(lpfc_mbx_reg_cgn_buf_cnt, reg_congestion_buf, 0);
13517 	reg_congestion_buf->length = sizeof(struct lpfc_cgn_info);
13518 	reg_congestion_buf->addr_lo =
13519 		putPaddrLow(phba->cgn_i->phys);
13520 	reg_congestion_buf->addr_hi =
13521 		putPaddrHigh(phba->cgn_i->phys);
13522 
13523 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
13524 	shdr = (union lpfc_sli4_cfg_shdr *)
13525 		&mboxq->u.mqe.un.sli4_config.header.cfg_shdr;
13526 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13527 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
13528 				 &shdr->response);
13529 	mempool_free(mboxq, phba->mbox_mem_pool);
13530 	if (shdr_status || shdr_add_status || rc) {
13531 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13532 				"2642 REG_CONGESTION_BUF mailbox "
13533 				"failed with status x%x add_status x%x,"
13534 				" mbx status x%x reg %d\n",
13535 				shdr_status, shdr_add_status, rc, reg);
13536 		return -ENXIO;
13537 	}
13538 	return 0;
13539 }
13540 
13541 int
13542 lpfc_unreg_congestion_buf(struct lpfc_hba *phba)
13543 {
13544 	lpfc_cmf_stop(phba);
13545 	return __lpfc_reg_congestion_buf(phba, 0);
13546 }
13547 
13548 int
13549 lpfc_reg_congestion_buf(struct lpfc_hba *phba)
13550 {
13551 	return __lpfc_reg_congestion_buf(phba, 1);
13552 }
13553 
13554 /**
13555  * lpfc_get_sli4_parameters - Get the SLI4 Config PARAMETERS.
13556  * @phba: Pointer to HBA context object.
13557  * @mboxq: Pointer to the mailboxq memory for the mailbox command response.
13558  *
13559  * This function is called in the SLI4 code path to read the port's
13560  * sli4 capabilities.
13561  *
13562  * This function may be be called from any context that can block-wait
13563  * for the completion.  The expectation is that this routine is called
13564  * typically from probe_one or from the online routine.
13565  **/
13566 int
13567 lpfc_get_sli4_parameters(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
13568 {
13569 	int rc;
13570 	struct lpfc_mqe *mqe = &mboxq->u.mqe;
13571 	struct lpfc_pc_sli4_params *sli4_params;
13572 	uint32_t mbox_tmo;
13573 	int length;
13574 	bool exp_wqcq_pages = true;
13575 	struct lpfc_sli4_parameters *mbx_sli4_parameters;
13576 
13577 	/*
13578 	 * By default, the driver assumes the SLI4 port requires RPI
13579 	 * header postings.  The SLI4_PARAM response will correct this
13580 	 * assumption.
13581 	 */
13582 	phba->sli4_hba.rpi_hdrs_in_use = 1;
13583 
13584 	/* Read the port's SLI4 Config Parameters */
13585 	length = (sizeof(struct lpfc_mbx_get_sli4_parameters) -
13586 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13587 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
13588 			 LPFC_MBOX_OPCODE_GET_SLI4_PARAMETERS,
13589 			 length, LPFC_SLI4_MBX_EMBED);
13590 	if (!phba->sli4_hba.intr_enable)
13591 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
13592 	else {
13593 		mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
13594 		rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
13595 	}
13596 	if (unlikely(rc))
13597 		return rc;
13598 	sli4_params = &phba->sli4_hba.pc_sli4_params;
13599 	mbx_sli4_parameters = &mqe->un.get_sli4_parameters.sli4_parameters;
13600 	sli4_params->if_type = bf_get(cfg_if_type, mbx_sli4_parameters);
13601 	sli4_params->sli_rev = bf_get(cfg_sli_rev, mbx_sli4_parameters);
13602 	sli4_params->sli_family = bf_get(cfg_sli_family, mbx_sli4_parameters);
13603 	sli4_params->featurelevel_1 = bf_get(cfg_sli_hint_1,
13604 					     mbx_sli4_parameters);
13605 	sli4_params->featurelevel_2 = bf_get(cfg_sli_hint_2,
13606 					     mbx_sli4_parameters);
13607 	if (bf_get(cfg_phwq, mbx_sli4_parameters))
13608 		phba->sli3_options |= LPFC_SLI4_PHWQ_ENABLED;
13609 	else
13610 		phba->sli3_options &= ~LPFC_SLI4_PHWQ_ENABLED;
13611 	sli4_params->sge_supp_len = mbx_sli4_parameters->sge_supp_len;
13612 	sli4_params->loopbk_scope = bf_get(cfg_loopbk_scope,
13613 					   mbx_sli4_parameters);
13614 	sli4_params->oas_supported = bf_get(cfg_oas, mbx_sli4_parameters);
13615 	sli4_params->cqv = bf_get(cfg_cqv, mbx_sli4_parameters);
13616 	sli4_params->mqv = bf_get(cfg_mqv, mbx_sli4_parameters);
13617 	sli4_params->wqv = bf_get(cfg_wqv, mbx_sli4_parameters);
13618 	sli4_params->rqv = bf_get(cfg_rqv, mbx_sli4_parameters);
13619 	sli4_params->eqav = bf_get(cfg_eqav, mbx_sli4_parameters);
13620 	sli4_params->cqav = bf_get(cfg_cqav, mbx_sli4_parameters);
13621 	sli4_params->wqsize = bf_get(cfg_wqsize, mbx_sli4_parameters);
13622 	sli4_params->bv1s = bf_get(cfg_bv1s, mbx_sli4_parameters);
13623 	sli4_params->pls = bf_get(cfg_pvl, mbx_sli4_parameters);
13624 	sli4_params->sgl_pages_max = bf_get(cfg_sgl_page_cnt,
13625 					    mbx_sli4_parameters);
13626 	sli4_params->wqpcnt = bf_get(cfg_wqpcnt, mbx_sli4_parameters);
13627 	sli4_params->sgl_pp_align = bf_get(cfg_sgl_pp_align,
13628 					   mbx_sli4_parameters);
13629 	phba->sli4_hba.extents_in_use = bf_get(cfg_ext, mbx_sli4_parameters);
13630 	phba->sli4_hba.rpi_hdrs_in_use = bf_get(cfg_hdrr, mbx_sli4_parameters);
13631 
13632 	/* Check for Extended Pre-Registered SGL support */
13633 	phba->cfg_xpsgl = bf_get(cfg_xpsgl, mbx_sli4_parameters);
13634 
13635 	/* Check for firmware nvme support */
13636 	rc = (bf_get(cfg_nvme, mbx_sli4_parameters) &&
13637 		     bf_get(cfg_xib, mbx_sli4_parameters));
13638 
13639 	if (rc) {
13640 		/* Save this to indicate the Firmware supports NVME */
13641 		sli4_params->nvme = 1;
13642 
13643 		/* Firmware NVME support, check driver FC4 NVME support */
13644 		if (phba->cfg_enable_fc4_type == LPFC_ENABLE_FCP) {
13645 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_NVME,
13646 					"6133 Disabling NVME support: "
13647 					"FC4 type not supported: x%x\n",
13648 					phba->cfg_enable_fc4_type);
13649 			goto fcponly;
13650 		}
13651 	} else {
13652 		/* No firmware NVME support, check driver FC4 NVME support */
13653 		sli4_params->nvme = 0;
13654 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13655 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_NVME,
13656 					"6101 Disabling NVME support: Not "
13657 					"supported by firmware (%d %d) x%x\n",
13658 					bf_get(cfg_nvme, mbx_sli4_parameters),
13659 					bf_get(cfg_xib, mbx_sli4_parameters),
13660 					phba->cfg_enable_fc4_type);
13661 fcponly:
13662 			phba->nvmet_support = 0;
13663 			phba->cfg_nvmet_mrq = 0;
13664 			phba->cfg_nvme_seg_cnt = 0;
13665 
13666 			/* If no FC4 type support, move to just SCSI support */
13667 			if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP))
13668 				return -ENODEV;
13669 			phba->cfg_enable_fc4_type = LPFC_ENABLE_FCP;
13670 		}
13671 	}
13672 
13673 	/* If the NVME FC4 type is enabled, scale the sg_seg_cnt to
13674 	 * accommodate 512K and 1M IOs in a single nvme buf.
13675 	 */
13676 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
13677 		phba->cfg_sg_seg_cnt = LPFC_MAX_NVME_SEG_CNT;
13678 
13679 	/* Enable embedded Payload BDE if support is indicated */
13680 	if (bf_get(cfg_pbde, mbx_sli4_parameters))
13681 		phba->cfg_enable_pbde = 1;
13682 	else
13683 		phba->cfg_enable_pbde = 0;
13684 
13685 	/*
13686 	 * To support Suppress Response feature we must satisfy 3 conditions.
13687 	 * lpfc_suppress_rsp module parameter must be set (default).
13688 	 * In SLI4-Parameters Descriptor:
13689 	 * Extended Inline Buffers (XIB) must be supported.
13690 	 * Suppress Response IU Not Supported (SRIUNS) must NOT be supported
13691 	 * (double negative).
13692 	 */
13693 	if (phba->cfg_suppress_rsp && bf_get(cfg_xib, mbx_sli4_parameters) &&
13694 	    !(bf_get(cfg_nosr, mbx_sli4_parameters)))
13695 		phba->sli.sli_flag |= LPFC_SLI_SUPPRESS_RSP;
13696 	else
13697 		phba->cfg_suppress_rsp = 0;
13698 
13699 	if (bf_get(cfg_eqdr, mbx_sli4_parameters))
13700 		phba->sli.sli_flag |= LPFC_SLI_USE_EQDR;
13701 
13702 	/* Make sure that sge_supp_len can be handled by the driver */
13703 	if (sli4_params->sge_supp_len > LPFC_MAX_SGE_SIZE)
13704 		sli4_params->sge_supp_len = LPFC_MAX_SGE_SIZE;
13705 
13706 	/*
13707 	 * Check whether the adapter supports an embedded copy of the
13708 	 * FCP CMD IU within the WQE for FCP_Ixxx commands. In order
13709 	 * to use this option, 128-byte WQEs must be used.
13710 	 */
13711 	if (bf_get(cfg_ext_embed_cb, mbx_sli4_parameters))
13712 		phba->fcp_embed_io = 1;
13713 	else
13714 		phba->fcp_embed_io = 0;
13715 
13716 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_NVME,
13717 			"6422 XIB %d PBDE %d: FCP %d NVME %d %d %d\n",
13718 			bf_get(cfg_xib, mbx_sli4_parameters),
13719 			phba->cfg_enable_pbde,
13720 			phba->fcp_embed_io, sli4_params->nvme,
13721 			phba->cfg_nvme_embed_cmd, phba->cfg_suppress_rsp);
13722 
13723 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
13724 	    LPFC_SLI_INTF_IF_TYPE_2) &&
13725 	    (bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf) ==
13726 		 LPFC_SLI_INTF_FAMILY_LNCR_A0))
13727 		exp_wqcq_pages = false;
13728 
13729 	if ((bf_get(cfg_cqpsize, mbx_sli4_parameters) & LPFC_CQ_16K_PAGE_SZ) &&
13730 	    (bf_get(cfg_wqpsize, mbx_sli4_parameters) & LPFC_WQ_16K_PAGE_SZ) &&
13731 	    exp_wqcq_pages &&
13732 	    (sli4_params->wqsize & LPFC_WQ_SZ128_SUPPORT))
13733 		phba->enab_exp_wqcq_pages = 1;
13734 	else
13735 		phba->enab_exp_wqcq_pages = 0;
13736 	/*
13737 	 * Check if the SLI port supports MDS Diagnostics
13738 	 */
13739 	if (bf_get(cfg_mds_diags, mbx_sli4_parameters))
13740 		phba->mds_diags_support = 1;
13741 	else
13742 		phba->mds_diags_support = 0;
13743 
13744 	/*
13745 	 * Check if the SLI port supports NSLER
13746 	 */
13747 	if (bf_get(cfg_nsler, mbx_sli4_parameters))
13748 		phba->nsler = 1;
13749 	else
13750 		phba->nsler = 0;
13751 
13752 	return 0;
13753 }
13754 
13755 /**
13756  * lpfc_pci_probe_one_s3 - PCI probe func to reg SLI-3 device to PCI subsystem.
13757  * @pdev: pointer to PCI device
13758  * @pid: pointer to PCI device identifier
13759  *
13760  * This routine is to be called to attach a device with SLI-3 interface spec
13761  * to the PCI subsystem. When an Emulex HBA with SLI-3 interface spec is
13762  * presented on PCI bus, the kernel PCI subsystem looks at PCI device-specific
13763  * information of the device and driver to see if the driver state that it can
13764  * support this kind of device. If the match is successful, the driver core
13765  * invokes this routine. If this routine determines it can claim the HBA, it
13766  * does all the initialization that it needs to do to handle the HBA properly.
13767  *
13768  * Return code
13769  * 	0 - driver can claim the device
13770  * 	negative value - driver can not claim the device
13771  **/
13772 static int
13773 lpfc_pci_probe_one_s3(struct pci_dev *pdev, const struct pci_device_id *pid)
13774 {
13775 	struct lpfc_hba   *phba;
13776 	struct lpfc_vport *vport = NULL;
13777 	struct Scsi_Host  *shost = NULL;
13778 	int error;
13779 	uint32_t cfg_mode, intr_mode;
13780 
13781 	/* Allocate memory for HBA structure */
13782 	phba = lpfc_hba_alloc(pdev);
13783 	if (!phba)
13784 		return -ENOMEM;
13785 
13786 	/* Perform generic PCI device enabling operation */
13787 	error = lpfc_enable_pci_dev(phba);
13788 	if (error)
13789 		goto out_free_phba;
13790 
13791 	/* Set up SLI API function jump table for PCI-device group-0 HBAs */
13792 	error = lpfc_api_table_setup(phba, LPFC_PCI_DEV_LP);
13793 	if (error)
13794 		goto out_disable_pci_dev;
13795 
13796 	/* Set up SLI-3 specific device PCI memory space */
13797 	error = lpfc_sli_pci_mem_setup(phba);
13798 	if (error) {
13799 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13800 				"1402 Failed to set up pci memory space.\n");
13801 		goto out_disable_pci_dev;
13802 	}
13803 
13804 	/* Set up SLI-3 specific device driver resources */
13805 	error = lpfc_sli_driver_resource_setup(phba);
13806 	if (error) {
13807 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13808 				"1404 Failed to set up driver resource.\n");
13809 		goto out_unset_pci_mem_s3;
13810 	}
13811 
13812 	/* Initialize and populate the iocb list per host */
13813 
13814 	error = lpfc_init_iocb_list(phba, LPFC_IOCB_LIST_CNT);
13815 	if (error) {
13816 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13817 				"1405 Failed to initialize iocb list.\n");
13818 		goto out_unset_driver_resource_s3;
13819 	}
13820 
13821 	/* Set up common device driver resources */
13822 	error = lpfc_setup_driver_resource_phase2(phba);
13823 	if (error) {
13824 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13825 				"1406 Failed to set up driver resource.\n");
13826 		goto out_free_iocb_list;
13827 	}
13828 
13829 	/* Get the default values for Model Name and Description */
13830 	lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
13831 
13832 	/* Create SCSI host to the physical port */
13833 	error = lpfc_create_shost(phba);
13834 	if (error) {
13835 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13836 				"1407 Failed to create scsi host.\n");
13837 		goto out_unset_driver_resource;
13838 	}
13839 
13840 	/* Configure sysfs attributes */
13841 	vport = phba->pport;
13842 	error = lpfc_alloc_sysfs_attr(vport);
13843 	if (error) {
13844 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13845 				"1476 Failed to allocate sysfs attr\n");
13846 		goto out_destroy_shost;
13847 	}
13848 
13849 	shost = lpfc_shost_from_vport(vport); /* save shost for error cleanup */
13850 	/* Now, trying to enable interrupt and bring up the device */
13851 	cfg_mode = phba->cfg_use_msi;
13852 	while (true) {
13853 		/* Put device to a known state before enabling interrupt */
13854 		lpfc_stop_port(phba);
13855 		/* Configure and enable interrupt */
13856 		intr_mode = lpfc_sli_enable_intr(phba, cfg_mode);
13857 		if (intr_mode == LPFC_INTR_ERROR) {
13858 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13859 					"0431 Failed to enable interrupt.\n");
13860 			error = -ENODEV;
13861 			goto out_free_sysfs_attr;
13862 		}
13863 		/* SLI-3 HBA setup */
13864 		if (lpfc_sli_hba_setup(phba)) {
13865 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13866 					"1477 Failed to set up hba\n");
13867 			error = -ENODEV;
13868 			goto out_remove_device;
13869 		}
13870 
13871 		/* Wait 50ms for the interrupts of previous mailbox commands */
13872 		msleep(50);
13873 		/* Check active interrupts on message signaled interrupts */
13874 		if (intr_mode == 0 ||
13875 		    phba->sli.slistat.sli_intr > LPFC_MSIX_VECTORS) {
13876 			/* Log the current active interrupt mode */
13877 			phba->intr_mode = intr_mode;
13878 			lpfc_log_intr_mode(phba, intr_mode);
13879 			break;
13880 		} else {
13881 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13882 					"0447 Configure interrupt mode (%d) "
13883 					"failed active interrupt test.\n",
13884 					intr_mode);
13885 			/* Disable the current interrupt mode */
13886 			lpfc_sli_disable_intr(phba);
13887 			/* Try next level of interrupt mode */
13888 			cfg_mode = --intr_mode;
13889 		}
13890 	}
13891 
13892 	/* Perform post initialization setup */
13893 	lpfc_post_init_setup(phba);
13894 
13895 	/* Check if there are static vports to be created. */
13896 	lpfc_create_static_vport(phba);
13897 
13898 	return 0;
13899 
13900 out_remove_device:
13901 	lpfc_unset_hba(phba);
13902 out_free_sysfs_attr:
13903 	lpfc_free_sysfs_attr(vport);
13904 out_destroy_shost:
13905 	lpfc_destroy_shost(phba);
13906 out_unset_driver_resource:
13907 	lpfc_unset_driver_resource_phase2(phba);
13908 out_free_iocb_list:
13909 	lpfc_free_iocb_list(phba);
13910 out_unset_driver_resource_s3:
13911 	lpfc_sli_driver_resource_unset(phba);
13912 out_unset_pci_mem_s3:
13913 	lpfc_sli_pci_mem_unset(phba);
13914 out_disable_pci_dev:
13915 	lpfc_disable_pci_dev(phba);
13916 	if (shost)
13917 		scsi_host_put(shost);
13918 out_free_phba:
13919 	lpfc_hba_free(phba);
13920 	return error;
13921 }
13922 
13923 /**
13924  * lpfc_pci_remove_one_s3 - PCI func to unreg SLI-3 device from PCI subsystem.
13925  * @pdev: pointer to PCI device
13926  *
13927  * This routine is to be called to disattach a device with SLI-3 interface
13928  * spec from PCI subsystem. When an Emulex HBA with SLI-3 interface spec is
13929  * removed from PCI bus, it performs all the necessary cleanup for the HBA
13930  * device to be removed from the PCI subsystem properly.
13931  **/
13932 static void
13933 lpfc_pci_remove_one_s3(struct pci_dev *pdev)
13934 {
13935 	struct Scsi_Host  *shost = pci_get_drvdata(pdev);
13936 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
13937 	struct lpfc_vport **vports;
13938 	struct lpfc_hba   *phba = vport->phba;
13939 	int i;
13940 
13941 	spin_lock_irq(&phba->hbalock);
13942 	vport->load_flag |= FC_UNLOADING;
13943 	spin_unlock_irq(&phba->hbalock);
13944 
13945 	lpfc_free_sysfs_attr(vport);
13946 
13947 	/* Release all the vports against this physical port */
13948 	vports = lpfc_create_vport_work_array(phba);
13949 	if (vports != NULL)
13950 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
13951 			if (vports[i]->port_type == LPFC_PHYSICAL_PORT)
13952 				continue;
13953 			fc_vport_terminate(vports[i]->fc_vport);
13954 		}
13955 	lpfc_destroy_vport_work_array(phba, vports);
13956 
13957 	/* Remove FC host with the physical port */
13958 	fc_remove_host(shost);
13959 	scsi_remove_host(shost);
13960 
13961 	/* Clean up all nodes, mailboxes and IOs. */
13962 	lpfc_cleanup(vport);
13963 
13964 	/*
13965 	 * Bring down the SLI Layer. This step disable all interrupts,
13966 	 * clears the rings, discards all mailbox commands, and resets
13967 	 * the HBA.
13968 	 */
13969 
13970 	/* HBA interrupt will be disabled after this call */
13971 	lpfc_sli_hba_down(phba);
13972 	/* Stop kthread signal shall trigger work_done one more time */
13973 	kthread_stop(phba->worker_thread);
13974 	/* Final cleanup of txcmplq and reset the HBA */
13975 	lpfc_sli_brdrestart(phba);
13976 
13977 	kfree(phba->vpi_bmask);
13978 	kfree(phba->vpi_ids);
13979 
13980 	lpfc_stop_hba_timers(phba);
13981 	spin_lock_irq(&phba->port_list_lock);
13982 	list_del_init(&vport->listentry);
13983 	spin_unlock_irq(&phba->port_list_lock);
13984 
13985 	lpfc_debugfs_terminate(vport);
13986 
13987 	/* Disable SR-IOV if enabled */
13988 	if (phba->cfg_sriov_nr_virtfn)
13989 		pci_disable_sriov(pdev);
13990 
13991 	/* Disable interrupt */
13992 	lpfc_sli_disable_intr(phba);
13993 
13994 	scsi_host_put(shost);
13995 
13996 	/*
13997 	 * Call scsi_free before mem_free since scsi bufs are released to their
13998 	 * corresponding pools here.
13999 	 */
14000 	lpfc_scsi_free(phba);
14001 	lpfc_free_iocb_list(phba);
14002 
14003 	lpfc_mem_free_all(phba);
14004 
14005 	dma_free_coherent(&pdev->dev, lpfc_sli_hbq_size(),
14006 			  phba->hbqslimp.virt, phba->hbqslimp.phys);
14007 
14008 	/* Free resources associated with SLI2 interface */
14009 	dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
14010 			  phba->slim2p.virt, phba->slim2p.phys);
14011 
14012 	/* unmap adapter SLIM and Control Registers */
14013 	iounmap(phba->ctrl_regs_memmap_p);
14014 	iounmap(phba->slim_memmap_p);
14015 
14016 	lpfc_hba_free(phba);
14017 
14018 	pci_release_mem_regions(pdev);
14019 	pci_disable_device(pdev);
14020 }
14021 
14022 /**
14023  * lpfc_pci_suspend_one_s3 - PCI func to suspend SLI-3 device for power mgmnt
14024  * @dev_d: pointer to device
14025  *
14026  * This routine is to be called from the kernel's PCI subsystem to support
14027  * system Power Management (PM) to device with SLI-3 interface spec. When
14028  * PM invokes this method, it quiesces the device by stopping the driver's
14029  * worker thread for the device, turning off device's interrupt and DMA,
14030  * and bring the device offline. Note that as the driver implements the
14031  * minimum PM requirements to a power-aware driver's PM support for the
14032  * suspend/resume -- all the possible PM messages (SUSPEND, HIBERNATE, FREEZE)
14033  * to the suspend() method call will be treated as SUSPEND and the driver will
14034  * fully reinitialize its device during resume() method call, the driver will
14035  * set device to PCI_D3hot state in PCI config space instead of setting it
14036  * according to the @msg provided by the PM.
14037  *
14038  * Return code
14039  * 	0 - driver suspended the device
14040  * 	Error otherwise
14041  **/
14042 static int __maybe_unused
14043 lpfc_pci_suspend_one_s3(struct device *dev_d)
14044 {
14045 	struct Scsi_Host *shost = dev_get_drvdata(dev_d);
14046 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14047 
14048 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
14049 			"0473 PCI device Power Management suspend.\n");
14050 
14051 	/* Bring down the device */
14052 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
14053 	lpfc_offline(phba);
14054 	kthread_stop(phba->worker_thread);
14055 
14056 	/* Disable interrupt from device */
14057 	lpfc_sli_disable_intr(phba);
14058 
14059 	return 0;
14060 }
14061 
14062 /**
14063  * lpfc_pci_resume_one_s3 - PCI func to resume SLI-3 device for power mgmnt
14064  * @dev_d: pointer to device
14065  *
14066  * This routine is to be called from the kernel's PCI subsystem to support
14067  * system Power Management (PM) to device with SLI-3 interface spec. When PM
14068  * invokes this method, it restores the device's PCI config space state and
14069  * fully reinitializes the device and brings it online. Note that as the
14070  * driver implements the minimum PM requirements to a power-aware driver's
14071  * PM for suspend/resume -- all the possible PM messages (SUSPEND, HIBERNATE,
14072  * FREEZE) to the suspend() method call will be treated as SUSPEND and the
14073  * driver will fully reinitialize its device during resume() method call,
14074  * the device will be set to PCI_D0 directly in PCI config space before
14075  * restoring the state.
14076  *
14077  * Return code
14078  * 	0 - driver suspended the device
14079  * 	Error otherwise
14080  **/
14081 static int __maybe_unused
14082 lpfc_pci_resume_one_s3(struct device *dev_d)
14083 {
14084 	struct Scsi_Host *shost = dev_get_drvdata(dev_d);
14085 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14086 	uint32_t intr_mode;
14087 	int error;
14088 
14089 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
14090 			"0452 PCI device Power Management resume.\n");
14091 
14092 	/* Startup the kernel thread for this host adapter. */
14093 	phba->worker_thread = kthread_run(lpfc_do_work, phba,
14094 					"lpfc_worker_%d", phba->brd_no);
14095 	if (IS_ERR(phba->worker_thread)) {
14096 		error = PTR_ERR(phba->worker_thread);
14097 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14098 				"0434 PM resume failed to start worker "
14099 				"thread: error=x%x.\n", error);
14100 		return error;
14101 	}
14102 
14103 	/* Init cpu_map array */
14104 	lpfc_cpu_map_array_init(phba);
14105 	/* Init hba_eq_hdl array */
14106 	lpfc_hba_eq_hdl_array_init(phba);
14107 	/* Configure and enable interrupt */
14108 	intr_mode = lpfc_sli_enable_intr(phba, phba->intr_mode);
14109 	if (intr_mode == LPFC_INTR_ERROR) {
14110 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14111 				"0430 PM resume Failed to enable interrupt\n");
14112 		return -EIO;
14113 	} else
14114 		phba->intr_mode = intr_mode;
14115 
14116 	/* Restart HBA and bring it online */
14117 	lpfc_sli_brdrestart(phba);
14118 	lpfc_online(phba);
14119 
14120 	/* Log the current active interrupt mode */
14121 	lpfc_log_intr_mode(phba, phba->intr_mode);
14122 
14123 	return 0;
14124 }
14125 
14126 /**
14127  * lpfc_sli_prep_dev_for_recover - Prepare SLI3 device for pci slot recover
14128  * @phba: pointer to lpfc hba data structure.
14129  *
14130  * This routine is called to prepare the SLI3 device for PCI slot recover. It
14131  * aborts all the outstanding SCSI I/Os to the pci device.
14132  **/
14133 static void
14134 lpfc_sli_prep_dev_for_recover(struct lpfc_hba *phba)
14135 {
14136 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14137 			"2723 PCI channel I/O abort preparing for recovery\n");
14138 
14139 	/*
14140 	 * There may be errored I/Os through HBA, abort all I/Os on txcmplq
14141 	 * and let the SCSI mid-layer to retry them to recover.
14142 	 */
14143 	lpfc_sli_abort_fcp_rings(phba);
14144 }
14145 
14146 /**
14147  * lpfc_sli_prep_dev_for_reset - Prepare SLI3 device for pci slot reset
14148  * @phba: pointer to lpfc hba data structure.
14149  *
14150  * This routine is called to prepare the SLI3 device for PCI slot reset. It
14151  * disables the device interrupt and pci device, and aborts the internal FCP
14152  * pending I/Os.
14153  **/
14154 static void
14155 lpfc_sli_prep_dev_for_reset(struct lpfc_hba *phba)
14156 {
14157 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14158 			"2710 PCI channel disable preparing for reset\n");
14159 
14160 	/* Block any management I/Os to the device */
14161 	lpfc_block_mgmt_io(phba, LPFC_MBX_WAIT);
14162 
14163 	/* Block all SCSI devices' I/Os on the host */
14164 	lpfc_scsi_dev_block(phba);
14165 
14166 	/* Flush all driver's outstanding SCSI I/Os as we are to reset */
14167 	lpfc_sli_flush_io_rings(phba);
14168 
14169 	/* stop all timers */
14170 	lpfc_stop_hba_timers(phba);
14171 
14172 	/* Disable interrupt and pci device */
14173 	lpfc_sli_disable_intr(phba);
14174 	pci_disable_device(phba->pcidev);
14175 }
14176 
14177 /**
14178  * lpfc_sli_prep_dev_for_perm_failure - Prepare SLI3 dev for pci slot disable
14179  * @phba: pointer to lpfc hba data structure.
14180  *
14181  * This routine is called to prepare the SLI3 device for PCI slot permanently
14182  * disabling. It blocks the SCSI transport layer traffic and flushes the FCP
14183  * pending I/Os.
14184  **/
14185 static void
14186 lpfc_sli_prep_dev_for_perm_failure(struct lpfc_hba *phba)
14187 {
14188 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14189 			"2711 PCI channel permanent disable for failure\n");
14190 	/* Block all SCSI devices' I/Os on the host */
14191 	lpfc_scsi_dev_block(phba);
14192 
14193 	/* stop all timers */
14194 	lpfc_stop_hba_timers(phba);
14195 
14196 	/* Clean up all driver's outstanding SCSI I/Os */
14197 	lpfc_sli_flush_io_rings(phba);
14198 }
14199 
14200 /**
14201  * lpfc_io_error_detected_s3 - Method for handling SLI-3 device PCI I/O error
14202  * @pdev: pointer to PCI device.
14203  * @state: the current PCI connection state.
14204  *
14205  * This routine is called from the PCI subsystem for I/O error handling to
14206  * device with SLI-3 interface spec. This function is called by the PCI
14207  * subsystem after a PCI bus error affecting this device has been detected.
14208  * When this function is invoked, it will need to stop all the I/Os and
14209  * interrupt(s) to the device. Once that is done, it will return
14210  * PCI_ERS_RESULT_NEED_RESET for the PCI subsystem to perform proper recovery
14211  * as desired.
14212  *
14213  * Return codes
14214  * 	PCI_ERS_RESULT_CAN_RECOVER - can be recovered with reset_link
14215  * 	PCI_ERS_RESULT_NEED_RESET - need to reset before recovery
14216  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
14217  **/
14218 static pci_ers_result_t
14219 lpfc_io_error_detected_s3(struct pci_dev *pdev, pci_channel_state_t state)
14220 {
14221 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
14222 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14223 
14224 	switch (state) {
14225 	case pci_channel_io_normal:
14226 		/* Non-fatal error, prepare for recovery */
14227 		lpfc_sli_prep_dev_for_recover(phba);
14228 		return PCI_ERS_RESULT_CAN_RECOVER;
14229 	case pci_channel_io_frozen:
14230 		/* Fatal error, prepare for slot reset */
14231 		lpfc_sli_prep_dev_for_reset(phba);
14232 		return PCI_ERS_RESULT_NEED_RESET;
14233 	case pci_channel_io_perm_failure:
14234 		/* Permanent failure, prepare for device down */
14235 		lpfc_sli_prep_dev_for_perm_failure(phba);
14236 		return PCI_ERS_RESULT_DISCONNECT;
14237 	default:
14238 		/* Unknown state, prepare and request slot reset */
14239 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14240 				"0472 Unknown PCI error state: x%x\n", state);
14241 		lpfc_sli_prep_dev_for_reset(phba);
14242 		return PCI_ERS_RESULT_NEED_RESET;
14243 	}
14244 }
14245 
14246 /**
14247  * lpfc_io_slot_reset_s3 - Method for restarting PCI SLI-3 device from scratch.
14248  * @pdev: pointer to PCI device.
14249  *
14250  * This routine is called from the PCI subsystem for error handling to
14251  * device with SLI-3 interface spec. This is called after PCI bus has been
14252  * reset to restart the PCI card from scratch, as if from a cold-boot.
14253  * During the PCI subsystem error recovery, after driver returns
14254  * PCI_ERS_RESULT_NEED_RESET, the PCI subsystem will perform proper error
14255  * recovery and then call this routine before calling the .resume method
14256  * to recover the device. This function will initialize the HBA device,
14257  * enable the interrupt, but it will just put the HBA to offline state
14258  * without passing any I/O traffic.
14259  *
14260  * Return codes
14261  * 	PCI_ERS_RESULT_RECOVERED - the device has been recovered
14262  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
14263  */
14264 static pci_ers_result_t
14265 lpfc_io_slot_reset_s3(struct pci_dev *pdev)
14266 {
14267 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
14268 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14269 	struct lpfc_sli *psli = &phba->sli;
14270 	uint32_t intr_mode;
14271 
14272 	dev_printk(KERN_INFO, &pdev->dev, "recovering from a slot reset.\n");
14273 	if (pci_enable_device_mem(pdev)) {
14274 		printk(KERN_ERR "lpfc: Cannot re-enable "
14275 			"PCI device after reset.\n");
14276 		return PCI_ERS_RESULT_DISCONNECT;
14277 	}
14278 
14279 	pci_restore_state(pdev);
14280 
14281 	/*
14282 	 * As the new kernel behavior of pci_restore_state() API call clears
14283 	 * device saved_state flag, need to save the restored state again.
14284 	 */
14285 	pci_save_state(pdev);
14286 
14287 	if (pdev->is_busmaster)
14288 		pci_set_master(pdev);
14289 
14290 	spin_lock_irq(&phba->hbalock);
14291 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
14292 	spin_unlock_irq(&phba->hbalock);
14293 
14294 	/* Configure and enable interrupt */
14295 	intr_mode = lpfc_sli_enable_intr(phba, phba->intr_mode);
14296 	if (intr_mode == LPFC_INTR_ERROR) {
14297 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14298 				"0427 Cannot re-enable interrupt after "
14299 				"slot reset.\n");
14300 		return PCI_ERS_RESULT_DISCONNECT;
14301 	} else
14302 		phba->intr_mode = intr_mode;
14303 
14304 	/* Take device offline, it will perform cleanup */
14305 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
14306 	lpfc_offline(phba);
14307 	lpfc_sli_brdrestart(phba);
14308 
14309 	/* Log the current active interrupt mode */
14310 	lpfc_log_intr_mode(phba, phba->intr_mode);
14311 
14312 	return PCI_ERS_RESULT_RECOVERED;
14313 }
14314 
14315 /**
14316  * lpfc_io_resume_s3 - Method for resuming PCI I/O operation on SLI-3 device.
14317  * @pdev: pointer to PCI device
14318  *
14319  * This routine is called from the PCI subsystem for error handling to device
14320  * with SLI-3 interface spec. It is called when kernel error recovery tells
14321  * the lpfc driver that it is ok to resume normal PCI operation after PCI bus
14322  * error recovery. After this call, traffic can start to flow from this device
14323  * again.
14324  */
14325 static void
14326 lpfc_io_resume_s3(struct pci_dev *pdev)
14327 {
14328 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
14329 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14330 
14331 	/* Bring device online, it will be no-op for non-fatal error resume */
14332 	lpfc_online(phba);
14333 }
14334 
14335 /**
14336  * lpfc_sli4_get_els_iocb_cnt - Calculate the # of ELS IOCBs to reserve
14337  * @phba: pointer to lpfc hba data structure.
14338  *
14339  * returns the number of ELS/CT IOCBs to reserve
14340  **/
14341 int
14342 lpfc_sli4_get_els_iocb_cnt(struct lpfc_hba *phba)
14343 {
14344 	int max_xri = phba->sli4_hba.max_cfg_param.max_xri;
14345 
14346 	if (phba->sli_rev == LPFC_SLI_REV4) {
14347 		if (max_xri <= 100)
14348 			return 10;
14349 		else if (max_xri <= 256)
14350 			return 25;
14351 		else if (max_xri <= 512)
14352 			return 50;
14353 		else if (max_xri <= 1024)
14354 			return 100;
14355 		else if (max_xri <= 1536)
14356 			return 150;
14357 		else if (max_xri <= 2048)
14358 			return 200;
14359 		else
14360 			return 250;
14361 	} else
14362 		return 0;
14363 }
14364 
14365 /**
14366  * lpfc_sli4_get_iocb_cnt - Calculate the # of total IOCBs to reserve
14367  * @phba: pointer to lpfc hba data structure.
14368  *
14369  * returns the number of ELS/CT + NVMET IOCBs to reserve
14370  **/
14371 int
14372 lpfc_sli4_get_iocb_cnt(struct lpfc_hba *phba)
14373 {
14374 	int max_xri = lpfc_sli4_get_els_iocb_cnt(phba);
14375 
14376 	if (phba->nvmet_support)
14377 		max_xri += LPFC_NVMET_BUF_POST;
14378 	return max_xri;
14379 }
14380 
14381 
14382 static int
14383 lpfc_log_write_firmware_error(struct lpfc_hba *phba, uint32_t offset,
14384 	uint32_t magic_number, uint32_t ftype, uint32_t fid, uint32_t fsize,
14385 	const struct firmware *fw)
14386 {
14387 	int rc;
14388 	u8 sli_family;
14389 
14390 	sli_family = bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf);
14391 	/* Three cases:  (1) FW was not supported on the detected adapter.
14392 	 * (2) FW update has been locked out administratively.
14393 	 * (3) Some other error during FW update.
14394 	 * In each case, an unmaskable message is written to the console
14395 	 * for admin diagnosis.
14396 	 */
14397 	if (offset == ADD_STATUS_FW_NOT_SUPPORTED ||
14398 	    (sli_family == LPFC_SLI_INTF_FAMILY_G6 &&
14399 	     magic_number != MAGIC_NUMBER_G6) ||
14400 	    (sli_family == LPFC_SLI_INTF_FAMILY_G7 &&
14401 	     magic_number != MAGIC_NUMBER_G7) ||
14402 	    (sli_family == LPFC_SLI_INTF_FAMILY_G7P &&
14403 	     magic_number != MAGIC_NUMBER_G7P)) {
14404 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14405 				"3030 This firmware version is not supported on"
14406 				" this HBA model. Device:%x Magic:%x Type:%x "
14407 				"ID:%x Size %d %zd\n",
14408 				phba->pcidev->device, magic_number, ftype, fid,
14409 				fsize, fw->size);
14410 		rc = -EINVAL;
14411 	} else if (offset == ADD_STATUS_FW_DOWNLOAD_HW_DISABLED) {
14412 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14413 				"3021 Firmware downloads have been prohibited "
14414 				"by a system configuration setting on "
14415 				"Device:%x Magic:%x Type:%x ID:%x Size %d "
14416 				"%zd\n",
14417 				phba->pcidev->device, magic_number, ftype, fid,
14418 				fsize, fw->size);
14419 		rc = -EACCES;
14420 	} else {
14421 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14422 				"3022 FW Download failed. Add Status x%x "
14423 				"Device:%x Magic:%x Type:%x ID:%x Size %d "
14424 				"%zd\n",
14425 				offset, phba->pcidev->device, magic_number,
14426 				ftype, fid, fsize, fw->size);
14427 		rc = -EIO;
14428 	}
14429 	return rc;
14430 }
14431 
14432 /**
14433  * lpfc_write_firmware - attempt to write a firmware image to the port
14434  * @fw: pointer to firmware image returned from request_firmware.
14435  * @context: pointer to firmware image returned from request_firmware.
14436  *
14437  **/
14438 static void
14439 lpfc_write_firmware(const struct firmware *fw, void *context)
14440 {
14441 	struct lpfc_hba *phba = (struct lpfc_hba *)context;
14442 	char fwrev[FW_REV_STR_SIZE];
14443 	struct lpfc_grp_hdr *image;
14444 	struct list_head dma_buffer_list;
14445 	int i, rc = 0;
14446 	struct lpfc_dmabuf *dmabuf, *next;
14447 	uint32_t offset = 0, temp_offset = 0;
14448 	uint32_t magic_number, ftype, fid, fsize;
14449 
14450 	/* It can be null in no-wait mode, sanity check */
14451 	if (!fw) {
14452 		rc = -ENXIO;
14453 		goto out;
14454 	}
14455 	image = (struct lpfc_grp_hdr *)fw->data;
14456 
14457 	magic_number = be32_to_cpu(image->magic_number);
14458 	ftype = bf_get_be32(lpfc_grp_hdr_file_type, image);
14459 	fid = bf_get_be32(lpfc_grp_hdr_id, image);
14460 	fsize = be32_to_cpu(image->size);
14461 
14462 	INIT_LIST_HEAD(&dma_buffer_list);
14463 	lpfc_decode_firmware_rev(phba, fwrev, 1);
14464 	if (strncmp(fwrev, image->revision, strnlen(image->revision, 16))) {
14465 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14466 				"3023 Updating Firmware, Current Version:%s "
14467 				"New Version:%s\n",
14468 				fwrev, image->revision);
14469 		for (i = 0; i < LPFC_MBX_WR_CONFIG_MAX_BDE; i++) {
14470 			dmabuf = kzalloc(sizeof(struct lpfc_dmabuf),
14471 					 GFP_KERNEL);
14472 			if (!dmabuf) {
14473 				rc = -ENOMEM;
14474 				goto release_out;
14475 			}
14476 			dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
14477 							  SLI4_PAGE_SIZE,
14478 							  &dmabuf->phys,
14479 							  GFP_KERNEL);
14480 			if (!dmabuf->virt) {
14481 				kfree(dmabuf);
14482 				rc = -ENOMEM;
14483 				goto release_out;
14484 			}
14485 			list_add_tail(&dmabuf->list, &dma_buffer_list);
14486 		}
14487 		while (offset < fw->size) {
14488 			temp_offset = offset;
14489 			list_for_each_entry(dmabuf, &dma_buffer_list, list) {
14490 				if (temp_offset + SLI4_PAGE_SIZE > fw->size) {
14491 					memcpy(dmabuf->virt,
14492 					       fw->data + temp_offset,
14493 					       fw->size - temp_offset);
14494 					temp_offset = fw->size;
14495 					break;
14496 				}
14497 				memcpy(dmabuf->virt, fw->data + temp_offset,
14498 				       SLI4_PAGE_SIZE);
14499 				temp_offset += SLI4_PAGE_SIZE;
14500 			}
14501 			rc = lpfc_wr_object(phba, &dma_buffer_list,
14502 				    (fw->size - offset), &offset);
14503 			if (rc) {
14504 				rc = lpfc_log_write_firmware_error(phba, offset,
14505 								   magic_number,
14506 								   ftype,
14507 								   fid,
14508 								   fsize,
14509 								   fw);
14510 				goto release_out;
14511 			}
14512 		}
14513 		rc = offset;
14514 	} else
14515 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14516 				"3029 Skipped Firmware update, Current "
14517 				"Version:%s New Version:%s\n",
14518 				fwrev, image->revision);
14519 
14520 release_out:
14521 	list_for_each_entry_safe(dmabuf, next, &dma_buffer_list, list) {
14522 		list_del(&dmabuf->list);
14523 		dma_free_coherent(&phba->pcidev->dev, SLI4_PAGE_SIZE,
14524 				  dmabuf->virt, dmabuf->phys);
14525 		kfree(dmabuf);
14526 	}
14527 	release_firmware(fw);
14528 out:
14529 	if (rc < 0)
14530 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14531 				"3062 Firmware update error, status %d.\n", rc);
14532 	else
14533 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14534 				"3024 Firmware update success: size %d.\n", rc);
14535 }
14536 
14537 /**
14538  * lpfc_sli4_request_firmware_update - Request linux generic firmware upgrade
14539  * @phba: pointer to lpfc hba data structure.
14540  * @fw_upgrade: which firmware to update.
14541  *
14542  * This routine is called to perform Linux generic firmware upgrade on device
14543  * that supports such feature.
14544  **/
14545 int
14546 lpfc_sli4_request_firmware_update(struct lpfc_hba *phba, uint8_t fw_upgrade)
14547 {
14548 	uint8_t file_name[ELX_MODEL_NAME_SIZE];
14549 	int ret;
14550 	const struct firmware *fw;
14551 
14552 	/* Only supported on SLI4 interface type 2 for now */
14553 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) <
14554 	    LPFC_SLI_INTF_IF_TYPE_2)
14555 		return -EPERM;
14556 
14557 	snprintf(file_name, ELX_MODEL_NAME_SIZE, "%s.grp", phba->ModelName);
14558 
14559 	if (fw_upgrade == INT_FW_UPGRADE) {
14560 		ret = request_firmware_nowait(THIS_MODULE, FW_ACTION_UEVENT,
14561 					file_name, &phba->pcidev->dev,
14562 					GFP_KERNEL, (void *)phba,
14563 					lpfc_write_firmware);
14564 	} else if (fw_upgrade == RUN_FW_UPGRADE) {
14565 		ret = request_firmware(&fw, file_name, &phba->pcidev->dev);
14566 		if (!ret)
14567 			lpfc_write_firmware(fw, (void *)phba);
14568 	} else {
14569 		ret = -EINVAL;
14570 	}
14571 
14572 	return ret;
14573 }
14574 
14575 /**
14576  * lpfc_pci_probe_one_s4 - PCI probe func to reg SLI-4 device to PCI subsys
14577  * @pdev: pointer to PCI device
14578  * @pid: pointer to PCI device identifier
14579  *
14580  * This routine is called from the kernel's PCI subsystem to device with
14581  * SLI-4 interface spec. When an Emulex HBA with SLI-4 interface spec is
14582  * presented on PCI bus, the kernel PCI subsystem looks at PCI device-specific
14583  * information of the device and driver to see if the driver state that it
14584  * can support this kind of device. If the match is successful, the driver
14585  * core invokes this routine. If this routine determines it can claim the HBA,
14586  * it does all the initialization that it needs to do to handle the HBA
14587  * properly.
14588  *
14589  * Return code
14590  * 	0 - driver can claim the device
14591  * 	negative value - driver can not claim the device
14592  **/
14593 static int
14594 lpfc_pci_probe_one_s4(struct pci_dev *pdev, const struct pci_device_id *pid)
14595 {
14596 	struct lpfc_hba   *phba;
14597 	struct lpfc_vport *vport = NULL;
14598 	struct Scsi_Host  *shost = NULL;
14599 	int error;
14600 	uint32_t cfg_mode, intr_mode;
14601 
14602 	/* Allocate memory for HBA structure */
14603 	phba = lpfc_hba_alloc(pdev);
14604 	if (!phba)
14605 		return -ENOMEM;
14606 
14607 	INIT_LIST_HEAD(&phba->poll_list);
14608 
14609 	/* Perform generic PCI device enabling operation */
14610 	error = lpfc_enable_pci_dev(phba);
14611 	if (error)
14612 		goto out_free_phba;
14613 
14614 	/* Set up SLI API function jump table for PCI-device group-1 HBAs */
14615 	error = lpfc_api_table_setup(phba, LPFC_PCI_DEV_OC);
14616 	if (error)
14617 		goto out_disable_pci_dev;
14618 
14619 	/* Set up SLI-4 specific device PCI memory space */
14620 	error = lpfc_sli4_pci_mem_setup(phba);
14621 	if (error) {
14622 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14623 				"1410 Failed to set up pci memory space.\n");
14624 		goto out_disable_pci_dev;
14625 	}
14626 
14627 	/* Set up SLI-4 Specific device driver resources */
14628 	error = lpfc_sli4_driver_resource_setup(phba);
14629 	if (error) {
14630 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14631 				"1412 Failed to set up driver resource.\n");
14632 		goto out_unset_pci_mem_s4;
14633 	}
14634 
14635 	INIT_LIST_HEAD(&phba->active_rrq_list);
14636 	INIT_LIST_HEAD(&phba->fcf.fcf_pri_list);
14637 
14638 	/* Set up common device driver resources */
14639 	error = lpfc_setup_driver_resource_phase2(phba);
14640 	if (error) {
14641 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14642 				"1414 Failed to set up driver resource.\n");
14643 		goto out_unset_driver_resource_s4;
14644 	}
14645 
14646 	/* Get the default values for Model Name and Description */
14647 	lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
14648 
14649 	/* Now, trying to enable interrupt and bring up the device */
14650 	cfg_mode = phba->cfg_use_msi;
14651 
14652 	/* Put device to a known state before enabling interrupt */
14653 	phba->pport = NULL;
14654 	lpfc_stop_port(phba);
14655 
14656 	/* Init cpu_map array */
14657 	lpfc_cpu_map_array_init(phba);
14658 
14659 	/* Init hba_eq_hdl array */
14660 	lpfc_hba_eq_hdl_array_init(phba);
14661 
14662 	/* Configure and enable interrupt */
14663 	intr_mode = lpfc_sli4_enable_intr(phba, cfg_mode);
14664 	if (intr_mode == LPFC_INTR_ERROR) {
14665 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14666 				"0426 Failed to enable interrupt.\n");
14667 		error = -ENODEV;
14668 		goto out_unset_driver_resource;
14669 	}
14670 	/* Default to single EQ for non-MSI-X */
14671 	if (phba->intr_type != MSIX) {
14672 		phba->cfg_irq_chann = 1;
14673 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
14674 			if (phba->nvmet_support)
14675 				phba->cfg_nvmet_mrq = 1;
14676 		}
14677 	}
14678 	lpfc_cpu_affinity_check(phba, phba->cfg_irq_chann);
14679 
14680 	/* Create SCSI host to the physical port */
14681 	error = lpfc_create_shost(phba);
14682 	if (error) {
14683 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14684 				"1415 Failed to create scsi host.\n");
14685 		goto out_disable_intr;
14686 	}
14687 	vport = phba->pport;
14688 	shost = lpfc_shost_from_vport(vport); /* save shost for error cleanup */
14689 
14690 	/* Configure sysfs attributes */
14691 	error = lpfc_alloc_sysfs_attr(vport);
14692 	if (error) {
14693 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14694 				"1416 Failed to allocate sysfs attr\n");
14695 		goto out_destroy_shost;
14696 	}
14697 
14698 	/* Set up SLI-4 HBA */
14699 	if (lpfc_sli4_hba_setup(phba)) {
14700 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14701 				"1421 Failed to set up hba\n");
14702 		error = -ENODEV;
14703 		goto out_free_sysfs_attr;
14704 	}
14705 
14706 	/* Log the current active interrupt mode */
14707 	phba->intr_mode = intr_mode;
14708 	lpfc_log_intr_mode(phba, intr_mode);
14709 
14710 	/* Perform post initialization setup */
14711 	lpfc_post_init_setup(phba);
14712 
14713 	/* NVME support in FW earlier in the driver load corrects the
14714 	 * FC4 type making a check for nvme_support unnecessary.
14715 	 */
14716 	if (phba->nvmet_support == 0) {
14717 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
14718 			/* Create NVME binding with nvme_fc_transport. This
14719 			 * ensures the vport is initialized.  If the localport
14720 			 * create fails, it should not unload the driver to
14721 			 * support field issues.
14722 			 */
14723 			error = lpfc_nvme_create_localport(vport);
14724 			if (error) {
14725 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14726 						"6004 NVME registration "
14727 						"failed, error x%x\n",
14728 						error);
14729 			}
14730 		}
14731 	}
14732 
14733 	/* check for firmware upgrade or downgrade */
14734 	if (phba->cfg_request_firmware_upgrade)
14735 		lpfc_sli4_request_firmware_update(phba, INT_FW_UPGRADE);
14736 
14737 	/* Check if there are static vports to be created. */
14738 	lpfc_create_static_vport(phba);
14739 
14740 	/* Enable RAS FW log support */
14741 	lpfc_sli4_ras_setup(phba);
14742 
14743 	timer_setup(&phba->cpuhp_poll_timer, lpfc_sli4_poll_hbtimer, 0);
14744 	cpuhp_state_add_instance_nocalls(lpfc_cpuhp_state, &phba->cpuhp);
14745 
14746 	return 0;
14747 
14748 out_free_sysfs_attr:
14749 	lpfc_free_sysfs_attr(vport);
14750 out_destroy_shost:
14751 	lpfc_destroy_shost(phba);
14752 out_disable_intr:
14753 	lpfc_sli4_disable_intr(phba);
14754 out_unset_driver_resource:
14755 	lpfc_unset_driver_resource_phase2(phba);
14756 out_unset_driver_resource_s4:
14757 	lpfc_sli4_driver_resource_unset(phba);
14758 out_unset_pci_mem_s4:
14759 	lpfc_sli4_pci_mem_unset(phba);
14760 out_disable_pci_dev:
14761 	lpfc_disable_pci_dev(phba);
14762 	if (shost)
14763 		scsi_host_put(shost);
14764 out_free_phba:
14765 	lpfc_hba_free(phba);
14766 	return error;
14767 }
14768 
14769 /**
14770  * lpfc_pci_remove_one_s4 - PCI func to unreg SLI-4 device from PCI subsystem
14771  * @pdev: pointer to PCI device
14772  *
14773  * This routine is called from the kernel's PCI subsystem to device with
14774  * SLI-4 interface spec. When an Emulex HBA with SLI-4 interface spec is
14775  * removed from PCI bus, it performs all the necessary cleanup for the HBA
14776  * device to be removed from the PCI subsystem properly.
14777  **/
14778 static void
14779 lpfc_pci_remove_one_s4(struct pci_dev *pdev)
14780 {
14781 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
14782 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
14783 	struct lpfc_vport **vports;
14784 	struct lpfc_hba *phba = vport->phba;
14785 	int i;
14786 
14787 	/* Mark the device unloading flag */
14788 	spin_lock_irq(&phba->hbalock);
14789 	vport->load_flag |= FC_UNLOADING;
14790 	spin_unlock_irq(&phba->hbalock);
14791 	if (phba->cgn_i)
14792 		lpfc_unreg_congestion_buf(phba);
14793 
14794 	lpfc_free_sysfs_attr(vport);
14795 
14796 	/* Release all the vports against this physical port */
14797 	vports = lpfc_create_vport_work_array(phba);
14798 	if (vports != NULL)
14799 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
14800 			if (vports[i]->port_type == LPFC_PHYSICAL_PORT)
14801 				continue;
14802 			fc_vport_terminate(vports[i]->fc_vport);
14803 		}
14804 	lpfc_destroy_vport_work_array(phba, vports);
14805 
14806 	/* Remove FC host with the physical port */
14807 	fc_remove_host(shost);
14808 	scsi_remove_host(shost);
14809 
14810 	/* Perform ndlp cleanup on the physical port.  The nvme and nvmet
14811 	 * localports are destroyed after to cleanup all transport memory.
14812 	 */
14813 	lpfc_cleanup(vport);
14814 	lpfc_nvmet_destroy_targetport(phba);
14815 	lpfc_nvme_destroy_localport(vport);
14816 
14817 	/* De-allocate multi-XRI pools */
14818 	if (phba->cfg_xri_rebalancing)
14819 		lpfc_destroy_multixri_pools(phba);
14820 
14821 	/*
14822 	 * Bring down the SLI Layer. This step disables all interrupts,
14823 	 * clears the rings, discards all mailbox commands, and resets
14824 	 * the HBA FCoE function.
14825 	 */
14826 	lpfc_debugfs_terminate(vport);
14827 
14828 	lpfc_stop_hba_timers(phba);
14829 	spin_lock_irq(&phba->port_list_lock);
14830 	list_del_init(&vport->listentry);
14831 	spin_unlock_irq(&phba->port_list_lock);
14832 
14833 	/* Perform scsi free before driver resource_unset since scsi
14834 	 * buffers are released to their corresponding pools here.
14835 	 */
14836 	lpfc_io_free(phba);
14837 	lpfc_free_iocb_list(phba);
14838 	lpfc_sli4_hba_unset(phba);
14839 
14840 	lpfc_unset_driver_resource_phase2(phba);
14841 	lpfc_sli4_driver_resource_unset(phba);
14842 
14843 	/* Unmap adapter Control and Doorbell registers */
14844 	lpfc_sli4_pci_mem_unset(phba);
14845 
14846 	/* Release PCI resources and disable device's PCI function */
14847 	scsi_host_put(shost);
14848 	lpfc_disable_pci_dev(phba);
14849 
14850 	/* Finally, free the driver's device data structure */
14851 	lpfc_hba_free(phba);
14852 
14853 	return;
14854 }
14855 
14856 /**
14857  * lpfc_pci_suspend_one_s4 - PCI func to suspend SLI-4 device for power mgmnt
14858  * @dev_d: pointer to device
14859  *
14860  * This routine is called from the kernel's PCI subsystem to support system
14861  * Power Management (PM) to device with SLI-4 interface spec. When PM invokes
14862  * this method, it quiesces the device by stopping the driver's worker
14863  * thread for the device, turning off device's interrupt and DMA, and bring
14864  * the device offline. Note that as the driver implements the minimum PM
14865  * requirements to a power-aware driver's PM support for suspend/resume -- all
14866  * the possible PM messages (SUSPEND, HIBERNATE, FREEZE) to the suspend()
14867  * method call will be treated as SUSPEND and the driver will fully
14868  * reinitialize its device during resume() method call, the driver will set
14869  * device to PCI_D3hot state in PCI config space instead of setting it
14870  * according to the @msg provided by the PM.
14871  *
14872  * Return code
14873  * 	0 - driver suspended the device
14874  * 	Error otherwise
14875  **/
14876 static int __maybe_unused
14877 lpfc_pci_suspend_one_s4(struct device *dev_d)
14878 {
14879 	struct Scsi_Host *shost = dev_get_drvdata(dev_d);
14880 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14881 
14882 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
14883 			"2843 PCI device Power Management suspend.\n");
14884 
14885 	/* Bring down the device */
14886 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
14887 	lpfc_offline(phba);
14888 	kthread_stop(phba->worker_thread);
14889 
14890 	/* Disable interrupt from device */
14891 	lpfc_sli4_disable_intr(phba);
14892 	lpfc_sli4_queue_destroy(phba);
14893 
14894 	return 0;
14895 }
14896 
14897 /**
14898  * lpfc_pci_resume_one_s4 - PCI func to resume SLI-4 device for power mgmnt
14899  * @dev_d: pointer to device
14900  *
14901  * This routine is called from the kernel's PCI subsystem to support system
14902  * Power Management (PM) to device with SLI-4 interface spac. When PM invokes
14903  * this method, it restores the device's PCI config space state and fully
14904  * reinitializes the device and brings it online. Note that as the driver
14905  * implements the minimum PM requirements to a power-aware driver's PM for
14906  * suspend/resume -- all the possible PM messages (SUSPEND, HIBERNATE, FREEZE)
14907  * to the suspend() method call will be treated as SUSPEND and the driver
14908  * will fully reinitialize its device during resume() method call, the device
14909  * will be set to PCI_D0 directly in PCI config space before restoring the
14910  * state.
14911  *
14912  * Return code
14913  * 	0 - driver suspended the device
14914  * 	Error otherwise
14915  **/
14916 static int __maybe_unused
14917 lpfc_pci_resume_one_s4(struct device *dev_d)
14918 {
14919 	struct Scsi_Host *shost = dev_get_drvdata(dev_d);
14920 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14921 	uint32_t intr_mode;
14922 	int error;
14923 
14924 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
14925 			"0292 PCI device Power Management resume.\n");
14926 
14927 	 /* Startup the kernel thread for this host adapter. */
14928 	phba->worker_thread = kthread_run(lpfc_do_work, phba,
14929 					"lpfc_worker_%d", phba->brd_no);
14930 	if (IS_ERR(phba->worker_thread)) {
14931 		error = PTR_ERR(phba->worker_thread);
14932 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14933 				"0293 PM resume failed to start worker "
14934 				"thread: error=x%x.\n", error);
14935 		return error;
14936 	}
14937 
14938 	/* Configure and enable interrupt */
14939 	intr_mode = lpfc_sli4_enable_intr(phba, phba->intr_mode);
14940 	if (intr_mode == LPFC_INTR_ERROR) {
14941 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14942 				"0294 PM resume Failed to enable interrupt\n");
14943 		return -EIO;
14944 	} else
14945 		phba->intr_mode = intr_mode;
14946 
14947 	/* Restart HBA and bring it online */
14948 	lpfc_sli_brdrestart(phba);
14949 	lpfc_online(phba);
14950 
14951 	/* Log the current active interrupt mode */
14952 	lpfc_log_intr_mode(phba, phba->intr_mode);
14953 
14954 	return 0;
14955 }
14956 
14957 /**
14958  * lpfc_sli4_prep_dev_for_recover - Prepare SLI4 device for pci slot recover
14959  * @phba: pointer to lpfc hba data structure.
14960  *
14961  * This routine is called to prepare the SLI4 device for PCI slot recover. It
14962  * aborts all the outstanding SCSI I/Os to the pci device.
14963  **/
14964 static void
14965 lpfc_sli4_prep_dev_for_recover(struct lpfc_hba *phba)
14966 {
14967 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14968 			"2828 PCI channel I/O abort preparing for recovery\n");
14969 	/*
14970 	 * There may be errored I/Os through HBA, abort all I/Os on txcmplq
14971 	 * and let the SCSI mid-layer to retry them to recover.
14972 	 */
14973 	lpfc_sli_abort_fcp_rings(phba);
14974 }
14975 
14976 /**
14977  * lpfc_sli4_prep_dev_for_reset - Prepare SLI4 device for pci slot reset
14978  * @phba: pointer to lpfc hba data structure.
14979  *
14980  * This routine is called to prepare the SLI4 device for PCI slot reset. It
14981  * disables the device interrupt and pci device, and aborts the internal FCP
14982  * pending I/Os.
14983  **/
14984 static void
14985 lpfc_sli4_prep_dev_for_reset(struct lpfc_hba *phba)
14986 {
14987 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14988 			"2826 PCI channel disable preparing for reset\n");
14989 
14990 	/* Block any management I/Os to the device */
14991 	lpfc_block_mgmt_io(phba, LPFC_MBX_NO_WAIT);
14992 
14993 	/* Block all SCSI devices' I/Os on the host */
14994 	lpfc_scsi_dev_block(phba);
14995 
14996 	/* Flush all driver's outstanding I/Os as we are to reset */
14997 	lpfc_sli_flush_io_rings(phba);
14998 
14999 	/* stop all timers */
15000 	lpfc_stop_hba_timers(phba);
15001 
15002 	/* Disable interrupt and pci device */
15003 	lpfc_sli4_disable_intr(phba);
15004 	lpfc_sli4_queue_destroy(phba);
15005 	pci_disable_device(phba->pcidev);
15006 }
15007 
15008 /**
15009  * lpfc_sli4_prep_dev_for_perm_failure - Prepare SLI4 dev for pci slot disable
15010  * @phba: pointer to lpfc hba data structure.
15011  *
15012  * This routine is called to prepare the SLI4 device for PCI slot permanently
15013  * disabling. It blocks the SCSI transport layer traffic and flushes the FCP
15014  * pending I/Os.
15015  **/
15016 static void
15017 lpfc_sli4_prep_dev_for_perm_failure(struct lpfc_hba *phba)
15018 {
15019 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15020 			"2827 PCI channel permanent disable for failure\n");
15021 
15022 	/* Block all SCSI devices' I/Os on the host */
15023 	lpfc_scsi_dev_block(phba);
15024 
15025 	/* stop all timers */
15026 	lpfc_stop_hba_timers(phba);
15027 
15028 	/* Clean up all driver's outstanding I/Os */
15029 	lpfc_sli_flush_io_rings(phba);
15030 }
15031 
15032 /**
15033  * lpfc_io_error_detected_s4 - Method for handling PCI I/O error to SLI-4 device
15034  * @pdev: pointer to PCI device.
15035  * @state: the current PCI connection state.
15036  *
15037  * This routine is called from the PCI subsystem for error handling to device
15038  * with SLI-4 interface spec. This function is called by the PCI subsystem
15039  * after a PCI bus error affecting this device has been detected. When this
15040  * function is invoked, it will need to stop all the I/Os and interrupt(s)
15041  * to the device. Once that is done, it will return PCI_ERS_RESULT_NEED_RESET
15042  * for the PCI subsystem to perform proper recovery as desired.
15043  *
15044  * Return codes
15045  * 	PCI_ERS_RESULT_NEED_RESET - need to reset before recovery
15046  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15047  **/
15048 static pci_ers_result_t
15049 lpfc_io_error_detected_s4(struct pci_dev *pdev, pci_channel_state_t state)
15050 {
15051 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15052 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15053 
15054 	switch (state) {
15055 	case pci_channel_io_normal:
15056 		/* Non-fatal error, prepare for recovery */
15057 		lpfc_sli4_prep_dev_for_recover(phba);
15058 		return PCI_ERS_RESULT_CAN_RECOVER;
15059 	case pci_channel_io_frozen:
15060 		phba->hba_flag |= HBA_PCI_ERR;
15061 		/* Fatal error, prepare for slot reset */
15062 		lpfc_sli4_prep_dev_for_reset(phba);
15063 		return PCI_ERS_RESULT_NEED_RESET;
15064 	case pci_channel_io_perm_failure:
15065 		phba->hba_flag |= HBA_PCI_ERR;
15066 		/* Permanent failure, prepare for device down */
15067 		lpfc_sli4_prep_dev_for_perm_failure(phba);
15068 		return PCI_ERS_RESULT_DISCONNECT;
15069 	default:
15070 		phba->hba_flag |= HBA_PCI_ERR;
15071 		/* Unknown state, prepare and request slot reset */
15072 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15073 				"2825 Unknown PCI error state: x%x\n", state);
15074 		lpfc_sli4_prep_dev_for_reset(phba);
15075 		return PCI_ERS_RESULT_NEED_RESET;
15076 	}
15077 }
15078 
15079 /**
15080  * lpfc_io_slot_reset_s4 - Method for restart PCI SLI-4 device from scratch
15081  * @pdev: pointer to PCI device.
15082  *
15083  * This routine is called from the PCI subsystem for error handling to device
15084  * with SLI-4 interface spec. It is called after PCI bus has been reset to
15085  * restart the PCI card from scratch, as if from a cold-boot. During the
15086  * PCI subsystem error recovery, after the driver returns
15087  * PCI_ERS_RESULT_NEED_RESET, the PCI subsystem will perform proper error
15088  * recovery and then call this routine before calling the .resume method to
15089  * recover the device. This function will initialize the HBA device, enable
15090  * the interrupt, but it will just put the HBA to offline state without
15091  * passing any I/O traffic.
15092  *
15093  * Return codes
15094  * 	PCI_ERS_RESULT_RECOVERED - the device has been recovered
15095  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15096  */
15097 static pci_ers_result_t
15098 lpfc_io_slot_reset_s4(struct pci_dev *pdev)
15099 {
15100 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15101 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15102 	struct lpfc_sli *psli = &phba->sli;
15103 	uint32_t intr_mode;
15104 
15105 	dev_printk(KERN_INFO, &pdev->dev, "recovering from a slot reset.\n");
15106 	if (pci_enable_device_mem(pdev)) {
15107 		printk(KERN_ERR "lpfc: Cannot re-enable "
15108 			"PCI device after reset.\n");
15109 		return PCI_ERS_RESULT_DISCONNECT;
15110 	}
15111 
15112 	pci_restore_state(pdev);
15113 
15114 	phba->hba_flag &= ~HBA_PCI_ERR;
15115 	/*
15116 	 * As the new kernel behavior of pci_restore_state() API call clears
15117 	 * device saved_state flag, need to save the restored state again.
15118 	 */
15119 	pci_save_state(pdev);
15120 
15121 	if (pdev->is_busmaster)
15122 		pci_set_master(pdev);
15123 
15124 	spin_lock_irq(&phba->hbalock);
15125 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
15126 	spin_unlock_irq(&phba->hbalock);
15127 
15128 	/* Init cpu_map array */
15129 	lpfc_cpu_map_array_init(phba);
15130 	/* Configure and enable interrupt */
15131 	intr_mode = lpfc_sli4_enable_intr(phba, phba->intr_mode);
15132 	if (intr_mode == LPFC_INTR_ERROR) {
15133 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15134 				"2824 Cannot re-enable interrupt after "
15135 				"slot reset.\n");
15136 		return PCI_ERS_RESULT_DISCONNECT;
15137 	} else
15138 		phba->intr_mode = intr_mode;
15139 	lpfc_cpu_affinity_check(phba, phba->cfg_irq_chann);
15140 
15141 	/* Log the current active interrupt mode */
15142 	lpfc_log_intr_mode(phba, phba->intr_mode);
15143 
15144 	return PCI_ERS_RESULT_RECOVERED;
15145 }
15146 
15147 /**
15148  * lpfc_io_resume_s4 - Method for resuming PCI I/O operation to SLI-4 device
15149  * @pdev: pointer to PCI device
15150  *
15151  * This routine is called from the PCI subsystem for error handling to device
15152  * with SLI-4 interface spec. It is called when kernel error recovery tells
15153  * the lpfc driver that it is ok to resume normal PCI operation after PCI bus
15154  * error recovery. After this call, traffic can start to flow from this device
15155  * again.
15156  **/
15157 static void
15158 lpfc_io_resume_s4(struct pci_dev *pdev)
15159 {
15160 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15161 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15162 
15163 	/*
15164 	 * In case of slot reset, as function reset is performed through
15165 	 * mailbox command which needs DMA to be enabled, this operation
15166 	 * has to be moved to the io resume phase. Taking device offline
15167 	 * will perform the necessary cleanup.
15168 	 */
15169 	if (!(phba->sli.sli_flag & LPFC_SLI_ACTIVE)) {
15170 		/* Perform device reset */
15171 		lpfc_offline_prep(phba, LPFC_MBX_WAIT);
15172 		lpfc_offline(phba);
15173 		lpfc_sli_brdrestart(phba);
15174 		/* Bring the device back online */
15175 		lpfc_online(phba);
15176 	}
15177 }
15178 
15179 /**
15180  * lpfc_pci_probe_one - lpfc PCI probe func to reg dev to PCI subsystem
15181  * @pdev: pointer to PCI device
15182  * @pid: pointer to PCI device identifier
15183  *
15184  * This routine is to be registered to the kernel's PCI subsystem. When an
15185  * Emulex HBA device is presented on PCI bus, the kernel PCI subsystem looks
15186  * at PCI device-specific information of the device and driver to see if the
15187  * driver state that it can support this kind of device. If the match is
15188  * successful, the driver core invokes this routine. This routine dispatches
15189  * the action to the proper SLI-3 or SLI-4 device probing routine, which will
15190  * do all the initialization that it needs to do to handle the HBA device
15191  * properly.
15192  *
15193  * Return code
15194  * 	0 - driver can claim the device
15195  * 	negative value - driver can not claim the device
15196  **/
15197 static int
15198 lpfc_pci_probe_one(struct pci_dev *pdev, const struct pci_device_id *pid)
15199 {
15200 	int rc;
15201 	struct lpfc_sli_intf intf;
15202 
15203 	if (pci_read_config_dword(pdev, LPFC_SLI_INTF, &intf.word0))
15204 		return -ENODEV;
15205 
15206 	if ((bf_get(lpfc_sli_intf_valid, &intf) == LPFC_SLI_INTF_VALID) &&
15207 	    (bf_get(lpfc_sli_intf_slirev, &intf) == LPFC_SLI_INTF_REV_SLI4))
15208 		rc = lpfc_pci_probe_one_s4(pdev, pid);
15209 	else
15210 		rc = lpfc_pci_probe_one_s3(pdev, pid);
15211 
15212 	return rc;
15213 }
15214 
15215 /**
15216  * lpfc_pci_remove_one - lpfc PCI func to unreg dev from PCI subsystem
15217  * @pdev: pointer to PCI device
15218  *
15219  * This routine is to be registered to the kernel's PCI subsystem. When an
15220  * Emulex HBA is removed from PCI bus, the driver core invokes this routine.
15221  * This routine dispatches the action to the proper SLI-3 or SLI-4 device
15222  * remove routine, which will perform all the necessary cleanup for the
15223  * device to be removed from the PCI subsystem properly.
15224  **/
15225 static void
15226 lpfc_pci_remove_one(struct pci_dev *pdev)
15227 {
15228 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15229 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15230 
15231 	switch (phba->pci_dev_grp) {
15232 	case LPFC_PCI_DEV_LP:
15233 		lpfc_pci_remove_one_s3(pdev);
15234 		break;
15235 	case LPFC_PCI_DEV_OC:
15236 		lpfc_pci_remove_one_s4(pdev);
15237 		break;
15238 	default:
15239 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15240 				"1424 Invalid PCI device group: 0x%x\n",
15241 				phba->pci_dev_grp);
15242 		break;
15243 	}
15244 	return;
15245 }
15246 
15247 /**
15248  * lpfc_pci_suspend_one - lpfc PCI func to suspend dev for power management
15249  * @dev: pointer to device
15250  *
15251  * This routine is to be registered to the kernel's PCI subsystem to support
15252  * system Power Management (PM). When PM invokes this method, it dispatches
15253  * the action to the proper SLI-3 or SLI-4 device suspend routine, which will
15254  * suspend the device.
15255  *
15256  * Return code
15257  * 	0 - driver suspended the device
15258  * 	Error otherwise
15259  **/
15260 static int __maybe_unused
15261 lpfc_pci_suspend_one(struct device *dev)
15262 {
15263 	struct Scsi_Host *shost = dev_get_drvdata(dev);
15264 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15265 	int rc = -ENODEV;
15266 
15267 	switch (phba->pci_dev_grp) {
15268 	case LPFC_PCI_DEV_LP:
15269 		rc = lpfc_pci_suspend_one_s3(dev);
15270 		break;
15271 	case LPFC_PCI_DEV_OC:
15272 		rc = lpfc_pci_suspend_one_s4(dev);
15273 		break;
15274 	default:
15275 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15276 				"1425 Invalid PCI device group: 0x%x\n",
15277 				phba->pci_dev_grp);
15278 		break;
15279 	}
15280 	return rc;
15281 }
15282 
15283 /**
15284  * lpfc_pci_resume_one - lpfc PCI func to resume dev for power management
15285  * @dev: pointer to device
15286  *
15287  * This routine is to be registered to the kernel's PCI subsystem to support
15288  * system Power Management (PM). When PM invokes this method, it dispatches
15289  * the action to the proper SLI-3 or SLI-4 device resume routine, which will
15290  * resume the device.
15291  *
15292  * Return code
15293  * 	0 - driver suspended the device
15294  * 	Error otherwise
15295  **/
15296 static int __maybe_unused
15297 lpfc_pci_resume_one(struct device *dev)
15298 {
15299 	struct Scsi_Host *shost = dev_get_drvdata(dev);
15300 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15301 	int rc = -ENODEV;
15302 
15303 	switch (phba->pci_dev_grp) {
15304 	case LPFC_PCI_DEV_LP:
15305 		rc = lpfc_pci_resume_one_s3(dev);
15306 		break;
15307 	case LPFC_PCI_DEV_OC:
15308 		rc = lpfc_pci_resume_one_s4(dev);
15309 		break;
15310 	default:
15311 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15312 				"1426 Invalid PCI device group: 0x%x\n",
15313 				phba->pci_dev_grp);
15314 		break;
15315 	}
15316 	return rc;
15317 }
15318 
15319 /**
15320  * lpfc_io_error_detected - lpfc method for handling PCI I/O error
15321  * @pdev: pointer to PCI device.
15322  * @state: the current PCI connection state.
15323  *
15324  * This routine is registered to the PCI subsystem for error handling. This
15325  * function is called by the PCI subsystem after a PCI bus error affecting
15326  * this device has been detected. When this routine is invoked, it dispatches
15327  * the action to the proper SLI-3 or SLI-4 device error detected handling
15328  * routine, which will perform the proper error detected operation.
15329  *
15330  * Return codes
15331  * 	PCI_ERS_RESULT_NEED_RESET - need to reset before recovery
15332  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15333  **/
15334 static pci_ers_result_t
15335 lpfc_io_error_detected(struct pci_dev *pdev, pci_channel_state_t state)
15336 {
15337 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15338 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15339 	pci_ers_result_t rc = PCI_ERS_RESULT_DISCONNECT;
15340 
15341 	if (phba->link_state == LPFC_HBA_ERROR &&
15342 	    phba->hba_flag & HBA_IOQ_FLUSH)
15343 		return PCI_ERS_RESULT_NEED_RESET;
15344 
15345 	switch (phba->pci_dev_grp) {
15346 	case LPFC_PCI_DEV_LP:
15347 		rc = lpfc_io_error_detected_s3(pdev, state);
15348 		break;
15349 	case LPFC_PCI_DEV_OC:
15350 		rc = lpfc_io_error_detected_s4(pdev, state);
15351 		break;
15352 	default:
15353 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15354 				"1427 Invalid PCI device group: 0x%x\n",
15355 				phba->pci_dev_grp);
15356 		break;
15357 	}
15358 	return rc;
15359 }
15360 
15361 /**
15362  * lpfc_io_slot_reset - lpfc method for restart PCI dev from scratch
15363  * @pdev: pointer to PCI device.
15364  *
15365  * This routine is registered to the PCI subsystem for error handling. This
15366  * function is called after PCI bus has been reset to restart the PCI card
15367  * from scratch, as if from a cold-boot. When this routine is invoked, it
15368  * dispatches the action to the proper SLI-3 or SLI-4 device reset handling
15369  * routine, which will perform the proper device reset.
15370  *
15371  * Return codes
15372  * 	PCI_ERS_RESULT_RECOVERED - the device has been recovered
15373  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15374  **/
15375 static pci_ers_result_t
15376 lpfc_io_slot_reset(struct pci_dev *pdev)
15377 {
15378 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15379 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15380 	pci_ers_result_t rc = PCI_ERS_RESULT_DISCONNECT;
15381 
15382 	switch (phba->pci_dev_grp) {
15383 	case LPFC_PCI_DEV_LP:
15384 		rc = lpfc_io_slot_reset_s3(pdev);
15385 		break;
15386 	case LPFC_PCI_DEV_OC:
15387 		rc = lpfc_io_slot_reset_s4(pdev);
15388 		break;
15389 	default:
15390 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15391 				"1428 Invalid PCI device group: 0x%x\n",
15392 				phba->pci_dev_grp);
15393 		break;
15394 	}
15395 	return rc;
15396 }
15397 
15398 /**
15399  * lpfc_io_resume - lpfc method for resuming PCI I/O operation
15400  * @pdev: pointer to PCI device
15401  *
15402  * This routine is registered to the PCI subsystem for error handling. It
15403  * is called when kernel error recovery tells the lpfc driver that it is
15404  * OK to resume normal PCI operation after PCI bus error recovery. When
15405  * this routine is invoked, it dispatches the action to the proper SLI-3
15406  * or SLI-4 device io_resume routine, which will resume the device operation.
15407  **/
15408 static void
15409 lpfc_io_resume(struct pci_dev *pdev)
15410 {
15411 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15412 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15413 
15414 	switch (phba->pci_dev_grp) {
15415 	case LPFC_PCI_DEV_LP:
15416 		lpfc_io_resume_s3(pdev);
15417 		break;
15418 	case LPFC_PCI_DEV_OC:
15419 		lpfc_io_resume_s4(pdev);
15420 		break;
15421 	default:
15422 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15423 				"1429 Invalid PCI device group: 0x%x\n",
15424 				phba->pci_dev_grp);
15425 		break;
15426 	}
15427 	return;
15428 }
15429 
15430 /**
15431  * lpfc_sli4_oas_verify - Verify OAS is supported by this adapter
15432  * @phba: pointer to lpfc hba data structure.
15433  *
15434  * This routine checks to see if OAS is supported for this adapter. If
15435  * supported, the configure Flash Optimized Fabric flag is set.  Otherwise,
15436  * the enable oas flag is cleared and the pool created for OAS device data
15437  * is destroyed.
15438  *
15439  **/
15440 static void
15441 lpfc_sli4_oas_verify(struct lpfc_hba *phba)
15442 {
15443 
15444 	if (!phba->cfg_EnableXLane)
15445 		return;
15446 
15447 	if (phba->sli4_hba.pc_sli4_params.oas_supported) {
15448 		phba->cfg_fof = 1;
15449 	} else {
15450 		phba->cfg_fof = 0;
15451 		mempool_destroy(phba->device_data_mem_pool);
15452 		phba->device_data_mem_pool = NULL;
15453 	}
15454 
15455 	return;
15456 }
15457 
15458 /**
15459  * lpfc_sli4_ras_init - Verify RAS-FW log is supported by this adapter
15460  * @phba: pointer to lpfc hba data structure.
15461  *
15462  * This routine checks to see if RAS is supported by the adapter. Check the
15463  * function through which RAS support enablement is to be done.
15464  **/
15465 void
15466 lpfc_sli4_ras_init(struct lpfc_hba *phba)
15467 {
15468 	/* if ASIC_GEN_NUM >= 0xC) */
15469 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
15470 		    LPFC_SLI_INTF_IF_TYPE_6) ||
15471 	    (bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf) ==
15472 		    LPFC_SLI_INTF_FAMILY_G6)) {
15473 		phba->ras_fwlog.ras_hwsupport = true;
15474 		if (phba->cfg_ras_fwlog_func == PCI_FUNC(phba->pcidev->devfn) &&
15475 		    phba->cfg_ras_fwlog_buffsize)
15476 			phba->ras_fwlog.ras_enabled = true;
15477 		else
15478 			phba->ras_fwlog.ras_enabled = false;
15479 	} else {
15480 		phba->ras_fwlog.ras_hwsupport = false;
15481 	}
15482 }
15483 
15484 
15485 MODULE_DEVICE_TABLE(pci, lpfc_id_table);
15486 
15487 static const struct pci_error_handlers lpfc_err_handler = {
15488 	.error_detected = lpfc_io_error_detected,
15489 	.slot_reset = lpfc_io_slot_reset,
15490 	.resume = lpfc_io_resume,
15491 };
15492 
15493 static SIMPLE_DEV_PM_OPS(lpfc_pci_pm_ops_one,
15494 			 lpfc_pci_suspend_one,
15495 			 lpfc_pci_resume_one);
15496 
15497 static struct pci_driver lpfc_driver = {
15498 	.name		= LPFC_DRIVER_NAME,
15499 	.id_table	= lpfc_id_table,
15500 	.probe		= lpfc_pci_probe_one,
15501 	.remove		= lpfc_pci_remove_one,
15502 	.shutdown	= lpfc_pci_remove_one,
15503 	.driver.pm	= &lpfc_pci_pm_ops_one,
15504 	.err_handler    = &lpfc_err_handler,
15505 };
15506 
15507 static const struct file_operations lpfc_mgmt_fop = {
15508 	.owner = THIS_MODULE,
15509 };
15510 
15511 static struct miscdevice lpfc_mgmt_dev = {
15512 	.minor = MISC_DYNAMIC_MINOR,
15513 	.name = "lpfcmgmt",
15514 	.fops = &lpfc_mgmt_fop,
15515 };
15516 
15517 /**
15518  * lpfc_init - lpfc module initialization routine
15519  *
15520  * This routine is to be invoked when the lpfc module is loaded into the
15521  * kernel. The special kernel macro module_init() is used to indicate the
15522  * role of this routine to the kernel as lpfc module entry point.
15523  *
15524  * Return codes
15525  *   0 - successful
15526  *   -ENOMEM - FC attach transport failed
15527  *   all others - failed
15528  */
15529 static int __init
15530 lpfc_init(void)
15531 {
15532 	int error = 0;
15533 
15534 	pr_info(LPFC_MODULE_DESC "\n");
15535 	pr_info(LPFC_COPYRIGHT "\n");
15536 
15537 	error = misc_register(&lpfc_mgmt_dev);
15538 	if (error)
15539 		printk(KERN_ERR "Could not register lpfcmgmt device, "
15540 			"misc_register returned with status %d", error);
15541 
15542 	error = -ENOMEM;
15543 	lpfc_transport_functions.vport_create = lpfc_vport_create;
15544 	lpfc_transport_functions.vport_delete = lpfc_vport_delete;
15545 	lpfc_transport_template =
15546 				fc_attach_transport(&lpfc_transport_functions);
15547 	if (lpfc_transport_template == NULL)
15548 		goto unregister;
15549 	lpfc_vport_transport_template =
15550 		fc_attach_transport(&lpfc_vport_transport_functions);
15551 	if (lpfc_vport_transport_template == NULL) {
15552 		fc_release_transport(lpfc_transport_template);
15553 		goto unregister;
15554 	}
15555 	lpfc_wqe_cmd_template();
15556 	lpfc_nvmet_cmd_template();
15557 
15558 	/* Initialize in case vector mapping is needed */
15559 	lpfc_present_cpu = num_present_cpus();
15560 
15561 	error = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN,
15562 					"lpfc/sli4:online",
15563 					lpfc_cpu_online, lpfc_cpu_offline);
15564 	if (error < 0)
15565 		goto cpuhp_failure;
15566 	lpfc_cpuhp_state = error;
15567 
15568 	error = pci_register_driver(&lpfc_driver);
15569 	if (error)
15570 		goto unwind;
15571 
15572 	return error;
15573 
15574 unwind:
15575 	cpuhp_remove_multi_state(lpfc_cpuhp_state);
15576 cpuhp_failure:
15577 	fc_release_transport(lpfc_transport_template);
15578 	fc_release_transport(lpfc_vport_transport_template);
15579 unregister:
15580 	misc_deregister(&lpfc_mgmt_dev);
15581 
15582 	return error;
15583 }
15584 
15585 void lpfc_dmp_dbg(struct lpfc_hba *phba)
15586 {
15587 	unsigned int start_idx;
15588 	unsigned int dbg_cnt;
15589 	unsigned int temp_idx;
15590 	int i;
15591 	int j = 0;
15592 	unsigned long rem_nsec;
15593 
15594 	if (atomic_cmpxchg(&phba->dbg_log_dmping, 0, 1) != 0)
15595 		return;
15596 
15597 	start_idx = (unsigned int)atomic_read(&phba->dbg_log_idx) % DBG_LOG_SZ;
15598 	dbg_cnt = (unsigned int)atomic_read(&phba->dbg_log_cnt);
15599 	if (!dbg_cnt)
15600 		goto out;
15601 	temp_idx = start_idx;
15602 	if (dbg_cnt >= DBG_LOG_SZ) {
15603 		dbg_cnt = DBG_LOG_SZ;
15604 		temp_idx -= 1;
15605 	} else {
15606 		if ((start_idx + dbg_cnt) > (DBG_LOG_SZ - 1)) {
15607 			temp_idx = (start_idx + dbg_cnt) % DBG_LOG_SZ;
15608 		} else {
15609 			if (start_idx < dbg_cnt)
15610 				start_idx = DBG_LOG_SZ - (dbg_cnt - start_idx);
15611 			else
15612 				start_idx -= dbg_cnt;
15613 		}
15614 	}
15615 	dev_info(&phba->pcidev->dev, "start %d end %d cnt %d\n",
15616 		 start_idx, temp_idx, dbg_cnt);
15617 
15618 	for (i = 0; i < dbg_cnt; i++) {
15619 		if ((start_idx + i) < DBG_LOG_SZ)
15620 			temp_idx = (start_idx + i) % DBG_LOG_SZ;
15621 		else
15622 			temp_idx = j++;
15623 		rem_nsec = do_div(phba->dbg_log[temp_idx].t_ns, NSEC_PER_SEC);
15624 		dev_info(&phba->pcidev->dev, "%d: [%5lu.%06lu] %s",
15625 			 temp_idx,
15626 			 (unsigned long)phba->dbg_log[temp_idx].t_ns,
15627 			 rem_nsec / 1000,
15628 			 phba->dbg_log[temp_idx].log);
15629 	}
15630 out:
15631 	atomic_set(&phba->dbg_log_cnt, 0);
15632 	atomic_set(&phba->dbg_log_dmping, 0);
15633 }
15634 
15635 __printf(2, 3)
15636 void lpfc_dbg_print(struct lpfc_hba *phba, const char *fmt, ...)
15637 {
15638 	unsigned int idx;
15639 	va_list args;
15640 	int dbg_dmping = atomic_read(&phba->dbg_log_dmping);
15641 	struct va_format vaf;
15642 
15643 
15644 	va_start(args, fmt);
15645 	if (unlikely(dbg_dmping)) {
15646 		vaf.fmt = fmt;
15647 		vaf.va = &args;
15648 		dev_info(&phba->pcidev->dev, "%pV", &vaf);
15649 		va_end(args);
15650 		return;
15651 	}
15652 	idx = (unsigned int)atomic_fetch_add(1, &phba->dbg_log_idx) %
15653 		DBG_LOG_SZ;
15654 
15655 	atomic_inc(&phba->dbg_log_cnt);
15656 
15657 	vscnprintf(phba->dbg_log[idx].log,
15658 		   sizeof(phba->dbg_log[idx].log), fmt, args);
15659 	va_end(args);
15660 
15661 	phba->dbg_log[idx].t_ns = local_clock();
15662 }
15663 
15664 /**
15665  * lpfc_exit - lpfc module removal routine
15666  *
15667  * This routine is invoked when the lpfc module is removed from the kernel.
15668  * The special kernel macro module_exit() is used to indicate the role of
15669  * this routine to the kernel as lpfc module exit point.
15670  */
15671 static void __exit
15672 lpfc_exit(void)
15673 {
15674 	misc_deregister(&lpfc_mgmt_dev);
15675 	pci_unregister_driver(&lpfc_driver);
15676 	cpuhp_remove_multi_state(lpfc_cpuhp_state);
15677 	fc_release_transport(lpfc_transport_template);
15678 	fc_release_transport(lpfc_vport_transport_template);
15679 	idr_destroy(&lpfc_hba_index);
15680 }
15681 
15682 module_init(lpfc_init);
15683 module_exit(lpfc_exit);
15684 MODULE_LICENSE("GPL");
15685 MODULE_DESCRIPTION(LPFC_MODULE_DESC);
15686 MODULE_AUTHOR("Broadcom");
15687 MODULE_VERSION("0:" LPFC_DRIVER_VERSION);
15688