xref: /linux/drivers/scsi/lpfc/lpfc_init.c (revision 44b6169ada7fe3cf4cb91e6b06019eaa22719f28)
1 /*******************************************************************
2  * This file is part of the Emulex Linux Device Driver for         *
3  * Fibre Channel Host Bus Adapters.                                *
4  * Copyright (C) 2017-2025 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/sched/clock.h>
34 #include <linux/ctype.h>
35 #include <linux/slab.h>
36 #include <linux/firmware.h>
37 #include <linux/miscdevice.h>
38 #include <linux/percpu.h>
39 #include <linux/irq.h>
40 #include <linux/bitops.h>
41 #include <linux/crash_dump.h>
42 #include <linux/cpu.h>
43 #include <linux/cpuhotplug.h>
44 
45 #include <scsi/scsi.h>
46 #include <scsi/scsi_device.h>
47 #include <scsi/scsi_host.h>
48 #include <scsi/scsi_transport_fc.h>
49 #include <scsi/scsi_tcq.h>
50 #include <scsi/fc/fc_fs.h>
51 
52 #include "lpfc_hw4.h"
53 #include "lpfc_hw.h"
54 #include "lpfc_sli.h"
55 #include "lpfc_sli4.h"
56 #include "lpfc_nl.h"
57 #include "lpfc_disc.h"
58 #include "lpfc.h"
59 #include "lpfc_scsi.h"
60 #include "lpfc_nvme.h"
61 #include "lpfc_logmsg.h"
62 #include "lpfc_crtn.h"
63 #include "lpfc_vport.h"
64 #include "lpfc_version.h"
65 #include "lpfc_ids.h"
66 
67 static enum cpuhp_state lpfc_cpuhp_state;
68 /* Used when mapping IRQ vectors in a driver centric manner */
69 static uint32_t lpfc_present_cpu;
70 static bool lpfc_pldv_detect;
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 static void lpfc_sli4_async_cmstat_evt(struct lpfc_hba *phba);
98 static void lpfc_sli4_prep_dev_for_reset(struct lpfc_hba *phba);
99 
100 static struct scsi_transport_template *lpfc_transport_template = NULL;
101 static struct scsi_transport_template *lpfc_vport_transport_template = NULL;
102 static DEFINE_IDR(lpfc_hba_index);
103 #define LPFC_NVMET_BUF_POST 254
104 static int lpfc_vmid_res_alloc(struct lpfc_hba *phba, struct lpfc_vport *vport);
105 static void lpfc_cgn_update_tstamp(struct lpfc_hba *phba, struct lpfc_cgn_ts *ts);
106 
107 /**
108  * lpfc_config_port_prep - Perform lpfc initialization prior to config port
109  * @phba: pointer to lpfc hba data structure.
110  *
111  * This routine will do LPFC initialization prior to issuing the CONFIG_PORT
112  * mailbox command. It retrieves the revision information from the HBA and
113  * collects the Vital Product Data (VPD) about the HBA for preparing the
114  * configuration of the HBA.
115  *
116  * Return codes:
117  *   0 - success.
118  *   -ERESTART - requests the SLI layer to reset the HBA and try again.
119  *   Any other value - indicates an error.
120  **/
121 int
122 lpfc_config_port_prep(struct lpfc_hba *phba)
123 {
124 	lpfc_vpd_t *vp = &phba->vpd;
125 	int i = 0, rc;
126 	LPFC_MBOXQ_t *pmb;
127 	MAILBOX_t *mb;
128 	char *lpfc_vpd_data = NULL;
129 	uint16_t offset = 0;
130 	static char licensed[56] =
131 		    "key unlock for use with gnu public licensed code only\0";
132 	static int init_key = 1;
133 
134 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
135 	if (!pmb) {
136 		phba->link_state = LPFC_HBA_ERROR;
137 		return -ENOMEM;
138 	}
139 
140 	mb = &pmb->u.mb;
141 	phba->link_state = LPFC_INIT_MBX_CMDS;
142 
143 	if (lpfc_is_LC_HBA(phba->pcidev->device)) {
144 		if (init_key) {
145 			uint32_t *ptext = (uint32_t *) licensed;
146 
147 			for (i = 0; i < 56; i += sizeof (uint32_t), ptext++)
148 				*ptext = cpu_to_be32(*ptext);
149 			init_key = 0;
150 		}
151 
152 		lpfc_read_nv(phba, pmb);
153 		memset((char*)mb->un.varRDnvp.rsvd3, 0,
154 			sizeof (mb->un.varRDnvp.rsvd3));
155 		memcpy((char*)mb->un.varRDnvp.rsvd3, licensed,
156 			 sizeof (licensed));
157 
158 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
159 
160 		if (rc != MBX_SUCCESS) {
161 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
162 					"0324 Config Port initialization "
163 					"error, mbxCmd x%x READ_NVPARM, "
164 					"mbxStatus x%x\n",
165 					mb->mbxCommand, mb->mbxStatus);
166 			mempool_free(pmb, phba->mbox_mem_pool);
167 			return -ERESTART;
168 		}
169 		memcpy(phba->wwnn, (char *)mb->un.varRDnvp.nodename,
170 		       sizeof(phba->wwnn));
171 		memcpy(phba->wwpn, (char *)mb->un.varRDnvp.portname,
172 		       sizeof(phba->wwpn));
173 	}
174 
175 	/*
176 	 * Clear all option bits except LPFC_SLI3_BG_ENABLED,
177 	 * which was already set in lpfc_get_cfgparam()
178 	 */
179 	phba->sli3_options &= (uint32_t)LPFC_SLI3_BG_ENABLED;
180 
181 	/* Setup and issue mailbox READ REV command */
182 	lpfc_read_rev(phba, pmb);
183 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
184 	if (rc != MBX_SUCCESS) {
185 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
186 				"0439 Adapter failed to init, mbxCmd x%x "
187 				"READ_REV, mbxStatus x%x\n",
188 				mb->mbxCommand, mb->mbxStatus);
189 		mempool_free( pmb, phba->mbox_mem_pool);
190 		return -ERESTART;
191 	}
192 
193 
194 	/*
195 	 * The value of rr must be 1 since the driver set the cv field to 1.
196 	 * This setting requires the FW to set all revision fields.
197 	 */
198 	if (mb->un.varRdRev.rr == 0) {
199 		vp->rev.rBit = 0;
200 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
201 				"0440 Adapter failed to init, READ_REV has "
202 				"missing revision information.\n");
203 		mempool_free(pmb, phba->mbox_mem_pool);
204 		return -ERESTART;
205 	}
206 
207 	if (phba->sli_rev == 3 && !mb->un.varRdRev.v3rsp) {
208 		mempool_free(pmb, phba->mbox_mem_pool);
209 		return -EINVAL;
210 	}
211 
212 	/* Save information as VPD data */
213 	vp->rev.rBit = 1;
214 	memcpy(&vp->sli3Feat, &mb->un.varRdRev.sli3Feat, sizeof(uint32_t));
215 	vp->rev.sli1FwRev = mb->un.varRdRev.sli1FwRev;
216 	memcpy(vp->rev.sli1FwName, (char*) mb->un.varRdRev.sli1FwName, 16);
217 	vp->rev.sli2FwRev = mb->un.varRdRev.sli2FwRev;
218 	memcpy(vp->rev.sli2FwName, (char *) mb->un.varRdRev.sli2FwName, 16);
219 	vp->rev.biuRev = mb->un.varRdRev.biuRev;
220 	vp->rev.smRev = mb->un.varRdRev.smRev;
221 	vp->rev.smFwRev = mb->un.varRdRev.un.smFwRev;
222 	vp->rev.endecRev = mb->un.varRdRev.endecRev;
223 	vp->rev.fcphHigh = mb->un.varRdRev.fcphHigh;
224 	vp->rev.fcphLow = mb->un.varRdRev.fcphLow;
225 	vp->rev.feaLevelHigh = mb->un.varRdRev.feaLevelHigh;
226 	vp->rev.feaLevelLow = mb->un.varRdRev.feaLevelLow;
227 	vp->rev.postKernRev = mb->un.varRdRev.postKernRev;
228 	vp->rev.opFwRev = mb->un.varRdRev.opFwRev;
229 
230 	/* If the sli feature level is less then 9, we must
231 	 * tear down all RPIs and VPIs on link down if NPIV
232 	 * is enabled.
233 	 */
234 	if (vp->rev.feaLevelHigh < 9)
235 		phba->sli3_options |= LPFC_SLI3_VPORT_TEARDOWN;
236 
237 	if (lpfc_is_LC_HBA(phba->pcidev->device))
238 		memcpy(phba->RandomData, (char *)&mb->un.varWords[24],
239 						sizeof (phba->RandomData));
240 
241 	/* Get adapter VPD information */
242 	lpfc_vpd_data = kmalloc(DMP_VPD_SIZE, GFP_KERNEL);
243 	if (!lpfc_vpd_data)
244 		goto out_free_mbox;
245 	do {
246 		lpfc_dump_mem(phba, pmb, offset, DMP_REGION_VPD);
247 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
248 
249 		if (rc != MBX_SUCCESS) {
250 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
251 					"0441 VPD not present on adapter, "
252 					"mbxCmd x%x DUMP VPD, mbxStatus x%x\n",
253 					mb->mbxCommand, mb->mbxStatus);
254 			mb->un.varDmp.word_cnt = 0;
255 		}
256 		/* dump mem may return a zero when finished or we got a
257 		 * mailbox error, either way we are done.
258 		 */
259 		if (mb->un.varDmp.word_cnt == 0)
260 			break;
261 
262 		if (mb->un.varDmp.word_cnt > DMP_VPD_SIZE - offset)
263 			mb->un.varDmp.word_cnt = DMP_VPD_SIZE - offset;
264 		lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
265 				      lpfc_vpd_data + offset,
266 				      mb->un.varDmp.word_cnt);
267 		offset += mb->un.varDmp.word_cnt;
268 	} while (mb->un.varDmp.word_cnt && offset < DMP_VPD_SIZE);
269 
270 	lpfc_parse_vpd(phba, lpfc_vpd_data, offset);
271 
272 	kfree(lpfc_vpd_data);
273 out_free_mbox:
274 	mempool_free(pmb, phba->mbox_mem_pool);
275 	return 0;
276 }
277 
278 /**
279  * lpfc_config_async_cmpl - Completion handler for config async event mbox cmd
280  * @phba: pointer to lpfc hba data structure.
281  * @pmboxq: pointer to the driver internal queue element for mailbox command.
282  *
283  * This is the completion handler for driver's configuring asynchronous event
284  * mailbox command to the device. If the mailbox command returns successfully,
285  * it will set internal async event support flag to 1; otherwise, it will
286  * set internal async event support flag to 0.
287  **/
288 static void
289 lpfc_config_async_cmpl(struct lpfc_hba * phba, LPFC_MBOXQ_t * pmboxq)
290 {
291 	if (pmboxq->u.mb.mbxStatus == MBX_SUCCESS)
292 		phba->temp_sensor_support = 1;
293 	else
294 		phba->temp_sensor_support = 0;
295 	mempool_free(pmboxq, phba->mbox_mem_pool);
296 	return;
297 }
298 
299 /**
300  * lpfc_dump_wakeup_param_cmpl - dump memory mailbox command completion handler
301  * @phba: pointer to lpfc hba data structure.
302  * @pmboxq: pointer to the driver internal queue element for mailbox command.
303  *
304  * This is the completion handler for dump mailbox command for getting
305  * wake up parameters. When this command complete, the response contain
306  * Option rom version of the HBA. This function translate the version number
307  * into a human readable string and store it in OptionROMVersion.
308  **/
309 static void
310 lpfc_dump_wakeup_param_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
311 {
312 	struct prog_id *prg;
313 	uint32_t prog_id_word;
314 	char dist = ' ';
315 	/* character array used for decoding dist type. */
316 	char dist_char[] = "nabx";
317 
318 	if (pmboxq->u.mb.mbxStatus != MBX_SUCCESS) {
319 		mempool_free(pmboxq, phba->mbox_mem_pool);
320 		return;
321 	}
322 
323 	prg = (struct prog_id *) &prog_id_word;
324 
325 	/* word 7 contain option rom version */
326 	prog_id_word = pmboxq->u.mb.un.varWords[7];
327 
328 	/* Decode the Option rom version word to a readable string */
329 	dist = dist_char[prg->dist];
330 
331 	if ((prg->dist == 3) && (prg->num == 0))
332 		snprintf(phba->OptionROMVersion, 32, "%d.%d%d",
333 			prg->ver, prg->rev, prg->lev);
334 	else
335 		snprintf(phba->OptionROMVersion, 32, "%d.%d%d%c%d",
336 			prg->ver, prg->rev, prg->lev,
337 			dist, prg->num);
338 	mempool_free(pmboxq, phba->mbox_mem_pool);
339 	return;
340 }
341 
342 /**
343  * lpfc_update_vport_wwn - Updates the fc_nodename, fc_portname,
344  * @vport: pointer to lpfc vport data structure.
345  *
346  *
347  * Return codes
348  *   None.
349  **/
350 void
351 lpfc_update_vport_wwn(struct lpfc_vport *vport)
352 {
353 	struct lpfc_hba *phba = vport->phba;
354 
355 	/*
356 	 * If the name is empty or there exists a soft name
357 	 * then copy the service params name, otherwise use the fc name
358 	 */
359 	if (vport->fc_nodename.u.wwn[0] == 0)
360 		memcpy(&vport->fc_nodename, &vport->fc_sparam.nodeName,
361 			sizeof(struct lpfc_name));
362 	else
363 		memcpy(&vport->fc_sparam.nodeName, &vport->fc_nodename,
364 			sizeof(struct lpfc_name));
365 
366 	/*
367 	 * If the port name has changed, then set the Param changes flag
368 	 * to unreg the login
369 	 */
370 	if (vport->fc_portname.u.wwn[0] != 0 &&
371 		memcmp(&vport->fc_portname, &vport->fc_sparam.portName,
372 		       sizeof(struct lpfc_name))) {
373 		vport->vport_flag |= FAWWPN_PARAM_CHG;
374 
375 		if (phba->sli_rev == LPFC_SLI_REV4 &&
376 		    vport->port_type == LPFC_PHYSICAL_PORT &&
377 		    phba->sli4_hba.fawwpn_flag & LPFC_FAWWPN_FABRIC) {
378 			if (!(phba->sli4_hba.fawwpn_flag & LPFC_FAWWPN_CONFIG))
379 				phba->sli4_hba.fawwpn_flag &=
380 						~LPFC_FAWWPN_FABRIC;
381 			lpfc_printf_log(phba, KERN_INFO,
382 					LOG_SLI | LOG_DISCOVERY | LOG_ELS,
383 					"2701 FA-PWWN change WWPN from %llx to "
384 					"%llx: vflag x%x fawwpn_flag x%x\n",
385 					wwn_to_u64(vport->fc_portname.u.wwn),
386 					wwn_to_u64
387 					   (vport->fc_sparam.portName.u.wwn),
388 					vport->vport_flag,
389 					phba->sli4_hba.fawwpn_flag);
390 			memcpy(&vport->fc_portname, &vport->fc_sparam.portName,
391 			       sizeof(struct lpfc_name));
392 		}
393 	}
394 
395 	if (vport->fc_portname.u.wwn[0] == 0)
396 		memcpy(&vport->fc_portname, &vport->fc_sparam.portName,
397 		       sizeof(struct lpfc_name));
398 	else
399 		memcpy(&vport->fc_sparam.portName, &vport->fc_portname,
400 		       sizeof(struct lpfc_name));
401 }
402 
403 /**
404  * lpfc_config_port_post - Perform lpfc initialization after config port
405  * @phba: pointer to lpfc hba data structure.
406  *
407  * This routine will do LPFC initialization after the CONFIG_PORT mailbox
408  * command call. It performs all internal resource and state setups on the
409  * port: post IOCB buffers, enable appropriate host interrupt attentions,
410  * ELS ring timers, etc.
411  *
412  * Return codes
413  *   0 - success.
414  *   Any other value - error.
415  **/
416 int
417 lpfc_config_port_post(struct lpfc_hba *phba)
418 {
419 	struct lpfc_vport *vport = phba->pport;
420 	struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
421 	LPFC_MBOXQ_t *pmb;
422 	MAILBOX_t *mb;
423 	struct lpfc_dmabuf *mp;
424 	struct lpfc_sli *psli = &phba->sli;
425 	uint32_t status, timeout;
426 	int i, j;
427 	int rc;
428 
429 	spin_lock_irq(&phba->hbalock);
430 	/*
431 	 * If the Config port completed correctly the HBA is not
432 	 * over heated any more.
433 	 */
434 	if (phba->over_temp_state == HBA_OVER_TEMP)
435 		phba->over_temp_state = HBA_NORMAL_TEMP;
436 	spin_unlock_irq(&phba->hbalock);
437 
438 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
439 	if (!pmb) {
440 		phba->link_state = LPFC_HBA_ERROR;
441 		return -ENOMEM;
442 	}
443 	mb = &pmb->u.mb;
444 
445 	/* Get login parameters for NID.  */
446 	rc = lpfc_read_sparam(phba, pmb, 0);
447 	if (rc) {
448 		mempool_free(pmb, phba->mbox_mem_pool);
449 		return -ENOMEM;
450 	}
451 
452 	pmb->vport = vport;
453 	if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
454 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
455 				"0448 Adapter failed init, mbxCmd x%x "
456 				"READ_SPARM mbxStatus x%x\n",
457 				mb->mbxCommand, mb->mbxStatus);
458 		phba->link_state = LPFC_HBA_ERROR;
459 		lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
460 		return -EIO;
461 	}
462 
463 	mp = pmb->ctx_buf;
464 
465 	/* This dmabuf was allocated by lpfc_read_sparam. The dmabuf is no
466 	 * longer needed.  Prevent unintended ctx_buf access as the mbox is
467 	 * reused.
468 	 */
469 	memcpy(&vport->fc_sparam, mp->virt, sizeof (struct serv_parm));
470 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
471 	kfree(mp);
472 	pmb->ctx_buf = NULL;
473 	lpfc_update_vport_wwn(vport);
474 
475 	/* Update the fc_host data structures with new wwn. */
476 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
477 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
478 	fc_host_max_npiv_vports(shost) = phba->max_vpi;
479 
480 	/* If no serial number in VPD data, use low 6 bytes of WWNN */
481 	/* This should be consolidated into parse_vpd ? - mr */
482 	if (phba->SerialNumber[0] == 0) {
483 		uint8_t *outptr;
484 
485 		outptr = &vport->fc_nodename.u.s.IEEE[0];
486 		for (i = 0; i < 12; i++) {
487 			status = *outptr++;
488 			j = ((status & 0xf0) >> 4);
489 			if (j <= 9)
490 				phba->SerialNumber[i] =
491 				    (char)((uint8_t) 0x30 + (uint8_t) j);
492 			else
493 				phba->SerialNumber[i] =
494 				    (char)((uint8_t) 0x61 + (uint8_t) (j - 10));
495 			i++;
496 			j = (status & 0xf);
497 			if (j <= 9)
498 				phba->SerialNumber[i] =
499 				    (char)((uint8_t) 0x30 + (uint8_t) j);
500 			else
501 				phba->SerialNumber[i] =
502 				    (char)((uint8_t) 0x61 + (uint8_t) (j - 10));
503 		}
504 	}
505 
506 	lpfc_read_config(phba, pmb);
507 	pmb->vport = vport;
508 	if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
509 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
510 				"0453 Adapter failed to init, mbxCmd x%x "
511 				"READ_CONFIG, mbxStatus x%x\n",
512 				mb->mbxCommand, mb->mbxStatus);
513 		phba->link_state = LPFC_HBA_ERROR;
514 		mempool_free( pmb, phba->mbox_mem_pool);
515 		return -EIO;
516 	}
517 
518 	/* Check if the port is disabled */
519 	lpfc_sli_read_link_ste(phba);
520 
521 	/* Reset the DFT_HBA_Q_DEPTH to the max xri  */
522 	if (phba->cfg_hba_queue_depth > mb->un.varRdConfig.max_xri) {
523 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
524 				"3359 HBA queue depth changed from %d to %d\n",
525 				phba->cfg_hba_queue_depth,
526 				mb->un.varRdConfig.max_xri);
527 		phba->cfg_hba_queue_depth = mb->un.varRdConfig.max_xri;
528 	}
529 
530 	phba->lmt = mb->un.varRdConfig.lmt;
531 
532 	/* Get the default values for Model Name and Description */
533 	lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
534 
535 	phba->link_state = LPFC_LINK_DOWN;
536 
537 	/* Only process IOCBs on ELS ring till hba_state is READY */
538 	if (psli->sli3_ring[LPFC_EXTRA_RING].sli.sli3.cmdringaddr)
539 		psli->sli3_ring[LPFC_EXTRA_RING].flag |= LPFC_STOP_IOCB_EVENT;
540 	if (psli->sli3_ring[LPFC_FCP_RING].sli.sli3.cmdringaddr)
541 		psli->sli3_ring[LPFC_FCP_RING].flag |= LPFC_STOP_IOCB_EVENT;
542 
543 	/* Post receive buffers for desired rings */
544 	if (phba->sli_rev != 3)
545 		lpfc_post_rcv_buf(phba);
546 
547 	/*
548 	 * Configure HBA MSI-X attention conditions to messages if MSI-X mode
549 	 */
550 	if (phba->intr_type == MSIX) {
551 		rc = lpfc_config_msi(phba, pmb);
552 		if (rc) {
553 			mempool_free(pmb, phba->mbox_mem_pool);
554 			return -EIO;
555 		}
556 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
557 		if (rc != MBX_SUCCESS) {
558 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
559 					"0352 Config MSI mailbox command "
560 					"failed, mbxCmd x%x, mbxStatus x%x\n",
561 					pmb->u.mb.mbxCommand,
562 					pmb->u.mb.mbxStatus);
563 			mempool_free(pmb, phba->mbox_mem_pool);
564 			return -EIO;
565 		}
566 	}
567 
568 	spin_lock_irq(&phba->hbalock);
569 	/* Initialize ERATT handling flag */
570 	clear_bit(HBA_ERATT_HANDLED, &phba->hba_flag);
571 
572 	/* Enable appropriate host interrupts */
573 	if (lpfc_readl(phba->HCregaddr, &status)) {
574 		spin_unlock_irq(&phba->hbalock);
575 		return -EIO;
576 	}
577 	status |= HC_MBINT_ENA | HC_ERINT_ENA | HC_LAINT_ENA;
578 	if (psli->num_rings > 0)
579 		status |= HC_R0INT_ENA;
580 	if (psli->num_rings > 1)
581 		status |= HC_R1INT_ENA;
582 	if (psli->num_rings > 2)
583 		status |= HC_R2INT_ENA;
584 	if (psli->num_rings > 3)
585 		status |= HC_R3INT_ENA;
586 
587 	if ((phba->cfg_poll & ENABLE_FCP_RING_POLLING) &&
588 	    (phba->cfg_poll & DISABLE_FCP_RING_INT))
589 		status &= ~(HC_R0INT_ENA);
590 
591 	writel(status, phba->HCregaddr);
592 	readl(phba->HCregaddr); /* flush */
593 	spin_unlock_irq(&phba->hbalock);
594 
595 	/* Set up ring-0 (ELS) timer */
596 	timeout = phba->fc_ratov * 2;
597 	mod_timer(&vport->els_tmofunc,
598 		  jiffies + secs_to_jiffies(timeout));
599 	/* Set up heart beat (HB) timer */
600 	mod_timer(&phba->hb_tmofunc,
601 		  jiffies + secs_to_jiffies(LPFC_HB_MBOX_INTERVAL));
602 	clear_bit(HBA_HBEAT_INP, &phba->hba_flag);
603 	clear_bit(HBA_HBEAT_TMO, &phba->hba_flag);
604 	phba->last_completion_time = jiffies;
605 	/* Set up error attention (ERATT) polling timer */
606 	mod_timer(&phba->eratt_poll,
607 		  jiffies + secs_to_jiffies(phba->eratt_poll_interval));
608 
609 	if (test_bit(LINK_DISABLED, &phba->hba_flag)) {
610 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
611 				"2598 Adapter Link is disabled.\n");
612 		lpfc_down_link(phba, pmb);
613 		pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
614 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
615 		if ((rc != MBX_SUCCESS) && (rc != MBX_BUSY)) {
616 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
617 					"2599 Adapter failed to issue DOWN_LINK"
618 					" mbox command rc 0x%x\n", rc);
619 
620 			mempool_free(pmb, phba->mbox_mem_pool);
621 			return -EIO;
622 		}
623 	} else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
624 		mempool_free(pmb, phba->mbox_mem_pool);
625 		rc = phba->lpfc_hba_init_link(phba, MBX_NOWAIT);
626 		if (rc)
627 			return rc;
628 	}
629 	/* MBOX buffer will be freed in mbox compl */
630 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
631 	if (!pmb) {
632 		phba->link_state = LPFC_HBA_ERROR;
633 		return -ENOMEM;
634 	}
635 
636 	lpfc_config_async(phba, pmb, LPFC_ELS_RING);
637 	pmb->mbox_cmpl = lpfc_config_async_cmpl;
638 	pmb->vport = phba->pport;
639 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
640 
641 	if ((rc != MBX_BUSY) && (rc != MBX_SUCCESS)) {
642 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
643 				"0456 Adapter failed to issue "
644 				"ASYNCEVT_ENABLE mbox status x%x\n",
645 				rc);
646 		mempool_free(pmb, phba->mbox_mem_pool);
647 	}
648 
649 	/* Get Option rom version */
650 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
651 	if (!pmb) {
652 		phba->link_state = LPFC_HBA_ERROR;
653 		return -ENOMEM;
654 	}
655 
656 	lpfc_dump_wakeup_param(phba, pmb);
657 	pmb->mbox_cmpl = lpfc_dump_wakeup_param_cmpl;
658 	pmb->vport = phba->pport;
659 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
660 
661 	if ((rc != MBX_BUSY) && (rc != MBX_SUCCESS)) {
662 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
663 				"0435 Adapter failed "
664 				"to get Option ROM version status x%x\n", rc);
665 		mempool_free(pmb, phba->mbox_mem_pool);
666 	}
667 
668 	return 0;
669 }
670 
671 /**
672  * lpfc_sli4_refresh_params - update driver copy of params.
673  * @phba: Pointer to HBA context object.
674  *
675  * This is called to refresh driver copy of dynamic fields from the
676  * common_get_sli4_parameters descriptor.
677  **/
678 int
679 lpfc_sli4_refresh_params(struct lpfc_hba *phba)
680 {
681 	LPFC_MBOXQ_t *mboxq;
682 	struct lpfc_mqe *mqe;
683 	struct lpfc_sli4_parameters *mbx_sli4_parameters;
684 	int length, rc;
685 
686 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
687 	if (!mboxq)
688 		return -ENOMEM;
689 
690 	mqe = &mboxq->u.mqe;
691 	/* Read the port's SLI4 Config Parameters */
692 	length = (sizeof(struct lpfc_mbx_get_sli4_parameters) -
693 		  sizeof(struct lpfc_sli4_cfg_mhdr));
694 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
695 			 LPFC_MBOX_OPCODE_GET_SLI4_PARAMETERS,
696 			 length, LPFC_SLI4_MBX_EMBED);
697 
698 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
699 	if (unlikely(rc)) {
700 		mempool_free(mboxq, phba->mbox_mem_pool);
701 		return rc;
702 	}
703 	mbx_sli4_parameters = &mqe->un.get_sli4_parameters.sli4_parameters;
704 	phba->sli4_hba.pc_sli4_params.mi_cap =
705 		bf_get(cfg_mi_ver, mbx_sli4_parameters);
706 
707 	/* Are we forcing MI off via module parameter? */
708 	if (phba->cfg_enable_mi)
709 		phba->sli4_hba.pc_sli4_params.mi_ver =
710 			bf_get(cfg_mi_ver, mbx_sli4_parameters);
711 	else
712 		phba->sli4_hba.pc_sli4_params.mi_ver = 0;
713 
714 	phba->sli4_hba.pc_sli4_params.cmf =
715 			bf_get(cfg_cmf, mbx_sli4_parameters);
716 	phba->sli4_hba.pc_sli4_params.pls =
717 			bf_get(cfg_pvl, mbx_sli4_parameters);
718 
719 	mempool_free(mboxq, phba->mbox_mem_pool);
720 	return rc;
721 }
722 
723 /**
724  * lpfc_hba_init_link - Initialize the FC link
725  * @phba: pointer to lpfc hba data structure.
726  * @flag: mailbox command issue mode - either MBX_POLL or MBX_NOWAIT
727  *
728  * This routine will issue the INIT_LINK mailbox command call.
729  * It is available to other drivers through the lpfc_hba data
730  * structure for use as a delayed link up mechanism with the
731  * module parameter lpfc_suppress_link_up.
732  *
733  * Return code
734  *		0 - success
735  *		Any other value - error
736  **/
737 static int
738 lpfc_hba_init_link(struct lpfc_hba *phba, uint32_t flag)
739 {
740 	return lpfc_hba_init_link_fc_topology(phba, phba->cfg_topology, flag);
741 }
742 
743 /**
744  * lpfc_hba_init_link_fc_topology - Initialize FC link with desired topology
745  * @phba: pointer to lpfc hba data structure.
746  * @fc_topology: desired fc topology.
747  * @flag: mailbox command issue mode - either MBX_POLL or MBX_NOWAIT
748  *
749  * This routine will issue the INIT_LINK mailbox command call.
750  * It is available to other drivers through the lpfc_hba data
751  * structure for use as a delayed link up mechanism with the
752  * module parameter lpfc_suppress_link_up.
753  *
754  * Return code
755  *              0 - success
756  *              Any other value - error
757  **/
758 int
759 lpfc_hba_init_link_fc_topology(struct lpfc_hba *phba, uint32_t fc_topology,
760 			       uint32_t flag)
761 {
762 	struct lpfc_vport *vport = phba->pport;
763 	LPFC_MBOXQ_t *pmb;
764 	MAILBOX_t *mb;
765 	int rc;
766 
767 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
768 	if (!pmb) {
769 		phba->link_state = LPFC_HBA_ERROR;
770 		return -ENOMEM;
771 	}
772 	mb = &pmb->u.mb;
773 	pmb->vport = vport;
774 
775 	if ((phba->cfg_link_speed > LPFC_USER_LINK_SPEED_MAX) ||
776 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_1G) &&
777 	     !(phba->lmt & LMT_1Gb)) ||
778 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_2G) &&
779 	     !(phba->lmt & LMT_2Gb)) ||
780 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_4G) &&
781 	     !(phba->lmt & LMT_4Gb)) ||
782 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_8G) &&
783 	     !(phba->lmt & LMT_8Gb)) ||
784 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_10G) &&
785 	     !(phba->lmt & LMT_10Gb)) ||
786 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_16G) &&
787 	     !(phba->lmt & LMT_16Gb)) ||
788 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_32G) &&
789 	     !(phba->lmt & LMT_32Gb)) ||
790 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_64G) &&
791 	     !(phba->lmt & LMT_64Gb))) {
792 		/* Reset link speed to auto */
793 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
794 				"1302 Invalid speed for this board:%d "
795 				"Reset link speed to auto.\n",
796 				phba->cfg_link_speed);
797 			phba->cfg_link_speed = LPFC_USER_LINK_SPEED_AUTO;
798 	}
799 	lpfc_init_link(phba, pmb, fc_topology, phba->cfg_link_speed);
800 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
801 	if (phba->sli_rev < LPFC_SLI_REV4)
802 		lpfc_set_loopback_flag(phba);
803 	rc = lpfc_sli_issue_mbox(phba, pmb, flag);
804 	if ((rc != MBX_BUSY) && (rc != MBX_SUCCESS)) {
805 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
806 				"0498 Adapter failed to init, mbxCmd x%x "
807 				"INIT_LINK, mbxStatus x%x\n",
808 				mb->mbxCommand, mb->mbxStatus);
809 		if (phba->sli_rev <= LPFC_SLI_REV3) {
810 			/* Clear all interrupt enable conditions */
811 			writel(0, phba->HCregaddr);
812 			readl(phba->HCregaddr); /* flush */
813 			/* Clear all pending interrupts */
814 			writel(0xffffffff, phba->HAregaddr);
815 			readl(phba->HAregaddr); /* flush */
816 		}
817 		phba->link_state = LPFC_HBA_ERROR;
818 		if (rc != MBX_BUSY || flag == MBX_POLL)
819 			mempool_free(pmb, phba->mbox_mem_pool);
820 		return -EIO;
821 	}
822 	phba->cfg_suppress_link_up = LPFC_INITIALIZE_LINK;
823 	if (flag == MBX_POLL)
824 		mempool_free(pmb, phba->mbox_mem_pool);
825 
826 	return 0;
827 }
828 
829 /**
830  * lpfc_hba_down_link - this routine downs the FC link
831  * @phba: pointer to lpfc hba data structure.
832  * @flag: mailbox command issue mode - either MBX_POLL or MBX_NOWAIT
833  *
834  * This routine will issue the DOWN_LINK mailbox command call.
835  * It is available to other drivers through the lpfc_hba data
836  * structure for use to stop the link.
837  *
838  * Return code
839  *		0 - success
840  *		Any other value - error
841  **/
842 static int
843 lpfc_hba_down_link(struct lpfc_hba *phba, uint32_t flag)
844 {
845 	LPFC_MBOXQ_t *pmb;
846 	int rc;
847 
848 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
849 	if (!pmb) {
850 		phba->link_state = LPFC_HBA_ERROR;
851 		return -ENOMEM;
852 	}
853 
854 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
855 			"0491 Adapter Link is disabled.\n");
856 	lpfc_down_link(phba, pmb);
857 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
858 	rc = lpfc_sli_issue_mbox(phba, pmb, flag);
859 	if ((rc != MBX_SUCCESS) && (rc != MBX_BUSY)) {
860 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
861 				"2522 Adapter failed to issue DOWN_LINK"
862 				" mbox command rc 0x%x\n", rc);
863 
864 		mempool_free(pmb, phba->mbox_mem_pool);
865 		return -EIO;
866 	}
867 	if (flag == MBX_POLL)
868 		mempool_free(pmb, phba->mbox_mem_pool);
869 
870 	return 0;
871 }
872 
873 /**
874  * lpfc_hba_down_prep - Perform lpfc uninitialization prior to HBA reset
875  * @phba: pointer to lpfc HBA data structure.
876  *
877  * This routine will do LPFC uninitialization before the HBA is reset when
878  * bringing down the SLI Layer.
879  *
880  * Return codes
881  *   0 - success.
882  *   Any other value - error.
883  **/
884 int
885 lpfc_hba_down_prep(struct lpfc_hba *phba)
886 {
887 	struct lpfc_vport **vports;
888 	int i;
889 
890 	if (phba->sli_rev <= LPFC_SLI_REV3) {
891 		/* Disable interrupts */
892 		writel(0, phba->HCregaddr);
893 		readl(phba->HCregaddr); /* flush */
894 	}
895 
896 	if (test_bit(FC_UNLOADING, &phba->pport->load_flag))
897 		lpfc_cleanup_discovery_resources(phba->pport);
898 	else {
899 		vports = lpfc_create_vport_work_array(phba);
900 		if (vports != NULL)
901 			for (i = 0; i <= phba->max_vports &&
902 				vports[i] != NULL; i++)
903 				lpfc_cleanup_discovery_resources(vports[i]);
904 		lpfc_destroy_vport_work_array(phba, vports);
905 	}
906 	return 0;
907 }
908 
909 /**
910  * lpfc_sli4_free_sp_events - Cleanup sp_queue_events to free
911  * rspiocb which got deferred
912  *
913  * @phba: pointer to lpfc HBA data structure.
914  *
915  * This routine will cleanup completed slow path events after HBA is reset
916  * when bringing down the SLI Layer.
917  *
918  *
919  * Return codes
920  *   void.
921  **/
922 static void
923 lpfc_sli4_free_sp_events(struct lpfc_hba *phba)
924 {
925 	struct lpfc_iocbq *rspiocbq;
926 	struct hbq_dmabuf *dmabuf;
927 	struct lpfc_cq_event *cq_event;
928 
929 	clear_bit(HBA_SP_QUEUE_EVT, &phba->hba_flag);
930 
931 	while (!list_empty(&phba->sli4_hba.sp_queue_event)) {
932 		/* Get the response iocb from the head of work queue */
933 		spin_lock_irq(&phba->hbalock);
934 		list_remove_head(&phba->sli4_hba.sp_queue_event,
935 				 cq_event, struct lpfc_cq_event, list);
936 		spin_unlock_irq(&phba->hbalock);
937 
938 		switch (bf_get(lpfc_wcqe_c_code, &cq_event->cqe.wcqe_cmpl)) {
939 		case CQE_CODE_COMPL_WQE:
940 			rspiocbq = container_of(cq_event, struct lpfc_iocbq,
941 						 cq_event);
942 			lpfc_sli_release_iocbq(phba, rspiocbq);
943 			break;
944 		case CQE_CODE_RECEIVE:
945 		case CQE_CODE_RECEIVE_V1:
946 			dmabuf = container_of(cq_event, struct hbq_dmabuf,
947 					      cq_event);
948 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
949 		}
950 	}
951 }
952 
953 /**
954  * lpfc_hba_free_post_buf - Perform lpfc uninitialization after HBA reset
955  * @phba: pointer to lpfc HBA data structure.
956  *
957  * This routine will cleanup posted ELS buffers after the HBA is reset
958  * when bringing down the SLI Layer.
959  *
960  *
961  * Return codes
962  *   void.
963  **/
964 static void
965 lpfc_hba_free_post_buf(struct lpfc_hba *phba)
966 {
967 	struct lpfc_sli *psli = &phba->sli;
968 	struct lpfc_sli_ring *pring;
969 	struct lpfc_dmabuf *mp, *next_mp;
970 	LIST_HEAD(buflist);
971 	int count;
972 
973 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)
974 		lpfc_sli_hbqbuf_free_all(phba);
975 	else {
976 		/* Cleanup preposted buffers on the ELS ring */
977 		pring = &psli->sli3_ring[LPFC_ELS_RING];
978 		spin_lock_irq(&phba->hbalock);
979 		list_splice_init(&pring->postbufq, &buflist);
980 		spin_unlock_irq(&phba->hbalock);
981 
982 		count = 0;
983 		list_for_each_entry_safe(mp, next_mp, &buflist, list) {
984 			list_del(&mp->list);
985 			count++;
986 			lpfc_mbuf_free(phba, mp->virt, mp->phys);
987 			kfree(mp);
988 		}
989 
990 		spin_lock_irq(&phba->hbalock);
991 		pring->postbufq_cnt -= count;
992 		spin_unlock_irq(&phba->hbalock);
993 	}
994 }
995 
996 /**
997  * lpfc_hba_clean_txcmplq - Perform lpfc uninitialization after HBA reset
998  * @phba: pointer to lpfc HBA data structure.
999  *
1000  * This routine will cleanup the txcmplq after the HBA is reset when bringing
1001  * down the SLI Layer.
1002  *
1003  * Return codes
1004  *   void
1005  **/
1006 static void
1007 lpfc_hba_clean_txcmplq(struct lpfc_hba *phba)
1008 {
1009 	struct lpfc_sli *psli = &phba->sli;
1010 	struct lpfc_queue *qp = NULL;
1011 	struct lpfc_sli_ring *pring;
1012 	LIST_HEAD(completions);
1013 	int i;
1014 	struct lpfc_iocbq *piocb, *next_iocb;
1015 
1016 	if (phba->sli_rev != LPFC_SLI_REV4) {
1017 		for (i = 0; i < psli->num_rings; i++) {
1018 			pring = &psli->sli3_ring[i];
1019 			spin_lock_irq(&phba->hbalock);
1020 			/* At this point in time the HBA is either reset or DOA
1021 			 * Nothing should be on txcmplq as it will
1022 			 * NEVER complete.
1023 			 */
1024 			list_splice_init(&pring->txcmplq, &completions);
1025 			pring->txcmplq_cnt = 0;
1026 			spin_unlock_irq(&phba->hbalock);
1027 
1028 			lpfc_sli_abort_iocb_ring(phba, pring);
1029 		}
1030 		/* Cancel all the IOCBs from the completions list */
1031 		lpfc_sli_cancel_iocbs(phba, &completions,
1032 				      IOSTAT_LOCAL_REJECT, IOERR_SLI_ABORTED);
1033 		return;
1034 	}
1035 	list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
1036 		pring = qp->pring;
1037 		if (!pring)
1038 			continue;
1039 		spin_lock_irq(&pring->ring_lock);
1040 		list_for_each_entry_safe(piocb, next_iocb,
1041 					 &pring->txcmplq, list)
1042 			piocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
1043 		list_splice_init(&pring->txcmplq, &completions);
1044 		pring->txcmplq_cnt = 0;
1045 		spin_unlock_irq(&pring->ring_lock);
1046 		lpfc_sli_abort_iocb_ring(phba, pring);
1047 	}
1048 	/* Cancel all the IOCBs from the completions list */
1049 	lpfc_sli_cancel_iocbs(phba, &completions,
1050 			      IOSTAT_LOCAL_REJECT, IOERR_SLI_ABORTED);
1051 }
1052 
1053 /**
1054  * lpfc_hba_down_post_s3 - Perform lpfc uninitialization after HBA reset
1055  * @phba: pointer to lpfc HBA data structure.
1056  *
1057  * This routine will do uninitialization after the HBA is reset when bring
1058  * down the SLI Layer.
1059  *
1060  * Return codes
1061  *   0 - success.
1062  *   Any other value - error.
1063  **/
1064 static int
1065 lpfc_hba_down_post_s3(struct lpfc_hba *phba)
1066 {
1067 	lpfc_hba_free_post_buf(phba);
1068 	lpfc_hba_clean_txcmplq(phba);
1069 	return 0;
1070 }
1071 
1072 /**
1073  * lpfc_hba_down_post_s4 - Perform lpfc uninitialization after HBA reset
1074  * @phba: pointer to lpfc HBA data structure.
1075  *
1076  * This routine will do uninitialization after the HBA is reset when bring
1077  * down the SLI Layer.
1078  *
1079  * Return codes
1080  *   0 - success.
1081  *   Any other value - error.
1082  **/
1083 static int
1084 lpfc_hba_down_post_s4(struct lpfc_hba *phba)
1085 {
1086 	struct lpfc_io_buf *psb, *psb_next;
1087 	struct lpfc_async_xchg_ctx *ctxp, *ctxp_next;
1088 	struct lpfc_sli4_hdw_queue *qp;
1089 	LIST_HEAD(aborts);
1090 	LIST_HEAD(nvme_aborts);
1091 	LIST_HEAD(nvmet_aborts);
1092 	struct lpfc_sglq *sglq_entry = NULL;
1093 	int cnt, idx;
1094 
1095 
1096 	lpfc_sli_hbqbuf_free_all(phba);
1097 	lpfc_hba_clean_txcmplq(phba);
1098 
1099 	/* At this point in time the HBA is either reset or DOA. Either
1100 	 * way, nothing should be on lpfc_abts_els_sgl_list, it needs to be
1101 	 * on the lpfc_els_sgl_list so that it can either be freed if the
1102 	 * driver is unloading or reposted if the driver is restarting
1103 	 * the port.
1104 	 */
1105 
1106 	/* sgl_list_lock required because worker thread uses this
1107 	 * list.
1108 	 */
1109 	spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
1110 	list_for_each_entry(sglq_entry,
1111 		&phba->sli4_hba.lpfc_abts_els_sgl_list, list)
1112 		sglq_entry->state = SGL_FREED;
1113 
1114 	list_splice_init(&phba->sli4_hba.lpfc_abts_els_sgl_list,
1115 			&phba->sli4_hba.lpfc_els_sgl_list);
1116 
1117 
1118 	spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
1119 
1120 	/* abts_xxxx_buf_list_lock required because worker thread uses this
1121 	 * list.
1122 	 */
1123 	spin_lock_irq(&phba->hbalock);
1124 	cnt = 0;
1125 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
1126 		qp = &phba->sli4_hba.hdwq[idx];
1127 
1128 		spin_lock(&qp->abts_io_buf_list_lock);
1129 		list_splice_init(&qp->lpfc_abts_io_buf_list,
1130 				 &aborts);
1131 
1132 		list_for_each_entry_safe(psb, psb_next, &aborts, list) {
1133 			psb->pCmd = NULL;
1134 			psb->status = IOSTAT_SUCCESS;
1135 			cnt++;
1136 		}
1137 		spin_lock(&qp->io_buf_list_put_lock);
1138 		list_splice_init(&aborts, &qp->lpfc_io_buf_list_put);
1139 		qp->put_io_bufs += qp->abts_scsi_io_bufs;
1140 		qp->put_io_bufs += qp->abts_nvme_io_bufs;
1141 		qp->abts_scsi_io_bufs = 0;
1142 		qp->abts_nvme_io_bufs = 0;
1143 		spin_unlock(&qp->io_buf_list_put_lock);
1144 		spin_unlock(&qp->abts_io_buf_list_lock);
1145 	}
1146 	spin_unlock_irq(&phba->hbalock);
1147 
1148 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
1149 		spin_lock_irq(&phba->sli4_hba.abts_nvmet_buf_list_lock);
1150 		list_splice_init(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list,
1151 				 &nvmet_aborts);
1152 		spin_unlock_irq(&phba->sli4_hba.abts_nvmet_buf_list_lock);
1153 		list_for_each_entry_safe(ctxp, ctxp_next, &nvmet_aborts, list) {
1154 			ctxp->flag &= ~(LPFC_NVME_XBUSY | LPFC_NVME_ABORT_OP);
1155 			lpfc_nvmet_ctxbuf_post(phba, ctxp->ctxbuf);
1156 		}
1157 	}
1158 
1159 	lpfc_sli4_free_sp_events(phba);
1160 	return cnt;
1161 }
1162 
1163 /**
1164  * lpfc_hba_down_post - Wrapper func for hba down post routine
1165  * @phba: pointer to lpfc HBA data structure.
1166  *
1167  * This routine wraps the actual SLI3 or SLI4 routine for performing
1168  * uninitialization after the HBA is reset when bring down the SLI Layer.
1169  *
1170  * Return codes
1171  *   0 - success.
1172  *   Any other value - error.
1173  **/
1174 int
1175 lpfc_hba_down_post(struct lpfc_hba *phba)
1176 {
1177 	return (*phba->lpfc_hba_down_post)(phba);
1178 }
1179 
1180 /**
1181  * lpfc_hb_timeout - The HBA-timer timeout handler
1182  * @t: timer context used to obtain the pointer to lpfc hba data structure.
1183  *
1184  * This is the HBA-timer timeout handler registered to the lpfc driver. When
1185  * this timer fires, a HBA timeout event shall be posted to the lpfc driver
1186  * work-port-events bitmap and the worker thread is notified. This timeout
1187  * event will be used by the worker thread to invoke the actual timeout
1188  * handler routine, lpfc_hb_timeout_handler. Any periodical operations will
1189  * be performed in the timeout handler and the HBA timeout event bit shall
1190  * be cleared by the worker thread after it has taken the event bitmap out.
1191  **/
1192 static void
1193 lpfc_hb_timeout(struct timer_list *t)
1194 {
1195 	struct lpfc_hba *phba;
1196 	uint32_t tmo_posted;
1197 	unsigned long iflag;
1198 
1199 	phba = timer_container_of(phba, t, hb_tmofunc);
1200 
1201 	/* Check for heart beat timeout conditions */
1202 	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
1203 	tmo_posted = phba->pport->work_port_events & WORKER_HB_TMO;
1204 	if (!tmo_posted)
1205 		phba->pport->work_port_events |= WORKER_HB_TMO;
1206 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
1207 
1208 	/* Tell the worker thread there is work to do */
1209 	if (!tmo_posted)
1210 		lpfc_worker_wake_up(phba);
1211 	return;
1212 }
1213 
1214 /**
1215  * lpfc_rrq_timeout - The RRQ-timer timeout handler
1216  * @t: timer context used to obtain the pointer to lpfc hba data structure.
1217  *
1218  * This is the RRQ-timer timeout handler registered to the lpfc driver. When
1219  * this timer fires, a RRQ timeout event shall be posted to the lpfc driver
1220  * work-port-events bitmap and the worker thread is notified. This timeout
1221  * event will be used by the worker thread to invoke the actual timeout
1222  * handler routine, lpfc_rrq_handler. Any periodical operations will
1223  * be performed in the timeout handler and the RRQ timeout event bit shall
1224  * be cleared by the worker thread after it has taken the event bitmap out.
1225  **/
1226 static void
1227 lpfc_rrq_timeout(struct timer_list *t)
1228 {
1229 	struct lpfc_hba *phba;
1230 
1231 	phba = timer_container_of(phba, t, rrq_tmr);
1232 	if (test_bit(FC_UNLOADING, &phba->pport->load_flag)) {
1233 		clear_bit(HBA_RRQ_ACTIVE, &phba->hba_flag);
1234 		return;
1235 	}
1236 
1237 	set_bit(HBA_RRQ_ACTIVE, &phba->hba_flag);
1238 	lpfc_worker_wake_up(phba);
1239 }
1240 
1241 /**
1242  * lpfc_hb_mbox_cmpl - The lpfc heart-beat mailbox command callback function
1243  * @phba: pointer to lpfc hba data structure.
1244  * @pmboxq: pointer to the driver internal queue element for mailbox command.
1245  *
1246  * This is the callback function to the lpfc heart-beat mailbox command.
1247  * If configured, the lpfc driver issues the heart-beat mailbox command to
1248  * the HBA every LPFC_HB_MBOX_INTERVAL (current 5) seconds. At the time the
1249  * heart-beat mailbox command is issued, the driver shall set up heart-beat
1250  * timeout timer to LPFC_HB_MBOX_TIMEOUT (current 30) seconds and marks
1251  * heart-beat outstanding state. Once the mailbox command comes back and
1252  * no error conditions detected, the heart-beat mailbox command timer is
1253  * reset to LPFC_HB_MBOX_INTERVAL seconds and the heart-beat outstanding
1254  * state is cleared for the next heart-beat. If the timer expired with the
1255  * heart-beat outstanding state set, the driver will put the HBA offline.
1256  **/
1257 static void
1258 lpfc_hb_mbox_cmpl(struct lpfc_hba * phba, LPFC_MBOXQ_t * pmboxq)
1259 {
1260 	clear_bit(HBA_HBEAT_INP, &phba->hba_flag);
1261 	clear_bit(HBA_HBEAT_TMO, &phba->hba_flag);
1262 
1263 	/* Check and reset heart-beat timer if necessary */
1264 	mempool_free(pmboxq, phba->mbox_mem_pool);
1265 	if (!test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag) &&
1266 	    !(phba->link_state == LPFC_HBA_ERROR) &&
1267 	    !test_bit(FC_UNLOADING, &phba->pport->load_flag))
1268 		mod_timer(&phba->hb_tmofunc,
1269 			  jiffies +
1270 			  secs_to_jiffies(LPFC_HB_MBOX_INTERVAL));
1271 	return;
1272 }
1273 
1274 /*
1275  * lpfc_idle_stat_delay_work - idle_stat tracking
1276  *
1277  * This routine tracks per-eq idle_stat and determines polling decisions.
1278  *
1279  * Return codes:
1280  *   None
1281  **/
1282 static void
1283 lpfc_idle_stat_delay_work(struct work_struct *work)
1284 {
1285 	struct lpfc_hba *phba = container_of(to_delayed_work(work),
1286 					     struct lpfc_hba,
1287 					     idle_stat_delay_work);
1288 	struct lpfc_queue *eq;
1289 	struct lpfc_sli4_hdw_queue *hdwq;
1290 	struct lpfc_idle_stat *idle_stat;
1291 	u32 i, idle_percent;
1292 	u64 wall, wall_idle, diff_wall, diff_idle, busy_time;
1293 
1294 	if (test_bit(FC_UNLOADING, &phba->pport->load_flag))
1295 		return;
1296 
1297 	if (phba->link_state == LPFC_HBA_ERROR ||
1298 	    test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag) ||
1299 	    phba->cmf_active_mode != LPFC_CFG_OFF)
1300 		goto requeue;
1301 
1302 	for_each_present_cpu(i) {
1303 		hdwq = &phba->sli4_hba.hdwq[phba->sli4_hba.cpu_map[i].hdwq];
1304 		eq = hdwq->hba_eq;
1305 
1306 		/* Skip if we've already handled this eq's primary CPU */
1307 		if (eq->chann != i)
1308 			continue;
1309 
1310 		idle_stat = &phba->sli4_hba.idle_stat[i];
1311 
1312 		/* get_cpu_idle_time returns values as running counters. Thus,
1313 		 * to know the amount for this period, the prior counter values
1314 		 * need to be subtracted from the current counter values.
1315 		 * From there, the idle time stat can be calculated as a
1316 		 * percentage of 100 - the sum of the other consumption times.
1317 		 */
1318 		wall_idle = get_cpu_idle_time(i, &wall, 1);
1319 		diff_idle = wall_idle - idle_stat->prev_idle;
1320 		diff_wall = wall - idle_stat->prev_wall;
1321 
1322 		if (diff_wall <= diff_idle)
1323 			busy_time = 0;
1324 		else
1325 			busy_time = diff_wall - diff_idle;
1326 
1327 		idle_percent = div64_u64(100 * busy_time, diff_wall);
1328 		idle_percent = 100 - idle_percent;
1329 
1330 		if (idle_percent < 15)
1331 			eq->poll_mode = LPFC_QUEUE_WORK;
1332 		else
1333 			eq->poll_mode = LPFC_THREADED_IRQ;
1334 
1335 		idle_stat->prev_idle = wall_idle;
1336 		idle_stat->prev_wall = wall;
1337 	}
1338 
1339 requeue:
1340 	schedule_delayed_work(&phba->idle_stat_delay_work,
1341 			      msecs_to_jiffies(LPFC_IDLE_STAT_DELAY));
1342 }
1343 
1344 static void
1345 lpfc_hb_eq_delay_work(struct work_struct *work)
1346 {
1347 	struct lpfc_hba *phba = container_of(to_delayed_work(work),
1348 					     struct lpfc_hba, eq_delay_work);
1349 	struct lpfc_eq_intr_info *eqi, *eqi_new;
1350 	struct lpfc_queue *eq, *eq_next;
1351 	unsigned char *ena_delay = NULL;
1352 	uint32_t usdelay;
1353 	int i;
1354 
1355 	if (!phba->cfg_auto_imax ||
1356 	    test_bit(FC_UNLOADING, &phba->pport->load_flag))
1357 		return;
1358 
1359 	if (phba->link_state == LPFC_HBA_ERROR ||
1360 	    test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag))
1361 		goto requeue;
1362 
1363 	ena_delay = kcalloc(phba->sli4_hba.num_possible_cpu, sizeof(*ena_delay),
1364 			    GFP_KERNEL);
1365 	if (!ena_delay)
1366 		goto requeue;
1367 
1368 	for (i = 0; i < phba->cfg_irq_chann; i++) {
1369 		/* Get the EQ corresponding to the IRQ vector */
1370 		eq = phba->sli4_hba.hba_eq_hdl[i].eq;
1371 		if (!eq)
1372 			continue;
1373 		if (eq->q_mode || eq->q_flag & HBA_EQ_DELAY_CHK) {
1374 			eq->q_flag &= ~HBA_EQ_DELAY_CHK;
1375 			ena_delay[eq->last_cpu] = 1;
1376 		}
1377 	}
1378 
1379 	for_each_present_cpu(i) {
1380 		eqi = per_cpu_ptr(phba->sli4_hba.eq_info, i);
1381 		if (ena_delay[i]) {
1382 			usdelay = (eqi->icnt >> 10) * LPFC_EQ_DELAY_STEP;
1383 			if (usdelay > LPFC_MAX_AUTO_EQ_DELAY)
1384 				usdelay = LPFC_MAX_AUTO_EQ_DELAY;
1385 		} else {
1386 			usdelay = 0;
1387 		}
1388 
1389 		eqi->icnt = 0;
1390 
1391 		list_for_each_entry_safe(eq, eq_next, &eqi->list, cpu_list) {
1392 			if (unlikely(eq->last_cpu != i)) {
1393 				eqi_new = per_cpu_ptr(phba->sli4_hba.eq_info,
1394 						      eq->last_cpu);
1395 				list_move_tail(&eq->cpu_list, &eqi_new->list);
1396 				continue;
1397 			}
1398 			if (usdelay != eq->q_mode)
1399 				lpfc_modify_hba_eq_delay(phba, eq->hdwq, 1,
1400 							 usdelay);
1401 		}
1402 	}
1403 
1404 	kfree(ena_delay);
1405 
1406 requeue:
1407 	queue_delayed_work(phba->wq, &phba->eq_delay_work,
1408 			   msecs_to_jiffies(LPFC_EQ_DELAY_MSECS));
1409 }
1410 
1411 /**
1412  * lpfc_hb_mxp_handler - Multi-XRI pools handler to adjust XRI distribution
1413  * @phba: pointer to lpfc hba data structure.
1414  *
1415  * For each heartbeat, this routine does some heuristic methods to adjust
1416  * XRI distribution. The goal is to fully utilize free XRIs.
1417  **/
1418 static void lpfc_hb_mxp_handler(struct lpfc_hba *phba)
1419 {
1420 	u32 i;
1421 	u32 hwq_count;
1422 
1423 	hwq_count = phba->cfg_hdw_queue;
1424 	for (i = 0; i < hwq_count; i++) {
1425 		/* Adjust XRIs in private pool */
1426 		lpfc_adjust_pvt_pool_count(phba, i);
1427 
1428 		/* Adjust high watermark */
1429 		lpfc_adjust_high_watermark(phba, i);
1430 
1431 #ifdef LPFC_MXP_STAT
1432 		/* Snapshot pbl, pvt and busy count */
1433 		lpfc_snapshot_mxp(phba, i);
1434 #endif
1435 	}
1436 }
1437 
1438 /**
1439  * lpfc_issue_hb_mbox - Issues heart-beat mailbox command
1440  * @phba: pointer to lpfc hba data structure.
1441  *
1442  * If a HB mbox is not already in progrees, this routine will allocate
1443  * a LPFC_MBOXQ_t, populate it with a MBX_HEARTBEAT (0x31) command,
1444  * and issue it. The HBA_HBEAT_INP flag means the command is in progress.
1445  **/
1446 int
1447 lpfc_issue_hb_mbox(struct lpfc_hba *phba)
1448 {
1449 	LPFC_MBOXQ_t *pmboxq;
1450 	int retval;
1451 
1452 	/* Is a Heartbeat mbox already in progress */
1453 	if (test_bit(HBA_HBEAT_INP, &phba->hba_flag))
1454 		return 0;
1455 
1456 	pmboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
1457 	if (!pmboxq)
1458 		return -ENOMEM;
1459 
1460 	lpfc_heart_beat(phba, pmboxq);
1461 	pmboxq->mbox_cmpl = lpfc_hb_mbox_cmpl;
1462 	pmboxq->vport = phba->pport;
1463 	retval = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
1464 
1465 	if (retval != MBX_BUSY && retval != MBX_SUCCESS) {
1466 		mempool_free(pmboxq, phba->mbox_mem_pool);
1467 		return -ENXIO;
1468 	}
1469 	set_bit(HBA_HBEAT_INP, &phba->hba_flag);
1470 
1471 	return 0;
1472 }
1473 
1474 /**
1475  * lpfc_issue_hb_tmo - Signals heartbeat timer to issue mbox command
1476  * @phba: pointer to lpfc hba data structure.
1477  *
1478  * The heartbeat timer (every 5 sec) will fire. If the HBA_HBEAT_TMO
1479  * flag is set, it will force a MBX_HEARTBEAT mbox command, regardless
1480  * of the value of lpfc_enable_hba_heartbeat.
1481  * If lpfc_enable_hba_heartbeat is set, the timeout routine will always
1482  * try to issue a MBX_HEARTBEAT mbox command.
1483  **/
1484 void
1485 lpfc_issue_hb_tmo(struct lpfc_hba *phba)
1486 {
1487 	if (phba->cfg_enable_hba_heartbeat)
1488 		return;
1489 	set_bit(HBA_HBEAT_TMO, &phba->hba_flag);
1490 }
1491 
1492 /**
1493  * lpfc_hb_timeout_handler - The HBA-timer timeout handler
1494  * @phba: pointer to lpfc hba data structure.
1495  *
1496  * This is the actual HBA-timer timeout handler to be invoked by the worker
1497  * thread whenever the HBA timer fired and HBA-timeout event posted. This
1498  * handler performs any periodic operations needed for the device. If such
1499  * periodic event has already been attended to either in the interrupt handler
1500  * or by processing slow-ring or fast-ring events within the HBA-timer
1501  * timeout window (LPFC_HB_MBOX_INTERVAL), this handler just simply resets
1502  * the timer for the next timeout period. If lpfc heart-beat mailbox command
1503  * is configured and there is no heart-beat mailbox command outstanding, a
1504  * heart-beat mailbox is issued and timer set properly. Otherwise, if there
1505  * has been a heart-beat mailbox command outstanding, the HBA shall be put
1506  * to offline.
1507  **/
1508 void
1509 lpfc_hb_timeout_handler(struct lpfc_hba *phba)
1510 {
1511 	struct lpfc_vport **vports;
1512 	struct lpfc_dmabuf *buf_ptr;
1513 	int retval = 0;
1514 	int i, tmo;
1515 	struct lpfc_sli *psli = &phba->sli;
1516 	LIST_HEAD(completions);
1517 
1518 	if (phba->cfg_xri_rebalancing) {
1519 		/* Multi-XRI pools handler */
1520 		lpfc_hb_mxp_handler(phba);
1521 	}
1522 
1523 	vports = lpfc_create_vport_work_array(phba);
1524 	if (vports != NULL)
1525 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
1526 			lpfc_rcv_seq_check_edtov(vports[i]);
1527 			lpfc_fdmi_change_check(vports[i]);
1528 		}
1529 	lpfc_destroy_vport_work_array(phba, vports);
1530 
1531 	if (phba->link_state == LPFC_HBA_ERROR ||
1532 	    test_bit(FC_UNLOADING, &phba->pport->load_flag) ||
1533 	    test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag))
1534 		return;
1535 
1536 	if (phba->elsbuf_cnt &&
1537 		(phba->elsbuf_cnt == phba->elsbuf_prev_cnt)) {
1538 		spin_lock_irq(&phba->hbalock);
1539 		list_splice_init(&phba->elsbuf, &completions);
1540 		phba->elsbuf_cnt = 0;
1541 		phba->elsbuf_prev_cnt = 0;
1542 		spin_unlock_irq(&phba->hbalock);
1543 
1544 		while (!list_empty(&completions)) {
1545 			list_remove_head(&completions, buf_ptr,
1546 				struct lpfc_dmabuf, list);
1547 			lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
1548 			kfree(buf_ptr);
1549 		}
1550 	}
1551 	phba->elsbuf_prev_cnt = phba->elsbuf_cnt;
1552 
1553 	/* If there is no heart beat outstanding, issue a heartbeat command */
1554 	if (phba->cfg_enable_hba_heartbeat) {
1555 		/* If IOs are completing, no need to issue a MBX_HEARTBEAT */
1556 		spin_lock_irq(&phba->pport->work_port_lock);
1557 		if (time_after(phba->last_completion_time +
1558 				secs_to_jiffies(LPFC_HB_MBOX_INTERVAL),
1559 				jiffies)) {
1560 			spin_unlock_irq(&phba->pport->work_port_lock);
1561 			if (test_bit(HBA_HBEAT_INP, &phba->hba_flag))
1562 				tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1563 			else
1564 				tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1565 			goto out;
1566 		}
1567 		spin_unlock_irq(&phba->pport->work_port_lock);
1568 
1569 		/* Check if a MBX_HEARTBEAT is already in progress */
1570 		if (test_bit(HBA_HBEAT_INP, &phba->hba_flag)) {
1571 			/*
1572 			 * If heart beat timeout called with HBA_HBEAT_INP set
1573 			 * we need to give the hb mailbox cmd a chance to
1574 			 * complete or TMO.
1575 			 */
1576 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
1577 				"0459 Adapter heartbeat still outstanding: "
1578 				"last compl time was %d ms.\n",
1579 				jiffies_to_msecs(jiffies
1580 					 - phba->last_completion_time));
1581 			tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1582 		} else {
1583 			if ((!(psli->sli_flag & LPFC_SLI_MBOX_ACTIVE)) &&
1584 				(list_empty(&psli->mboxq))) {
1585 
1586 				retval = lpfc_issue_hb_mbox(phba);
1587 				if (retval) {
1588 					tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1589 					goto out;
1590 				}
1591 				phba->skipped_hb = 0;
1592 			} else if (time_before_eq(phba->last_completion_time,
1593 					phba->skipped_hb)) {
1594 				lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
1595 					"2857 Last completion time not "
1596 					" updated in %d ms\n",
1597 					jiffies_to_msecs(jiffies
1598 						 - phba->last_completion_time));
1599 			} else
1600 				phba->skipped_hb = jiffies;
1601 
1602 			tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1603 			goto out;
1604 		}
1605 	} else {
1606 		/* Check to see if we want to force a MBX_HEARTBEAT */
1607 		if (test_bit(HBA_HBEAT_TMO, &phba->hba_flag)) {
1608 			retval = lpfc_issue_hb_mbox(phba);
1609 			if (retval)
1610 				tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1611 			else
1612 				tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1613 			goto out;
1614 		}
1615 		tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1616 	}
1617 out:
1618 	mod_timer(&phba->hb_tmofunc, jiffies + msecs_to_jiffies(tmo));
1619 }
1620 
1621 /**
1622  * lpfc_offline_eratt - Bring lpfc offline on hardware error attention
1623  * @phba: pointer to lpfc hba data structure.
1624  *
1625  * This routine is called to bring the HBA offline when HBA hardware error
1626  * other than Port Error 6 has been detected.
1627  **/
1628 static void
1629 lpfc_offline_eratt(struct lpfc_hba *phba)
1630 {
1631 	struct lpfc_sli   *psli = &phba->sli;
1632 
1633 	spin_lock_irq(&phba->hbalock);
1634 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1635 	spin_unlock_irq(&phba->hbalock);
1636 	lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
1637 
1638 	lpfc_offline(phba);
1639 	lpfc_reset_barrier(phba);
1640 	spin_lock_irq(&phba->hbalock);
1641 	lpfc_sli_brdreset(phba);
1642 	spin_unlock_irq(&phba->hbalock);
1643 	lpfc_hba_down_post(phba);
1644 	lpfc_sli_brdready(phba, HS_MBRDY);
1645 	lpfc_unblock_mgmt_io(phba);
1646 	phba->link_state = LPFC_HBA_ERROR;
1647 	return;
1648 }
1649 
1650 /**
1651  * lpfc_sli4_offline_eratt - Bring lpfc offline on SLI4 hardware error attention
1652  * @phba: pointer to lpfc hba data structure.
1653  *
1654  * This routine is called to bring a SLI4 HBA offline when HBA hardware error
1655  * other than Port Error 6 has been detected.
1656  **/
1657 void
1658 lpfc_sli4_offline_eratt(struct lpfc_hba *phba)
1659 {
1660 	spin_lock_irq(&phba->hbalock);
1661 	if (phba->link_state == LPFC_HBA_ERROR &&
1662 		test_bit(HBA_PCI_ERR, &phba->bit_flags)) {
1663 		spin_unlock_irq(&phba->hbalock);
1664 		return;
1665 	}
1666 	phba->link_state = LPFC_HBA_ERROR;
1667 	spin_unlock_irq(&phba->hbalock);
1668 
1669 	lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
1670 	lpfc_sli_flush_io_rings(phba);
1671 	lpfc_offline(phba);
1672 	lpfc_hba_down_post(phba);
1673 	lpfc_unblock_mgmt_io(phba);
1674 }
1675 
1676 /**
1677  * lpfc_handle_deferred_eratt - The HBA hardware deferred error handler
1678  * @phba: pointer to lpfc hba data structure.
1679  *
1680  * This routine is invoked to handle the deferred HBA hardware error
1681  * conditions. This type of error is indicated by HBA by setting ER1
1682  * and another ER bit in the host status register. The driver will
1683  * wait until the ER1 bit clears before handling the error condition.
1684  **/
1685 static void
1686 lpfc_handle_deferred_eratt(struct lpfc_hba *phba)
1687 {
1688 	uint32_t old_host_status = phba->work_hs;
1689 	struct lpfc_sli *psli = &phba->sli;
1690 
1691 	/* If the pci channel is offline, ignore possible errors,
1692 	 * since we cannot communicate with the pci card anyway.
1693 	 */
1694 	if (pci_channel_offline(phba->pcidev)) {
1695 		clear_bit(DEFER_ERATT, &phba->hba_flag);
1696 		return;
1697 	}
1698 
1699 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1700 			"0479 Deferred Adapter Hardware Error "
1701 			"Data: x%x x%x x%x\n",
1702 			phba->work_hs, phba->work_status[0],
1703 			phba->work_status[1]);
1704 
1705 	spin_lock_irq(&phba->hbalock);
1706 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1707 	spin_unlock_irq(&phba->hbalock);
1708 
1709 
1710 	/*
1711 	 * Firmware stops when it triggred erratt. That could cause the I/Os
1712 	 * dropped by the firmware. Error iocb (I/O) on txcmplq and let the
1713 	 * SCSI layer retry it after re-establishing link.
1714 	 */
1715 	lpfc_sli_abort_fcp_rings(phba);
1716 
1717 	/*
1718 	 * There was a firmware error. Take the hba offline and then
1719 	 * attempt to restart it.
1720 	 */
1721 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
1722 	lpfc_offline(phba);
1723 
1724 	/* Wait for the ER1 bit to clear.*/
1725 	while (phba->work_hs & HS_FFER1) {
1726 		msleep(100);
1727 		if (lpfc_readl(phba->HSregaddr, &phba->work_hs)) {
1728 			phba->work_hs = UNPLUG_ERR ;
1729 			break;
1730 		}
1731 		/* If driver is unloading let the worker thread continue */
1732 		if (test_bit(FC_UNLOADING, &phba->pport->load_flag)) {
1733 			phba->work_hs = 0;
1734 			break;
1735 		}
1736 	}
1737 
1738 	/*
1739 	 * This is to ptrotect against a race condition in which
1740 	 * first write to the host attention register clear the
1741 	 * host status register.
1742 	 */
1743 	if (!phba->work_hs && !test_bit(FC_UNLOADING, &phba->pport->load_flag))
1744 		phba->work_hs = old_host_status & ~HS_FFER1;
1745 
1746 	clear_bit(DEFER_ERATT, &phba->hba_flag);
1747 	phba->work_status[0] = readl(phba->MBslimaddr + 0xa8);
1748 	phba->work_status[1] = readl(phba->MBslimaddr + 0xac);
1749 }
1750 
1751 static void
1752 lpfc_board_errevt_to_mgmt(struct lpfc_hba *phba)
1753 {
1754 	struct lpfc_board_event_header board_event;
1755 	struct Scsi_Host *shost;
1756 
1757 	board_event.event_type = FC_REG_BOARD_EVENT;
1758 	board_event.subcategory = LPFC_EVENT_PORTINTERR;
1759 	shost = lpfc_shost_from_vport(phba->pport);
1760 	fc_host_post_vendor_event(shost, fc_get_event_number(),
1761 				  sizeof(board_event),
1762 				  (char *) &board_event,
1763 				  LPFC_NL_VENDOR_ID);
1764 }
1765 
1766 /**
1767  * lpfc_handle_eratt_s3 - The SLI3 HBA hardware error handler
1768  * @phba: pointer to lpfc hba data structure.
1769  *
1770  * This routine is invoked to handle the following HBA hardware error
1771  * conditions:
1772  * 1 - HBA error attention interrupt
1773  * 2 - DMA ring index out of range
1774  * 3 - Mailbox command came back as unknown
1775  **/
1776 static void
1777 lpfc_handle_eratt_s3(struct lpfc_hba *phba)
1778 {
1779 	struct lpfc_vport *vport = phba->pport;
1780 	struct lpfc_sli   *psli = &phba->sli;
1781 	uint32_t event_data;
1782 	unsigned long temperature;
1783 	struct temp_event temp_event_data;
1784 	struct Scsi_Host  *shost;
1785 
1786 	/* If the pci channel is offline, ignore possible errors,
1787 	 * since we cannot communicate with the pci card anyway.
1788 	 */
1789 	if (pci_channel_offline(phba->pcidev)) {
1790 		clear_bit(DEFER_ERATT, &phba->hba_flag);
1791 		return;
1792 	}
1793 
1794 	/* If resets are disabled then leave the HBA alone and return */
1795 	if (!phba->cfg_enable_hba_reset)
1796 		return;
1797 
1798 	/* Send an internal error event to mgmt application */
1799 	lpfc_board_errevt_to_mgmt(phba);
1800 
1801 	if (test_bit(DEFER_ERATT, &phba->hba_flag))
1802 		lpfc_handle_deferred_eratt(phba);
1803 
1804 	if ((phba->work_hs & HS_FFER6) || (phba->work_hs & HS_FFER8)) {
1805 		if (phba->work_hs & HS_FFER6)
1806 			/* Re-establishing Link */
1807 			lpfc_printf_log(phba, KERN_INFO, LOG_LINK_EVENT,
1808 					"1301 Re-establishing Link "
1809 					"Data: x%x x%x x%x\n",
1810 					phba->work_hs, phba->work_status[0],
1811 					phba->work_status[1]);
1812 		if (phba->work_hs & HS_FFER8)
1813 			/* Device Zeroization */
1814 			lpfc_printf_log(phba, KERN_INFO, LOG_LINK_EVENT,
1815 					"2861 Host Authentication device "
1816 					"zeroization Data:x%x x%x x%x\n",
1817 					phba->work_hs, phba->work_status[0],
1818 					phba->work_status[1]);
1819 
1820 		spin_lock_irq(&phba->hbalock);
1821 		psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1822 		spin_unlock_irq(&phba->hbalock);
1823 
1824 		/*
1825 		* Firmware stops when it triggled erratt with HS_FFER6.
1826 		* That could cause the I/Os dropped by the firmware.
1827 		* Error iocb (I/O) on txcmplq and let the SCSI layer
1828 		* retry it after re-establishing link.
1829 		*/
1830 		lpfc_sli_abort_fcp_rings(phba);
1831 
1832 		/*
1833 		 * There was a firmware error.  Take the hba offline and then
1834 		 * attempt to restart it.
1835 		 */
1836 		lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
1837 		lpfc_offline(phba);
1838 		lpfc_sli_brdrestart(phba);
1839 		if (lpfc_online(phba) == 0) {	/* Initialize the HBA */
1840 			lpfc_unblock_mgmt_io(phba);
1841 			return;
1842 		}
1843 		lpfc_unblock_mgmt_io(phba);
1844 	} else if (phba->work_hs & HS_CRIT_TEMP) {
1845 		temperature = readl(phba->MBslimaddr + TEMPERATURE_OFFSET);
1846 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
1847 		temp_event_data.event_code = LPFC_CRIT_TEMP;
1848 		temp_event_data.data = (uint32_t)temperature;
1849 
1850 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1851 				"0406 Adapter maximum temperature exceeded "
1852 				"(%ld), taking this port offline "
1853 				"Data: x%x x%x x%x\n",
1854 				temperature, phba->work_hs,
1855 				phba->work_status[0], phba->work_status[1]);
1856 
1857 		shost = lpfc_shost_from_vport(phba->pport);
1858 		fc_host_post_vendor_event(shost, fc_get_event_number(),
1859 					  sizeof(temp_event_data),
1860 					  (char *) &temp_event_data,
1861 					  SCSI_NL_VID_TYPE_PCI
1862 					  | PCI_VENDOR_ID_EMULEX);
1863 
1864 		spin_lock_irq(&phba->hbalock);
1865 		phba->over_temp_state = HBA_OVER_TEMP;
1866 		spin_unlock_irq(&phba->hbalock);
1867 		lpfc_offline_eratt(phba);
1868 
1869 	} else {
1870 		/* The if clause above forces this code path when the status
1871 		 * failure is a value other than FFER6. Do not call the offline
1872 		 * twice. This is the adapter hardware error path.
1873 		 */
1874 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1875 				"0457 Adapter Hardware Error "
1876 				"Data: x%x x%x x%x\n",
1877 				phba->work_hs,
1878 				phba->work_status[0], phba->work_status[1]);
1879 
1880 		event_data = FC_REG_DUMP_EVENT;
1881 		shost = lpfc_shost_from_vport(vport);
1882 		fc_host_post_vendor_event(shost, fc_get_event_number(),
1883 				sizeof(event_data), (char *) &event_data,
1884 				SCSI_NL_VID_TYPE_PCI | PCI_VENDOR_ID_EMULEX);
1885 
1886 		lpfc_offline_eratt(phba);
1887 	}
1888 	return;
1889 }
1890 
1891 /**
1892  * lpfc_sli4_port_sta_fn_reset - The SLI4 function reset due to port status reg
1893  * @phba: pointer to lpfc hba data structure.
1894  * @mbx_action: flag for mailbox shutdown action.
1895  * @en_rn_msg: send reset/port recovery message.
1896  * This routine is invoked to perform an SLI4 port PCI function reset in
1897  * response to port status register polling attention. It waits for port
1898  * status register (ERR, RDY, RN) bits before proceeding with function reset.
1899  * During this process, interrupt vectors are freed and later requested
1900  * for handling possible port resource change.
1901  **/
1902 static int
1903 lpfc_sli4_port_sta_fn_reset(struct lpfc_hba *phba, int mbx_action,
1904 			    bool en_rn_msg)
1905 {
1906 	int rc;
1907 	uint32_t intr_mode;
1908 	LPFC_MBOXQ_t *mboxq;
1909 
1910 	/* Notifying the transport that the targets are going offline. */
1911 	lpfc_scsi_dev_block(phba);
1912 
1913 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) >=
1914 	    LPFC_SLI_INTF_IF_TYPE_2) {
1915 		/*
1916 		 * On error status condition, driver need to wait for port
1917 		 * ready before performing reset.
1918 		 */
1919 		rc = lpfc_sli4_pdev_status_reg_wait(phba);
1920 		if (rc)
1921 			return rc;
1922 	}
1923 
1924 	/* need reset: attempt for port recovery */
1925 	if (en_rn_msg)
1926 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
1927 				"2887 Reset Needed: Attempting Port "
1928 				"Recovery...\n");
1929 
1930 	/* If we are no wait, the HBA has been reset and is not
1931 	 * functional, thus we should clear
1932 	 * (LPFC_SLI_ACTIVE | LPFC_SLI_MBOX_ACTIVE) flags.
1933 	 */
1934 	if (mbx_action == LPFC_MBX_NO_WAIT) {
1935 		spin_lock_irq(&phba->hbalock);
1936 		phba->sli.sli_flag &= ~LPFC_SLI_ACTIVE;
1937 		if (phba->sli.mbox_active) {
1938 			mboxq = phba->sli.mbox_active;
1939 			mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
1940 			__lpfc_mbox_cmpl_put(phba, mboxq);
1941 			phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
1942 			phba->sli.mbox_active = NULL;
1943 		}
1944 		spin_unlock_irq(&phba->hbalock);
1945 	}
1946 
1947 	lpfc_offline_prep(phba, mbx_action);
1948 	lpfc_sli_flush_io_rings(phba);
1949 	lpfc_nvmels_flush_cmd(phba);
1950 	lpfc_offline(phba);
1951 	/* release interrupt for possible resource change */
1952 	lpfc_sli4_disable_intr(phba);
1953 	rc = lpfc_sli_brdrestart(phba);
1954 	if (rc) {
1955 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1956 				"6309 Failed to restart board\n");
1957 		return rc;
1958 	}
1959 	/* request and enable interrupt */
1960 	intr_mode = lpfc_sli4_enable_intr(phba, phba->intr_mode);
1961 	if (intr_mode == LPFC_INTR_ERROR) {
1962 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1963 				"3175 Failed to enable interrupt\n");
1964 		return -EIO;
1965 	}
1966 	phba->intr_mode = intr_mode;
1967 	rc = lpfc_online(phba);
1968 	if (rc == 0)
1969 		lpfc_unblock_mgmt_io(phba);
1970 
1971 	return rc;
1972 }
1973 
1974 /**
1975  * lpfc_handle_eratt_s4 - The SLI4 HBA hardware error handler
1976  * @phba: pointer to lpfc hba data structure.
1977  *
1978  * This routine is invoked to handle the SLI4 HBA hardware error attention
1979  * conditions.
1980  **/
1981 static void
1982 lpfc_handle_eratt_s4(struct lpfc_hba *phba)
1983 {
1984 	struct lpfc_vport *vport = phba->pport;
1985 	uint32_t event_data;
1986 	struct Scsi_Host *shost;
1987 	uint32_t if_type;
1988 	struct lpfc_register portstat_reg = {0};
1989 	uint32_t reg_err1, reg_err2;
1990 	uint32_t uerrlo_reg, uemasklo_reg;
1991 	uint32_t smphr_port_status = 0, pci_rd_rc1, pci_rd_rc2;
1992 	bool en_rn_msg = true;
1993 	struct temp_event temp_event_data;
1994 	struct lpfc_register portsmphr_reg;
1995 	int rc, i;
1996 
1997 	/* If the pci channel is offline, ignore possible errors, since
1998 	 * we cannot communicate with the pci card anyway.
1999 	 */
2000 	if (pci_channel_offline(phba->pcidev)) {
2001 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2002 				"3166 pci channel is offline\n");
2003 		lpfc_sli_flush_io_rings(phba);
2004 		return;
2005 	}
2006 
2007 	memset(&portsmphr_reg, 0, sizeof(portsmphr_reg));
2008 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
2009 	switch (if_type) {
2010 	case LPFC_SLI_INTF_IF_TYPE_0:
2011 		pci_rd_rc1 = lpfc_readl(
2012 				phba->sli4_hba.u.if_type0.UERRLOregaddr,
2013 				&uerrlo_reg);
2014 		pci_rd_rc2 = lpfc_readl(
2015 				phba->sli4_hba.u.if_type0.UEMASKLOregaddr,
2016 				&uemasklo_reg);
2017 		/* consider PCI bus read error as pci_channel_offline */
2018 		if (pci_rd_rc1 == -EIO && pci_rd_rc2 == -EIO)
2019 			return;
2020 		if (!test_bit(HBA_RECOVERABLE_UE, &phba->hba_flag)) {
2021 			lpfc_sli4_offline_eratt(phba);
2022 			return;
2023 		}
2024 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2025 				"7623 Checking UE recoverable");
2026 
2027 		for (i = 0; i < phba->sli4_hba.ue_to_sr / 1000; i++) {
2028 			if (lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
2029 				       &portsmphr_reg.word0))
2030 				continue;
2031 
2032 			smphr_port_status = bf_get(lpfc_port_smphr_port_status,
2033 						   &portsmphr_reg);
2034 			if ((smphr_port_status & LPFC_PORT_SEM_MASK) ==
2035 			    LPFC_PORT_SEM_UE_RECOVERABLE)
2036 				break;
2037 			/*Sleep for 1Sec, before checking SEMAPHORE */
2038 			msleep(1000);
2039 		}
2040 
2041 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2042 				"4827 smphr_port_status x%x : Waited %dSec",
2043 				smphr_port_status, i);
2044 
2045 		/* Recoverable UE, reset the HBA device */
2046 		if ((smphr_port_status & LPFC_PORT_SEM_MASK) ==
2047 		    LPFC_PORT_SEM_UE_RECOVERABLE) {
2048 			for (i = 0; i < 20; i++) {
2049 				msleep(1000);
2050 				if (!lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
2051 				    &portsmphr_reg.word0) &&
2052 				    (LPFC_POST_STAGE_PORT_READY ==
2053 				     bf_get(lpfc_port_smphr_port_status,
2054 				     &portsmphr_reg))) {
2055 					rc = lpfc_sli4_port_sta_fn_reset(phba,
2056 						LPFC_MBX_NO_WAIT, en_rn_msg);
2057 					if (rc == 0)
2058 						return;
2059 					lpfc_printf_log(phba, KERN_ERR,
2060 						LOG_TRACE_EVENT,
2061 						"4215 Failed to recover UE");
2062 					break;
2063 				}
2064 			}
2065 		}
2066 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2067 				"7624 Firmware not ready: Failing UE recovery,"
2068 				" waited %dSec", i);
2069 		phba->link_state = LPFC_HBA_ERROR;
2070 		break;
2071 
2072 	case LPFC_SLI_INTF_IF_TYPE_2:
2073 	case LPFC_SLI_INTF_IF_TYPE_6:
2074 		pci_rd_rc1 = lpfc_readl(
2075 				phba->sli4_hba.u.if_type2.STATUSregaddr,
2076 				&portstat_reg.word0);
2077 		/* consider PCI bus read error as pci_channel_offline */
2078 		if (pci_rd_rc1 == -EIO) {
2079 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2080 				"3151 PCI bus read access failure: x%x\n",
2081 				readl(phba->sli4_hba.u.if_type2.STATUSregaddr));
2082 			lpfc_sli4_offline_eratt(phba);
2083 			return;
2084 		}
2085 		reg_err1 = readl(phba->sli4_hba.u.if_type2.ERR1regaddr);
2086 		reg_err2 = readl(phba->sli4_hba.u.if_type2.ERR2regaddr);
2087 		if (bf_get(lpfc_sliport_status_oti, &portstat_reg)) {
2088 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2089 					"2889 Port Overtemperature event, "
2090 					"taking port offline Data: x%x x%x\n",
2091 					reg_err1, reg_err2);
2092 
2093 			phba->sfp_alarm |= LPFC_TRANSGRESSION_HIGH_TEMPERATURE;
2094 			temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
2095 			temp_event_data.event_code = LPFC_CRIT_TEMP;
2096 			temp_event_data.data = 0xFFFFFFFF;
2097 
2098 			shost = lpfc_shost_from_vport(phba->pport);
2099 			fc_host_post_vendor_event(shost, fc_get_event_number(),
2100 						  sizeof(temp_event_data),
2101 						  (char *)&temp_event_data,
2102 						  SCSI_NL_VID_TYPE_PCI
2103 						  | PCI_VENDOR_ID_EMULEX);
2104 
2105 			spin_lock_irq(&phba->hbalock);
2106 			phba->over_temp_state = HBA_OVER_TEMP;
2107 			spin_unlock_irq(&phba->hbalock);
2108 			lpfc_sli4_offline_eratt(phba);
2109 			return;
2110 		}
2111 		if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2112 		    reg_err2 == SLIPORT_ERR2_REG_FW_RESTART) {
2113 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2114 					"3143 Port Down: Firmware Update "
2115 					"Detected\n");
2116 			en_rn_msg = false;
2117 		} else if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2118 			 reg_err2 == SLIPORT_ERR2_REG_FORCED_DUMP)
2119 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2120 					"3144 Port Down: Debug Dump\n");
2121 		else if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2122 			 reg_err2 == SLIPORT_ERR2_REG_FUNC_PROVISON)
2123 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2124 					"3145 Port Down: Provisioning\n");
2125 
2126 		/* If resets are disabled then leave the HBA alone and return */
2127 		if (!phba->cfg_enable_hba_reset)
2128 			return;
2129 
2130 		/* Check port status register for function reset */
2131 		rc = lpfc_sli4_port_sta_fn_reset(phba, LPFC_MBX_NO_WAIT,
2132 				en_rn_msg);
2133 		if (rc == 0) {
2134 			/* don't report event on forced debug dump */
2135 			if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2136 			    reg_err2 == SLIPORT_ERR2_REG_FORCED_DUMP)
2137 				return;
2138 			else
2139 				break;
2140 		}
2141 		/* fall through for not able to recover */
2142 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2143 				"3152 Unrecoverable error\n");
2144 		lpfc_sli4_offline_eratt(phba);
2145 		break;
2146 	case LPFC_SLI_INTF_IF_TYPE_1:
2147 	default:
2148 		break;
2149 	}
2150 	lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
2151 			"3123 Report dump event to upper layer\n");
2152 	/* Send an internal error event to mgmt application */
2153 	lpfc_board_errevt_to_mgmt(phba);
2154 
2155 	event_data = FC_REG_DUMP_EVENT;
2156 	shost = lpfc_shost_from_vport(vport);
2157 	fc_host_post_vendor_event(shost, fc_get_event_number(),
2158 				  sizeof(event_data), (char *) &event_data,
2159 				  SCSI_NL_VID_TYPE_PCI | PCI_VENDOR_ID_EMULEX);
2160 }
2161 
2162 /**
2163  * lpfc_handle_eratt - Wrapper func for handling hba error attention
2164  * @phba: pointer to lpfc HBA data structure.
2165  *
2166  * This routine wraps the actual SLI3 or SLI4 hba error attention handling
2167  * routine from the API jump table function pointer from the lpfc_hba struct.
2168  *
2169  * Return codes
2170  *   0 - success.
2171  *   Any other value - error.
2172  **/
2173 void
2174 lpfc_handle_eratt(struct lpfc_hba *phba)
2175 {
2176 	(*phba->lpfc_handle_eratt)(phba);
2177 }
2178 
2179 /**
2180  * lpfc_handle_latt - The HBA link event handler
2181  * @phba: pointer to lpfc hba data structure.
2182  *
2183  * This routine is invoked from the worker thread to handle a HBA host
2184  * attention link event. SLI3 only.
2185  **/
2186 void
2187 lpfc_handle_latt(struct lpfc_hba *phba)
2188 {
2189 	struct lpfc_vport *vport = phba->pport;
2190 	struct lpfc_sli   *psli = &phba->sli;
2191 	LPFC_MBOXQ_t *pmb;
2192 	volatile uint32_t control;
2193 	int rc = 0;
2194 
2195 	pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
2196 	if (!pmb) {
2197 		rc = 1;
2198 		goto lpfc_handle_latt_err_exit;
2199 	}
2200 
2201 	rc = lpfc_mbox_rsrc_prep(phba, pmb);
2202 	if (rc) {
2203 		rc = 2;
2204 		mempool_free(pmb, phba->mbox_mem_pool);
2205 		goto lpfc_handle_latt_err_exit;
2206 	}
2207 
2208 	/* Cleanup any outstanding ELS commands */
2209 	lpfc_els_flush_all_cmd(phba);
2210 	psli->slistat.link_event++;
2211 	lpfc_read_topology(phba, pmb, pmb->ctx_buf);
2212 	pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
2213 	pmb->vport = vport;
2214 	/* Block ELS IOCBs until we have processed this mbox command */
2215 	phba->sli.sli3_ring[LPFC_ELS_RING].flag |= LPFC_STOP_IOCB_EVENT;
2216 	rc = lpfc_sli_issue_mbox (phba, pmb, MBX_NOWAIT);
2217 	if (rc == MBX_NOT_FINISHED) {
2218 		rc = 4;
2219 		goto lpfc_handle_latt_free_mbuf;
2220 	}
2221 
2222 	/* Clear Link Attention in HA REG */
2223 	spin_lock_irq(&phba->hbalock);
2224 	writel(HA_LATT, phba->HAregaddr);
2225 	readl(phba->HAregaddr); /* flush */
2226 	spin_unlock_irq(&phba->hbalock);
2227 
2228 	return;
2229 
2230 lpfc_handle_latt_free_mbuf:
2231 	phba->sli.sli3_ring[LPFC_ELS_RING].flag &= ~LPFC_STOP_IOCB_EVENT;
2232 	lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
2233 lpfc_handle_latt_err_exit:
2234 	/* Enable Link attention interrupts */
2235 	spin_lock_irq(&phba->hbalock);
2236 	psli->sli_flag |= LPFC_PROCESS_LA;
2237 	control = readl(phba->HCregaddr);
2238 	control |= HC_LAINT_ENA;
2239 	writel(control, phba->HCregaddr);
2240 	readl(phba->HCregaddr); /* flush */
2241 
2242 	/* Clear Link Attention in HA REG */
2243 	writel(HA_LATT, phba->HAregaddr);
2244 	readl(phba->HAregaddr); /* flush */
2245 	spin_unlock_irq(&phba->hbalock);
2246 	lpfc_linkdown(phba);
2247 	phba->link_state = LPFC_HBA_ERROR;
2248 
2249 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2250 			"0300 LATT: Cannot issue READ_LA: Data:%d\n", rc);
2251 
2252 	return;
2253 }
2254 
2255 static void
2256 lpfc_fill_vpd(struct lpfc_hba *phba, uint8_t *vpd, int length, int *pindex)
2257 {
2258 	int i, j;
2259 
2260 	while (length > 0) {
2261 		/* Look for Serial Number */
2262 		if ((vpd[*pindex] == 'S') && (vpd[*pindex + 1] == 'N')) {
2263 			*pindex += 2;
2264 			i = vpd[*pindex];
2265 			*pindex += 1;
2266 			j = 0;
2267 			length -= (3+i);
2268 			while (i--) {
2269 				phba->SerialNumber[j++] = vpd[(*pindex)++];
2270 				if (j == 31)
2271 					break;
2272 			}
2273 			phba->SerialNumber[j] = 0;
2274 			continue;
2275 		} else if ((vpd[*pindex] == 'V') && (vpd[*pindex + 1] == '1')) {
2276 			phba->vpd_flag |= VPD_MODEL_DESC;
2277 			*pindex += 2;
2278 			i = vpd[*pindex];
2279 			*pindex += 1;
2280 			j = 0;
2281 			length -= (3+i);
2282 			while (i--) {
2283 				phba->ModelDesc[j++] = vpd[(*pindex)++];
2284 				if (j == 255)
2285 					break;
2286 			}
2287 			phba->ModelDesc[j] = 0;
2288 			continue;
2289 		} else if ((vpd[*pindex] == 'V') && (vpd[*pindex + 1] == '2')) {
2290 			phba->vpd_flag |= VPD_MODEL_NAME;
2291 			*pindex += 2;
2292 			i = vpd[*pindex];
2293 			*pindex += 1;
2294 			j = 0;
2295 			length -= (3+i);
2296 			while (i--) {
2297 				phba->ModelName[j++] = vpd[(*pindex)++];
2298 				if (j == 79)
2299 					break;
2300 			}
2301 			phba->ModelName[j] = 0;
2302 			continue;
2303 		} else if ((vpd[*pindex] == 'V') && (vpd[*pindex + 1] == '3')) {
2304 			phba->vpd_flag |= VPD_PROGRAM_TYPE;
2305 			*pindex += 2;
2306 			i = vpd[*pindex];
2307 			*pindex += 1;
2308 			j = 0;
2309 			length -= (3+i);
2310 			while (i--) {
2311 				phba->ProgramType[j++] = vpd[(*pindex)++];
2312 				if (j == 255)
2313 					break;
2314 			}
2315 			phba->ProgramType[j] = 0;
2316 			continue;
2317 		} else if ((vpd[*pindex] == 'V') && (vpd[*pindex + 1] == '4')) {
2318 			phba->vpd_flag |= VPD_PORT;
2319 			*pindex += 2;
2320 			i = vpd[*pindex];
2321 			*pindex += 1;
2322 			j = 0;
2323 			length -= (3 + i);
2324 			while (i--) {
2325 				if ((phba->sli_rev == LPFC_SLI_REV4) &&
2326 				    (phba->sli4_hba.pport_name_sta ==
2327 				     LPFC_SLI4_PPNAME_GET)) {
2328 					j++;
2329 					(*pindex)++;
2330 				} else
2331 					phba->Port[j++] = vpd[(*pindex)++];
2332 				if (j == 19)
2333 					break;
2334 			}
2335 			if ((phba->sli_rev != LPFC_SLI_REV4) ||
2336 			    (phba->sli4_hba.pport_name_sta ==
2337 			     LPFC_SLI4_PPNAME_NON))
2338 				phba->Port[j] = 0;
2339 			continue;
2340 		} else {
2341 			*pindex += 2;
2342 			i = vpd[*pindex];
2343 			*pindex += 1;
2344 			*pindex += i;
2345 			length -= (3 + i);
2346 		}
2347 	}
2348 }
2349 
2350 /**
2351  * lpfc_parse_vpd - Parse VPD (Vital Product Data)
2352  * @phba: pointer to lpfc hba data structure.
2353  * @vpd: pointer to the vital product data.
2354  * @len: length of the vital product data in bytes.
2355  *
2356  * This routine parses the Vital Product Data (VPD). The VPD is treated as
2357  * an array of characters. In this routine, the ModelName, ProgramType, and
2358  * ModelDesc, etc. fields of the phba data structure will be populated.
2359  *
2360  * Return codes
2361  *   0 - pointer to the VPD passed in is NULL
2362  *   1 - success
2363  **/
2364 int
2365 lpfc_parse_vpd(struct lpfc_hba *phba, uint8_t *vpd, int len)
2366 {
2367 	uint8_t lenlo, lenhi;
2368 	int Length;
2369 	int i;
2370 	int finished = 0;
2371 	int index = 0;
2372 
2373 	if (!vpd)
2374 		return 0;
2375 
2376 	/* Vital Product */
2377 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
2378 			"0455 Vital Product Data: x%x x%x x%x x%x\n",
2379 			(uint32_t) vpd[0], (uint32_t) vpd[1], (uint32_t) vpd[2],
2380 			(uint32_t) vpd[3]);
2381 	while (!finished && (index < (len - 4))) {
2382 		switch (vpd[index]) {
2383 		case 0x82:
2384 		case 0x91:
2385 			index += 1;
2386 			lenlo = vpd[index];
2387 			index += 1;
2388 			lenhi = vpd[index];
2389 			index += 1;
2390 			i = ((((unsigned short)lenhi) << 8) + lenlo);
2391 			index += i;
2392 			break;
2393 		case 0x90:
2394 			index += 1;
2395 			lenlo = vpd[index];
2396 			index += 1;
2397 			lenhi = vpd[index];
2398 			index += 1;
2399 			Length = ((((unsigned short)lenhi) << 8) + lenlo);
2400 			if (Length > len - index)
2401 				Length = len - index;
2402 
2403 			lpfc_fill_vpd(phba, vpd, Length, &index);
2404 			finished = 0;
2405 			break;
2406 		case 0x78:
2407 			finished = 1;
2408 			break;
2409 		default:
2410 			index ++;
2411 			break;
2412 		}
2413 	}
2414 
2415 	return(1);
2416 }
2417 
2418 /**
2419  * lpfc_get_atto_model_desc - Retrieve ATTO HBA device model name and description
2420  * @phba: pointer to lpfc hba data structure.
2421  * @mdp: pointer to the data structure to hold the derived model name.
2422  * @descp: pointer to the data structure to hold the derived description.
2423  *
2424  * This routine retrieves HBA's description based on its registered PCI device
2425  * ID. The @descp passed into this function points to an array of 256 chars. It
2426  * shall be returned with the model name, maximum speed, and the host bus type.
2427  * The @mdp passed into this function points to an array of 80 chars. When the
2428  * function returns, the @mdp will be filled with the model name.
2429  **/
2430 static void
2431 lpfc_get_atto_model_desc(struct lpfc_hba *phba, uint8_t *mdp, uint8_t *descp)
2432 {
2433 	uint16_t sub_dev_id = phba->pcidev->subsystem_device;
2434 	char *model = "<Unknown>";
2435 	int tbolt = 0;
2436 
2437 	switch (sub_dev_id) {
2438 	case PCI_DEVICE_ID_CLRY_161E:
2439 		model = "161E";
2440 		break;
2441 	case PCI_DEVICE_ID_CLRY_162E:
2442 		model = "162E";
2443 		break;
2444 	case PCI_DEVICE_ID_CLRY_164E:
2445 		model = "164E";
2446 		break;
2447 	case PCI_DEVICE_ID_CLRY_161P:
2448 		model = "161P";
2449 		break;
2450 	case PCI_DEVICE_ID_CLRY_162P:
2451 		model = "162P";
2452 		break;
2453 	case PCI_DEVICE_ID_CLRY_164P:
2454 		model = "164P";
2455 		break;
2456 	case PCI_DEVICE_ID_CLRY_321E:
2457 		model = "321E";
2458 		break;
2459 	case PCI_DEVICE_ID_CLRY_322E:
2460 		model = "322E";
2461 		break;
2462 	case PCI_DEVICE_ID_CLRY_324E:
2463 		model = "324E";
2464 		break;
2465 	case PCI_DEVICE_ID_CLRY_321P:
2466 		model = "321P";
2467 		break;
2468 	case PCI_DEVICE_ID_CLRY_322P:
2469 		model = "322P";
2470 		break;
2471 	case PCI_DEVICE_ID_CLRY_324P:
2472 		model = "324P";
2473 		break;
2474 	case PCI_DEVICE_ID_TLFC_2XX2:
2475 		model = "2XX2";
2476 		tbolt = 1;
2477 		break;
2478 	case PCI_DEVICE_ID_TLFC_3162:
2479 		model = "3162";
2480 		tbolt = 1;
2481 		break;
2482 	case PCI_DEVICE_ID_TLFC_3322:
2483 		model = "3322";
2484 		tbolt = 1;
2485 		break;
2486 	default:
2487 		model = "Unknown";
2488 		break;
2489 	}
2490 
2491 	if (mdp && mdp[0] == '\0')
2492 		snprintf(mdp, 79, "%s", model);
2493 
2494 	if (descp && descp[0] == '\0')
2495 		snprintf(descp, 255,
2496 			 "ATTO %s%s, Fibre Channel Adapter Initiator, Port %s",
2497 			 (tbolt) ? "ThunderLink FC " : "Celerity FC-",
2498 			 model,
2499 			 phba->Port);
2500 }
2501 
2502 /**
2503  * lpfc_get_hba_model_desc - Retrieve HBA device model name and description
2504  * @phba: pointer to lpfc hba data structure.
2505  * @mdp: pointer to the data structure to hold the derived model name.
2506  * @descp: pointer to the data structure to hold the derived description.
2507  *
2508  * This routine retrieves HBA's description based on its registered PCI device
2509  * ID. The @descp passed into this function points to an array of 256 chars. It
2510  * shall be returned with the model name, maximum speed, and the host bus type.
2511  * The @mdp passed into this function points to an array of 80 chars. When the
2512  * function returns, the @mdp will be filled with the model name.
2513  **/
2514 static void
2515 lpfc_get_hba_model_desc(struct lpfc_hba *phba, uint8_t *mdp, uint8_t *descp)
2516 {
2517 	lpfc_vpd_t *vp;
2518 	uint16_t dev_id = phba->pcidev->device;
2519 	int max_speed;
2520 	int GE = 0;
2521 	int oneConnect = 0; /* default is not a oneConnect */
2522 	struct {
2523 		char *name;
2524 		char *bus;
2525 		char *function;
2526 	} m = {"<Unknown>", "", ""};
2527 
2528 	if (mdp && mdp[0] != '\0'
2529 		&& descp && descp[0] != '\0')
2530 		return;
2531 
2532 	if (phba->pcidev->vendor == PCI_VENDOR_ID_ATTO) {
2533 		lpfc_get_atto_model_desc(phba, mdp, descp);
2534 		return;
2535 	}
2536 
2537 	if (phba->lmt & LMT_64Gb)
2538 		max_speed = 64;
2539 	else if (phba->lmt & LMT_32Gb)
2540 		max_speed = 32;
2541 	else if (phba->lmt & LMT_16Gb)
2542 		max_speed = 16;
2543 	else if (phba->lmt & LMT_10Gb)
2544 		max_speed = 10;
2545 	else if (phba->lmt & LMT_8Gb)
2546 		max_speed = 8;
2547 	else if (phba->lmt & LMT_4Gb)
2548 		max_speed = 4;
2549 	else if (phba->lmt & LMT_2Gb)
2550 		max_speed = 2;
2551 	else if (phba->lmt & LMT_1Gb)
2552 		max_speed = 1;
2553 	else
2554 		max_speed = 0;
2555 
2556 	vp = &phba->vpd;
2557 
2558 	switch (dev_id) {
2559 	case PCI_DEVICE_ID_FIREFLY:
2560 		m = (typeof(m)){"LP6000", "PCI",
2561 				"Obsolete, Unsupported Fibre Channel Adapter"};
2562 		break;
2563 	case PCI_DEVICE_ID_SUPERFLY:
2564 		if (vp->rev.biuRev >= 1 && vp->rev.biuRev <= 3)
2565 			m = (typeof(m)){"LP7000", "PCI", ""};
2566 		else
2567 			m = (typeof(m)){"LP7000E", "PCI", ""};
2568 		m.function = "Obsolete, Unsupported Fibre Channel Adapter";
2569 		break;
2570 	case PCI_DEVICE_ID_DRAGONFLY:
2571 		m = (typeof(m)){"LP8000", "PCI",
2572 				"Obsolete, Unsupported Fibre Channel Adapter"};
2573 		break;
2574 	case PCI_DEVICE_ID_CENTAUR:
2575 		if (FC_JEDEC_ID(vp->rev.biuRev) == CENTAUR_2G_JEDEC_ID)
2576 			m = (typeof(m)){"LP9002", "PCI", ""};
2577 		else
2578 			m = (typeof(m)){"LP9000", "PCI", ""};
2579 		m.function = "Obsolete, Unsupported Fibre Channel Adapter";
2580 		break;
2581 	case PCI_DEVICE_ID_RFLY:
2582 		m = (typeof(m)){"LP952", "PCI",
2583 				"Obsolete, Unsupported Fibre Channel Adapter"};
2584 		break;
2585 	case PCI_DEVICE_ID_PEGASUS:
2586 		m = (typeof(m)){"LP9802", "PCI-X",
2587 				"Obsolete, Unsupported Fibre Channel Adapter"};
2588 		break;
2589 	case PCI_DEVICE_ID_THOR:
2590 		m = (typeof(m)){"LP10000", "PCI-X",
2591 				"Obsolete, Unsupported Fibre Channel Adapter"};
2592 		break;
2593 	case PCI_DEVICE_ID_VIPER:
2594 		m = (typeof(m)){"LPX1000",  "PCI-X",
2595 				"Obsolete, Unsupported Fibre Channel Adapter"};
2596 		break;
2597 	case PCI_DEVICE_ID_PFLY:
2598 		m = (typeof(m)){"LP982", "PCI-X",
2599 				"Obsolete, Unsupported Fibre Channel Adapter"};
2600 		break;
2601 	case PCI_DEVICE_ID_TFLY:
2602 		m = (typeof(m)){"LP1050", "PCI-X",
2603 				"Obsolete, Unsupported Fibre Channel Adapter"};
2604 		break;
2605 	case PCI_DEVICE_ID_HELIOS:
2606 		m = (typeof(m)){"LP11000", "PCI-X2",
2607 				"Obsolete, Unsupported Fibre Channel Adapter"};
2608 		break;
2609 	case PCI_DEVICE_ID_HELIOS_SCSP:
2610 		m = (typeof(m)){"LP11000-SP", "PCI-X2",
2611 				"Obsolete, Unsupported Fibre Channel Adapter"};
2612 		break;
2613 	case PCI_DEVICE_ID_HELIOS_DCSP:
2614 		m = (typeof(m)){"LP11002-SP",  "PCI-X2",
2615 				"Obsolete, Unsupported Fibre Channel Adapter"};
2616 		break;
2617 	case PCI_DEVICE_ID_NEPTUNE:
2618 		m = (typeof(m)){"LPe1000", "PCIe",
2619 				"Obsolete, Unsupported Fibre Channel Adapter"};
2620 		break;
2621 	case PCI_DEVICE_ID_NEPTUNE_SCSP:
2622 		m = (typeof(m)){"LPe1000-SP", "PCIe",
2623 				"Obsolete, Unsupported Fibre Channel Adapter"};
2624 		break;
2625 	case PCI_DEVICE_ID_NEPTUNE_DCSP:
2626 		m = (typeof(m)){"LPe1002-SP", "PCIe",
2627 				"Obsolete, Unsupported Fibre Channel Adapter"};
2628 		break;
2629 	case PCI_DEVICE_ID_BMID:
2630 		m = (typeof(m)){"LP1150", "PCI-X2",
2631 				"Obsolete, Unsupported Fibre Channel Adapter"};
2632 		break;
2633 	case PCI_DEVICE_ID_BSMB:
2634 		m = (typeof(m)){"LP111", "PCI-X2",
2635 				"Obsolete, Unsupported Fibre Channel Adapter"};
2636 		break;
2637 	case PCI_DEVICE_ID_ZEPHYR:
2638 		m = (typeof(m)){"LPe11000", "PCIe",
2639 				"Obsolete, Unsupported Fibre Channel Adapter"};
2640 		break;
2641 	case PCI_DEVICE_ID_ZEPHYR_SCSP:
2642 		m = (typeof(m)){"LPe11000", "PCIe",
2643 				"Obsolete, Unsupported Fibre Channel Adapter"};
2644 		break;
2645 	case PCI_DEVICE_ID_ZEPHYR_DCSP:
2646 		m = (typeof(m)){"LP2105", "PCIe",
2647 				"Obsolete, Unsupported FCoE Adapter"};
2648 		GE = 1;
2649 		break;
2650 	case PCI_DEVICE_ID_ZMID:
2651 		m = (typeof(m)){"LPe1150", "PCIe",
2652 				"Obsolete, Unsupported Fibre Channel Adapter"};
2653 		break;
2654 	case PCI_DEVICE_ID_ZSMB:
2655 		m = (typeof(m)){"LPe111", "PCIe",
2656 				"Obsolete, Unsupported Fibre Channel Adapter"};
2657 		break;
2658 	case PCI_DEVICE_ID_LP101:
2659 		m = (typeof(m)){"LP101", "PCI-X",
2660 				"Obsolete, Unsupported Fibre Channel Adapter"};
2661 		break;
2662 	case PCI_DEVICE_ID_LP10000S:
2663 		m = (typeof(m)){"LP10000-S", "PCI",
2664 				"Obsolete, Unsupported Fibre Channel Adapter"};
2665 		break;
2666 	case PCI_DEVICE_ID_LP11000S:
2667 		m = (typeof(m)){"LP11000-S", "PCI-X2",
2668 				"Obsolete, Unsupported Fibre Channel Adapter"};
2669 		break;
2670 	case PCI_DEVICE_ID_LPE11000S:
2671 		m = (typeof(m)){"LPe11000-S", "PCIe",
2672 				"Obsolete, Unsupported Fibre Channel Adapter"};
2673 		break;
2674 	case PCI_DEVICE_ID_SAT:
2675 		m = (typeof(m)){"LPe12000", "PCIe",
2676 				"Obsolete, Unsupported Fibre Channel Adapter"};
2677 		break;
2678 	case PCI_DEVICE_ID_SAT_MID:
2679 		m = (typeof(m)){"LPe1250", "PCIe",
2680 				"Obsolete, Unsupported Fibre Channel Adapter"};
2681 		break;
2682 	case PCI_DEVICE_ID_SAT_SMB:
2683 		m = (typeof(m)){"LPe121", "PCIe",
2684 				"Obsolete, Unsupported Fibre Channel Adapter"};
2685 		break;
2686 	case PCI_DEVICE_ID_SAT_DCSP:
2687 		m = (typeof(m)){"LPe12002-SP", "PCIe",
2688 				"Obsolete, Unsupported Fibre Channel Adapter"};
2689 		break;
2690 	case PCI_DEVICE_ID_SAT_SCSP:
2691 		m = (typeof(m)){"LPe12000-SP", "PCIe",
2692 				"Obsolete, Unsupported Fibre Channel Adapter"};
2693 		break;
2694 	case PCI_DEVICE_ID_SAT_S:
2695 		m = (typeof(m)){"LPe12000-S", "PCIe",
2696 				"Obsolete, Unsupported Fibre Channel Adapter"};
2697 		break;
2698 	case PCI_DEVICE_ID_PROTEUS_VF:
2699 		m = (typeof(m)){"LPev12000", "PCIe IOV",
2700 				"Obsolete, Unsupported Fibre Channel Adapter"};
2701 		break;
2702 	case PCI_DEVICE_ID_PROTEUS_PF:
2703 		m = (typeof(m)){"LPev12000", "PCIe IOV",
2704 				"Obsolete, Unsupported Fibre Channel Adapter"};
2705 		break;
2706 	case PCI_DEVICE_ID_PROTEUS_S:
2707 		m = (typeof(m)){"LPemv12002-S", "PCIe IOV",
2708 				"Obsolete, Unsupported Fibre Channel Adapter"};
2709 		break;
2710 	case PCI_DEVICE_ID_TIGERSHARK:
2711 		oneConnect = 1;
2712 		m = (typeof(m)){"OCe10100", "PCIe",
2713 				"Obsolete, Unsupported FCoE Adapter"};
2714 		break;
2715 	case PCI_DEVICE_ID_TOMCAT:
2716 		oneConnect = 1;
2717 		m = (typeof(m)){"OCe11100", "PCIe",
2718 				"Obsolete, Unsupported FCoE Adapter"};
2719 		break;
2720 	case PCI_DEVICE_ID_FALCON:
2721 		m = (typeof(m)){"LPSe12002-ML1-E", "PCIe",
2722 				"Obsolete, Unsupported Fibre Channel Adapter"};
2723 		break;
2724 	case PCI_DEVICE_ID_BALIUS:
2725 		m = (typeof(m)){"LPVe12002", "PCIe Shared I/O",
2726 				"Obsolete, Unsupported Fibre Channel Adapter"};
2727 		break;
2728 	case PCI_DEVICE_ID_LANCER_FC:
2729 		m = (typeof(m)){"LPe16000", "PCIe",
2730 				"Obsolete, Unsupported Fibre Channel Adapter"};
2731 		break;
2732 	case PCI_DEVICE_ID_LANCER_FC_VF:
2733 		m = (typeof(m)){"LPe16000", "PCIe",
2734 				"Obsolete, Unsupported Fibre Channel Adapter"};
2735 		break;
2736 	case PCI_DEVICE_ID_LANCER_FCOE:
2737 		oneConnect = 1;
2738 		m = (typeof(m)){"OCe15100", "PCIe",
2739 				"Obsolete, Unsupported FCoE Adapter"};
2740 		break;
2741 	case PCI_DEVICE_ID_LANCER_FCOE_VF:
2742 		oneConnect = 1;
2743 		m = (typeof(m)){"OCe15100", "PCIe",
2744 				"Obsolete, Unsupported FCoE Adapter"};
2745 		break;
2746 	case PCI_DEVICE_ID_LANCER_G6_FC:
2747 		m = (typeof(m)){"LPe32000", "PCIe", "Fibre Channel Adapter"};
2748 		break;
2749 	case PCI_DEVICE_ID_LANCER_G7_FC:
2750 		m = (typeof(m)){"LPe36000", "PCIe", "Fibre Channel Adapter"};
2751 		break;
2752 	case PCI_DEVICE_ID_LANCER_G7P_FC:
2753 		m = (typeof(m)){"LPe38000", "PCIe", "Fibre Channel Adapter"};
2754 		break;
2755 	case PCI_DEVICE_ID_SKYHAWK:
2756 	case PCI_DEVICE_ID_SKYHAWK_VF:
2757 		oneConnect = 1;
2758 		m = (typeof(m)){"OCe14000", "PCIe",
2759 				"Obsolete, Unsupported FCoE Adapter"};
2760 		break;
2761 	default:
2762 		m = (typeof(m)){"Unknown", "", ""};
2763 		break;
2764 	}
2765 
2766 	if (mdp && mdp[0] == '\0')
2767 		snprintf(mdp, 79,"%s", m.name);
2768 	/*
2769 	 * oneConnect hba requires special processing, they are all initiators
2770 	 * and we put the port number on the end
2771 	 */
2772 	if (descp && descp[0] == '\0') {
2773 		if (oneConnect)
2774 			snprintf(descp, 255,
2775 				"Emulex OneConnect %s, %s Initiator %s",
2776 				m.name, m.function,
2777 				phba->Port);
2778 		else if (max_speed == 0)
2779 			snprintf(descp, 255,
2780 				"Emulex %s %s %s",
2781 				m.name, m.bus, m.function);
2782 		else
2783 			snprintf(descp, 255,
2784 				"Emulex %s %d%s %s %s",
2785 				m.name, max_speed, (GE) ? "GE" : "Gb",
2786 				m.bus, m.function);
2787 	}
2788 }
2789 
2790 /**
2791  * lpfc_sli3_post_buffer - Post IOCB(s) with DMA buffer descriptor(s) to a IOCB ring
2792  * @phba: pointer to lpfc hba data structure.
2793  * @pring: pointer to a IOCB ring.
2794  * @cnt: the number of IOCBs to be posted to the IOCB ring.
2795  *
2796  * This routine posts a given number of IOCBs with the associated DMA buffer
2797  * descriptors specified by the cnt argument to the given IOCB ring.
2798  *
2799  * Return codes
2800  *   The number of IOCBs NOT able to be posted to the IOCB ring.
2801  **/
2802 int
2803 lpfc_sli3_post_buffer(struct lpfc_hba *phba, struct lpfc_sli_ring *pring, int cnt)
2804 {
2805 	IOCB_t *icmd;
2806 	struct lpfc_iocbq *iocb;
2807 	struct lpfc_dmabuf *mp1, *mp2;
2808 
2809 	cnt += pring->missbufcnt;
2810 
2811 	/* While there are buffers to post */
2812 	while (cnt > 0) {
2813 		/* Allocate buffer for  command iocb */
2814 		iocb = lpfc_sli_get_iocbq(phba);
2815 		if (iocb == NULL) {
2816 			pring->missbufcnt = cnt;
2817 			return cnt;
2818 		}
2819 		icmd = &iocb->iocb;
2820 
2821 		/* 2 buffers can be posted per command */
2822 		/* Allocate buffer to post */
2823 		mp1 = kmalloc(sizeof (struct lpfc_dmabuf), GFP_KERNEL);
2824 		if (mp1)
2825 		    mp1->virt = lpfc_mbuf_alloc(phba, MEM_PRI, &mp1->phys);
2826 		if (!mp1 || !mp1->virt) {
2827 			kfree(mp1);
2828 			lpfc_sli_release_iocbq(phba, iocb);
2829 			pring->missbufcnt = cnt;
2830 			return cnt;
2831 		}
2832 
2833 		INIT_LIST_HEAD(&mp1->list);
2834 		/* Allocate buffer to post */
2835 		if (cnt > 1) {
2836 			mp2 = kmalloc(sizeof (struct lpfc_dmabuf), GFP_KERNEL);
2837 			if (mp2)
2838 				mp2->virt = lpfc_mbuf_alloc(phba, MEM_PRI,
2839 							    &mp2->phys);
2840 			if (!mp2 || !mp2->virt) {
2841 				kfree(mp2);
2842 				lpfc_mbuf_free(phba, mp1->virt, mp1->phys);
2843 				kfree(mp1);
2844 				lpfc_sli_release_iocbq(phba, iocb);
2845 				pring->missbufcnt = cnt;
2846 				return cnt;
2847 			}
2848 
2849 			INIT_LIST_HEAD(&mp2->list);
2850 		} else {
2851 			mp2 = NULL;
2852 		}
2853 
2854 		icmd->un.cont64[0].addrHigh = putPaddrHigh(mp1->phys);
2855 		icmd->un.cont64[0].addrLow = putPaddrLow(mp1->phys);
2856 		icmd->un.cont64[0].tus.f.bdeSize = FCELSSIZE;
2857 		icmd->ulpBdeCount = 1;
2858 		cnt--;
2859 		if (mp2) {
2860 			icmd->un.cont64[1].addrHigh = putPaddrHigh(mp2->phys);
2861 			icmd->un.cont64[1].addrLow = putPaddrLow(mp2->phys);
2862 			icmd->un.cont64[1].tus.f.bdeSize = FCELSSIZE;
2863 			cnt--;
2864 			icmd->ulpBdeCount = 2;
2865 		}
2866 
2867 		icmd->ulpCommand = CMD_QUE_RING_BUF64_CN;
2868 		icmd->ulpLe = 1;
2869 
2870 		if (lpfc_sli_issue_iocb(phba, pring->ringno, iocb, 0) ==
2871 		    IOCB_ERROR) {
2872 			lpfc_mbuf_free(phba, mp1->virt, mp1->phys);
2873 			kfree(mp1);
2874 			cnt++;
2875 			if (mp2) {
2876 				lpfc_mbuf_free(phba, mp2->virt, mp2->phys);
2877 				kfree(mp2);
2878 				cnt++;
2879 			}
2880 			lpfc_sli_release_iocbq(phba, iocb);
2881 			pring->missbufcnt = cnt;
2882 			return cnt;
2883 		}
2884 		lpfc_sli_ringpostbuf_put(phba, pring, mp1);
2885 		if (mp2)
2886 			lpfc_sli_ringpostbuf_put(phba, pring, mp2);
2887 	}
2888 	pring->missbufcnt = 0;
2889 	return 0;
2890 }
2891 
2892 /**
2893  * lpfc_post_rcv_buf - Post the initial receive IOCB buffers to ELS ring
2894  * @phba: pointer to lpfc hba data structure.
2895  *
2896  * This routine posts initial receive IOCB buffers to the ELS ring. The
2897  * current number of initial IOCB buffers specified by LPFC_BUF_RING0 is
2898  * set to 64 IOCBs. SLI3 only.
2899  *
2900  * Return codes
2901  *   0 - success (currently always success)
2902  **/
2903 static int
2904 lpfc_post_rcv_buf(struct lpfc_hba *phba)
2905 {
2906 	struct lpfc_sli *psli = &phba->sli;
2907 
2908 	/* Ring 0, ELS / CT buffers */
2909 	lpfc_sli3_post_buffer(phba, &psli->sli3_ring[LPFC_ELS_RING], LPFC_BUF_RING0);
2910 	/* Ring 2 - FCP no buffers needed */
2911 
2912 	return 0;
2913 }
2914 
2915 #define S(N,V) (((V)<<(N))|((V)>>(32-(N))))
2916 
2917 /**
2918  * lpfc_sha_init - Set up initial array of hash table entries
2919  * @HashResultPointer: pointer to an array as hash table.
2920  *
2921  * This routine sets up the initial values to the array of hash table entries
2922  * for the LC HBAs.
2923  **/
2924 static void
2925 lpfc_sha_init(uint32_t * HashResultPointer)
2926 {
2927 	HashResultPointer[0] = 0x67452301;
2928 	HashResultPointer[1] = 0xEFCDAB89;
2929 	HashResultPointer[2] = 0x98BADCFE;
2930 	HashResultPointer[3] = 0x10325476;
2931 	HashResultPointer[4] = 0xC3D2E1F0;
2932 }
2933 
2934 /**
2935  * lpfc_sha_iterate - Iterate initial hash table with the working hash table
2936  * @HashResultPointer: pointer to an initial/result hash table.
2937  * @HashWorkingPointer: pointer to an working hash table.
2938  *
2939  * This routine iterates an initial hash table pointed by @HashResultPointer
2940  * with the values from the working hash table pointeed by @HashWorkingPointer.
2941  * The results are putting back to the initial hash table, returned through
2942  * the @HashResultPointer as the result hash table.
2943  **/
2944 static void
2945 lpfc_sha_iterate(uint32_t * HashResultPointer, uint32_t * HashWorkingPointer)
2946 {
2947 	int t;
2948 	uint32_t TEMP;
2949 	uint32_t A, B, C, D, E;
2950 	t = 16;
2951 	do {
2952 		HashWorkingPointer[t] =
2953 		    S(1,
2954 		      HashWorkingPointer[t - 3] ^ HashWorkingPointer[t -
2955 								     8] ^
2956 		      HashWorkingPointer[t - 14] ^ HashWorkingPointer[t - 16]);
2957 	} while (++t <= 79);
2958 	t = 0;
2959 	A = HashResultPointer[0];
2960 	B = HashResultPointer[1];
2961 	C = HashResultPointer[2];
2962 	D = HashResultPointer[3];
2963 	E = HashResultPointer[4];
2964 
2965 	do {
2966 		if (t < 20) {
2967 			TEMP = ((B & C) | ((~B) & D)) + 0x5A827999;
2968 		} else if (t < 40) {
2969 			TEMP = (B ^ C ^ D) + 0x6ED9EBA1;
2970 		} else if (t < 60) {
2971 			TEMP = ((B & C) | (B & D) | (C & D)) + 0x8F1BBCDC;
2972 		} else {
2973 			TEMP = (B ^ C ^ D) + 0xCA62C1D6;
2974 		}
2975 		TEMP += S(5, A) + E + HashWorkingPointer[t];
2976 		E = D;
2977 		D = C;
2978 		C = S(30, B);
2979 		B = A;
2980 		A = TEMP;
2981 	} while (++t <= 79);
2982 
2983 	HashResultPointer[0] += A;
2984 	HashResultPointer[1] += B;
2985 	HashResultPointer[2] += C;
2986 	HashResultPointer[3] += D;
2987 	HashResultPointer[4] += E;
2988 
2989 }
2990 
2991 /**
2992  * lpfc_challenge_key - Create challenge key based on WWPN of the HBA
2993  * @RandomChallenge: pointer to the entry of host challenge random number array.
2994  * @HashWorking: pointer to the entry of the working hash array.
2995  *
2996  * This routine calculates the working hash array referred by @HashWorking
2997  * from the challenge random numbers associated with the host, referred by
2998  * @RandomChallenge. The result is put into the entry of the working hash
2999  * array and returned by reference through @HashWorking.
3000  **/
3001 static void
3002 lpfc_challenge_key(uint32_t * RandomChallenge, uint32_t * HashWorking)
3003 {
3004 	*HashWorking = (*RandomChallenge ^ *HashWorking);
3005 }
3006 
3007 /**
3008  * lpfc_hba_init - Perform special handling for LC HBA initialization
3009  * @phba: pointer to lpfc hba data structure.
3010  * @hbainit: pointer to an array of unsigned 32-bit integers.
3011  *
3012  * This routine performs the special handling for LC HBA initialization.
3013  **/
3014 void
3015 lpfc_hba_init(struct lpfc_hba *phba, uint32_t *hbainit)
3016 {
3017 	int t;
3018 	uint32_t *HashWorking;
3019 	uint32_t *pwwnn = (uint32_t *) phba->wwnn;
3020 
3021 	HashWorking = kcalloc(80, sizeof(uint32_t), GFP_KERNEL);
3022 	if (!HashWorking)
3023 		return;
3024 
3025 	HashWorking[0] = HashWorking[78] = *pwwnn++;
3026 	HashWorking[1] = HashWorking[79] = *pwwnn;
3027 
3028 	for (t = 0; t < 7; t++)
3029 		lpfc_challenge_key(phba->RandomData + t, HashWorking + t);
3030 
3031 	lpfc_sha_init(hbainit);
3032 	lpfc_sha_iterate(hbainit, HashWorking);
3033 	kfree(HashWorking);
3034 }
3035 
3036 /**
3037  * lpfc_cleanup - Performs vport cleanups before deleting a vport
3038  * @vport: pointer to a virtual N_Port data structure.
3039  *
3040  * This routine performs the necessary cleanups before deleting the @vport.
3041  * It invokes the discovery state machine to perform necessary state
3042  * transitions and to release the ndlps associated with the @vport. Note,
3043  * the physical port is treated as @vport 0.
3044  **/
3045 void
3046 lpfc_cleanup(struct lpfc_vport *vport)
3047 {
3048 	struct lpfc_hba   *phba = vport->phba;
3049 	struct lpfc_nodelist *ndlp, *next_ndlp;
3050 	int i = 0;
3051 
3052 	if (phba->link_state > LPFC_LINK_DOWN)
3053 		lpfc_port_link_failure(vport);
3054 
3055 	/* Clean up VMID resources */
3056 	if (lpfc_is_vmid_enabled(phba))
3057 		lpfc_vmid_vport_cleanup(vport);
3058 
3059 	list_for_each_entry_safe(ndlp, next_ndlp, &vport->fc_nodes, nlp_listp) {
3060 		if (vport->port_type != LPFC_PHYSICAL_PORT &&
3061 		    ndlp->nlp_DID == Fabric_DID) {
3062 			/* Just free up ndlp with Fabric_DID for vports */
3063 			lpfc_nlp_put(ndlp);
3064 			continue;
3065 		}
3066 
3067 		if (ndlp->nlp_DID == Fabric_Cntl_DID &&
3068 		    ndlp->nlp_state == NLP_STE_UNUSED_NODE) {
3069 			lpfc_nlp_put(ndlp);
3070 			continue;
3071 		}
3072 
3073 		/* Fabric Ports not in UNMAPPED state are cleaned up in the
3074 		 * DEVICE_RM event.
3075 		 */
3076 		if (ndlp->nlp_type & NLP_FABRIC &&
3077 		    ndlp->nlp_state == NLP_STE_UNMAPPED_NODE)
3078 			lpfc_disc_state_machine(vport, ndlp, NULL,
3079 					NLP_EVT_DEVICE_RECOVERY);
3080 
3081 		if (!(ndlp->fc4_xpt_flags & (NVME_XPT_REGD|SCSI_XPT_REGD)))
3082 			lpfc_disc_state_machine(vport, ndlp, NULL,
3083 					NLP_EVT_DEVICE_RM);
3084 	}
3085 
3086 	/* This is a special case flush to return all
3087 	 * IOs before entering this loop. There are
3088 	 * two points in the code where a flush is
3089 	 * avoided if the FC_UNLOADING flag is set.
3090 	 * one is in the multipool destroy,
3091 	 * (this prevents a crash) and the other is
3092 	 * in the nvme abort handler, ( also prevents
3093 	 * a crash). Both of these exceptions are
3094 	 * cases where the slot is still accessible.
3095 	 * The flush here is only when the pci slot
3096 	 * is offline.
3097 	 */
3098 	if (test_bit(FC_UNLOADING, &vport->load_flag) &&
3099 	    pci_channel_offline(phba->pcidev))
3100 		lpfc_sli_flush_io_rings(vport->phba);
3101 
3102 	/* At this point, ALL ndlp's should be gone
3103 	 * because of the previous NLP_EVT_DEVICE_RM.
3104 	 * Lets wait for this to happen, if needed.
3105 	 */
3106 	while (!list_empty(&vport->fc_nodes)) {
3107 		if (i++ > 3000) {
3108 			lpfc_printf_vlog(vport, KERN_ERR,
3109 					 LOG_TRACE_EVENT,
3110 				"0233 Nodelist not empty\n");
3111 			list_for_each_entry_safe(ndlp, next_ndlp,
3112 						&vport->fc_nodes, nlp_listp) {
3113 				lpfc_printf_vlog(ndlp->vport, KERN_ERR,
3114 						 LOG_DISCOVERY,
3115 						 "0282 did:x%x ndlp:x%px "
3116 						 "refcnt:%d xflags x%x "
3117 						 "nflag x%lx\n",
3118 						 ndlp->nlp_DID, (void *)ndlp,
3119 						 kref_read(&ndlp->kref),
3120 						 ndlp->fc4_xpt_flags,
3121 						 ndlp->nlp_flag);
3122 			}
3123 			break;
3124 		}
3125 
3126 		/* Wait for any activity on ndlps to settle */
3127 		msleep(10);
3128 	}
3129 	lpfc_cleanup_vports_rrqs(vport, NULL);
3130 }
3131 
3132 /**
3133  * lpfc_stop_vport_timers - Stop all the timers associated with a vport
3134  * @vport: pointer to a virtual N_Port data structure.
3135  *
3136  * This routine stops all the timers associated with a @vport. This function
3137  * is invoked before disabling or deleting a @vport. Note that the physical
3138  * port is treated as @vport 0.
3139  **/
3140 void
3141 lpfc_stop_vport_timers(struct lpfc_vport *vport)
3142 {
3143 	timer_delete_sync(&vport->els_tmofunc);
3144 	timer_delete_sync(&vport->delayed_disc_tmo);
3145 	lpfc_can_disctmo(vport);
3146 	return;
3147 }
3148 
3149 /**
3150  * __lpfc_sli4_stop_fcf_redisc_wait_timer - Stop FCF rediscovery wait timer
3151  * @phba: pointer to lpfc hba data structure.
3152  *
3153  * This routine stops the SLI4 FCF rediscover wait timer if it's on. The
3154  * caller of this routine should already hold the host lock.
3155  **/
3156 void
3157 __lpfc_sli4_stop_fcf_redisc_wait_timer(struct lpfc_hba *phba)
3158 {
3159 	/* Clear pending FCF rediscovery wait flag */
3160 	phba->fcf.fcf_flag &= ~FCF_REDISC_PEND;
3161 
3162 	/* Now, try to stop the timer */
3163 	timer_delete(&phba->fcf.redisc_wait);
3164 }
3165 
3166 /**
3167  * lpfc_sli4_stop_fcf_redisc_wait_timer - Stop FCF rediscovery wait timer
3168  * @phba: pointer to lpfc hba data structure.
3169  *
3170  * This routine stops the SLI4 FCF rediscover wait timer if it's on. It
3171  * checks whether the FCF rediscovery wait timer is pending with the host
3172  * lock held before proceeding with disabling the timer and clearing the
3173  * wait timer pendig flag.
3174  **/
3175 void
3176 lpfc_sli4_stop_fcf_redisc_wait_timer(struct lpfc_hba *phba)
3177 {
3178 	spin_lock_irq(&phba->hbalock);
3179 	if (!(phba->fcf.fcf_flag & FCF_REDISC_PEND)) {
3180 		/* FCF rediscovery timer already fired or stopped */
3181 		spin_unlock_irq(&phba->hbalock);
3182 		return;
3183 	}
3184 	__lpfc_sli4_stop_fcf_redisc_wait_timer(phba);
3185 	/* Clear failover in progress flags */
3186 	phba->fcf.fcf_flag &= ~(FCF_DEAD_DISC | FCF_ACVL_DISC);
3187 	spin_unlock_irq(&phba->hbalock);
3188 }
3189 
3190 /**
3191  * lpfc_cmf_stop - Stop CMF processing
3192  * @phba: pointer to lpfc hba data structure.
3193  *
3194  * This is called when the link goes down or if CMF mode is turned OFF.
3195  * It is also called when going offline or unloaded just before the
3196  * congestion info buffer is unregistered.
3197  **/
3198 void
3199 lpfc_cmf_stop(struct lpfc_hba *phba)
3200 {
3201 	int cpu;
3202 	struct lpfc_cgn_stat *cgs;
3203 
3204 	/* We only do something if CMF is enabled */
3205 	if (!phba->sli4_hba.pc_sli4_params.cmf)
3206 		return;
3207 
3208 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
3209 			"6221 Stop CMF / Cancel Timer\n");
3210 
3211 	/* Cancel the CMF timer */
3212 	hrtimer_cancel(&phba->cmf_stats_timer);
3213 	hrtimer_cancel(&phba->cmf_timer);
3214 
3215 	/* Zero CMF counters */
3216 	atomic_set(&phba->cmf_busy, 0);
3217 	for_each_present_cpu(cpu) {
3218 		cgs = per_cpu_ptr(phba->cmf_stat, cpu);
3219 		atomic64_set(&cgs->total_bytes, 0);
3220 		atomic64_set(&cgs->rcv_bytes, 0);
3221 		atomic_set(&cgs->rx_io_cnt, 0);
3222 		atomic64_set(&cgs->rx_latency, 0);
3223 	}
3224 	atomic_set(&phba->cmf_bw_wait, 0);
3225 
3226 	/* Resume any blocked IO - Queue unblock on workqueue */
3227 	queue_work(phba->wq, &phba->unblock_request_work);
3228 }
3229 
3230 static inline uint64_t
3231 lpfc_get_max_line_rate(struct lpfc_hba *phba)
3232 {
3233 	uint64_t rate = lpfc_sli_port_speed_get(phba);
3234 
3235 	return ((((unsigned long)rate) * 1024 * 1024) / 10);
3236 }
3237 
3238 void
3239 lpfc_cmf_signal_init(struct lpfc_hba *phba)
3240 {
3241 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
3242 			"6223 Signal CMF init\n");
3243 
3244 	/* Use the new fc_linkspeed to recalculate */
3245 	phba->cmf_interval_rate = LPFC_CMF_INTERVAL;
3246 	phba->cmf_max_line_rate = lpfc_get_max_line_rate(phba);
3247 	phba->cmf_link_byte_count = div_u64(phba->cmf_max_line_rate *
3248 					    phba->cmf_interval_rate, 1000);
3249 	phba->cmf_max_bytes_per_interval = phba->cmf_link_byte_count;
3250 
3251 	/* This is a signal to firmware to sync up CMF BW with link speed */
3252 	lpfc_issue_cmf_sync_wqe(phba, 0, 0);
3253 }
3254 
3255 /**
3256  * lpfc_cmf_start - Start CMF processing
3257  * @phba: pointer to lpfc hba data structure.
3258  *
3259  * This is called when the link comes up or if CMF mode is turned OFF
3260  * to Monitor or Managed.
3261  **/
3262 void
3263 lpfc_cmf_start(struct lpfc_hba *phba)
3264 {
3265 	struct lpfc_cgn_stat *cgs;
3266 	int cpu;
3267 
3268 	/* We only do something if CMF is enabled */
3269 	if (!phba->sli4_hba.pc_sli4_params.cmf ||
3270 	    phba->cmf_active_mode == LPFC_CFG_OFF)
3271 		return;
3272 
3273 	/* Reinitialize congestion buffer info */
3274 	lpfc_init_congestion_buf(phba);
3275 
3276 	atomic_set(&phba->cgn_fabric_warn_cnt, 0);
3277 	atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
3278 	atomic_set(&phba->cgn_sync_alarm_cnt, 0);
3279 	atomic_set(&phba->cgn_sync_warn_cnt, 0);
3280 
3281 	atomic_set(&phba->cmf_busy, 0);
3282 	for_each_present_cpu(cpu) {
3283 		cgs = per_cpu_ptr(phba->cmf_stat, cpu);
3284 		atomic64_set(&cgs->total_bytes, 0);
3285 		atomic64_set(&cgs->rcv_bytes, 0);
3286 		atomic_set(&cgs->rx_io_cnt, 0);
3287 		atomic64_set(&cgs->rx_latency, 0);
3288 	}
3289 	phba->cmf_latency.tv_sec = 0;
3290 	phba->cmf_latency.tv_nsec = 0;
3291 
3292 	lpfc_cmf_signal_init(phba);
3293 
3294 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
3295 			"6222 Start CMF / Timer\n");
3296 
3297 	phba->cmf_timer_cnt = 0;
3298 	hrtimer_start(&phba->cmf_timer,
3299 		      ktime_set(0, LPFC_CMF_INTERVAL * NSEC_PER_MSEC),
3300 		      HRTIMER_MODE_REL);
3301 	hrtimer_start(&phba->cmf_stats_timer,
3302 		      ktime_set(0, LPFC_SEC_MIN * NSEC_PER_SEC),
3303 		      HRTIMER_MODE_REL);
3304 	/* Setup for latency check in IO cmpl routines */
3305 	ktime_get_real_ts64(&phba->cmf_latency);
3306 
3307 	atomic_set(&phba->cmf_bw_wait, 0);
3308 	atomic_set(&phba->cmf_stop_io, 0);
3309 }
3310 
3311 /**
3312  * lpfc_stop_hba_timers - Stop all the timers associated with an HBA
3313  * @phba: pointer to lpfc hba data structure.
3314  *
3315  * This routine stops all the timers associated with a HBA. This function is
3316  * invoked before either putting a HBA offline or unloading the driver.
3317  **/
3318 void
3319 lpfc_stop_hba_timers(struct lpfc_hba *phba)
3320 {
3321 	if (phba->pport)
3322 		lpfc_stop_vport_timers(phba->pport);
3323 	cancel_delayed_work_sync(&phba->eq_delay_work);
3324 	cancel_delayed_work_sync(&phba->idle_stat_delay_work);
3325 	timer_delete_sync(&phba->sli.mbox_tmo);
3326 	timer_delete_sync(&phba->fabric_block_timer);
3327 	timer_delete_sync(&phba->eratt_poll);
3328 	timer_delete_sync(&phba->hb_tmofunc);
3329 	if (phba->sli_rev == LPFC_SLI_REV4) {
3330 		timer_delete_sync(&phba->rrq_tmr);
3331 		clear_bit(HBA_RRQ_ACTIVE, &phba->hba_flag);
3332 	}
3333 	clear_bit(HBA_HBEAT_INP, &phba->hba_flag);
3334 	clear_bit(HBA_HBEAT_TMO, &phba->hba_flag);
3335 
3336 	switch (phba->pci_dev_grp) {
3337 	case LPFC_PCI_DEV_LP:
3338 		/* Stop any LightPulse device specific driver timers */
3339 		timer_delete_sync(&phba->fcp_poll_timer);
3340 		break;
3341 	case LPFC_PCI_DEV_OC:
3342 		/* Stop any OneConnect device specific driver timers */
3343 		lpfc_sli4_stop_fcf_redisc_wait_timer(phba);
3344 		break;
3345 	default:
3346 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3347 				"0297 Invalid device group (x%x)\n",
3348 				phba->pci_dev_grp);
3349 		break;
3350 	}
3351 	return;
3352 }
3353 
3354 /**
3355  * lpfc_block_mgmt_io - Mark a HBA's management interface as blocked
3356  * @phba: pointer to lpfc hba data structure.
3357  * @mbx_action: flag for mailbox no wait action.
3358  *
3359  * This routine marks a HBA's management interface as blocked. Once the HBA's
3360  * management interface is marked as blocked, all the user space access to
3361  * the HBA, whether they are from sysfs interface or libdfc interface will
3362  * all be blocked. The HBA is set to block the management interface when the
3363  * driver prepares the HBA interface for online or offline.
3364  **/
3365 static void
3366 lpfc_block_mgmt_io(struct lpfc_hba *phba, int mbx_action)
3367 {
3368 	unsigned long iflag;
3369 	uint8_t actcmd = MBX_HEARTBEAT;
3370 	unsigned long timeout;
3371 
3372 	spin_lock_irqsave(&phba->hbalock, iflag);
3373 	phba->sli.sli_flag |= LPFC_BLOCK_MGMT_IO;
3374 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3375 	if (mbx_action == LPFC_MBX_NO_WAIT)
3376 		return;
3377 	timeout = secs_to_jiffies(LPFC_MBOX_TMO) + jiffies;
3378 	spin_lock_irqsave(&phba->hbalock, iflag);
3379 	if (phba->sli.mbox_active) {
3380 		actcmd = phba->sli.mbox_active->u.mb.mbxCommand;
3381 		/* Determine how long we might wait for the active mailbox
3382 		 * command to be gracefully completed by firmware.
3383 		 */
3384 		timeout = secs_to_jiffies(lpfc_mbox_tmo_val(phba,
3385 				phba->sli.mbox_active)) + jiffies;
3386 	}
3387 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3388 
3389 	/* Wait for the outstnading mailbox command to complete */
3390 	while (phba->sli.mbox_active) {
3391 		/* Check active mailbox complete status every 2ms */
3392 		msleep(2);
3393 		if (time_after(jiffies, timeout)) {
3394 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3395 					"2813 Mgmt IO is Blocked %x "
3396 					"- mbox cmd %x still active\n",
3397 					phba->sli.sli_flag, actcmd);
3398 			break;
3399 		}
3400 	}
3401 }
3402 
3403 /**
3404  * lpfc_sli4_node_rpi_restore - Recover assigned RPIs for active nodes.
3405  * @phba: pointer to lpfc hba data structure.
3406  *
3407  * Allocate RPIs for all active remote nodes. This is needed whenever
3408  * an SLI4 adapter is reset and the driver is not unloading. Its purpose
3409  * is to fixup the temporary rpi assignments.
3410  **/
3411 void
3412 lpfc_sli4_node_rpi_restore(struct lpfc_hba *phba)
3413 {
3414 	struct lpfc_nodelist  *ndlp, *next_ndlp;
3415 	struct lpfc_vport **vports;
3416 	int i, rpi;
3417 
3418 	if (phba->sli_rev != LPFC_SLI_REV4)
3419 		return;
3420 
3421 	vports = lpfc_create_vport_work_array(phba);
3422 	if (!vports)
3423 		return;
3424 
3425 	for (i = 0; i <= phba->max_vports && vports[i]; i++) {
3426 		if (test_bit(FC_UNLOADING, &vports[i]->load_flag))
3427 			continue;
3428 
3429 		list_for_each_entry_safe(ndlp, next_ndlp,
3430 					 &vports[i]->fc_nodes,
3431 					 nlp_listp) {
3432 			rpi = lpfc_sli4_alloc_rpi(phba);
3433 			if (rpi == LPFC_RPI_ALLOC_ERROR) {
3434 				lpfc_printf_vlog(ndlp->vport, KERN_INFO,
3435 						 LOG_NODE | LOG_DISCOVERY,
3436 						 "0099 RPI alloc error for "
3437 						 "ndlp x%px DID:x%06x "
3438 						 "flg:x%lx\n",
3439 						 ndlp, ndlp->nlp_DID,
3440 						 ndlp->nlp_flag);
3441 				continue;
3442 			}
3443 			ndlp->nlp_rpi = rpi;
3444 			lpfc_printf_vlog(ndlp->vport, KERN_INFO,
3445 					 LOG_NODE | LOG_DISCOVERY,
3446 					 "0009 Assign RPI x%x to ndlp x%px "
3447 					 "DID:x%06x flg:x%lx\n",
3448 					 ndlp->nlp_rpi, ndlp, ndlp->nlp_DID,
3449 					 ndlp->nlp_flag);
3450 		}
3451 	}
3452 	lpfc_destroy_vport_work_array(phba, vports);
3453 }
3454 
3455 /**
3456  * lpfc_create_expedite_pool - create expedite pool
3457  * @phba: pointer to lpfc hba data structure.
3458  *
3459  * This routine moves a batch of XRIs from lpfc_io_buf_list_put of HWQ 0
3460  * to expedite pool. Mark them as expedite.
3461  **/
3462 static void lpfc_create_expedite_pool(struct lpfc_hba *phba)
3463 {
3464 	struct lpfc_sli4_hdw_queue *qp;
3465 	struct lpfc_io_buf *lpfc_ncmd;
3466 	struct lpfc_io_buf *lpfc_ncmd_next;
3467 	struct lpfc_epd_pool *epd_pool;
3468 	unsigned long iflag;
3469 
3470 	epd_pool = &phba->epd_pool;
3471 	qp = &phba->sli4_hba.hdwq[0];
3472 
3473 	spin_lock_init(&epd_pool->lock);
3474 	spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3475 	spin_lock(&epd_pool->lock);
3476 	INIT_LIST_HEAD(&epd_pool->list);
3477 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3478 				 &qp->lpfc_io_buf_list_put, list) {
3479 		list_move_tail(&lpfc_ncmd->list, &epd_pool->list);
3480 		lpfc_ncmd->expedite = true;
3481 		qp->put_io_bufs--;
3482 		epd_pool->count++;
3483 		if (epd_pool->count >= XRI_BATCH)
3484 			break;
3485 	}
3486 	spin_unlock(&epd_pool->lock);
3487 	spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3488 }
3489 
3490 /**
3491  * lpfc_destroy_expedite_pool - destroy expedite pool
3492  * @phba: pointer to lpfc hba data structure.
3493  *
3494  * This routine returns XRIs from expedite pool to lpfc_io_buf_list_put
3495  * of HWQ 0. Clear the mark.
3496  **/
3497 static void lpfc_destroy_expedite_pool(struct lpfc_hba *phba)
3498 {
3499 	struct lpfc_sli4_hdw_queue *qp;
3500 	struct lpfc_io_buf *lpfc_ncmd;
3501 	struct lpfc_io_buf *lpfc_ncmd_next;
3502 	struct lpfc_epd_pool *epd_pool;
3503 	unsigned long iflag;
3504 
3505 	epd_pool = &phba->epd_pool;
3506 	qp = &phba->sli4_hba.hdwq[0];
3507 
3508 	spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3509 	spin_lock(&epd_pool->lock);
3510 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3511 				 &epd_pool->list, list) {
3512 		list_move_tail(&lpfc_ncmd->list,
3513 			       &qp->lpfc_io_buf_list_put);
3514 		lpfc_ncmd->flags = false;
3515 		qp->put_io_bufs++;
3516 		epd_pool->count--;
3517 	}
3518 	spin_unlock(&epd_pool->lock);
3519 	spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3520 }
3521 
3522 /**
3523  * lpfc_create_multixri_pools - create multi-XRI pools
3524  * @phba: pointer to lpfc hba data structure.
3525  *
3526  * This routine initialize public, private per HWQ. Then, move XRIs from
3527  * lpfc_io_buf_list_put to public pool. High and low watermark are also
3528  * Initialized.
3529  **/
3530 void lpfc_create_multixri_pools(struct lpfc_hba *phba)
3531 {
3532 	u32 i, j;
3533 	u32 hwq_count;
3534 	u32 count_per_hwq;
3535 	struct lpfc_io_buf *lpfc_ncmd;
3536 	struct lpfc_io_buf *lpfc_ncmd_next;
3537 	unsigned long iflag;
3538 	struct lpfc_sli4_hdw_queue *qp;
3539 	struct lpfc_multixri_pool *multixri_pool;
3540 	struct lpfc_pbl_pool *pbl_pool;
3541 	struct lpfc_pvt_pool *pvt_pool;
3542 
3543 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3544 			"1234 num_hdw_queue=%d num_present_cpu=%d common_xri_cnt=%d\n",
3545 			phba->cfg_hdw_queue, phba->sli4_hba.num_present_cpu,
3546 			phba->sli4_hba.io_xri_cnt);
3547 
3548 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
3549 		lpfc_create_expedite_pool(phba);
3550 
3551 	hwq_count = phba->cfg_hdw_queue;
3552 	count_per_hwq = phba->sli4_hba.io_xri_cnt / hwq_count;
3553 
3554 	for (i = 0; i < hwq_count; i++) {
3555 		multixri_pool = kzalloc(sizeof(*multixri_pool), GFP_KERNEL);
3556 
3557 		if (!multixri_pool) {
3558 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3559 					"1238 Failed to allocate memory for "
3560 					"multixri_pool\n");
3561 
3562 			if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
3563 				lpfc_destroy_expedite_pool(phba);
3564 
3565 			j = 0;
3566 			while (j < i) {
3567 				qp = &phba->sli4_hba.hdwq[j];
3568 				kfree(qp->p_multixri_pool);
3569 				j++;
3570 			}
3571 			phba->cfg_xri_rebalancing = 0;
3572 			return;
3573 		}
3574 
3575 		qp = &phba->sli4_hba.hdwq[i];
3576 		qp->p_multixri_pool = multixri_pool;
3577 
3578 		multixri_pool->xri_limit = count_per_hwq;
3579 		multixri_pool->rrb_next_hwqid = i;
3580 
3581 		/* Deal with public free xri pool */
3582 		pbl_pool = &multixri_pool->pbl_pool;
3583 		spin_lock_init(&pbl_pool->lock);
3584 		spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3585 		spin_lock(&pbl_pool->lock);
3586 		INIT_LIST_HEAD(&pbl_pool->list);
3587 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3588 					 &qp->lpfc_io_buf_list_put, list) {
3589 			list_move_tail(&lpfc_ncmd->list, &pbl_pool->list);
3590 			qp->put_io_bufs--;
3591 			pbl_pool->count++;
3592 		}
3593 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3594 				"1235 Moved %d buffers from PUT list over to pbl_pool[%d]\n",
3595 				pbl_pool->count, i);
3596 		spin_unlock(&pbl_pool->lock);
3597 		spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3598 
3599 		/* Deal with private free xri pool */
3600 		pvt_pool = &multixri_pool->pvt_pool;
3601 		pvt_pool->high_watermark = multixri_pool->xri_limit / 2;
3602 		pvt_pool->low_watermark = XRI_BATCH;
3603 		spin_lock_init(&pvt_pool->lock);
3604 		spin_lock_irqsave(&pvt_pool->lock, iflag);
3605 		INIT_LIST_HEAD(&pvt_pool->list);
3606 		pvt_pool->count = 0;
3607 		spin_unlock_irqrestore(&pvt_pool->lock, iflag);
3608 	}
3609 }
3610 
3611 /**
3612  * lpfc_destroy_multixri_pools - destroy multi-XRI pools
3613  * @phba: pointer to lpfc hba data structure.
3614  *
3615  * This routine returns XRIs from public/private to lpfc_io_buf_list_put.
3616  **/
3617 static void lpfc_destroy_multixri_pools(struct lpfc_hba *phba)
3618 {
3619 	u32 i;
3620 	u32 hwq_count;
3621 	struct lpfc_io_buf *lpfc_ncmd;
3622 	struct lpfc_io_buf *lpfc_ncmd_next;
3623 	unsigned long iflag;
3624 	struct lpfc_sli4_hdw_queue *qp;
3625 	struct lpfc_multixri_pool *multixri_pool;
3626 	struct lpfc_pbl_pool *pbl_pool;
3627 	struct lpfc_pvt_pool *pvt_pool;
3628 
3629 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
3630 		lpfc_destroy_expedite_pool(phba);
3631 
3632 	if (!test_bit(FC_UNLOADING, &phba->pport->load_flag))
3633 		lpfc_sli_flush_io_rings(phba);
3634 
3635 	hwq_count = phba->cfg_hdw_queue;
3636 
3637 	for (i = 0; i < hwq_count; i++) {
3638 		qp = &phba->sli4_hba.hdwq[i];
3639 		multixri_pool = qp->p_multixri_pool;
3640 		if (!multixri_pool)
3641 			continue;
3642 
3643 		qp->p_multixri_pool = NULL;
3644 
3645 		spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3646 
3647 		/* Deal with public free xri pool */
3648 		pbl_pool = &multixri_pool->pbl_pool;
3649 		spin_lock(&pbl_pool->lock);
3650 
3651 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3652 				"1236 Moving %d buffers from pbl_pool[%d] TO PUT list\n",
3653 				pbl_pool->count, i);
3654 
3655 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3656 					 &pbl_pool->list, list) {
3657 			list_move_tail(&lpfc_ncmd->list,
3658 				       &qp->lpfc_io_buf_list_put);
3659 			qp->put_io_bufs++;
3660 			pbl_pool->count--;
3661 		}
3662 
3663 		INIT_LIST_HEAD(&pbl_pool->list);
3664 		pbl_pool->count = 0;
3665 
3666 		spin_unlock(&pbl_pool->lock);
3667 
3668 		/* Deal with private free xri pool */
3669 		pvt_pool = &multixri_pool->pvt_pool;
3670 		spin_lock(&pvt_pool->lock);
3671 
3672 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3673 				"1237 Moving %d buffers from pvt_pool[%d] TO PUT list\n",
3674 				pvt_pool->count, i);
3675 
3676 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3677 					 &pvt_pool->list, list) {
3678 			list_move_tail(&lpfc_ncmd->list,
3679 				       &qp->lpfc_io_buf_list_put);
3680 			qp->put_io_bufs++;
3681 			pvt_pool->count--;
3682 		}
3683 
3684 		INIT_LIST_HEAD(&pvt_pool->list);
3685 		pvt_pool->count = 0;
3686 
3687 		spin_unlock(&pvt_pool->lock);
3688 		spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3689 
3690 		kfree(multixri_pool);
3691 	}
3692 }
3693 
3694 /**
3695  * lpfc_online - Initialize and bring a HBA online
3696  * @phba: pointer to lpfc hba data structure.
3697  *
3698  * This routine initializes the HBA and brings a HBA online. During this
3699  * process, the management interface is blocked to prevent user space access
3700  * to the HBA interfering with the driver initialization.
3701  *
3702  * Return codes
3703  *   0 - successful
3704  *   1 - failed
3705  **/
3706 int
3707 lpfc_online(struct lpfc_hba *phba)
3708 {
3709 	struct lpfc_vport *vport;
3710 	struct lpfc_vport **vports;
3711 	int i, error = 0;
3712 	bool vpis_cleared = false;
3713 
3714 	if (!phba)
3715 		return 0;
3716 	vport = phba->pport;
3717 
3718 	if (!test_bit(FC_OFFLINE_MODE, &vport->fc_flag))
3719 		return 0;
3720 
3721 	lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
3722 			"0458 Bring Adapter online\n");
3723 
3724 	lpfc_block_mgmt_io(phba, LPFC_MBX_WAIT);
3725 
3726 	if (phba->sli_rev == LPFC_SLI_REV4) {
3727 		if (lpfc_sli4_hba_setup(phba)) { /* Initialize SLI4 HBA */
3728 			lpfc_unblock_mgmt_io(phba);
3729 			return 1;
3730 		}
3731 		spin_lock_irq(&phba->hbalock);
3732 		if (!phba->sli4_hba.max_cfg_param.vpi_used)
3733 			vpis_cleared = true;
3734 		spin_unlock_irq(&phba->hbalock);
3735 
3736 		/* Reestablish the local initiator port.
3737 		 * The offline process destroyed the previous lport.
3738 		 */
3739 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME &&
3740 				!phba->nvmet_support) {
3741 			error = lpfc_nvme_create_localport(phba->pport);
3742 			if (error)
3743 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3744 					"6132 NVME restore reg failed "
3745 					"on nvmei error x%x\n", error);
3746 		}
3747 	} else {
3748 		lpfc_sli_queue_init(phba);
3749 		if (lpfc_sli_hba_setup(phba)) {	/* Initialize SLI2/SLI3 HBA */
3750 			lpfc_unblock_mgmt_io(phba);
3751 			return 1;
3752 		}
3753 	}
3754 
3755 	vports = lpfc_create_vport_work_array(phba);
3756 	if (vports != NULL) {
3757 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3758 			clear_bit(FC_OFFLINE_MODE, &vports[i]->fc_flag);
3759 			if (phba->sli3_options & LPFC_SLI3_NPIV_ENABLED)
3760 				set_bit(FC_VPORT_NEEDS_REG_VPI,
3761 					&vports[i]->fc_flag);
3762 			if (phba->sli_rev == LPFC_SLI_REV4) {
3763 				set_bit(FC_VPORT_NEEDS_INIT_VPI,
3764 					&vports[i]->fc_flag);
3765 				if ((vpis_cleared) &&
3766 				    (vports[i]->port_type !=
3767 					LPFC_PHYSICAL_PORT))
3768 					vports[i]->vpi = 0;
3769 			}
3770 		}
3771 	}
3772 	lpfc_destroy_vport_work_array(phba, vports);
3773 
3774 	if (phba->cfg_xri_rebalancing)
3775 		lpfc_create_multixri_pools(phba);
3776 
3777 	lpfc_cpuhp_add(phba);
3778 
3779 	lpfc_unblock_mgmt_io(phba);
3780 	return 0;
3781 }
3782 
3783 /**
3784  * lpfc_unblock_mgmt_io - Mark a HBA's management interface to be not blocked
3785  * @phba: pointer to lpfc hba data structure.
3786  *
3787  * This routine marks a HBA's management interface as not blocked. Once the
3788  * HBA's management interface is marked as not blocked, all the user space
3789  * access to the HBA, whether they are from sysfs interface or libdfc
3790  * interface will be allowed. The HBA is set to block the management interface
3791  * when the driver prepares the HBA interface for online or offline and then
3792  * set to unblock the management interface afterwards.
3793  **/
3794 void
3795 lpfc_unblock_mgmt_io(struct lpfc_hba * phba)
3796 {
3797 	unsigned long iflag;
3798 
3799 	spin_lock_irqsave(&phba->hbalock, iflag);
3800 	phba->sli.sli_flag &= ~LPFC_BLOCK_MGMT_IO;
3801 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3802 }
3803 
3804 /**
3805  * lpfc_offline_prep - Prepare a HBA to be brought offline
3806  * @phba: pointer to lpfc hba data structure.
3807  * @mbx_action: flag for mailbox shutdown action.
3808  *
3809  * This routine is invoked to prepare a HBA to be brought offline. It performs
3810  * unregistration login to all the nodes on all vports and flushes the mailbox
3811  * queue to make it ready to be brought offline.
3812  **/
3813 void
3814 lpfc_offline_prep(struct lpfc_hba *phba, int mbx_action)
3815 {
3816 	struct lpfc_vport *vport = phba->pport;
3817 	struct lpfc_nodelist  *ndlp, *next_ndlp;
3818 	struct lpfc_vport **vports;
3819 	struct Scsi_Host *shost;
3820 	int i;
3821 	int offline;
3822 	bool hba_pci_err;
3823 
3824 	if (test_bit(FC_OFFLINE_MODE, &vport->fc_flag))
3825 		return;
3826 
3827 	lpfc_block_mgmt_io(phba, mbx_action);
3828 
3829 	lpfc_linkdown(phba);
3830 
3831 	offline =  pci_channel_offline(phba->pcidev);
3832 	hba_pci_err = test_bit(HBA_PCI_ERR, &phba->bit_flags);
3833 
3834 	/* Issue an unreg_login to all nodes on all vports */
3835 	vports = lpfc_create_vport_work_array(phba);
3836 	if (vports != NULL) {
3837 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3838 			if (test_bit(FC_UNLOADING, &vports[i]->load_flag))
3839 				continue;
3840 			shost = lpfc_shost_from_vport(vports[i]);
3841 			spin_lock_irq(shost->host_lock);
3842 			vports[i]->vpi_state &= ~LPFC_VPI_REGISTERED;
3843 			spin_unlock_irq(shost->host_lock);
3844 			set_bit(FC_VPORT_NEEDS_REG_VPI, &vports[i]->fc_flag);
3845 			clear_bit(FC_VFI_REGISTERED, &vports[i]->fc_flag);
3846 
3847 			list_for_each_entry_safe(ndlp, next_ndlp,
3848 						 &vports[i]->fc_nodes,
3849 						 nlp_listp) {
3850 
3851 				clear_bit(NLP_NPR_ADISC, &ndlp->nlp_flag);
3852 				if (offline || hba_pci_err) {
3853 					clear_bit(NLP_UNREG_INP,
3854 						  &ndlp->nlp_flag);
3855 					clear_bit(NLP_RPI_REGISTERED,
3856 						  &ndlp->nlp_flag);
3857 				}
3858 
3859 				if (ndlp->nlp_type & NLP_FABRIC) {
3860 					lpfc_disc_state_machine(vports[i], ndlp,
3861 						NULL, NLP_EVT_DEVICE_RECOVERY);
3862 
3863 					/* Don't remove the node unless the node
3864 					 * has been unregistered with the
3865 					 * transport, and we're not in recovery
3866 					 * before dev_loss_tmo triggered.
3867 					 * Otherwise, let dev_loss take care of
3868 					 * the node.
3869 					 */
3870 					if (!test_bit(NLP_IN_RECOV_POST_DEV_LOSS,
3871 						      &ndlp->save_flags) &&
3872 					    !(ndlp->fc4_xpt_flags &
3873 					      (NVME_XPT_REGD | SCSI_XPT_REGD)))
3874 						lpfc_disc_state_machine
3875 							(vports[i], ndlp,
3876 							 NULL,
3877 							 NLP_EVT_DEVICE_RM);
3878 				}
3879 			}
3880 		}
3881 	}
3882 	lpfc_destroy_vport_work_array(phba, vports);
3883 
3884 	lpfc_sli_mbox_sys_shutdown(phba, mbx_action);
3885 
3886 	if (phba->wq)
3887 		flush_workqueue(phba->wq);
3888 }
3889 
3890 /**
3891  * lpfc_offline - Bring a HBA offline
3892  * @phba: pointer to lpfc hba data structure.
3893  *
3894  * This routine actually brings a HBA offline. It stops all the timers
3895  * associated with the HBA, brings down the SLI layer, and eventually
3896  * marks the HBA as in offline state for the upper layer protocol.
3897  **/
3898 void
3899 lpfc_offline(struct lpfc_hba *phba)
3900 {
3901 	struct Scsi_Host  *shost;
3902 	struct lpfc_vport **vports;
3903 	int i;
3904 
3905 	if (test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag))
3906 		return;
3907 
3908 	/* stop port and all timers associated with this hba */
3909 	lpfc_stop_port(phba);
3910 
3911 	/* Tear down the local and target port registrations.  The
3912 	 * nvme transports need to cleanup.
3913 	 */
3914 	lpfc_nvmet_destroy_targetport(phba);
3915 	lpfc_nvme_destroy_localport(phba->pport);
3916 
3917 	vports = lpfc_create_vport_work_array(phba);
3918 	if (vports != NULL)
3919 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++)
3920 			lpfc_stop_vport_timers(vports[i]);
3921 	lpfc_destroy_vport_work_array(phba, vports);
3922 	lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
3923 			"0460 Bring Adapter offline\n");
3924 	/* Bring down the SLI Layer and cleanup.  The HBA is offline
3925 	   now.  */
3926 	lpfc_sli_hba_down(phba);
3927 	spin_lock_irq(&phba->hbalock);
3928 	phba->work_ha = 0;
3929 	spin_unlock_irq(&phba->hbalock);
3930 	vports = lpfc_create_vport_work_array(phba);
3931 	if (vports != NULL)
3932 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3933 			shost = lpfc_shost_from_vport(vports[i]);
3934 			spin_lock_irq(shost->host_lock);
3935 			vports[i]->work_port_events = 0;
3936 			spin_unlock_irq(shost->host_lock);
3937 			set_bit(FC_OFFLINE_MODE, &vports[i]->fc_flag);
3938 		}
3939 	lpfc_destroy_vport_work_array(phba, vports);
3940 	/* If OFFLINE flag is clear (i.e. unloading), cpuhp removal is handled
3941 	 * in hba_unset
3942 	 */
3943 	if (test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag))
3944 		__lpfc_cpuhp_remove(phba);
3945 
3946 	if (phba->cfg_xri_rebalancing)
3947 		lpfc_destroy_multixri_pools(phba);
3948 }
3949 
3950 /**
3951  * lpfc_scsi_free - Free all the SCSI buffers and IOCBs from driver lists
3952  * @phba: pointer to lpfc hba data structure.
3953  *
3954  * This routine is to free all the SCSI buffers and IOCBs from the driver
3955  * list back to kernel. It is called from lpfc_pci_remove_one to free
3956  * the internal resources before the device is removed from the system.
3957  **/
3958 static void
3959 lpfc_scsi_free(struct lpfc_hba *phba)
3960 {
3961 	struct lpfc_io_buf *sb, *sb_next;
3962 
3963 	if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP))
3964 		return;
3965 
3966 	spin_lock_irq(&phba->hbalock);
3967 
3968 	/* Release all the lpfc_scsi_bufs maintained by this host. */
3969 
3970 	spin_lock(&phba->scsi_buf_list_put_lock);
3971 	list_for_each_entry_safe(sb, sb_next, &phba->lpfc_scsi_buf_list_put,
3972 				 list) {
3973 		list_del(&sb->list);
3974 		dma_pool_free(phba->lpfc_sg_dma_buf_pool, sb->data,
3975 			      sb->dma_handle);
3976 		kfree(sb);
3977 		phba->total_scsi_bufs--;
3978 	}
3979 	spin_unlock(&phba->scsi_buf_list_put_lock);
3980 
3981 	spin_lock(&phba->scsi_buf_list_get_lock);
3982 	list_for_each_entry_safe(sb, sb_next, &phba->lpfc_scsi_buf_list_get,
3983 				 list) {
3984 		list_del(&sb->list);
3985 		dma_pool_free(phba->lpfc_sg_dma_buf_pool, sb->data,
3986 			      sb->dma_handle);
3987 		kfree(sb);
3988 		phba->total_scsi_bufs--;
3989 	}
3990 	spin_unlock(&phba->scsi_buf_list_get_lock);
3991 	spin_unlock_irq(&phba->hbalock);
3992 }
3993 
3994 /**
3995  * lpfc_io_free - Free all the IO buffers and IOCBs from driver lists
3996  * @phba: pointer to lpfc hba data structure.
3997  *
3998  * This routine is to free all the IO buffers and IOCBs from the driver
3999  * list back to kernel. It is called from lpfc_pci_remove_one to free
4000  * the internal resources before the device is removed from the system.
4001  **/
4002 void
4003 lpfc_io_free(struct lpfc_hba *phba)
4004 {
4005 	struct lpfc_io_buf *lpfc_ncmd, *lpfc_ncmd_next;
4006 	struct lpfc_sli4_hdw_queue *qp;
4007 	int idx;
4008 
4009 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
4010 		qp = &phba->sli4_hba.hdwq[idx];
4011 		/* Release all the lpfc_nvme_bufs maintained by this host. */
4012 		spin_lock(&qp->io_buf_list_put_lock);
4013 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
4014 					 &qp->lpfc_io_buf_list_put,
4015 					 list) {
4016 			list_del(&lpfc_ncmd->list);
4017 			qp->put_io_bufs--;
4018 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4019 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4020 			if (phba->cfg_xpsgl && !phba->nvmet_support)
4021 				lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
4022 			lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
4023 			kfree(lpfc_ncmd);
4024 			qp->total_io_bufs--;
4025 		}
4026 		spin_unlock(&qp->io_buf_list_put_lock);
4027 
4028 		spin_lock(&qp->io_buf_list_get_lock);
4029 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
4030 					 &qp->lpfc_io_buf_list_get,
4031 					 list) {
4032 			list_del(&lpfc_ncmd->list);
4033 			qp->get_io_bufs--;
4034 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4035 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4036 			if (phba->cfg_xpsgl && !phba->nvmet_support)
4037 				lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
4038 			lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
4039 			kfree(lpfc_ncmd);
4040 			qp->total_io_bufs--;
4041 		}
4042 		spin_unlock(&qp->io_buf_list_get_lock);
4043 	}
4044 }
4045 
4046 /**
4047  * lpfc_sli4_els_sgl_update - update ELS xri-sgl sizing and mapping
4048  * @phba: pointer to lpfc hba data structure.
4049  *
4050  * This routine first calculates the sizes of the current els and allocated
4051  * scsi sgl lists, and then goes through all sgls to updates the physical
4052  * XRIs assigned due to port function reset. During port initialization, the
4053  * current els and allocated scsi sgl lists are 0s.
4054  *
4055  * Return codes
4056  *   0 - successful (for now, it always returns 0)
4057  **/
4058 int
4059 lpfc_sli4_els_sgl_update(struct lpfc_hba *phba)
4060 {
4061 	struct lpfc_sglq *sglq_entry = NULL, *sglq_entry_next = NULL;
4062 	uint16_t i, lxri, xri_cnt, els_xri_cnt;
4063 	LIST_HEAD(els_sgl_list);
4064 	int rc;
4065 
4066 	/*
4067 	 * update on pci function's els xri-sgl list
4068 	 */
4069 	els_xri_cnt = lpfc_sli4_get_els_iocb_cnt(phba);
4070 
4071 	if (els_xri_cnt > phba->sli4_hba.els_xri_cnt) {
4072 		/* els xri-sgl expanded */
4073 		xri_cnt = els_xri_cnt - phba->sli4_hba.els_xri_cnt;
4074 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4075 				"3157 ELS xri-sgl count increased from "
4076 				"%d to %d\n", phba->sli4_hba.els_xri_cnt,
4077 				els_xri_cnt);
4078 		/* allocate the additional els sgls */
4079 		for (i = 0; i < xri_cnt; i++) {
4080 			sglq_entry = kzalloc(sizeof(struct lpfc_sglq),
4081 					     GFP_KERNEL);
4082 			if (sglq_entry == NULL) {
4083 				lpfc_printf_log(phba, KERN_ERR,
4084 						LOG_TRACE_EVENT,
4085 						"2562 Failure to allocate an "
4086 						"ELS sgl entry:%d\n", i);
4087 				rc = -ENOMEM;
4088 				goto out_free_mem;
4089 			}
4090 			sglq_entry->buff_type = GEN_BUFF_TYPE;
4091 			sglq_entry->virt = lpfc_mbuf_alloc(phba, 0,
4092 							   &sglq_entry->phys);
4093 			if (sglq_entry->virt == NULL) {
4094 				kfree(sglq_entry);
4095 				lpfc_printf_log(phba, KERN_ERR,
4096 						LOG_TRACE_EVENT,
4097 						"2563 Failure to allocate an "
4098 						"ELS mbuf:%d\n", i);
4099 				rc = -ENOMEM;
4100 				goto out_free_mem;
4101 			}
4102 			sglq_entry->sgl = sglq_entry->virt;
4103 			memset(sglq_entry->sgl, 0, LPFC_BPL_SIZE);
4104 			sglq_entry->state = SGL_FREED;
4105 			list_add_tail(&sglq_entry->list, &els_sgl_list);
4106 		}
4107 		spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
4108 		list_splice_init(&els_sgl_list,
4109 				 &phba->sli4_hba.lpfc_els_sgl_list);
4110 		spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
4111 	} else if (els_xri_cnt < phba->sli4_hba.els_xri_cnt) {
4112 		/* els xri-sgl shrinked */
4113 		xri_cnt = phba->sli4_hba.els_xri_cnt - els_xri_cnt;
4114 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4115 				"3158 ELS xri-sgl count decreased from "
4116 				"%d to %d\n", phba->sli4_hba.els_xri_cnt,
4117 				els_xri_cnt);
4118 		spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
4119 		list_splice_init(&phba->sli4_hba.lpfc_els_sgl_list,
4120 				 &els_sgl_list);
4121 		/* release extra els sgls from list */
4122 		for (i = 0; i < xri_cnt; i++) {
4123 			list_remove_head(&els_sgl_list,
4124 					 sglq_entry, struct lpfc_sglq, list);
4125 			if (sglq_entry) {
4126 				__lpfc_mbuf_free(phba, sglq_entry->virt,
4127 						 sglq_entry->phys);
4128 				kfree(sglq_entry);
4129 			}
4130 		}
4131 		list_splice_init(&els_sgl_list,
4132 				 &phba->sli4_hba.lpfc_els_sgl_list);
4133 		spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
4134 	} else
4135 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4136 				"3163 ELS xri-sgl count unchanged: %d\n",
4137 				els_xri_cnt);
4138 	phba->sli4_hba.els_xri_cnt = els_xri_cnt;
4139 
4140 	/* update xris to els sgls on the list */
4141 	sglq_entry = NULL;
4142 	sglq_entry_next = NULL;
4143 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
4144 				 &phba->sli4_hba.lpfc_els_sgl_list, list) {
4145 		lxri = lpfc_sli4_next_xritag(phba);
4146 		if (lxri == NO_XRI) {
4147 			lpfc_printf_log(phba, KERN_ERR,
4148 					LOG_TRACE_EVENT,
4149 					"2400 Failed to allocate xri for "
4150 					"ELS sgl\n");
4151 			rc = -ENOMEM;
4152 			goto out_free_mem;
4153 		}
4154 		sglq_entry->sli4_lxritag = lxri;
4155 		sglq_entry->sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4156 	}
4157 	return 0;
4158 
4159 out_free_mem:
4160 	lpfc_free_els_sgl_list(phba);
4161 	return rc;
4162 }
4163 
4164 /**
4165  * lpfc_sli4_nvmet_sgl_update - update xri-sgl sizing and mapping
4166  * @phba: pointer to lpfc hba data structure.
4167  *
4168  * This routine first calculates the sizes of the current els and allocated
4169  * scsi sgl lists, and then goes through all sgls to updates the physical
4170  * XRIs assigned due to port function reset. During port initialization, the
4171  * current els and allocated scsi sgl lists are 0s.
4172  *
4173  * Return codes
4174  *   0 - successful (for now, it always returns 0)
4175  **/
4176 int
4177 lpfc_sli4_nvmet_sgl_update(struct lpfc_hba *phba)
4178 {
4179 	struct lpfc_sglq *sglq_entry = NULL, *sglq_entry_next = NULL;
4180 	uint16_t i, lxri, xri_cnt, els_xri_cnt;
4181 	uint16_t nvmet_xri_cnt;
4182 	LIST_HEAD(nvmet_sgl_list);
4183 	int rc;
4184 
4185 	/*
4186 	 * update on pci function's nvmet xri-sgl list
4187 	 */
4188 	els_xri_cnt = lpfc_sli4_get_els_iocb_cnt(phba);
4189 
4190 	/* For NVMET, ALL remaining XRIs are dedicated for IO processing */
4191 	nvmet_xri_cnt = phba->sli4_hba.max_cfg_param.max_xri - els_xri_cnt;
4192 	if (nvmet_xri_cnt > phba->sli4_hba.nvmet_xri_cnt) {
4193 		/* els xri-sgl expanded */
4194 		xri_cnt = nvmet_xri_cnt - phba->sli4_hba.nvmet_xri_cnt;
4195 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4196 				"6302 NVMET xri-sgl cnt grew from %d to %d\n",
4197 				phba->sli4_hba.nvmet_xri_cnt, nvmet_xri_cnt);
4198 		/* allocate the additional nvmet sgls */
4199 		for (i = 0; i < xri_cnt; i++) {
4200 			sglq_entry = kzalloc(sizeof(struct lpfc_sglq),
4201 					     GFP_KERNEL);
4202 			if (sglq_entry == NULL) {
4203 				lpfc_printf_log(phba, KERN_ERR,
4204 						LOG_TRACE_EVENT,
4205 						"6303 Failure to allocate an "
4206 						"NVMET sgl entry:%d\n", i);
4207 				rc = -ENOMEM;
4208 				goto out_free_mem;
4209 			}
4210 			sglq_entry->buff_type = NVMET_BUFF_TYPE;
4211 			sglq_entry->virt = lpfc_nvmet_buf_alloc(phba, 0,
4212 							   &sglq_entry->phys);
4213 			if (sglq_entry->virt == NULL) {
4214 				kfree(sglq_entry);
4215 				lpfc_printf_log(phba, KERN_ERR,
4216 						LOG_TRACE_EVENT,
4217 						"6304 Failure to allocate an "
4218 						"NVMET buf:%d\n", i);
4219 				rc = -ENOMEM;
4220 				goto out_free_mem;
4221 			}
4222 			sglq_entry->sgl = sglq_entry->virt;
4223 			memset(sglq_entry->sgl, 0,
4224 			       phba->cfg_sg_dma_buf_size);
4225 			sglq_entry->state = SGL_FREED;
4226 			list_add_tail(&sglq_entry->list, &nvmet_sgl_list);
4227 		}
4228 		spin_lock_irq(&phba->hbalock);
4229 		spin_lock(&phba->sli4_hba.sgl_list_lock);
4230 		list_splice_init(&nvmet_sgl_list,
4231 				 &phba->sli4_hba.lpfc_nvmet_sgl_list);
4232 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
4233 		spin_unlock_irq(&phba->hbalock);
4234 	} else if (nvmet_xri_cnt < phba->sli4_hba.nvmet_xri_cnt) {
4235 		/* nvmet xri-sgl shrunk */
4236 		xri_cnt = phba->sli4_hba.nvmet_xri_cnt - nvmet_xri_cnt;
4237 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4238 				"6305 NVMET xri-sgl count decreased from "
4239 				"%d to %d\n", phba->sli4_hba.nvmet_xri_cnt,
4240 				nvmet_xri_cnt);
4241 		spin_lock_irq(&phba->hbalock);
4242 		spin_lock(&phba->sli4_hba.sgl_list_lock);
4243 		list_splice_init(&phba->sli4_hba.lpfc_nvmet_sgl_list,
4244 				 &nvmet_sgl_list);
4245 		/* release extra nvmet sgls from list */
4246 		for (i = 0; i < xri_cnt; i++) {
4247 			list_remove_head(&nvmet_sgl_list,
4248 					 sglq_entry, struct lpfc_sglq, list);
4249 			if (sglq_entry) {
4250 				lpfc_nvmet_buf_free(phba, sglq_entry->virt,
4251 						    sglq_entry->phys);
4252 				kfree(sglq_entry);
4253 			}
4254 		}
4255 		list_splice_init(&nvmet_sgl_list,
4256 				 &phba->sli4_hba.lpfc_nvmet_sgl_list);
4257 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
4258 		spin_unlock_irq(&phba->hbalock);
4259 	} else
4260 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4261 				"6306 NVMET xri-sgl count unchanged: %d\n",
4262 				nvmet_xri_cnt);
4263 	phba->sli4_hba.nvmet_xri_cnt = nvmet_xri_cnt;
4264 
4265 	/* update xris to nvmet sgls on the list */
4266 	sglq_entry = NULL;
4267 	sglq_entry_next = NULL;
4268 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
4269 				 &phba->sli4_hba.lpfc_nvmet_sgl_list, list) {
4270 		lxri = lpfc_sli4_next_xritag(phba);
4271 		if (lxri == NO_XRI) {
4272 			lpfc_printf_log(phba, KERN_ERR,
4273 					LOG_TRACE_EVENT,
4274 					"6307 Failed to allocate xri for "
4275 					"NVMET sgl\n");
4276 			rc = -ENOMEM;
4277 			goto out_free_mem;
4278 		}
4279 		sglq_entry->sli4_lxritag = lxri;
4280 		sglq_entry->sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4281 	}
4282 	return 0;
4283 
4284 out_free_mem:
4285 	lpfc_free_nvmet_sgl_list(phba);
4286 	return rc;
4287 }
4288 
4289 int
4290 lpfc_io_buf_flush(struct lpfc_hba *phba, struct list_head *cbuf)
4291 {
4292 	LIST_HEAD(blist);
4293 	struct lpfc_sli4_hdw_queue *qp;
4294 	struct lpfc_io_buf *lpfc_cmd;
4295 	struct lpfc_io_buf *iobufp, *prev_iobufp;
4296 	int idx, cnt, xri, inserted;
4297 
4298 	cnt = 0;
4299 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
4300 		qp = &phba->sli4_hba.hdwq[idx];
4301 		spin_lock_irq(&qp->io_buf_list_get_lock);
4302 		spin_lock(&qp->io_buf_list_put_lock);
4303 
4304 		/* Take everything off the get and put lists */
4305 		list_splice_init(&qp->lpfc_io_buf_list_get, &blist);
4306 		list_splice(&qp->lpfc_io_buf_list_put, &blist);
4307 		INIT_LIST_HEAD(&qp->lpfc_io_buf_list_get);
4308 		INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
4309 		cnt += qp->get_io_bufs + qp->put_io_bufs;
4310 		qp->get_io_bufs = 0;
4311 		qp->put_io_bufs = 0;
4312 		qp->total_io_bufs = 0;
4313 		spin_unlock(&qp->io_buf_list_put_lock);
4314 		spin_unlock_irq(&qp->io_buf_list_get_lock);
4315 	}
4316 
4317 	/*
4318 	 * Take IO buffers off blist and put on cbuf sorted by XRI.
4319 	 * This is because POST_SGL takes a sequential range of XRIs
4320 	 * to post to the firmware.
4321 	 */
4322 	for (idx = 0; idx < cnt; idx++) {
4323 		list_remove_head(&blist, lpfc_cmd, struct lpfc_io_buf, list);
4324 		if (!lpfc_cmd)
4325 			return cnt;
4326 		if (idx == 0) {
4327 			list_add_tail(&lpfc_cmd->list, cbuf);
4328 			continue;
4329 		}
4330 		xri = lpfc_cmd->cur_iocbq.sli4_xritag;
4331 		inserted = 0;
4332 		prev_iobufp = NULL;
4333 		list_for_each_entry(iobufp, cbuf, list) {
4334 			if (xri < iobufp->cur_iocbq.sli4_xritag) {
4335 				if (prev_iobufp)
4336 					list_add(&lpfc_cmd->list,
4337 						 &prev_iobufp->list);
4338 				else
4339 					list_add(&lpfc_cmd->list, cbuf);
4340 				inserted = 1;
4341 				break;
4342 			}
4343 			prev_iobufp = iobufp;
4344 		}
4345 		if (!inserted)
4346 			list_add_tail(&lpfc_cmd->list, cbuf);
4347 	}
4348 	return cnt;
4349 }
4350 
4351 int
4352 lpfc_io_buf_replenish(struct lpfc_hba *phba, struct list_head *cbuf)
4353 {
4354 	struct lpfc_sli4_hdw_queue *qp;
4355 	struct lpfc_io_buf *lpfc_cmd;
4356 	int idx, cnt;
4357 	unsigned long iflags;
4358 
4359 	qp = phba->sli4_hba.hdwq;
4360 	cnt = 0;
4361 	while (!list_empty(cbuf)) {
4362 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
4363 			list_remove_head(cbuf, lpfc_cmd,
4364 					 struct lpfc_io_buf, list);
4365 			if (!lpfc_cmd)
4366 				return cnt;
4367 			cnt++;
4368 			qp = &phba->sli4_hba.hdwq[idx];
4369 			lpfc_cmd->hdwq_no = idx;
4370 			lpfc_cmd->hdwq = qp;
4371 			lpfc_cmd->cur_iocbq.cmd_cmpl = NULL;
4372 			spin_lock_irqsave(&qp->io_buf_list_put_lock, iflags);
4373 			list_add_tail(&lpfc_cmd->list,
4374 				      &qp->lpfc_io_buf_list_put);
4375 			qp->put_io_bufs++;
4376 			qp->total_io_bufs++;
4377 			spin_unlock_irqrestore(&qp->io_buf_list_put_lock,
4378 					       iflags);
4379 		}
4380 	}
4381 	return cnt;
4382 }
4383 
4384 /**
4385  * lpfc_sli4_io_sgl_update - update xri-sgl sizing and mapping
4386  * @phba: pointer to lpfc hba data structure.
4387  *
4388  * This routine first calculates the sizes of the current els and allocated
4389  * scsi sgl lists, and then goes through all sgls to updates the physical
4390  * XRIs assigned due to port function reset. During port initialization, the
4391  * current els and allocated scsi sgl lists are 0s.
4392  *
4393  * Return codes
4394  *   0 - successful (for now, it always returns 0)
4395  **/
4396 int
4397 lpfc_sli4_io_sgl_update(struct lpfc_hba *phba)
4398 {
4399 	struct lpfc_io_buf *lpfc_ncmd = NULL, *lpfc_ncmd_next = NULL;
4400 	uint16_t i, lxri, els_xri_cnt;
4401 	uint16_t io_xri_cnt, io_xri_max;
4402 	LIST_HEAD(io_sgl_list);
4403 	int rc, cnt;
4404 
4405 	/*
4406 	 * update on pci function's allocated nvme xri-sgl list
4407 	 */
4408 
4409 	/* maximum number of xris available for nvme buffers */
4410 	els_xri_cnt = lpfc_sli4_get_els_iocb_cnt(phba);
4411 	io_xri_max = phba->sli4_hba.max_cfg_param.max_xri - els_xri_cnt;
4412 	phba->sli4_hba.io_xri_max = io_xri_max;
4413 
4414 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4415 			"6074 Current allocated XRI sgl count:%d, "
4416 			"maximum XRI count:%d els_xri_cnt:%d\n\n",
4417 			phba->sli4_hba.io_xri_cnt,
4418 			phba->sli4_hba.io_xri_max,
4419 			els_xri_cnt);
4420 
4421 	cnt = lpfc_io_buf_flush(phba, &io_sgl_list);
4422 
4423 	if (phba->sli4_hba.io_xri_cnt > phba->sli4_hba.io_xri_max) {
4424 		/* max nvme xri shrunk below the allocated nvme buffers */
4425 		io_xri_cnt = phba->sli4_hba.io_xri_cnt -
4426 					phba->sli4_hba.io_xri_max;
4427 		/* release the extra allocated nvme buffers */
4428 		for (i = 0; i < io_xri_cnt; i++) {
4429 			list_remove_head(&io_sgl_list, lpfc_ncmd,
4430 					 struct lpfc_io_buf, list);
4431 			if (lpfc_ncmd) {
4432 				dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4433 					      lpfc_ncmd->data,
4434 					      lpfc_ncmd->dma_handle);
4435 				kfree(lpfc_ncmd);
4436 			}
4437 		}
4438 		phba->sli4_hba.io_xri_cnt -= io_xri_cnt;
4439 	}
4440 
4441 	/* update xris associated to remaining allocated nvme buffers */
4442 	lpfc_ncmd = NULL;
4443 	lpfc_ncmd_next = NULL;
4444 	phba->sli4_hba.io_xri_cnt = cnt;
4445 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
4446 				 &io_sgl_list, list) {
4447 		lxri = lpfc_sli4_next_xritag(phba);
4448 		if (lxri == NO_XRI) {
4449 			lpfc_printf_log(phba, KERN_ERR,
4450 					LOG_TRACE_EVENT,
4451 					"6075 Failed to allocate xri for "
4452 					"nvme buffer\n");
4453 			rc = -ENOMEM;
4454 			goto out_free_mem;
4455 		}
4456 		lpfc_ncmd->cur_iocbq.sli4_lxritag = lxri;
4457 		lpfc_ncmd->cur_iocbq.sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4458 	}
4459 	cnt = lpfc_io_buf_replenish(phba, &io_sgl_list);
4460 	return 0;
4461 
4462 out_free_mem:
4463 	lpfc_io_free(phba);
4464 	return rc;
4465 }
4466 
4467 /**
4468  * lpfc_new_io_buf - IO buffer allocator for HBA with SLI4 IF spec
4469  * @phba: Pointer to lpfc hba data structure.
4470  * @num_to_alloc: The requested number of buffers to allocate.
4471  *
4472  * This routine allocates nvme buffers for device with SLI-4 interface spec,
4473  * the nvme buffer contains all the necessary information needed to initiate
4474  * an I/O. After allocating up to @num_to_allocate IO buffers and put
4475  * them on a list, it post them to the port by using SGL block post.
4476  *
4477  * Return codes:
4478  *   int - number of IO buffers that were allocated and posted.
4479  *   0 = failure, less than num_to_alloc is a partial failure.
4480  **/
4481 int
4482 lpfc_new_io_buf(struct lpfc_hba *phba, int num_to_alloc)
4483 {
4484 	struct lpfc_io_buf *lpfc_ncmd;
4485 	struct lpfc_iocbq *pwqeq;
4486 	uint16_t iotag, lxri = 0;
4487 	int bcnt, num_posted;
4488 	LIST_HEAD(prep_nblist);
4489 	LIST_HEAD(post_nblist);
4490 	LIST_HEAD(nvme_nblist);
4491 
4492 	phba->sli4_hba.io_xri_cnt = 0;
4493 	for (bcnt = 0; bcnt < num_to_alloc; bcnt++) {
4494 		lpfc_ncmd = kzalloc(sizeof(*lpfc_ncmd), GFP_KERNEL);
4495 		if (!lpfc_ncmd)
4496 			break;
4497 		/*
4498 		 * Get memory from the pci pool to map the virt space to
4499 		 * pci bus space for an I/O. The DMA buffer includes the
4500 		 * number of SGE's necessary to support the sg_tablesize.
4501 		 */
4502 		lpfc_ncmd->data = dma_pool_zalloc(phba->lpfc_sg_dma_buf_pool,
4503 						  GFP_KERNEL,
4504 						  &lpfc_ncmd->dma_handle);
4505 		if (!lpfc_ncmd->data) {
4506 			kfree(lpfc_ncmd);
4507 			break;
4508 		}
4509 
4510 		if (phba->cfg_xpsgl && !phba->nvmet_support) {
4511 			INIT_LIST_HEAD(&lpfc_ncmd->dma_sgl_xtra_list);
4512 		} else {
4513 			/*
4514 			 * 4K Page alignment is CRITICAL to BlockGuard, double
4515 			 * check to be sure.
4516 			 */
4517 			if ((phba->sli3_options & LPFC_SLI3_BG_ENABLED) &&
4518 			    (((unsigned long)(lpfc_ncmd->data) &
4519 			    (unsigned long)(SLI4_PAGE_SIZE - 1)) != 0)) {
4520 				lpfc_printf_log(phba, KERN_ERR,
4521 						LOG_TRACE_EVENT,
4522 						"3369 Memory alignment err: "
4523 						"addr=%lx\n",
4524 						(unsigned long)lpfc_ncmd->data);
4525 				dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4526 					      lpfc_ncmd->data,
4527 					      lpfc_ncmd->dma_handle);
4528 				kfree(lpfc_ncmd);
4529 				break;
4530 			}
4531 		}
4532 
4533 		INIT_LIST_HEAD(&lpfc_ncmd->dma_cmd_rsp_list);
4534 
4535 		lxri = lpfc_sli4_next_xritag(phba);
4536 		if (lxri == NO_XRI) {
4537 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4538 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4539 			kfree(lpfc_ncmd);
4540 			break;
4541 		}
4542 		pwqeq = &lpfc_ncmd->cur_iocbq;
4543 
4544 		/* Allocate iotag for lpfc_ncmd->cur_iocbq. */
4545 		iotag = lpfc_sli_next_iotag(phba, pwqeq);
4546 		if (iotag == 0) {
4547 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4548 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4549 			kfree(lpfc_ncmd);
4550 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4551 					"6121 Failed to allocate IOTAG for"
4552 					" XRI:0x%x\n", lxri);
4553 			lpfc_sli4_free_xri(phba, lxri);
4554 			break;
4555 		}
4556 		pwqeq->sli4_lxritag = lxri;
4557 		pwqeq->sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4558 
4559 		/* Initialize local short-hand pointers. */
4560 		lpfc_ncmd->dma_sgl = lpfc_ncmd->data;
4561 		lpfc_ncmd->dma_phys_sgl = lpfc_ncmd->dma_handle;
4562 		lpfc_ncmd->cur_iocbq.io_buf = lpfc_ncmd;
4563 		spin_lock_init(&lpfc_ncmd->buf_lock);
4564 
4565 		/* add the nvme buffer to a post list */
4566 		list_add_tail(&lpfc_ncmd->list, &post_nblist);
4567 		phba->sli4_hba.io_xri_cnt++;
4568 	}
4569 	lpfc_printf_log(phba, KERN_INFO, LOG_NVME,
4570 			"6114 Allocate %d out of %d requested new NVME "
4571 			"buffers of size x%zu bytes\n", bcnt, num_to_alloc,
4572 			sizeof(*lpfc_ncmd));
4573 
4574 
4575 	/* post the list of nvme buffer sgls to port if available */
4576 	if (!list_empty(&post_nblist))
4577 		num_posted = lpfc_sli4_post_io_sgl_list(
4578 				phba, &post_nblist, bcnt);
4579 	else
4580 		num_posted = 0;
4581 
4582 	return num_posted;
4583 }
4584 
4585 static uint64_t
4586 lpfc_get_wwpn(struct lpfc_hba *phba)
4587 {
4588 	uint64_t wwn;
4589 	int rc;
4590 	LPFC_MBOXQ_t *mboxq;
4591 	MAILBOX_t *mb;
4592 
4593 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
4594 						GFP_KERNEL);
4595 	if (!mboxq)
4596 		return (uint64_t)-1;
4597 
4598 	/* First get WWN of HBA instance */
4599 	lpfc_read_nv(phba, mboxq);
4600 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
4601 	if (rc != MBX_SUCCESS) {
4602 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4603 				"6019 Mailbox failed , mbxCmd x%x "
4604 				"READ_NV, mbxStatus x%x\n",
4605 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
4606 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
4607 		mempool_free(mboxq, phba->mbox_mem_pool);
4608 		return (uint64_t) -1;
4609 	}
4610 	mb = &mboxq->u.mb;
4611 	memcpy(&wwn, (char *)mb->un.varRDnvp.portname, sizeof(uint64_t));
4612 	/* wwn is WWPN of HBA instance */
4613 	mempool_free(mboxq, phba->mbox_mem_pool);
4614 	if (phba->sli_rev == LPFC_SLI_REV4)
4615 		return be64_to_cpu(wwn);
4616 	else
4617 		return rol64(wwn, 32);
4618 }
4619 
4620 static unsigned short lpfc_get_sg_tablesize(struct lpfc_hba *phba)
4621 {
4622 	if (phba->sli_rev == LPFC_SLI_REV4)
4623 		if (phba->cfg_xpsgl && !phba->nvmet_support)
4624 			return LPFC_MAX_SG_TABLESIZE;
4625 		else
4626 			return phba->cfg_scsi_seg_cnt;
4627 	else
4628 		return phba->cfg_sg_seg_cnt;
4629 }
4630 
4631 /**
4632  * lpfc_vmid_res_alloc - Allocates resources for VMID
4633  * @phba: pointer to lpfc hba data structure.
4634  * @vport: pointer to vport data structure
4635  *
4636  * This routine allocated the resources needed for the VMID.
4637  *
4638  * Return codes
4639  *	0 on Success
4640  *	Non-0 on Failure
4641  */
4642 static int
4643 lpfc_vmid_res_alloc(struct lpfc_hba *phba, struct lpfc_vport *vport)
4644 {
4645 	/* VMID feature is supported only on SLI4 */
4646 	if (phba->sli_rev == LPFC_SLI_REV3) {
4647 		phba->cfg_vmid_app_header = 0;
4648 		phba->cfg_vmid_priority_tagging = 0;
4649 	}
4650 
4651 	if (lpfc_is_vmid_enabled(phba)) {
4652 		vport->vmid =
4653 		    kcalloc(phba->cfg_max_vmid, sizeof(struct lpfc_vmid),
4654 			    GFP_KERNEL);
4655 		if (!vport->vmid)
4656 			return -ENOMEM;
4657 
4658 		rwlock_init(&vport->vmid_lock);
4659 
4660 		/* Set the VMID parameters for the vport */
4661 		vport->vmid_priority_tagging = phba->cfg_vmid_priority_tagging;
4662 		vport->vmid_inactivity_timeout =
4663 		    phba->cfg_vmid_inactivity_timeout;
4664 		vport->max_vmid = phba->cfg_max_vmid;
4665 		vport->cur_vmid_cnt = 0;
4666 
4667 		vport->vmid_priority_range = bitmap_zalloc
4668 			(LPFC_VMID_MAX_PRIORITY_RANGE, GFP_KERNEL);
4669 
4670 		if (!vport->vmid_priority_range) {
4671 			kfree(vport->vmid);
4672 			return -ENOMEM;
4673 		}
4674 
4675 		hash_init(vport->hash_table);
4676 	}
4677 	return 0;
4678 }
4679 
4680 /**
4681  * lpfc_create_port - Create an FC port
4682  * @phba: pointer to lpfc hba data structure.
4683  * @instance: a unique integer ID to this FC port.
4684  * @dev: pointer to the device data structure.
4685  *
4686  * This routine creates a FC port for the upper layer protocol. The FC port
4687  * can be created on top of either a physical port or a virtual port provided
4688  * by the HBA. This routine also allocates a SCSI host data structure (shost)
4689  * and associates the FC port created before adding the shost into the SCSI
4690  * layer.
4691  *
4692  * Return codes
4693  *   @vport - pointer to the virtual N_Port data structure.
4694  *   NULL - port create failed.
4695  **/
4696 struct lpfc_vport *
4697 lpfc_create_port(struct lpfc_hba *phba, int instance, struct device *dev)
4698 {
4699 	struct lpfc_vport *vport;
4700 	struct Scsi_Host  *shost = NULL;
4701 	struct scsi_host_template *template;
4702 	int error = 0;
4703 	int i;
4704 	uint64_t wwn;
4705 	bool use_no_reset_hba = false;
4706 	int rc;
4707 	u8 if_type;
4708 
4709 	if (lpfc_no_hba_reset_cnt) {
4710 		if (phba->sli_rev < LPFC_SLI_REV4 &&
4711 		    dev == &phba->pcidev->dev) {
4712 			/* Reset the port first */
4713 			lpfc_sli_brdrestart(phba);
4714 			rc = lpfc_sli_chipset_init(phba);
4715 			if (rc)
4716 				return NULL;
4717 		}
4718 		wwn = lpfc_get_wwpn(phba);
4719 	}
4720 
4721 	for (i = 0; i < lpfc_no_hba_reset_cnt; i++) {
4722 		if (wwn == lpfc_no_hba_reset[i]) {
4723 			lpfc_printf_log(phba, KERN_ERR,
4724 					LOG_TRACE_EVENT,
4725 					"6020 Setting use_no_reset port=%llx\n",
4726 					wwn);
4727 			use_no_reset_hba = true;
4728 			break;
4729 		}
4730 	}
4731 
4732 	/* Seed template for SCSI host registration */
4733 	if (dev == &phba->pcidev->dev) {
4734 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP) {
4735 			/* Seed physical port template */
4736 			template = &lpfc_template;
4737 
4738 			if (use_no_reset_hba)
4739 				/* template is for a no reset SCSI Host */
4740 				template->eh_host_reset_handler = NULL;
4741 
4742 			/* Seed updated value of sg_tablesize */
4743 			template->sg_tablesize = lpfc_get_sg_tablesize(phba);
4744 		} else {
4745 			/* NVMET is for physical port only */
4746 			template = &lpfc_template_nvme;
4747 		}
4748 	} else {
4749 		/* Seed vport template */
4750 		template = &lpfc_vport_template;
4751 
4752 		/* Seed updated value of sg_tablesize */
4753 		template->sg_tablesize = lpfc_get_sg_tablesize(phba);
4754 	}
4755 
4756 	shost = scsi_host_alloc(template, sizeof(struct lpfc_vport));
4757 	if (!shost)
4758 		goto out;
4759 
4760 	vport = (struct lpfc_vport *) shost->hostdata;
4761 	vport->phba = phba;
4762 	set_bit(FC_LOADING, &vport->load_flag);
4763 	set_bit(FC_VPORT_NEEDS_REG_VPI, &vport->fc_flag);
4764 	vport->fc_rscn_flush = 0;
4765 	atomic_set(&vport->fc_plogi_cnt, 0);
4766 	atomic_set(&vport->fc_adisc_cnt, 0);
4767 	atomic_set(&vport->fc_reglogin_cnt, 0);
4768 	atomic_set(&vport->fc_prli_cnt, 0);
4769 	atomic_set(&vport->fc_unmap_cnt, 0);
4770 	atomic_set(&vport->fc_map_cnt, 0);
4771 	atomic_set(&vport->fc_npr_cnt, 0);
4772 	atomic_set(&vport->fc_unused_cnt, 0);
4773 	lpfc_get_vport_cfgparam(vport);
4774 
4775 	/* Adjust value in vport */
4776 	vport->cfg_enable_fc4_type = phba->cfg_enable_fc4_type;
4777 
4778 	shost->unique_id = instance;
4779 	shost->max_id = LPFC_MAX_TARGET;
4780 	shost->max_lun = vport->cfg_max_luns;
4781 	shost->this_id = -1;
4782 
4783 	/* Set max_cmd_len applicable to ASIC support */
4784 	if (phba->sli_rev == LPFC_SLI_REV4) {
4785 		if_type = bf_get(lpfc_sli_intf_if_type,
4786 				 &phba->sli4_hba.sli_intf);
4787 		switch (if_type) {
4788 		case LPFC_SLI_INTF_IF_TYPE_2:
4789 			fallthrough;
4790 		case LPFC_SLI_INTF_IF_TYPE_6:
4791 			shost->max_cmd_len = LPFC_FCP_CDB_LEN_32;
4792 			break;
4793 		default:
4794 			shost->max_cmd_len = LPFC_FCP_CDB_LEN;
4795 			break;
4796 		}
4797 	} else {
4798 		shost->max_cmd_len = LPFC_FCP_CDB_LEN;
4799 	}
4800 
4801 	if (phba->sli_rev == LPFC_SLI_REV4) {
4802 		if (!phba->cfg_fcp_mq_threshold ||
4803 		    phba->cfg_fcp_mq_threshold > phba->cfg_hdw_queue)
4804 			phba->cfg_fcp_mq_threshold = phba->cfg_hdw_queue;
4805 
4806 		shost->nr_hw_queues = min_t(int, 2 * num_possible_nodes(),
4807 					    phba->cfg_fcp_mq_threshold);
4808 
4809 		shost->dma_boundary =
4810 			phba->sli4_hba.pc_sli4_params.sge_supp_len-1;
4811 	} else
4812 		/* SLI-3 has a limited number of hardware queues (3),
4813 		 * thus there is only one for FCP processing.
4814 		 */
4815 		shost->nr_hw_queues = 1;
4816 
4817 	/*
4818 	 * Set initial can_queue value since 0 is no longer supported and
4819 	 * scsi_add_host will fail. This will be adjusted later based on the
4820 	 * max xri value determined in hba setup.
4821 	 */
4822 	shost->can_queue = phba->cfg_hba_queue_depth - 10;
4823 	if (dev != &phba->pcidev->dev) {
4824 		shost->transportt = lpfc_vport_transport_template;
4825 		vport->port_type = LPFC_NPIV_PORT;
4826 	} else {
4827 		shost->transportt = lpfc_transport_template;
4828 		vport->port_type = LPFC_PHYSICAL_PORT;
4829 	}
4830 
4831 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP,
4832 			"9081 CreatePort TMPLATE type %x TBLsize %d "
4833 			"SEGcnt %d/%d\n",
4834 			vport->port_type, shost->sg_tablesize,
4835 			phba->cfg_scsi_seg_cnt, phba->cfg_sg_seg_cnt);
4836 
4837 	/* Allocate the resources for VMID */
4838 	rc = lpfc_vmid_res_alloc(phba, vport);
4839 
4840 	if (rc)
4841 		goto out_put_shost;
4842 
4843 	/* Initialize all internally managed lists. */
4844 	INIT_LIST_HEAD(&vport->fc_nodes);
4845 	spin_lock_init(&vport->fc_nodes_list_lock);
4846 	INIT_LIST_HEAD(&vport->rcv_buffer_list);
4847 	spin_lock_init(&vport->work_port_lock);
4848 
4849 	timer_setup(&vport->fc_disctmo, lpfc_disc_timeout, 0);
4850 
4851 	timer_setup(&vport->els_tmofunc, lpfc_els_timeout, 0);
4852 
4853 	timer_setup(&vport->delayed_disc_tmo, lpfc_delayed_disc_tmo, 0);
4854 
4855 	if (phba->sli3_options & LPFC_SLI3_BG_ENABLED)
4856 		lpfc_setup_bg(phba, shost);
4857 
4858 	error = scsi_add_host_with_dma(shost, dev, &phba->pcidev->dev);
4859 	if (error)
4860 		goto out_free_vmid;
4861 
4862 	spin_lock_irq(&phba->port_list_lock);
4863 	list_add_tail(&vport->listentry, &phba->port_list);
4864 	spin_unlock_irq(&phba->port_list_lock);
4865 	return vport;
4866 
4867 out_free_vmid:
4868 	kfree(vport->vmid);
4869 	bitmap_free(vport->vmid_priority_range);
4870 out_put_shost:
4871 	scsi_host_put(shost);
4872 out:
4873 	return NULL;
4874 }
4875 
4876 /**
4877  * destroy_port -  destroy an FC port
4878  * @vport: pointer to an lpfc virtual N_Port data structure.
4879  *
4880  * This routine destroys a FC port from the upper layer protocol. All the
4881  * resources associated with the port are released.
4882  **/
4883 void
4884 destroy_port(struct lpfc_vport *vport)
4885 {
4886 	struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
4887 	struct lpfc_hba  *phba = vport->phba;
4888 
4889 	lpfc_debugfs_terminate(vport);
4890 	fc_remove_host(shost);
4891 	scsi_remove_host(shost);
4892 
4893 	spin_lock_irq(&phba->port_list_lock);
4894 	list_del_init(&vport->listentry);
4895 	spin_unlock_irq(&phba->port_list_lock);
4896 
4897 	lpfc_cleanup(vport);
4898 	return;
4899 }
4900 
4901 /**
4902  * lpfc_get_instance - Get a unique integer ID
4903  *
4904  * This routine allocates a unique integer ID from lpfc_hba_index pool. It
4905  * uses the kernel idr facility to perform the task.
4906  *
4907  * Return codes:
4908  *   instance - a unique integer ID allocated as the new instance.
4909  *   -1 - lpfc get instance failed.
4910  **/
4911 int
4912 lpfc_get_instance(void)
4913 {
4914 	int ret;
4915 
4916 	ret = idr_alloc(&lpfc_hba_index, NULL, 0, 0, GFP_KERNEL);
4917 	return ret < 0 ? -1 : ret;
4918 }
4919 
4920 /**
4921  * lpfc_scan_finished - method for SCSI layer to detect whether scan is done
4922  * @shost: pointer to SCSI host data structure.
4923  * @time: elapsed time of the scan in jiffies.
4924  *
4925  * This routine is called by the SCSI layer with a SCSI host to determine
4926  * whether the scan host is finished.
4927  *
4928  * Note: there is no scan_start function as adapter initialization will have
4929  * asynchronously kicked off the link initialization.
4930  *
4931  * Return codes
4932  *   0 - SCSI host scan is not over yet.
4933  *   1 - SCSI host scan is over.
4934  **/
4935 int lpfc_scan_finished(struct Scsi_Host *shost, unsigned long time)
4936 {
4937 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
4938 	struct lpfc_hba   *phba = vport->phba;
4939 	int stat = 0;
4940 
4941 	spin_lock_irq(shost->host_lock);
4942 
4943 	if (test_bit(FC_UNLOADING, &vport->load_flag)) {
4944 		stat = 1;
4945 		goto finished;
4946 	}
4947 	if (time >= secs_to_jiffies(30)) {
4948 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4949 				"0461 Scanning longer than 30 "
4950 				"seconds.  Continuing initialization\n");
4951 		stat = 1;
4952 		goto finished;
4953 	}
4954 	if (time >= secs_to_jiffies(15) &&
4955 	    phba->link_state <= LPFC_LINK_DOWN) {
4956 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4957 				"0465 Link down longer than 15 "
4958 				"seconds.  Continuing initialization\n");
4959 		stat = 1;
4960 		goto finished;
4961 	}
4962 
4963 	if (vport->port_state != LPFC_VPORT_READY)
4964 		goto finished;
4965 	if (vport->num_disc_nodes || vport->fc_prli_sent)
4966 		goto finished;
4967 	if (!atomic_read(&vport->fc_map_cnt) &&
4968 	    time < secs_to_jiffies(2))
4969 		goto finished;
4970 	if ((phba->sli.sli_flag & LPFC_SLI_MBOX_ACTIVE) != 0)
4971 		goto finished;
4972 
4973 	stat = 1;
4974 
4975 finished:
4976 	spin_unlock_irq(shost->host_lock);
4977 	return stat;
4978 }
4979 
4980 static void lpfc_host_supported_speeds_set(struct Scsi_Host *shost)
4981 {
4982 	struct lpfc_vport *vport = (struct lpfc_vport *)shost->hostdata;
4983 	struct lpfc_hba   *phba = vport->phba;
4984 
4985 	fc_host_supported_speeds(shost) = 0;
4986 	/*
4987 	 * Avoid reporting supported link speed for FCoE as it can't be
4988 	 * controlled via FCoE.
4989 	 */
4990 	if (test_bit(HBA_FCOE_MODE, &phba->hba_flag))
4991 		return;
4992 
4993 	if (phba->lmt & LMT_256Gb)
4994 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_256GBIT;
4995 	if (phba->lmt & LMT_128Gb)
4996 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_128GBIT;
4997 	if (phba->lmt & LMT_64Gb)
4998 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_64GBIT;
4999 	if (phba->lmt & LMT_32Gb)
5000 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_32GBIT;
5001 	if (phba->lmt & LMT_16Gb)
5002 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_16GBIT;
5003 	if (phba->lmt & LMT_10Gb)
5004 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_10GBIT;
5005 	if (phba->lmt & LMT_8Gb)
5006 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_8GBIT;
5007 	if (phba->lmt & LMT_4Gb)
5008 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_4GBIT;
5009 	if (phba->lmt & LMT_2Gb)
5010 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_2GBIT;
5011 	if (phba->lmt & LMT_1Gb)
5012 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_1GBIT;
5013 }
5014 
5015 /**
5016  * lpfc_host_attrib_init - Initialize SCSI host attributes on a FC port
5017  * @shost: pointer to SCSI host data structure.
5018  *
5019  * This routine initializes a given SCSI host attributes on a FC port. The
5020  * SCSI host can be either on top of a physical port or a virtual port.
5021  **/
5022 void lpfc_host_attrib_init(struct Scsi_Host *shost)
5023 {
5024 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
5025 	struct lpfc_hba   *phba = vport->phba;
5026 	/*
5027 	 * Set fixed host attributes.  Must done after lpfc_sli_hba_setup().
5028 	 */
5029 
5030 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
5031 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
5032 	fc_host_supported_classes(shost) = FC_COS_CLASS3;
5033 
5034 	memset(fc_host_supported_fc4s(shost), 0,
5035 	       sizeof(fc_host_supported_fc4s(shost)));
5036 	fc_host_supported_fc4s(shost)[2] = 1;
5037 	fc_host_supported_fc4s(shost)[7] = 1;
5038 
5039 	lpfc_vport_symbolic_node_name(vport, fc_host_symbolic_name(shost),
5040 				 sizeof fc_host_symbolic_name(shost));
5041 
5042 	lpfc_host_supported_speeds_set(shost);
5043 
5044 	fc_host_maxframe_size(shost) =
5045 		(((uint32_t) vport->fc_sparam.cmn.bbRcvSizeMsb & 0x0F) << 8) |
5046 		(uint32_t) vport->fc_sparam.cmn.bbRcvSizeLsb;
5047 
5048 	fc_host_dev_loss_tmo(shost) = vport->cfg_devloss_tmo;
5049 
5050 	/* This value is also unchanging */
5051 	memset(fc_host_active_fc4s(shost), 0,
5052 	       sizeof(fc_host_active_fc4s(shost)));
5053 	fc_host_active_fc4s(shost)[2] = 1;
5054 	fc_host_active_fc4s(shost)[7] = 1;
5055 
5056 	fc_host_max_npiv_vports(shost) = phba->max_vpi;
5057 	clear_bit(FC_LOADING, &vport->load_flag);
5058 }
5059 
5060 /**
5061  * lpfc_stop_port_s3 - Stop SLI3 device port
5062  * @phba: pointer to lpfc hba data structure.
5063  *
5064  * This routine is invoked to stop an SLI3 device port, it stops the device
5065  * from generating interrupts and stops the device driver's timers for the
5066  * device.
5067  **/
5068 static void
5069 lpfc_stop_port_s3(struct lpfc_hba *phba)
5070 {
5071 	/* Clear all interrupt enable conditions */
5072 	writel(0, phba->HCregaddr);
5073 	readl(phba->HCregaddr); /* flush */
5074 	/* Clear all pending interrupts */
5075 	writel(0xffffffff, phba->HAregaddr);
5076 	readl(phba->HAregaddr); /* flush */
5077 
5078 	/* Reset some HBA SLI setup states */
5079 	lpfc_stop_hba_timers(phba);
5080 	phba->pport->work_port_events = 0;
5081 }
5082 
5083 /**
5084  * lpfc_stop_port_s4 - Stop SLI4 device port
5085  * @phba: pointer to lpfc hba data structure.
5086  *
5087  * This routine is invoked to stop an SLI4 device port, it stops the device
5088  * from generating interrupts and stops the device driver's timers for the
5089  * device.
5090  **/
5091 static void
5092 lpfc_stop_port_s4(struct lpfc_hba *phba)
5093 {
5094 	/* Reset some HBA SLI4 setup states */
5095 	lpfc_stop_hba_timers(phba);
5096 	if (phba->pport)
5097 		phba->pport->work_port_events = 0;
5098 	phba->sli4_hba.intr_enable = 0;
5099 }
5100 
5101 /**
5102  * lpfc_stop_port - Wrapper function for stopping hba port
5103  * @phba: Pointer to HBA context object.
5104  *
5105  * This routine wraps the actual SLI3 or SLI4 hba stop port routine from
5106  * the API jump table function pointer from the lpfc_hba struct.
5107  **/
5108 void
5109 lpfc_stop_port(struct lpfc_hba *phba)
5110 {
5111 	phba->lpfc_stop_port(phba);
5112 
5113 	if (phba->wq)
5114 		flush_workqueue(phba->wq);
5115 }
5116 
5117 /**
5118  * lpfc_fcf_redisc_wait_start_timer - Start fcf rediscover wait timer
5119  * @phba: Pointer to hba for which this call is being executed.
5120  *
5121  * This routine starts the timer waiting for the FCF rediscovery to complete.
5122  **/
5123 void
5124 lpfc_fcf_redisc_wait_start_timer(struct lpfc_hba *phba)
5125 {
5126 	unsigned long fcf_redisc_wait_tmo =
5127 		(jiffies + msecs_to_jiffies(LPFC_FCF_REDISCOVER_WAIT_TMO));
5128 	/* Start fcf rediscovery wait period timer */
5129 	mod_timer(&phba->fcf.redisc_wait, fcf_redisc_wait_tmo);
5130 	spin_lock_irq(&phba->hbalock);
5131 	/* Allow action to new fcf asynchronous event */
5132 	phba->fcf.fcf_flag &= ~(FCF_AVAILABLE | FCF_SCAN_DONE);
5133 	/* Mark the FCF rediscovery pending state */
5134 	phba->fcf.fcf_flag |= FCF_REDISC_PEND;
5135 	spin_unlock_irq(&phba->hbalock);
5136 }
5137 
5138 /**
5139  * lpfc_sli4_fcf_redisc_wait_tmo - FCF table rediscover wait timeout
5140  * @t: Timer context used to obtain the pointer to lpfc hba data structure.
5141  *
5142  * This routine is invoked when waiting for FCF table rediscover has been
5143  * timed out. If new FCF record(s) has (have) been discovered during the
5144  * wait period, a new FCF event shall be added to the FCOE async event
5145  * list, and then worker thread shall be waked up for processing from the
5146  * worker thread context.
5147  **/
5148 static void
5149 lpfc_sli4_fcf_redisc_wait_tmo(struct timer_list *t)
5150 {
5151 	struct lpfc_hba *phba = timer_container_of(phba, t, fcf.redisc_wait);
5152 
5153 	/* Don't send FCF rediscovery event if timer cancelled */
5154 	spin_lock_irq(&phba->hbalock);
5155 	if (!(phba->fcf.fcf_flag & FCF_REDISC_PEND)) {
5156 		spin_unlock_irq(&phba->hbalock);
5157 		return;
5158 	}
5159 	/* Clear FCF rediscovery timer pending flag */
5160 	phba->fcf.fcf_flag &= ~FCF_REDISC_PEND;
5161 	/* FCF rediscovery event to worker thread */
5162 	phba->fcf.fcf_flag |= FCF_REDISC_EVT;
5163 	spin_unlock_irq(&phba->hbalock);
5164 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
5165 			"2776 FCF rediscover quiescent timer expired\n");
5166 	/* wake up worker thread */
5167 	lpfc_worker_wake_up(phba);
5168 }
5169 
5170 /**
5171  * lpfc_vmid_poll - VMID timeout detection
5172  * @t: Timer context used to obtain the pointer to lpfc hba data structure.
5173  *
5174  * This routine is invoked when there is no I/O on by a VM for the specified
5175  * amount of time. When this situation is detected, the VMID has to be
5176  * deregistered from the switch and all the local resources freed. The VMID
5177  * will be reassigned to the VM once the I/O begins.
5178  **/
5179 static void
5180 lpfc_vmid_poll(struct timer_list *t)
5181 {
5182 	struct lpfc_hba *phba = timer_container_of(phba, t,
5183 						   inactive_vmid_poll);
5184 	u32 wake_up = 0;
5185 
5186 	/* check if there is a need to issue QFPA */
5187 	if (phba->pport->vmid_priority_tagging) {
5188 		wake_up = 1;
5189 		phba->pport->work_port_events |= WORKER_CHECK_VMID_ISSUE_QFPA;
5190 	}
5191 
5192 	/* Is the vmid inactivity timer enabled */
5193 	if (phba->pport->vmid_inactivity_timeout ||
5194 	    test_bit(FC_DEREGISTER_ALL_APP_ID, &phba->pport->load_flag)) {
5195 		wake_up = 1;
5196 		phba->pport->work_port_events |= WORKER_CHECK_INACTIVE_VMID;
5197 	}
5198 
5199 	if (wake_up)
5200 		lpfc_worker_wake_up(phba);
5201 
5202 	/* restart the timer for the next iteration */
5203 	mod_timer(&phba->inactive_vmid_poll,
5204 		  jiffies + secs_to_jiffies(LPFC_VMID_TIMER));
5205 }
5206 
5207 /**
5208  * lpfc_sli4_parse_latt_fault - Parse sli4 link-attention link fault code
5209  * @phba: pointer to lpfc hba data structure.
5210  * @acqe_link: pointer to the async link completion queue entry.
5211  *
5212  * This routine is to parse the SLI4 link-attention link fault code.
5213  **/
5214 static void
5215 lpfc_sli4_parse_latt_fault(struct lpfc_hba *phba,
5216 			   struct lpfc_acqe_link *acqe_link)
5217 {
5218 	switch (bf_get(lpfc_acqe_fc_la_att_type, acqe_link)) {
5219 	case LPFC_FC_LA_TYPE_LINK_DOWN:
5220 	case LPFC_FC_LA_TYPE_TRUNKING_EVENT:
5221 	case LPFC_FC_LA_TYPE_ACTIVATE_FAIL:
5222 	case LPFC_FC_LA_TYPE_LINK_RESET_PRTCL_EVT:
5223 		break;
5224 	default:
5225 		switch (bf_get(lpfc_acqe_link_fault, acqe_link)) {
5226 		case LPFC_ASYNC_LINK_FAULT_NONE:
5227 		case LPFC_ASYNC_LINK_FAULT_LOCAL:
5228 		case LPFC_ASYNC_LINK_FAULT_REMOTE:
5229 		case LPFC_ASYNC_LINK_FAULT_LR_LRR:
5230 			break;
5231 		default:
5232 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5233 					"0398 Unknown link fault code: x%x\n",
5234 					bf_get(lpfc_acqe_link_fault, acqe_link));
5235 			break;
5236 		}
5237 		break;
5238 	}
5239 }
5240 
5241 /**
5242  * lpfc_sli4_parse_latt_type - Parse sli4 link attention type
5243  * @phba: pointer to lpfc hba data structure.
5244  * @acqe_link: pointer to the async link completion queue entry.
5245  *
5246  * This routine is to parse the SLI4 link attention type and translate it
5247  * into the base driver's link attention type coding.
5248  *
5249  * Return: Link attention type in terms of base driver's coding.
5250  **/
5251 static uint8_t
5252 lpfc_sli4_parse_latt_type(struct lpfc_hba *phba,
5253 			  struct lpfc_acqe_link *acqe_link)
5254 {
5255 	uint8_t att_type;
5256 
5257 	switch (bf_get(lpfc_acqe_link_status, acqe_link)) {
5258 	case LPFC_ASYNC_LINK_STATUS_DOWN:
5259 	case LPFC_ASYNC_LINK_STATUS_LOGICAL_DOWN:
5260 		att_type = LPFC_ATT_LINK_DOWN;
5261 		break;
5262 	case LPFC_ASYNC_LINK_STATUS_UP:
5263 		/* Ignore physical link up events - wait for logical link up */
5264 		att_type = LPFC_ATT_RESERVED;
5265 		break;
5266 	case LPFC_ASYNC_LINK_STATUS_LOGICAL_UP:
5267 		att_type = LPFC_ATT_LINK_UP;
5268 		break;
5269 	default:
5270 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5271 				"0399 Invalid link attention type: x%x\n",
5272 				bf_get(lpfc_acqe_link_status, acqe_link));
5273 		att_type = LPFC_ATT_RESERVED;
5274 		break;
5275 	}
5276 	return att_type;
5277 }
5278 
5279 /**
5280  * lpfc_sli_port_speed_get - Get sli3 link speed code to link speed
5281  * @phba: pointer to lpfc hba data structure.
5282  *
5283  * This routine is to get an SLI3 FC port's link speed in Mbps.
5284  *
5285  * Return: link speed in terms of Mbps.
5286  **/
5287 uint32_t
5288 lpfc_sli_port_speed_get(struct lpfc_hba *phba)
5289 {
5290 	uint32_t link_speed;
5291 
5292 	if (!lpfc_is_link_up(phba))
5293 		return 0;
5294 
5295 	if (phba->sli_rev <= LPFC_SLI_REV3) {
5296 		switch (phba->fc_linkspeed) {
5297 		case LPFC_LINK_SPEED_1GHZ:
5298 			link_speed = 1000;
5299 			break;
5300 		case LPFC_LINK_SPEED_2GHZ:
5301 			link_speed = 2000;
5302 			break;
5303 		case LPFC_LINK_SPEED_4GHZ:
5304 			link_speed = 4000;
5305 			break;
5306 		case LPFC_LINK_SPEED_8GHZ:
5307 			link_speed = 8000;
5308 			break;
5309 		case LPFC_LINK_SPEED_10GHZ:
5310 			link_speed = 10000;
5311 			break;
5312 		case LPFC_LINK_SPEED_16GHZ:
5313 			link_speed = 16000;
5314 			break;
5315 		default:
5316 			link_speed = 0;
5317 		}
5318 	} else {
5319 		if (phba->sli4_hba.link_state.logical_speed)
5320 			link_speed =
5321 			      phba->sli4_hba.link_state.logical_speed;
5322 		else
5323 			link_speed = phba->sli4_hba.link_state.speed;
5324 	}
5325 	return link_speed;
5326 }
5327 
5328 /**
5329  * lpfc_sli4_port_speed_parse - Parse async evt link speed code to link speed
5330  * @phba: pointer to lpfc hba data structure.
5331  * @evt_code: asynchronous event code.
5332  * @speed_code: asynchronous event link speed code.
5333  *
5334  * This routine is to parse the giving SLI4 async event link speed code into
5335  * value of Mbps for the link speed.
5336  *
5337  * Return: link speed in terms of Mbps.
5338  **/
5339 static uint32_t
5340 lpfc_sli4_port_speed_parse(struct lpfc_hba *phba, uint32_t evt_code,
5341 			   uint8_t speed_code)
5342 {
5343 	uint32_t port_speed;
5344 
5345 	switch (evt_code) {
5346 	case LPFC_TRAILER_CODE_LINK:
5347 		switch (speed_code) {
5348 		case LPFC_ASYNC_LINK_SPEED_ZERO:
5349 			port_speed = 0;
5350 			break;
5351 		case LPFC_ASYNC_LINK_SPEED_10MBPS:
5352 			port_speed = 10;
5353 			break;
5354 		case LPFC_ASYNC_LINK_SPEED_100MBPS:
5355 			port_speed = 100;
5356 			break;
5357 		case LPFC_ASYNC_LINK_SPEED_1GBPS:
5358 			port_speed = 1000;
5359 			break;
5360 		case LPFC_ASYNC_LINK_SPEED_10GBPS:
5361 			port_speed = 10000;
5362 			break;
5363 		case LPFC_ASYNC_LINK_SPEED_20GBPS:
5364 			port_speed = 20000;
5365 			break;
5366 		case LPFC_ASYNC_LINK_SPEED_25GBPS:
5367 			port_speed = 25000;
5368 			break;
5369 		case LPFC_ASYNC_LINK_SPEED_40GBPS:
5370 			port_speed = 40000;
5371 			break;
5372 		case LPFC_ASYNC_LINK_SPEED_100GBPS:
5373 			port_speed = 100000;
5374 			break;
5375 		default:
5376 			port_speed = 0;
5377 		}
5378 		break;
5379 	case LPFC_TRAILER_CODE_FC:
5380 		switch (speed_code) {
5381 		case LPFC_FC_LA_SPEED_UNKNOWN:
5382 			port_speed = 0;
5383 			break;
5384 		case LPFC_FC_LA_SPEED_1G:
5385 			port_speed = 1000;
5386 			break;
5387 		case LPFC_FC_LA_SPEED_2G:
5388 			port_speed = 2000;
5389 			break;
5390 		case LPFC_FC_LA_SPEED_4G:
5391 			port_speed = 4000;
5392 			break;
5393 		case LPFC_FC_LA_SPEED_8G:
5394 			port_speed = 8000;
5395 			break;
5396 		case LPFC_FC_LA_SPEED_10G:
5397 			port_speed = 10000;
5398 			break;
5399 		case LPFC_FC_LA_SPEED_16G:
5400 			port_speed = 16000;
5401 			break;
5402 		case LPFC_FC_LA_SPEED_32G:
5403 			port_speed = 32000;
5404 			break;
5405 		case LPFC_FC_LA_SPEED_64G:
5406 			port_speed = 64000;
5407 			break;
5408 		case LPFC_FC_LA_SPEED_128G:
5409 			port_speed = 128000;
5410 			break;
5411 		case LPFC_FC_LA_SPEED_256G:
5412 			port_speed = 256000;
5413 			break;
5414 		default:
5415 			port_speed = 0;
5416 		}
5417 		break;
5418 	default:
5419 		port_speed = 0;
5420 	}
5421 	return port_speed;
5422 }
5423 
5424 /**
5425  * lpfc_sli4_async_link_evt - Process the asynchronous FCoE link event
5426  * @phba: pointer to lpfc hba data structure.
5427  * @acqe_link: pointer to the async link completion queue entry.
5428  *
5429  * This routine is to handle the SLI4 asynchronous FCoE link event.
5430  **/
5431 static void
5432 lpfc_sli4_async_link_evt(struct lpfc_hba *phba,
5433 			 struct lpfc_acqe_link *acqe_link)
5434 {
5435 	LPFC_MBOXQ_t *pmb;
5436 	MAILBOX_t *mb;
5437 	struct lpfc_mbx_read_top *la;
5438 	uint8_t att_type;
5439 	int rc;
5440 
5441 	att_type = lpfc_sli4_parse_latt_type(phba, acqe_link);
5442 	if (att_type != LPFC_ATT_LINK_DOWN && att_type != LPFC_ATT_LINK_UP)
5443 		return;
5444 	phba->fcoe_eventtag = acqe_link->event_tag;
5445 	pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5446 	if (!pmb) {
5447 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5448 				"0395 The mboxq allocation failed\n");
5449 		return;
5450 	}
5451 
5452 	rc = lpfc_mbox_rsrc_prep(phba, pmb);
5453 	if (rc) {
5454 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5455 				"0396 mailbox allocation failed\n");
5456 		goto out_free_pmb;
5457 	}
5458 
5459 	/* Cleanup any outstanding ELS commands */
5460 	lpfc_els_flush_all_cmd(phba);
5461 
5462 	/* Block ELS IOCBs until we have done process link event */
5463 	phba->sli4_hba.els_wq->pring->flag |= LPFC_STOP_IOCB_EVENT;
5464 
5465 	/* Update link event statistics */
5466 	phba->sli.slistat.link_event++;
5467 
5468 	/* Create lpfc_handle_latt mailbox command from link ACQE */
5469 	lpfc_read_topology(phba, pmb, pmb->ctx_buf);
5470 	pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
5471 	pmb->vport = phba->pport;
5472 
5473 	/* Keep the link status for extra SLI4 state machine reference */
5474 	phba->sli4_hba.link_state.speed =
5475 			lpfc_sli4_port_speed_parse(phba, LPFC_TRAILER_CODE_LINK,
5476 				bf_get(lpfc_acqe_link_speed, acqe_link));
5477 	phba->sli4_hba.link_state.duplex =
5478 				bf_get(lpfc_acqe_link_duplex, acqe_link);
5479 	phba->sli4_hba.link_state.status =
5480 				bf_get(lpfc_acqe_link_status, acqe_link);
5481 	phba->sli4_hba.link_state.type =
5482 				bf_get(lpfc_acqe_link_type, acqe_link);
5483 	phba->sli4_hba.link_state.number =
5484 				bf_get(lpfc_acqe_link_number, acqe_link);
5485 	phba->sli4_hba.link_state.fault =
5486 				bf_get(lpfc_acqe_link_fault, acqe_link);
5487 	phba->sli4_hba.link_state.logical_speed =
5488 			bf_get(lpfc_acqe_logical_link_speed, acqe_link) * 10;
5489 
5490 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5491 			"2900 Async FC/FCoE Link event - Speed:%dGBit "
5492 			"duplex:x%x LA Type:x%x Port Type:%d Port Number:%d "
5493 			"Logical speed:%dMbps Fault:%d\n",
5494 			phba->sli4_hba.link_state.speed,
5495 			phba->sli4_hba.link_state.topology,
5496 			phba->sli4_hba.link_state.status,
5497 			phba->sli4_hba.link_state.type,
5498 			phba->sli4_hba.link_state.number,
5499 			phba->sli4_hba.link_state.logical_speed,
5500 			phba->sli4_hba.link_state.fault);
5501 	/*
5502 	 * For FC Mode: issue the READ_TOPOLOGY mailbox command to fetch
5503 	 * topology info. Note: Optional for non FC-AL ports.
5504 	 */
5505 	if (!test_bit(HBA_FCOE_MODE, &phba->hba_flag)) {
5506 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
5507 		if (rc == MBX_NOT_FINISHED)
5508 			goto out_free_pmb;
5509 		return;
5510 	}
5511 	/*
5512 	 * For FCoE Mode: fill in all the topology information we need and call
5513 	 * the READ_TOPOLOGY completion routine to continue without actually
5514 	 * sending the READ_TOPOLOGY mailbox command to the port.
5515 	 */
5516 	/* Initialize completion status */
5517 	mb = &pmb->u.mb;
5518 	mb->mbxStatus = MBX_SUCCESS;
5519 
5520 	/* Parse port fault information field */
5521 	lpfc_sli4_parse_latt_fault(phba, acqe_link);
5522 
5523 	/* Parse and translate link attention fields */
5524 	la = (struct lpfc_mbx_read_top *) &pmb->u.mb.un.varReadTop;
5525 	la->eventTag = acqe_link->event_tag;
5526 	bf_set(lpfc_mbx_read_top_att_type, la, att_type);
5527 	bf_set(lpfc_mbx_read_top_link_spd, la,
5528 	       (bf_get(lpfc_acqe_link_speed, acqe_link)));
5529 
5530 	/* Fake the following irrelevant fields */
5531 	bf_set(lpfc_mbx_read_top_topology, la, LPFC_TOPOLOGY_PT_PT);
5532 	bf_set(lpfc_mbx_read_top_alpa_granted, la, 0);
5533 	bf_set(lpfc_mbx_read_top_il, la, 0);
5534 	bf_set(lpfc_mbx_read_top_pb, la, 0);
5535 	bf_set(lpfc_mbx_read_top_fa, la, 0);
5536 	bf_set(lpfc_mbx_read_top_mm, la, 0);
5537 
5538 	/* Invoke the lpfc_handle_latt mailbox command callback function */
5539 	lpfc_mbx_cmpl_read_topology(phba, pmb);
5540 
5541 	return;
5542 
5543 out_free_pmb:
5544 	lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
5545 }
5546 
5547 /**
5548  * lpfc_async_link_speed_to_read_top - Parse async evt link speed code to read
5549  * topology.
5550  * @phba: pointer to lpfc hba data structure.
5551  * @speed_code: asynchronous event link speed code.
5552  *
5553  * This routine is to parse the giving SLI4 async event link speed code into
5554  * value of Read topology link speed.
5555  *
5556  * Return: link speed in terms of Read topology.
5557  **/
5558 static uint8_t
5559 lpfc_async_link_speed_to_read_top(struct lpfc_hba *phba, uint8_t speed_code)
5560 {
5561 	uint8_t port_speed;
5562 
5563 	switch (speed_code) {
5564 	case LPFC_FC_LA_SPEED_1G:
5565 		port_speed = LPFC_LINK_SPEED_1GHZ;
5566 		break;
5567 	case LPFC_FC_LA_SPEED_2G:
5568 		port_speed = LPFC_LINK_SPEED_2GHZ;
5569 		break;
5570 	case LPFC_FC_LA_SPEED_4G:
5571 		port_speed = LPFC_LINK_SPEED_4GHZ;
5572 		break;
5573 	case LPFC_FC_LA_SPEED_8G:
5574 		port_speed = LPFC_LINK_SPEED_8GHZ;
5575 		break;
5576 	case LPFC_FC_LA_SPEED_16G:
5577 		port_speed = LPFC_LINK_SPEED_16GHZ;
5578 		break;
5579 	case LPFC_FC_LA_SPEED_32G:
5580 		port_speed = LPFC_LINK_SPEED_32GHZ;
5581 		break;
5582 	case LPFC_FC_LA_SPEED_64G:
5583 		port_speed = LPFC_LINK_SPEED_64GHZ;
5584 		break;
5585 	case LPFC_FC_LA_SPEED_128G:
5586 		port_speed = LPFC_LINK_SPEED_128GHZ;
5587 		break;
5588 	case LPFC_FC_LA_SPEED_256G:
5589 		port_speed = LPFC_LINK_SPEED_256GHZ;
5590 		break;
5591 	default:
5592 		port_speed = 0;
5593 		break;
5594 	}
5595 
5596 	return port_speed;
5597 }
5598 
5599 void
5600 lpfc_cgn_dump_rxmonitor(struct lpfc_hba *phba)
5601 {
5602 	if (!phba->rx_monitor) {
5603 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5604 				"4411 Rx Monitor Info is empty.\n");
5605 	} else {
5606 		lpfc_rx_monitor_report(phba, phba->rx_monitor, NULL, 0,
5607 				       LPFC_MAX_RXMONITOR_DUMP);
5608 	}
5609 }
5610 
5611 /**
5612  * lpfc_cgn_update_stat - Save data into congestion stats buffer
5613  * @phba: pointer to lpfc hba data structure.
5614  * @dtag: FPIN descriptor received
5615  *
5616  * Increment the FPIN received counter/time when it happens.
5617  */
5618 void
5619 lpfc_cgn_update_stat(struct lpfc_hba *phba, uint32_t dtag)
5620 {
5621 	struct lpfc_cgn_info *cp;
5622 	u32 value;
5623 
5624 	/* Make sure we have a congestion info buffer */
5625 	if (!phba->cgn_i)
5626 		return;
5627 	cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
5628 
5629 	/* Update congestion statistics */
5630 	switch (dtag) {
5631 	case ELS_DTAG_LNK_INTEGRITY:
5632 		le32_add_cpu(&cp->link_integ_notification, 1);
5633 		lpfc_cgn_update_tstamp(phba, &cp->stat_lnk);
5634 		break;
5635 	case ELS_DTAG_DELIVERY:
5636 		le32_add_cpu(&cp->delivery_notification, 1);
5637 		lpfc_cgn_update_tstamp(phba, &cp->stat_delivery);
5638 		break;
5639 	case ELS_DTAG_PEER_CONGEST:
5640 		le32_add_cpu(&cp->cgn_peer_notification, 1);
5641 		lpfc_cgn_update_tstamp(phba, &cp->stat_peer);
5642 		break;
5643 	case ELS_DTAG_CONGESTION:
5644 		le32_add_cpu(&cp->cgn_notification, 1);
5645 		lpfc_cgn_update_tstamp(phba, &cp->stat_fpin);
5646 	}
5647 	if (phba->cgn_fpin_frequency &&
5648 	    phba->cgn_fpin_frequency != LPFC_FPIN_INIT_FREQ) {
5649 		value = LPFC_CGN_TIMER_TO_MIN / phba->cgn_fpin_frequency;
5650 		cp->cgn_stat_npm = value;
5651 	}
5652 
5653 	value = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ,
5654 				    LPFC_CGN_CRC32_SEED);
5655 	cp->cgn_info_crc = cpu_to_le32(value);
5656 }
5657 
5658 /**
5659  * lpfc_cgn_update_tstamp - Update cmf timestamp
5660  * @phba: pointer to lpfc hba data structure.
5661  * @ts: structure to write the timestamp to.
5662  */
5663 void
5664 lpfc_cgn_update_tstamp(struct lpfc_hba *phba, struct lpfc_cgn_ts *ts)
5665 {
5666 	struct timespec64 cur_time;
5667 	struct tm tm_val;
5668 
5669 	ktime_get_real_ts64(&cur_time);
5670 	time64_to_tm(cur_time.tv_sec, 0, &tm_val);
5671 
5672 	ts->month = tm_val.tm_mon + 1;
5673 	ts->day	= tm_val.tm_mday;
5674 	ts->year = tm_val.tm_year - 100;
5675 	ts->hour = tm_val.tm_hour;
5676 	ts->minute = tm_val.tm_min;
5677 	ts->second = tm_val.tm_sec;
5678 
5679 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5680 			"2646 Updated CMF timestamp : "
5681 			"%u/%u/%u %u:%u:%u\n",
5682 			ts->day, ts->month,
5683 			ts->year, ts->hour,
5684 			ts->minute, ts->second);
5685 }
5686 
5687 /**
5688  * lpfc_cmf_stats_timer - Save data into registered congestion buffer
5689  * @timer: Timer cookie to access lpfc private data
5690  *
5691  * Save the congestion event data every minute.
5692  * On the hour collapse all the minute data into hour data. Every day
5693  * collapse all the hour data into daily data. Separate driver
5694  * and fabrc congestion event counters that will be saved out
5695  * to the registered congestion buffer every minute.
5696  */
5697 static enum hrtimer_restart
5698 lpfc_cmf_stats_timer(struct hrtimer *timer)
5699 {
5700 	struct lpfc_hba *phba;
5701 	struct lpfc_cgn_info *cp;
5702 	uint32_t i, index;
5703 	uint16_t value, mvalue;
5704 	uint64_t bps;
5705 	uint32_t mbps;
5706 	uint32_t dvalue, wvalue, lvalue, avalue;
5707 	uint64_t latsum;
5708 	__le16 *ptr;
5709 	__le32 *lptr;
5710 	__le16 *mptr;
5711 
5712 	phba = container_of(timer, struct lpfc_hba, cmf_stats_timer);
5713 	/* Make sure we have a congestion info buffer */
5714 	if (!phba->cgn_i)
5715 		return HRTIMER_NORESTART;
5716 	cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
5717 
5718 	phba->cgn_evt_timestamp = jiffies +
5719 			msecs_to_jiffies(LPFC_CGN_TIMER_TO_MIN);
5720 	phba->cgn_evt_minute++;
5721 
5722 	/* We should get to this point in the routine on 1 minute intervals */
5723 	lpfc_cgn_update_tstamp(phba, &cp->base_time);
5724 
5725 	if (phba->cgn_fpin_frequency &&
5726 	    phba->cgn_fpin_frequency != LPFC_FPIN_INIT_FREQ) {
5727 		value = LPFC_CGN_TIMER_TO_MIN / phba->cgn_fpin_frequency;
5728 		cp->cgn_stat_npm = value;
5729 	}
5730 
5731 	/* Read and clear the latency counters for this minute */
5732 	lvalue = atomic_read(&phba->cgn_latency_evt_cnt);
5733 	latsum = atomic64_read(&phba->cgn_latency_evt);
5734 	atomic_set(&phba->cgn_latency_evt_cnt, 0);
5735 	atomic64_set(&phba->cgn_latency_evt, 0);
5736 
5737 	/* We need to store MB/sec bandwidth in the congestion information.
5738 	 * block_cnt is count of 512 byte blocks for the entire minute,
5739 	 * bps will get bytes per sec before finally converting to MB/sec.
5740 	 */
5741 	bps = div_u64(phba->rx_block_cnt, LPFC_SEC_MIN) * 512;
5742 	phba->rx_block_cnt = 0;
5743 	mvalue = bps / (1024 * 1024); /* convert to MB/sec */
5744 
5745 	/* Every minute */
5746 	/* cgn parameters */
5747 	cp->cgn_info_mode = phba->cgn_p.cgn_param_mode;
5748 	cp->cgn_info_level0 = phba->cgn_p.cgn_param_level0;
5749 	cp->cgn_info_level1 = phba->cgn_p.cgn_param_level1;
5750 	cp->cgn_info_level2 = phba->cgn_p.cgn_param_level2;
5751 
5752 	/* Fill in default LUN qdepth */
5753 	value = (uint16_t)(phba->pport->cfg_lun_queue_depth);
5754 	cp->cgn_lunq = cpu_to_le16(value);
5755 
5756 	/* Record congestion buffer info - every minute
5757 	 * cgn_driver_evt_cnt (Driver events)
5758 	 * cgn_fabric_warn_cnt (Congestion Warnings)
5759 	 * cgn_latency_evt_cnt / cgn_latency_evt (IO Latency)
5760 	 * cgn_fabric_alarm_cnt (Congestion Alarms)
5761 	 */
5762 	index = ++cp->cgn_index_minute;
5763 	if (cp->cgn_index_minute == LPFC_MIN_HOUR) {
5764 		cp->cgn_index_minute = 0;
5765 		index = 0;
5766 	}
5767 
5768 	/* Get the number of driver events in this sample and reset counter */
5769 	dvalue = atomic_read(&phba->cgn_driver_evt_cnt);
5770 	atomic_set(&phba->cgn_driver_evt_cnt, 0);
5771 
5772 	/* Get the number of warning events - FPIN and Signal for this minute */
5773 	wvalue = 0;
5774 	if ((phba->cgn_reg_fpin & LPFC_CGN_FPIN_WARN) ||
5775 	    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY ||
5776 	    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM)
5777 		wvalue = atomic_read(&phba->cgn_fabric_warn_cnt);
5778 	atomic_set(&phba->cgn_fabric_warn_cnt, 0);
5779 
5780 	/* Get the number of alarm events - FPIN and Signal for this minute */
5781 	avalue = 0;
5782 	if ((phba->cgn_reg_fpin & LPFC_CGN_FPIN_ALARM) ||
5783 	    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM)
5784 		avalue = atomic_read(&phba->cgn_fabric_alarm_cnt);
5785 	atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
5786 
5787 	/* Collect the driver, warning, alarm and latency counts for this
5788 	 * minute into the driver congestion buffer.
5789 	 */
5790 	ptr = &cp->cgn_drvr_min[index];
5791 	value = (uint16_t)dvalue;
5792 	*ptr = cpu_to_le16(value);
5793 
5794 	ptr = &cp->cgn_warn_min[index];
5795 	value = (uint16_t)wvalue;
5796 	*ptr = cpu_to_le16(value);
5797 
5798 	ptr = &cp->cgn_alarm_min[index];
5799 	value = (uint16_t)avalue;
5800 	*ptr = cpu_to_le16(value);
5801 
5802 	lptr = &cp->cgn_latency_min[index];
5803 	if (lvalue) {
5804 		lvalue = (uint32_t)div_u64(latsum, lvalue);
5805 		*lptr = cpu_to_le32(lvalue);
5806 	} else {
5807 		*lptr = 0;
5808 	}
5809 
5810 	/* Collect the bandwidth value into the driver's congesion buffer. */
5811 	mptr = &cp->cgn_bw_min[index];
5812 	*mptr = cpu_to_le16(mvalue);
5813 
5814 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5815 			"2418 Congestion Info - minute (%d): %d %d %d %d %d\n",
5816 			index, dvalue, wvalue, *lptr, mvalue, avalue);
5817 
5818 	/* Every hour */
5819 	if ((phba->cgn_evt_minute % LPFC_MIN_HOUR) == 0) {
5820 		/* Record congestion buffer info - every hour
5821 		 * Collapse all minutes into an hour
5822 		 */
5823 		index = ++cp->cgn_index_hour;
5824 		if (cp->cgn_index_hour == LPFC_HOUR_DAY) {
5825 			cp->cgn_index_hour = 0;
5826 			index = 0;
5827 		}
5828 
5829 		dvalue = 0;
5830 		wvalue = 0;
5831 		lvalue = 0;
5832 		avalue = 0;
5833 		mvalue = 0;
5834 		mbps = 0;
5835 		for (i = 0; i < LPFC_MIN_HOUR; i++) {
5836 			dvalue += le16_to_cpu(cp->cgn_drvr_min[i]);
5837 			wvalue += le16_to_cpu(cp->cgn_warn_min[i]);
5838 			lvalue += le32_to_cpu(cp->cgn_latency_min[i]);
5839 			mbps += le16_to_cpu(cp->cgn_bw_min[i]);
5840 			avalue += le16_to_cpu(cp->cgn_alarm_min[i]);
5841 		}
5842 		if (lvalue)		/* Avg of latency averages */
5843 			lvalue /= LPFC_MIN_HOUR;
5844 		if (mbps)		/* Avg of Bandwidth averages */
5845 			mvalue = mbps / LPFC_MIN_HOUR;
5846 
5847 		lptr = &cp->cgn_drvr_hr[index];
5848 		*lptr = cpu_to_le32(dvalue);
5849 		lptr = &cp->cgn_warn_hr[index];
5850 		*lptr = cpu_to_le32(wvalue);
5851 		lptr = &cp->cgn_latency_hr[index];
5852 		*lptr = cpu_to_le32(lvalue);
5853 		mptr = &cp->cgn_bw_hr[index];
5854 		*mptr = cpu_to_le16(mvalue);
5855 		lptr = &cp->cgn_alarm_hr[index];
5856 		*lptr = cpu_to_le32(avalue);
5857 
5858 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5859 				"2419 Congestion Info - hour "
5860 				"(%d): %d %d %d %d %d\n",
5861 				index, dvalue, wvalue, lvalue, mvalue, avalue);
5862 	}
5863 
5864 	/* Every day */
5865 	if ((phba->cgn_evt_minute % LPFC_MIN_DAY) == 0) {
5866 		/* Record congestion buffer info - every hour
5867 		 * Collapse all hours into a day. Rotate days
5868 		 * after LPFC_MAX_CGN_DAYS.
5869 		 */
5870 		index = ++cp->cgn_index_day;
5871 		if (cp->cgn_index_day == LPFC_MAX_CGN_DAYS) {
5872 			cp->cgn_index_day = 0;
5873 			index = 0;
5874 		}
5875 
5876 		dvalue = 0;
5877 		wvalue = 0;
5878 		lvalue = 0;
5879 		mvalue = 0;
5880 		mbps = 0;
5881 		avalue = 0;
5882 		for (i = 0; i < LPFC_HOUR_DAY; i++) {
5883 			dvalue += le32_to_cpu(cp->cgn_drvr_hr[i]);
5884 			wvalue += le32_to_cpu(cp->cgn_warn_hr[i]);
5885 			lvalue += le32_to_cpu(cp->cgn_latency_hr[i]);
5886 			mbps += le16_to_cpu(cp->cgn_bw_hr[i]);
5887 			avalue += le32_to_cpu(cp->cgn_alarm_hr[i]);
5888 		}
5889 		if (lvalue)		/* Avg of latency averages */
5890 			lvalue /= LPFC_HOUR_DAY;
5891 		if (mbps)		/* Avg of Bandwidth averages */
5892 			mvalue = mbps / LPFC_HOUR_DAY;
5893 
5894 		lptr = &cp->cgn_drvr_day[index];
5895 		*lptr = cpu_to_le32(dvalue);
5896 		lptr = &cp->cgn_warn_day[index];
5897 		*lptr = cpu_to_le32(wvalue);
5898 		lptr = &cp->cgn_latency_day[index];
5899 		*lptr = cpu_to_le32(lvalue);
5900 		mptr = &cp->cgn_bw_day[index];
5901 		*mptr = cpu_to_le16(mvalue);
5902 		lptr = &cp->cgn_alarm_day[index];
5903 		*lptr = cpu_to_le32(avalue);
5904 
5905 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5906 				"2420 Congestion Info - daily (%d): "
5907 				"%d %d %d %d %d\n",
5908 				index, dvalue, wvalue, lvalue, mvalue, avalue);
5909 	}
5910 
5911 	/* Use the frequency found in the last rcv'ed FPIN */
5912 	value = phba->cgn_fpin_frequency;
5913 	cp->cgn_warn_freq = cpu_to_le16(value);
5914 	cp->cgn_alarm_freq = cpu_to_le16(value);
5915 
5916 	lvalue = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ,
5917 				     LPFC_CGN_CRC32_SEED);
5918 	cp->cgn_info_crc = cpu_to_le32(lvalue);
5919 
5920 	hrtimer_forward_now(timer, ktime_set(0, LPFC_SEC_MIN * NSEC_PER_SEC));
5921 
5922 	return HRTIMER_RESTART;
5923 }
5924 
5925 /**
5926  * lpfc_calc_cmf_latency - latency from start of rxate timer interval
5927  * @phba: The Hba for which this call is being executed.
5928  *
5929  * The routine calculates the latency from the beginning of the CMF timer
5930  * interval to the current point in time. It is called from IO completion
5931  * when we exceed our Bandwidth limitation for the time interval.
5932  */
5933 uint32_t
5934 lpfc_calc_cmf_latency(struct lpfc_hba *phba)
5935 {
5936 	struct timespec64 cmpl_time;
5937 	uint32_t msec = 0;
5938 
5939 	ktime_get_real_ts64(&cmpl_time);
5940 
5941 	/* This routine works on a ms granularity so sec and usec are
5942 	 * converted accordingly.
5943 	 */
5944 	if (cmpl_time.tv_sec == phba->cmf_latency.tv_sec) {
5945 		msec = (cmpl_time.tv_nsec - phba->cmf_latency.tv_nsec) /
5946 			NSEC_PER_MSEC;
5947 	} else {
5948 		if (cmpl_time.tv_nsec >= phba->cmf_latency.tv_nsec) {
5949 			msec = (cmpl_time.tv_sec -
5950 				phba->cmf_latency.tv_sec) * MSEC_PER_SEC;
5951 			msec += ((cmpl_time.tv_nsec -
5952 				  phba->cmf_latency.tv_nsec) / NSEC_PER_MSEC);
5953 		} else {
5954 			msec = (cmpl_time.tv_sec - phba->cmf_latency.tv_sec -
5955 				1) * MSEC_PER_SEC;
5956 			msec += (((NSEC_PER_SEC - phba->cmf_latency.tv_nsec) +
5957 				 cmpl_time.tv_nsec) / NSEC_PER_MSEC);
5958 		}
5959 	}
5960 	return msec;
5961 }
5962 
5963 /**
5964  * lpfc_cmf_timer -  This is the timer function for one congestion
5965  * rate interval.
5966  * @timer: Pointer to the high resolution timer that expired
5967  */
5968 static enum hrtimer_restart
5969 lpfc_cmf_timer(struct hrtimer *timer)
5970 {
5971 	struct lpfc_hba *phba = container_of(timer, struct lpfc_hba,
5972 					     cmf_timer);
5973 	struct rx_info_entry entry;
5974 	uint32_t io_cnt;
5975 	uint32_t busy, max_read;
5976 	uint64_t total, rcv, lat, mbpi, extra, cnt;
5977 	int timer_interval = LPFC_CMF_INTERVAL;
5978 	uint32_t ms;
5979 	struct lpfc_cgn_stat *cgs;
5980 	int cpu;
5981 
5982 	/* Only restart the timer if congestion mgmt is on */
5983 	if (phba->cmf_active_mode == LPFC_CFG_OFF ||
5984 	    !phba->cmf_latency.tv_sec) {
5985 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5986 				"6224 CMF timer exit: %d %lld\n",
5987 				phba->cmf_active_mode,
5988 				(uint64_t)phba->cmf_latency.tv_sec);
5989 		return HRTIMER_NORESTART;
5990 	}
5991 
5992 	/* If pport is not ready yet, just exit and wait for
5993 	 * the next timer cycle to hit.
5994 	 */
5995 	if (!phba->pport)
5996 		goto skip;
5997 
5998 	/* Do not block SCSI IO while in the timer routine since
5999 	 * total_bytes will be cleared
6000 	 */
6001 	atomic_set(&phba->cmf_stop_io, 1);
6002 
6003 	/* First we need to calculate the actual ms between
6004 	 * the last timer interrupt and this one. We ask for
6005 	 * LPFC_CMF_INTERVAL, however the actual time may
6006 	 * vary depending on system overhead.
6007 	 */
6008 	ms = lpfc_calc_cmf_latency(phba);
6009 
6010 
6011 	/* Immediately after we calculate the time since the last
6012 	 * timer interrupt, set the start time for the next
6013 	 * interrupt
6014 	 */
6015 	ktime_get_real_ts64(&phba->cmf_latency);
6016 
6017 	phba->cmf_link_byte_count =
6018 		div_u64(phba->cmf_max_line_rate * LPFC_CMF_INTERVAL, 1000);
6019 
6020 	/* Collect all the stats from the prior timer interval */
6021 	total = 0;
6022 	io_cnt = 0;
6023 	lat = 0;
6024 	rcv = 0;
6025 	for_each_present_cpu(cpu) {
6026 		cgs = per_cpu_ptr(phba->cmf_stat, cpu);
6027 		total += atomic64_xchg(&cgs->total_bytes, 0);
6028 		io_cnt += atomic_xchg(&cgs->rx_io_cnt, 0);
6029 		lat += atomic64_xchg(&cgs->rx_latency, 0);
6030 		rcv += atomic64_xchg(&cgs->rcv_bytes, 0);
6031 	}
6032 
6033 	/* Before we issue another CMF_SYNC_WQE, retrieve the BW
6034 	 * returned from the last CMF_SYNC_WQE issued, from
6035 	 * cmf_last_sync_bw. This will be the target BW for
6036 	 * this next timer interval.
6037 	 */
6038 	if (phba->cmf_active_mode == LPFC_CFG_MANAGED &&
6039 	    phba->link_state != LPFC_LINK_DOWN &&
6040 	    test_bit(HBA_SETUP, &phba->hba_flag)) {
6041 		mbpi = phba->cmf_last_sync_bw;
6042 		phba->cmf_last_sync_bw = 0;
6043 		extra = 0;
6044 
6045 		/* Calculate any extra bytes needed to account for the
6046 		 * timer accuracy. If we are less than LPFC_CMF_INTERVAL
6047 		 * calculate the adjustment needed for total to reflect
6048 		 * a full LPFC_CMF_INTERVAL.
6049 		 */
6050 		if (ms && ms < LPFC_CMF_INTERVAL) {
6051 			cnt = div_u64(total, ms); /* bytes per ms */
6052 			cnt *= LPFC_CMF_INTERVAL; /* what total should be */
6053 			extra = cnt - total;
6054 		}
6055 		lpfc_issue_cmf_sync_wqe(phba, LPFC_CMF_INTERVAL, total + extra);
6056 	} else {
6057 		/* For Monitor mode or link down we want mbpi
6058 		 * to be the full link speed
6059 		 */
6060 		mbpi = phba->cmf_link_byte_count;
6061 		extra = 0;
6062 	}
6063 	phba->cmf_timer_cnt++;
6064 
6065 	if (io_cnt) {
6066 		/* Update congestion info buffer latency in us */
6067 		atomic_add(io_cnt, &phba->cgn_latency_evt_cnt);
6068 		atomic64_add(lat, &phba->cgn_latency_evt);
6069 	}
6070 	busy = atomic_xchg(&phba->cmf_busy, 0);
6071 	max_read = atomic_xchg(&phba->rx_max_read_cnt, 0);
6072 
6073 	/* Calculate MBPI for the next timer interval */
6074 	if (mbpi) {
6075 		if (mbpi > phba->cmf_link_byte_count ||
6076 		    phba->cmf_active_mode == LPFC_CFG_MONITOR)
6077 			mbpi = phba->cmf_link_byte_count;
6078 
6079 		/* Change max_bytes_per_interval to what the prior
6080 		 * CMF_SYNC_WQE cmpl indicated.
6081 		 */
6082 		if (mbpi != phba->cmf_max_bytes_per_interval)
6083 			phba->cmf_max_bytes_per_interval = mbpi;
6084 	}
6085 
6086 	/* Save rxmonitor information for debug */
6087 	if (phba->rx_monitor) {
6088 		entry.total_bytes = total;
6089 		entry.cmf_bytes = total + extra;
6090 		entry.rcv_bytes = rcv;
6091 		entry.cmf_busy = busy;
6092 		entry.cmf_info = phba->cmf_active_info;
6093 		if (io_cnt) {
6094 			entry.avg_io_latency = div_u64(lat, io_cnt);
6095 			entry.avg_io_size = div_u64(rcv, io_cnt);
6096 		} else {
6097 			entry.avg_io_latency = 0;
6098 			entry.avg_io_size = 0;
6099 		}
6100 		entry.max_read_cnt = max_read;
6101 		entry.io_cnt = io_cnt;
6102 		entry.max_bytes_per_interval = mbpi;
6103 		if (phba->cmf_active_mode == LPFC_CFG_MANAGED)
6104 			entry.timer_utilization = phba->cmf_last_ts;
6105 		else
6106 			entry.timer_utilization = ms;
6107 		entry.timer_interval = ms;
6108 		phba->cmf_last_ts = 0;
6109 
6110 		lpfc_rx_monitor_record(phba->rx_monitor, &entry);
6111 	}
6112 
6113 	if (phba->cmf_active_mode == LPFC_CFG_MONITOR) {
6114 		/* If Monitor mode, check if we are oversubscribed
6115 		 * against the full line rate.
6116 		 */
6117 		if (mbpi && total > mbpi)
6118 			atomic_inc(&phba->cgn_driver_evt_cnt);
6119 	}
6120 	phba->rx_block_cnt += div_u64(rcv, 512);  /* save 512 byte block cnt */
6121 
6122 	/* Since total_bytes has already been zero'ed, its okay to unblock
6123 	 * after max_bytes_per_interval is setup.
6124 	 */
6125 	if (atomic_xchg(&phba->cmf_bw_wait, 0))
6126 		queue_work(phba->wq, &phba->unblock_request_work);
6127 
6128 	/* SCSI IO is now unblocked */
6129 	atomic_set(&phba->cmf_stop_io, 0);
6130 
6131 skip:
6132 	hrtimer_forward_now(timer,
6133 			    ktime_set(0, timer_interval * NSEC_PER_MSEC));
6134 	return HRTIMER_RESTART;
6135 }
6136 
6137 #define trunk_link_status(__idx)\
6138 	bf_get(lpfc_acqe_fc_la_trunk_config_port##__idx, acqe_fc) ?\
6139 	       ((phba->trunk_link.link##__idx.state == LPFC_LINK_UP) ?\
6140 		"Link up" : "Link down") : "NA"
6141 /* Did port __idx reported an error */
6142 #define trunk_port_fault(__idx)\
6143 	bf_get(lpfc_acqe_fc_la_trunk_config_port##__idx, acqe_fc) ?\
6144 	       (port_fault & (1 << __idx) ? "YES" : "NO") : "NA"
6145 
6146 static void
6147 lpfc_update_trunk_link_status(struct lpfc_hba *phba,
6148 			      struct lpfc_acqe_fc_la *acqe_fc)
6149 {
6150 	uint8_t port_fault = bf_get(lpfc_acqe_fc_la_trunk_linkmask, acqe_fc);
6151 	uint8_t err = bf_get(lpfc_acqe_fc_la_trunk_fault, acqe_fc);
6152 	u8 cnt = 0;
6153 
6154 	phba->sli4_hba.link_state.speed =
6155 		lpfc_sli4_port_speed_parse(phba, LPFC_TRAILER_CODE_FC,
6156 				bf_get(lpfc_acqe_fc_la_speed, acqe_fc));
6157 
6158 	phba->sli4_hba.link_state.logical_speed =
6159 				bf_get(lpfc_acqe_fc_la_llink_spd, acqe_fc) * 10;
6160 	/* We got FC link speed, convert to fc_linkspeed (READ_TOPOLOGY) */
6161 	phba->fc_linkspeed =
6162 		 lpfc_async_link_speed_to_read_top(
6163 				phba,
6164 				bf_get(lpfc_acqe_fc_la_speed, acqe_fc));
6165 
6166 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port0, acqe_fc)) {
6167 		phba->trunk_link.link0.state =
6168 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port0, acqe_fc)
6169 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
6170 		phba->trunk_link.link0.fault = port_fault & 0x1 ? err : 0;
6171 		cnt++;
6172 	}
6173 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port1, acqe_fc)) {
6174 		phba->trunk_link.link1.state =
6175 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port1, acqe_fc)
6176 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
6177 		phba->trunk_link.link1.fault = port_fault & 0x2 ? err : 0;
6178 		cnt++;
6179 	}
6180 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port2, acqe_fc)) {
6181 		phba->trunk_link.link2.state =
6182 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port2, acqe_fc)
6183 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
6184 		phba->trunk_link.link2.fault = port_fault & 0x4 ? err : 0;
6185 		cnt++;
6186 	}
6187 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port3, acqe_fc)) {
6188 		phba->trunk_link.link3.state =
6189 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port3, acqe_fc)
6190 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
6191 		phba->trunk_link.link3.fault = port_fault & 0x8 ? err : 0;
6192 		cnt++;
6193 	}
6194 
6195 	if (cnt)
6196 		phba->trunk_link.phy_lnk_speed =
6197 			phba->sli4_hba.link_state.logical_speed / (cnt * 1000);
6198 	else
6199 		phba->trunk_link.phy_lnk_speed = LPFC_LINK_SPEED_UNKNOWN;
6200 
6201 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6202 			"2910 Async FC Trunking Event - Speed:%d\n"
6203 			"\tLogical speed:%d "
6204 			"port0: %s port1: %s port2: %s port3: %s\n",
6205 			phba->sli4_hba.link_state.speed,
6206 			phba->sli4_hba.link_state.logical_speed,
6207 			trunk_link_status(0), trunk_link_status(1),
6208 			trunk_link_status(2), trunk_link_status(3));
6209 
6210 	if (phba->cmf_active_mode != LPFC_CFG_OFF)
6211 		lpfc_cmf_signal_init(phba);
6212 
6213 	if (port_fault)
6214 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6215 				"3202 trunk error:0x%x (%s) seen on port0:%s "
6216 				/*
6217 				 * SLI-4: We have only 0xA error codes
6218 				 * defined as of now. print an appropriate
6219 				 * message in case driver needs to be updated.
6220 				 */
6221 				"port1:%s port2:%s port3:%s\n", err, err > 0xA ?
6222 				"UNDEFINED. update driver." : trunk_errmsg[err],
6223 				trunk_port_fault(0), trunk_port_fault(1),
6224 				trunk_port_fault(2), trunk_port_fault(3));
6225 }
6226 
6227 
6228 /**
6229  * lpfc_sli4_async_fc_evt - Process the asynchronous FC link event
6230  * @phba: pointer to lpfc hba data structure.
6231  * @acqe_fc: pointer to the async fc completion queue entry.
6232  *
6233  * This routine is to handle the SLI4 asynchronous FC event. It will simply log
6234  * that the event was received and then issue a read_topology mailbox command so
6235  * that the rest of the driver will treat it the same as SLI3.
6236  **/
6237 static void
6238 lpfc_sli4_async_fc_evt(struct lpfc_hba *phba, struct lpfc_acqe_fc_la *acqe_fc)
6239 {
6240 	LPFC_MBOXQ_t *pmb;
6241 	MAILBOX_t *mb;
6242 	struct lpfc_mbx_read_top *la;
6243 	char *log_level;
6244 	int rc;
6245 
6246 	if (bf_get(lpfc_trailer_type, acqe_fc) !=
6247 	    LPFC_FC_LA_EVENT_TYPE_FC_LINK) {
6248 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6249 				"2895 Non FC link Event detected.(%d)\n",
6250 				bf_get(lpfc_trailer_type, acqe_fc));
6251 		return;
6252 	}
6253 
6254 	if (bf_get(lpfc_acqe_fc_la_att_type, acqe_fc) ==
6255 	    LPFC_FC_LA_TYPE_TRUNKING_EVENT) {
6256 		lpfc_update_trunk_link_status(phba, acqe_fc);
6257 		return;
6258 	}
6259 
6260 	/* Keep the link status for extra SLI4 state machine reference */
6261 	phba->sli4_hba.link_state.speed =
6262 			lpfc_sli4_port_speed_parse(phba, LPFC_TRAILER_CODE_FC,
6263 				bf_get(lpfc_acqe_fc_la_speed, acqe_fc));
6264 	phba->sli4_hba.link_state.duplex = LPFC_ASYNC_LINK_DUPLEX_FULL;
6265 	phba->sli4_hba.link_state.topology =
6266 				bf_get(lpfc_acqe_fc_la_topology, acqe_fc);
6267 	phba->sli4_hba.link_state.status =
6268 				bf_get(lpfc_acqe_fc_la_att_type, acqe_fc);
6269 	phba->sli4_hba.link_state.type =
6270 				bf_get(lpfc_acqe_fc_la_port_type, acqe_fc);
6271 	phba->sli4_hba.link_state.number =
6272 				bf_get(lpfc_acqe_fc_la_port_number, acqe_fc);
6273 	phba->sli4_hba.link_state.fault =
6274 				bf_get(lpfc_acqe_link_fault, acqe_fc);
6275 	phba->sli4_hba.link_state.link_status =
6276 				bf_get(lpfc_acqe_fc_la_link_status, acqe_fc);
6277 
6278 	/*
6279 	 * Only select attention types need logical speed modification to what
6280 	 * was previously set.
6281 	 */
6282 	if (phba->sli4_hba.link_state.status >= LPFC_FC_LA_TYPE_LINK_UP &&
6283 	    phba->sli4_hba.link_state.status < LPFC_FC_LA_TYPE_ACTIVATE_FAIL) {
6284 		if (bf_get(lpfc_acqe_fc_la_att_type, acqe_fc) ==
6285 		    LPFC_FC_LA_TYPE_LINK_DOWN)
6286 			phba->sli4_hba.link_state.logical_speed = 0;
6287 		else if (!phba->sli4_hba.conf_trunk)
6288 			phba->sli4_hba.link_state.logical_speed =
6289 				bf_get(lpfc_acqe_fc_la_llink_spd, acqe_fc) * 10;
6290 	}
6291 
6292 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6293 			"2896 Async FC event - Speed:%dGBaud Topology:x%x "
6294 			"LA Type:x%x Port Type:%d Port Number:%d Logical speed:"
6295 			"%dMbps Fault:x%x Link Status:x%x\n",
6296 			phba->sli4_hba.link_state.speed,
6297 			phba->sli4_hba.link_state.topology,
6298 			phba->sli4_hba.link_state.status,
6299 			phba->sli4_hba.link_state.type,
6300 			phba->sli4_hba.link_state.number,
6301 			phba->sli4_hba.link_state.logical_speed,
6302 			phba->sli4_hba.link_state.fault,
6303 			phba->sli4_hba.link_state.link_status);
6304 
6305 	/*
6306 	 * The following attention types are informational only, providing
6307 	 * further details about link status.  Overwrite the value of
6308 	 * link_state.status appropriately.  No further action is required.
6309 	 */
6310 	if (phba->sli4_hba.link_state.status >= LPFC_FC_LA_TYPE_ACTIVATE_FAIL) {
6311 		switch (phba->sli4_hba.link_state.status) {
6312 		case LPFC_FC_LA_TYPE_ACTIVATE_FAIL:
6313 			log_level = KERN_WARNING;
6314 			phba->sli4_hba.link_state.status =
6315 					LPFC_FC_LA_TYPE_LINK_DOWN;
6316 			break;
6317 		case LPFC_FC_LA_TYPE_LINK_RESET_PRTCL_EVT:
6318 			/*
6319 			 * During bb credit recovery establishment, receiving
6320 			 * this attention type is normal.  Link Up attention
6321 			 * type is expected to occur before this informational
6322 			 * attention type so keep the Link Up status.
6323 			 */
6324 			log_level = KERN_INFO;
6325 			phba->sli4_hba.link_state.status =
6326 					LPFC_FC_LA_TYPE_LINK_UP;
6327 			break;
6328 		default:
6329 			log_level = KERN_INFO;
6330 			break;
6331 		}
6332 		lpfc_log_msg(phba, log_level, LOG_SLI,
6333 			     "2992 Async FC event - Informational Link "
6334 			     "Attention Type x%x\n",
6335 			     bf_get(lpfc_acqe_fc_la_att_type, acqe_fc));
6336 		return;
6337 	}
6338 
6339 	pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6340 	if (!pmb) {
6341 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6342 				"2897 The mboxq allocation failed\n");
6343 		return;
6344 	}
6345 	rc = lpfc_mbox_rsrc_prep(phba, pmb);
6346 	if (rc) {
6347 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6348 				"2898 The mboxq prep failed\n");
6349 		goto out_free_pmb;
6350 	}
6351 
6352 	/* Cleanup any outstanding ELS commands */
6353 	lpfc_els_flush_all_cmd(phba);
6354 
6355 	/* Block ELS IOCBs until we have done process link event */
6356 	phba->sli4_hba.els_wq->pring->flag |= LPFC_STOP_IOCB_EVENT;
6357 
6358 	/* Update link event statistics */
6359 	phba->sli.slistat.link_event++;
6360 
6361 	/* Create lpfc_handle_latt mailbox command from link ACQE */
6362 	lpfc_read_topology(phba, pmb, pmb->ctx_buf);
6363 	pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
6364 	pmb->vport = phba->pport;
6365 
6366 	if (phba->sli4_hba.link_state.status != LPFC_FC_LA_TYPE_LINK_UP) {
6367 		phba->link_flag &= ~(LS_MDS_LINK_DOWN | LS_MDS_LOOPBACK);
6368 
6369 		switch (phba->sli4_hba.link_state.status) {
6370 		case LPFC_FC_LA_TYPE_MDS_LINK_DOWN:
6371 			phba->link_flag |= LS_MDS_LINK_DOWN;
6372 			break;
6373 		case LPFC_FC_LA_TYPE_MDS_LOOPBACK:
6374 			phba->link_flag |= LS_MDS_LOOPBACK;
6375 			break;
6376 		default:
6377 			break;
6378 		}
6379 
6380 		/* Initialize completion status */
6381 		mb = &pmb->u.mb;
6382 		mb->mbxStatus = MBX_SUCCESS;
6383 
6384 		/* Parse port fault information field */
6385 		lpfc_sli4_parse_latt_fault(phba, (void *)acqe_fc);
6386 
6387 		/* Parse and translate link attention fields */
6388 		la = (struct lpfc_mbx_read_top *)&pmb->u.mb.un.varReadTop;
6389 		la->eventTag = acqe_fc->event_tag;
6390 
6391 		if (phba->sli4_hba.link_state.status ==
6392 		    LPFC_FC_LA_TYPE_UNEXP_WWPN) {
6393 			bf_set(lpfc_mbx_read_top_att_type, la,
6394 			       LPFC_FC_LA_TYPE_UNEXP_WWPN);
6395 		} else {
6396 			bf_set(lpfc_mbx_read_top_att_type, la,
6397 			       LPFC_FC_LA_TYPE_LINK_DOWN);
6398 		}
6399 		/* Invoke the mailbox command callback function */
6400 		lpfc_mbx_cmpl_read_topology(phba, pmb);
6401 
6402 		return;
6403 	}
6404 
6405 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
6406 	if (rc == MBX_NOT_FINISHED)
6407 		goto out_free_pmb;
6408 	return;
6409 
6410 out_free_pmb:
6411 	lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
6412 }
6413 
6414 /**
6415  * lpfc_sli4_async_sli_evt - Process the asynchronous SLI link event
6416  * @phba: pointer to lpfc hba data structure.
6417  * @acqe_sli: pointer to the async SLI completion queue entry.
6418  *
6419  * This routine is to handle the SLI4 asynchronous SLI events.
6420  **/
6421 static void
6422 lpfc_sli4_async_sli_evt(struct lpfc_hba *phba, struct lpfc_acqe_sli *acqe_sli)
6423 {
6424 	char port_name;
6425 	char message[128];
6426 	uint8_t status;
6427 	uint8_t evt_type;
6428 	uint8_t operational = 0;
6429 	struct temp_event temp_event_data;
6430 	struct lpfc_acqe_misconfigured_event *misconfigured;
6431 	struct lpfc_acqe_cgn_signal *cgn_signal;
6432 	struct Scsi_Host  *shost;
6433 	struct lpfc_vport **vports;
6434 	int rc, i, cnt;
6435 
6436 	evt_type = bf_get(lpfc_trailer_type, acqe_sli);
6437 
6438 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6439 			"2901 Async SLI event - Type:%d, Event Data: x%08x "
6440 			"x%08x x%08x x%08x\n", evt_type,
6441 			acqe_sli->event_data1, acqe_sli->event_data2,
6442 			acqe_sli->event_data3, acqe_sli->trailer);
6443 
6444 	port_name = phba->Port[0];
6445 	if (port_name == 0x00)
6446 		port_name = '?'; /* get port name is empty */
6447 
6448 	switch (evt_type) {
6449 	case LPFC_SLI_EVENT_TYPE_OVER_TEMP:
6450 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
6451 		temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
6452 		temp_event_data.data = (uint32_t)acqe_sli->event_data1;
6453 
6454 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6455 				"3190 Over Temperature:%d Celsius- Port Name %c\n",
6456 				acqe_sli->event_data1, port_name);
6457 
6458 		phba->sfp_warning |= LPFC_TRANSGRESSION_HIGH_TEMPERATURE;
6459 		shost = lpfc_shost_from_vport(phba->pport);
6460 		fc_host_post_vendor_event(shost, fc_get_event_number(),
6461 					  sizeof(temp_event_data),
6462 					  (char *)&temp_event_data,
6463 					  SCSI_NL_VID_TYPE_PCI
6464 					  | PCI_VENDOR_ID_EMULEX);
6465 		break;
6466 	case LPFC_SLI_EVENT_TYPE_NORM_TEMP:
6467 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
6468 		temp_event_data.event_code = LPFC_NORMAL_TEMP;
6469 		temp_event_data.data = (uint32_t)acqe_sli->event_data1;
6470 
6471 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI | LOG_LDS_EVENT,
6472 				"3191 Normal Temperature:%d Celsius - Port Name %c\n",
6473 				acqe_sli->event_data1, port_name);
6474 
6475 		shost = lpfc_shost_from_vport(phba->pport);
6476 		fc_host_post_vendor_event(shost, fc_get_event_number(),
6477 					  sizeof(temp_event_data),
6478 					  (char *)&temp_event_data,
6479 					  SCSI_NL_VID_TYPE_PCI
6480 					  | PCI_VENDOR_ID_EMULEX);
6481 		break;
6482 	case LPFC_SLI_EVENT_TYPE_MISCONFIGURED:
6483 		misconfigured = (struct lpfc_acqe_misconfigured_event *)
6484 					&acqe_sli->event_data1;
6485 
6486 		/* fetch the status for this port */
6487 		switch (phba->sli4_hba.lnk_info.lnk_no) {
6488 		case LPFC_LINK_NUMBER_0:
6489 			status = bf_get(lpfc_sli_misconfigured_port0_state,
6490 					&misconfigured->theEvent);
6491 			operational = bf_get(lpfc_sli_misconfigured_port0_op,
6492 					&misconfigured->theEvent);
6493 			break;
6494 		case LPFC_LINK_NUMBER_1:
6495 			status = bf_get(lpfc_sli_misconfigured_port1_state,
6496 					&misconfigured->theEvent);
6497 			operational = bf_get(lpfc_sli_misconfigured_port1_op,
6498 					&misconfigured->theEvent);
6499 			break;
6500 		case LPFC_LINK_NUMBER_2:
6501 			status = bf_get(lpfc_sli_misconfigured_port2_state,
6502 					&misconfigured->theEvent);
6503 			operational = bf_get(lpfc_sli_misconfigured_port2_op,
6504 					&misconfigured->theEvent);
6505 			break;
6506 		case LPFC_LINK_NUMBER_3:
6507 			status = bf_get(lpfc_sli_misconfigured_port3_state,
6508 					&misconfigured->theEvent);
6509 			operational = bf_get(lpfc_sli_misconfigured_port3_op,
6510 					&misconfigured->theEvent);
6511 			break;
6512 		default:
6513 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6514 					"3296 "
6515 					"LPFC_SLI_EVENT_TYPE_MISCONFIGURED "
6516 					"event: Invalid link %d",
6517 					phba->sli4_hba.lnk_info.lnk_no);
6518 			return;
6519 		}
6520 
6521 		/* Skip if optic state unchanged */
6522 		if (phba->sli4_hba.lnk_info.optic_state == status)
6523 			return;
6524 
6525 		switch (status) {
6526 		case LPFC_SLI_EVENT_STATUS_VALID:
6527 			sprintf(message, "Physical Link is functional");
6528 			break;
6529 		case LPFC_SLI_EVENT_STATUS_NOT_PRESENT:
6530 			sprintf(message, "Optics faulted/incorrectly "
6531 				"installed/not installed - Reseat optics, "
6532 				"if issue not resolved, replace.");
6533 			break;
6534 		case LPFC_SLI_EVENT_STATUS_WRONG_TYPE:
6535 			sprintf(message,
6536 				"Optics of two types installed - Remove one "
6537 				"optic or install matching pair of optics.");
6538 			break;
6539 		case LPFC_SLI_EVENT_STATUS_UNSUPPORTED:
6540 			sprintf(message, "Incompatible optics - Replace with "
6541 				"compatible optics for card to function.");
6542 			break;
6543 		case LPFC_SLI_EVENT_STATUS_UNQUALIFIED:
6544 			sprintf(message, "Unqualified optics - Replace with "
6545 				"Avago optics for Warranty and Technical "
6546 				"Support - Link is%s operational",
6547 				(operational) ? " not" : "");
6548 			break;
6549 		case LPFC_SLI_EVENT_STATUS_UNCERTIFIED:
6550 			sprintf(message, "Uncertified optics - Replace with "
6551 				"Avago-certified optics to enable link "
6552 				"operation - Link is%s operational",
6553 				(operational) ? " not" : "");
6554 			break;
6555 		default:
6556 			/* firmware is reporting a status we don't know about */
6557 			sprintf(message, "Unknown event status x%02x", status);
6558 			break;
6559 		}
6560 
6561 		/* Issue READ_CONFIG mbox command to refresh supported speeds */
6562 		rc = lpfc_sli4_read_config(phba);
6563 		if (rc) {
6564 			phba->lmt = 0;
6565 			lpfc_printf_log(phba, KERN_ERR,
6566 					LOG_TRACE_EVENT,
6567 					"3194 Unable to retrieve supported "
6568 					"speeds, rc = 0x%x\n", rc);
6569 		}
6570 		rc = lpfc_sli4_refresh_params(phba);
6571 		if (rc) {
6572 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6573 					"3174 Unable to update pls support, "
6574 					"rc x%x\n", rc);
6575 		}
6576 		vports = lpfc_create_vport_work_array(phba);
6577 		if (vports != NULL) {
6578 			for (i = 0; i <= phba->max_vports && vports[i] != NULL;
6579 					i++) {
6580 				shost = lpfc_shost_from_vport(vports[i]);
6581 				lpfc_host_supported_speeds_set(shost);
6582 			}
6583 		}
6584 		lpfc_destroy_vport_work_array(phba, vports);
6585 
6586 		phba->sli4_hba.lnk_info.optic_state = status;
6587 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6588 				"3176 Port Name %c %s\n", port_name, message);
6589 		break;
6590 	case LPFC_SLI_EVENT_TYPE_REMOTE_DPORT:
6591 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6592 				"3192 Remote DPort Test Initiated - "
6593 				"Event Data1:x%08x Event Data2: x%08x\n",
6594 				acqe_sli->event_data1, acqe_sli->event_data2);
6595 		break;
6596 	case LPFC_SLI_EVENT_TYPE_PORT_PARAMS_CHG:
6597 		/* Call FW to obtain active parms */
6598 		lpfc_sli4_cgn_parm_chg_evt(phba);
6599 		break;
6600 	case LPFC_SLI_EVENT_TYPE_MISCONF_FAWWN:
6601 		/* Misconfigured WWN. Reports that the SLI Port is configured
6602 		 * to use FA-WWN, but the attached device doesn’t support it.
6603 		 * Event Data1 - N.A, Event Data2 - N.A
6604 		 * This event only happens on the physical port.
6605 		 */
6606 		lpfc_log_msg(phba, KERN_WARNING, LOG_SLI | LOG_DISCOVERY,
6607 			     "2699 Misconfigured FA-PWWN - Attached device "
6608 			     "does not support FA-PWWN\n");
6609 		phba->sli4_hba.fawwpn_flag &= ~LPFC_FAWWPN_FABRIC;
6610 		memset(phba->pport->fc_portname.u.wwn, 0,
6611 		       sizeof(struct lpfc_name));
6612 		break;
6613 	case LPFC_SLI_EVENT_TYPE_EEPROM_FAILURE:
6614 		/* EEPROM failure. No driver action is required */
6615 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6616 			     "2518 EEPROM failure - "
6617 			     "Event Data1: x%08x Event Data2: x%08x\n",
6618 			     acqe_sli->event_data1, acqe_sli->event_data2);
6619 		break;
6620 	case LPFC_SLI_EVENT_TYPE_CGN_SIGNAL:
6621 		if (phba->cmf_active_mode == LPFC_CFG_OFF)
6622 			break;
6623 		cgn_signal = (struct lpfc_acqe_cgn_signal *)
6624 					&acqe_sli->event_data1;
6625 		phba->cgn_acqe_cnt++;
6626 
6627 		cnt = bf_get(lpfc_warn_acqe, cgn_signal);
6628 		atomic64_add(cnt, &phba->cgn_acqe_stat.warn);
6629 		atomic64_add(cgn_signal->alarm_cnt, &phba->cgn_acqe_stat.alarm);
6630 
6631 		/* no threshold for CMF, even 1 signal will trigger an event */
6632 
6633 		/* Alarm overrides warning, so check that first */
6634 		if (cgn_signal->alarm_cnt) {
6635 			if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
6636 				/* Keep track of alarm cnt for CMF_SYNC_WQE */
6637 				atomic_add(cgn_signal->alarm_cnt,
6638 					   &phba->cgn_sync_alarm_cnt);
6639 			}
6640 		} else if (cnt) {
6641 			/* signal action needs to be taken */
6642 			if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY ||
6643 			    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
6644 				/* Keep track of warning cnt for CMF_SYNC_WQE */
6645 				atomic_add(cnt, &phba->cgn_sync_warn_cnt);
6646 			}
6647 		}
6648 		break;
6649 	case LPFC_SLI_EVENT_TYPE_RD_SIGNAL:
6650 		/* May be accompanied by a temperature event */
6651 		lpfc_printf_log(phba, KERN_INFO,
6652 				LOG_SLI | LOG_LINK_EVENT | LOG_LDS_EVENT,
6653 				"2902 Remote Degrade Signaling: x%08x x%08x "
6654 				"x%08x\n",
6655 				acqe_sli->event_data1, acqe_sli->event_data2,
6656 				acqe_sli->event_data3);
6657 		break;
6658 	case LPFC_SLI_EVENT_TYPE_RESET_CM_STATS:
6659 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
6660 				"2905 Reset CM statistics\n");
6661 		lpfc_sli4_async_cmstat_evt(phba);
6662 		break;
6663 	default:
6664 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6665 				"3193 Unrecognized SLI event, type: 0x%x",
6666 				evt_type);
6667 		break;
6668 	}
6669 }
6670 
6671 /**
6672  * lpfc_sli4_perform_vport_cvl - Perform clear virtual link on a vport
6673  * @vport: pointer to vport data structure.
6674  *
6675  * This routine is to perform Clear Virtual Link (CVL) on a vport in
6676  * response to a CVL event.
6677  *
6678  * Return the pointer to the ndlp with the vport if successful, otherwise
6679  * return NULL.
6680  **/
6681 static struct lpfc_nodelist *
6682 lpfc_sli4_perform_vport_cvl(struct lpfc_vport *vport)
6683 {
6684 	struct lpfc_nodelist *ndlp;
6685 	struct Scsi_Host *shost;
6686 	struct lpfc_hba *phba;
6687 
6688 	if (!vport)
6689 		return NULL;
6690 	phba = vport->phba;
6691 	if (!phba)
6692 		return NULL;
6693 	ndlp = lpfc_findnode_did(vport, Fabric_DID);
6694 	if (!ndlp) {
6695 		/* Cannot find existing Fabric ndlp, so allocate a new one */
6696 		ndlp = lpfc_nlp_init(vport, Fabric_DID);
6697 		if (!ndlp)
6698 			return NULL;
6699 		/* Set the node type */
6700 		ndlp->nlp_type |= NLP_FABRIC;
6701 		/* Put ndlp onto node list */
6702 		lpfc_enqueue_node(vport, ndlp);
6703 	}
6704 	if ((phba->pport->port_state < LPFC_FLOGI) &&
6705 		(phba->pport->port_state != LPFC_VPORT_FAILED))
6706 		return NULL;
6707 	/* If virtual link is not yet instantiated ignore CVL */
6708 	if ((vport != phba->pport) && (vport->port_state < LPFC_FDISC)
6709 		&& (vport->port_state != LPFC_VPORT_FAILED))
6710 		return NULL;
6711 	shost = lpfc_shost_from_vport(vport);
6712 	if (!shost)
6713 		return NULL;
6714 	lpfc_linkdown_port(vport);
6715 	lpfc_cleanup_pending_mbox(vport);
6716 	set_bit(FC_VPORT_CVL_RCVD, &vport->fc_flag);
6717 
6718 	return ndlp;
6719 }
6720 
6721 /**
6722  * lpfc_sli4_perform_all_vport_cvl - Perform clear virtual link on all vports
6723  * @phba: pointer to lpfc hba data structure.
6724  *
6725  * This routine is to perform Clear Virtual Link (CVL) on all vports in
6726  * response to a FCF dead event.
6727  **/
6728 static void
6729 lpfc_sli4_perform_all_vport_cvl(struct lpfc_hba *phba)
6730 {
6731 	struct lpfc_vport **vports;
6732 	int i;
6733 
6734 	vports = lpfc_create_vport_work_array(phba);
6735 	if (vports)
6736 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++)
6737 			lpfc_sli4_perform_vport_cvl(vports[i]);
6738 	lpfc_destroy_vport_work_array(phba, vports);
6739 }
6740 
6741 /**
6742  * lpfc_sli4_async_fip_evt - Process the asynchronous FCoE FIP event
6743  * @phba: pointer to lpfc hba data structure.
6744  * @acqe_fip: pointer to the async fcoe completion queue entry.
6745  *
6746  * This routine is to handle the SLI4 asynchronous fcoe event.
6747  **/
6748 static void
6749 lpfc_sli4_async_fip_evt(struct lpfc_hba *phba,
6750 			struct lpfc_acqe_fip *acqe_fip)
6751 {
6752 	uint8_t event_type = bf_get(lpfc_trailer_type, acqe_fip);
6753 	int rc;
6754 	struct lpfc_vport *vport;
6755 	struct lpfc_nodelist *ndlp;
6756 	int active_vlink_present;
6757 	struct lpfc_vport **vports;
6758 	int i;
6759 
6760 	phba->fc_eventTag = acqe_fip->event_tag;
6761 	phba->fcoe_eventtag = acqe_fip->event_tag;
6762 	switch (event_type) {
6763 	case LPFC_FIP_EVENT_TYPE_NEW_FCF:
6764 	case LPFC_FIP_EVENT_TYPE_FCF_PARAM_MOD:
6765 		if (event_type == LPFC_FIP_EVENT_TYPE_NEW_FCF)
6766 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6767 					"2546 New FCF event, evt_tag:x%x, "
6768 					"index:x%x\n",
6769 					acqe_fip->event_tag,
6770 					acqe_fip->index);
6771 		else
6772 			lpfc_printf_log(phba, KERN_WARNING, LOG_FIP |
6773 					LOG_DISCOVERY,
6774 					"2788 FCF param modified event, "
6775 					"evt_tag:x%x, index:x%x\n",
6776 					acqe_fip->event_tag,
6777 					acqe_fip->index);
6778 		if (phba->fcf.fcf_flag & FCF_DISCOVERY) {
6779 			/*
6780 			 * During period of FCF discovery, read the FCF
6781 			 * table record indexed by the event to update
6782 			 * FCF roundrobin failover eligible FCF bmask.
6783 			 */
6784 			lpfc_printf_log(phba, KERN_INFO, LOG_FIP |
6785 					LOG_DISCOVERY,
6786 					"2779 Read FCF (x%x) for updating "
6787 					"roundrobin FCF failover bmask\n",
6788 					acqe_fip->index);
6789 			rc = lpfc_sli4_read_fcf_rec(phba, acqe_fip->index);
6790 		}
6791 
6792 		/* If the FCF discovery is in progress, do nothing. */
6793 		if (test_bit(FCF_TS_INPROG, &phba->hba_flag))
6794 			break;
6795 		spin_lock_irq(&phba->hbalock);
6796 		/* If fast FCF failover rescan event is pending, do nothing */
6797 		if (phba->fcf.fcf_flag & (FCF_REDISC_EVT | FCF_REDISC_PEND)) {
6798 			spin_unlock_irq(&phba->hbalock);
6799 			break;
6800 		}
6801 
6802 		/* If the FCF has been in discovered state, do nothing. */
6803 		if (phba->fcf.fcf_flag & FCF_SCAN_DONE) {
6804 			spin_unlock_irq(&phba->hbalock);
6805 			break;
6806 		}
6807 		spin_unlock_irq(&phba->hbalock);
6808 
6809 		/* Otherwise, scan the entire FCF table and re-discover SAN */
6810 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
6811 				"2770 Start FCF table scan per async FCF "
6812 				"event, evt_tag:x%x, index:x%x\n",
6813 				acqe_fip->event_tag, acqe_fip->index);
6814 		rc = lpfc_sli4_fcf_scan_read_fcf_rec(phba,
6815 						     LPFC_FCOE_FCF_GET_FIRST);
6816 		if (rc)
6817 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6818 					"2547 Issue FCF scan read FCF mailbox "
6819 					"command failed (x%x)\n", rc);
6820 		break;
6821 
6822 	case LPFC_FIP_EVENT_TYPE_FCF_TABLE_FULL:
6823 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6824 				"2548 FCF Table full count 0x%x tag 0x%x\n",
6825 				bf_get(lpfc_acqe_fip_fcf_count, acqe_fip),
6826 				acqe_fip->event_tag);
6827 		break;
6828 
6829 	case LPFC_FIP_EVENT_TYPE_FCF_DEAD:
6830 		phba->fcoe_cvl_eventtag = acqe_fip->event_tag;
6831 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6832 				"2549 FCF (x%x) disconnected from network, "
6833 				 "tag:x%x\n", acqe_fip->index,
6834 				 acqe_fip->event_tag);
6835 		/*
6836 		 * If we are in the middle of FCF failover process, clear
6837 		 * the corresponding FCF bit in the roundrobin bitmap.
6838 		 */
6839 		spin_lock_irq(&phba->hbalock);
6840 		if ((phba->fcf.fcf_flag & FCF_DISCOVERY) &&
6841 		    (phba->fcf.current_rec.fcf_indx != acqe_fip->index)) {
6842 			spin_unlock_irq(&phba->hbalock);
6843 			/* Update FLOGI FCF failover eligible FCF bmask */
6844 			lpfc_sli4_fcf_rr_index_clear(phba, acqe_fip->index);
6845 			break;
6846 		}
6847 		spin_unlock_irq(&phba->hbalock);
6848 
6849 		/* If the event is not for currently used fcf do nothing */
6850 		if (phba->fcf.current_rec.fcf_indx != acqe_fip->index)
6851 			break;
6852 
6853 		/*
6854 		 * Otherwise, request the port to rediscover the entire FCF
6855 		 * table for a fast recovery from case that the current FCF
6856 		 * is no longer valid as we are not in the middle of FCF
6857 		 * failover process already.
6858 		 */
6859 		spin_lock_irq(&phba->hbalock);
6860 		/* Mark the fast failover process in progress */
6861 		phba->fcf.fcf_flag |= FCF_DEAD_DISC;
6862 		spin_unlock_irq(&phba->hbalock);
6863 
6864 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
6865 				"2771 Start FCF fast failover process due to "
6866 				"FCF DEAD event: evt_tag:x%x, fcf_index:x%x "
6867 				"\n", acqe_fip->event_tag, acqe_fip->index);
6868 		rc = lpfc_sli4_redisc_fcf_table(phba);
6869 		if (rc) {
6870 			lpfc_printf_log(phba, KERN_ERR, LOG_FIP |
6871 					LOG_TRACE_EVENT,
6872 					"2772 Issue FCF rediscover mailbox "
6873 					"command failed, fail through to FCF "
6874 					"dead event\n");
6875 			spin_lock_irq(&phba->hbalock);
6876 			phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
6877 			spin_unlock_irq(&phba->hbalock);
6878 			/*
6879 			 * Last resort will fail over by treating this
6880 			 * as a link down to FCF registration.
6881 			 */
6882 			lpfc_sli4_fcf_dead_failthrough(phba);
6883 		} else {
6884 			/* Reset FCF roundrobin bmask for new discovery */
6885 			lpfc_sli4_clear_fcf_rr_bmask(phba);
6886 			/*
6887 			 * Handling fast FCF failover to a DEAD FCF event is
6888 			 * considered equalivant to receiving CVL to all vports.
6889 			 */
6890 			lpfc_sli4_perform_all_vport_cvl(phba);
6891 		}
6892 		break;
6893 	case LPFC_FIP_EVENT_TYPE_CVL:
6894 		phba->fcoe_cvl_eventtag = acqe_fip->event_tag;
6895 		lpfc_printf_log(phba, KERN_ERR,
6896 				LOG_TRACE_EVENT,
6897 			"2718 Clear Virtual Link Received for VPI 0x%x"
6898 			" tag 0x%x\n", acqe_fip->index, acqe_fip->event_tag);
6899 
6900 		vport = lpfc_find_vport_by_vpid(phba,
6901 						acqe_fip->index);
6902 		ndlp = lpfc_sli4_perform_vport_cvl(vport);
6903 		if (!ndlp)
6904 			break;
6905 		active_vlink_present = 0;
6906 
6907 		vports = lpfc_create_vport_work_array(phba);
6908 		if (vports) {
6909 			for (i = 0; i <= phba->max_vports && vports[i] != NULL;
6910 					i++) {
6911 				if (!test_bit(FC_VPORT_CVL_RCVD,
6912 					      &vports[i]->fc_flag) &&
6913 				    vports[i]->port_state > LPFC_FDISC) {
6914 					active_vlink_present = 1;
6915 					break;
6916 				}
6917 			}
6918 			lpfc_destroy_vport_work_array(phba, vports);
6919 		}
6920 
6921 		/*
6922 		 * Don't re-instantiate if vport is marked for deletion.
6923 		 * If we are here first then vport_delete is going to wait
6924 		 * for discovery to complete.
6925 		 */
6926 		if (!test_bit(FC_UNLOADING, &vport->load_flag) &&
6927 		    active_vlink_present) {
6928 			/*
6929 			 * If there are other active VLinks present,
6930 			 * re-instantiate the Vlink using FDISC.
6931 			 */
6932 			mod_timer(&ndlp->nlp_delayfunc,
6933 				  jiffies + secs_to_jiffies(1));
6934 			set_bit(NLP_DELAY_TMO, &ndlp->nlp_flag);
6935 			ndlp->nlp_last_elscmd = ELS_CMD_FDISC;
6936 			vport->port_state = LPFC_FDISC;
6937 		} else {
6938 			/*
6939 			 * Otherwise, we request port to rediscover
6940 			 * the entire FCF table for a fast recovery
6941 			 * from possible case that the current FCF
6942 			 * is no longer valid if we are not already
6943 			 * in the FCF failover process.
6944 			 */
6945 			spin_lock_irq(&phba->hbalock);
6946 			if (phba->fcf.fcf_flag & FCF_DISCOVERY) {
6947 				spin_unlock_irq(&phba->hbalock);
6948 				break;
6949 			}
6950 			/* Mark the fast failover process in progress */
6951 			phba->fcf.fcf_flag |= FCF_ACVL_DISC;
6952 			spin_unlock_irq(&phba->hbalock);
6953 			lpfc_printf_log(phba, KERN_INFO, LOG_FIP |
6954 					LOG_DISCOVERY,
6955 					"2773 Start FCF failover per CVL, "
6956 					"evt_tag:x%x\n", acqe_fip->event_tag);
6957 			rc = lpfc_sli4_redisc_fcf_table(phba);
6958 			if (rc) {
6959 				lpfc_printf_log(phba, KERN_ERR, LOG_FIP |
6960 						LOG_TRACE_EVENT,
6961 						"2774 Issue FCF rediscover "
6962 						"mailbox command failed, "
6963 						"through to CVL event\n");
6964 				spin_lock_irq(&phba->hbalock);
6965 				phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
6966 				spin_unlock_irq(&phba->hbalock);
6967 				/*
6968 				 * Last resort will be re-try on the
6969 				 * the current registered FCF entry.
6970 				 */
6971 				lpfc_retry_pport_discovery(phba);
6972 			} else
6973 				/*
6974 				 * Reset FCF roundrobin bmask for new
6975 				 * discovery.
6976 				 */
6977 				lpfc_sli4_clear_fcf_rr_bmask(phba);
6978 		}
6979 		break;
6980 	default:
6981 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6982 				"0288 Unknown FCoE event type 0x%x event tag "
6983 				"0x%x\n", event_type, acqe_fip->event_tag);
6984 		break;
6985 	}
6986 }
6987 
6988 /**
6989  * lpfc_sli4_async_dcbx_evt - Process the asynchronous dcbx event
6990  * @phba: pointer to lpfc hba data structure.
6991  * @acqe_dcbx: pointer to the async dcbx completion queue entry.
6992  *
6993  * This routine is to handle the SLI4 asynchronous dcbx event.
6994  **/
6995 static void
6996 lpfc_sli4_async_dcbx_evt(struct lpfc_hba *phba,
6997 			 struct lpfc_acqe_dcbx *acqe_dcbx)
6998 {
6999 	phba->fc_eventTag = acqe_dcbx->event_tag;
7000 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7001 			"0290 The SLI4 DCBX asynchronous event is not "
7002 			"handled yet\n");
7003 }
7004 
7005 /**
7006  * lpfc_sli4_async_grp5_evt - Process the asynchronous group5 event
7007  * @phba: pointer to lpfc hba data structure.
7008  * @acqe_grp5: pointer to the async grp5 completion queue entry.
7009  *
7010  * This routine is to handle the SLI4 asynchronous grp5 event. A grp5 event
7011  * is an asynchronous notified of a logical link speed change.  The Port
7012  * reports the logical link speed in units of 10Mbps.
7013  **/
7014 static void
7015 lpfc_sli4_async_grp5_evt(struct lpfc_hba *phba,
7016 			 struct lpfc_acqe_grp5 *acqe_grp5)
7017 {
7018 	uint16_t prev_ll_spd;
7019 
7020 	phba->fc_eventTag = acqe_grp5->event_tag;
7021 	phba->fcoe_eventtag = acqe_grp5->event_tag;
7022 	prev_ll_spd = phba->sli4_hba.link_state.logical_speed;
7023 	phba->sli4_hba.link_state.logical_speed =
7024 		(bf_get(lpfc_acqe_grp5_llink_spd, acqe_grp5)) * 10;
7025 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
7026 			"2789 GRP5 Async Event: Updating logical link speed "
7027 			"from %dMbps to %dMbps\n", prev_ll_spd,
7028 			phba->sli4_hba.link_state.logical_speed);
7029 }
7030 
7031 /**
7032  * lpfc_sli4_async_cmstat_evt - Process the asynchronous cmstat event
7033  * @phba: pointer to lpfc hba data structure.
7034  *
7035  * This routine is to handle the SLI4 asynchronous cmstat event. A cmstat event
7036  * is an asynchronous notification of a request to reset CM stats.
7037  **/
7038 static void
7039 lpfc_sli4_async_cmstat_evt(struct lpfc_hba *phba)
7040 {
7041 	if (!phba->cgn_i)
7042 		return;
7043 	lpfc_init_congestion_stat(phba);
7044 }
7045 
7046 /**
7047  * lpfc_cgn_params_val - Validate FW congestion parameters.
7048  * @phba: pointer to lpfc hba data structure.
7049  * @p_cfg_param: pointer to FW provided congestion parameters.
7050  *
7051  * This routine validates the congestion parameters passed
7052  * by the FW to the driver via an ACQE event.
7053  **/
7054 static void
7055 lpfc_cgn_params_val(struct lpfc_hba *phba, struct lpfc_cgn_param *p_cfg_param)
7056 {
7057 	spin_lock_irq(&phba->hbalock);
7058 
7059 	if (!lpfc_rangecheck(p_cfg_param->cgn_param_mode, LPFC_CFG_OFF,
7060 			     LPFC_CFG_MONITOR)) {
7061 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT,
7062 				"6225 CMF mode param out of range: %d\n",
7063 				 p_cfg_param->cgn_param_mode);
7064 		p_cfg_param->cgn_param_mode = LPFC_CFG_OFF;
7065 	}
7066 
7067 	spin_unlock_irq(&phba->hbalock);
7068 }
7069 
7070 static const char * const lpfc_cmf_mode_to_str[] = {
7071 	"OFF",
7072 	"MANAGED",
7073 	"MONITOR",
7074 };
7075 
7076 /**
7077  * lpfc_cgn_params_parse - Process a FW cong parm change event
7078  * @phba: pointer to lpfc hba data structure.
7079  * @p_cgn_param: pointer to a data buffer with the FW cong params.
7080  * @len: the size of pdata in bytes.
7081  *
7082  * This routine validates the congestion management buffer signature
7083  * from the FW, validates the contents and makes corrections for
7084  * valid, in-range values.  If the signature magic is correct and
7085  * after parameter validation, the contents are copied to the driver's
7086  * @phba structure. If the magic is incorrect, an error message is
7087  * logged.
7088  **/
7089 static void
7090 lpfc_cgn_params_parse(struct lpfc_hba *phba,
7091 		      struct lpfc_cgn_param *p_cgn_param, uint32_t len)
7092 {
7093 	struct lpfc_cgn_info *cp;
7094 	uint32_t crc, oldmode;
7095 	char acr_string[4] = {0};
7096 
7097 	/* Make sure the FW has encoded the correct magic number to
7098 	 * validate the congestion parameter in FW memory.
7099 	 */
7100 	if (p_cgn_param->cgn_param_magic == LPFC_CFG_PARAM_MAGIC_NUM) {
7101 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT | LOG_INIT,
7102 				"4668 FW cgn parm buffer data: "
7103 				"magic 0x%x version %d mode %d "
7104 				"level0 %d level1 %d "
7105 				"level2 %d byte13 %d "
7106 				"byte14 %d byte15 %d "
7107 				"byte11 %d byte12 %d activeMode %d\n",
7108 				p_cgn_param->cgn_param_magic,
7109 				p_cgn_param->cgn_param_version,
7110 				p_cgn_param->cgn_param_mode,
7111 				p_cgn_param->cgn_param_level0,
7112 				p_cgn_param->cgn_param_level1,
7113 				p_cgn_param->cgn_param_level2,
7114 				p_cgn_param->byte13,
7115 				p_cgn_param->byte14,
7116 				p_cgn_param->byte15,
7117 				p_cgn_param->byte11,
7118 				p_cgn_param->byte12,
7119 				phba->cmf_active_mode);
7120 
7121 		oldmode = phba->cmf_active_mode;
7122 
7123 		/* Any parameters out of range are corrected to defaults
7124 		 * by this routine.  No need to fail.
7125 		 */
7126 		lpfc_cgn_params_val(phba, p_cgn_param);
7127 
7128 		/* Parameters are verified, move them into driver storage */
7129 		spin_lock_irq(&phba->hbalock);
7130 		memcpy(&phba->cgn_p, p_cgn_param,
7131 		       sizeof(struct lpfc_cgn_param));
7132 
7133 		/* Update parameters in congestion info buffer now */
7134 		if (phba->cgn_i) {
7135 			cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
7136 			cp->cgn_info_mode = phba->cgn_p.cgn_param_mode;
7137 			cp->cgn_info_level0 = phba->cgn_p.cgn_param_level0;
7138 			cp->cgn_info_level1 = phba->cgn_p.cgn_param_level1;
7139 			cp->cgn_info_level2 = phba->cgn_p.cgn_param_level2;
7140 			crc = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ,
7141 						  LPFC_CGN_CRC32_SEED);
7142 			cp->cgn_info_crc = cpu_to_le32(crc);
7143 		}
7144 		spin_unlock_irq(&phba->hbalock);
7145 
7146 		phba->cmf_active_mode = phba->cgn_p.cgn_param_mode;
7147 
7148 		switch (oldmode) {
7149 		case LPFC_CFG_OFF:
7150 			if (phba->cgn_p.cgn_param_mode != LPFC_CFG_OFF) {
7151 				/* Turning CMF on */
7152 				lpfc_cmf_start(phba);
7153 
7154 				if (phba->link_state >= LPFC_LINK_UP) {
7155 					phba->cgn_reg_fpin =
7156 						phba->cgn_init_reg_fpin;
7157 					phba->cgn_reg_signal =
7158 						phba->cgn_init_reg_signal;
7159 					lpfc_issue_els_edc(phba->pport, 0);
7160 				}
7161 			}
7162 			break;
7163 		case LPFC_CFG_MANAGED:
7164 			switch (phba->cgn_p.cgn_param_mode) {
7165 			case LPFC_CFG_OFF:
7166 				/* Turning CMF off */
7167 				lpfc_cmf_stop(phba);
7168 				if (phba->link_state >= LPFC_LINK_UP)
7169 					lpfc_issue_els_edc(phba->pport, 0);
7170 				break;
7171 			case LPFC_CFG_MONITOR:
7172 				phba->cmf_max_bytes_per_interval =
7173 					phba->cmf_link_byte_count;
7174 
7175 				/* Resume blocked IO - unblock on workqueue */
7176 				queue_work(phba->wq,
7177 					   &phba->unblock_request_work);
7178 				break;
7179 			}
7180 			break;
7181 		case LPFC_CFG_MONITOR:
7182 			switch (phba->cgn_p.cgn_param_mode) {
7183 			case LPFC_CFG_OFF:
7184 				/* Turning CMF off */
7185 				lpfc_cmf_stop(phba);
7186 				if (phba->link_state >= LPFC_LINK_UP)
7187 					lpfc_issue_els_edc(phba->pport, 0);
7188 				break;
7189 			case LPFC_CFG_MANAGED:
7190 				lpfc_cmf_signal_init(phba);
7191 				break;
7192 			}
7193 			break;
7194 		}
7195 		if (oldmode != LPFC_CFG_OFF ||
7196 		    oldmode != phba->cgn_p.cgn_param_mode) {
7197 			if (phba->cgn_p.cgn_param_mode == LPFC_CFG_MANAGED)
7198 				scnprintf(acr_string, sizeof(acr_string), "%u",
7199 					  phba->cgn_p.cgn_param_level0);
7200 			else
7201 				scnprintf(acr_string, sizeof(acr_string), "NA");
7202 
7203 			dev_info(&phba->pcidev->dev, "%d: "
7204 				 "4663 CMF: Mode %s acr %s\n",
7205 				 phba->brd_no,
7206 				 lpfc_cmf_mode_to_str
7207 				 [phba->cgn_p.cgn_param_mode],
7208 				 acr_string);
7209 		}
7210 	} else {
7211 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7212 				"4669 FW cgn parm buf wrong magic 0x%x "
7213 				"version %d\n", p_cgn_param->cgn_param_magic,
7214 				p_cgn_param->cgn_param_version);
7215 	}
7216 }
7217 
7218 /**
7219  * lpfc_sli4_cgn_params_read - Read and Validate FW congestion parameters.
7220  * @phba: pointer to lpfc hba data structure.
7221  *
7222  * This routine issues a read_object mailbox command to
7223  * get the congestion management parameters from the FW
7224  * parses it and updates the driver maintained values.
7225  *
7226  * Returns
7227  *  0     if the object was empty
7228  *  -Eval if an error was encountered
7229  *  Count if bytes were read from object
7230  **/
7231 int
7232 lpfc_sli4_cgn_params_read(struct lpfc_hba *phba)
7233 {
7234 	int ret = 0;
7235 	struct lpfc_cgn_param *p_cgn_param = NULL;
7236 	u32 *pdata = NULL;
7237 	u32 len = 0;
7238 
7239 	/* Find out if the FW has a new set of congestion parameters. */
7240 	len = sizeof(struct lpfc_cgn_param);
7241 	pdata = kzalloc(len, GFP_KERNEL);
7242 	if (!pdata)
7243 		return -ENOMEM;
7244 	ret = lpfc_read_object(phba, (char *)LPFC_PORT_CFG_NAME,
7245 			       pdata, len);
7246 
7247 	/* 0 means no data.  A negative means error.  A positive means
7248 	 * bytes were copied.
7249 	 */
7250 	if (!ret) {
7251 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7252 				"4670 CGN RD OBJ returns no data\n");
7253 		goto rd_obj_err;
7254 	} else if (ret < 0) {
7255 		/* Some error.  Just exit and return it to the caller.*/
7256 		goto rd_obj_err;
7257 	}
7258 
7259 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT | LOG_INIT,
7260 			"6234 READ CGN PARAMS Successful %d\n", len);
7261 
7262 	/* Parse data pointer over len and update the phba congestion
7263 	 * parameters with values passed back.  The receive rate values
7264 	 * may have been altered in FW, but take no action here.
7265 	 */
7266 	p_cgn_param = (struct lpfc_cgn_param *)pdata;
7267 	lpfc_cgn_params_parse(phba, p_cgn_param, len);
7268 
7269  rd_obj_err:
7270 	kfree(pdata);
7271 	return ret;
7272 }
7273 
7274 /**
7275  * lpfc_sli4_cgn_parm_chg_evt - Process a FW congestion param change event
7276  * @phba: pointer to lpfc hba data structure.
7277  *
7278  * The FW generated Async ACQE SLI event calls this routine when
7279  * the event type is an SLI Internal Port Event and the Event Code
7280  * indicates a change to the FW maintained congestion parameters.
7281  *
7282  * This routine executes a Read_Object mailbox call to obtain the
7283  * current congestion parameters maintained in FW and corrects
7284  * the driver's active congestion parameters.
7285  *
7286  * The acqe event is not passed because there is no further data
7287  * required.
7288  *
7289  * Returns nonzero error if event processing encountered an error.
7290  * Zero otherwise for success.
7291  **/
7292 static int
7293 lpfc_sli4_cgn_parm_chg_evt(struct lpfc_hba *phba)
7294 {
7295 	int ret = 0;
7296 
7297 	if (!phba->sli4_hba.pc_sli4_params.cmf) {
7298 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7299 				"4664 Cgn Evt when E2E off. Drop event\n");
7300 		return -EACCES;
7301 	}
7302 
7303 	/* If the event is claiming an empty object, it's ok.  A write
7304 	 * could have cleared it.  Only error is a negative return
7305 	 * status.
7306 	 */
7307 	ret = lpfc_sli4_cgn_params_read(phba);
7308 	if (ret < 0) {
7309 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7310 				"4667 Error reading Cgn Params (%d)\n",
7311 				ret);
7312 	} else if (!ret) {
7313 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7314 				"4673 CGN Event empty object.\n");
7315 	}
7316 	return ret;
7317 }
7318 
7319 /**
7320  * lpfc_sli4_async_event_proc - Process all the pending asynchronous event
7321  * @phba: pointer to lpfc hba data structure.
7322  *
7323  * This routine is invoked by the worker thread to process all the pending
7324  * SLI4 asynchronous events.
7325  **/
7326 void lpfc_sli4_async_event_proc(struct lpfc_hba *phba)
7327 {
7328 	struct lpfc_cq_event *cq_event;
7329 	unsigned long iflags;
7330 
7331 	/* First, declare the async event has been handled */
7332 	clear_bit(ASYNC_EVENT, &phba->hba_flag);
7333 
7334 	/* Now, handle all the async events */
7335 	spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
7336 	while (!list_empty(&phba->sli4_hba.sp_asynce_work_queue)) {
7337 		list_remove_head(&phba->sli4_hba.sp_asynce_work_queue,
7338 				 cq_event, struct lpfc_cq_event, list);
7339 		spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock,
7340 				       iflags);
7341 
7342 		/* Process the asynchronous event */
7343 		switch (bf_get(lpfc_trailer_code, &cq_event->cqe.mcqe_cmpl)) {
7344 		case LPFC_TRAILER_CODE_LINK:
7345 			lpfc_sli4_async_link_evt(phba,
7346 						 &cq_event->cqe.acqe_link);
7347 			break;
7348 		case LPFC_TRAILER_CODE_FCOE:
7349 			lpfc_sli4_async_fip_evt(phba, &cq_event->cqe.acqe_fip);
7350 			break;
7351 		case LPFC_TRAILER_CODE_DCBX:
7352 			lpfc_sli4_async_dcbx_evt(phba,
7353 						 &cq_event->cqe.acqe_dcbx);
7354 			break;
7355 		case LPFC_TRAILER_CODE_GRP5:
7356 			lpfc_sli4_async_grp5_evt(phba,
7357 						 &cq_event->cqe.acqe_grp5);
7358 			break;
7359 		case LPFC_TRAILER_CODE_FC:
7360 			lpfc_sli4_async_fc_evt(phba, &cq_event->cqe.acqe_fc);
7361 			break;
7362 		case LPFC_TRAILER_CODE_SLI:
7363 			lpfc_sli4_async_sli_evt(phba, &cq_event->cqe.acqe_sli);
7364 			break;
7365 		default:
7366 			lpfc_printf_log(phba, KERN_ERR,
7367 					LOG_TRACE_EVENT,
7368 					"1804 Invalid asynchronous event code: "
7369 					"x%x\n", bf_get(lpfc_trailer_code,
7370 					&cq_event->cqe.mcqe_cmpl));
7371 			break;
7372 		}
7373 
7374 		/* Free the completion event processed to the free pool */
7375 		lpfc_sli4_cq_event_release(phba, cq_event);
7376 		spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
7377 	}
7378 	spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock, iflags);
7379 }
7380 
7381 /**
7382  * lpfc_sli4_fcf_redisc_event_proc - Process fcf table rediscovery event
7383  * @phba: pointer to lpfc hba data structure.
7384  *
7385  * This routine is invoked by the worker thread to process FCF table
7386  * rediscovery pending completion event.
7387  **/
7388 void lpfc_sli4_fcf_redisc_event_proc(struct lpfc_hba *phba)
7389 {
7390 	int rc;
7391 
7392 	spin_lock_irq(&phba->hbalock);
7393 	/* Clear FCF rediscovery timeout event */
7394 	phba->fcf.fcf_flag &= ~FCF_REDISC_EVT;
7395 	/* Clear driver fast failover FCF record flag */
7396 	phba->fcf.failover_rec.flag = 0;
7397 	/* Set state for FCF fast failover */
7398 	phba->fcf.fcf_flag |= FCF_REDISC_FOV;
7399 	spin_unlock_irq(&phba->hbalock);
7400 
7401 	/* Scan FCF table from the first entry to re-discover SAN */
7402 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
7403 			"2777 Start post-quiescent FCF table scan\n");
7404 	rc = lpfc_sli4_fcf_scan_read_fcf_rec(phba, LPFC_FCOE_FCF_GET_FIRST);
7405 	if (rc)
7406 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7407 				"2747 Issue FCF scan read FCF mailbox "
7408 				"command failed 0x%x\n", rc);
7409 }
7410 
7411 /**
7412  * lpfc_api_table_setup - Set up per hba pci-device group func api jump table
7413  * @phba: pointer to lpfc hba data structure.
7414  * @dev_grp: The HBA PCI-Device group number.
7415  *
7416  * This routine is invoked to set up the per HBA PCI-Device group function
7417  * API jump table entries.
7418  *
7419  * Return: 0 if success, otherwise -ENODEV
7420  **/
7421 int
7422 lpfc_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
7423 {
7424 	int rc;
7425 
7426 	/* Set up lpfc PCI-device group */
7427 	phba->pci_dev_grp = dev_grp;
7428 
7429 	/* The LPFC_PCI_DEV_OC uses SLI4 */
7430 	if (dev_grp == LPFC_PCI_DEV_OC)
7431 		phba->sli_rev = LPFC_SLI_REV4;
7432 
7433 	/* Set up device INIT API function jump table */
7434 	rc = lpfc_init_api_table_setup(phba, dev_grp);
7435 	if (rc)
7436 		return -ENODEV;
7437 	/* Set up SCSI API function jump table */
7438 	rc = lpfc_scsi_api_table_setup(phba, dev_grp);
7439 	if (rc)
7440 		return -ENODEV;
7441 	/* Set up SLI API function jump table */
7442 	rc = lpfc_sli_api_table_setup(phba, dev_grp);
7443 	if (rc)
7444 		return -ENODEV;
7445 	/* Set up MBOX API function jump table */
7446 	rc = lpfc_mbox_api_table_setup(phba, dev_grp);
7447 	if (rc)
7448 		return -ENODEV;
7449 
7450 	return 0;
7451 }
7452 
7453 /**
7454  * lpfc_log_intr_mode - Log the active interrupt mode
7455  * @phba: pointer to lpfc hba data structure.
7456  * @intr_mode: active interrupt mode adopted.
7457  *
7458  * This routine it invoked to log the currently used active interrupt mode
7459  * to the device.
7460  **/
7461 static void lpfc_log_intr_mode(struct lpfc_hba *phba, uint32_t intr_mode)
7462 {
7463 	switch (intr_mode) {
7464 	case 0:
7465 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7466 				"0470 Enable INTx interrupt mode.\n");
7467 		break;
7468 	case 1:
7469 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7470 				"0481 Enabled MSI interrupt mode.\n");
7471 		break;
7472 	case 2:
7473 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7474 				"0480 Enabled MSI-X interrupt mode.\n");
7475 		break;
7476 	default:
7477 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7478 				"0482 Illegal interrupt mode.\n");
7479 		break;
7480 	}
7481 	return;
7482 }
7483 
7484 /**
7485  * lpfc_enable_pci_dev - Enable a generic PCI device.
7486  * @phba: pointer to lpfc hba data structure.
7487  *
7488  * This routine is invoked to enable the PCI device that is common to all
7489  * PCI devices.
7490  *
7491  * Return codes
7492  * 	0 - successful
7493  * 	other values - error
7494  **/
7495 static int
7496 lpfc_enable_pci_dev(struct lpfc_hba *phba)
7497 {
7498 	struct pci_dev *pdev;
7499 
7500 	/* Obtain PCI device reference */
7501 	if (!phba->pcidev)
7502 		goto out_error;
7503 	else
7504 		pdev = phba->pcidev;
7505 	/* Enable PCI device */
7506 	if (pci_enable_device_mem(pdev))
7507 		goto out_error;
7508 	/* Request PCI resource for the device */
7509 	if (pci_request_mem_regions(pdev, LPFC_DRIVER_NAME))
7510 		goto out_disable_device;
7511 	/* Set up device as PCI master and save state for EEH */
7512 	pci_set_master(pdev);
7513 	pci_try_set_mwi(pdev);
7514 	pci_save_state(pdev);
7515 
7516 	/* PCIe EEH recovery on powerpc platforms needs fundamental reset */
7517 	if (pci_is_pcie(pdev))
7518 		pdev->needs_freset = 1;
7519 
7520 	return 0;
7521 
7522 out_disable_device:
7523 	pci_disable_device(pdev);
7524 out_error:
7525 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7526 			"1401 Failed to enable pci device\n");
7527 	return -ENODEV;
7528 }
7529 
7530 /**
7531  * lpfc_disable_pci_dev - Disable a generic PCI device.
7532  * @phba: pointer to lpfc hba data structure.
7533  *
7534  * This routine is invoked to disable the PCI device that is common to all
7535  * PCI devices.
7536  **/
7537 static void
7538 lpfc_disable_pci_dev(struct lpfc_hba *phba)
7539 {
7540 	struct pci_dev *pdev;
7541 
7542 	/* Obtain PCI device reference */
7543 	if (!phba->pcidev)
7544 		return;
7545 	else
7546 		pdev = phba->pcidev;
7547 	/* Release PCI resource and disable PCI device */
7548 	pci_release_mem_regions(pdev);
7549 	pci_disable_device(pdev);
7550 
7551 	return;
7552 }
7553 
7554 /**
7555  * lpfc_reset_hba - Reset a hba
7556  * @phba: pointer to lpfc hba data structure.
7557  *
7558  * This routine is invoked to reset a hba device. It brings the HBA
7559  * offline, performs a board restart, and then brings the board back
7560  * online. The lpfc_offline calls lpfc_sli_hba_down which will clean up
7561  * on outstanding mailbox commands.
7562  **/
7563 void
7564 lpfc_reset_hba(struct lpfc_hba *phba)
7565 {
7566 	int rc = 0;
7567 
7568 	/* If resets are disabled then set error state and return. */
7569 	if (!phba->cfg_enable_hba_reset) {
7570 		phba->link_state = LPFC_HBA_ERROR;
7571 		return;
7572 	}
7573 
7574 	/* If not LPFC_SLI_ACTIVE, force all IO to be flushed */
7575 	if (phba->sli.sli_flag & LPFC_SLI_ACTIVE) {
7576 		lpfc_offline_prep(phba, LPFC_MBX_WAIT);
7577 	} else {
7578 		if (test_bit(MBX_TMO_ERR, &phba->bit_flags)) {
7579 			/* Perform a PCI function reset to start from clean */
7580 			rc = lpfc_pci_function_reset(phba);
7581 			lpfc_els_flush_all_cmd(phba);
7582 		}
7583 		lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
7584 		lpfc_sli_flush_io_rings(phba);
7585 	}
7586 	lpfc_offline(phba);
7587 	clear_bit(MBX_TMO_ERR, &phba->bit_flags);
7588 	if (unlikely(rc)) {
7589 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
7590 				"8888 PCI function reset failed rc %x\n",
7591 				rc);
7592 	} else {
7593 		lpfc_sli_brdrestart(phba);
7594 		lpfc_online(phba);
7595 		lpfc_unblock_mgmt_io(phba);
7596 	}
7597 }
7598 
7599 /**
7600  * lpfc_sli_sriov_nr_virtfn_get - Get the number of sr-iov virtual functions
7601  * @phba: pointer to lpfc hba data structure.
7602  *
7603  * This function enables the PCI SR-IOV virtual functions to a physical
7604  * function. It invokes the PCI SR-IOV api with the @nr_vfn provided to
7605  * enable the number of virtual functions to the physical function. As
7606  * not all devices support SR-IOV, the return code from the pci_enable_sriov()
7607  * API call does not considered as an error condition for most of the device.
7608  **/
7609 uint16_t
7610 lpfc_sli_sriov_nr_virtfn_get(struct lpfc_hba *phba)
7611 {
7612 	struct pci_dev *pdev = phba->pcidev;
7613 	uint16_t nr_virtfn;
7614 	int pos;
7615 
7616 	pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_SRIOV);
7617 	if (pos == 0)
7618 		return 0;
7619 
7620 	pci_read_config_word(pdev, pos + PCI_SRIOV_TOTAL_VF, &nr_virtfn);
7621 	return nr_virtfn;
7622 }
7623 
7624 /**
7625  * lpfc_sli_probe_sriov_nr_virtfn - Enable a number of sr-iov virtual functions
7626  * @phba: pointer to lpfc hba data structure.
7627  * @nr_vfn: number of virtual functions to be enabled.
7628  *
7629  * This function enables the PCI SR-IOV virtual functions to a physical
7630  * function. It invokes the PCI SR-IOV api with the @nr_vfn provided to
7631  * enable the number of virtual functions to the physical function. As
7632  * not all devices support SR-IOV, the return code from the pci_enable_sriov()
7633  * API call does not considered as an error condition for most of the device.
7634  **/
7635 int
7636 lpfc_sli_probe_sriov_nr_virtfn(struct lpfc_hba *phba, int nr_vfn)
7637 {
7638 	struct pci_dev *pdev = phba->pcidev;
7639 	uint16_t max_nr_vfn;
7640 	int rc;
7641 
7642 	max_nr_vfn = lpfc_sli_sriov_nr_virtfn_get(phba);
7643 	if (nr_vfn > max_nr_vfn) {
7644 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7645 				"3057 Requested vfs (%d) greater than "
7646 				"supported vfs (%d)", nr_vfn, max_nr_vfn);
7647 		return -EINVAL;
7648 	}
7649 
7650 	rc = pci_enable_sriov(pdev, nr_vfn);
7651 	if (rc) {
7652 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7653 				"2806 Failed to enable sriov on this device "
7654 				"with vfn number nr_vf:%d, rc:%d\n",
7655 				nr_vfn, rc);
7656 	} else
7657 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7658 				"2807 Successful enable sriov on this device "
7659 				"with vfn number nr_vf:%d\n", nr_vfn);
7660 	return rc;
7661 }
7662 
7663 static void
7664 lpfc_unblock_requests_work(struct work_struct *work)
7665 {
7666 	struct lpfc_hba *phba = container_of(work, struct lpfc_hba,
7667 					     unblock_request_work);
7668 
7669 	lpfc_unblock_requests(phba);
7670 }
7671 
7672 /**
7673  * lpfc_setup_driver_resource_phase1 - Phase1 etup driver internal resources.
7674  * @phba: pointer to lpfc hba data structure.
7675  *
7676  * This routine is invoked to set up the driver internal resources before the
7677  * device specific resource setup to support the HBA device it attached to.
7678  *
7679  * Return codes
7680  *	0 - successful
7681  *	other values - error
7682  **/
7683 static int
7684 lpfc_setup_driver_resource_phase1(struct lpfc_hba *phba)
7685 {
7686 	struct lpfc_sli *psli = &phba->sli;
7687 
7688 	/*
7689 	 * Driver resources common to all SLI revisions
7690 	 */
7691 	atomic_set(&phba->fast_event_count, 0);
7692 	atomic_set(&phba->dbg_log_idx, 0);
7693 	atomic_set(&phba->dbg_log_cnt, 0);
7694 	atomic_set(&phba->dbg_log_dmping, 0);
7695 	spin_lock_init(&phba->hbalock);
7696 
7697 	/* Initialize port_list spinlock */
7698 	spin_lock_init(&phba->port_list_lock);
7699 	INIT_LIST_HEAD(&phba->port_list);
7700 
7701 	INIT_LIST_HEAD(&phba->work_list);
7702 
7703 	/* Initialize the wait queue head for the kernel thread */
7704 	init_waitqueue_head(&phba->work_waitq);
7705 
7706 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7707 			"1403 Protocols supported %s %s %s\n",
7708 			((phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP) ?
7709 				"SCSI" : " "),
7710 			((phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) ?
7711 				"NVME" : " "),
7712 			(phba->nvmet_support ? "NVMET" : " "));
7713 
7714 	/* ras_fwlog state */
7715 	spin_lock_init(&phba->ras_fwlog_lock);
7716 
7717 	/* Initialize the IO buffer list used by driver for SLI3 SCSI */
7718 	spin_lock_init(&phba->scsi_buf_list_get_lock);
7719 	INIT_LIST_HEAD(&phba->lpfc_scsi_buf_list_get);
7720 	spin_lock_init(&phba->scsi_buf_list_put_lock);
7721 	INIT_LIST_HEAD(&phba->lpfc_scsi_buf_list_put);
7722 
7723 	/* Initialize the fabric iocb list */
7724 	INIT_LIST_HEAD(&phba->fabric_iocb_list);
7725 
7726 	/* Initialize list to save ELS buffers */
7727 	INIT_LIST_HEAD(&phba->elsbuf);
7728 
7729 	/* Initialize FCF connection rec list */
7730 	INIT_LIST_HEAD(&phba->fcf_conn_rec_list);
7731 
7732 	/* Initialize OAS configuration list */
7733 	spin_lock_init(&phba->devicelock);
7734 	INIT_LIST_HEAD(&phba->luns);
7735 
7736 	/* MBOX heartbeat timer */
7737 	timer_setup(&psli->mbox_tmo, lpfc_mbox_timeout, 0);
7738 	/* Fabric block timer */
7739 	timer_setup(&phba->fabric_block_timer, lpfc_fabric_block_timeout, 0);
7740 	/* EA polling mode timer */
7741 	timer_setup(&phba->eratt_poll, lpfc_poll_eratt, 0);
7742 	/* Heartbeat timer */
7743 	timer_setup(&phba->hb_tmofunc, lpfc_hb_timeout, 0);
7744 
7745 	INIT_DELAYED_WORK(&phba->eq_delay_work, lpfc_hb_eq_delay_work);
7746 
7747 	INIT_DELAYED_WORK(&phba->idle_stat_delay_work,
7748 			  lpfc_idle_stat_delay_work);
7749 	INIT_WORK(&phba->unblock_request_work, lpfc_unblock_requests_work);
7750 	return 0;
7751 }
7752 
7753 /**
7754  * lpfc_sli_driver_resource_setup - Setup driver internal resources for SLI3 dev
7755  * @phba: pointer to lpfc hba data structure.
7756  *
7757  * This routine is invoked to set up the driver internal resources specific to
7758  * support the SLI-3 HBA device it attached to.
7759  *
7760  * Return codes
7761  * 0 - successful
7762  * other values - error
7763  **/
7764 static int
7765 lpfc_sli_driver_resource_setup(struct lpfc_hba *phba)
7766 {
7767 	int rc, entry_sz;
7768 
7769 	/*
7770 	 * Initialize timers used by driver
7771 	 */
7772 
7773 	/* FCP polling mode timer */
7774 	timer_setup(&phba->fcp_poll_timer, lpfc_poll_timeout, 0);
7775 
7776 	/* Host attention work mask setup */
7777 	phba->work_ha_mask = (HA_ERATT | HA_MBATT | HA_LATT);
7778 	phba->work_ha_mask |= (HA_RXMASK << (LPFC_ELS_RING * 4));
7779 
7780 	/* Get all the module params for configuring this host */
7781 	lpfc_get_cfgparam(phba);
7782 	/* Set up phase-1 common device driver resources */
7783 
7784 	rc = lpfc_setup_driver_resource_phase1(phba);
7785 	if (rc)
7786 		return -ENODEV;
7787 
7788 	if (!phba->sli.sli3_ring)
7789 		phba->sli.sli3_ring = kcalloc(LPFC_SLI3_MAX_RING,
7790 					      sizeof(struct lpfc_sli_ring),
7791 					      GFP_KERNEL);
7792 	if (!phba->sli.sli3_ring)
7793 		return -ENOMEM;
7794 
7795 	/*
7796 	 * Since lpfc_sg_seg_cnt is module parameter, the sg_dma_buf_size
7797 	 * used to create the sg_dma_buf_pool must be dynamically calculated.
7798 	 */
7799 
7800 	if (phba->sli_rev == LPFC_SLI_REV4)
7801 		entry_sz = sizeof(struct sli4_sge);
7802 	else
7803 		entry_sz = sizeof(struct ulp_bde64);
7804 
7805 	/* There are going to be 2 reserved BDEs: 1 FCP cmnd + 1 FCP rsp */
7806 	if (phba->cfg_enable_bg) {
7807 		/*
7808 		 * The scsi_buf for a T10-DIF I/O will hold the FCP cmnd,
7809 		 * the FCP rsp, and a BDE for each. Sice we have no control
7810 		 * over how many protection data segments the SCSI Layer
7811 		 * will hand us (ie: there could be one for every block
7812 		 * in the IO), we just allocate enough BDEs to accomidate
7813 		 * our max amount and we need to limit lpfc_sg_seg_cnt to
7814 		 * minimize the risk of running out.
7815 		 */
7816 		phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd) +
7817 			sizeof(struct fcp_rsp) +
7818 			(LPFC_MAX_SG_SEG_CNT * entry_sz);
7819 
7820 		if (phba->cfg_sg_seg_cnt > LPFC_MAX_SG_SEG_CNT_DIF)
7821 			phba->cfg_sg_seg_cnt = LPFC_MAX_SG_SEG_CNT_DIF;
7822 
7823 		/* Total BDEs in BPL for scsi_sg_list and scsi_sg_prot_list */
7824 		phba->cfg_total_seg_cnt = LPFC_MAX_SG_SEG_CNT;
7825 	} else {
7826 		/*
7827 		 * The scsi_buf for a regular I/O will hold the FCP cmnd,
7828 		 * the FCP rsp, a BDE for each, and a BDE for up to
7829 		 * cfg_sg_seg_cnt data segments.
7830 		 */
7831 		phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd) +
7832 			sizeof(struct fcp_rsp) +
7833 			((phba->cfg_sg_seg_cnt + 2) * entry_sz);
7834 
7835 		/* Total BDEs in BPL for scsi_sg_list */
7836 		phba->cfg_total_seg_cnt = phba->cfg_sg_seg_cnt + 2;
7837 	}
7838 
7839 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP,
7840 			"9088 INIT sg_tablesize:%d dmabuf_size:%d total_bde:%d\n",
7841 			phba->cfg_sg_seg_cnt, phba->cfg_sg_dma_buf_size,
7842 			phba->cfg_total_seg_cnt);
7843 
7844 	phba->max_vpi = LPFC_MAX_VPI;
7845 	/* This will be set to correct value after config_port mbox */
7846 	phba->max_vports = 0;
7847 
7848 	/*
7849 	 * Initialize the SLI Layer to run with lpfc HBAs.
7850 	 */
7851 	lpfc_sli_setup(phba);
7852 	lpfc_sli_queue_init(phba);
7853 
7854 	/* Allocate device driver memory */
7855 	if (lpfc_mem_alloc(phba, BPL_ALIGN_SZ))
7856 		return -ENOMEM;
7857 
7858 	phba->lpfc_sg_dma_buf_pool =
7859 		dma_pool_create("lpfc_sg_dma_buf_pool",
7860 				&phba->pcidev->dev, phba->cfg_sg_dma_buf_size,
7861 				BPL_ALIGN_SZ, 0);
7862 
7863 	if (!phba->lpfc_sg_dma_buf_pool)
7864 		goto fail_free_mem;
7865 
7866 	phba->lpfc_cmd_rsp_buf_pool =
7867 			dma_pool_create("lpfc_cmd_rsp_buf_pool",
7868 					&phba->pcidev->dev,
7869 					sizeof(struct fcp_cmnd) +
7870 					sizeof(struct fcp_rsp),
7871 					BPL_ALIGN_SZ, 0);
7872 
7873 	if (!phba->lpfc_cmd_rsp_buf_pool)
7874 		goto fail_free_dma_buf_pool;
7875 
7876 	/*
7877 	 * Enable sr-iov virtual functions if supported and configured
7878 	 * through the module parameter.
7879 	 */
7880 	if (phba->cfg_sriov_nr_virtfn > 0) {
7881 		rc = lpfc_sli_probe_sriov_nr_virtfn(phba,
7882 						 phba->cfg_sriov_nr_virtfn);
7883 		if (rc) {
7884 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7885 					"2808 Requested number of SR-IOV "
7886 					"virtual functions (%d) is not "
7887 					"supported\n",
7888 					phba->cfg_sriov_nr_virtfn);
7889 			phba->cfg_sriov_nr_virtfn = 0;
7890 		}
7891 	}
7892 
7893 	return 0;
7894 
7895 fail_free_dma_buf_pool:
7896 	dma_pool_destroy(phba->lpfc_sg_dma_buf_pool);
7897 	phba->lpfc_sg_dma_buf_pool = NULL;
7898 fail_free_mem:
7899 	lpfc_mem_free(phba);
7900 	return -ENOMEM;
7901 }
7902 
7903 /**
7904  * lpfc_sli_driver_resource_unset - Unset drvr internal resources for SLI3 dev
7905  * @phba: pointer to lpfc hba data structure.
7906  *
7907  * This routine is invoked to unset the driver internal resources set up
7908  * specific for supporting the SLI-3 HBA device it attached to.
7909  **/
7910 static void
7911 lpfc_sli_driver_resource_unset(struct lpfc_hba *phba)
7912 {
7913 	/* Free device driver memory allocated */
7914 	lpfc_mem_free_all(phba);
7915 
7916 	return;
7917 }
7918 
7919 /**
7920  * lpfc_sli4_driver_resource_setup - Setup drvr internal resources for SLI4 dev
7921  * @phba: pointer to lpfc hba data structure.
7922  *
7923  * This routine is invoked to set up the driver internal resources specific to
7924  * support the SLI-4 HBA device it attached to.
7925  *
7926  * Return codes
7927  * 	0 - successful
7928  * 	other values - error
7929  **/
7930 static int
7931 lpfc_sli4_driver_resource_setup(struct lpfc_hba *phba)
7932 {
7933 	LPFC_MBOXQ_t *mboxq;
7934 	MAILBOX_t *mb;
7935 	int rc, i, max_buf_size;
7936 	int longs;
7937 	int extra;
7938 	uint64_t wwn;
7939 
7940 	phba->sli4_hba.num_present_cpu = lpfc_present_cpu;
7941 	phba->sli4_hba.num_possible_cpu = cpumask_last(cpu_possible_mask) + 1;
7942 	phba->sli4_hba.curr_disp_cpu = 0;
7943 
7944 	/* Get all the module params for configuring this host */
7945 	lpfc_get_cfgparam(phba);
7946 
7947 	/* Set up phase-1 common device driver resources */
7948 	rc = lpfc_setup_driver_resource_phase1(phba);
7949 	if (rc)
7950 		return -ENODEV;
7951 
7952 	/* Before proceed, wait for POST done and device ready */
7953 	rc = lpfc_sli4_post_status_check(phba);
7954 	if (rc)
7955 		return -ENODEV;
7956 
7957 	/* Allocate all driver workqueues here */
7958 
7959 	/* The lpfc_wq workqueue for deferred irq use */
7960 	phba->wq = alloc_workqueue("lpfc_wq", WQ_MEM_RECLAIM, 0);
7961 	if (!phba->wq)
7962 		return -ENOMEM;
7963 
7964 	/*
7965 	 * Initialize timers used by driver
7966 	 */
7967 
7968 	timer_setup(&phba->rrq_tmr, lpfc_rrq_timeout, 0);
7969 
7970 	/* FCF rediscover timer */
7971 	timer_setup(&phba->fcf.redisc_wait, lpfc_sli4_fcf_redisc_wait_tmo, 0);
7972 
7973 	/* CMF congestion timer */
7974 	hrtimer_setup(&phba->cmf_timer, lpfc_cmf_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
7975 	/* CMF 1 minute stats collection timer */
7976 	hrtimer_setup(&phba->cmf_stats_timer, lpfc_cmf_stats_timer, CLOCK_MONOTONIC,
7977 		      HRTIMER_MODE_REL);
7978 
7979 	/*
7980 	 * Control structure for handling external multi-buffer mailbox
7981 	 * command pass-through.
7982 	 */
7983 	memset((uint8_t *)&phba->mbox_ext_buf_ctx, 0,
7984 		sizeof(struct lpfc_mbox_ext_buf_ctx));
7985 	INIT_LIST_HEAD(&phba->mbox_ext_buf_ctx.ext_dmabuf_list);
7986 
7987 	phba->max_vpi = LPFC_MAX_VPI;
7988 
7989 	/* This will be set to correct value after the read_config mbox */
7990 	phba->max_vports = 0;
7991 
7992 	/* Program the default value of vlan_id and fc_map */
7993 	phba->valid_vlan = 0;
7994 	phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
7995 	phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
7996 	phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
7997 
7998 	/*
7999 	 * For SLI4, instead of using ring 0 (LPFC_FCP_RING) for FCP commands
8000 	 * we will associate a new ring, for each EQ/CQ/WQ tuple.
8001 	 * The WQ create will allocate the ring.
8002 	 */
8003 
8004 	/* Initialize buffer queue management fields */
8005 	INIT_LIST_HEAD(&phba->hbqs[LPFC_ELS_HBQ].hbq_buffer_list);
8006 	phba->hbqs[LPFC_ELS_HBQ].hbq_alloc_buffer = lpfc_sli4_rb_alloc;
8007 	phba->hbqs[LPFC_ELS_HBQ].hbq_free_buffer = lpfc_sli4_rb_free;
8008 
8009 	/* for VMID idle timeout if VMID is enabled */
8010 	if (lpfc_is_vmid_enabled(phba))
8011 		timer_setup(&phba->inactive_vmid_poll, lpfc_vmid_poll, 0);
8012 
8013 	/*
8014 	 * Initialize the SLI Layer to run with lpfc SLI4 HBAs.
8015 	 */
8016 	/* Initialize the Abort buffer list used by driver */
8017 	spin_lock_init(&phba->sli4_hba.abts_io_buf_list_lock);
8018 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_io_buf_list);
8019 
8020 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
8021 		/* Initialize the Abort nvme buffer list used by driver */
8022 		spin_lock_init(&phba->sli4_hba.abts_nvmet_buf_list_lock);
8023 		INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
8024 		INIT_LIST_HEAD(&phba->sli4_hba.lpfc_nvmet_io_wait_list);
8025 		spin_lock_init(&phba->sli4_hba.t_active_list_lock);
8026 		INIT_LIST_HEAD(&phba->sli4_hba.t_active_ctx_list);
8027 	}
8028 
8029 	/* This abort list used by worker thread */
8030 	spin_lock_init(&phba->sli4_hba.sgl_list_lock);
8031 	spin_lock_init(&phba->sli4_hba.nvmet_io_wait_lock);
8032 	spin_lock_init(&phba->sli4_hba.asynce_list_lock);
8033 	spin_lock_init(&phba->sli4_hba.els_xri_abrt_list_lock);
8034 
8035 	/*
8036 	 * Initialize driver internal slow-path work queues
8037 	 */
8038 
8039 	/* Driver internel slow-path CQ Event pool */
8040 	INIT_LIST_HEAD(&phba->sli4_hba.sp_cqe_event_pool);
8041 	/* Response IOCB work queue list */
8042 	INIT_LIST_HEAD(&phba->sli4_hba.sp_queue_event);
8043 	/* Asynchronous event CQ Event work queue list */
8044 	INIT_LIST_HEAD(&phba->sli4_hba.sp_asynce_work_queue);
8045 	/* Slow-path XRI aborted CQ Event work queue list */
8046 	INIT_LIST_HEAD(&phba->sli4_hba.sp_els_xri_aborted_work_queue);
8047 	/* Receive queue CQ Event work queue list */
8048 	INIT_LIST_HEAD(&phba->sli4_hba.sp_unsol_work_queue);
8049 
8050 	/* Initialize extent block lists. */
8051 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_rpi_blk_list);
8052 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_xri_blk_list);
8053 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_vfi_blk_list);
8054 	INIT_LIST_HEAD(&phba->lpfc_vpi_blk_list);
8055 
8056 	/* Initialize mboxq lists. If the early init routines fail
8057 	 * these lists need to be correctly initialized.
8058 	 */
8059 	INIT_LIST_HEAD(&phba->sli.mboxq);
8060 	INIT_LIST_HEAD(&phba->sli.mboxq_cmpl);
8061 
8062 	/* initialize optic_state to 0xFF */
8063 	phba->sli4_hba.lnk_info.optic_state = 0xff;
8064 
8065 	/* Allocate device driver memory */
8066 	rc = lpfc_mem_alloc(phba, SGL_ALIGN_SZ);
8067 	if (rc)
8068 		goto out_destroy_workqueue;
8069 
8070 	/* IF Type 2 ports get initialized now. */
8071 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) >=
8072 	    LPFC_SLI_INTF_IF_TYPE_2) {
8073 		rc = lpfc_pci_function_reset(phba);
8074 		if (unlikely(rc)) {
8075 			rc = -ENODEV;
8076 			goto out_free_mem;
8077 		}
8078 		phba->temp_sensor_support = 1;
8079 	}
8080 
8081 	/* Create the bootstrap mailbox command */
8082 	rc = lpfc_create_bootstrap_mbox(phba);
8083 	if (unlikely(rc))
8084 		goto out_free_mem;
8085 
8086 	/* Set up the host's endian order with the device. */
8087 	rc = lpfc_setup_endian_order(phba);
8088 	if (unlikely(rc))
8089 		goto out_free_bsmbx;
8090 
8091 	/* Set up the hba's configuration parameters. */
8092 	rc = lpfc_sli4_read_config(phba);
8093 	if (unlikely(rc))
8094 		goto out_free_bsmbx;
8095 
8096 	if (phba->sli4_hba.fawwpn_flag & LPFC_FAWWPN_CONFIG) {
8097 		/* Right now the link is down, if FA-PWWN is configured the
8098 		 * firmware will try FLOGI before the driver gets a link up.
8099 		 * If it fails, the driver should get a MISCONFIGURED async
8100 		 * event which will clear this flag. The only notification
8101 		 * the driver gets is if it fails, if it succeeds there is no
8102 		 * notification given. Assume success.
8103 		 */
8104 		phba->sli4_hba.fawwpn_flag |= LPFC_FAWWPN_FABRIC;
8105 	}
8106 
8107 	rc = lpfc_mem_alloc_active_rrq_pool_s4(phba);
8108 	if (unlikely(rc))
8109 		goto out_free_bsmbx;
8110 
8111 	/* IF Type 0 ports get initialized now. */
8112 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
8113 	    LPFC_SLI_INTF_IF_TYPE_0) {
8114 		rc = lpfc_pci_function_reset(phba);
8115 		if (unlikely(rc))
8116 			goto out_free_bsmbx;
8117 	}
8118 
8119 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
8120 						       GFP_KERNEL);
8121 	if (!mboxq) {
8122 		rc = -ENOMEM;
8123 		goto out_free_bsmbx;
8124 	}
8125 
8126 	/* Check for NVMET being configured */
8127 	phba->nvmet_support = 0;
8128 	if (lpfc_enable_nvmet_cnt) {
8129 
8130 		/* First get WWN of HBA instance */
8131 		lpfc_read_nv(phba, mboxq);
8132 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8133 		if (rc != MBX_SUCCESS) {
8134 			lpfc_printf_log(phba, KERN_ERR,
8135 					LOG_TRACE_EVENT,
8136 					"6016 Mailbox failed , mbxCmd x%x "
8137 					"READ_NV, mbxStatus x%x\n",
8138 					bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8139 					bf_get(lpfc_mqe_status, &mboxq->u.mqe));
8140 			mempool_free(mboxq, phba->mbox_mem_pool);
8141 			rc = -EIO;
8142 			goto out_free_bsmbx;
8143 		}
8144 		mb = &mboxq->u.mb;
8145 		memcpy(&wwn, (char *)mb->un.varRDnvp.nodename,
8146 		       sizeof(uint64_t));
8147 		wwn = cpu_to_be64(wwn);
8148 		phba->sli4_hba.wwnn.u.name = wwn;
8149 		memcpy(&wwn, (char *)mb->un.varRDnvp.portname,
8150 		       sizeof(uint64_t));
8151 		/* wwn is WWPN of HBA instance */
8152 		wwn = cpu_to_be64(wwn);
8153 		phba->sli4_hba.wwpn.u.name = wwn;
8154 
8155 		/* Check to see if it matches any module parameter */
8156 		for (i = 0; i < lpfc_enable_nvmet_cnt; i++) {
8157 			if (wwn == lpfc_enable_nvmet[i]) {
8158 #if (IS_ENABLED(CONFIG_NVME_TARGET_FC))
8159 				if (lpfc_nvmet_mem_alloc(phba))
8160 					break;
8161 
8162 				phba->nvmet_support = 1; /* a match */
8163 
8164 				lpfc_printf_log(phba, KERN_ERR,
8165 						LOG_TRACE_EVENT,
8166 						"6017 NVME Target %016llx\n",
8167 						wwn);
8168 #else
8169 				lpfc_printf_log(phba, KERN_ERR,
8170 						LOG_TRACE_EVENT,
8171 						"6021 Can't enable NVME Target."
8172 						" NVME_TARGET_FC infrastructure"
8173 						" is not in kernel\n");
8174 #endif
8175 				/* Not supported for NVMET */
8176 				phba->cfg_xri_rebalancing = 0;
8177 				if (phba->irq_chann_mode == NHT_MODE) {
8178 					phba->cfg_irq_chann =
8179 						phba->sli4_hba.num_present_cpu;
8180 					phba->cfg_hdw_queue =
8181 						phba->sli4_hba.num_present_cpu;
8182 					phba->irq_chann_mode = NORMAL_MODE;
8183 				}
8184 				break;
8185 			}
8186 		}
8187 	}
8188 
8189 	lpfc_nvme_mod_param_dep(phba);
8190 
8191 	/*
8192 	 * Get sli4 parameters that override parameters from Port capabilities.
8193 	 * If this call fails, it isn't critical unless the SLI4 parameters come
8194 	 * back in conflict.
8195 	 */
8196 	rc = lpfc_get_sli4_parameters(phba, mboxq);
8197 	if (rc) {
8198 		lpfc_log_msg(phba, KERN_WARNING, LOG_INIT,
8199 			     "2999 Could not get SLI4 parameters\n");
8200 		rc = -EIO;
8201 		mempool_free(mboxq, phba->mbox_mem_pool);
8202 		goto out_free_bsmbx;
8203 	}
8204 
8205 	/*
8206 	 * 1 for cmd, 1 for rsp, NVME adds an extra one
8207 	 * for boundary conditions in its max_sgl_segment template.
8208 	 */
8209 	extra = 2;
8210 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
8211 		extra++;
8212 
8213 	/*
8214 	 * It doesn't matter what family our adapter is in, we are
8215 	 * limited to 2 Pages, 512 SGEs, for our SGL.
8216 	 * There are going to be 2 reserved SGEs: 1 FCP cmnd + 1 FCP rsp
8217 	 */
8218 	max_buf_size = (2 * SLI4_PAGE_SIZE);
8219 
8220 	/*
8221 	 * Since lpfc_sg_seg_cnt is module param, the sg_dma_buf_size
8222 	 * used to create the sg_dma_buf_pool must be calculated.
8223 	 */
8224 	if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
8225 		/* Both cfg_enable_bg and cfg_external_dif code paths */
8226 
8227 		/*
8228 		 * The scsi_buf for a T10-DIF I/O holds the FCP cmnd,
8229 		 * the FCP rsp, and a SGE. Sice we have no control
8230 		 * over how many protection segments the SCSI Layer
8231 		 * will hand us (ie: there could be one for every block
8232 		 * in the IO), just allocate enough SGEs to accomidate
8233 		 * our max amount and we need to limit lpfc_sg_seg_cnt
8234 		 * to minimize the risk of running out.
8235 		 */
8236 		phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd32) +
8237 				sizeof(struct fcp_rsp) + max_buf_size;
8238 
8239 		/* Total SGEs for scsi_sg_list and scsi_sg_prot_list */
8240 		phba->cfg_total_seg_cnt = LPFC_MAX_SGL_SEG_CNT;
8241 
8242 		/*
8243 		 * If supporting DIF, reduce the seg count for scsi to
8244 		 * allow room for the DIF sges.
8245 		 */
8246 		if (phba->cfg_enable_bg &&
8247 		    phba->cfg_sg_seg_cnt > LPFC_MAX_BG_SLI4_SEG_CNT_DIF)
8248 			phba->cfg_scsi_seg_cnt = LPFC_MAX_BG_SLI4_SEG_CNT_DIF;
8249 		else
8250 			phba->cfg_scsi_seg_cnt = phba->cfg_sg_seg_cnt;
8251 
8252 	} else {
8253 		/*
8254 		 * The scsi_buf for a regular I/O holds the FCP cmnd,
8255 		 * the FCP rsp, a SGE for each, and a SGE for up to
8256 		 * cfg_sg_seg_cnt data segments.
8257 		 */
8258 		phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd32) +
8259 				sizeof(struct fcp_rsp) +
8260 				((phba->cfg_sg_seg_cnt + extra) *
8261 				sizeof(struct sli4_sge));
8262 
8263 		/* Total SGEs for scsi_sg_list */
8264 		phba->cfg_total_seg_cnt = phba->cfg_sg_seg_cnt + extra;
8265 		phba->cfg_scsi_seg_cnt = phba->cfg_sg_seg_cnt;
8266 
8267 		/*
8268 		 * NOTE: if (phba->cfg_sg_seg_cnt + extra) <= 256 we only
8269 		 * need to post 1 page for the SGL.
8270 		 */
8271 	}
8272 
8273 	if (phba->cfg_xpsgl && !phba->nvmet_support)
8274 		phba->cfg_sg_dma_buf_size = LPFC_DEFAULT_XPSGL_SIZE;
8275 	else if (phba->cfg_sg_dma_buf_size  <= LPFC_MIN_SG_SLI4_BUF_SZ)
8276 		phba->cfg_sg_dma_buf_size = LPFC_MIN_SG_SLI4_BUF_SZ;
8277 	else
8278 		phba->cfg_sg_dma_buf_size =
8279 				SLI4_PAGE_ALIGN(phba->cfg_sg_dma_buf_size);
8280 
8281 	phba->border_sge_num = phba->cfg_sg_dma_buf_size /
8282 			       sizeof(struct sli4_sge);
8283 
8284 	/* Limit to LPFC_MAX_NVME_SEG_CNT for NVME. */
8285 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
8286 		if (phba->cfg_sg_seg_cnt > LPFC_MAX_NVME_SEG_CNT) {
8287 			lpfc_printf_log(phba, KERN_INFO, LOG_NVME | LOG_INIT,
8288 					"6300 Reducing NVME sg segment "
8289 					"cnt to %d\n",
8290 					LPFC_MAX_NVME_SEG_CNT);
8291 			phba->cfg_nvme_seg_cnt = LPFC_MAX_NVME_SEG_CNT;
8292 		} else
8293 			phba->cfg_nvme_seg_cnt = phba->cfg_sg_seg_cnt;
8294 	}
8295 
8296 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP,
8297 			"9087 sg_seg_cnt:%d dmabuf_size:%d "
8298 			"total:%d scsi:%d nvme:%d\n",
8299 			phba->cfg_sg_seg_cnt, phba->cfg_sg_dma_buf_size,
8300 			phba->cfg_total_seg_cnt,  phba->cfg_scsi_seg_cnt,
8301 			phba->cfg_nvme_seg_cnt);
8302 
8303 	i = min(phba->cfg_sg_dma_buf_size, SLI4_PAGE_SIZE);
8304 
8305 	phba->lpfc_sg_dma_buf_pool =
8306 			dma_pool_create("lpfc_sg_dma_buf_pool",
8307 					&phba->pcidev->dev,
8308 					phba->cfg_sg_dma_buf_size,
8309 					i, 0);
8310 	if (!phba->lpfc_sg_dma_buf_pool) {
8311 		rc = -ENOMEM;
8312 		goto out_free_bsmbx;
8313 	}
8314 
8315 	phba->lpfc_cmd_rsp_buf_pool =
8316 			dma_pool_create("lpfc_cmd_rsp_buf_pool",
8317 					&phba->pcidev->dev,
8318 					sizeof(struct fcp_cmnd32) +
8319 					sizeof(struct fcp_rsp),
8320 					i, 0);
8321 	if (!phba->lpfc_cmd_rsp_buf_pool) {
8322 		rc = -ENOMEM;
8323 		goto out_free_sg_dma_buf;
8324 	}
8325 
8326 	mempool_free(mboxq, phba->mbox_mem_pool);
8327 
8328 	/* Verify OAS is supported */
8329 	lpfc_sli4_oas_verify(phba);
8330 
8331 	/* Verify RAS support on adapter */
8332 	lpfc_sli4_ras_init(phba);
8333 
8334 	/* Verify all the SLI4 queues */
8335 	rc = lpfc_sli4_queue_verify(phba);
8336 	if (rc)
8337 		goto out_free_cmd_rsp_buf;
8338 
8339 	/* Create driver internal CQE event pool */
8340 	rc = lpfc_sli4_cq_event_pool_create(phba);
8341 	if (rc)
8342 		goto out_free_cmd_rsp_buf;
8343 
8344 	/* Initialize sgl lists per host */
8345 	lpfc_init_sgl_list(phba);
8346 
8347 	/* Allocate and initialize active sgl array */
8348 	rc = lpfc_init_active_sgl_array(phba);
8349 	if (rc) {
8350 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8351 				"1430 Failed to initialize sgl list.\n");
8352 		goto out_destroy_cq_event_pool;
8353 	}
8354 	rc = lpfc_sli4_init_rpi_hdrs(phba);
8355 	if (rc) {
8356 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8357 				"1432 Failed to initialize rpi headers.\n");
8358 		goto out_free_active_sgl;
8359 	}
8360 
8361 	/* Allocate eligible FCF bmask memory for FCF roundrobin failover */
8362 	longs = (LPFC_SLI4_FCF_TBL_INDX_MAX + BITS_PER_LONG - 1)/BITS_PER_LONG;
8363 	phba->fcf.fcf_rr_bmask = kcalloc(longs, sizeof(unsigned long),
8364 					 GFP_KERNEL);
8365 	if (!phba->fcf.fcf_rr_bmask) {
8366 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8367 				"2759 Failed allocate memory for FCF round "
8368 				"robin failover bmask\n");
8369 		rc = -ENOMEM;
8370 		goto out_remove_rpi_hdrs;
8371 	}
8372 
8373 	phba->sli4_hba.hba_eq_hdl = kcalloc(phba->cfg_irq_chann,
8374 					    sizeof(struct lpfc_hba_eq_hdl),
8375 					    GFP_KERNEL);
8376 	if (!phba->sli4_hba.hba_eq_hdl) {
8377 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8378 				"2572 Failed allocate memory for "
8379 				"fast-path per-EQ handle array\n");
8380 		rc = -ENOMEM;
8381 		goto out_free_fcf_rr_bmask;
8382 	}
8383 
8384 	phba->sli4_hba.cpu_map = kcalloc(phba->sli4_hba.num_possible_cpu,
8385 					sizeof(struct lpfc_vector_map_info),
8386 					GFP_KERNEL);
8387 	if (!phba->sli4_hba.cpu_map) {
8388 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8389 				"3327 Failed allocate memory for msi-x "
8390 				"interrupt vector mapping\n");
8391 		rc = -ENOMEM;
8392 		goto out_free_hba_eq_hdl;
8393 	}
8394 
8395 	phba->sli4_hba.eq_info = alloc_percpu(struct lpfc_eq_intr_info);
8396 	if (!phba->sli4_hba.eq_info) {
8397 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8398 				"3321 Failed allocation for per_cpu stats\n");
8399 		rc = -ENOMEM;
8400 		goto out_free_hba_cpu_map;
8401 	}
8402 
8403 	phba->sli4_hba.idle_stat = kcalloc(phba->sli4_hba.num_possible_cpu,
8404 					   sizeof(*phba->sli4_hba.idle_stat),
8405 					   GFP_KERNEL);
8406 	if (!phba->sli4_hba.idle_stat) {
8407 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8408 				"3390 Failed allocation for idle_stat\n");
8409 		rc = -ENOMEM;
8410 		goto out_free_hba_eq_info;
8411 	}
8412 
8413 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
8414 	phba->sli4_hba.c_stat = alloc_percpu(struct lpfc_hdwq_stat);
8415 	if (!phba->sli4_hba.c_stat) {
8416 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8417 				"3332 Failed allocating per cpu hdwq stats\n");
8418 		rc = -ENOMEM;
8419 		goto out_free_hba_idle_stat;
8420 	}
8421 #endif
8422 
8423 	phba->cmf_stat = alloc_percpu(struct lpfc_cgn_stat);
8424 	if (!phba->cmf_stat) {
8425 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8426 				"3331 Failed allocating per cpu cgn stats\n");
8427 		rc = -ENOMEM;
8428 		goto out_free_hba_hdwq_info;
8429 	}
8430 
8431 	/*
8432 	 * Enable sr-iov virtual functions if supported and configured
8433 	 * through the module parameter.
8434 	 */
8435 	if (phba->cfg_sriov_nr_virtfn > 0) {
8436 		rc = lpfc_sli_probe_sriov_nr_virtfn(phba,
8437 						 phba->cfg_sriov_nr_virtfn);
8438 		if (rc) {
8439 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
8440 					"3020 Requested number of SR-IOV "
8441 					"virtual functions (%d) is not "
8442 					"supported\n",
8443 					phba->cfg_sriov_nr_virtfn);
8444 			phba->cfg_sriov_nr_virtfn = 0;
8445 		}
8446 	}
8447 
8448 	return 0;
8449 
8450 out_free_hba_hdwq_info:
8451 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
8452 	free_percpu(phba->sli4_hba.c_stat);
8453 out_free_hba_idle_stat:
8454 #endif
8455 	kfree(phba->sli4_hba.idle_stat);
8456 out_free_hba_eq_info:
8457 	free_percpu(phba->sli4_hba.eq_info);
8458 out_free_hba_cpu_map:
8459 	kfree(phba->sli4_hba.cpu_map);
8460 out_free_hba_eq_hdl:
8461 	kfree(phba->sli4_hba.hba_eq_hdl);
8462 out_free_fcf_rr_bmask:
8463 	kfree(phba->fcf.fcf_rr_bmask);
8464 out_remove_rpi_hdrs:
8465 	lpfc_sli4_remove_rpi_hdrs(phba);
8466 out_free_active_sgl:
8467 	lpfc_free_active_sgl(phba);
8468 out_destroy_cq_event_pool:
8469 	lpfc_sli4_cq_event_pool_destroy(phba);
8470 out_free_cmd_rsp_buf:
8471 	dma_pool_destroy(phba->lpfc_cmd_rsp_buf_pool);
8472 	phba->lpfc_cmd_rsp_buf_pool = NULL;
8473 out_free_sg_dma_buf:
8474 	dma_pool_destroy(phba->lpfc_sg_dma_buf_pool);
8475 	phba->lpfc_sg_dma_buf_pool = NULL;
8476 out_free_bsmbx:
8477 	lpfc_destroy_bootstrap_mbox(phba);
8478 out_free_mem:
8479 	lpfc_mem_free(phba);
8480 out_destroy_workqueue:
8481 	destroy_workqueue(phba->wq);
8482 	phba->wq = NULL;
8483 	return rc;
8484 }
8485 
8486 /**
8487  * lpfc_sli4_driver_resource_unset - Unset drvr internal resources for SLI4 dev
8488  * @phba: pointer to lpfc hba data structure.
8489  *
8490  * This routine is invoked to unset the driver internal resources set up
8491  * specific for supporting the SLI-4 HBA device it attached to.
8492  **/
8493 static void
8494 lpfc_sli4_driver_resource_unset(struct lpfc_hba *phba)
8495 {
8496 	struct lpfc_fcf_conn_entry *conn_entry, *next_conn_entry;
8497 
8498 	free_percpu(phba->sli4_hba.eq_info);
8499 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
8500 	free_percpu(phba->sli4_hba.c_stat);
8501 #endif
8502 	free_percpu(phba->cmf_stat);
8503 	kfree(phba->sli4_hba.idle_stat);
8504 
8505 	/* Free memory allocated for msi-x interrupt vector to CPU mapping */
8506 	kfree(phba->sli4_hba.cpu_map);
8507 	phba->sli4_hba.num_possible_cpu = 0;
8508 	phba->sli4_hba.num_present_cpu = 0;
8509 	phba->sli4_hba.curr_disp_cpu = 0;
8510 	cpumask_clear(&phba->sli4_hba.irq_aff_mask);
8511 
8512 	/* Free memory allocated for fast-path work queue handles */
8513 	kfree(phba->sli4_hba.hba_eq_hdl);
8514 
8515 	/* Free the allocated rpi headers. */
8516 	lpfc_sli4_remove_rpi_hdrs(phba);
8517 	lpfc_sli4_remove_rpis(phba);
8518 
8519 	/* Free eligible FCF index bmask */
8520 	kfree(phba->fcf.fcf_rr_bmask);
8521 
8522 	/* Free the ELS sgl list */
8523 	lpfc_free_active_sgl(phba);
8524 	lpfc_free_els_sgl_list(phba);
8525 	lpfc_free_nvmet_sgl_list(phba);
8526 
8527 	/* Free the completion queue EQ event pool */
8528 	lpfc_sli4_cq_event_release_all(phba);
8529 	lpfc_sli4_cq_event_pool_destroy(phba);
8530 
8531 	/* Release resource identifiers. */
8532 	lpfc_sli4_dealloc_resource_identifiers(phba);
8533 
8534 	/* Free the bsmbx region. */
8535 	lpfc_destroy_bootstrap_mbox(phba);
8536 
8537 	/* Free the SLI Layer memory with SLI4 HBAs */
8538 	lpfc_mem_free_all(phba);
8539 
8540 	/* Free the current connect table */
8541 	list_for_each_entry_safe(conn_entry, next_conn_entry,
8542 		&phba->fcf_conn_rec_list, list) {
8543 		list_del_init(&conn_entry->list);
8544 		kfree(conn_entry);
8545 	}
8546 
8547 	return;
8548 }
8549 
8550 /**
8551  * lpfc_init_api_table_setup - Set up init api function jump table
8552  * @phba: The hba struct for which this call is being executed.
8553  * @dev_grp: The HBA PCI-Device group number.
8554  *
8555  * This routine sets up the device INIT interface API function jump table
8556  * in @phba struct.
8557  *
8558  * Returns: 0 - success, -ENODEV - failure.
8559  **/
8560 int
8561 lpfc_init_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
8562 {
8563 	phba->lpfc_hba_init_link = lpfc_hba_init_link;
8564 	phba->lpfc_hba_down_link = lpfc_hba_down_link;
8565 	phba->lpfc_selective_reset = lpfc_selective_reset;
8566 	switch (dev_grp) {
8567 	case LPFC_PCI_DEV_LP:
8568 		phba->lpfc_hba_down_post = lpfc_hba_down_post_s3;
8569 		phba->lpfc_handle_eratt = lpfc_handle_eratt_s3;
8570 		phba->lpfc_stop_port = lpfc_stop_port_s3;
8571 		break;
8572 	case LPFC_PCI_DEV_OC:
8573 		phba->lpfc_hba_down_post = lpfc_hba_down_post_s4;
8574 		phba->lpfc_handle_eratt = lpfc_handle_eratt_s4;
8575 		phba->lpfc_stop_port = lpfc_stop_port_s4;
8576 		break;
8577 	default:
8578 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8579 				"1431 Invalid HBA PCI-device group: 0x%x\n",
8580 				dev_grp);
8581 		return -ENODEV;
8582 	}
8583 	return 0;
8584 }
8585 
8586 /**
8587  * lpfc_setup_driver_resource_phase2 - Phase2 setup driver internal resources.
8588  * @phba: pointer to lpfc hba data structure.
8589  *
8590  * This routine is invoked to set up the driver internal resources after the
8591  * device specific resource setup to support the HBA device it attached to.
8592  *
8593  * Return codes
8594  * 	0 - successful
8595  * 	other values - error
8596  **/
8597 static int
8598 lpfc_setup_driver_resource_phase2(struct lpfc_hba *phba)
8599 {
8600 	int error;
8601 
8602 	/* Startup the kernel thread for this host adapter. */
8603 	phba->worker_thread = kthread_run(lpfc_do_work, phba,
8604 					  "lpfc_worker_%d", phba->brd_no);
8605 	if (IS_ERR(phba->worker_thread)) {
8606 		error = PTR_ERR(phba->worker_thread);
8607 		return error;
8608 	}
8609 
8610 	return 0;
8611 }
8612 
8613 /**
8614  * lpfc_unset_driver_resource_phase2 - Phase2 unset driver internal resources.
8615  * @phba: pointer to lpfc hba data structure.
8616  *
8617  * This routine is invoked to unset the driver internal resources set up after
8618  * the device specific resource setup for supporting the HBA device it
8619  * attached to.
8620  **/
8621 static void
8622 lpfc_unset_driver_resource_phase2(struct lpfc_hba *phba)
8623 {
8624 	if (phba->wq) {
8625 		destroy_workqueue(phba->wq);
8626 		phba->wq = NULL;
8627 	}
8628 
8629 	/* Stop kernel worker thread */
8630 	if (phba->worker_thread)
8631 		kthread_stop(phba->worker_thread);
8632 }
8633 
8634 /**
8635  * lpfc_free_iocb_list - Free iocb list.
8636  * @phba: pointer to lpfc hba data structure.
8637  *
8638  * This routine is invoked to free the driver's IOCB list and memory.
8639  **/
8640 void
8641 lpfc_free_iocb_list(struct lpfc_hba *phba)
8642 {
8643 	struct lpfc_iocbq *iocbq_entry = NULL, *iocbq_next = NULL;
8644 
8645 	spin_lock_irq(&phba->hbalock);
8646 	list_for_each_entry_safe(iocbq_entry, iocbq_next,
8647 				 &phba->lpfc_iocb_list, list) {
8648 		list_del(&iocbq_entry->list);
8649 		kfree(iocbq_entry);
8650 		phba->total_iocbq_bufs--;
8651 	}
8652 	spin_unlock_irq(&phba->hbalock);
8653 
8654 	return;
8655 }
8656 
8657 /**
8658  * lpfc_init_iocb_list - Allocate and initialize iocb list.
8659  * @phba: pointer to lpfc hba data structure.
8660  * @iocb_count: number of requested iocbs
8661  *
8662  * This routine is invoked to allocate and initizlize the driver's IOCB
8663  * list and set up the IOCB tag array accordingly.
8664  *
8665  * Return codes
8666  *	0 - successful
8667  *	other values - error
8668  **/
8669 int
8670 lpfc_init_iocb_list(struct lpfc_hba *phba, int iocb_count)
8671 {
8672 	struct lpfc_iocbq *iocbq_entry = NULL;
8673 	uint16_t iotag;
8674 	int i;
8675 
8676 	/* Initialize and populate the iocb list per host.  */
8677 	INIT_LIST_HEAD(&phba->lpfc_iocb_list);
8678 	for (i = 0; i < iocb_count; i++) {
8679 		iocbq_entry = kzalloc(sizeof(struct lpfc_iocbq), GFP_KERNEL);
8680 		if (iocbq_entry == NULL) {
8681 			printk(KERN_ERR "%s: only allocated %d iocbs of "
8682 				"expected %d count. Unloading driver.\n",
8683 				__func__, i, iocb_count);
8684 			goto out_free_iocbq;
8685 		}
8686 
8687 		iotag = lpfc_sli_next_iotag(phba, iocbq_entry);
8688 		if (iotag == 0) {
8689 			kfree(iocbq_entry);
8690 			printk(KERN_ERR "%s: failed to allocate IOTAG. "
8691 				"Unloading driver.\n", __func__);
8692 			goto out_free_iocbq;
8693 		}
8694 		iocbq_entry->sli4_lxritag = NO_XRI;
8695 		iocbq_entry->sli4_xritag = NO_XRI;
8696 
8697 		spin_lock_irq(&phba->hbalock);
8698 		list_add(&iocbq_entry->list, &phba->lpfc_iocb_list);
8699 		phba->total_iocbq_bufs++;
8700 		spin_unlock_irq(&phba->hbalock);
8701 	}
8702 
8703 	return 0;
8704 
8705 out_free_iocbq:
8706 	lpfc_free_iocb_list(phba);
8707 
8708 	return -ENOMEM;
8709 }
8710 
8711 /**
8712  * lpfc_free_sgl_list - Free a given sgl list.
8713  * @phba: pointer to lpfc hba data structure.
8714  * @sglq_list: pointer to the head of sgl list.
8715  *
8716  * This routine is invoked to free a give sgl list and memory.
8717  **/
8718 void
8719 lpfc_free_sgl_list(struct lpfc_hba *phba, struct list_head *sglq_list)
8720 {
8721 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
8722 
8723 	list_for_each_entry_safe(sglq_entry, sglq_next, sglq_list, list) {
8724 		list_del(&sglq_entry->list);
8725 		lpfc_mbuf_free(phba, sglq_entry->virt, sglq_entry->phys);
8726 		kfree(sglq_entry);
8727 	}
8728 }
8729 
8730 /**
8731  * lpfc_free_els_sgl_list - Free els sgl list.
8732  * @phba: pointer to lpfc hba data structure.
8733  *
8734  * This routine is invoked to free the driver's els sgl list and memory.
8735  **/
8736 static void
8737 lpfc_free_els_sgl_list(struct lpfc_hba *phba)
8738 {
8739 	LIST_HEAD(sglq_list);
8740 
8741 	/* Retrieve all els sgls from driver list */
8742 	spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
8743 	list_splice_init(&phba->sli4_hba.lpfc_els_sgl_list, &sglq_list);
8744 	spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
8745 
8746 	/* Now free the sgl list */
8747 	lpfc_free_sgl_list(phba, &sglq_list);
8748 }
8749 
8750 /**
8751  * lpfc_free_nvmet_sgl_list - Free nvmet sgl list.
8752  * @phba: pointer to lpfc hba data structure.
8753  *
8754  * This routine is invoked to free the driver's nvmet sgl list and memory.
8755  **/
8756 static void
8757 lpfc_free_nvmet_sgl_list(struct lpfc_hba *phba)
8758 {
8759 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
8760 	LIST_HEAD(sglq_list);
8761 
8762 	/* Retrieve all nvmet sgls from driver list */
8763 	spin_lock_irq(&phba->hbalock);
8764 	spin_lock(&phba->sli4_hba.sgl_list_lock);
8765 	list_splice_init(&phba->sli4_hba.lpfc_nvmet_sgl_list, &sglq_list);
8766 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
8767 	spin_unlock_irq(&phba->hbalock);
8768 
8769 	/* Now free the sgl list */
8770 	list_for_each_entry_safe(sglq_entry, sglq_next, &sglq_list, list) {
8771 		list_del(&sglq_entry->list);
8772 		lpfc_nvmet_buf_free(phba, sglq_entry->virt, sglq_entry->phys);
8773 		kfree(sglq_entry);
8774 	}
8775 
8776 	/* Update the nvmet_xri_cnt to reflect no current sgls.
8777 	 * The next initialization cycle sets the count and allocates
8778 	 * the sgls over again.
8779 	 */
8780 	phba->sli4_hba.nvmet_xri_cnt = 0;
8781 }
8782 
8783 /**
8784  * lpfc_init_active_sgl_array - Allocate the buf to track active ELS XRIs.
8785  * @phba: pointer to lpfc hba data structure.
8786  *
8787  * This routine is invoked to allocate the driver's active sgl memory.
8788  * This array will hold the sglq_entry's for active IOs.
8789  **/
8790 static int
8791 lpfc_init_active_sgl_array(struct lpfc_hba *phba)
8792 {
8793 	int size;
8794 	size = sizeof(struct lpfc_sglq *);
8795 	size *= phba->sli4_hba.max_cfg_param.max_xri;
8796 
8797 	phba->sli4_hba.lpfc_sglq_active_list =
8798 		kzalloc(size, GFP_KERNEL);
8799 	if (!phba->sli4_hba.lpfc_sglq_active_list)
8800 		return -ENOMEM;
8801 	return 0;
8802 }
8803 
8804 /**
8805  * lpfc_free_active_sgl - Free the buf that tracks active ELS XRIs.
8806  * @phba: pointer to lpfc hba data structure.
8807  *
8808  * This routine is invoked to walk through the array of active sglq entries
8809  * and free all of the resources.
8810  * This is just a place holder for now.
8811  **/
8812 static void
8813 lpfc_free_active_sgl(struct lpfc_hba *phba)
8814 {
8815 	kfree(phba->sli4_hba.lpfc_sglq_active_list);
8816 }
8817 
8818 /**
8819  * lpfc_init_sgl_list - Allocate and initialize sgl list.
8820  * @phba: pointer to lpfc hba data structure.
8821  *
8822  * This routine is invoked to allocate and initizlize the driver's sgl
8823  * list and set up the sgl xritag tag array accordingly.
8824  *
8825  **/
8826 static void
8827 lpfc_init_sgl_list(struct lpfc_hba *phba)
8828 {
8829 	/* Initialize and populate the sglq list per host/VF. */
8830 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_els_sgl_list);
8831 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_els_sgl_list);
8832 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_nvmet_sgl_list);
8833 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
8834 
8835 	/* els xri-sgl book keeping */
8836 	phba->sli4_hba.els_xri_cnt = 0;
8837 
8838 	/* nvme xri-buffer book keeping */
8839 	phba->sli4_hba.io_xri_cnt = 0;
8840 }
8841 
8842 /**
8843  * lpfc_sli4_init_rpi_hdrs - Post the rpi header memory region to the port
8844  * @phba: pointer to lpfc hba data structure.
8845  *
8846  * This routine is invoked to post rpi header templates to the
8847  * port for those SLI4 ports that do not support extents.  This routine
8848  * posts a PAGE_SIZE memory region to the port to hold up to
8849  * PAGE_SIZE modulo 64 rpi context headers.  This is an initialization routine
8850  * and should be called only when interrupts are disabled.
8851  *
8852  * Return codes
8853  * 	0 - successful
8854  *	-ERROR - otherwise.
8855  **/
8856 int
8857 lpfc_sli4_init_rpi_hdrs(struct lpfc_hba *phba)
8858 {
8859 	int rc = 0;
8860 	struct lpfc_rpi_hdr *rpi_hdr;
8861 
8862 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_rpi_hdr_list);
8863 	if (!phba->sli4_hba.rpi_hdrs_in_use)
8864 		return rc;
8865 	if (phba->sli4_hba.extents_in_use)
8866 		return -EIO;
8867 
8868 	rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
8869 	if (!rpi_hdr) {
8870 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8871 				"0391 Error during rpi post operation\n");
8872 		lpfc_sli4_remove_rpis(phba);
8873 		rc = -ENODEV;
8874 	}
8875 
8876 	return rc;
8877 }
8878 
8879 /**
8880  * lpfc_sli4_create_rpi_hdr - Allocate an rpi header memory region
8881  * @phba: pointer to lpfc hba data structure.
8882  *
8883  * This routine is invoked to allocate a single 4KB memory region to
8884  * support rpis and stores them in the phba.  This single region
8885  * provides support for up to 64 rpis.  The region is used globally
8886  * by the device.
8887  *
8888  * Returns:
8889  *   A valid rpi hdr on success.
8890  *   A NULL pointer on any failure.
8891  **/
8892 struct lpfc_rpi_hdr *
8893 lpfc_sli4_create_rpi_hdr(struct lpfc_hba *phba)
8894 {
8895 	uint16_t rpi_limit, curr_rpi_range;
8896 	struct lpfc_dmabuf *dmabuf;
8897 	struct lpfc_rpi_hdr *rpi_hdr;
8898 
8899 	/*
8900 	 * If the SLI4 port supports extents, posting the rpi header isn't
8901 	 * required.  Set the expected maximum count and let the actual value
8902 	 * get set when extents are fully allocated.
8903 	 */
8904 	if (!phba->sli4_hba.rpi_hdrs_in_use)
8905 		return NULL;
8906 	if (phba->sli4_hba.extents_in_use)
8907 		return NULL;
8908 
8909 	/* The limit on the logical index is just the max_rpi count. */
8910 	rpi_limit = phba->sli4_hba.max_cfg_param.max_rpi;
8911 
8912 	spin_lock_irq(&phba->hbalock);
8913 	/*
8914 	 * Establish the starting RPI in this header block.  The starting
8915 	 * rpi is normalized to a zero base because the physical rpi is
8916 	 * port based.
8917 	 */
8918 	curr_rpi_range = phba->sli4_hba.next_rpi;
8919 	spin_unlock_irq(&phba->hbalock);
8920 
8921 	/* Reached full RPI range */
8922 	if (curr_rpi_range == rpi_limit)
8923 		return NULL;
8924 
8925 	/*
8926 	 * First allocate the protocol header region for the port.  The
8927 	 * port expects a 4KB DMA-mapped memory region that is 4K aligned.
8928 	 */
8929 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
8930 	if (!dmabuf)
8931 		return NULL;
8932 
8933 	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
8934 					  LPFC_HDR_TEMPLATE_SIZE,
8935 					  &dmabuf->phys, GFP_KERNEL);
8936 	if (!dmabuf->virt) {
8937 		rpi_hdr = NULL;
8938 		goto err_free_dmabuf;
8939 	}
8940 
8941 	if (!IS_ALIGNED(dmabuf->phys, LPFC_HDR_TEMPLATE_SIZE)) {
8942 		rpi_hdr = NULL;
8943 		goto err_free_coherent;
8944 	}
8945 
8946 	/* Save the rpi header data for cleanup later. */
8947 	rpi_hdr = kzalloc(sizeof(struct lpfc_rpi_hdr), GFP_KERNEL);
8948 	if (!rpi_hdr)
8949 		goto err_free_coherent;
8950 
8951 	rpi_hdr->dmabuf = dmabuf;
8952 	rpi_hdr->len = LPFC_HDR_TEMPLATE_SIZE;
8953 	rpi_hdr->page_count = 1;
8954 	spin_lock_irq(&phba->hbalock);
8955 
8956 	/* The rpi_hdr stores the logical index only. */
8957 	rpi_hdr->start_rpi = curr_rpi_range;
8958 	rpi_hdr->next_rpi = phba->sli4_hba.next_rpi + LPFC_RPI_HDR_COUNT;
8959 	list_add_tail(&rpi_hdr->list, &phba->sli4_hba.lpfc_rpi_hdr_list);
8960 
8961 	spin_unlock_irq(&phba->hbalock);
8962 	return rpi_hdr;
8963 
8964  err_free_coherent:
8965 	dma_free_coherent(&phba->pcidev->dev, LPFC_HDR_TEMPLATE_SIZE,
8966 			  dmabuf->virt, dmabuf->phys);
8967  err_free_dmabuf:
8968 	kfree(dmabuf);
8969 	return NULL;
8970 }
8971 
8972 /**
8973  * lpfc_sli4_remove_rpi_hdrs - Remove all rpi header memory regions
8974  * @phba: pointer to lpfc hba data structure.
8975  *
8976  * This routine is invoked to remove all memory resources allocated
8977  * to support rpis for SLI4 ports not supporting extents. This routine
8978  * presumes the caller has released all rpis consumed by fabric or port
8979  * logins and is prepared to have the header pages removed.
8980  **/
8981 void
8982 lpfc_sli4_remove_rpi_hdrs(struct lpfc_hba *phba)
8983 {
8984 	struct lpfc_rpi_hdr *rpi_hdr, *next_rpi_hdr;
8985 
8986 	if (!phba->sli4_hba.rpi_hdrs_in_use)
8987 		goto exit;
8988 
8989 	list_for_each_entry_safe(rpi_hdr, next_rpi_hdr,
8990 				 &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
8991 		list_del(&rpi_hdr->list);
8992 		dma_free_coherent(&phba->pcidev->dev, rpi_hdr->len,
8993 				  rpi_hdr->dmabuf->virt, rpi_hdr->dmabuf->phys);
8994 		kfree(rpi_hdr->dmabuf);
8995 		kfree(rpi_hdr);
8996 	}
8997  exit:
8998 	/* There are no rpis available to the port now. */
8999 	phba->sli4_hba.next_rpi = 0;
9000 }
9001 
9002 /**
9003  * lpfc_hba_alloc - Allocate driver hba data structure for a device.
9004  * @pdev: pointer to pci device data structure.
9005  *
9006  * This routine is invoked to allocate the driver hba data structure for an
9007  * HBA device. If the allocation is successful, the phba reference to the
9008  * PCI device data structure is set.
9009  *
9010  * Return codes
9011  *      pointer to @phba - successful
9012  *      NULL - error
9013  **/
9014 static struct lpfc_hba *
9015 lpfc_hba_alloc(struct pci_dev *pdev)
9016 {
9017 	struct lpfc_hba *phba;
9018 
9019 	/* Allocate memory for HBA structure */
9020 	phba = kzalloc(sizeof(struct lpfc_hba), GFP_KERNEL);
9021 	if (!phba) {
9022 		dev_err(&pdev->dev, "failed to allocate hba struct\n");
9023 		return NULL;
9024 	}
9025 
9026 	/* Set reference to PCI device in HBA structure */
9027 	phba->pcidev = pdev;
9028 
9029 	/* Assign an unused board number */
9030 	phba->brd_no = lpfc_get_instance();
9031 	if (phba->brd_no < 0) {
9032 		kfree(phba);
9033 		return NULL;
9034 	}
9035 	phba->eratt_poll_interval = LPFC_ERATT_POLL_INTERVAL;
9036 
9037 	spin_lock_init(&phba->ct_ev_lock);
9038 	INIT_LIST_HEAD(&phba->ct_ev_waiters);
9039 
9040 	return phba;
9041 }
9042 
9043 /**
9044  * lpfc_hba_free - Free driver hba data structure with a device.
9045  * @phba: pointer to lpfc hba data structure.
9046  *
9047  * This routine is invoked to free the driver hba data structure with an
9048  * HBA device.
9049  **/
9050 static void
9051 lpfc_hba_free(struct lpfc_hba *phba)
9052 {
9053 	if (phba->sli_rev == LPFC_SLI_REV4)
9054 		kfree(phba->sli4_hba.hdwq);
9055 
9056 	/* Release the driver assigned board number */
9057 	idr_remove(&lpfc_hba_index, phba->brd_no);
9058 
9059 	/* Free memory allocated with sli3 rings */
9060 	kfree(phba->sli.sli3_ring);
9061 	phba->sli.sli3_ring = NULL;
9062 
9063 	kfree(phba);
9064 	return;
9065 }
9066 
9067 /**
9068  * lpfc_setup_fdmi_mask - Setup initial FDMI mask for HBA and Port attributes
9069  * @vport: pointer to lpfc vport data structure.
9070  *
9071  * This routine is will setup initial FDMI attribute masks for
9072  * FDMI2 or SmartSAN depending on module parameters. The driver will attempt
9073  * to get these attributes first before falling back, the attribute
9074  * fallback hierarchy is SmartSAN -> FDMI2 -> FMDI1
9075  **/
9076 void
9077 lpfc_setup_fdmi_mask(struct lpfc_vport *vport)
9078 {
9079 	struct lpfc_hba *phba = vport->phba;
9080 
9081 	set_bit(FC_ALLOW_FDMI, &vport->load_flag);
9082 	if (phba->cfg_enable_SmartSAN ||
9083 	    phba->cfg_fdmi_on == LPFC_FDMI_SUPPORT) {
9084 		/* Setup appropriate attribute masks */
9085 		vport->fdmi_hba_mask = LPFC_FDMI2_HBA_ATTR;
9086 		if (phba->cfg_enable_SmartSAN)
9087 			vport->fdmi_port_mask = LPFC_FDMI2_SMART_ATTR;
9088 		else
9089 			vport->fdmi_port_mask = LPFC_FDMI2_PORT_ATTR;
9090 	}
9091 
9092 	lpfc_printf_log(phba, KERN_INFO, LOG_DISCOVERY,
9093 			"6077 Setup FDMI mask: hba x%x port x%x\n",
9094 			vport->fdmi_hba_mask, vport->fdmi_port_mask);
9095 }
9096 
9097 /**
9098  * lpfc_create_shost - Create hba physical port with associated scsi host.
9099  * @phba: pointer to lpfc hba data structure.
9100  *
9101  * This routine is invoked to create HBA physical port and associate a SCSI
9102  * host with it.
9103  *
9104  * Return codes
9105  *      0 - successful
9106  *      other values - error
9107  **/
9108 static int
9109 lpfc_create_shost(struct lpfc_hba *phba)
9110 {
9111 	struct lpfc_vport *vport;
9112 	struct Scsi_Host  *shost;
9113 
9114 	/* Initialize HBA FC structure */
9115 	phba->fc_edtov = FF_DEF_EDTOV;
9116 	phba->fc_ratov = FF_DEF_RATOV;
9117 	phba->fc_altov = FF_DEF_ALTOV;
9118 	phba->fc_arbtov = FF_DEF_ARBTOV;
9119 
9120 	atomic_set(&phba->sdev_cnt, 0);
9121 	vport = lpfc_create_port(phba, phba->brd_no, &phba->pcidev->dev);
9122 	if (!vport)
9123 		return -ENODEV;
9124 
9125 	shost = lpfc_shost_from_vport(vport);
9126 	phba->pport = vport;
9127 
9128 	if (phba->nvmet_support) {
9129 		/* Only 1 vport (pport) will support NVME target */
9130 		phba->targetport = NULL;
9131 		phba->cfg_enable_fc4_type = LPFC_ENABLE_NVME;
9132 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_NVME_DISC,
9133 				"6076 NVME Target Found\n");
9134 	}
9135 
9136 	lpfc_debugfs_initialize(vport);
9137 	/* Put reference to SCSI host to driver's device private data */
9138 	pci_set_drvdata(phba->pcidev, shost);
9139 
9140 	lpfc_setup_fdmi_mask(vport);
9141 
9142 	/*
9143 	 * At this point we are fully registered with PSA. In addition,
9144 	 * any initial discovery should be completed.
9145 	 */
9146 	return 0;
9147 }
9148 
9149 /**
9150  * lpfc_destroy_shost - Destroy hba physical port with associated scsi host.
9151  * @phba: pointer to lpfc hba data structure.
9152  *
9153  * This routine is invoked to destroy HBA physical port and the associated
9154  * SCSI host.
9155  **/
9156 static void
9157 lpfc_destroy_shost(struct lpfc_hba *phba)
9158 {
9159 	struct lpfc_vport *vport = phba->pport;
9160 
9161 	/* Destroy physical port that associated with the SCSI host */
9162 	destroy_port(vport);
9163 
9164 	return;
9165 }
9166 
9167 /**
9168  * lpfc_setup_bg - Setup Block guard structures and debug areas.
9169  * @phba: pointer to lpfc hba data structure.
9170  * @shost: the shost to be used to detect Block guard settings.
9171  *
9172  * This routine sets up the local Block guard protocol settings for @shost.
9173  * This routine also allocates memory for debugging bg buffers.
9174  **/
9175 static void
9176 lpfc_setup_bg(struct lpfc_hba *phba, struct Scsi_Host *shost)
9177 {
9178 	uint32_t old_mask;
9179 	uint32_t old_guard;
9180 
9181 	if (phba->cfg_prot_mask && phba->cfg_prot_guard) {
9182 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9183 				"1478 Registering BlockGuard with the "
9184 				"SCSI layer\n");
9185 
9186 		old_mask = phba->cfg_prot_mask;
9187 		old_guard = phba->cfg_prot_guard;
9188 
9189 		/* Only allow supported values */
9190 		phba->cfg_prot_mask &= (SHOST_DIF_TYPE1_PROTECTION |
9191 			SHOST_DIX_TYPE0_PROTECTION |
9192 			SHOST_DIX_TYPE1_PROTECTION);
9193 		phba->cfg_prot_guard &= (SHOST_DIX_GUARD_IP |
9194 					 SHOST_DIX_GUARD_CRC);
9195 
9196 		/* DIF Type 1 protection for profiles AST1/C1 is end to end */
9197 		if (phba->cfg_prot_mask == SHOST_DIX_TYPE1_PROTECTION)
9198 			phba->cfg_prot_mask |= SHOST_DIF_TYPE1_PROTECTION;
9199 
9200 		if (phba->cfg_prot_mask && phba->cfg_prot_guard) {
9201 			if ((old_mask != phba->cfg_prot_mask) ||
9202 				(old_guard != phba->cfg_prot_guard))
9203 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9204 					"1475 Registering BlockGuard with the "
9205 					"SCSI layer: mask %d  guard %d\n",
9206 					phba->cfg_prot_mask,
9207 					phba->cfg_prot_guard);
9208 
9209 			scsi_host_set_prot(shost, phba->cfg_prot_mask);
9210 			scsi_host_set_guard(shost, phba->cfg_prot_guard);
9211 		} else
9212 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9213 				"1479 Not Registering BlockGuard with the SCSI "
9214 				"layer, Bad protection parameters: %d %d\n",
9215 				old_mask, old_guard);
9216 	}
9217 }
9218 
9219 /**
9220  * lpfc_post_init_setup - Perform necessary device post initialization setup.
9221  * @phba: pointer to lpfc hba data structure.
9222  *
9223  * This routine is invoked to perform all the necessary post initialization
9224  * setup for the device.
9225  **/
9226 static void
9227 lpfc_post_init_setup(struct lpfc_hba *phba)
9228 {
9229 	struct Scsi_Host  *shost;
9230 	struct lpfc_adapter_event_header adapter_event;
9231 
9232 	/* Get the default values for Model Name and Description */
9233 	lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
9234 
9235 	/*
9236 	 * hba setup may have changed the hba_queue_depth so we need to
9237 	 * adjust the value of can_queue.
9238 	 */
9239 	shost = pci_get_drvdata(phba->pcidev);
9240 	shost->can_queue = phba->cfg_hba_queue_depth - 10;
9241 
9242 	lpfc_host_attrib_init(shost);
9243 
9244 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
9245 		spin_lock_irq(shost->host_lock);
9246 		lpfc_poll_start_timer(phba);
9247 		spin_unlock_irq(shost->host_lock);
9248 	}
9249 
9250 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9251 			"0428 Perform SCSI scan\n");
9252 	/* Send board arrival event to upper layer */
9253 	adapter_event.event_type = FC_REG_ADAPTER_EVENT;
9254 	adapter_event.subcategory = LPFC_EVENT_ARRIVAL;
9255 	fc_host_post_vendor_event(shost, fc_get_event_number(),
9256 				  sizeof(adapter_event),
9257 				  (char *) &adapter_event,
9258 				  LPFC_NL_VENDOR_ID);
9259 	return;
9260 }
9261 
9262 /**
9263  * lpfc_sli_pci_mem_setup - Setup SLI3 HBA PCI memory space.
9264  * @phba: pointer to lpfc hba data structure.
9265  *
9266  * This routine is invoked to set up the PCI device memory space for device
9267  * with SLI-3 interface spec.
9268  *
9269  * Return codes
9270  * 	0 - successful
9271  * 	other values - error
9272  **/
9273 static int
9274 lpfc_sli_pci_mem_setup(struct lpfc_hba *phba)
9275 {
9276 	struct pci_dev *pdev = phba->pcidev;
9277 	unsigned long bar0map_len, bar2map_len;
9278 	int i, hbq_count;
9279 	void *ptr;
9280 	int error;
9281 
9282 	if (!pdev)
9283 		return -ENODEV;
9284 
9285 	/* Set the device DMA mask size */
9286 	error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
9287 	if (error)
9288 		error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32));
9289 	if (error)
9290 		return error;
9291 	error = -ENODEV;
9292 
9293 	/* Get the bus address of Bar0 and Bar2 and the number of bytes
9294 	 * required by each mapping.
9295 	 */
9296 	phba->pci_bar0_map = pci_resource_start(pdev, 0);
9297 	bar0map_len = pci_resource_len(pdev, 0);
9298 
9299 	phba->pci_bar2_map = pci_resource_start(pdev, 2);
9300 	bar2map_len = pci_resource_len(pdev, 2);
9301 
9302 	/* Map HBA SLIM to a kernel virtual address. */
9303 	phba->slim_memmap_p = ioremap(phba->pci_bar0_map, bar0map_len);
9304 	if (!phba->slim_memmap_p) {
9305 		dev_printk(KERN_ERR, &pdev->dev,
9306 			   "ioremap failed for SLIM memory.\n");
9307 		goto out;
9308 	}
9309 
9310 	/* Map HBA Control Registers to a kernel virtual address. */
9311 	phba->ctrl_regs_memmap_p = ioremap(phba->pci_bar2_map, bar2map_len);
9312 	if (!phba->ctrl_regs_memmap_p) {
9313 		dev_printk(KERN_ERR, &pdev->dev,
9314 			   "ioremap failed for HBA control registers.\n");
9315 		goto out_iounmap_slim;
9316 	}
9317 
9318 	/* Allocate memory for SLI-2 structures */
9319 	phba->slim2p.virt = dma_alloc_coherent(&pdev->dev, SLI2_SLIM_SIZE,
9320 					       &phba->slim2p.phys, GFP_KERNEL);
9321 	if (!phba->slim2p.virt)
9322 		goto out_iounmap;
9323 
9324 	phba->mbox = phba->slim2p.virt + offsetof(struct lpfc_sli2_slim, mbx);
9325 	phba->mbox_ext = (phba->slim2p.virt +
9326 		offsetof(struct lpfc_sli2_slim, mbx_ext_words));
9327 	phba->pcb = (phba->slim2p.virt + offsetof(struct lpfc_sli2_slim, pcb));
9328 	phba->IOCBs = (phba->slim2p.virt +
9329 		       offsetof(struct lpfc_sli2_slim, IOCBs));
9330 
9331 	phba->hbqslimp.virt = dma_alloc_coherent(&pdev->dev,
9332 						 lpfc_sli_hbq_size(),
9333 						 &phba->hbqslimp.phys,
9334 						 GFP_KERNEL);
9335 	if (!phba->hbqslimp.virt)
9336 		goto out_free_slim;
9337 
9338 	hbq_count = lpfc_sli_hbq_count();
9339 	ptr = phba->hbqslimp.virt;
9340 	for (i = 0; i < hbq_count; ++i) {
9341 		phba->hbqs[i].hbq_virt = ptr;
9342 		INIT_LIST_HEAD(&phba->hbqs[i].hbq_buffer_list);
9343 		ptr += (lpfc_hbq_defs[i]->entry_count *
9344 			sizeof(struct lpfc_hbq_entry));
9345 	}
9346 	phba->hbqs[LPFC_ELS_HBQ].hbq_alloc_buffer = lpfc_els_hbq_alloc;
9347 	phba->hbqs[LPFC_ELS_HBQ].hbq_free_buffer = lpfc_els_hbq_free;
9348 
9349 	memset(phba->hbqslimp.virt, 0, lpfc_sli_hbq_size());
9350 
9351 	phba->MBslimaddr = phba->slim_memmap_p;
9352 	phba->HAregaddr = phba->ctrl_regs_memmap_p + HA_REG_OFFSET;
9353 	phba->CAregaddr = phba->ctrl_regs_memmap_p + CA_REG_OFFSET;
9354 	phba->HSregaddr = phba->ctrl_regs_memmap_p + HS_REG_OFFSET;
9355 	phba->HCregaddr = phba->ctrl_regs_memmap_p + HC_REG_OFFSET;
9356 
9357 	return 0;
9358 
9359 out_free_slim:
9360 	dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
9361 			  phba->slim2p.virt, phba->slim2p.phys);
9362 out_iounmap:
9363 	iounmap(phba->ctrl_regs_memmap_p);
9364 out_iounmap_slim:
9365 	iounmap(phba->slim_memmap_p);
9366 out:
9367 	return error;
9368 }
9369 
9370 /**
9371  * lpfc_sli_pci_mem_unset - Unset SLI3 HBA PCI memory space.
9372  * @phba: pointer to lpfc hba data structure.
9373  *
9374  * This routine is invoked to unset the PCI device memory space for device
9375  * with SLI-3 interface spec.
9376  **/
9377 static void
9378 lpfc_sli_pci_mem_unset(struct lpfc_hba *phba)
9379 {
9380 	struct pci_dev *pdev;
9381 
9382 	/* Obtain PCI device reference */
9383 	if (!phba->pcidev)
9384 		return;
9385 	else
9386 		pdev = phba->pcidev;
9387 
9388 	/* Free coherent DMA memory allocated */
9389 	dma_free_coherent(&pdev->dev, lpfc_sli_hbq_size(),
9390 			  phba->hbqslimp.virt, phba->hbqslimp.phys);
9391 	dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
9392 			  phba->slim2p.virt, phba->slim2p.phys);
9393 
9394 	/* I/O memory unmap */
9395 	iounmap(phba->ctrl_regs_memmap_p);
9396 	iounmap(phba->slim_memmap_p);
9397 
9398 	return;
9399 }
9400 
9401 /**
9402  * lpfc_sli4_post_status_check - Wait for SLI4 POST done and check status
9403  * @phba: pointer to lpfc hba data structure.
9404  *
9405  * This routine is invoked to wait for SLI4 device Power On Self Test (POST)
9406  * done and check status.
9407  *
9408  * Return 0 if successful, otherwise -ENODEV.
9409  **/
9410 int
9411 lpfc_sli4_post_status_check(struct lpfc_hba *phba)
9412 {
9413 	struct lpfc_register portsmphr_reg, uerrlo_reg, uerrhi_reg;
9414 	struct lpfc_register reg_data;
9415 	int i, port_error = 0;
9416 	uint32_t if_type;
9417 
9418 	memset(&portsmphr_reg, 0, sizeof(portsmphr_reg));
9419 	memset(&reg_data, 0, sizeof(reg_data));
9420 	if (!phba->sli4_hba.PSMPHRregaddr)
9421 		return -ENODEV;
9422 
9423 	/* Wait up to 30 seconds for the SLI Port POST done and ready */
9424 	for (i = 0; i < 3000; i++) {
9425 		if (lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
9426 			&portsmphr_reg.word0) ||
9427 			(bf_get(lpfc_port_smphr_perr, &portsmphr_reg))) {
9428 			/* Port has a fatal POST error, break out */
9429 			port_error = -ENODEV;
9430 			break;
9431 		}
9432 		if (LPFC_POST_STAGE_PORT_READY ==
9433 		    bf_get(lpfc_port_smphr_port_status, &portsmphr_reg))
9434 			break;
9435 		msleep(10);
9436 	}
9437 
9438 	/*
9439 	 * If there was a port error during POST, then don't proceed with
9440 	 * other register reads as the data may not be valid.  Just exit.
9441 	 */
9442 	if (port_error) {
9443 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9444 			"1408 Port Failed POST - portsmphr=0x%x, "
9445 			"perr=x%x, sfi=x%x, nip=x%x, ipc=x%x, scr1=x%x, "
9446 			"scr2=x%x, hscratch=x%x, pstatus=x%x\n",
9447 			portsmphr_reg.word0,
9448 			bf_get(lpfc_port_smphr_perr, &portsmphr_reg),
9449 			bf_get(lpfc_port_smphr_sfi, &portsmphr_reg),
9450 			bf_get(lpfc_port_smphr_nip, &portsmphr_reg),
9451 			bf_get(lpfc_port_smphr_ipc, &portsmphr_reg),
9452 			bf_get(lpfc_port_smphr_scr1, &portsmphr_reg),
9453 			bf_get(lpfc_port_smphr_scr2, &portsmphr_reg),
9454 			bf_get(lpfc_port_smphr_host_scratch, &portsmphr_reg),
9455 			bf_get(lpfc_port_smphr_port_status, &portsmphr_reg));
9456 	} else {
9457 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9458 				"2534 Device Info: SLIFamily=0x%x, "
9459 				"SLIRev=0x%x, IFType=0x%x, SLIHint_1=0x%x, "
9460 				"SLIHint_2=0x%x, FT=0x%x\n",
9461 				bf_get(lpfc_sli_intf_sli_family,
9462 				       &phba->sli4_hba.sli_intf),
9463 				bf_get(lpfc_sli_intf_slirev,
9464 				       &phba->sli4_hba.sli_intf),
9465 				bf_get(lpfc_sli_intf_if_type,
9466 				       &phba->sli4_hba.sli_intf),
9467 				bf_get(lpfc_sli_intf_sli_hint1,
9468 				       &phba->sli4_hba.sli_intf),
9469 				bf_get(lpfc_sli_intf_sli_hint2,
9470 				       &phba->sli4_hba.sli_intf),
9471 				bf_get(lpfc_sli_intf_func_type,
9472 				       &phba->sli4_hba.sli_intf));
9473 		/*
9474 		 * Check for other Port errors during the initialization
9475 		 * process.  Fail the load if the port did not come up
9476 		 * correctly.
9477 		 */
9478 		if_type = bf_get(lpfc_sli_intf_if_type,
9479 				 &phba->sli4_hba.sli_intf);
9480 		switch (if_type) {
9481 		case LPFC_SLI_INTF_IF_TYPE_0:
9482 			phba->sli4_hba.ue_mask_lo =
9483 			      readl(phba->sli4_hba.u.if_type0.UEMASKLOregaddr);
9484 			phba->sli4_hba.ue_mask_hi =
9485 			      readl(phba->sli4_hba.u.if_type0.UEMASKHIregaddr);
9486 			uerrlo_reg.word0 =
9487 			      readl(phba->sli4_hba.u.if_type0.UERRLOregaddr);
9488 			uerrhi_reg.word0 =
9489 				readl(phba->sli4_hba.u.if_type0.UERRHIregaddr);
9490 			if ((~phba->sli4_hba.ue_mask_lo & uerrlo_reg.word0) ||
9491 			    (~phba->sli4_hba.ue_mask_hi & uerrhi_reg.word0)) {
9492 				lpfc_printf_log(phba, KERN_ERR,
9493 						LOG_TRACE_EVENT,
9494 						"1422 Unrecoverable Error "
9495 						"Detected during POST "
9496 						"uerr_lo_reg=0x%x, "
9497 						"uerr_hi_reg=0x%x, "
9498 						"ue_mask_lo_reg=0x%x, "
9499 						"ue_mask_hi_reg=0x%x\n",
9500 						uerrlo_reg.word0,
9501 						uerrhi_reg.word0,
9502 						phba->sli4_hba.ue_mask_lo,
9503 						phba->sli4_hba.ue_mask_hi);
9504 				port_error = -ENODEV;
9505 			}
9506 			break;
9507 		case LPFC_SLI_INTF_IF_TYPE_2:
9508 		case LPFC_SLI_INTF_IF_TYPE_6:
9509 			/* Final checks.  The port status should be clean. */
9510 			if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
9511 				&reg_data.word0) ||
9512 				lpfc_sli4_unrecoverable_port(&reg_data)) {
9513 				phba->work_status[0] =
9514 					readl(phba->sli4_hba.u.if_type2.
9515 					      ERR1regaddr);
9516 				phba->work_status[1] =
9517 					readl(phba->sli4_hba.u.if_type2.
9518 					      ERR2regaddr);
9519 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9520 					"2888 Unrecoverable port error "
9521 					"following POST: port status reg "
9522 					"0x%x, port_smphr reg 0x%x, "
9523 					"error 1=0x%x, error 2=0x%x\n",
9524 					reg_data.word0,
9525 					portsmphr_reg.word0,
9526 					phba->work_status[0],
9527 					phba->work_status[1]);
9528 				port_error = -ENODEV;
9529 				break;
9530 			}
9531 
9532 			if (lpfc_pldv_detect &&
9533 			    bf_get(lpfc_sli_intf_sli_family,
9534 				   &phba->sli4_hba.sli_intf) ==
9535 					LPFC_SLI_INTF_FAMILY_G6)
9536 				pci_write_config_byte(phba->pcidev,
9537 						      LPFC_SLI_INTF, CFG_PLD);
9538 			break;
9539 		case LPFC_SLI_INTF_IF_TYPE_1:
9540 		default:
9541 			break;
9542 		}
9543 	}
9544 	return port_error;
9545 }
9546 
9547 /**
9548  * lpfc_sli4_bar0_register_memmap - Set up SLI4 BAR0 register memory map.
9549  * @phba: pointer to lpfc hba data structure.
9550  * @if_type:  The SLI4 interface type getting configured.
9551  *
9552  * This routine is invoked to set up SLI4 BAR0 PCI config space register
9553  * memory map.
9554  **/
9555 static void
9556 lpfc_sli4_bar0_register_memmap(struct lpfc_hba *phba, uint32_t if_type)
9557 {
9558 	switch (if_type) {
9559 	case LPFC_SLI_INTF_IF_TYPE_0:
9560 		phba->sli4_hba.u.if_type0.UERRLOregaddr =
9561 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UERR_STATUS_LO;
9562 		phba->sli4_hba.u.if_type0.UERRHIregaddr =
9563 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UERR_STATUS_HI;
9564 		phba->sli4_hba.u.if_type0.UEMASKLOregaddr =
9565 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UE_MASK_LO;
9566 		phba->sli4_hba.u.if_type0.UEMASKHIregaddr =
9567 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UE_MASK_HI;
9568 		phba->sli4_hba.SLIINTFregaddr =
9569 			phba->sli4_hba.conf_regs_memmap_p + LPFC_SLI_INTF;
9570 		break;
9571 	case LPFC_SLI_INTF_IF_TYPE_2:
9572 		phba->sli4_hba.u.if_type2.EQDregaddr =
9573 			phba->sli4_hba.conf_regs_memmap_p +
9574 						LPFC_CTL_PORT_EQ_DELAY_OFFSET;
9575 		phba->sli4_hba.u.if_type2.ERR1regaddr =
9576 			phba->sli4_hba.conf_regs_memmap_p +
9577 						LPFC_CTL_PORT_ER1_OFFSET;
9578 		phba->sli4_hba.u.if_type2.ERR2regaddr =
9579 			phba->sli4_hba.conf_regs_memmap_p +
9580 						LPFC_CTL_PORT_ER2_OFFSET;
9581 		phba->sli4_hba.u.if_type2.CTRLregaddr =
9582 			phba->sli4_hba.conf_regs_memmap_p +
9583 						LPFC_CTL_PORT_CTL_OFFSET;
9584 		phba->sli4_hba.u.if_type2.STATUSregaddr =
9585 			phba->sli4_hba.conf_regs_memmap_p +
9586 						LPFC_CTL_PORT_STA_OFFSET;
9587 		phba->sli4_hba.SLIINTFregaddr =
9588 			phba->sli4_hba.conf_regs_memmap_p + LPFC_SLI_INTF;
9589 		phba->sli4_hba.PSMPHRregaddr =
9590 			phba->sli4_hba.conf_regs_memmap_p +
9591 						LPFC_CTL_PORT_SEM_OFFSET;
9592 		phba->sli4_hba.RQDBregaddr =
9593 			phba->sli4_hba.conf_regs_memmap_p +
9594 						LPFC_ULP0_RQ_DOORBELL;
9595 		phba->sli4_hba.WQDBregaddr =
9596 			phba->sli4_hba.conf_regs_memmap_p +
9597 						LPFC_ULP0_WQ_DOORBELL;
9598 		phba->sli4_hba.CQDBregaddr =
9599 			phba->sli4_hba.conf_regs_memmap_p + LPFC_EQCQ_DOORBELL;
9600 		phba->sli4_hba.EQDBregaddr = phba->sli4_hba.CQDBregaddr;
9601 		phba->sli4_hba.MQDBregaddr =
9602 			phba->sli4_hba.conf_regs_memmap_p + LPFC_MQ_DOORBELL;
9603 		phba->sli4_hba.BMBXregaddr =
9604 			phba->sli4_hba.conf_regs_memmap_p + LPFC_BMBX;
9605 		break;
9606 	case LPFC_SLI_INTF_IF_TYPE_6:
9607 		phba->sli4_hba.u.if_type2.EQDregaddr =
9608 			phba->sli4_hba.conf_regs_memmap_p +
9609 						LPFC_CTL_PORT_EQ_DELAY_OFFSET;
9610 		phba->sli4_hba.u.if_type2.ERR1regaddr =
9611 			phba->sli4_hba.conf_regs_memmap_p +
9612 						LPFC_CTL_PORT_ER1_OFFSET;
9613 		phba->sli4_hba.u.if_type2.ERR2regaddr =
9614 			phba->sli4_hba.conf_regs_memmap_p +
9615 						LPFC_CTL_PORT_ER2_OFFSET;
9616 		phba->sli4_hba.u.if_type2.CTRLregaddr =
9617 			phba->sli4_hba.conf_regs_memmap_p +
9618 						LPFC_CTL_PORT_CTL_OFFSET;
9619 		phba->sli4_hba.u.if_type2.STATUSregaddr =
9620 			phba->sli4_hba.conf_regs_memmap_p +
9621 						LPFC_CTL_PORT_STA_OFFSET;
9622 		phba->sli4_hba.PSMPHRregaddr =
9623 			phba->sli4_hba.conf_regs_memmap_p +
9624 						LPFC_CTL_PORT_SEM_OFFSET;
9625 		phba->sli4_hba.BMBXregaddr =
9626 			phba->sli4_hba.conf_regs_memmap_p + LPFC_BMBX;
9627 		break;
9628 	case LPFC_SLI_INTF_IF_TYPE_1:
9629 	default:
9630 		dev_printk(KERN_ERR, &phba->pcidev->dev,
9631 			   "FATAL - unsupported SLI4 interface type - %d\n",
9632 			   if_type);
9633 		break;
9634 	}
9635 }
9636 
9637 /**
9638  * lpfc_sli4_bar1_register_memmap - Set up SLI4 BAR1 register memory map.
9639  * @phba: pointer to lpfc hba data structure.
9640  * @if_type: sli if type to operate on.
9641  *
9642  * This routine is invoked to set up SLI4 BAR1 register memory map.
9643  **/
9644 static void
9645 lpfc_sli4_bar1_register_memmap(struct lpfc_hba *phba, uint32_t if_type)
9646 {
9647 	switch (if_type) {
9648 	case LPFC_SLI_INTF_IF_TYPE_0:
9649 		phba->sli4_hba.PSMPHRregaddr =
9650 			phba->sli4_hba.ctrl_regs_memmap_p +
9651 			LPFC_SLIPORT_IF0_SMPHR;
9652 		phba->sli4_hba.ISRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
9653 			LPFC_HST_ISR0;
9654 		phba->sli4_hba.IMRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
9655 			LPFC_HST_IMR0;
9656 		phba->sli4_hba.ISCRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
9657 			LPFC_HST_ISCR0;
9658 		break;
9659 	case LPFC_SLI_INTF_IF_TYPE_6:
9660 		phba->sli4_hba.RQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9661 			LPFC_IF6_RQ_DOORBELL;
9662 		phba->sli4_hba.WQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9663 			LPFC_IF6_WQ_DOORBELL;
9664 		phba->sli4_hba.CQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9665 			LPFC_IF6_CQ_DOORBELL;
9666 		phba->sli4_hba.EQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9667 			LPFC_IF6_EQ_DOORBELL;
9668 		phba->sli4_hba.MQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9669 			LPFC_IF6_MQ_DOORBELL;
9670 		break;
9671 	case LPFC_SLI_INTF_IF_TYPE_2:
9672 	case LPFC_SLI_INTF_IF_TYPE_1:
9673 	default:
9674 		dev_err(&phba->pcidev->dev,
9675 			   "FATAL - unsupported SLI4 interface type - %d\n",
9676 			   if_type);
9677 		break;
9678 	}
9679 }
9680 
9681 /**
9682  * lpfc_sli4_bar2_register_memmap - Set up SLI4 BAR2 register memory map.
9683  * @phba: pointer to lpfc hba data structure.
9684  * @vf: virtual function number
9685  *
9686  * This routine is invoked to set up SLI4 BAR2 doorbell register memory map
9687  * based on the given viftual function number, @vf.
9688  *
9689  * Return 0 if successful, otherwise -ENODEV.
9690  **/
9691 static int
9692 lpfc_sli4_bar2_register_memmap(struct lpfc_hba *phba, uint32_t vf)
9693 {
9694 	if (vf > LPFC_VIR_FUNC_MAX)
9695 		return -ENODEV;
9696 
9697 	phba->sli4_hba.RQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9698 				vf * LPFC_VFR_PAGE_SIZE +
9699 					LPFC_ULP0_RQ_DOORBELL);
9700 	phba->sli4_hba.WQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9701 				vf * LPFC_VFR_PAGE_SIZE +
9702 					LPFC_ULP0_WQ_DOORBELL);
9703 	phba->sli4_hba.CQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9704 				vf * LPFC_VFR_PAGE_SIZE +
9705 					LPFC_EQCQ_DOORBELL);
9706 	phba->sli4_hba.EQDBregaddr = phba->sli4_hba.CQDBregaddr;
9707 	phba->sli4_hba.MQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9708 				vf * LPFC_VFR_PAGE_SIZE + LPFC_MQ_DOORBELL);
9709 	phba->sli4_hba.BMBXregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9710 				vf * LPFC_VFR_PAGE_SIZE + LPFC_BMBX);
9711 	return 0;
9712 }
9713 
9714 /**
9715  * lpfc_create_bootstrap_mbox - Create the bootstrap mailbox
9716  * @phba: pointer to lpfc hba data structure.
9717  *
9718  * This routine is invoked to create the bootstrap mailbox
9719  * region consistent with the SLI-4 interface spec.  This
9720  * routine allocates all memory necessary to communicate
9721  * mailbox commands to the port and sets up all alignment
9722  * needs.  No locks are expected to be held when calling
9723  * this routine.
9724  *
9725  * Return codes
9726  * 	0 - successful
9727  * 	-ENOMEM - could not allocated memory.
9728  **/
9729 static int
9730 lpfc_create_bootstrap_mbox(struct lpfc_hba *phba)
9731 {
9732 	uint32_t bmbx_size;
9733 	struct lpfc_dmabuf *dmabuf;
9734 	struct dma_address *dma_address;
9735 	uint32_t pa_addr;
9736 	uint64_t phys_addr;
9737 
9738 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
9739 	if (!dmabuf)
9740 		return -ENOMEM;
9741 
9742 	/*
9743 	 * The bootstrap mailbox region is comprised of 2 parts
9744 	 * plus an alignment restriction of 16 bytes.
9745 	 */
9746 	bmbx_size = sizeof(struct lpfc_bmbx_create) + (LPFC_ALIGN_16_BYTE - 1);
9747 	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev, bmbx_size,
9748 					  &dmabuf->phys, GFP_KERNEL);
9749 	if (!dmabuf->virt) {
9750 		kfree(dmabuf);
9751 		return -ENOMEM;
9752 	}
9753 
9754 	/*
9755 	 * Initialize the bootstrap mailbox pointers now so that the register
9756 	 * operations are simple later.  The mailbox dma address is required
9757 	 * to be 16-byte aligned.  Also align the virtual memory as each
9758 	 * maibox is copied into the bmbx mailbox region before issuing the
9759 	 * command to the port.
9760 	 */
9761 	phba->sli4_hba.bmbx.dmabuf = dmabuf;
9762 	phba->sli4_hba.bmbx.bmbx_size = bmbx_size;
9763 
9764 	phba->sli4_hba.bmbx.avirt = PTR_ALIGN(dmabuf->virt,
9765 					      LPFC_ALIGN_16_BYTE);
9766 	phba->sli4_hba.bmbx.aphys = ALIGN(dmabuf->phys,
9767 					      LPFC_ALIGN_16_BYTE);
9768 
9769 	/*
9770 	 * Set the high and low physical addresses now.  The SLI4 alignment
9771 	 * requirement is 16 bytes and the mailbox is posted to the port
9772 	 * as two 30-bit addresses.  The other data is a bit marking whether
9773 	 * the 30-bit address is the high or low address.
9774 	 * Upcast bmbx aphys to 64bits so shift instruction compiles
9775 	 * clean on 32 bit machines.
9776 	 */
9777 	dma_address = &phba->sli4_hba.bmbx.dma_address;
9778 	phys_addr = (uint64_t)phba->sli4_hba.bmbx.aphys;
9779 	pa_addr = (uint32_t) ((phys_addr >> 34) & 0x3fffffff);
9780 	dma_address->addr_hi = (uint32_t) ((pa_addr << 2) |
9781 					   LPFC_BMBX_BIT1_ADDR_HI);
9782 
9783 	pa_addr = (uint32_t) ((phba->sli4_hba.bmbx.aphys >> 4) & 0x3fffffff);
9784 	dma_address->addr_lo = (uint32_t) ((pa_addr << 2) |
9785 					   LPFC_BMBX_BIT1_ADDR_LO);
9786 	return 0;
9787 }
9788 
9789 /**
9790  * lpfc_destroy_bootstrap_mbox - Destroy all bootstrap mailbox resources
9791  * @phba: pointer to lpfc hba data structure.
9792  *
9793  * This routine is invoked to teardown the bootstrap mailbox
9794  * region and release all host resources. This routine requires
9795  * the caller to ensure all mailbox commands recovered, no
9796  * additional mailbox comands are sent, and interrupts are disabled
9797  * before calling this routine.
9798  *
9799  **/
9800 static void
9801 lpfc_destroy_bootstrap_mbox(struct lpfc_hba *phba)
9802 {
9803 	dma_free_coherent(&phba->pcidev->dev,
9804 			  phba->sli4_hba.bmbx.bmbx_size,
9805 			  phba->sli4_hba.bmbx.dmabuf->virt,
9806 			  phba->sli4_hba.bmbx.dmabuf->phys);
9807 
9808 	kfree(phba->sli4_hba.bmbx.dmabuf);
9809 	memset(&phba->sli4_hba.bmbx, 0, sizeof(struct lpfc_bmbx));
9810 }
9811 
9812 static const char * const lpfc_topo_to_str[] = {
9813 	"Loop then P2P",
9814 	"Loopback",
9815 	"P2P Only",
9816 	"Unsupported",
9817 	"Loop Only",
9818 	"Unsupported",
9819 	"P2P then Loop",
9820 };
9821 
9822 #define	LINK_FLAGS_DEF	0x0
9823 #define	LINK_FLAGS_P2P	0x1
9824 #define	LINK_FLAGS_LOOP	0x2
9825 /**
9826  * lpfc_map_topology - Map the topology read from READ_CONFIG
9827  * @phba: pointer to lpfc hba data structure.
9828  * @rd_config: pointer to read config data
9829  *
9830  * This routine is invoked to map the topology values as read
9831  * from the read config mailbox command. If the persistent
9832  * topology feature is supported, the firmware will provide the
9833  * saved topology information to be used in INIT_LINK
9834  **/
9835 static void
9836 lpfc_map_topology(struct lpfc_hba *phba, struct lpfc_mbx_read_config *rd_config)
9837 {
9838 	u8 ptv, tf, pt;
9839 
9840 	ptv = bf_get(lpfc_mbx_rd_conf_ptv, rd_config);
9841 	tf = bf_get(lpfc_mbx_rd_conf_tf, rd_config);
9842 	pt = bf_get(lpfc_mbx_rd_conf_pt, rd_config);
9843 
9844 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9845 			"2027 Read Config Data : ptv:0x%x, tf:0x%x pt:0x%x",
9846 			 ptv, tf, pt);
9847 	if (!ptv) {
9848 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9849 				"2019 FW does not support persistent topology "
9850 				"Using driver parameter defined value [%s]",
9851 				lpfc_topo_to_str[phba->cfg_topology]);
9852 		return;
9853 	}
9854 	/* FW supports persistent topology - override module parameter value */
9855 	set_bit(HBA_PERSISTENT_TOPO, &phba->hba_flag);
9856 
9857 	/* if ASIC_GEN_NUM >= 0xC) */
9858 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
9859 		    LPFC_SLI_INTF_IF_TYPE_6) ||
9860 	    (bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf) ==
9861 		    LPFC_SLI_INTF_FAMILY_G6)) {
9862 		if (!tf)
9863 			phba->cfg_topology = ((pt == LINK_FLAGS_LOOP)
9864 					? FLAGS_TOPOLOGY_MODE_LOOP
9865 					: FLAGS_TOPOLOGY_MODE_PT_PT);
9866 		else
9867 			clear_bit(HBA_PERSISTENT_TOPO, &phba->hba_flag);
9868 	} else { /* G5 */
9869 		if (tf)
9870 			/* If topology failover set - pt is '0' or '1' */
9871 			phba->cfg_topology = (pt ? FLAGS_TOPOLOGY_MODE_PT_LOOP :
9872 					      FLAGS_TOPOLOGY_MODE_LOOP_PT);
9873 		else
9874 			phba->cfg_topology = ((pt == LINK_FLAGS_P2P)
9875 					? FLAGS_TOPOLOGY_MODE_PT_PT
9876 					: FLAGS_TOPOLOGY_MODE_LOOP);
9877 	}
9878 	if (test_bit(HBA_PERSISTENT_TOPO, &phba->hba_flag))
9879 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9880 				"2020 Using persistent topology value [%s]",
9881 				lpfc_topo_to_str[phba->cfg_topology]);
9882 	else
9883 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9884 				"2021 Invalid topology values from FW "
9885 				"Using driver parameter defined value [%s]",
9886 				lpfc_topo_to_str[phba->cfg_topology]);
9887 }
9888 
9889 /**
9890  * lpfc_sli4_read_config - Get the config parameters.
9891  * @phba: pointer to lpfc hba data structure.
9892  *
9893  * This routine is invoked to read the configuration parameters from the HBA.
9894  * The configuration parameters are used to set the base and maximum values
9895  * for RPI's XRI's VPI's VFI's and FCFIs. These values also affect the resource
9896  * allocation for the port.
9897  *
9898  * Return codes
9899  * 	0 - successful
9900  * 	-ENOMEM - No available memory
9901  *      -EIO - The mailbox failed to complete successfully.
9902  **/
9903 int
9904 lpfc_sli4_read_config(struct lpfc_hba *phba)
9905 {
9906 	LPFC_MBOXQ_t *pmb;
9907 	struct lpfc_mbx_read_config *rd_config;
9908 	union  lpfc_sli4_cfg_shdr *shdr;
9909 	uint32_t shdr_status, shdr_add_status;
9910 	struct lpfc_mbx_get_func_cfg *get_func_cfg;
9911 	struct lpfc_rsrc_desc_fcfcoe *desc;
9912 	char *pdesc_0;
9913 	uint16_t forced_link_speed;
9914 	uint32_t if_type, qmin, fawwpn;
9915 	int length, i, rc = 0, rc2;
9916 
9917 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
9918 	if (!pmb) {
9919 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9920 				"2011 Unable to allocate memory for issuing "
9921 				"SLI_CONFIG_SPECIAL mailbox command\n");
9922 		return -ENOMEM;
9923 	}
9924 
9925 	lpfc_read_config(phba, pmb);
9926 
9927 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
9928 	if (rc != MBX_SUCCESS) {
9929 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9930 				"2012 Mailbox failed , mbxCmd x%x "
9931 				"READ_CONFIG, mbxStatus x%x\n",
9932 				bf_get(lpfc_mqe_command, &pmb->u.mqe),
9933 				bf_get(lpfc_mqe_status, &pmb->u.mqe));
9934 		rc = -EIO;
9935 	} else {
9936 		rd_config = &pmb->u.mqe.un.rd_config;
9937 		if (bf_get(lpfc_mbx_rd_conf_lnk_ldv, rd_config)) {
9938 			phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL;
9939 			phba->sli4_hba.lnk_info.lnk_tp =
9940 				bf_get(lpfc_mbx_rd_conf_lnk_type, rd_config);
9941 			phba->sli4_hba.lnk_info.lnk_no =
9942 				bf_get(lpfc_mbx_rd_conf_lnk_numb, rd_config);
9943 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9944 					"3081 lnk_type:%d, lnk_numb:%d\n",
9945 					phba->sli4_hba.lnk_info.lnk_tp,
9946 					phba->sli4_hba.lnk_info.lnk_no);
9947 		} else
9948 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9949 					"3082 Mailbox (x%x) returned ldv:x0\n",
9950 					bf_get(lpfc_mqe_command, &pmb->u.mqe));
9951 		if (bf_get(lpfc_mbx_rd_conf_bbscn_def, rd_config)) {
9952 			phba->bbcredit_support = 1;
9953 			phba->sli4_hba.bbscn_params.word0 = rd_config->word8;
9954 		}
9955 
9956 		fawwpn = bf_get(lpfc_mbx_rd_conf_fawwpn, rd_config);
9957 
9958 		if (fawwpn) {
9959 			lpfc_printf_log(phba, KERN_INFO,
9960 					LOG_INIT | LOG_DISCOVERY,
9961 					"2702 READ_CONFIG: FA-PWWN is "
9962 					"configured on\n");
9963 			phba->sli4_hba.fawwpn_flag |= LPFC_FAWWPN_CONFIG;
9964 		} else {
9965 			/* Clear FW configured flag, preserve driver flag */
9966 			phba->sli4_hba.fawwpn_flag &= ~LPFC_FAWWPN_CONFIG;
9967 		}
9968 
9969 		phba->sli4_hba.conf_trunk =
9970 			bf_get(lpfc_mbx_rd_conf_trunk, rd_config);
9971 		phba->sli4_hba.extents_in_use =
9972 			bf_get(lpfc_mbx_rd_conf_extnts_inuse, rd_config);
9973 
9974 		phba->sli4_hba.max_cfg_param.max_xri =
9975 			bf_get(lpfc_mbx_rd_conf_xri_count, rd_config);
9976 		/* Reduce resource usage in kdump environment */
9977 		if (is_kdump_kernel() &&
9978 		    phba->sli4_hba.max_cfg_param.max_xri > 512)
9979 			phba->sli4_hba.max_cfg_param.max_xri = 512;
9980 		phba->sli4_hba.max_cfg_param.xri_base =
9981 			bf_get(lpfc_mbx_rd_conf_xri_base, rd_config);
9982 		phba->sli4_hba.max_cfg_param.max_vpi =
9983 			bf_get(lpfc_mbx_rd_conf_vpi_count, rd_config);
9984 		/* Limit the max we support */
9985 		if (phba->sli4_hba.max_cfg_param.max_vpi > LPFC_MAX_VPORTS)
9986 			phba->sli4_hba.max_cfg_param.max_vpi = LPFC_MAX_VPORTS;
9987 		phba->sli4_hba.max_cfg_param.vpi_base =
9988 			bf_get(lpfc_mbx_rd_conf_vpi_base, rd_config);
9989 		phba->sli4_hba.max_cfg_param.max_rpi =
9990 			bf_get(lpfc_mbx_rd_conf_rpi_count, rd_config);
9991 		phba->sli4_hba.max_cfg_param.rpi_base =
9992 			bf_get(lpfc_mbx_rd_conf_rpi_base, rd_config);
9993 		phba->sli4_hba.max_cfg_param.max_vfi =
9994 			bf_get(lpfc_mbx_rd_conf_vfi_count, rd_config);
9995 		phba->sli4_hba.max_cfg_param.vfi_base =
9996 			bf_get(lpfc_mbx_rd_conf_vfi_base, rd_config);
9997 		phba->sli4_hba.max_cfg_param.max_fcfi =
9998 			bf_get(lpfc_mbx_rd_conf_fcfi_count, rd_config);
9999 		phba->sli4_hba.max_cfg_param.max_eq =
10000 			bf_get(lpfc_mbx_rd_conf_eq_count, rd_config);
10001 		phba->sli4_hba.max_cfg_param.max_rq =
10002 			bf_get(lpfc_mbx_rd_conf_rq_count, rd_config);
10003 		phba->sli4_hba.max_cfg_param.max_wq =
10004 			bf_get(lpfc_mbx_rd_conf_wq_count, rd_config);
10005 		phba->sli4_hba.max_cfg_param.max_cq =
10006 			bf_get(lpfc_mbx_rd_conf_cq_count, rd_config);
10007 		phba->lmt = bf_get(lpfc_mbx_rd_conf_lmt, rd_config);
10008 		phba->sli4_hba.next_xri = phba->sli4_hba.max_cfg_param.xri_base;
10009 		phba->vpi_base = phba->sli4_hba.max_cfg_param.vpi_base;
10010 		phba->vfi_base = phba->sli4_hba.max_cfg_param.vfi_base;
10011 		phba->max_vpi = (phba->sli4_hba.max_cfg_param.max_vpi > 0) ?
10012 				(phba->sli4_hba.max_cfg_param.max_vpi - 1) : 0;
10013 		phba->max_vports = phba->max_vpi;
10014 
10015 		/* Next decide on FPIN or Signal E2E CGN support
10016 		 * For congestion alarms and warnings valid combination are:
10017 		 * 1. FPIN alarms / FPIN warnings
10018 		 * 2. Signal alarms / Signal warnings
10019 		 * 3. FPIN alarms / Signal warnings
10020 		 * 4. Signal alarms / FPIN warnings
10021 		 *
10022 		 * Initialize the adapter frequency to 100 mSecs
10023 		 */
10024 		phba->cgn_reg_fpin = LPFC_CGN_FPIN_BOTH;
10025 		phba->cgn_reg_signal = EDC_CG_SIG_NOTSUPPORTED;
10026 		phba->cgn_sig_freq = lpfc_fabric_cgn_frequency;
10027 
10028 		if (lpfc_use_cgn_signal) {
10029 			if (bf_get(lpfc_mbx_rd_conf_wcs, rd_config)) {
10030 				phba->cgn_reg_signal = EDC_CG_SIG_WARN_ONLY;
10031 				phba->cgn_reg_fpin &= ~LPFC_CGN_FPIN_WARN;
10032 			}
10033 			if (bf_get(lpfc_mbx_rd_conf_acs, rd_config)) {
10034 				/* MUST support both alarm and warning
10035 				 * because EDC does not support alarm alone.
10036 				 */
10037 				if (phba->cgn_reg_signal !=
10038 				    EDC_CG_SIG_WARN_ONLY) {
10039 					/* Must support both or none */
10040 					phba->cgn_reg_fpin = LPFC_CGN_FPIN_BOTH;
10041 					phba->cgn_reg_signal =
10042 						EDC_CG_SIG_NOTSUPPORTED;
10043 				} else {
10044 					phba->cgn_reg_signal =
10045 						EDC_CG_SIG_WARN_ALARM;
10046 					phba->cgn_reg_fpin =
10047 						LPFC_CGN_FPIN_NONE;
10048 				}
10049 			}
10050 		}
10051 
10052 		/* Set the congestion initial signal and fpin values. */
10053 		phba->cgn_init_reg_fpin = phba->cgn_reg_fpin;
10054 		phba->cgn_init_reg_signal = phba->cgn_reg_signal;
10055 
10056 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
10057 				"6446 READ_CONFIG reg_sig x%x reg_fpin:x%x\n",
10058 				phba->cgn_reg_signal, phba->cgn_reg_fpin);
10059 
10060 		lpfc_map_topology(phba, rd_config);
10061 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10062 				"2003 cfg params Extents? %d "
10063 				"XRI(B:%d M:%d), "
10064 				"VPI(B:%d M:%d) "
10065 				"VFI(B:%d M:%d) "
10066 				"RPI(B:%d M:%d) "
10067 				"FCFI:%d EQ:%d CQ:%d WQ:%d RQ:%d lmt:x%x\n",
10068 				phba->sli4_hba.extents_in_use,
10069 				phba->sli4_hba.max_cfg_param.xri_base,
10070 				phba->sli4_hba.max_cfg_param.max_xri,
10071 				phba->sli4_hba.max_cfg_param.vpi_base,
10072 				phba->sli4_hba.max_cfg_param.max_vpi,
10073 				phba->sli4_hba.max_cfg_param.vfi_base,
10074 				phba->sli4_hba.max_cfg_param.max_vfi,
10075 				phba->sli4_hba.max_cfg_param.rpi_base,
10076 				phba->sli4_hba.max_cfg_param.max_rpi,
10077 				phba->sli4_hba.max_cfg_param.max_fcfi,
10078 				phba->sli4_hba.max_cfg_param.max_eq,
10079 				phba->sli4_hba.max_cfg_param.max_cq,
10080 				phba->sli4_hba.max_cfg_param.max_wq,
10081 				phba->sli4_hba.max_cfg_param.max_rq,
10082 				phba->lmt);
10083 
10084 		/*
10085 		 * Calculate queue resources based on how
10086 		 * many WQ/CQ/EQs are available.
10087 		 */
10088 		qmin = phba->sli4_hba.max_cfg_param.max_wq;
10089 		if (phba->sli4_hba.max_cfg_param.max_cq < qmin)
10090 			qmin = phba->sli4_hba.max_cfg_param.max_cq;
10091 		/*
10092 		 * Reserve 4 (ELS, NVME LS, MBOX, plus one extra) and
10093 		 * the remainder can be used for NVME / FCP.
10094 		 */
10095 		qmin -= 4;
10096 		if (phba->sli4_hba.max_cfg_param.max_eq < qmin)
10097 			qmin = phba->sli4_hba.max_cfg_param.max_eq;
10098 
10099 		/* Check to see if there is enough for default cfg */
10100 		if ((phba->cfg_irq_chann > qmin) ||
10101 		    (phba->cfg_hdw_queue > qmin)) {
10102 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10103 					"2005 Reducing Queues - "
10104 					"FW resource limitation: "
10105 					"WQ %d CQ %d EQ %d: min %d: "
10106 					"IRQ %d HDWQ %d\n",
10107 					phba->sli4_hba.max_cfg_param.max_wq,
10108 					phba->sli4_hba.max_cfg_param.max_cq,
10109 					phba->sli4_hba.max_cfg_param.max_eq,
10110 					qmin, phba->cfg_irq_chann,
10111 					phba->cfg_hdw_queue);
10112 
10113 			if (phba->cfg_irq_chann > qmin)
10114 				phba->cfg_irq_chann = qmin;
10115 			if (phba->cfg_hdw_queue > qmin)
10116 				phba->cfg_hdw_queue = qmin;
10117 		}
10118 	}
10119 
10120 	if (rc)
10121 		goto read_cfg_out;
10122 
10123 	/* Update link speed if forced link speed is supported */
10124 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
10125 	if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
10126 		forced_link_speed =
10127 			bf_get(lpfc_mbx_rd_conf_link_speed, rd_config);
10128 		if (forced_link_speed) {
10129 			set_bit(HBA_FORCED_LINK_SPEED, &phba->hba_flag);
10130 
10131 			switch (forced_link_speed) {
10132 			case LINK_SPEED_1G:
10133 				phba->cfg_link_speed =
10134 					LPFC_USER_LINK_SPEED_1G;
10135 				break;
10136 			case LINK_SPEED_2G:
10137 				phba->cfg_link_speed =
10138 					LPFC_USER_LINK_SPEED_2G;
10139 				break;
10140 			case LINK_SPEED_4G:
10141 				phba->cfg_link_speed =
10142 					LPFC_USER_LINK_SPEED_4G;
10143 				break;
10144 			case LINK_SPEED_8G:
10145 				phba->cfg_link_speed =
10146 					LPFC_USER_LINK_SPEED_8G;
10147 				break;
10148 			case LINK_SPEED_10G:
10149 				phba->cfg_link_speed =
10150 					LPFC_USER_LINK_SPEED_10G;
10151 				break;
10152 			case LINK_SPEED_16G:
10153 				phba->cfg_link_speed =
10154 					LPFC_USER_LINK_SPEED_16G;
10155 				break;
10156 			case LINK_SPEED_32G:
10157 				phba->cfg_link_speed =
10158 					LPFC_USER_LINK_SPEED_32G;
10159 				break;
10160 			case LINK_SPEED_64G:
10161 				phba->cfg_link_speed =
10162 					LPFC_USER_LINK_SPEED_64G;
10163 				break;
10164 			case 0xffff:
10165 				phba->cfg_link_speed =
10166 					LPFC_USER_LINK_SPEED_AUTO;
10167 				break;
10168 			default:
10169 				lpfc_printf_log(phba, KERN_ERR,
10170 						LOG_TRACE_EVENT,
10171 						"0047 Unrecognized link "
10172 						"speed : %d\n",
10173 						forced_link_speed);
10174 				phba->cfg_link_speed =
10175 					LPFC_USER_LINK_SPEED_AUTO;
10176 			}
10177 		}
10178 	}
10179 
10180 	/* Reset the DFT_HBA_Q_DEPTH to the max xri  */
10181 	length = phba->sli4_hba.max_cfg_param.max_xri -
10182 			lpfc_sli4_get_els_iocb_cnt(phba);
10183 	if (phba->cfg_hba_queue_depth > length) {
10184 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
10185 				"3361 HBA queue depth changed from %d to %d\n",
10186 				phba->cfg_hba_queue_depth, length);
10187 		phba->cfg_hba_queue_depth = length;
10188 	}
10189 
10190 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) <
10191 	    LPFC_SLI_INTF_IF_TYPE_2)
10192 		goto read_cfg_out;
10193 
10194 	/* get the pf# and vf# for SLI4 if_type 2 port */
10195 	length = (sizeof(struct lpfc_mbx_get_func_cfg) -
10196 		  sizeof(struct lpfc_sli4_cfg_mhdr));
10197 	lpfc_sli4_config(phba, pmb, LPFC_MBOX_SUBSYSTEM_COMMON,
10198 			 LPFC_MBOX_OPCODE_GET_FUNCTION_CONFIG,
10199 			 length, LPFC_SLI4_MBX_EMBED);
10200 
10201 	rc2 = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
10202 	shdr = (union lpfc_sli4_cfg_shdr *)
10203 				&pmb->u.mqe.un.sli4_config.header.cfg_shdr;
10204 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
10205 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
10206 	if (rc2 || shdr_status || shdr_add_status) {
10207 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10208 				"3026 Mailbox failed , mbxCmd x%x "
10209 				"GET_FUNCTION_CONFIG, mbxStatus x%x\n",
10210 				bf_get(lpfc_mqe_command, &pmb->u.mqe),
10211 				bf_get(lpfc_mqe_status, &pmb->u.mqe));
10212 		goto read_cfg_out;
10213 	}
10214 
10215 	/* search for fc_fcoe resrouce descriptor */
10216 	get_func_cfg = &pmb->u.mqe.un.get_func_cfg;
10217 
10218 	pdesc_0 = (char *)&get_func_cfg->func_cfg.desc[0];
10219 	desc = (struct lpfc_rsrc_desc_fcfcoe *)pdesc_0;
10220 	length = bf_get(lpfc_rsrc_desc_fcfcoe_length, desc);
10221 	if (length == LPFC_RSRC_DESC_TYPE_FCFCOE_V0_RSVD)
10222 		length = LPFC_RSRC_DESC_TYPE_FCFCOE_V0_LENGTH;
10223 	else if (length != LPFC_RSRC_DESC_TYPE_FCFCOE_V1_LENGTH)
10224 		goto read_cfg_out;
10225 
10226 	for (i = 0; i < LPFC_RSRC_DESC_MAX_NUM; i++) {
10227 		desc = (struct lpfc_rsrc_desc_fcfcoe *)(pdesc_0 + length * i);
10228 		if (LPFC_RSRC_DESC_TYPE_FCFCOE ==
10229 		    bf_get(lpfc_rsrc_desc_fcfcoe_type, desc)) {
10230 			phba->sli4_hba.iov.pf_number =
10231 				bf_get(lpfc_rsrc_desc_fcfcoe_pfnum, desc);
10232 			phba->sli4_hba.iov.vf_number =
10233 				bf_get(lpfc_rsrc_desc_fcfcoe_vfnum, desc);
10234 			break;
10235 		}
10236 	}
10237 
10238 	if (i < LPFC_RSRC_DESC_MAX_NUM)
10239 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10240 				"3027 GET_FUNCTION_CONFIG: pf_number:%d, "
10241 				"vf_number:%d\n", phba->sli4_hba.iov.pf_number,
10242 				phba->sli4_hba.iov.vf_number);
10243 	else
10244 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10245 				"3028 GET_FUNCTION_CONFIG: failed to find "
10246 				"Resource Descriptor:x%x\n",
10247 				LPFC_RSRC_DESC_TYPE_FCFCOE);
10248 
10249 read_cfg_out:
10250 	mempool_free(pmb, phba->mbox_mem_pool);
10251 	return rc;
10252 }
10253 
10254 /**
10255  * lpfc_setup_endian_order - Write endian order to an SLI4 if_type 0 port.
10256  * @phba: pointer to lpfc hba data structure.
10257  *
10258  * This routine is invoked to setup the port-side endian order when
10259  * the port if_type is 0.  This routine has no function for other
10260  * if_types.
10261  *
10262  * Return codes
10263  * 	0 - successful
10264  * 	-ENOMEM - No available memory
10265  *      -EIO - The mailbox failed to complete successfully.
10266  **/
10267 static int
10268 lpfc_setup_endian_order(struct lpfc_hba *phba)
10269 {
10270 	LPFC_MBOXQ_t *mboxq;
10271 	uint32_t if_type, rc = 0;
10272 	uint32_t endian_mb_data[2] = {HOST_ENDIAN_LOW_WORD0,
10273 				      HOST_ENDIAN_HIGH_WORD1};
10274 
10275 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
10276 	switch (if_type) {
10277 	case LPFC_SLI_INTF_IF_TYPE_0:
10278 		mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
10279 						       GFP_KERNEL);
10280 		if (!mboxq) {
10281 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10282 					"0492 Unable to allocate memory for "
10283 					"issuing SLI_CONFIG_SPECIAL mailbox "
10284 					"command\n");
10285 			return -ENOMEM;
10286 		}
10287 
10288 		/*
10289 		 * The SLI4_CONFIG_SPECIAL mailbox command requires the first
10290 		 * two words to contain special data values and no other data.
10291 		 */
10292 		memset(mboxq, 0, sizeof(LPFC_MBOXQ_t));
10293 		memcpy(&mboxq->u.mqe, &endian_mb_data, sizeof(endian_mb_data));
10294 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
10295 		if (rc != MBX_SUCCESS) {
10296 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10297 					"0493 SLI_CONFIG_SPECIAL mailbox "
10298 					"failed with status x%x\n",
10299 					rc);
10300 			rc = -EIO;
10301 		}
10302 		mempool_free(mboxq, phba->mbox_mem_pool);
10303 		break;
10304 	case LPFC_SLI_INTF_IF_TYPE_6:
10305 	case LPFC_SLI_INTF_IF_TYPE_2:
10306 	case LPFC_SLI_INTF_IF_TYPE_1:
10307 	default:
10308 		break;
10309 	}
10310 	return rc;
10311 }
10312 
10313 /**
10314  * lpfc_sli4_queue_verify - Verify and update EQ counts
10315  * @phba: pointer to lpfc hba data structure.
10316  *
10317  * This routine is invoked to check the user settable queue counts for EQs.
10318  * After this routine is called the counts will be set to valid values that
10319  * adhere to the constraints of the system's interrupt vectors and the port's
10320  * queue resources.
10321  *
10322  * Return codes
10323  *      0 - successful
10324  *      -ENOMEM - No available memory
10325  **/
10326 static int
10327 lpfc_sli4_queue_verify(struct lpfc_hba *phba)
10328 {
10329 	/*
10330 	 * Sanity check for configured queue parameters against the run-time
10331 	 * device parameters
10332 	 */
10333 
10334 	if (phba->nvmet_support) {
10335 		if (phba->cfg_hdw_queue < phba->cfg_nvmet_mrq)
10336 			phba->cfg_nvmet_mrq = phba->cfg_hdw_queue;
10337 		if (phba->cfg_nvmet_mrq > LPFC_NVMET_MRQ_MAX)
10338 			phba->cfg_nvmet_mrq = LPFC_NVMET_MRQ_MAX;
10339 	}
10340 
10341 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10342 			"2574 IO channels: hdwQ %d IRQ %d MRQ: %d\n",
10343 			phba->cfg_hdw_queue, phba->cfg_irq_chann,
10344 			phba->cfg_nvmet_mrq);
10345 
10346 	/* Get EQ depth from module parameter, fake the default for now */
10347 	phba->sli4_hba.eq_esize = LPFC_EQE_SIZE_4B;
10348 	phba->sli4_hba.eq_ecount = LPFC_EQE_DEF_COUNT;
10349 
10350 	/* Get CQ depth from module parameter, fake the default for now */
10351 	phba->sli4_hba.cq_esize = LPFC_CQE_SIZE;
10352 	phba->sli4_hba.cq_ecount = LPFC_CQE_DEF_COUNT;
10353 	return 0;
10354 }
10355 
10356 static int
10357 lpfc_alloc_io_wq_cq(struct lpfc_hba *phba, int idx)
10358 {
10359 	struct lpfc_queue *qdesc;
10360 	u32 wqesize;
10361 	int cpu;
10362 
10363 	cpu = lpfc_find_cpu_handle(phba, idx, LPFC_FIND_BY_HDWQ);
10364 	/* Create Fast Path IO CQs */
10365 	if (phba->enab_exp_wqcq_pages)
10366 		/* Increase the CQ size when WQEs contain an embedded cdb */
10367 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_EXPANDED_PAGE_SIZE,
10368 					      phba->sli4_hba.cq_esize,
10369 					      LPFC_CQE_EXP_COUNT, cpu);
10370 
10371 	else
10372 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10373 					      phba->sli4_hba.cq_esize,
10374 					      phba->sli4_hba.cq_ecount, cpu);
10375 	if (!qdesc) {
10376 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10377 				"0499 Failed allocate fast-path IO CQ (%d)\n",
10378 				idx);
10379 		return 1;
10380 	}
10381 	qdesc->qe_valid = 1;
10382 	qdesc->hdwq = idx;
10383 	qdesc->chann = cpu;
10384 	phba->sli4_hba.hdwq[idx].io_cq = qdesc;
10385 
10386 	/* Create Fast Path IO WQs */
10387 	if (phba->enab_exp_wqcq_pages) {
10388 		/* Increase the WQ size when WQEs contain an embedded cdb */
10389 		wqesize = (phba->fcp_embed_io) ?
10390 			LPFC_WQE128_SIZE : phba->sli4_hba.wq_esize;
10391 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_EXPANDED_PAGE_SIZE,
10392 					      wqesize,
10393 					      LPFC_WQE_EXP_COUNT, cpu);
10394 	} else
10395 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10396 					      phba->sli4_hba.wq_esize,
10397 					      phba->sli4_hba.wq_ecount, cpu);
10398 
10399 	if (!qdesc) {
10400 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10401 				"0503 Failed allocate fast-path IO WQ (%d)\n",
10402 				idx);
10403 		return 1;
10404 	}
10405 	qdesc->hdwq = idx;
10406 	qdesc->chann = cpu;
10407 	phba->sli4_hba.hdwq[idx].io_wq = qdesc;
10408 	list_add_tail(&qdesc->wq_list, &phba->sli4_hba.lpfc_wq_list);
10409 	return 0;
10410 }
10411 
10412 /**
10413  * lpfc_sli4_queue_create - Create all the SLI4 queues
10414  * @phba: pointer to lpfc hba data structure.
10415  *
10416  * This routine is invoked to allocate all the SLI4 queues for the FCoE HBA
10417  * operation. For each SLI4 queue type, the parameters such as queue entry
10418  * count (queue depth) shall be taken from the module parameter. For now,
10419  * we just use some constant number as place holder.
10420  *
10421  * Return codes
10422  *      0 - successful
10423  *      -ENOMEM - No availble memory
10424  *      -EIO - The mailbox failed to complete successfully.
10425  **/
10426 int
10427 lpfc_sli4_queue_create(struct lpfc_hba *phba)
10428 {
10429 	struct lpfc_queue *qdesc;
10430 	int idx, cpu, eqcpu;
10431 	struct lpfc_sli4_hdw_queue *qp;
10432 	struct lpfc_vector_map_info *cpup;
10433 	struct lpfc_vector_map_info *eqcpup;
10434 	struct lpfc_eq_intr_info *eqi;
10435 	u32 wqesize;
10436 
10437 	/*
10438 	 * Create HBA Record arrays.
10439 	 * Both NVME and FCP will share that same vectors / EQs
10440 	 */
10441 	phba->sli4_hba.mq_esize = LPFC_MQE_SIZE;
10442 	phba->sli4_hba.mq_ecount = LPFC_MQE_DEF_COUNT;
10443 	phba->sli4_hba.wq_esize = LPFC_WQE_SIZE;
10444 	phba->sli4_hba.wq_ecount = LPFC_WQE_DEF_COUNT;
10445 	phba->sli4_hba.rq_esize = LPFC_RQE_SIZE;
10446 	phba->sli4_hba.rq_ecount = LPFC_RQE_DEF_COUNT;
10447 	phba->sli4_hba.eq_esize = LPFC_EQE_SIZE_4B;
10448 	phba->sli4_hba.eq_ecount = LPFC_EQE_DEF_COUNT;
10449 	phba->sli4_hba.cq_esize = LPFC_CQE_SIZE;
10450 	phba->sli4_hba.cq_ecount = LPFC_CQE_DEF_COUNT;
10451 
10452 	if (!phba->sli4_hba.hdwq) {
10453 		phba->sli4_hba.hdwq = kcalloc(
10454 			phba->cfg_hdw_queue, sizeof(struct lpfc_sli4_hdw_queue),
10455 			GFP_KERNEL);
10456 		if (!phba->sli4_hba.hdwq) {
10457 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10458 					"6427 Failed allocate memory for "
10459 					"fast-path Hardware Queue array\n");
10460 			goto out_error;
10461 		}
10462 		/* Prepare hardware queues to take IO buffers */
10463 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10464 			qp = &phba->sli4_hba.hdwq[idx];
10465 			spin_lock_init(&qp->io_buf_list_get_lock);
10466 			spin_lock_init(&qp->io_buf_list_put_lock);
10467 			INIT_LIST_HEAD(&qp->lpfc_io_buf_list_get);
10468 			INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
10469 			qp->get_io_bufs = 0;
10470 			qp->put_io_bufs = 0;
10471 			qp->total_io_bufs = 0;
10472 			spin_lock_init(&qp->abts_io_buf_list_lock);
10473 			INIT_LIST_HEAD(&qp->lpfc_abts_io_buf_list);
10474 			qp->abts_scsi_io_bufs = 0;
10475 			qp->abts_nvme_io_bufs = 0;
10476 			INIT_LIST_HEAD(&qp->sgl_list);
10477 			INIT_LIST_HEAD(&qp->cmd_rsp_buf_list);
10478 			spin_lock_init(&qp->hdwq_lock);
10479 		}
10480 	}
10481 
10482 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
10483 		if (phba->nvmet_support) {
10484 			phba->sli4_hba.nvmet_cqset = kcalloc(
10485 					phba->cfg_nvmet_mrq,
10486 					sizeof(struct lpfc_queue *),
10487 					GFP_KERNEL);
10488 			if (!phba->sli4_hba.nvmet_cqset) {
10489 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10490 					"3121 Fail allocate memory for "
10491 					"fast-path CQ set array\n");
10492 				goto out_error;
10493 			}
10494 			phba->sli4_hba.nvmet_mrq_hdr = kcalloc(
10495 					phba->cfg_nvmet_mrq,
10496 					sizeof(struct lpfc_queue *),
10497 					GFP_KERNEL);
10498 			if (!phba->sli4_hba.nvmet_mrq_hdr) {
10499 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10500 					"3122 Fail allocate memory for "
10501 					"fast-path RQ set hdr array\n");
10502 				goto out_error;
10503 			}
10504 			phba->sli4_hba.nvmet_mrq_data = kcalloc(
10505 					phba->cfg_nvmet_mrq,
10506 					sizeof(struct lpfc_queue *),
10507 					GFP_KERNEL);
10508 			if (!phba->sli4_hba.nvmet_mrq_data) {
10509 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10510 					"3124 Fail allocate memory for "
10511 					"fast-path RQ set data array\n");
10512 				goto out_error;
10513 			}
10514 		}
10515 	}
10516 
10517 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_wq_list);
10518 
10519 	/* Create HBA Event Queues (EQs) */
10520 	for_each_present_cpu(cpu) {
10521 		/* We only want to create 1 EQ per vector, even though
10522 		 * multiple CPUs might be using that vector. so only
10523 		 * selects the CPUs that are LPFC_CPU_FIRST_IRQ.
10524 		 */
10525 		cpup = &phba->sli4_hba.cpu_map[cpu];
10526 		if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
10527 			continue;
10528 
10529 		/* Get a ptr to the Hardware Queue associated with this CPU */
10530 		qp = &phba->sli4_hba.hdwq[cpup->hdwq];
10531 
10532 		/* Allocate an EQ */
10533 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10534 					      phba->sli4_hba.eq_esize,
10535 					      phba->sli4_hba.eq_ecount, cpu);
10536 		if (!qdesc) {
10537 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10538 					"0497 Failed allocate EQ (%d)\n",
10539 					cpup->hdwq);
10540 			goto out_error;
10541 		}
10542 		qdesc->qe_valid = 1;
10543 		qdesc->hdwq = cpup->hdwq;
10544 		qdesc->chann = cpu; /* First CPU this EQ is affinitized to */
10545 		qdesc->last_cpu = qdesc->chann;
10546 
10547 		/* Save the allocated EQ in the Hardware Queue */
10548 		qp->hba_eq = qdesc;
10549 
10550 		eqi = per_cpu_ptr(phba->sli4_hba.eq_info, qdesc->last_cpu);
10551 		list_add(&qdesc->cpu_list, &eqi->list);
10552 	}
10553 
10554 	/* Now we need to populate the other Hardware Queues, that share
10555 	 * an IRQ vector, with the associated EQ ptr.
10556 	 */
10557 	for_each_present_cpu(cpu) {
10558 		cpup = &phba->sli4_hba.cpu_map[cpu];
10559 
10560 		/* Check for EQ already allocated in previous loop */
10561 		if (cpup->flag & LPFC_CPU_FIRST_IRQ)
10562 			continue;
10563 
10564 		/* Check for multiple CPUs per hdwq */
10565 		qp = &phba->sli4_hba.hdwq[cpup->hdwq];
10566 		if (qp->hba_eq)
10567 			continue;
10568 
10569 		/* We need to share an EQ for this hdwq */
10570 		eqcpu = lpfc_find_cpu_handle(phba, cpup->eq, LPFC_FIND_BY_EQ);
10571 		eqcpup = &phba->sli4_hba.cpu_map[eqcpu];
10572 		qp->hba_eq = phba->sli4_hba.hdwq[eqcpup->hdwq].hba_eq;
10573 	}
10574 
10575 	/* Allocate IO Path SLI4 CQ/WQs */
10576 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10577 		if (lpfc_alloc_io_wq_cq(phba, idx))
10578 			goto out_error;
10579 	}
10580 
10581 	if (phba->nvmet_support) {
10582 		for (idx = 0; idx < phba->cfg_nvmet_mrq; idx++) {
10583 			cpu = lpfc_find_cpu_handle(phba, idx,
10584 						   LPFC_FIND_BY_HDWQ);
10585 			qdesc = lpfc_sli4_queue_alloc(phba,
10586 						      LPFC_DEFAULT_PAGE_SIZE,
10587 						      phba->sli4_hba.cq_esize,
10588 						      phba->sli4_hba.cq_ecount,
10589 						      cpu);
10590 			if (!qdesc) {
10591 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10592 						"3142 Failed allocate NVME "
10593 						"CQ Set (%d)\n", idx);
10594 				goto out_error;
10595 			}
10596 			qdesc->qe_valid = 1;
10597 			qdesc->hdwq = idx;
10598 			qdesc->chann = cpu;
10599 			phba->sli4_hba.nvmet_cqset[idx] = qdesc;
10600 		}
10601 	}
10602 
10603 	/*
10604 	 * Create Slow Path Completion Queues (CQs)
10605 	 */
10606 
10607 	cpu = lpfc_find_cpu_handle(phba, 0, LPFC_FIND_BY_EQ);
10608 	/* Create slow-path Mailbox Command Complete Queue */
10609 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10610 				      phba->sli4_hba.cq_esize,
10611 				      phba->sli4_hba.cq_ecount, cpu);
10612 	if (!qdesc) {
10613 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10614 				"0500 Failed allocate slow-path mailbox CQ\n");
10615 		goto out_error;
10616 	}
10617 	qdesc->qe_valid = 1;
10618 	phba->sli4_hba.mbx_cq = qdesc;
10619 
10620 	/* Create slow-path ELS Complete Queue */
10621 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10622 				      phba->sli4_hba.cq_esize,
10623 				      phba->sli4_hba.cq_ecount, cpu);
10624 	if (!qdesc) {
10625 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10626 				"0501 Failed allocate slow-path ELS CQ\n");
10627 		goto out_error;
10628 	}
10629 	qdesc->qe_valid = 1;
10630 	qdesc->chann = cpu;
10631 	phba->sli4_hba.els_cq = qdesc;
10632 
10633 
10634 	/*
10635 	 * Create Slow Path Work Queues (WQs)
10636 	 */
10637 
10638 	/* Create Mailbox Command Queue */
10639 
10640 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10641 				      phba->sli4_hba.mq_esize,
10642 				      phba->sli4_hba.mq_ecount, cpu);
10643 	if (!qdesc) {
10644 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10645 				"0505 Failed allocate slow-path MQ\n");
10646 		goto out_error;
10647 	}
10648 	qdesc->chann = cpu;
10649 	phba->sli4_hba.mbx_wq = qdesc;
10650 
10651 	/*
10652 	 * Create ELS Work Queues
10653 	 */
10654 
10655 	/*
10656 	 * Create slow-path ELS Work Queue.
10657 	 * Increase the ELS WQ size when WQEs contain an embedded cdb
10658 	 */
10659 	wqesize = (phba->fcp_embed_io) ?
10660 			LPFC_WQE128_SIZE : phba->sli4_hba.wq_esize;
10661 
10662 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10663 				      wqesize,
10664 				      phba->sli4_hba.wq_ecount, cpu);
10665 	if (!qdesc) {
10666 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10667 				"0504 Failed allocate slow-path ELS WQ\n");
10668 		goto out_error;
10669 	}
10670 	qdesc->chann = cpu;
10671 	phba->sli4_hba.els_wq = qdesc;
10672 	list_add_tail(&qdesc->wq_list, &phba->sli4_hba.lpfc_wq_list);
10673 
10674 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
10675 		/* Create NVME LS Complete Queue */
10676 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10677 					      phba->sli4_hba.cq_esize,
10678 					      phba->sli4_hba.cq_ecount, cpu);
10679 		if (!qdesc) {
10680 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10681 					"6079 Failed allocate NVME LS CQ\n");
10682 			goto out_error;
10683 		}
10684 		qdesc->chann = cpu;
10685 		qdesc->qe_valid = 1;
10686 		phba->sli4_hba.nvmels_cq = qdesc;
10687 
10688 		/* Create NVME LS Work Queue */
10689 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10690 					      phba->sli4_hba.wq_esize,
10691 					      phba->sli4_hba.wq_ecount, cpu);
10692 		if (!qdesc) {
10693 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10694 					"6080 Failed allocate NVME LS WQ\n");
10695 			goto out_error;
10696 		}
10697 		qdesc->chann = cpu;
10698 		phba->sli4_hba.nvmels_wq = qdesc;
10699 		list_add_tail(&qdesc->wq_list, &phba->sli4_hba.lpfc_wq_list);
10700 	}
10701 
10702 	/*
10703 	 * Create Receive Queue (RQ)
10704 	 */
10705 
10706 	/* Create Receive Queue for header */
10707 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10708 				      phba->sli4_hba.rq_esize,
10709 				      phba->sli4_hba.rq_ecount, cpu);
10710 	if (!qdesc) {
10711 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10712 				"0506 Failed allocate receive HRQ\n");
10713 		goto out_error;
10714 	}
10715 	phba->sli4_hba.hdr_rq = qdesc;
10716 
10717 	/* Create Receive Queue for data */
10718 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10719 				      phba->sli4_hba.rq_esize,
10720 				      phba->sli4_hba.rq_ecount, cpu);
10721 	if (!qdesc) {
10722 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10723 				"0507 Failed allocate receive DRQ\n");
10724 		goto out_error;
10725 	}
10726 	phba->sli4_hba.dat_rq = qdesc;
10727 
10728 	if ((phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) &&
10729 	    phba->nvmet_support) {
10730 		for (idx = 0; idx < phba->cfg_nvmet_mrq; idx++) {
10731 			cpu = lpfc_find_cpu_handle(phba, idx,
10732 						   LPFC_FIND_BY_HDWQ);
10733 			/* Create NVMET Receive Queue for header */
10734 			qdesc = lpfc_sli4_queue_alloc(phba,
10735 						      LPFC_DEFAULT_PAGE_SIZE,
10736 						      phba->sli4_hba.rq_esize,
10737 						      LPFC_NVMET_RQE_DEF_COUNT,
10738 						      cpu);
10739 			if (!qdesc) {
10740 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10741 						"3146 Failed allocate "
10742 						"receive HRQ\n");
10743 				goto out_error;
10744 			}
10745 			qdesc->hdwq = idx;
10746 			phba->sli4_hba.nvmet_mrq_hdr[idx] = qdesc;
10747 
10748 			/* Only needed for header of RQ pair */
10749 			qdesc->rqbp = kzalloc_node(sizeof(*qdesc->rqbp),
10750 						   GFP_KERNEL,
10751 						   cpu_to_node(cpu));
10752 			if (qdesc->rqbp == NULL) {
10753 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10754 						"6131 Failed allocate "
10755 						"Header RQBP\n");
10756 				goto out_error;
10757 			}
10758 
10759 			/* Put list in known state in case driver load fails. */
10760 			INIT_LIST_HEAD(&qdesc->rqbp->rqb_buffer_list);
10761 
10762 			/* Create NVMET Receive Queue for data */
10763 			qdesc = lpfc_sli4_queue_alloc(phba,
10764 						      LPFC_DEFAULT_PAGE_SIZE,
10765 						      phba->sli4_hba.rq_esize,
10766 						      LPFC_NVMET_RQE_DEF_COUNT,
10767 						      cpu);
10768 			if (!qdesc) {
10769 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10770 						"3156 Failed allocate "
10771 						"receive DRQ\n");
10772 				goto out_error;
10773 			}
10774 			qdesc->hdwq = idx;
10775 			phba->sli4_hba.nvmet_mrq_data[idx] = qdesc;
10776 		}
10777 	}
10778 
10779 	/* Clear NVME stats */
10780 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
10781 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10782 			memset(&phba->sli4_hba.hdwq[idx].nvme_cstat, 0,
10783 			       sizeof(phba->sli4_hba.hdwq[idx].nvme_cstat));
10784 		}
10785 	}
10786 
10787 	/* Clear SCSI stats */
10788 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP) {
10789 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10790 			memset(&phba->sli4_hba.hdwq[idx].scsi_cstat, 0,
10791 			       sizeof(phba->sli4_hba.hdwq[idx].scsi_cstat));
10792 		}
10793 	}
10794 
10795 	return 0;
10796 
10797 out_error:
10798 	lpfc_sli4_queue_destroy(phba);
10799 	return -ENOMEM;
10800 }
10801 
10802 static inline void
10803 __lpfc_sli4_release_queue(struct lpfc_queue **qp)
10804 {
10805 	if (*qp != NULL) {
10806 		lpfc_sli4_queue_free(*qp);
10807 		*qp = NULL;
10808 	}
10809 }
10810 
10811 static inline void
10812 lpfc_sli4_release_queues(struct lpfc_queue ***qs, int max)
10813 {
10814 	int idx;
10815 
10816 	if (*qs == NULL)
10817 		return;
10818 
10819 	for (idx = 0; idx < max; idx++)
10820 		__lpfc_sli4_release_queue(&(*qs)[idx]);
10821 
10822 	kfree(*qs);
10823 	*qs = NULL;
10824 }
10825 
10826 static inline void
10827 lpfc_sli4_release_hdwq(struct lpfc_hba *phba)
10828 {
10829 	struct lpfc_sli4_hdw_queue *hdwq;
10830 	struct lpfc_queue *eq;
10831 	uint32_t idx;
10832 
10833 	hdwq = phba->sli4_hba.hdwq;
10834 
10835 	/* Loop thru all Hardware Queues */
10836 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10837 		/* Free the CQ/WQ corresponding to the Hardware Queue */
10838 		lpfc_sli4_queue_free(hdwq[idx].io_cq);
10839 		lpfc_sli4_queue_free(hdwq[idx].io_wq);
10840 		hdwq[idx].hba_eq = NULL;
10841 		hdwq[idx].io_cq = NULL;
10842 		hdwq[idx].io_wq = NULL;
10843 		if (phba->cfg_xpsgl && !phba->nvmet_support)
10844 			lpfc_free_sgl_per_hdwq(phba, &hdwq[idx]);
10845 		lpfc_free_cmd_rsp_buf_per_hdwq(phba, &hdwq[idx]);
10846 	}
10847 	/* Loop thru all IRQ vectors */
10848 	for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
10849 		/* Free the EQ corresponding to the IRQ vector */
10850 		eq = phba->sli4_hba.hba_eq_hdl[idx].eq;
10851 		lpfc_sli4_queue_free(eq);
10852 		phba->sli4_hba.hba_eq_hdl[idx].eq = NULL;
10853 	}
10854 }
10855 
10856 /**
10857  * lpfc_sli4_queue_destroy - Destroy all the SLI4 queues
10858  * @phba: pointer to lpfc hba data structure.
10859  *
10860  * This routine is invoked to release all the SLI4 queues with the FCoE HBA
10861  * operation.
10862  *
10863  * Return codes
10864  *      0 - successful
10865  *      -ENOMEM - No available memory
10866  *      -EIO - The mailbox failed to complete successfully.
10867  **/
10868 void
10869 lpfc_sli4_queue_destroy(struct lpfc_hba *phba)
10870 {
10871 	/*
10872 	 * Set FREE_INIT before beginning to free the queues.
10873 	 * Wait until the users of queues to acknowledge to
10874 	 * release queues by clearing FREE_WAIT.
10875 	 */
10876 	spin_lock_irq(&phba->hbalock);
10877 	phba->sli.sli_flag |= LPFC_QUEUE_FREE_INIT;
10878 	while (phba->sli.sli_flag & LPFC_QUEUE_FREE_WAIT) {
10879 		spin_unlock_irq(&phba->hbalock);
10880 		msleep(20);
10881 		spin_lock_irq(&phba->hbalock);
10882 	}
10883 	spin_unlock_irq(&phba->hbalock);
10884 
10885 	lpfc_sli4_cleanup_poll_list(phba);
10886 
10887 	/* Release HBA eqs */
10888 	if (phba->sli4_hba.hdwq)
10889 		lpfc_sli4_release_hdwq(phba);
10890 
10891 	if (phba->nvmet_support) {
10892 		lpfc_sli4_release_queues(&phba->sli4_hba.nvmet_cqset,
10893 					 phba->cfg_nvmet_mrq);
10894 
10895 		lpfc_sli4_release_queues(&phba->sli4_hba.nvmet_mrq_hdr,
10896 					 phba->cfg_nvmet_mrq);
10897 		lpfc_sli4_release_queues(&phba->sli4_hba.nvmet_mrq_data,
10898 					 phba->cfg_nvmet_mrq);
10899 	}
10900 
10901 	/* Release mailbox command work queue */
10902 	__lpfc_sli4_release_queue(&phba->sli4_hba.mbx_wq);
10903 
10904 	/* Release ELS work queue */
10905 	__lpfc_sli4_release_queue(&phba->sli4_hba.els_wq);
10906 
10907 	/* Release ELS work queue */
10908 	__lpfc_sli4_release_queue(&phba->sli4_hba.nvmels_wq);
10909 
10910 	/* Release unsolicited receive queue */
10911 	__lpfc_sli4_release_queue(&phba->sli4_hba.hdr_rq);
10912 	__lpfc_sli4_release_queue(&phba->sli4_hba.dat_rq);
10913 
10914 	/* Release ELS complete queue */
10915 	__lpfc_sli4_release_queue(&phba->sli4_hba.els_cq);
10916 
10917 	/* Release NVME LS complete queue */
10918 	__lpfc_sli4_release_queue(&phba->sli4_hba.nvmels_cq);
10919 
10920 	/* Release mailbox command complete queue */
10921 	__lpfc_sli4_release_queue(&phba->sli4_hba.mbx_cq);
10922 
10923 	/* Everything on this list has been freed */
10924 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_wq_list);
10925 
10926 	/* Done with freeing the queues */
10927 	spin_lock_irq(&phba->hbalock);
10928 	phba->sli.sli_flag &= ~LPFC_QUEUE_FREE_INIT;
10929 	spin_unlock_irq(&phba->hbalock);
10930 }
10931 
10932 int
10933 lpfc_free_rq_buffer(struct lpfc_hba *phba, struct lpfc_queue *rq)
10934 {
10935 	struct lpfc_rqb *rqbp;
10936 	struct lpfc_dmabuf *h_buf;
10937 	struct rqb_dmabuf *rqb_buffer;
10938 
10939 	rqbp = rq->rqbp;
10940 	while (!list_empty(&rqbp->rqb_buffer_list)) {
10941 		list_remove_head(&rqbp->rqb_buffer_list, h_buf,
10942 				 struct lpfc_dmabuf, list);
10943 
10944 		rqb_buffer = container_of(h_buf, struct rqb_dmabuf, hbuf);
10945 		(rqbp->rqb_free_buffer)(phba, rqb_buffer);
10946 		rqbp->buffer_count--;
10947 	}
10948 	return 1;
10949 }
10950 
10951 static int
10952 lpfc_create_wq_cq(struct lpfc_hba *phba, struct lpfc_queue *eq,
10953 	struct lpfc_queue *cq, struct lpfc_queue *wq, uint16_t *cq_map,
10954 	int qidx, uint32_t qtype)
10955 {
10956 	struct lpfc_sli_ring *pring;
10957 	int rc;
10958 
10959 	if (!eq || !cq || !wq) {
10960 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10961 			"6085 Fast-path %s (%d) not allocated\n",
10962 			((eq) ? ((cq) ? "WQ" : "CQ") : "EQ"), qidx);
10963 		return -ENOMEM;
10964 	}
10965 
10966 	/* create the Cq first */
10967 	rc = lpfc_cq_create(phba, cq, eq,
10968 			(qtype == LPFC_MBOX) ? LPFC_MCQ : LPFC_WCQ, qtype);
10969 	if (rc) {
10970 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10971 				"6086 Failed setup of CQ (%d), rc = 0x%x\n",
10972 				qidx, (uint32_t)rc);
10973 		return rc;
10974 	}
10975 
10976 	if (qtype != LPFC_MBOX) {
10977 		/* Setup cq_map for fast lookup */
10978 		if (cq_map)
10979 			*cq_map = cq->queue_id;
10980 
10981 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
10982 			"6087 CQ setup: cq[%d]-id=%d, parent eq[%d]-id=%d\n",
10983 			qidx, cq->queue_id, qidx, eq->queue_id);
10984 
10985 		/* create the wq */
10986 		rc = lpfc_wq_create(phba, wq, cq, qtype);
10987 		if (rc) {
10988 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10989 				"4618 Fail setup fastpath WQ (%d), rc = 0x%x\n",
10990 				qidx, (uint32_t)rc);
10991 			/* no need to tear down cq - caller will do so */
10992 			return rc;
10993 		}
10994 
10995 		/* Bind this CQ/WQ to the NVME ring */
10996 		pring = wq->pring;
10997 		pring->sli.sli4.wqp = (void *)wq;
10998 		cq->pring = pring;
10999 
11000 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11001 			"2593 WQ setup: wq[%d]-id=%d assoc=%d, cq[%d]-id=%d\n",
11002 			qidx, wq->queue_id, wq->assoc_qid, qidx, cq->queue_id);
11003 	} else {
11004 		rc = lpfc_mq_create(phba, wq, cq, LPFC_MBOX);
11005 		if (rc) {
11006 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11007 					"0539 Failed setup of slow-path MQ: "
11008 					"rc = 0x%x\n", rc);
11009 			/* no need to tear down cq - caller will do so */
11010 			return rc;
11011 		}
11012 
11013 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11014 			"2589 MBX MQ setup: wq-id=%d, parent cq-id=%d\n",
11015 			phba->sli4_hba.mbx_wq->queue_id,
11016 			phba->sli4_hba.mbx_cq->queue_id);
11017 	}
11018 
11019 	return 0;
11020 }
11021 
11022 /**
11023  * lpfc_setup_cq_lookup - Setup the CQ lookup table
11024  * @phba: pointer to lpfc hba data structure.
11025  *
11026  * This routine will populate the cq_lookup table by all
11027  * available CQ queue_id's.
11028  **/
11029 static void
11030 lpfc_setup_cq_lookup(struct lpfc_hba *phba)
11031 {
11032 	struct lpfc_queue *eq, *childq;
11033 	int qidx;
11034 
11035 	memset(phba->sli4_hba.cq_lookup, 0,
11036 	       (sizeof(struct lpfc_queue *) * (phba->sli4_hba.cq_max + 1)));
11037 	/* Loop thru all IRQ vectors */
11038 	for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
11039 		/* Get the EQ corresponding to the IRQ vector */
11040 		eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
11041 		if (!eq)
11042 			continue;
11043 		/* Loop through all CQs associated with that EQ */
11044 		list_for_each_entry(childq, &eq->child_list, list) {
11045 			if (childq->queue_id > phba->sli4_hba.cq_max)
11046 				continue;
11047 			if (childq->subtype == LPFC_IO)
11048 				phba->sli4_hba.cq_lookup[childq->queue_id] =
11049 					childq;
11050 		}
11051 	}
11052 }
11053 
11054 /**
11055  * lpfc_sli4_queue_setup - Set up all the SLI4 queues
11056  * @phba: pointer to lpfc hba data structure.
11057  *
11058  * This routine is invoked to set up all the SLI4 queues for the FCoE HBA
11059  * operation.
11060  *
11061  * Return codes
11062  *      0 - successful
11063  *      -ENOMEM - No available memory
11064  *      -EIO - The mailbox failed to complete successfully.
11065  **/
11066 int
11067 lpfc_sli4_queue_setup(struct lpfc_hba *phba)
11068 {
11069 	uint32_t shdr_status, shdr_add_status;
11070 	union lpfc_sli4_cfg_shdr *shdr;
11071 	struct lpfc_vector_map_info *cpup;
11072 	struct lpfc_sli4_hdw_queue *qp;
11073 	LPFC_MBOXQ_t *mboxq;
11074 	int qidx, cpu;
11075 	uint32_t length, usdelay;
11076 	int rc = -ENOMEM;
11077 
11078 	/* Check for dual-ULP support */
11079 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
11080 	if (!mboxq) {
11081 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11082 				"3249 Unable to allocate memory for "
11083 				"QUERY_FW_CFG mailbox command\n");
11084 		return -ENOMEM;
11085 	}
11086 	length = (sizeof(struct lpfc_mbx_query_fw_config) -
11087 		  sizeof(struct lpfc_sli4_cfg_mhdr));
11088 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
11089 			 LPFC_MBOX_OPCODE_QUERY_FW_CFG,
11090 			 length, LPFC_SLI4_MBX_EMBED);
11091 
11092 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
11093 
11094 	shdr = (union lpfc_sli4_cfg_shdr *)
11095 			&mboxq->u.mqe.un.sli4_config.header.cfg_shdr;
11096 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
11097 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
11098 	if (shdr_status || shdr_add_status || rc) {
11099 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11100 				"3250 QUERY_FW_CFG mailbox failed with status "
11101 				"x%x add_status x%x, mbx status x%x\n",
11102 				shdr_status, shdr_add_status, rc);
11103 		mempool_free(mboxq, phba->mbox_mem_pool);
11104 		rc = -ENXIO;
11105 		goto out_error;
11106 	}
11107 
11108 	phba->sli4_hba.fw_func_mode =
11109 			mboxq->u.mqe.un.query_fw_cfg.rsp.function_mode;
11110 	phba->sli4_hba.physical_port =
11111 			mboxq->u.mqe.un.query_fw_cfg.rsp.physical_port;
11112 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11113 			"3251 QUERY_FW_CFG: func_mode:x%x\n",
11114 			phba->sli4_hba.fw_func_mode);
11115 
11116 	mempool_free(mboxq, phba->mbox_mem_pool);
11117 
11118 	/*
11119 	 * Set up HBA Event Queues (EQs)
11120 	 */
11121 	qp = phba->sli4_hba.hdwq;
11122 
11123 	/* Set up HBA event queue */
11124 	if (!qp) {
11125 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11126 				"3147 Fast-path EQs not allocated\n");
11127 		rc = -ENOMEM;
11128 		goto out_error;
11129 	}
11130 
11131 	/* Loop thru all IRQ vectors */
11132 	for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
11133 		/* Create HBA Event Queues (EQs) in order */
11134 		for_each_present_cpu(cpu) {
11135 			cpup = &phba->sli4_hba.cpu_map[cpu];
11136 
11137 			/* Look for the CPU thats using that vector with
11138 			 * LPFC_CPU_FIRST_IRQ set.
11139 			 */
11140 			if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
11141 				continue;
11142 			if (qidx != cpup->eq)
11143 				continue;
11144 
11145 			/* Create an EQ for that vector */
11146 			rc = lpfc_eq_create(phba, qp[cpup->hdwq].hba_eq,
11147 					    phba->cfg_fcp_imax);
11148 			if (rc) {
11149 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11150 						"0523 Failed setup of fast-path"
11151 						" EQ (%d), rc = 0x%x\n",
11152 						cpup->eq, (uint32_t)rc);
11153 				goto out_destroy;
11154 			}
11155 
11156 			/* Save the EQ for that vector in the hba_eq_hdl */
11157 			phba->sli4_hba.hba_eq_hdl[cpup->eq].eq =
11158 				qp[cpup->hdwq].hba_eq;
11159 
11160 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11161 					"2584 HBA EQ setup: queue[%d]-id=%d\n",
11162 					cpup->eq,
11163 					qp[cpup->hdwq].hba_eq->queue_id);
11164 		}
11165 	}
11166 
11167 	/* Loop thru all Hardware Queues */
11168 	for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
11169 		cpu = lpfc_find_cpu_handle(phba, qidx, LPFC_FIND_BY_HDWQ);
11170 		cpup = &phba->sli4_hba.cpu_map[cpu];
11171 
11172 		/* Create the CQ/WQ corresponding to the Hardware Queue */
11173 		rc = lpfc_create_wq_cq(phba,
11174 				       phba->sli4_hba.hdwq[cpup->hdwq].hba_eq,
11175 				       qp[qidx].io_cq,
11176 				       qp[qidx].io_wq,
11177 				       &phba->sli4_hba.hdwq[qidx].io_cq_map,
11178 				       qidx,
11179 				       LPFC_IO);
11180 		if (rc) {
11181 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11182 					"0535 Failed to setup fastpath "
11183 					"IO WQ/CQ (%d), rc = 0x%x\n",
11184 					qidx, (uint32_t)rc);
11185 			goto out_destroy;
11186 		}
11187 	}
11188 
11189 	/*
11190 	 * Set up Slow Path Complete Queues (CQs)
11191 	 */
11192 
11193 	/* Set up slow-path MBOX CQ/MQ */
11194 
11195 	if (!phba->sli4_hba.mbx_cq || !phba->sli4_hba.mbx_wq) {
11196 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11197 				"0528 %s not allocated\n",
11198 				phba->sli4_hba.mbx_cq ?
11199 				"Mailbox WQ" : "Mailbox CQ");
11200 		rc = -ENOMEM;
11201 		goto out_destroy;
11202 	}
11203 
11204 	rc = lpfc_create_wq_cq(phba, qp[0].hba_eq,
11205 			       phba->sli4_hba.mbx_cq,
11206 			       phba->sli4_hba.mbx_wq,
11207 			       NULL, 0, LPFC_MBOX);
11208 	if (rc) {
11209 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11210 			"0529 Failed setup of mailbox WQ/CQ: rc = 0x%x\n",
11211 			(uint32_t)rc);
11212 		goto out_destroy;
11213 	}
11214 	if (phba->nvmet_support) {
11215 		if (!phba->sli4_hba.nvmet_cqset) {
11216 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11217 					"3165 Fast-path NVME CQ Set "
11218 					"array not allocated\n");
11219 			rc = -ENOMEM;
11220 			goto out_destroy;
11221 		}
11222 		if (phba->cfg_nvmet_mrq > 1) {
11223 			rc = lpfc_cq_create_set(phba,
11224 					phba->sli4_hba.nvmet_cqset,
11225 					qp,
11226 					LPFC_WCQ, LPFC_NVMET);
11227 			if (rc) {
11228 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11229 						"3164 Failed setup of NVME CQ "
11230 						"Set, rc = 0x%x\n",
11231 						(uint32_t)rc);
11232 				goto out_destroy;
11233 			}
11234 		} else {
11235 			/* Set up NVMET Receive Complete Queue */
11236 			rc = lpfc_cq_create(phba, phba->sli4_hba.nvmet_cqset[0],
11237 					    qp[0].hba_eq,
11238 					    LPFC_WCQ, LPFC_NVMET);
11239 			if (rc) {
11240 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11241 						"6089 Failed setup NVMET CQ: "
11242 						"rc = 0x%x\n", (uint32_t)rc);
11243 				goto out_destroy;
11244 			}
11245 			phba->sli4_hba.nvmet_cqset[0]->chann = 0;
11246 
11247 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11248 					"6090 NVMET CQ setup: cq-id=%d, "
11249 					"parent eq-id=%d\n",
11250 					phba->sli4_hba.nvmet_cqset[0]->queue_id,
11251 					qp[0].hba_eq->queue_id);
11252 		}
11253 	}
11254 
11255 	/* Set up slow-path ELS WQ/CQ */
11256 	if (!phba->sli4_hba.els_cq || !phba->sli4_hba.els_wq) {
11257 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11258 				"0530 ELS %s not allocated\n",
11259 				phba->sli4_hba.els_cq ? "WQ" : "CQ");
11260 		rc = -ENOMEM;
11261 		goto out_destroy;
11262 	}
11263 	rc = lpfc_create_wq_cq(phba, qp[0].hba_eq,
11264 			       phba->sli4_hba.els_cq,
11265 			       phba->sli4_hba.els_wq,
11266 			       NULL, 0, LPFC_ELS);
11267 	if (rc) {
11268 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11269 				"0525 Failed setup of ELS WQ/CQ: rc = 0x%x\n",
11270 				(uint32_t)rc);
11271 		goto out_destroy;
11272 	}
11273 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11274 			"2590 ELS WQ setup: wq-id=%d, parent cq-id=%d\n",
11275 			phba->sli4_hba.els_wq->queue_id,
11276 			phba->sli4_hba.els_cq->queue_id);
11277 
11278 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
11279 		/* Set up NVME LS Complete Queue */
11280 		if (!phba->sli4_hba.nvmels_cq || !phba->sli4_hba.nvmels_wq) {
11281 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11282 					"6091 LS %s not allocated\n",
11283 					phba->sli4_hba.nvmels_cq ? "WQ" : "CQ");
11284 			rc = -ENOMEM;
11285 			goto out_destroy;
11286 		}
11287 		rc = lpfc_create_wq_cq(phba, qp[0].hba_eq,
11288 				       phba->sli4_hba.nvmels_cq,
11289 				       phba->sli4_hba.nvmels_wq,
11290 				       NULL, 0, LPFC_NVME_LS);
11291 		if (rc) {
11292 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11293 					"0526 Failed setup of NVVME LS WQ/CQ: "
11294 					"rc = 0x%x\n", (uint32_t)rc);
11295 			goto out_destroy;
11296 		}
11297 
11298 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11299 				"6096 ELS WQ setup: wq-id=%d, "
11300 				"parent cq-id=%d\n",
11301 				phba->sli4_hba.nvmels_wq->queue_id,
11302 				phba->sli4_hba.nvmels_cq->queue_id);
11303 	}
11304 
11305 	/*
11306 	 * Create NVMET Receive Queue (RQ)
11307 	 */
11308 	if (phba->nvmet_support) {
11309 		if ((!phba->sli4_hba.nvmet_cqset) ||
11310 		    (!phba->sli4_hba.nvmet_mrq_hdr) ||
11311 		    (!phba->sli4_hba.nvmet_mrq_data)) {
11312 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11313 					"6130 MRQ CQ Queues not "
11314 					"allocated\n");
11315 			rc = -ENOMEM;
11316 			goto out_destroy;
11317 		}
11318 		if (phba->cfg_nvmet_mrq > 1) {
11319 			rc = lpfc_mrq_create(phba,
11320 					     phba->sli4_hba.nvmet_mrq_hdr,
11321 					     phba->sli4_hba.nvmet_mrq_data,
11322 					     phba->sli4_hba.nvmet_cqset,
11323 					     LPFC_NVMET);
11324 			if (rc) {
11325 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11326 						"6098 Failed setup of NVMET "
11327 						"MRQ: rc = 0x%x\n",
11328 						(uint32_t)rc);
11329 				goto out_destroy;
11330 			}
11331 
11332 		} else {
11333 			rc = lpfc_rq_create(phba,
11334 					    phba->sli4_hba.nvmet_mrq_hdr[0],
11335 					    phba->sli4_hba.nvmet_mrq_data[0],
11336 					    phba->sli4_hba.nvmet_cqset[0],
11337 					    LPFC_NVMET);
11338 			if (rc) {
11339 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11340 						"6057 Failed setup of NVMET "
11341 						"Receive Queue: rc = 0x%x\n",
11342 						(uint32_t)rc);
11343 				goto out_destroy;
11344 			}
11345 
11346 			lpfc_printf_log(
11347 				phba, KERN_INFO, LOG_INIT,
11348 				"6099 NVMET RQ setup: hdr-rq-id=%d, "
11349 				"dat-rq-id=%d parent cq-id=%d\n",
11350 				phba->sli4_hba.nvmet_mrq_hdr[0]->queue_id,
11351 				phba->sli4_hba.nvmet_mrq_data[0]->queue_id,
11352 				phba->sli4_hba.nvmet_cqset[0]->queue_id);
11353 
11354 		}
11355 	}
11356 
11357 	if (!phba->sli4_hba.hdr_rq || !phba->sli4_hba.dat_rq) {
11358 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11359 				"0540 Receive Queue not allocated\n");
11360 		rc = -ENOMEM;
11361 		goto out_destroy;
11362 	}
11363 
11364 	rc = lpfc_rq_create(phba, phba->sli4_hba.hdr_rq, phba->sli4_hba.dat_rq,
11365 			    phba->sli4_hba.els_cq, LPFC_USOL);
11366 	if (rc) {
11367 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11368 				"0541 Failed setup of Receive Queue: "
11369 				"rc = 0x%x\n", (uint32_t)rc);
11370 		goto out_destroy;
11371 	}
11372 
11373 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11374 			"2592 USL RQ setup: hdr-rq-id=%d, dat-rq-id=%d "
11375 			"parent cq-id=%d\n",
11376 			phba->sli4_hba.hdr_rq->queue_id,
11377 			phba->sli4_hba.dat_rq->queue_id,
11378 			phba->sli4_hba.els_cq->queue_id);
11379 
11380 	if (phba->cfg_fcp_imax)
11381 		usdelay = LPFC_SEC_TO_USEC / phba->cfg_fcp_imax;
11382 	else
11383 		usdelay = 0;
11384 
11385 	for (qidx = 0; qidx < phba->cfg_irq_chann;
11386 	     qidx += LPFC_MAX_EQ_DELAY_EQID_CNT)
11387 		lpfc_modify_hba_eq_delay(phba, qidx, LPFC_MAX_EQ_DELAY_EQID_CNT,
11388 					 usdelay);
11389 
11390 	if (phba->sli4_hba.cq_max) {
11391 		kfree(phba->sli4_hba.cq_lookup);
11392 		phba->sli4_hba.cq_lookup = kcalloc((phba->sli4_hba.cq_max + 1),
11393 			sizeof(struct lpfc_queue *), GFP_KERNEL);
11394 		if (!phba->sli4_hba.cq_lookup) {
11395 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11396 					"0549 Failed setup of CQ Lookup table: "
11397 					"size 0x%x\n", phba->sli4_hba.cq_max);
11398 			rc = -ENOMEM;
11399 			goto out_destroy;
11400 		}
11401 		lpfc_setup_cq_lookup(phba);
11402 	}
11403 	return 0;
11404 
11405 out_destroy:
11406 	lpfc_sli4_queue_unset(phba);
11407 out_error:
11408 	return rc;
11409 }
11410 
11411 /**
11412  * lpfc_sli4_queue_unset - Unset all the SLI4 queues
11413  * @phba: pointer to lpfc hba data structure.
11414  *
11415  * This routine is invoked to unset all the SLI4 queues with the FCoE HBA
11416  * operation.
11417  *
11418  * Return codes
11419  *      0 - successful
11420  *      -ENOMEM - No available memory
11421  *      -EIO - The mailbox failed to complete successfully.
11422  **/
11423 void
11424 lpfc_sli4_queue_unset(struct lpfc_hba *phba)
11425 {
11426 	struct lpfc_sli4_hdw_queue *qp;
11427 	struct lpfc_queue *eq;
11428 	int qidx;
11429 
11430 	/* Unset mailbox command work queue */
11431 	if (phba->sli4_hba.mbx_wq)
11432 		lpfc_mq_destroy(phba, phba->sli4_hba.mbx_wq);
11433 
11434 	/* Unset NVME LS work queue */
11435 	if (phba->sli4_hba.nvmels_wq)
11436 		lpfc_wq_destroy(phba, phba->sli4_hba.nvmels_wq);
11437 
11438 	/* Unset ELS work queue */
11439 	if (phba->sli4_hba.els_wq)
11440 		lpfc_wq_destroy(phba, phba->sli4_hba.els_wq);
11441 
11442 	/* Unset unsolicited receive queue */
11443 	if (phba->sli4_hba.hdr_rq)
11444 		lpfc_rq_destroy(phba, phba->sli4_hba.hdr_rq,
11445 				phba->sli4_hba.dat_rq);
11446 
11447 	/* Unset mailbox command complete queue */
11448 	if (phba->sli4_hba.mbx_cq)
11449 		lpfc_cq_destroy(phba, phba->sli4_hba.mbx_cq);
11450 
11451 	/* Unset ELS complete queue */
11452 	if (phba->sli4_hba.els_cq)
11453 		lpfc_cq_destroy(phba, phba->sli4_hba.els_cq);
11454 
11455 	/* Unset NVME LS complete queue */
11456 	if (phba->sli4_hba.nvmels_cq)
11457 		lpfc_cq_destroy(phba, phba->sli4_hba.nvmels_cq);
11458 
11459 	if (phba->nvmet_support) {
11460 		/* Unset NVMET MRQ queue */
11461 		if (phba->sli4_hba.nvmet_mrq_hdr) {
11462 			for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++)
11463 				lpfc_rq_destroy(
11464 					phba,
11465 					phba->sli4_hba.nvmet_mrq_hdr[qidx],
11466 					phba->sli4_hba.nvmet_mrq_data[qidx]);
11467 		}
11468 
11469 		/* Unset NVMET CQ Set complete queue */
11470 		if (phba->sli4_hba.nvmet_cqset) {
11471 			for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++)
11472 				lpfc_cq_destroy(
11473 					phba, phba->sli4_hba.nvmet_cqset[qidx]);
11474 		}
11475 	}
11476 
11477 	/* Unset fast-path SLI4 queues */
11478 	if (phba->sli4_hba.hdwq) {
11479 		/* Loop thru all Hardware Queues */
11480 		for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
11481 			/* Destroy the CQ/WQ corresponding to Hardware Queue */
11482 			qp = &phba->sli4_hba.hdwq[qidx];
11483 			lpfc_wq_destroy(phba, qp->io_wq);
11484 			lpfc_cq_destroy(phba, qp->io_cq);
11485 		}
11486 		/* Loop thru all IRQ vectors */
11487 		for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
11488 			/* Destroy the EQ corresponding to the IRQ vector */
11489 			eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
11490 			lpfc_eq_destroy(phba, eq);
11491 		}
11492 	}
11493 
11494 	kfree(phba->sli4_hba.cq_lookup);
11495 	phba->sli4_hba.cq_lookup = NULL;
11496 	phba->sli4_hba.cq_max = 0;
11497 }
11498 
11499 /**
11500  * lpfc_sli4_cq_event_pool_create - Create completion-queue event free pool
11501  * @phba: pointer to lpfc hba data structure.
11502  *
11503  * This routine is invoked to allocate and set up a pool of completion queue
11504  * events. The body of the completion queue event is a completion queue entry
11505  * CQE. For now, this pool is used for the interrupt service routine to queue
11506  * the following HBA completion queue events for the worker thread to process:
11507  *   - Mailbox asynchronous events
11508  *   - Receive queue completion unsolicited events
11509  * Later, this can be used for all the slow-path events.
11510  *
11511  * Return codes
11512  *      0 - successful
11513  *      -ENOMEM - No available memory
11514  **/
11515 static int
11516 lpfc_sli4_cq_event_pool_create(struct lpfc_hba *phba)
11517 {
11518 	struct lpfc_cq_event *cq_event;
11519 	int i;
11520 
11521 	for (i = 0; i < (4 * phba->sli4_hba.cq_ecount); i++) {
11522 		cq_event = kmalloc(sizeof(struct lpfc_cq_event), GFP_KERNEL);
11523 		if (!cq_event)
11524 			goto out_pool_create_fail;
11525 		list_add_tail(&cq_event->list,
11526 			      &phba->sli4_hba.sp_cqe_event_pool);
11527 	}
11528 	return 0;
11529 
11530 out_pool_create_fail:
11531 	lpfc_sli4_cq_event_pool_destroy(phba);
11532 	return -ENOMEM;
11533 }
11534 
11535 /**
11536  * lpfc_sli4_cq_event_pool_destroy - Free completion-queue event free pool
11537  * @phba: pointer to lpfc hba data structure.
11538  *
11539  * This routine is invoked to free the pool of completion queue events at
11540  * driver unload time. Note that, it is the responsibility of the driver
11541  * cleanup routine to free all the outstanding completion-queue events
11542  * allocated from this pool back into the pool before invoking this routine
11543  * to destroy the pool.
11544  **/
11545 static void
11546 lpfc_sli4_cq_event_pool_destroy(struct lpfc_hba *phba)
11547 {
11548 	struct lpfc_cq_event *cq_event, *next_cq_event;
11549 
11550 	list_for_each_entry_safe(cq_event, next_cq_event,
11551 				 &phba->sli4_hba.sp_cqe_event_pool, list) {
11552 		list_del(&cq_event->list);
11553 		kfree(cq_event);
11554 	}
11555 }
11556 
11557 /**
11558  * __lpfc_sli4_cq_event_alloc - Allocate a completion-queue event from free pool
11559  * @phba: pointer to lpfc hba data structure.
11560  *
11561  * This routine is the lock free version of the API invoked to allocate a
11562  * completion-queue event from the free pool.
11563  *
11564  * Return: Pointer to the newly allocated completion-queue event if successful
11565  *         NULL otherwise.
11566  **/
11567 struct lpfc_cq_event *
11568 __lpfc_sli4_cq_event_alloc(struct lpfc_hba *phba)
11569 {
11570 	struct lpfc_cq_event *cq_event = NULL;
11571 
11572 	list_remove_head(&phba->sli4_hba.sp_cqe_event_pool, cq_event,
11573 			 struct lpfc_cq_event, list);
11574 	return cq_event;
11575 }
11576 
11577 /**
11578  * lpfc_sli4_cq_event_alloc - Allocate a completion-queue event from free pool
11579  * @phba: pointer to lpfc hba data structure.
11580  *
11581  * This routine is the lock version of the API invoked to allocate a
11582  * completion-queue event from the free pool.
11583  *
11584  * Return: Pointer to the newly allocated completion-queue event if successful
11585  *         NULL otherwise.
11586  **/
11587 struct lpfc_cq_event *
11588 lpfc_sli4_cq_event_alloc(struct lpfc_hba *phba)
11589 {
11590 	struct lpfc_cq_event *cq_event;
11591 	unsigned long iflags;
11592 
11593 	spin_lock_irqsave(&phba->hbalock, iflags);
11594 	cq_event = __lpfc_sli4_cq_event_alloc(phba);
11595 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11596 	return cq_event;
11597 }
11598 
11599 /**
11600  * __lpfc_sli4_cq_event_release - Release a completion-queue event to free pool
11601  * @phba: pointer to lpfc hba data structure.
11602  * @cq_event: pointer to the completion queue event to be freed.
11603  *
11604  * This routine is the lock free version of the API invoked to release a
11605  * completion-queue event back into the free pool.
11606  **/
11607 void
11608 __lpfc_sli4_cq_event_release(struct lpfc_hba *phba,
11609 			     struct lpfc_cq_event *cq_event)
11610 {
11611 	list_add_tail(&cq_event->list, &phba->sli4_hba.sp_cqe_event_pool);
11612 }
11613 
11614 /**
11615  * lpfc_sli4_cq_event_release - Release a completion-queue event to free pool
11616  * @phba: pointer to lpfc hba data structure.
11617  * @cq_event: pointer to the completion queue event to be freed.
11618  *
11619  * This routine is the lock version of the API invoked to release a
11620  * completion-queue event back into the free pool.
11621  **/
11622 void
11623 lpfc_sli4_cq_event_release(struct lpfc_hba *phba,
11624 			   struct lpfc_cq_event *cq_event)
11625 {
11626 	unsigned long iflags;
11627 	spin_lock_irqsave(&phba->hbalock, iflags);
11628 	__lpfc_sli4_cq_event_release(phba, cq_event);
11629 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11630 }
11631 
11632 /**
11633  * lpfc_sli4_cq_event_release_all - Release all cq events to the free pool
11634  * @phba: pointer to lpfc hba data structure.
11635  *
11636  * This routine is to free all the pending completion-queue events to the
11637  * back into the free pool for device reset.
11638  **/
11639 static void
11640 lpfc_sli4_cq_event_release_all(struct lpfc_hba *phba)
11641 {
11642 	LIST_HEAD(cq_event_list);
11643 	struct lpfc_cq_event *cq_event;
11644 	unsigned long iflags;
11645 
11646 	/* Retrieve all the pending WCQEs from pending WCQE lists */
11647 
11648 	/* Pending ELS XRI abort events */
11649 	spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
11650 	list_splice_init(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
11651 			 &cq_event_list);
11652 	spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
11653 
11654 	/* Pending asynnc events */
11655 	spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
11656 	list_splice_init(&phba->sli4_hba.sp_asynce_work_queue,
11657 			 &cq_event_list);
11658 	spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock, iflags);
11659 
11660 	while (!list_empty(&cq_event_list)) {
11661 		list_remove_head(&cq_event_list, cq_event,
11662 				 struct lpfc_cq_event, list);
11663 		lpfc_sli4_cq_event_release(phba, cq_event);
11664 	}
11665 }
11666 
11667 /**
11668  * lpfc_pci_function_reset - Reset pci function.
11669  * @phba: pointer to lpfc hba data structure.
11670  *
11671  * This routine is invoked to request a PCI function reset. It will destroys
11672  * all resources assigned to the PCI function which originates this request.
11673  *
11674  * Return codes
11675  *      0 - successful
11676  *      -ENOMEM - No available memory
11677  *      -EIO - The mailbox failed to complete successfully.
11678  **/
11679 int
11680 lpfc_pci_function_reset(struct lpfc_hba *phba)
11681 {
11682 	LPFC_MBOXQ_t *mboxq;
11683 	uint32_t rc = 0, if_type;
11684 	uint32_t shdr_status, shdr_add_status;
11685 	uint32_t rdy_chk;
11686 	uint32_t port_reset = 0;
11687 	union lpfc_sli4_cfg_shdr *shdr;
11688 	struct lpfc_register reg_data;
11689 	uint16_t devid;
11690 
11691 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
11692 	switch (if_type) {
11693 	case LPFC_SLI_INTF_IF_TYPE_0:
11694 		mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
11695 						       GFP_KERNEL);
11696 		if (!mboxq) {
11697 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11698 					"0494 Unable to allocate memory for "
11699 					"issuing SLI_FUNCTION_RESET mailbox "
11700 					"command\n");
11701 			return -ENOMEM;
11702 		}
11703 
11704 		/* Setup PCI function reset mailbox-ioctl command */
11705 		lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
11706 				 LPFC_MBOX_OPCODE_FUNCTION_RESET, 0,
11707 				 LPFC_SLI4_MBX_EMBED);
11708 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
11709 		shdr = (union lpfc_sli4_cfg_shdr *)
11710 			&mboxq->u.mqe.un.sli4_config.header.cfg_shdr;
11711 		shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
11712 		shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
11713 					 &shdr->response);
11714 		mempool_free(mboxq, phba->mbox_mem_pool);
11715 		if (shdr_status || shdr_add_status || rc) {
11716 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11717 					"0495 SLI_FUNCTION_RESET mailbox "
11718 					"failed with status x%x add_status x%x,"
11719 					" mbx status x%x\n",
11720 					shdr_status, shdr_add_status, rc);
11721 			rc = -ENXIO;
11722 		}
11723 		break;
11724 	case LPFC_SLI_INTF_IF_TYPE_2:
11725 	case LPFC_SLI_INTF_IF_TYPE_6:
11726 wait:
11727 		/*
11728 		 * Poll the Port Status Register and wait for RDY for
11729 		 * up to 30 seconds. If the port doesn't respond, treat
11730 		 * it as an error.
11731 		 */
11732 		for (rdy_chk = 0; rdy_chk < 1500; rdy_chk++) {
11733 			if (lpfc_readl(phba->sli4_hba.u.if_type2.
11734 				STATUSregaddr, &reg_data.word0)) {
11735 				rc = -ENODEV;
11736 				goto out;
11737 			}
11738 			if (bf_get(lpfc_sliport_status_rdy, &reg_data))
11739 				break;
11740 			msleep(20);
11741 		}
11742 
11743 		if (!bf_get(lpfc_sliport_status_rdy, &reg_data)) {
11744 			phba->work_status[0] = readl(
11745 				phba->sli4_hba.u.if_type2.ERR1regaddr);
11746 			phba->work_status[1] = readl(
11747 				phba->sli4_hba.u.if_type2.ERR2regaddr);
11748 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11749 					"2890 Port not ready, port status reg "
11750 					"0x%x error 1=0x%x, error 2=0x%x\n",
11751 					reg_data.word0,
11752 					phba->work_status[0],
11753 					phba->work_status[1]);
11754 			rc = -ENODEV;
11755 			goto out;
11756 		}
11757 
11758 		if (bf_get(lpfc_sliport_status_pldv, &reg_data))
11759 			lpfc_pldv_detect = true;
11760 
11761 		if (!port_reset) {
11762 			/*
11763 			 * Reset the port now
11764 			 */
11765 			reg_data.word0 = 0;
11766 			bf_set(lpfc_sliport_ctrl_end, &reg_data,
11767 			       LPFC_SLIPORT_LITTLE_ENDIAN);
11768 			bf_set(lpfc_sliport_ctrl_ip, &reg_data,
11769 			       LPFC_SLIPORT_INIT_PORT);
11770 			writel(reg_data.word0, phba->sli4_hba.u.if_type2.
11771 			       CTRLregaddr);
11772 			/* flush */
11773 			pci_read_config_word(phba->pcidev,
11774 					     PCI_DEVICE_ID, &devid);
11775 
11776 			port_reset = 1;
11777 			msleep(20);
11778 			goto wait;
11779 		} else if (bf_get(lpfc_sliport_status_rn, &reg_data)) {
11780 			rc = -ENODEV;
11781 			goto out;
11782 		}
11783 		break;
11784 
11785 	case LPFC_SLI_INTF_IF_TYPE_1:
11786 	default:
11787 		break;
11788 	}
11789 
11790 out:
11791 	/* Catch the not-ready port failure after a port reset. */
11792 	if (rc) {
11793 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11794 				"3317 HBA not functional: IP Reset Failed "
11795 				"try: echo fw_reset > board_mode\n");
11796 		rc = -ENODEV;
11797 	}
11798 
11799 	return rc;
11800 }
11801 
11802 /**
11803  * lpfc_sli4_pci_mem_setup - Setup SLI4 HBA PCI memory space.
11804  * @phba: pointer to lpfc hba data structure.
11805  *
11806  * This routine is invoked to set up the PCI device memory space for device
11807  * with SLI-4 interface spec.
11808  *
11809  * Return codes
11810  * 	0 - successful
11811  * 	other values - error
11812  **/
11813 static int
11814 lpfc_sli4_pci_mem_setup(struct lpfc_hba *phba)
11815 {
11816 	struct pci_dev *pdev = phba->pcidev;
11817 	unsigned long bar0map_len, bar1map_len, bar2map_len;
11818 	int error;
11819 	uint32_t if_type;
11820 
11821 	if (!pdev)
11822 		return -ENODEV;
11823 
11824 	/* Set the device DMA mask size */
11825 	error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
11826 	if (error)
11827 		error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32));
11828 	if (error)
11829 		return error;
11830 
11831 	/*
11832 	 * The BARs and register set definitions and offset locations are
11833 	 * dependent on the if_type.
11834 	 */
11835 	if (pci_read_config_dword(pdev, LPFC_SLI_INTF,
11836 				  &phba->sli4_hba.sli_intf.word0)) {
11837 		return -ENODEV;
11838 	}
11839 
11840 	/* There is no SLI3 failback for SLI4 devices. */
11841 	if (bf_get(lpfc_sli_intf_valid, &phba->sli4_hba.sli_intf) !=
11842 	    LPFC_SLI_INTF_VALID) {
11843 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11844 				"2894 SLI_INTF reg contents invalid "
11845 				"sli_intf reg 0x%x\n",
11846 				phba->sli4_hba.sli_intf.word0);
11847 		return -ENODEV;
11848 	}
11849 
11850 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
11851 	/*
11852 	 * Get the bus address of SLI4 device Bar regions and the
11853 	 * number of bytes required by each mapping. The mapping of the
11854 	 * particular PCI BARs regions is dependent on the type of
11855 	 * SLI4 device.
11856 	 */
11857 	if (pci_resource_start(pdev, PCI_64BIT_BAR0)) {
11858 		phba->pci_bar0_map = pci_resource_start(pdev, PCI_64BIT_BAR0);
11859 		bar0map_len = pci_resource_len(pdev, PCI_64BIT_BAR0);
11860 
11861 		/*
11862 		 * Map SLI4 PCI Config Space Register base to a kernel virtual
11863 		 * addr
11864 		 */
11865 		phba->sli4_hba.conf_regs_memmap_p =
11866 			ioremap(phba->pci_bar0_map, bar0map_len);
11867 		if (!phba->sli4_hba.conf_regs_memmap_p) {
11868 			dev_printk(KERN_ERR, &pdev->dev,
11869 				   "ioremap failed for SLI4 PCI config "
11870 				   "registers.\n");
11871 			return -ENODEV;
11872 		}
11873 		phba->pci_bar0_memmap_p = phba->sli4_hba.conf_regs_memmap_p;
11874 		/* Set up BAR0 PCI config space register memory map */
11875 		lpfc_sli4_bar0_register_memmap(phba, if_type);
11876 	} else {
11877 		phba->pci_bar0_map = pci_resource_start(pdev, 1);
11878 		bar0map_len = pci_resource_len(pdev, 1);
11879 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
11880 			dev_printk(KERN_ERR, &pdev->dev,
11881 			   "FATAL - No BAR0 mapping for SLI4, if_type 2\n");
11882 			return -ENODEV;
11883 		}
11884 		phba->sli4_hba.conf_regs_memmap_p =
11885 				ioremap(phba->pci_bar0_map, bar0map_len);
11886 		if (!phba->sli4_hba.conf_regs_memmap_p) {
11887 			dev_printk(KERN_ERR, &pdev->dev,
11888 				"ioremap failed for SLI4 PCI config "
11889 				"registers.\n");
11890 			return -ENODEV;
11891 		}
11892 		lpfc_sli4_bar0_register_memmap(phba, if_type);
11893 	}
11894 
11895 	if (if_type == LPFC_SLI_INTF_IF_TYPE_0) {
11896 		if (pci_resource_start(pdev, PCI_64BIT_BAR2)) {
11897 			/*
11898 			 * Map SLI4 if type 0 HBA Control Register base to a
11899 			 * kernel virtual address and setup the registers.
11900 			 */
11901 			phba->pci_bar1_map = pci_resource_start(pdev,
11902 								PCI_64BIT_BAR2);
11903 			bar1map_len = pci_resource_len(pdev, PCI_64BIT_BAR2);
11904 			phba->sli4_hba.ctrl_regs_memmap_p =
11905 					ioremap(phba->pci_bar1_map,
11906 						bar1map_len);
11907 			if (!phba->sli4_hba.ctrl_regs_memmap_p) {
11908 				dev_err(&pdev->dev,
11909 					   "ioremap failed for SLI4 HBA "
11910 					    "control registers.\n");
11911 				error = -ENOMEM;
11912 				goto out_iounmap_conf;
11913 			}
11914 			phba->pci_bar2_memmap_p =
11915 					 phba->sli4_hba.ctrl_regs_memmap_p;
11916 			lpfc_sli4_bar1_register_memmap(phba, if_type);
11917 		} else {
11918 			error = -ENOMEM;
11919 			goto out_iounmap_conf;
11920 		}
11921 	}
11922 
11923 	if ((if_type == LPFC_SLI_INTF_IF_TYPE_6) &&
11924 	    (pci_resource_start(pdev, PCI_64BIT_BAR2))) {
11925 		/*
11926 		 * Map SLI4 if type 6 HBA Doorbell Register base to a kernel
11927 		 * virtual address and setup the registers.
11928 		 */
11929 		phba->pci_bar1_map = pci_resource_start(pdev, PCI_64BIT_BAR2);
11930 		bar1map_len = pci_resource_len(pdev, PCI_64BIT_BAR2);
11931 		phba->sli4_hba.drbl_regs_memmap_p =
11932 				ioremap(phba->pci_bar1_map, bar1map_len);
11933 		if (!phba->sli4_hba.drbl_regs_memmap_p) {
11934 			dev_err(&pdev->dev,
11935 			   "ioremap failed for SLI4 HBA doorbell registers.\n");
11936 			error = -ENOMEM;
11937 			goto out_iounmap_conf;
11938 		}
11939 		phba->pci_bar2_memmap_p = phba->sli4_hba.drbl_regs_memmap_p;
11940 		lpfc_sli4_bar1_register_memmap(phba, if_type);
11941 	}
11942 
11943 	if (if_type == LPFC_SLI_INTF_IF_TYPE_0) {
11944 		if (pci_resource_start(pdev, PCI_64BIT_BAR4)) {
11945 			/*
11946 			 * Map SLI4 if type 0 HBA Doorbell Register base to
11947 			 * a kernel virtual address and setup the registers.
11948 			 */
11949 			phba->pci_bar2_map = pci_resource_start(pdev,
11950 								PCI_64BIT_BAR4);
11951 			bar2map_len = pci_resource_len(pdev, PCI_64BIT_BAR4);
11952 			phba->sli4_hba.drbl_regs_memmap_p =
11953 					ioremap(phba->pci_bar2_map,
11954 						bar2map_len);
11955 			if (!phba->sli4_hba.drbl_regs_memmap_p) {
11956 				dev_err(&pdev->dev,
11957 					   "ioremap failed for SLI4 HBA"
11958 					   " doorbell registers.\n");
11959 				error = -ENOMEM;
11960 				goto out_iounmap_ctrl;
11961 			}
11962 			phba->pci_bar4_memmap_p =
11963 					phba->sli4_hba.drbl_regs_memmap_p;
11964 			error = lpfc_sli4_bar2_register_memmap(phba, LPFC_VF0);
11965 			if (error)
11966 				goto out_iounmap_all;
11967 		} else {
11968 			error = -ENOMEM;
11969 			goto out_iounmap_ctrl;
11970 		}
11971 	}
11972 
11973 	if (if_type == LPFC_SLI_INTF_IF_TYPE_6 &&
11974 	    pci_resource_start(pdev, PCI_64BIT_BAR4)) {
11975 		/*
11976 		 * Map SLI4 if type 6 HBA DPP Register base to a kernel
11977 		 * virtual address and setup the registers.
11978 		 */
11979 		phba->pci_bar2_map = pci_resource_start(pdev, PCI_64BIT_BAR4);
11980 		bar2map_len = pci_resource_len(pdev, PCI_64BIT_BAR4);
11981 		phba->sli4_hba.dpp_regs_memmap_p =
11982 				ioremap(phba->pci_bar2_map, bar2map_len);
11983 		if (!phba->sli4_hba.dpp_regs_memmap_p) {
11984 			dev_err(&pdev->dev,
11985 			   "ioremap failed for SLI4 HBA dpp registers.\n");
11986 			error = -ENOMEM;
11987 			goto out_iounmap_all;
11988 		}
11989 		phba->pci_bar4_memmap_p = phba->sli4_hba.dpp_regs_memmap_p;
11990 	}
11991 
11992 	/* Set up the EQ/CQ register handeling functions now */
11993 	switch (if_type) {
11994 	case LPFC_SLI_INTF_IF_TYPE_0:
11995 	case LPFC_SLI_INTF_IF_TYPE_2:
11996 		phba->sli4_hba.sli4_eq_clr_intr = lpfc_sli4_eq_clr_intr;
11997 		phba->sli4_hba.sli4_write_eq_db = lpfc_sli4_write_eq_db;
11998 		phba->sli4_hba.sli4_write_cq_db = lpfc_sli4_write_cq_db;
11999 		break;
12000 	case LPFC_SLI_INTF_IF_TYPE_6:
12001 		phba->sli4_hba.sli4_eq_clr_intr = lpfc_sli4_if6_eq_clr_intr;
12002 		phba->sli4_hba.sli4_write_eq_db = lpfc_sli4_if6_write_eq_db;
12003 		phba->sli4_hba.sli4_write_cq_db = lpfc_sli4_if6_write_cq_db;
12004 		break;
12005 	default:
12006 		break;
12007 	}
12008 
12009 	return 0;
12010 
12011 out_iounmap_all:
12012 	if (phba->sli4_hba.drbl_regs_memmap_p)
12013 		iounmap(phba->sli4_hba.drbl_regs_memmap_p);
12014 out_iounmap_ctrl:
12015 	if (phba->sli4_hba.ctrl_regs_memmap_p)
12016 		iounmap(phba->sli4_hba.ctrl_regs_memmap_p);
12017 out_iounmap_conf:
12018 	iounmap(phba->sli4_hba.conf_regs_memmap_p);
12019 
12020 	return error;
12021 }
12022 
12023 /**
12024  * lpfc_sli4_pci_mem_unset - Unset SLI4 HBA PCI memory space.
12025  * @phba: pointer to lpfc hba data structure.
12026  *
12027  * This routine is invoked to unset the PCI device memory space for device
12028  * with SLI-4 interface spec.
12029  **/
12030 static void
12031 lpfc_sli4_pci_mem_unset(struct lpfc_hba *phba)
12032 {
12033 	uint32_t if_type;
12034 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
12035 
12036 	switch (if_type) {
12037 	case LPFC_SLI_INTF_IF_TYPE_0:
12038 		iounmap(phba->sli4_hba.drbl_regs_memmap_p);
12039 		iounmap(phba->sli4_hba.ctrl_regs_memmap_p);
12040 		iounmap(phba->sli4_hba.conf_regs_memmap_p);
12041 		break;
12042 	case LPFC_SLI_INTF_IF_TYPE_2:
12043 		iounmap(phba->sli4_hba.conf_regs_memmap_p);
12044 		break;
12045 	case LPFC_SLI_INTF_IF_TYPE_6:
12046 		iounmap(phba->sli4_hba.drbl_regs_memmap_p);
12047 		iounmap(phba->sli4_hba.conf_regs_memmap_p);
12048 		if (phba->sli4_hba.dpp_regs_memmap_p)
12049 			iounmap(phba->sli4_hba.dpp_regs_memmap_p);
12050 		break;
12051 	case LPFC_SLI_INTF_IF_TYPE_1:
12052 		break;
12053 	default:
12054 		dev_printk(KERN_ERR, &phba->pcidev->dev,
12055 			   "FATAL - unsupported SLI4 interface type - %d\n",
12056 			   if_type);
12057 		break;
12058 	}
12059 }
12060 
12061 /**
12062  * lpfc_sli_enable_msix - Enable MSI-X interrupt mode on SLI-3 device
12063  * @phba: pointer to lpfc hba data structure.
12064  *
12065  * This routine is invoked to enable the MSI-X interrupt vectors to device
12066  * with SLI-3 interface specs.
12067  *
12068  * Return codes
12069  *   0 - successful
12070  *   other values - error
12071  **/
12072 static int
12073 lpfc_sli_enable_msix(struct lpfc_hba *phba)
12074 {
12075 	int rc;
12076 	LPFC_MBOXQ_t *pmb;
12077 
12078 	/* Set up MSI-X multi-message vectors */
12079 	rc = pci_alloc_irq_vectors(phba->pcidev,
12080 			LPFC_MSIX_VECTORS, LPFC_MSIX_VECTORS, PCI_IRQ_MSIX);
12081 	if (rc < 0) {
12082 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12083 				"0420 PCI enable MSI-X failed (%d)\n", rc);
12084 		goto vec_fail_out;
12085 	}
12086 
12087 	/*
12088 	 * Assign MSI-X vectors to interrupt handlers
12089 	 */
12090 
12091 	/* vector-0 is associated to slow-path handler */
12092 	rc = request_irq(pci_irq_vector(phba->pcidev, 0),
12093 			 &lpfc_sli_sp_intr_handler, 0,
12094 			 LPFC_SP_DRIVER_HANDLER_NAME, phba);
12095 	if (rc) {
12096 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
12097 				"0421 MSI-X slow-path request_irq failed "
12098 				"(%d)\n", rc);
12099 		goto msi_fail_out;
12100 	}
12101 
12102 	/* vector-1 is associated to fast-path handler */
12103 	rc = request_irq(pci_irq_vector(phba->pcidev, 1),
12104 			 &lpfc_sli_fp_intr_handler, 0,
12105 			 LPFC_FP_DRIVER_HANDLER_NAME, phba);
12106 
12107 	if (rc) {
12108 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
12109 				"0429 MSI-X fast-path request_irq failed "
12110 				"(%d)\n", rc);
12111 		goto irq_fail_out;
12112 	}
12113 
12114 	/*
12115 	 * Configure HBA MSI-X attention conditions to messages
12116 	 */
12117 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
12118 
12119 	if (!pmb) {
12120 		rc = -ENOMEM;
12121 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12122 				"0474 Unable to allocate memory for issuing "
12123 				"MBOX_CONFIG_MSI command\n");
12124 		goto mem_fail_out;
12125 	}
12126 	rc = lpfc_config_msi(phba, pmb);
12127 	if (rc)
12128 		goto mbx_fail_out;
12129 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
12130 	if (rc != MBX_SUCCESS) {
12131 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX,
12132 				"0351 Config MSI mailbox command failed, "
12133 				"mbxCmd x%x, mbxStatus x%x\n",
12134 				pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus);
12135 		goto mbx_fail_out;
12136 	}
12137 
12138 	/* Free memory allocated for mailbox command */
12139 	mempool_free(pmb, phba->mbox_mem_pool);
12140 	return rc;
12141 
12142 mbx_fail_out:
12143 	/* Free memory allocated for mailbox command */
12144 	mempool_free(pmb, phba->mbox_mem_pool);
12145 
12146 mem_fail_out:
12147 	/* free the irq already requested */
12148 	free_irq(pci_irq_vector(phba->pcidev, 1), phba);
12149 
12150 irq_fail_out:
12151 	/* free the irq already requested */
12152 	free_irq(pci_irq_vector(phba->pcidev, 0), phba);
12153 
12154 msi_fail_out:
12155 	/* Unconfigure MSI-X capability structure */
12156 	pci_free_irq_vectors(phba->pcidev);
12157 
12158 vec_fail_out:
12159 	return rc;
12160 }
12161 
12162 /**
12163  * lpfc_sli_enable_msi - Enable MSI interrupt mode on SLI-3 device.
12164  * @phba: pointer to lpfc hba data structure.
12165  *
12166  * This routine is invoked to enable the MSI interrupt mode to device with
12167  * SLI-3 interface spec. The kernel function pci_enable_msi() is called to
12168  * enable the MSI vector. The device driver is responsible for calling the
12169  * request_irq() to register MSI vector with a interrupt the handler, which
12170  * is done in this function.
12171  *
12172  * Return codes
12173  * 	0 - successful
12174  * 	other values - error
12175  */
12176 static int
12177 lpfc_sli_enable_msi(struct lpfc_hba *phba)
12178 {
12179 	int rc;
12180 
12181 	rc = pci_enable_msi(phba->pcidev);
12182 	if (!rc)
12183 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12184 				"0012 PCI enable MSI mode success.\n");
12185 	else {
12186 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12187 				"0471 PCI enable MSI mode failed (%d)\n", rc);
12188 		return rc;
12189 	}
12190 
12191 	rc = request_irq(phba->pcidev->irq, lpfc_sli_intr_handler,
12192 			 0, LPFC_DRIVER_NAME, phba);
12193 	if (rc) {
12194 		pci_disable_msi(phba->pcidev);
12195 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
12196 				"0478 MSI request_irq failed (%d)\n", rc);
12197 	}
12198 	return rc;
12199 }
12200 
12201 /**
12202  * lpfc_sli_enable_intr - Enable device interrupt to SLI-3 device.
12203  * @phba: pointer to lpfc hba data structure.
12204  * @cfg_mode: Interrupt configuration mode (INTx, MSI or MSI-X).
12205  *
12206  * This routine is invoked to enable device interrupt and associate driver's
12207  * interrupt handler(s) to interrupt vector(s) to device with SLI-3 interface
12208  * spec. Depends on the interrupt mode configured to the driver, the driver
12209  * will try to fallback from the configured interrupt mode to an interrupt
12210  * mode which is supported by the platform, kernel, and device in the order
12211  * of:
12212  * MSI-X -> MSI -> IRQ.
12213  *
12214  * Return codes
12215  *   0 - successful
12216  *   other values - error
12217  **/
12218 static uint32_t
12219 lpfc_sli_enable_intr(struct lpfc_hba *phba, uint32_t cfg_mode)
12220 {
12221 	uint32_t intr_mode = LPFC_INTR_ERROR;
12222 	int retval;
12223 
12224 	/* Need to issue conf_port mbox cmd before conf_msi mbox cmd */
12225 	retval = lpfc_sli_config_port(phba, LPFC_SLI_REV3);
12226 	if (retval)
12227 		return intr_mode;
12228 	clear_bit(HBA_NEEDS_CFG_PORT, &phba->hba_flag);
12229 
12230 	if (cfg_mode == 2) {
12231 		/* Now, try to enable MSI-X interrupt mode */
12232 		retval = lpfc_sli_enable_msix(phba);
12233 		if (!retval) {
12234 			/* Indicate initialization to MSI-X mode */
12235 			phba->intr_type = MSIX;
12236 			intr_mode = 2;
12237 		}
12238 	}
12239 
12240 	/* Fallback to MSI if MSI-X initialization failed */
12241 	if (cfg_mode >= 1 && phba->intr_type == NONE) {
12242 		retval = lpfc_sli_enable_msi(phba);
12243 		if (!retval) {
12244 			/* Indicate initialization to MSI mode */
12245 			phba->intr_type = MSI;
12246 			intr_mode = 1;
12247 		}
12248 	}
12249 
12250 	/* Fallback to INTx if both MSI-X/MSI initalization failed */
12251 	if (phba->intr_type == NONE) {
12252 		retval = request_irq(phba->pcidev->irq, lpfc_sli_intr_handler,
12253 				     IRQF_SHARED, LPFC_DRIVER_NAME, phba);
12254 		if (!retval) {
12255 			/* Indicate initialization to INTx mode */
12256 			phba->intr_type = INTx;
12257 			intr_mode = 0;
12258 		}
12259 	}
12260 	return intr_mode;
12261 }
12262 
12263 /**
12264  * lpfc_sli_disable_intr - Disable device interrupt to SLI-3 device.
12265  * @phba: pointer to lpfc hba data structure.
12266  *
12267  * This routine is invoked to disable device interrupt and disassociate the
12268  * driver's interrupt handler(s) from interrupt vector(s) to device with
12269  * SLI-3 interface spec. Depending on the interrupt mode, the driver will
12270  * release the interrupt vector(s) for the message signaled interrupt.
12271  **/
12272 static void
12273 lpfc_sli_disable_intr(struct lpfc_hba *phba)
12274 {
12275 	int nr_irqs, i;
12276 
12277 	if (phba->intr_type == MSIX)
12278 		nr_irqs = LPFC_MSIX_VECTORS;
12279 	else
12280 		nr_irqs = 1;
12281 
12282 	for (i = 0; i < nr_irqs; i++)
12283 		free_irq(pci_irq_vector(phba->pcidev, i), phba);
12284 	pci_free_irq_vectors(phba->pcidev);
12285 
12286 	/* Reset interrupt management states */
12287 	phba->intr_type = NONE;
12288 	phba->sli.slistat.sli_intr = 0;
12289 }
12290 
12291 /**
12292  * lpfc_find_cpu_handle - Find the CPU that corresponds to the specified Queue
12293  * @phba: pointer to lpfc hba data structure.
12294  * @id: EQ vector index or Hardware Queue index
12295  * @match: LPFC_FIND_BY_EQ = match by EQ
12296  *         LPFC_FIND_BY_HDWQ = match by Hardware Queue
12297  * Return the CPU that matches the selection criteria
12298  */
12299 static uint16_t
12300 lpfc_find_cpu_handle(struct lpfc_hba *phba, uint16_t id, int match)
12301 {
12302 	struct lpfc_vector_map_info *cpup;
12303 	int cpu;
12304 
12305 	/* Loop through all CPUs */
12306 	for_each_present_cpu(cpu) {
12307 		cpup = &phba->sli4_hba.cpu_map[cpu];
12308 
12309 		/* If we are matching by EQ, there may be multiple CPUs using
12310 		 * using the same vector, so select the one with
12311 		 * LPFC_CPU_FIRST_IRQ set.
12312 		 */
12313 		if ((match == LPFC_FIND_BY_EQ) &&
12314 		    (cpup->flag & LPFC_CPU_FIRST_IRQ) &&
12315 		    (cpup->eq == id))
12316 			return cpu;
12317 
12318 		/* If matching by HDWQ, select the first CPU that matches */
12319 		if ((match == LPFC_FIND_BY_HDWQ) && (cpup->hdwq == id))
12320 			return cpu;
12321 	}
12322 	return 0;
12323 }
12324 
12325 #ifdef CONFIG_X86
12326 /**
12327  * lpfc_find_hyper - Determine if the CPU map entry is hyper-threaded
12328  * @phba: pointer to lpfc hba data structure.
12329  * @cpu: CPU map index
12330  * @phys_id: CPU package physical id
12331  * @core_id: CPU core id
12332  */
12333 static int
12334 lpfc_find_hyper(struct lpfc_hba *phba, int cpu,
12335 		uint16_t phys_id, uint16_t core_id)
12336 {
12337 	struct lpfc_vector_map_info *cpup;
12338 	int idx;
12339 
12340 	for_each_present_cpu(idx) {
12341 		cpup = &phba->sli4_hba.cpu_map[idx];
12342 		/* Does the cpup match the one we are looking for */
12343 		if ((cpup->phys_id == phys_id) &&
12344 		    (cpup->core_id == core_id) &&
12345 		    (cpu != idx))
12346 			return 1;
12347 	}
12348 	return 0;
12349 }
12350 #endif
12351 
12352 /*
12353  * lpfc_assign_eq_map_info - Assigns eq for vector_map structure
12354  * @phba: pointer to lpfc hba data structure.
12355  * @eqidx: index for eq and irq vector
12356  * @flag: flags to set for vector_map structure
12357  * @cpu: cpu used to index vector_map structure
12358  *
12359  * The routine assigns eq info into vector_map structure
12360  */
12361 static inline void
12362 lpfc_assign_eq_map_info(struct lpfc_hba *phba, uint16_t eqidx, uint16_t flag,
12363 			unsigned int cpu)
12364 {
12365 	struct lpfc_vector_map_info *cpup = &phba->sli4_hba.cpu_map[cpu];
12366 	struct lpfc_hba_eq_hdl *eqhdl = lpfc_get_eq_hdl(eqidx);
12367 
12368 	cpup->eq = eqidx;
12369 	cpup->flag |= flag;
12370 
12371 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12372 			"3336 Set Affinity: CPU %d irq %d eq %d flag x%x\n",
12373 			cpu, eqhdl->irq, cpup->eq, cpup->flag);
12374 }
12375 
12376 /**
12377  * lpfc_cpu_map_array_init - Initialize cpu_map structure
12378  * @phba: pointer to lpfc hba data structure.
12379  *
12380  * The routine initializes the cpu_map array structure
12381  */
12382 static void
12383 lpfc_cpu_map_array_init(struct lpfc_hba *phba)
12384 {
12385 	struct lpfc_vector_map_info *cpup;
12386 	struct lpfc_eq_intr_info *eqi;
12387 	int cpu;
12388 
12389 	for_each_possible_cpu(cpu) {
12390 		cpup = &phba->sli4_hba.cpu_map[cpu];
12391 		cpup->phys_id = LPFC_VECTOR_MAP_EMPTY;
12392 		cpup->core_id = LPFC_VECTOR_MAP_EMPTY;
12393 		cpup->hdwq = LPFC_VECTOR_MAP_EMPTY;
12394 		cpup->eq = LPFC_VECTOR_MAP_EMPTY;
12395 		cpup->flag = 0;
12396 		eqi = per_cpu_ptr(phba->sli4_hba.eq_info, cpu);
12397 		INIT_LIST_HEAD(&eqi->list);
12398 		eqi->icnt = 0;
12399 	}
12400 }
12401 
12402 /**
12403  * lpfc_hba_eq_hdl_array_init - Initialize hba_eq_hdl structure
12404  * @phba: pointer to lpfc hba data structure.
12405  *
12406  * The routine initializes the hba_eq_hdl array structure
12407  */
12408 static void
12409 lpfc_hba_eq_hdl_array_init(struct lpfc_hba *phba)
12410 {
12411 	struct lpfc_hba_eq_hdl *eqhdl;
12412 	int i;
12413 
12414 	for (i = 0; i < phba->cfg_irq_chann; i++) {
12415 		eqhdl = lpfc_get_eq_hdl(i);
12416 		eqhdl->irq = LPFC_IRQ_EMPTY;
12417 		eqhdl->phba = phba;
12418 	}
12419 }
12420 
12421 /**
12422  * lpfc_cpu_affinity_check - Check vector CPU affinity mappings
12423  * @phba: pointer to lpfc hba data structure.
12424  * @vectors: number of msix vectors allocated.
12425  *
12426  * The routine will figure out the CPU affinity assignment for every
12427  * MSI-X vector allocated for the HBA.
12428  * In addition, the CPU to IO channel mapping will be calculated
12429  * and the phba->sli4_hba.cpu_map array will reflect this.
12430  */
12431 static void
12432 lpfc_cpu_affinity_check(struct lpfc_hba *phba, int vectors)
12433 {
12434 	int i, cpu, idx, next_idx, new_cpu, start_cpu, first_cpu;
12435 	int max_phys_id, min_phys_id;
12436 	int max_core_id, min_core_id;
12437 	struct lpfc_vector_map_info *cpup;
12438 	struct lpfc_vector_map_info *new_cpup;
12439 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
12440 	struct lpfc_hdwq_stat *c_stat;
12441 #endif
12442 
12443 	max_phys_id = 0;
12444 	min_phys_id = LPFC_VECTOR_MAP_EMPTY;
12445 	max_core_id = 0;
12446 	min_core_id = LPFC_VECTOR_MAP_EMPTY;
12447 
12448 	/* Update CPU map with physical id and core id of each CPU */
12449 	for_each_present_cpu(cpu) {
12450 		cpup = &phba->sli4_hba.cpu_map[cpu];
12451 #ifdef CONFIG_X86
12452 		cpup->phys_id = topology_physical_package_id(cpu);
12453 		cpup->core_id = topology_core_id(cpu);
12454 		if (lpfc_find_hyper(phba, cpu, cpup->phys_id, cpup->core_id))
12455 			cpup->flag |= LPFC_CPU_MAP_HYPER;
12456 #else
12457 		/* No distinction between CPUs for other platforms */
12458 		cpup->phys_id = 0;
12459 		cpup->core_id = cpu;
12460 #endif
12461 
12462 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12463 				"3328 CPU %d physid %d coreid %d flag x%x\n",
12464 				cpu, cpup->phys_id, cpup->core_id, cpup->flag);
12465 
12466 		if (cpup->phys_id > max_phys_id)
12467 			max_phys_id = cpup->phys_id;
12468 		if (cpup->phys_id < min_phys_id)
12469 			min_phys_id = cpup->phys_id;
12470 
12471 		if (cpup->core_id > max_core_id)
12472 			max_core_id = cpup->core_id;
12473 		if (cpup->core_id < min_core_id)
12474 			min_core_id = cpup->core_id;
12475 	}
12476 
12477 	/* After looking at each irq vector assigned to this pcidev, its
12478 	 * possible to see that not ALL CPUs have been accounted for.
12479 	 * Next we will set any unassigned (unaffinitized) cpu map
12480 	 * entries to a IRQ on the same phys_id.
12481 	 */
12482 	first_cpu = cpumask_first(cpu_present_mask);
12483 	start_cpu = first_cpu;
12484 
12485 	for_each_present_cpu(cpu) {
12486 		cpup = &phba->sli4_hba.cpu_map[cpu];
12487 
12488 		/* Is this CPU entry unassigned */
12489 		if (cpup->eq == LPFC_VECTOR_MAP_EMPTY) {
12490 			/* Mark CPU as IRQ not assigned by the kernel */
12491 			cpup->flag |= LPFC_CPU_MAP_UNASSIGN;
12492 
12493 			/* If so, find a new_cpup that is on the SAME
12494 			 * phys_id as cpup. start_cpu will start where we
12495 			 * left off so all unassigned entries don't get assgined
12496 			 * the IRQ of the first entry.
12497 			 */
12498 			new_cpu = start_cpu;
12499 			for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12500 				new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12501 				if (!(new_cpup->flag & LPFC_CPU_MAP_UNASSIGN) &&
12502 				    (new_cpup->eq != LPFC_VECTOR_MAP_EMPTY) &&
12503 				    (new_cpup->phys_id == cpup->phys_id))
12504 					goto found_same;
12505 				new_cpu = lpfc_next_present_cpu(new_cpu);
12506 			}
12507 			/* At this point, we leave the CPU as unassigned */
12508 			continue;
12509 found_same:
12510 			/* We found a matching phys_id, so copy the IRQ info */
12511 			cpup->eq = new_cpup->eq;
12512 
12513 			/* Bump start_cpu to the next slot to minmize the
12514 			 * chance of having multiple unassigned CPU entries
12515 			 * selecting the same IRQ.
12516 			 */
12517 			start_cpu = lpfc_next_present_cpu(new_cpu);
12518 
12519 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12520 					"3337 Set Affinity: CPU %d "
12521 					"eq %d from peer cpu %d same "
12522 					"phys_id (%d)\n",
12523 					cpu, cpup->eq, new_cpu,
12524 					cpup->phys_id);
12525 		}
12526 	}
12527 
12528 	/* Set any unassigned cpu map entries to a IRQ on any phys_id */
12529 	start_cpu = first_cpu;
12530 
12531 	for_each_present_cpu(cpu) {
12532 		cpup = &phba->sli4_hba.cpu_map[cpu];
12533 
12534 		/* Is this entry unassigned */
12535 		if (cpup->eq == LPFC_VECTOR_MAP_EMPTY) {
12536 			/* Mark it as IRQ not assigned by the kernel */
12537 			cpup->flag |= LPFC_CPU_MAP_UNASSIGN;
12538 
12539 			/* If so, find a new_cpup thats on ANY phys_id
12540 			 * as the cpup. start_cpu will start where we
12541 			 * left off so all unassigned entries don't get
12542 			 * assigned the IRQ of the first entry.
12543 			 */
12544 			new_cpu = start_cpu;
12545 			for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12546 				new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12547 				if (!(new_cpup->flag & LPFC_CPU_MAP_UNASSIGN) &&
12548 				    (new_cpup->eq != LPFC_VECTOR_MAP_EMPTY))
12549 					goto found_any;
12550 				new_cpu = lpfc_next_present_cpu(new_cpu);
12551 			}
12552 			/* We should never leave an entry unassigned */
12553 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12554 					"3339 Set Affinity: CPU %d "
12555 					"eq %d UNASSIGNED\n",
12556 					cpup->hdwq, cpup->eq);
12557 			continue;
12558 found_any:
12559 			/* We found an available entry, copy the IRQ info */
12560 			cpup->eq = new_cpup->eq;
12561 
12562 			/* Bump start_cpu to the next slot to minmize the
12563 			 * chance of having multiple unassigned CPU entries
12564 			 * selecting the same IRQ.
12565 			 */
12566 			start_cpu = lpfc_next_present_cpu(new_cpu);
12567 
12568 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12569 					"3338 Set Affinity: CPU %d "
12570 					"eq %d from peer cpu %d (%d/%d)\n",
12571 					cpu, cpup->eq, new_cpu,
12572 					new_cpup->phys_id, new_cpup->core_id);
12573 		}
12574 	}
12575 
12576 	/* Assign hdwq indices that are unique across all cpus in the map
12577 	 * that are also FIRST_CPUs.
12578 	 */
12579 	idx = 0;
12580 	for_each_present_cpu(cpu) {
12581 		cpup = &phba->sli4_hba.cpu_map[cpu];
12582 
12583 		/* Only FIRST IRQs get a hdwq index assignment. */
12584 		if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
12585 			continue;
12586 
12587 		/* 1 to 1, the first LPFC_CPU_FIRST_IRQ cpus to a unique hdwq */
12588 		cpup->hdwq = idx;
12589 		idx++;
12590 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12591 				"3333 Set Affinity: CPU %d (phys %d core %d): "
12592 				"hdwq %d eq %d flg x%x\n",
12593 				cpu, cpup->phys_id, cpup->core_id,
12594 				cpup->hdwq, cpup->eq, cpup->flag);
12595 	}
12596 	/* Associate a hdwq with each cpu_map entry
12597 	 * This will be 1 to 1 - hdwq to cpu, unless there are less
12598 	 * hardware queues then CPUs. For that case we will just round-robin
12599 	 * the available hardware queues as they get assigned to CPUs.
12600 	 * The next_idx is the idx from the FIRST_CPU loop above to account
12601 	 * for irq_chann < hdwq.  The idx is used for round-robin assignments
12602 	 * and needs to start at 0.
12603 	 */
12604 	next_idx = idx;
12605 	start_cpu = 0;
12606 	idx = 0;
12607 	for_each_present_cpu(cpu) {
12608 		cpup = &phba->sli4_hba.cpu_map[cpu];
12609 
12610 		/* FIRST cpus are already mapped. */
12611 		if (cpup->flag & LPFC_CPU_FIRST_IRQ)
12612 			continue;
12613 
12614 		/* If the cfg_irq_chann < cfg_hdw_queue, set the hdwq
12615 		 * of the unassigned cpus to the next idx so that all
12616 		 * hdw queues are fully utilized.
12617 		 */
12618 		if (next_idx < phba->cfg_hdw_queue) {
12619 			cpup->hdwq = next_idx;
12620 			next_idx++;
12621 			continue;
12622 		}
12623 
12624 		/* Not a First CPU and all hdw_queues are used.  Reuse a
12625 		 * Hardware Queue for another CPU, so be smart about it
12626 		 * and pick one that has its IRQ/EQ mapped to the same phys_id
12627 		 * (CPU package) and core_id.
12628 		 */
12629 		new_cpu = start_cpu;
12630 		for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12631 			new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12632 			if (new_cpup->hdwq != LPFC_VECTOR_MAP_EMPTY &&
12633 			    new_cpup->phys_id == cpup->phys_id &&
12634 			    new_cpup->core_id == cpup->core_id) {
12635 				goto found_hdwq;
12636 			}
12637 			new_cpu = lpfc_next_present_cpu(new_cpu);
12638 		}
12639 
12640 		/* If we can't match both phys_id and core_id,
12641 		 * settle for just a phys_id match.
12642 		 */
12643 		new_cpu = start_cpu;
12644 		for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12645 			new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12646 			if (new_cpup->hdwq != LPFC_VECTOR_MAP_EMPTY &&
12647 			    new_cpup->phys_id == cpup->phys_id)
12648 				goto found_hdwq;
12649 			new_cpu = lpfc_next_present_cpu(new_cpu);
12650 		}
12651 
12652 		/* Otherwise just round robin on cfg_hdw_queue */
12653 		cpup->hdwq = idx % phba->cfg_hdw_queue;
12654 		idx++;
12655 		goto logit;
12656  found_hdwq:
12657 		/* We found an available entry, copy the IRQ info */
12658 		start_cpu = lpfc_next_present_cpu(new_cpu);
12659 		cpup->hdwq = new_cpup->hdwq;
12660  logit:
12661 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12662 				"3335 Set Affinity: CPU %d (phys %d core %d): "
12663 				"hdwq %d eq %d flg x%x\n",
12664 				cpu, cpup->phys_id, cpup->core_id,
12665 				cpup->hdwq, cpup->eq, cpup->flag);
12666 	}
12667 
12668 	/*
12669 	 * Initialize the cpu_map slots for not-present cpus in case
12670 	 * a cpu is hot-added. Perform a simple hdwq round robin assignment.
12671 	 */
12672 	idx = 0;
12673 	for_each_possible_cpu(cpu) {
12674 		cpup = &phba->sli4_hba.cpu_map[cpu];
12675 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
12676 		c_stat = per_cpu_ptr(phba->sli4_hba.c_stat, cpu);
12677 		c_stat->hdwq_no = cpup->hdwq;
12678 #endif
12679 		if (cpup->hdwq != LPFC_VECTOR_MAP_EMPTY)
12680 			continue;
12681 
12682 		cpup->hdwq = idx++ % phba->cfg_hdw_queue;
12683 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
12684 		c_stat->hdwq_no = cpup->hdwq;
12685 #endif
12686 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12687 				"3340 Set Affinity: not present "
12688 				"CPU %d hdwq %d\n",
12689 				cpu, cpup->hdwq);
12690 	}
12691 
12692 	/* The cpu_map array will be used later during initialization
12693 	 * when EQ / CQ / WQs are allocated and configured.
12694 	 */
12695 	return;
12696 }
12697 
12698 /**
12699  * lpfc_cpuhp_get_eq
12700  *
12701  * @phba:   pointer to lpfc hba data structure.
12702  * @cpu:    cpu going offline
12703  * @eqlist: eq list to append to
12704  */
12705 static int
12706 lpfc_cpuhp_get_eq(struct lpfc_hba *phba, unsigned int cpu,
12707 		  struct list_head *eqlist)
12708 {
12709 	const struct cpumask *maskp;
12710 	struct lpfc_queue *eq;
12711 	struct cpumask *tmp;
12712 	u16 idx;
12713 
12714 	tmp = kzalloc(cpumask_size(), GFP_KERNEL);
12715 	if (!tmp)
12716 		return -ENOMEM;
12717 
12718 	for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
12719 		maskp = pci_irq_get_affinity(phba->pcidev, idx);
12720 		if (!maskp)
12721 			continue;
12722 		/*
12723 		 * if irq is not affinitized to the cpu going
12724 		 * then we don't need to poll the eq attached
12725 		 * to it.
12726 		 */
12727 		if (!cpumask_and(tmp, maskp, cpumask_of(cpu)))
12728 			continue;
12729 		/* get the cpus that are online and are affini-
12730 		 * tized to this irq vector.  If the count is
12731 		 * more than 1 then cpuhp is not going to shut-
12732 		 * down this vector.  Since this cpu has not
12733 		 * gone offline yet, we need >1.
12734 		 */
12735 		cpumask_and(tmp, maskp, cpu_online_mask);
12736 		if (cpumask_weight(tmp) > 1)
12737 			continue;
12738 
12739 		/* Now that we have an irq to shutdown, get the eq
12740 		 * mapped to this irq.  Note: multiple hdwq's in
12741 		 * the software can share an eq, but eventually
12742 		 * only eq will be mapped to this vector
12743 		 */
12744 		eq = phba->sli4_hba.hba_eq_hdl[idx].eq;
12745 		list_add(&eq->_poll_list, eqlist);
12746 	}
12747 	kfree(tmp);
12748 	return 0;
12749 }
12750 
12751 static void __lpfc_cpuhp_remove(struct lpfc_hba *phba)
12752 {
12753 	if (phba->sli_rev != LPFC_SLI_REV4)
12754 		return;
12755 
12756 	cpuhp_state_remove_instance_nocalls(lpfc_cpuhp_state,
12757 					    &phba->cpuhp);
12758 	/*
12759 	 * unregistering the instance doesn't stop the polling
12760 	 * timer. Wait for the poll timer to retire.
12761 	 */
12762 	synchronize_rcu();
12763 	timer_delete_sync(&phba->cpuhp_poll_timer);
12764 }
12765 
12766 static void lpfc_cpuhp_remove(struct lpfc_hba *phba)
12767 {
12768 	if (phba->pport &&
12769 	    test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag))
12770 		return;
12771 
12772 	__lpfc_cpuhp_remove(phba);
12773 }
12774 
12775 static void lpfc_cpuhp_add(struct lpfc_hba *phba)
12776 {
12777 	if (phba->sli_rev != LPFC_SLI_REV4)
12778 		return;
12779 
12780 	rcu_read_lock();
12781 
12782 	if (!list_empty(&phba->poll_list))
12783 		mod_timer(&phba->cpuhp_poll_timer,
12784 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
12785 
12786 	rcu_read_unlock();
12787 
12788 	cpuhp_state_add_instance_nocalls(lpfc_cpuhp_state,
12789 					 &phba->cpuhp);
12790 }
12791 
12792 static int __lpfc_cpuhp_checks(struct lpfc_hba *phba, int *retval)
12793 {
12794 	if (test_bit(FC_UNLOADING, &phba->pport->load_flag)) {
12795 		*retval = -EAGAIN;
12796 		return true;
12797 	}
12798 
12799 	if (phba->sli_rev != LPFC_SLI_REV4) {
12800 		*retval = 0;
12801 		return true;
12802 	}
12803 
12804 	/* proceed with the hotplug */
12805 	return false;
12806 }
12807 
12808 /**
12809  * lpfc_irq_set_aff - set IRQ affinity
12810  * @eqhdl: EQ handle
12811  * @cpu: cpu to set affinity
12812  *
12813  **/
12814 static inline void
12815 lpfc_irq_set_aff(struct lpfc_hba_eq_hdl *eqhdl, unsigned int cpu)
12816 {
12817 	cpumask_clear(&eqhdl->aff_mask);
12818 	cpumask_set_cpu(cpu, &eqhdl->aff_mask);
12819 	irq_set_status_flags(eqhdl->irq, IRQ_NO_BALANCING);
12820 	irq_set_affinity(eqhdl->irq, &eqhdl->aff_mask);
12821 }
12822 
12823 /**
12824  * lpfc_irq_clear_aff - clear IRQ affinity
12825  * @eqhdl: EQ handle
12826  *
12827  **/
12828 static inline void
12829 lpfc_irq_clear_aff(struct lpfc_hba_eq_hdl *eqhdl)
12830 {
12831 	cpumask_clear(&eqhdl->aff_mask);
12832 	irq_clear_status_flags(eqhdl->irq, IRQ_NO_BALANCING);
12833 }
12834 
12835 /**
12836  * lpfc_irq_rebalance - rebalances IRQ affinity according to cpuhp event
12837  * @phba: pointer to HBA context object.
12838  * @cpu: cpu going offline/online
12839  * @offline: true, cpu is going offline. false, cpu is coming online.
12840  *
12841  * If cpu is going offline, we'll try our best effort to find the next
12842  * online cpu on the phba's original_mask and migrate all offlining IRQ
12843  * affinities.
12844  *
12845  * If cpu is coming online, reaffinitize the IRQ back to the onlining cpu.
12846  *
12847  * Note: Call only if NUMA or NHT mode is enabled, otherwise rely on
12848  *	 PCI_IRQ_AFFINITY to auto-manage IRQ affinity.
12849  *
12850  **/
12851 static void
12852 lpfc_irq_rebalance(struct lpfc_hba *phba, unsigned int cpu, bool offline)
12853 {
12854 	struct lpfc_vector_map_info *cpup;
12855 	struct cpumask *aff_mask;
12856 	unsigned int cpu_select, cpu_next, idx;
12857 	const struct cpumask *orig_mask;
12858 
12859 	if (phba->irq_chann_mode == NORMAL_MODE)
12860 		return;
12861 
12862 	orig_mask = &phba->sli4_hba.irq_aff_mask;
12863 
12864 	if (!cpumask_test_cpu(cpu, orig_mask))
12865 		return;
12866 
12867 	cpup = &phba->sli4_hba.cpu_map[cpu];
12868 
12869 	if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
12870 		return;
12871 
12872 	if (offline) {
12873 		/* Find next online CPU on original mask */
12874 		cpu_next = cpumask_next_wrap(cpu, orig_mask);
12875 		cpu_select = lpfc_next_online_cpu(orig_mask, cpu_next);
12876 
12877 		/* Found a valid CPU */
12878 		if ((cpu_select < nr_cpu_ids) && (cpu_select != cpu)) {
12879 			/* Go through each eqhdl and ensure offlining
12880 			 * cpu aff_mask is migrated
12881 			 */
12882 			for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
12883 				aff_mask = lpfc_get_aff_mask(idx);
12884 
12885 				/* Migrate affinity */
12886 				if (cpumask_test_cpu(cpu, aff_mask))
12887 					lpfc_irq_set_aff(lpfc_get_eq_hdl(idx),
12888 							 cpu_select);
12889 			}
12890 		} else {
12891 			/* Rely on irqbalance if no online CPUs left on NUMA */
12892 			for (idx = 0; idx < phba->cfg_irq_chann; idx++)
12893 				lpfc_irq_clear_aff(lpfc_get_eq_hdl(idx));
12894 		}
12895 	} else {
12896 		/* Migrate affinity back to this CPU */
12897 		lpfc_irq_set_aff(lpfc_get_eq_hdl(cpup->eq), cpu);
12898 	}
12899 }
12900 
12901 static int lpfc_cpu_offline(unsigned int cpu, struct hlist_node *node)
12902 {
12903 	struct lpfc_hba *phba = hlist_entry_safe(node, struct lpfc_hba, cpuhp);
12904 	struct lpfc_queue *eq, *next;
12905 	LIST_HEAD(eqlist);
12906 	int retval;
12907 
12908 	if (!phba) {
12909 		WARN_ONCE(!phba, "cpu: %u. phba:NULL", raw_smp_processor_id());
12910 		return 0;
12911 	}
12912 
12913 	if (__lpfc_cpuhp_checks(phba, &retval))
12914 		return retval;
12915 
12916 	lpfc_irq_rebalance(phba, cpu, true);
12917 
12918 	retval = lpfc_cpuhp_get_eq(phba, cpu, &eqlist);
12919 	if (retval)
12920 		return retval;
12921 
12922 	/* start polling on these eq's */
12923 	list_for_each_entry_safe(eq, next, &eqlist, _poll_list) {
12924 		list_del_init(&eq->_poll_list);
12925 		lpfc_sli4_start_polling(eq);
12926 	}
12927 
12928 	return 0;
12929 }
12930 
12931 static int lpfc_cpu_online(unsigned int cpu, struct hlist_node *node)
12932 {
12933 	struct lpfc_hba *phba = hlist_entry_safe(node, struct lpfc_hba, cpuhp);
12934 	struct lpfc_queue *eq, *next;
12935 	unsigned int n;
12936 	int retval;
12937 
12938 	if (!phba) {
12939 		WARN_ONCE(!phba, "cpu: %u. phba:NULL", raw_smp_processor_id());
12940 		return 0;
12941 	}
12942 
12943 	if (__lpfc_cpuhp_checks(phba, &retval))
12944 		return retval;
12945 
12946 	lpfc_irq_rebalance(phba, cpu, false);
12947 
12948 	list_for_each_entry_safe(eq, next, &phba->poll_list, _poll_list) {
12949 		n = lpfc_find_cpu_handle(phba, eq->hdwq, LPFC_FIND_BY_HDWQ);
12950 		if (n == cpu)
12951 			lpfc_sli4_stop_polling(eq);
12952 	}
12953 
12954 	return 0;
12955 }
12956 
12957 /**
12958  * lpfc_sli4_enable_msix - Enable MSI-X interrupt mode to SLI-4 device
12959  * @phba: pointer to lpfc hba data structure.
12960  *
12961  * This routine is invoked to enable the MSI-X interrupt vectors to device
12962  * with SLI-4 interface spec.  It also allocates MSI-X vectors and maps them
12963  * to cpus on the system.
12964  *
12965  * When cfg_irq_numa is enabled, the adapter will only allocate vectors for
12966  * the number of cpus on the same numa node as this adapter.  The vectors are
12967  * allocated without requesting OS affinity mapping.  A vector will be
12968  * allocated and assigned to each online and offline cpu.  If the cpu is
12969  * online, then affinity will be set to that cpu.  If the cpu is offline, then
12970  * affinity will be set to the nearest peer cpu within the numa node that is
12971  * online.  If there are no online cpus within the numa node, affinity is not
12972  * assigned and the OS may do as it pleases. Note: cpu vector affinity mapping
12973  * is consistent with the way cpu online/offline is handled when cfg_irq_numa is
12974  * configured.
12975  *
12976  * If numa mode is not enabled and there is more than 1 vector allocated, then
12977  * the driver relies on the managed irq interface where the OS assigns vector to
12978  * cpu affinity.  The driver will then use that affinity mapping to setup its
12979  * cpu mapping table.
12980  *
12981  * Return codes
12982  * 0 - successful
12983  * other values - error
12984  **/
12985 static int
12986 lpfc_sli4_enable_msix(struct lpfc_hba *phba)
12987 {
12988 	int vectors, rc, index;
12989 	char *name;
12990 	const struct cpumask *aff_mask = NULL;
12991 	unsigned int cpu = 0, cpu_cnt = 0, cpu_select = nr_cpu_ids;
12992 	struct lpfc_vector_map_info *cpup;
12993 	struct lpfc_hba_eq_hdl *eqhdl;
12994 	const struct cpumask *maskp;
12995 	unsigned int flags = PCI_IRQ_MSIX;
12996 
12997 	/* Set up MSI-X multi-message vectors */
12998 	vectors = phba->cfg_irq_chann;
12999 
13000 	if (phba->irq_chann_mode != NORMAL_MODE)
13001 		aff_mask = &phba->sli4_hba.irq_aff_mask;
13002 
13003 	if (aff_mask) {
13004 		cpu_cnt = cpumask_weight(aff_mask);
13005 		vectors = min(phba->cfg_irq_chann, cpu_cnt);
13006 
13007 		/* cpu: iterates over aff_mask including offline or online
13008 		 * cpu_select: iterates over online aff_mask to set affinity
13009 		 */
13010 		cpu = cpumask_first(aff_mask);
13011 		cpu_select = lpfc_next_online_cpu(aff_mask, cpu);
13012 	} else {
13013 		flags |= PCI_IRQ_AFFINITY;
13014 	}
13015 
13016 	rc = pci_alloc_irq_vectors(phba->pcidev, 1, vectors, flags);
13017 	if (rc < 0) {
13018 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13019 				"0484 PCI enable MSI-X failed (%d)\n", rc);
13020 		goto vec_fail_out;
13021 	}
13022 	vectors = rc;
13023 
13024 	/* Assign MSI-X vectors to interrupt handlers */
13025 	for (index = 0; index < vectors; index++) {
13026 		eqhdl = lpfc_get_eq_hdl(index);
13027 		name = eqhdl->handler_name;
13028 		memset(name, 0, LPFC_SLI4_HANDLER_NAME_SZ);
13029 		snprintf(name, LPFC_SLI4_HANDLER_NAME_SZ,
13030 			 LPFC_DRIVER_HANDLER_NAME"%d", index);
13031 
13032 		eqhdl->idx = index;
13033 		rc = pci_irq_vector(phba->pcidev, index);
13034 		if (rc < 0) {
13035 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13036 					"0489 MSI-X fast-path (%d) "
13037 					"pci_irq_vec failed (%d)\n", index, rc);
13038 			goto cfg_fail_out;
13039 		}
13040 		eqhdl->irq = rc;
13041 
13042 		rc = request_threaded_irq(eqhdl->irq,
13043 					  &lpfc_sli4_hba_intr_handler,
13044 					  &lpfc_sli4_hba_intr_handler_th,
13045 					  0, name, eqhdl);
13046 		if (rc) {
13047 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13048 					"0486 MSI-X fast-path (%d) "
13049 					"request_irq failed (%d)\n", index, rc);
13050 			goto cfg_fail_out;
13051 		}
13052 
13053 		if (aff_mask) {
13054 			/* If found a neighboring online cpu, set affinity */
13055 			if (cpu_select < nr_cpu_ids)
13056 				lpfc_irq_set_aff(eqhdl, cpu_select);
13057 
13058 			/* Assign EQ to cpu_map */
13059 			lpfc_assign_eq_map_info(phba, index,
13060 						LPFC_CPU_FIRST_IRQ,
13061 						cpu);
13062 
13063 			/* Iterate to next offline or online cpu in aff_mask */
13064 			cpu = cpumask_next(cpu, aff_mask);
13065 
13066 			/* Find next online cpu in aff_mask to set affinity */
13067 			cpu_select = lpfc_next_online_cpu(aff_mask, cpu);
13068 		} else if (vectors == 1) {
13069 			cpu = cpumask_first(cpu_present_mask);
13070 			lpfc_assign_eq_map_info(phba, index, LPFC_CPU_FIRST_IRQ,
13071 						cpu);
13072 		} else {
13073 			maskp = pci_irq_get_affinity(phba->pcidev, index);
13074 
13075 			/* Loop through all CPUs associated with vector index */
13076 			for_each_cpu_and(cpu, maskp, cpu_present_mask) {
13077 				cpup = &phba->sli4_hba.cpu_map[cpu];
13078 
13079 				/* If this is the first CPU thats assigned to
13080 				 * this vector, set LPFC_CPU_FIRST_IRQ.
13081 				 *
13082 				 * With certain platforms its possible that irq
13083 				 * vectors are affinitized to all the cpu's.
13084 				 * This can result in each cpu_map.eq to be set
13085 				 * to the last vector, resulting in overwrite
13086 				 * of all the previous cpu_map.eq.  Ensure that
13087 				 * each vector receives a place in cpu_map.
13088 				 * Later call to lpfc_cpu_affinity_check will
13089 				 * ensure we are nicely balanced out.
13090 				 */
13091 				if (cpup->eq != LPFC_VECTOR_MAP_EMPTY)
13092 					continue;
13093 				lpfc_assign_eq_map_info(phba, index,
13094 							LPFC_CPU_FIRST_IRQ,
13095 							cpu);
13096 				break;
13097 			}
13098 		}
13099 	}
13100 
13101 	if (vectors != phba->cfg_irq_chann) {
13102 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13103 				"3238 Reducing IO channels to match number of "
13104 				"MSI-X vectors, requested %d got %d\n",
13105 				phba->cfg_irq_chann, vectors);
13106 		if (phba->cfg_irq_chann > vectors)
13107 			phba->cfg_irq_chann = vectors;
13108 	}
13109 
13110 	return rc;
13111 
13112 cfg_fail_out:
13113 	/* free the irq already requested */
13114 	for (--index; index >= 0; index--) {
13115 		eqhdl = lpfc_get_eq_hdl(index);
13116 		lpfc_irq_clear_aff(eqhdl);
13117 		free_irq(eqhdl->irq, eqhdl);
13118 	}
13119 
13120 	/* Unconfigure MSI-X capability structure */
13121 	pci_free_irq_vectors(phba->pcidev);
13122 
13123 vec_fail_out:
13124 	return rc;
13125 }
13126 
13127 /**
13128  * lpfc_sli4_enable_msi - Enable MSI interrupt mode to SLI-4 device
13129  * @phba: pointer to lpfc hba data structure.
13130  *
13131  * This routine is invoked to enable the MSI interrupt mode to device with
13132  * SLI-4 interface spec. The kernel function pci_alloc_irq_vectors() is
13133  * called to enable the MSI vector. The device driver is responsible for
13134  * calling the request_irq() to register MSI vector with a interrupt the
13135  * handler, which is done in this function.
13136  *
13137  * Return codes
13138  * 	0 - successful
13139  * 	other values - error
13140  **/
13141 static int
13142 lpfc_sli4_enable_msi(struct lpfc_hba *phba)
13143 {
13144 	int rc, index;
13145 	unsigned int cpu;
13146 	struct lpfc_hba_eq_hdl *eqhdl;
13147 
13148 	rc = pci_alloc_irq_vectors(phba->pcidev, 1, 1,
13149 				   PCI_IRQ_MSI | PCI_IRQ_AFFINITY);
13150 	if (rc > 0)
13151 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13152 				"0487 PCI enable MSI mode success.\n");
13153 	else {
13154 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13155 				"0488 PCI enable MSI mode failed (%d)\n", rc);
13156 		return rc ? rc : -1;
13157 	}
13158 
13159 	rc = request_irq(phba->pcidev->irq, lpfc_sli4_intr_handler,
13160 			 0, LPFC_DRIVER_NAME, phba);
13161 	if (rc) {
13162 		pci_free_irq_vectors(phba->pcidev);
13163 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13164 				"0490 MSI request_irq failed (%d)\n", rc);
13165 		return rc;
13166 	}
13167 
13168 	eqhdl = lpfc_get_eq_hdl(0);
13169 	rc = pci_irq_vector(phba->pcidev, 0);
13170 	if (rc < 0) {
13171 		free_irq(phba->pcidev->irq, phba);
13172 		pci_free_irq_vectors(phba->pcidev);
13173 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13174 				"0496 MSI pci_irq_vec failed (%d)\n", rc);
13175 		return rc;
13176 	}
13177 	eqhdl->irq = rc;
13178 
13179 	cpu = cpumask_first(cpu_present_mask);
13180 	lpfc_assign_eq_map_info(phba, 0, LPFC_CPU_FIRST_IRQ, cpu);
13181 
13182 	for (index = 0; index < phba->cfg_irq_chann; index++) {
13183 		eqhdl = lpfc_get_eq_hdl(index);
13184 		eqhdl->idx = index;
13185 	}
13186 
13187 	return 0;
13188 }
13189 
13190 /**
13191  * lpfc_sli4_enable_intr - Enable device interrupt to SLI-4 device
13192  * @phba: pointer to lpfc hba data structure.
13193  * @cfg_mode: Interrupt configuration mode (INTx, MSI or MSI-X).
13194  *
13195  * This routine is invoked to enable device interrupt and associate driver's
13196  * interrupt handler(s) to interrupt vector(s) to device with SLI-4
13197  * interface spec. Depends on the interrupt mode configured to the driver,
13198  * the driver will try to fallback from the configured interrupt mode to an
13199  * interrupt mode which is supported by the platform, kernel, and device in
13200  * the order of:
13201  * MSI-X -> MSI -> IRQ.
13202  *
13203  * Return codes
13204  *	Interrupt mode (2, 1, 0) - successful
13205  *	LPFC_INTR_ERROR - error
13206  **/
13207 static uint32_t
13208 lpfc_sli4_enable_intr(struct lpfc_hba *phba, uint32_t cfg_mode)
13209 {
13210 	uint32_t intr_mode = LPFC_INTR_ERROR;
13211 	int retval, idx;
13212 
13213 	if (cfg_mode == 2) {
13214 		/* Preparation before conf_msi mbox cmd */
13215 		retval = 0;
13216 		if (!retval) {
13217 			/* Now, try to enable MSI-X interrupt mode */
13218 			retval = lpfc_sli4_enable_msix(phba);
13219 			if (!retval) {
13220 				/* Indicate initialization to MSI-X mode */
13221 				phba->intr_type = MSIX;
13222 				intr_mode = 2;
13223 			}
13224 		}
13225 	}
13226 
13227 	/* Fallback to MSI if MSI-X initialization failed */
13228 	if (cfg_mode >= 1 && phba->intr_type == NONE) {
13229 		retval = lpfc_sli4_enable_msi(phba);
13230 		if (!retval) {
13231 			/* Indicate initialization to MSI mode */
13232 			phba->intr_type = MSI;
13233 			intr_mode = 1;
13234 		}
13235 	}
13236 
13237 	/* Fallback to INTx if both MSI-X/MSI initalization failed */
13238 	if (phba->intr_type == NONE) {
13239 		retval = request_irq(phba->pcidev->irq, lpfc_sli4_intr_handler,
13240 				     IRQF_SHARED, LPFC_DRIVER_NAME, phba);
13241 		if (!retval) {
13242 			struct lpfc_hba_eq_hdl *eqhdl;
13243 			unsigned int cpu;
13244 
13245 			/* Indicate initialization to INTx mode */
13246 			phba->intr_type = INTx;
13247 			intr_mode = 0;
13248 
13249 			eqhdl = lpfc_get_eq_hdl(0);
13250 			retval = pci_irq_vector(phba->pcidev, 0);
13251 			if (retval < 0) {
13252 				free_irq(phba->pcidev->irq, phba);
13253 				lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13254 					"0502 INTR pci_irq_vec failed (%d)\n",
13255 					 retval);
13256 				return LPFC_INTR_ERROR;
13257 			}
13258 			eqhdl->irq = retval;
13259 
13260 			cpu = cpumask_first(cpu_present_mask);
13261 			lpfc_assign_eq_map_info(phba, 0, LPFC_CPU_FIRST_IRQ,
13262 						cpu);
13263 			for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
13264 				eqhdl = lpfc_get_eq_hdl(idx);
13265 				eqhdl->idx = idx;
13266 			}
13267 		}
13268 	}
13269 	return intr_mode;
13270 }
13271 
13272 /**
13273  * lpfc_sli4_disable_intr - Disable device interrupt to SLI-4 device
13274  * @phba: pointer to lpfc hba data structure.
13275  *
13276  * This routine is invoked to disable device interrupt and disassociate
13277  * the driver's interrupt handler(s) from interrupt vector(s) to device
13278  * with SLI-4 interface spec. Depending on the interrupt mode, the driver
13279  * will release the interrupt vector(s) for the message signaled interrupt.
13280  **/
13281 static void
13282 lpfc_sli4_disable_intr(struct lpfc_hba *phba)
13283 {
13284 	/* Disable the currently initialized interrupt mode */
13285 	if (phba->intr_type == MSIX) {
13286 		int index;
13287 		struct lpfc_hba_eq_hdl *eqhdl;
13288 
13289 		/* Free up MSI-X multi-message vectors */
13290 		for (index = 0; index < phba->cfg_irq_chann; index++) {
13291 			eqhdl = lpfc_get_eq_hdl(index);
13292 			lpfc_irq_clear_aff(eqhdl);
13293 			free_irq(eqhdl->irq, eqhdl);
13294 		}
13295 	} else {
13296 		free_irq(phba->pcidev->irq, phba);
13297 	}
13298 
13299 	pci_free_irq_vectors(phba->pcidev);
13300 
13301 	/* Reset interrupt management states */
13302 	phba->intr_type = NONE;
13303 	phba->sli.slistat.sli_intr = 0;
13304 }
13305 
13306 /**
13307  * lpfc_unset_hba - Unset SLI3 hba device initialization
13308  * @phba: pointer to lpfc hba data structure.
13309  *
13310  * This routine is invoked to unset the HBA device initialization steps to
13311  * a device with SLI-3 interface spec.
13312  **/
13313 static void
13314 lpfc_unset_hba(struct lpfc_hba *phba)
13315 {
13316 	set_bit(FC_UNLOADING, &phba->pport->load_flag);
13317 
13318 	kfree(phba->vpi_bmask);
13319 	kfree(phba->vpi_ids);
13320 
13321 	lpfc_stop_hba_timers(phba);
13322 
13323 	phba->pport->work_port_events = 0;
13324 
13325 	lpfc_sli_hba_down(phba);
13326 
13327 	lpfc_sli_brdrestart(phba);
13328 
13329 	lpfc_sli_disable_intr(phba);
13330 
13331 	return;
13332 }
13333 
13334 /**
13335  * lpfc_sli4_xri_exchange_busy_wait - Wait for device XRI exchange busy
13336  * @phba: Pointer to HBA context object.
13337  *
13338  * This function is called in the SLI4 code path to wait for completion
13339  * of device's XRIs exchange busy. It will check the XRI exchange busy
13340  * on outstanding FCP and ELS I/Os every 10ms for up to 10 seconds; after
13341  * that, it will check the XRI exchange busy on outstanding FCP and ELS
13342  * I/Os every 30 seconds, log error message, and wait forever. Only when
13343  * all XRI exchange busy complete, the driver unload shall proceed with
13344  * invoking the function reset ioctl mailbox command to the CNA and the
13345  * the rest of the driver unload resource release.
13346  **/
13347 static void
13348 lpfc_sli4_xri_exchange_busy_wait(struct lpfc_hba *phba)
13349 {
13350 	struct lpfc_sli4_hdw_queue *qp;
13351 	int idx, ccnt;
13352 	int wait_time = 0;
13353 	int io_xri_cmpl = 1;
13354 	int nvmet_xri_cmpl = 1;
13355 	int els_xri_cmpl = list_empty(&phba->sli4_hba.lpfc_abts_els_sgl_list);
13356 
13357 	/* Driver just aborted IOs during the hba_unset process.  Pause
13358 	 * here to give the HBA time to complete the IO and get entries
13359 	 * into the abts lists.
13360 	 */
13361 	msleep(LPFC_XRI_EXCH_BUSY_WAIT_T1 * 5);
13362 
13363 	/* Wait for NVME pending IO to flush back to transport. */
13364 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
13365 		lpfc_nvme_wait_for_io_drain(phba);
13366 
13367 	ccnt = 0;
13368 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
13369 		qp = &phba->sli4_hba.hdwq[idx];
13370 		io_xri_cmpl = list_empty(&qp->lpfc_abts_io_buf_list);
13371 		if (!io_xri_cmpl) /* if list is NOT empty */
13372 			ccnt++;
13373 	}
13374 	if (ccnt)
13375 		io_xri_cmpl = 0;
13376 
13377 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13378 		nvmet_xri_cmpl =
13379 			list_empty(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
13380 	}
13381 
13382 	while (!els_xri_cmpl || !io_xri_cmpl || !nvmet_xri_cmpl) {
13383 		if (wait_time > LPFC_XRI_EXCH_BUSY_WAIT_TMO) {
13384 			if (!nvmet_xri_cmpl)
13385 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13386 						"6424 NVMET XRI exchange busy "
13387 						"wait time: %d seconds.\n",
13388 						wait_time/1000);
13389 			if (!io_xri_cmpl)
13390 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13391 						"6100 IO XRI exchange busy "
13392 						"wait time: %d seconds.\n",
13393 						wait_time/1000);
13394 			if (!els_xri_cmpl)
13395 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13396 						"2878 ELS XRI exchange busy "
13397 						"wait time: %d seconds.\n",
13398 						wait_time/1000);
13399 			msleep(LPFC_XRI_EXCH_BUSY_WAIT_T2);
13400 			wait_time += LPFC_XRI_EXCH_BUSY_WAIT_T2;
13401 		} else {
13402 			msleep(LPFC_XRI_EXCH_BUSY_WAIT_T1);
13403 			wait_time += LPFC_XRI_EXCH_BUSY_WAIT_T1;
13404 		}
13405 
13406 		ccnt = 0;
13407 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
13408 			qp = &phba->sli4_hba.hdwq[idx];
13409 			io_xri_cmpl = list_empty(
13410 			    &qp->lpfc_abts_io_buf_list);
13411 			if (!io_xri_cmpl) /* if list is NOT empty */
13412 				ccnt++;
13413 		}
13414 		if (ccnt)
13415 			io_xri_cmpl = 0;
13416 
13417 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13418 			nvmet_xri_cmpl = list_empty(
13419 				&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
13420 		}
13421 		els_xri_cmpl =
13422 			list_empty(&phba->sli4_hba.lpfc_abts_els_sgl_list);
13423 
13424 	}
13425 }
13426 
13427 /**
13428  * lpfc_sli4_hba_unset - Unset the fcoe hba
13429  * @phba: Pointer to HBA context object.
13430  *
13431  * This function is called in the SLI4 code path to reset the HBA's FCoE
13432  * function. The caller is not required to hold any lock. This routine
13433  * issues PCI function reset mailbox command to reset the FCoE function.
13434  * At the end of the function, it calls lpfc_hba_down_post function to
13435  * free any pending commands.
13436  **/
13437 static void
13438 lpfc_sli4_hba_unset(struct lpfc_hba *phba)
13439 {
13440 	int wait_cnt = 0;
13441 	LPFC_MBOXQ_t *mboxq;
13442 	struct pci_dev *pdev = phba->pcidev;
13443 
13444 	lpfc_stop_hba_timers(phba);
13445 	hrtimer_cancel(&phba->cmf_stats_timer);
13446 	hrtimer_cancel(&phba->cmf_timer);
13447 
13448 	if (phba->pport)
13449 		phba->sli4_hba.intr_enable = 0;
13450 
13451 	/*
13452 	 * Gracefully wait out the potential current outstanding asynchronous
13453 	 * mailbox command.
13454 	 */
13455 
13456 	/* First, block any pending async mailbox command from posted */
13457 	spin_lock_irq(&phba->hbalock);
13458 	phba->sli.sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
13459 	spin_unlock_irq(&phba->hbalock);
13460 	/* Now, trying to wait it out if we can */
13461 	while (phba->sli.sli_flag & LPFC_SLI_MBOX_ACTIVE) {
13462 		msleep(10);
13463 		if (++wait_cnt > LPFC_ACTIVE_MBOX_WAIT_CNT)
13464 			break;
13465 	}
13466 	/* Forcefully release the outstanding mailbox command if timed out */
13467 	if (phba->sli.sli_flag & LPFC_SLI_MBOX_ACTIVE) {
13468 		spin_lock_irq(&phba->hbalock);
13469 		mboxq = phba->sli.mbox_active;
13470 		mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
13471 		__lpfc_mbox_cmpl_put(phba, mboxq);
13472 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
13473 		phba->sli.mbox_active = NULL;
13474 		spin_unlock_irq(&phba->hbalock);
13475 	}
13476 
13477 	/* Abort all iocbs associated with the hba */
13478 	lpfc_sli_hba_iocb_abort(phba);
13479 
13480 	if (!pci_channel_offline(phba->pcidev))
13481 		/* Wait for completion of device XRI exchange busy */
13482 		lpfc_sli4_xri_exchange_busy_wait(phba);
13483 
13484 	/* per-phba callback de-registration for hotplug event */
13485 	if (phba->pport)
13486 		lpfc_cpuhp_remove(phba);
13487 
13488 	/* Disable PCI subsystem interrupt */
13489 	lpfc_sli4_disable_intr(phba);
13490 
13491 	/* Disable SR-IOV if enabled */
13492 	if (phba->cfg_sriov_nr_virtfn)
13493 		pci_disable_sriov(pdev);
13494 
13495 	/* Stop kthread signal shall trigger work_done one more time */
13496 	kthread_stop(phba->worker_thread);
13497 
13498 	/* Disable FW logging to host memory */
13499 	lpfc_ras_stop_fwlog(phba);
13500 
13501 	lpfc_sli4_queue_unset(phba);
13502 
13503 	/* Reset SLI4 HBA FCoE function */
13504 	lpfc_pci_function_reset(phba);
13505 
13506 	/* release all queue allocated resources. */
13507 	lpfc_sli4_queue_destroy(phba);
13508 
13509 	/* Free RAS DMA memory */
13510 	if (phba->ras_fwlog.ras_enabled)
13511 		lpfc_sli4_ras_dma_free(phba);
13512 
13513 	/* Stop the SLI4 device port */
13514 	if (phba->pport)
13515 		phba->pport->work_port_events = 0;
13516 }
13517 
13518 static uint32_t
13519 lpfc_cgn_crc32(uint32_t crc, u8 byte)
13520 {
13521 	uint32_t msb = 0;
13522 	uint32_t bit;
13523 
13524 	for (bit = 0; bit < 8; bit++) {
13525 		msb = (crc >> 31) & 1;
13526 		crc <<= 1;
13527 
13528 		if (msb ^ (byte & 1)) {
13529 			crc ^= LPFC_CGN_CRC32_MAGIC_NUMBER;
13530 			crc |= 1;
13531 		}
13532 		byte >>= 1;
13533 	}
13534 	return crc;
13535 }
13536 
13537 static uint32_t
13538 lpfc_cgn_reverse_bits(uint32_t wd)
13539 {
13540 	uint32_t result = 0;
13541 	uint32_t i;
13542 
13543 	for (i = 0; i < 32; i++) {
13544 		result <<= 1;
13545 		result |= (1 & (wd >> i));
13546 	}
13547 	return result;
13548 }
13549 
13550 /*
13551  * The routine corresponds with the algorithm the HBA firmware
13552  * uses to validate the data integrity.
13553  */
13554 uint32_t
13555 lpfc_cgn_calc_crc32(void *ptr, uint32_t byteLen, uint32_t crc)
13556 {
13557 	uint32_t  i;
13558 	uint32_t result;
13559 	uint8_t  *data = (uint8_t *)ptr;
13560 
13561 	for (i = 0; i < byteLen; ++i)
13562 		crc = lpfc_cgn_crc32(crc, data[i]);
13563 
13564 	result = ~lpfc_cgn_reverse_bits(crc);
13565 	return result;
13566 }
13567 
13568 void
13569 lpfc_init_congestion_buf(struct lpfc_hba *phba)
13570 {
13571 	struct lpfc_cgn_info *cp;
13572 	uint16_t size;
13573 	uint32_t crc;
13574 
13575 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
13576 			"6235 INIT Congestion Buffer %p\n", phba->cgn_i);
13577 
13578 	if (!phba->cgn_i)
13579 		return;
13580 	cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
13581 
13582 	atomic_set(&phba->cgn_fabric_warn_cnt, 0);
13583 	atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
13584 	atomic_set(&phba->cgn_sync_alarm_cnt, 0);
13585 	atomic_set(&phba->cgn_sync_warn_cnt, 0);
13586 
13587 	atomic_set(&phba->cgn_driver_evt_cnt, 0);
13588 	atomic_set(&phba->cgn_latency_evt_cnt, 0);
13589 	atomic64_set(&phba->cgn_latency_evt, 0);
13590 	phba->cgn_evt_minute = 0;
13591 
13592 	memset(cp, 0xff, offsetof(struct lpfc_cgn_info, cgn_stat));
13593 	cp->cgn_info_size = cpu_to_le16(LPFC_CGN_INFO_SZ);
13594 	cp->cgn_info_version = LPFC_CGN_INFO_V4;
13595 
13596 	/* cgn parameters */
13597 	cp->cgn_info_mode = phba->cgn_p.cgn_param_mode;
13598 	cp->cgn_info_level0 = phba->cgn_p.cgn_param_level0;
13599 	cp->cgn_info_level1 = phba->cgn_p.cgn_param_level1;
13600 	cp->cgn_info_level2 = phba->cgn_p.cgn_param_level2;
13601 
13602 	lpfc_cgn_update_tstamp(phba, &cp->base_time);
13603 
13604 	/* Fill in default LUN qdepth */
13605 	if (phba->pport) {
13606 		size = (uint16_t)(phba->pport->cfg_lun_queue_depth);
13607 		cp->cgn_lunq = cpu_to_le16(size);
13608 	}
13609 
13610 	/* last used Index initialized to 0xff already */
13611 
13612 	cp->cgn_warn_freq = cpu_to_le16(LPFC_FPIN_INIT_FREQ);
13613 	cp->cgn_alarm_freq = cpu_to_le16(LPFC_FPIN_INIT_FREQ);
13614 	crc = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ, LPFC_CGN_CRC32_SEED);
13615 	cp->cgn_info_crc = cpu_to_le32(crc);
13616 
13617 	phba->cgn_evt_timestamp = jiffies +
13618 		msecs_to_jiffies(LPFC_CGN_TIMER_TO_MIN);
13619 }
13620 
13621 void
13622 lpfc_init_congestion_stat(struct lpfc_hba *phba)
13623 {
13624 	struct lpfc_cgn_info *cp;
13625 	uint32_t crc;
13626 
13627 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
13628 			"6236 INIT Congestion Stat %p\n", phba->cgn_i);
13629 
13630 	if (!phba->cgn_i)
13631 		return;
13632 
13633 	cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
13634 	memset(&cp->cgn_stat, 0, sizeof(cp->cgn_stat));
13635 
13636 	lpfc_cgn_update_tstamp(phba, &cp->stat_start);
13637 	crc = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ, LPFC_CGN_CRC32_SEED);
13638 	cp->cgn_info_crc = cpu_to_le32(crc);
13639 }
13640 
13641 /**
13642  * __lpfc_reg_congestion_buf - register congestion info buffer with HBA
13643  * @phba: Pointer to hba context object.
13644  * @reg: flag to determine register or unregister.
13645  */
13646 static int
13647 __lpfc_reg_congestion_buf(struct lpfc_hba *phba, int reg)
13648 {
13649 	struct lpfc_mbx_reg_congestion_buf *reg_congestion_buf;
13650 	union  lpfc_sli4_cfg_shdr *shdr;
13651 	uint32_t shdr_status, shdr_add_status;
13652 	LPFC_MBOXQ_t *mboxq;
13653 	int length, rc;
13654 
13655 	if (!phba->cgn_i)
13656 		return -ENXIO;
13657 
13658 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
13659 	if (!mboxq) {
13660 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX,
13661 				"2641 REG_CONGESTION_BUF mbox allocation fail: "
13662 				"HBA state x%x reg %d\n",
13663 				phba->pport->port_state, reg);
13664 		return -ENOMEM;
13665 	}
13666 
13667 	length = (sizeof(struct lpfc_mbx_reg_congestion_buf) -
13668 		sizeof(struct lpfc_sli4_cfg_mhdr));
13669 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
13670 			 LPFC_MBOX_OPCODE_REG_CONGESTION_BUF, length,
13671 			 LPFC_SLI4_MBX_EMBED);
13672 	reg_congestion_buf = &mboxq->u.mqe.un.reg_congestion_buf;
13673 	bf_set(lpfc_mbx_reg_cgn_buf_type, reg_congestion_buf, 1);
13674 	if (reg > 0)
13675 		bf_set(lpfc_mbx_reg_cgn_buf_cnt, reg_congestion_buf, 1);
13676 	else
13677 		bf_set(lpfc_mbx_reg_cgn_buf_cnt, reg_congestion_buf, 0);
13678 	reg_congestion_buf->length = sizeof(struct lpfc_cgn_info);
13679 	reg_congestion_buf->addr_lo =
13680 		putPaddrLow(phba->cgn_i->phys);
13681 	reg_congestion_buf->addr_hi =
13682 		putPaddrHigh(phba->cgn_i->phys);
13683 
13684 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
13685 	shdr = (union lpfc_sli4_cfg_shdr *)
13686 		&mboxq->u.mqe.un.sli4_config.header.cfg_shdr;
13687 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13688 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
13689 				 &shdr->response);
13690 	mempool_free(mboxq, phba->mbox_mem_pool);
13691 	if (shdr_status || shdr_add_status || rc) {
13692 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13693 				"2642 REG_CONGESTION_BUF mailbox "
13694 				"failed with status x%x add_status x%x,"
13695 				" mbx status x%x reg %d\n",
13696 				shdr_status, shdr_add_status, rc, reg);
13697 		return -ENXIO;
13698 	}
13699 	return 0;
13700 }
13701 
13702 int
13703 lpfc_unreg_congestion_buf(struct lpfc_hba *phba)
13704 {
13705 	lpfc_cmf_stop(phba);
13706 	return __lpfc_reg_congestion_buf(phba, 0);
13707 }
13708 
13709 int
13710 lpfc_reg_congestion_buf(struct lpfc_hba *phba)
13711 {
13712 	return __lpfc_reg_congestion_buf(phba, 1);
13713 }
13714 
13715 /**
13716  * lpfc_get_sli4_parameters - Get the SLI4 Config PARAMETERS.
13717  * @phba: Pointer to HBA context object.
13718  * @mboxq: Pointer to the mailboxq memory for the mailbox command response.
13719  *
13720  * This function is called in the SLI4 code path to read the port's
13721  * sli4 capabilities.
13722  *
13723  * This function may be be called from any context that can block-wait
13724  * for the completion.  The expectation is that this routine is called
13725  * typically from probe_one or from the online routine.
13726  **/
13727 int
13728 lpfc_get_sli4_parameters(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
13729 {
13730 	int rc;
13731 	struct lpfc_mqe *mqe = &mboxq->u.mqe;
13732 	struct lpfc_pc_sli4_params *sli4_params;
13733 	uint32_t mbox_tmo;
13734 	int length;
13735 	bool exp_wqcq_pages = true;
13736 	struct lpfc_sli4_parameters *mbx_sli4_parameters;
13737 
13738 	/*
13739 	 * By default, the driver assumes the SLI4 port requires RPI
13740 	 * header postings.  The SLI4_PARAM response will correct this
13741 	 * assumption.
13742 	 */
13743 	phba->sli4_hba.rpi_hdrs_in_use = 1;
13744 
13745 	/* Read the port's SLI4 Config Parameters */
13746 	length = (sizeof(struct lpfc_mbx_get_sli4_parameters) -
13747 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13748 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
13749 			 LPFC_MBOX_OPCODE_GET_SLI4_PARAMETERS,
13750 			 length, LPFC_SLI4_MBX_EMBED);
13751 	if (!phba->sli4_hba.intr_enable)
13752 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
13753 	else {
13754 		mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
13755 		rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
13756 	}
13757 	if (unlikely(rc))
13758 		return rc;
13759 	sli4_params = &phba->sli4_hba.pc_sli4_params;
13760 	mbx_sli4_parameters = &mqe->un.get_sli4_parameters.sli4_parameters;
13761 	sli4_params->if_type = bf_get(cfg_if_type, mbx_sli4_parameters);
13762 	sli4_params->sli_rev = bf_get(cfg_sli_rev, mbx_sli4_parameters);
13763 	sli4_params->sli_family = bf_get(cfg_sli_family, mbx_sli4_parameters);
13764 	sli4_params->featurelevel_1 = bf_get(cfg_sli_hint_1,
13765 					     mbx_sli4_parameters);
13766 	sli4_params->featurelevel_2 = bf_get(cfg_sli_hint_2,
13767 					     mbx_sli4_parameters);
13768 	if (bf_get(cfg_phwq, mbx_sli4_parameters))
13769 		phba->sli3_options |= LPFC_SLI4_PHWQ_ENABLED;
13770 	else
13771 		phba->sli3_options &= ~LPFC_SLI4_PHWQ_ENABLED;
13772 	sli4_params->sge_supp_len = mbx_sli4_parameters->sge_supp_len;
13773 	sli4_params->loopbk_scope = bf_get(cfg_loopbk_scope,
13774 					   mbx_sli4_parameters);
13775 	sli4_params->oas_supported = bf_get(cfg_oas, mbx_sli4_parameters);
13776 	sli4_params->cqv = bf_get(cfg_cqv, mbx_sli4_parameters);
13777 	sli4_params->mqv = bf_get(cfg_mqv, mbx_sli4_parameters);
13778 	sli4_params->wqv = bf_get(cfg_wqv, mbx_sli4_parameters);
13779 	sli4_params->rqv = bf_get(cfg_rqv, mbx_sli4_parameters);
13780 	sli4_params->eqav = bf_get(cfg_eqav, mbx_sli4_parameters);
13781 	sli4_params->cqav = bf_get(cfg_cqav, mbx_sli4_parameters);
13782 	sli4_params->wqsize = bf_get(cfg_wqsize, mbx_sli4_parameters);
13783 	sli4_params->bv1s = bf_get(cfg_bv1s, mbx_sli4_parameters);
13784 	sli4_params->pls = bf_get(cfg_pvl, mbx_sli4_parameters);
13785 	sli4_params->sgl_pages_max = bf_get(cfg_sgl_page_cnt,
13786 					    mbx_sli4_parameters);
13787 	sli4_params->wqpcnt = bf_get(cfg_wqpcnt, mbx_sli4_parameters);
13788 	sli4_params->sgl_pp_align = bf_get(cfg_sgl_pp_align,
13789 					   mbx_sli4_parameters);
13790 	phba->sli4_hba.extents_in_use = bf_get(cfg_ext, mbx_sli4_parameters);
13791 	phba->sli4_hba.rpi_hdrs_in_use = bf_get(cfg_hdrr, mbx_sli4_parameters);
13792 	sli4_params->mi_cap = bf_get(cfg_mi_ver, mbx_sli4_parameters);
13793 
13794 	/* Check for Extended Pre-Registered SGL support */
13795 	phba->cfg_xpsgl = bf_get(cfg_xpsgl, mbx_sli4_parameters);
13796 
13797 	/* Check for firmware nvme support */
13798 	rc = (bf_get(cfg_nvme, mbx_sli4_parameters) &&
13799 		     bf_get(cfg_xib, mbx_sli4_parameters));
13800 
13801 	if (rc) {
13802 		/* Save this to indicate the Firmware supports NVME */
13803 		sli4_params->nvme = 1;
13804 
13805 		/* Firmware NVME support, check driver FC4 NVME support */
13806 		if (phba->cfg_enable_fc4_type == LPFC_ENABLE_FCP) {
13807 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_NVME,
13808 					"6133 Disabling NVME support: "
13809 					"FC4 type not supported: x%x\n",
13810 					phba->cfg_enable_fc4_type);
13811 			goto fcponly;
13812 		}
13813 	} else {
13814 		/* No firmware NVME support, check driver FC4 NVME support */
13815 		sli4_params->nvme = 0;
13816 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13817 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_NVME,
13818 					"6101 Disabling NVME support: Not "
13819 					"supported by firmware (%d %d) x%x\n",
13820 					bf_get(cfg_nvme, mbx_sli4_parameters),
13821 					bf_get(cfg_xib, mbx_sli4_parameters),
13822 					phba->cfg_enable_fc4_type);
13823 fcponly:
13824 			phba->nvmet_support = 0;
13825 			phba->cfg_nvmet_mrq = 0;
13826 			phba->cfg_nvme_seg_cnt = 0;
13827 
13828 			/* If no FC4 type support, move to just SCSI support */
13829 			if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP))
13830 				return -ENODEV;
13831 			phba->cfg_enable_fc4_type = LPFC_ENABLE_FCP;
13832 		}
13833 	}
13834 
13835 	/* If the NVME FC4 type is enabled, scale the sg_seg_cnt to
13836 	 * accommodate 512K and 1M IOs in a single nvme buf.
13837 	 */
13838 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
13839 		phba->cfg_sg_seg_cnt = LPFC_MAX_NVME_SEG_CNT;
13840 
13841 	/* Enable embedded Payload BDE if support is indicated */
13842 	if (bf_get(cfg_pbde, mbx_sli4_parameters))
13843 		phba->cfg_enable_pbde = 1;
13844 	else
13845 		phba->cfg_enable_pbde = 0;
13846 
13847 	/*
13848 	 * To support Suppress Response feature we must satisfy 3 conditions.
13849 	 * lpfc_suppress_rsp module parameter must be set (default).
13850 	 * In SLI4-Parameters Descriptor:
13851 	 * Extended Inline Buffers (XIB) must be supported.
13852 	 * Suppress Response IU Not Supported (SRIUNS) must NOT be supported
13853 	 * (double negative).
13854 	 */
13855 	if (phba->cfg_suppress_rsp && bf_get(cfg_xib, mbx_sli4_parameters) &&
13856 	    !(bf_get(cfg_nosr, mbx_sli4_parameters)))
13857 		phba->sli.sli_flag |= LPFC_SLI_SUPPRESS_RSP;
13858 	else
13859 		phba->cfg_suppress_rsp = 0;
13860 
13861 	if (bf_get(cfg_eqdr, mbx_sli4_parameters))
13862 		phba->sli.sli_flag |= LPFC_SLI_USE_EQDR;
13863 
13864 	/* Make sure that sge_supp_len can be handled by the driver */
13865 	if (sli4_params->sge_supp_len > LPFC_MAX_SGE_SIZE)
13866 		sli4_params->sge_supp_len = LPFC_MAX_SGE_SIZE;
13867 
13868 	dma_set_max_seg_size(&phba->pcidev->dev, sli4_params->sge_supp_len);
13869 
13870 	/*
13871 	 * Check whether the adapter supports an embedded copy of the
13872 	 * FCP CMD IU within the WQE for FCP_Ixxx commands. In order
13873 	 * to use this option, 128-byte WQEs must be used.
13874 	 */
13875 	if (bf_get(cfg_ext_embed_cb, mbx_sli4_parameters))
13876 		phba->fcp_embed_io = 1;
13877 	else
13878 		phba->fcp_embed_io = 0;
13879 
13880 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_NVME,
13881 			"6422 XIB %d PBDE %d: FCP %d NVME %d %d %d\n",
13882 			bf_get(cfg_xib, mbx_sli4_parameters),
13883 			phba->cfg_enable_pbde,
13884 			phba->fcp_embed_io, sli4_params->nvme,
13885 			phba->cfg_nvme_embed_cmd, phba->cfg_suppress_rsp);
13886 
13887 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
13888 	    LPFC_SLI_INTF_IF_TYPE_2) &&
13889 	    (bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf) ==
13890 		 LPFC_SLI_INTF_FAMILY_LNCR_A0))
13891 		exp_wqcq_pages = false;
13892 
13893 	if ((bf_get(cfg_cqpsize, mbx_sli4_parameters) & LPFC_CQ_16K_PAGE_SZ) &&
13894 	    (bf_get(cfg_wqpsize, mbx_sli4_parameters) & LPFC_WQ_16K_PAGE_SZ) &&
13895 	    exp_wqcq_pages &&
13896 	    (sli4_params->wqsize & LPFC_WQ_SZ128_SUPPORT))
13897 		phba->enab_exp_wqcq_pages = 1;
13898 	else
13899 		phba->enab_exp_wqcq_pages = 0;
13900 	/*
13901 	 * Check if the SLI port supports MDS Diagnostics
13902 	 */
13903 	if (bf_get(cfg_mds_diags, mbx_sli4_parameters))
13904 		phba->mds_diags_support = 1;
13905 	else
13906 		phba->mds_diags_support = 0;
13907 
13908 	/*
13909 	 * Check if the SLI port supports NSLER
13910 	 */
13911 	if (bf_get(cfg_nsler, mbx_sli4_parameters))
13912 		phba->nsler = 1;
13913 	else
13914 		phba->nsler = 0;
13915 
13916 	return 0;
13917 }
13918 
13919 /**
13920  * lpfc_pci_probe_one_s3 - PCI probe func to reg SLI-3 device to PCI subsystem.
13921  * @pdev: pointer to PCI device
13922  * @pid: pointer to PCI device identifier
13923  *
13924  * This routine is to be called to attach a device with SLI-3 interface spec
13925  * to the PCI subsystem. When an Emulex HBA with SLI-3 interface spec is
13926  * presented on PCI bus, the kernel PCI subsystem looks at PCI device-specific
13927  * information of the device and driver to see if the driver state that it can
13928  * support this kind of device. If the match is successful, the driver core
13929  * invokes this routine. If this routine determines it can claim the HBA, it
13930  * does all the initialization that it needs to do to handle the HBA properly.
13931  *
13932  * Return code
13933  * 	0 - driver can claim the device
13934  * 	negative value - driver can not claim the device
13935  **/
13936 static int
13937 lpfc_pci_probe_one_s3(struct pci_dev *pdev, const struct pci_device_id *pid)
13938 {
13939 	struct lpfc_hba   *phba;
13940 	struct lpfc_vport *vport = NULL;
13941 	struct Scsi_Host  *shost = NULL;
13942 	int error;
13943 	uint32_t cfg_mode, intr_mode;
13944 
13945 	/* Allocate memory for HBA structure */
13946 	phba = lpfc_hba_alloc(pdev);
13947 	if (!phba)
13948 		return -ENOMEM;
13949 
13950 	/* Perform generic PCI device enabling operation */
13951 	error = lpfc_enable_pci_dev(phba);
13952 	if (error)
13953 		goto out_free_phba;
13954 
13955 	/* Set up SLI API function jump table for PCI-device group-0 HBAs */
13956 	error = lpfc_api_table_setup(phba, LPFC_PCI_DEV_LP);
13957 	if (error)
13958 		goto out_disable_pci_dev;
13959 
13960 	/* Set up SLI-3 specific device PCI memory space */
13961 	error = lpfc_sli_pci_mem_setup(phba);
13962 	if (error) {
13963 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13964 				"1402 Failed to set up pci memory space.\n");
13965 		goto out_disable_pci_dev;
13966 	}
13967 
13968 	/* Set up SLI-3 specific device driver resources */
13969 	error = lpfc_sli_driver_resource_setup(phba);
13970 	if (error) {
13971 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13972 				"1404 Failed to set up driver resource.\n");
13973 		goto out_unset_pci_mem_s3;
13974 	}
13975 
13976 	/* Initialize and populate the iocb list per host */
13977 
13978 	error = lpfc_init_iocb_list(phba, LPFC_IOCB_LIST_CNT);
13979 	if (error) {
13980 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13981 				"1405 Failed to initialize iocb list.\n");
13982 		goto out_unset_driver_resource_s3;
13983 	}
13984 
13985 	/* Set up common device driver resources */
13986 	error = lpfc_setup_driver_resource_phase2(phba);
13987 	if (error) {
13988 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13989 				"1406 Failed to set up driver resource.\n");
13990 		goto out_free_iocb_list;
13991 	}
13992 
13993 	/* Get the default values for Model Name and Description */
13994 	lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
13995 
13996 	/* Create SCSI host to the physical port */
13997 	error = lpfc_create_shost(phba);
13998 	if (error) {
13999 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14000 				"1407 Failed to create scsi host.\n");
14001 		goto out_unset_driver_resource;
14002 	}
14003 
14004 	/* Configure sysfs attributes */
14005 	vport = phba->pport;
14006 	error = lpfc_alloc_sysfs_attr(vport);
14007 	if (error) {
14008 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14009 				"1476 Failed to allocate sysfs attr\n");
14010 		goto out_destroy_shost;
14011 	}
14012 
14013 	shost = lpfc_shost_from_vport(vport); /* save shost for error cleanup */
14014 	/* Now, trying to enable interrupt and bring up the device */
14015 	cfg_mode = phba->cfg_use_msi;
14016 	while (true) {
14017 		/* Put device to a known state before enabling interrupt */
14018 		lpfc_stop_port(phba);
14019 		/* Configure and enable interrupt */
14020 		intr_mode = lpfc_sli_enable_intr(phba, cfg_mode);
14021 		if (intr_mode == LPFC_INTR_ERROR) {
14022 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14023 					"0431 Failed to enable interrupt.\n");
14024 			error = -ENODEV;
14025 			goto out_free_sysfs_attr;
14026 		}
14027 		/* SLI-3 HBA setup */
14028 		if (lpfc_sli_hba_setup(phba)) {
14029 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14030 					"1477 Failed to set up hba\n");
14031 			error = -ENODEV;
14032 			goto out_remove_device;
14033 		}
14034 
14035 		/* Wait 50ms for the interrupts of previous mailbox commands */
14036 		msleep(50);
14037 		/* Check active interrupts on message signaled interrupts */
14038 		if (intr_mode == 0 ||
14039 		    phba->sli.slistat.sli_intr > LPFC_MSIX_VECTORS) {
14040 			/* Log the current active interrupt mode */
14041 			phba->intr_mode = intr_mode;
14042 			lpfc_log_intr_mode(phba, intr_mode);
14043 			break;
14044 		} else {
14045 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
14046 					"0447 Configure interrupt mode (%d) "
14047 					"failed active interrupt test.\n",
14048 					intr_mode);
14049 			/* Disable the current interrupt mode */
14050 			lpfc_sli_disable_intr(phba);
14051 			/* Try next level of interrupt mode */
14052 			cfg_mode = --intr_mode;
14053 		}
14054 	}
14055 
14056 	/* Perform post initialization setup */
14057 	lpfc_post_init_setup(phba);
14058 
14059 	/* Check if there are static vports to be created. */
14060 	lpfc_create_static_vport(phba);
14061 
14062 	return 0;
14063 
14064 out_remove_device:
14065 	lpfc_unset_hba(phba);
14066 out_free_sysfs_attr:
14067 	lpfc_free_sysfs_attr(vport);
14068 out_destroy_shost:
14069 	lpfc_destroy_shost(phba);
14070 out_unset_driver_resource:
14071 	lpfc_unset_driver_resource_phase2(phba);
14072 out_free_iocb_list:
14073 	lpfc_free_iocb_list(phba);
14074 out_unset_driver_resource_s3:
14075 	lpfc_sli_driver_resource_unset(phba);
14076 out_unset_pci_mem_s3:
14077 	lpfc_sli_pci_mem_unset(phba);
14078 out_disable_pci_dev:
14079 	lpfc_disable_pci_dev(phba);
14080 	if (shost)
14081 		scsi_host_put(shost);
14082 out_free_phba:
14083 	lpfc_hba_free(phba);
14084 	return error;
14085 }
14086 
14087 /**
14088  * lpfc_pci_remove_one_s3 - PCI func to unreg SLI-3 device from PCI subsystem.
14089  * @pdev: pointer to PCI device
14090  *
14091  * This routine is to be called to disattach a device with SLI-3 interface
14092  * spec from PCI subsystem. When an Emulex HBA with SLI-3 interface spec is
14093  * removed from PCI bus, it performs all the necessary cleanup for the HBA
14094  * device to be removed from the PCI subsystem properly.
14095  **/
14096 static void
14097 lpfc_pci_remove_one_s3(struct pci_dev *pdev)
14098 {
14099 	struct Scsi_Host  *shost = pci_get_drvdata(pdev);
14100 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
14101 	struct lpfc_vport **vports;
14102 	struct lpfc_hba   *phba = vport->phba;
14103 	int i;
14104 
14105 	set_bit(FC_UNLOADING, &vport->load_flag);
14106 
14107 	lpfc_free_sysfs_attr(vport);
14108 
14109 	/* Release all the vports against this physical port */
14110 	vports = lpfc_create_vport_work_array(phba);
14111 	if (vports != NULL)
14112 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
14113 			if (vports[i]->port_type == LPFC_PHYSICAL_PORT)
14114 				continue;
14115 			fc_vport_terminate(vports[i]->fc_vport);
14116 		}
14117 	lpfc_destroy_vport_work_array(phba, vports);
14118 
14119 	/* Remove FC host with the physical port */
14120 	fc_remove_host(shost);
14121 	scsi_remove_host(shost);
14122 
14123 	/* Clean up all nodes, mailboxes and IOs. */
14124 	lpfc_cleanup(vport);
14125 
14126 	/*
14127 	 * Bring down the SLI Layer. This step disable all interrupts,
14128 	 * clears the rings, discards all mailbox commands, and resets
14129 	 * the HBA.
14130 	 */
14131 
14132 	/* HBA interrupt will be disabled after this call */
14133 	lpfc_sli_hba_down(phba);
14134 	/* Stop kthread signal shall trigger work_done one more time */
14135 	kthread_stop(phba->worker_thread);
14136 	/* Final cleanup of txcmplq and reset the HBA */
14137 	lpfc_sli_brdrestart(phba);
14138 
14139 	kfree(phba->vpi_bmask);
14140 	kfree(phba->vpi_ids);
14141 
14142 	lpfc_stop_hba_timers(phba);
14143 	spin_lock_irq(&phba->port_list_lock);
14144 	list_del_init(&vport->listentry);
14145 	spin_unlock_irq(&phba->port_list_lock);
14146 
14147 	lpfc_debugfs_terminate(vport);
14148 
14149 	/* Disable SR-IOV if enabled */
14150 	if (phba->cfg_sriov_nr_virtfn)
14151 		pci_disable_sriov(pdev);
14152 
14153 	/* Disable interrupt */
14154 	lpfc_sli_disable_intr(phba);
14155 
14156 	scsi_host_put(shost);
14157 
14158 	/*
14159 	 * Call scsi_free before mem_free since scsi bufs are released to their
14160 	 * corresponding pools here.
14161 	 */
14162 	lpfc_scsi_free(phba);
14163 	lpfc_free_iocb_list(phba);
14164 
14165 	lpfc_mem_free_all(phba);
14166 
14167 	dma_free_coherent(&pdev->dev, lpfc_sli_hbq_size(),
14168 			  phba->hbqslimp.virt, phba->hbqslimp.phys);
14169 
14170 	/* Free resources associated with SLI2 interface */
14171 	dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
14172 			  phba->slim2p.virt, phba->slim2p.phys);
14173 
14174 	/* unmap adapter SLIM and Control Registers */
14175 	iounmap(phba->ctrl_regs_memmap_p);
14176 	iounmap(phba->slim_memmap_p);
14177 
14178 	lpfc_hba_free(phba);
14179 
14180 	pci_release_mem_regions(pdev);
14181 	pci_disable_device(pdev);
14182 }
14183 
14184 /**
14185  * lpfc_pci_suspend_one_s3 - PCI func to suspend SLI-3 device for power mgmnt
14186  * @dev_d: pointer to device
14187  *
14188  * This routine is to be called from the kernel's PCI subsystem to support
14189  * system Power Management (PM) to device with SLI-3 interface spec. When
14190  * PM invokes this method, it quiesces the device by stopping the driver's
14191  * worker thread for the device, turning off device's interrupt and DMA,
14192  * and bring the device offline. Note that as the driver implements the
14193  * minimum PM requirements to a power-aware driver's PM support for the
14194  * suspend/resume -- all the possible PM messages (SUSPEND, HIBERNATE, FREEZE)
14195  * to the suspend() method call will be treated as SUSPEND and the driver will
14196  * fully reinitialize its device during resume() method call, the driver will
14197  * set device to PCI_D3hot state in PCI config space instead of setting it
14198  * according to the @msg provided by the PM.
14199  *
14200  * Return code
14201  * 	0 - driver suspended the device
14202  * 	Error otherwise
14203  **/
14204 static int __maybe_unused
14205 lpfc_pci_suspend_one_s3(struct device *dev_d)
14206 {
14207 	struct Scsi_Host *shost = dev_get_drvdata(dev_d);
14208 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14209 
14210 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
14211 			"0473 PCI device Power Management suspend.\n");
14212 
14213 	/* Bring down the device */
14214 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
14215 	lpfc_offline(phba);
14216 	kthread_stop(phba->worker_thread);
14217 
14218 	/* Disable interrupt from device */
14219 	lpfc_sli_disable_intr(phba);
14220 
14221 	return 0;
14222 }
14223 
14224 /**
14225  * lpfc_pci_resume_one_s3 - PCI func to resume SLI-3 device for power mgmnt
14226  * @dev_d: pointer to device
14227  *
14228  * This routine is to be called from the kernel's PCI subsystem to support
14229  * system Power Management (PM) to device with SLI-3 interface spec. When PM
14230  * invokes this method, it restores the device's PCI config space state and
14231  * fully reinitializes the device and brings it online. Note that as the
14232  * driver implements the minimum PM requirements to a power-aware driver's
14233  * PM for suspend/resume -- all the possible PM messages (SUSPEND, HIBERNATE,
14234  * FREEZE) to the suspend() method call will be treated as SUSPEND and the
14235  * driver will fully reinitialize its device during resume() method call,
14236  * the device will be set to PCI_D0 directly in PCI config space before
14237  * restoring the state.
14238  *
14239  * Return code
14240  * 	0 - driver suspended the device
14241  * 	Error otherwise
14242  **/
14243 static int __maybe_unused
14244 lpfc_pci_resume_one_s3(struct device *dev_d)
14245 {
14246 	struct Scsi_Host *shost = dev_get_drvdata(dev_d);
14247 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14248 	uint32_t intr_mode;
14249 	int error;
14250 
14251 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
14252 			"0452 PCI device Power Management resume.\n");
14253 
14254 	/* Startup the kernel thread for this host adapter. */
14255 	phba->worker_thread = kthread_run(lpfc_do_work, phba,
14256 					"lpfc_worker_%d", phba->brd_no);
14257 	if (IS_ERR(phba->worker_thread)) {
14258 		error = PTR_ERR(phba->worker_thread);
14259 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14260 				"0434 PM resume failed to start worker "
14261 				"thread: error=x%x.\n", error);
14262 		return error;
14263 	}
14264 
14265 	/* Init cpu_map array */
14266 	lpfc_cpu_map_array_init(phba);
14267 	/* Init hba_eq_hdl array */
14268 	lpfc_hba_eq_hdl_array_init(phba);
14269 	/* Configure and enable interrupt */
14270 	intr_mode = lpfc_sli_enable_intr(phba, phba->intr_mode);
14271 	if (intr_mode == LPFC_INTR_ERROR) {
14272 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14273 				"0430 PM resume Failed to enable interrupt\n");
14274 		return -EIO;
14275 	} else
14276 		phba->intr_mode = intr_mode;
14277 
14278 	/* Restart HBA and bring it online */
14279 	lpfc_sli_brdrestart(phba);
14280 	lpfc_online(phba);
14281 
14282 	/* Log the current active interrupt mode */
14283 	lpfc_log_intr_mode(phba, phba->intr_mode);
14284 
14285 	return 0;
14286 }
14287 
14288 /**
14289  * lpfc_sli_prep_dev_for_recover - Prepare SLI3 device for pci slot recover
14290  * @phba: pointer to lpfc hba data structure.
14291  *
14292  * This routine is called to prepare the SLI3 device for PCI slot recover. It
14293  * aborts all the outstanding SCSI I/Os to the pci device.
14294  **/
14295 static void
14296 lpfc_sli_prep_dev_for_recover(struct lpfc_hba *phba)
14297 {
14298 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14299 			"2723 PCI channel I/O abort preparing for recovery\n");
14300 
14301 	/*
14302 	 * There may be errored I/Os through HBA, abort all I/Os on txcmplq
14303 	 * and let the SCSI mid-layer to retry them to recover.
14304 	 */
14305 	lpfc_sli_abort_fcp_rings(phba);
14306 }
14307 
14308 /**
14309  * lpfc_sli_prep_dev_for_reset - Prepare SLI3 device for pci slot reset
14310  * @phba: pointer to lpfc hba data structure.
14311  *
14312  * This routine is called to prepare the SLI3 device for PCI slot reset. It
14313  * disables the device interrupt and pci device, and aborts the internal FCP
14314  * pending I/Os.
14315  **/
14316 static void
14317 lpfc_sli_prep_dev_for_reset(struct lpfc_hba *phba)
14318 {
14319 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14320 			"2710 PCI channel disable preparing for reset\n");
14321 
14322 	/* Block any management I/Os to the device */
14323 	lpfc_block_mgmt_io(phba, LPFC_MBX_WAIT);
14324 
14325 	/* Block all SCSI devices' I/Os on the host */
14326 	lpfc_scsi_dev_block(phba);
14327 
14328 	/* Flush all driver's outstanding SCSI I/Os as we are to reset */
14329 	lpfc_sli_flush_io_rings(phba);
14330 
14331 	/* stop all timers */
14332 	lpfc_stop_hba_timers(phba);
14333 
14334 	/* Disable interrupt and pci device */
14335 	lpfc_sli_disable_intr(phba);
14336 	pci_disable_device(phba->pcidev);
14337 }
14338 
14339 /**
14340  * lpfc_sli_prep_dev_for_perm_failure - Prepare SLI3 dev for pci slot disable
14341  * @phba: pointer to lpfc hba data structure.
14342  *
14343  * This routine is called to prepare the SLI3 device for PCI slot permanently
14344  * disabling. It blocks the SCSI transport layer traffic and flushes the FCP
14345  * pending I/Os.
14346  **/
14347 static void
14348 lpfc_sli_prep_dev_for_perm_failure(struct lpfc_hba *phba)
14349 {
14350 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14351 			"2711 PCI channel permanent disable for failure\n");
14352 	/* Block all SCSI devices' I/Os on the host */
14353 	lpfc_scsi_dev_block(phba);
14354 	lpfc_sli4_prep_dev_for_reset(phba);
14355 
14356 	/* stop all timers */
14357 	lpfc_stop_hba_timers(phba);
14358 
14359 	/* Clean up all driver's outstanding SCSI I/Os */
14360 	lpfc_sli_flush_io_rings(phba);
14361 }
14362 
14363 /**
14364  * lpfc_io_error_detected_s3 - Method for handling SLI-3 device PCI I/O error
14365  * @pdev: pointer to PCI device.
14366  * @state: the current PCI connection state.
14367  *
14368  * This routine is called from the PCI subsystem for I/O error handling to
14369  * device with SLI-3 interface spec. This function is called by the PCI
14370  * subsystem after a PCI bus error affecting this device has been detected.
14371  * When this function is invoked, it will need to stop all the I/Os and
14372  * interrupt(s) to the device. Once that is done, it will return
14373  * PCI_ERS_RESULT_NEED_RESET for the PCI subsystem to perform proper recovery
14374  * as desired.
14375  *
14376  * Return codes
14377  * 	PCI_ERS_RESULT_CAN_RECOVER - can be recovered with reset_link
14378  * 	PCI_ERS_RESULT_NEED_RESET - need to reset before recovery
14379  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
14380  **/
14381 static pci_ers_result_t
14382 lpfc_io_error_detected_s3(struct pci_dev *pdev, pci_channel_state_t state)
14383 {
14384 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
14385 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14386 
14387 	switch (state) {
14388 	case pci_channel_io_normal:
14389 		/* Non-fatal error, prepare for recovery */
14390 		lpfc_sli_prep_dev_for_recover(phba);
14391 		return PCI_ERS_RESULT_CAN_RECOVER;
14392 	case pci_channel_io_frozen:
14393 		/* Fatal error, prepare for slot reset */
14394 		lpfc_sli_prep_dev_for_reset(phba);
14395 		return PCI_ERS_RESULT_NEED_RESET;
14396 	case pci_channel_io_perm_failure:
14397 		/* Permanent failure, prepare for device down */
14398 		lpfc_sli_prep_dev_for_perm_failure(phba);
14399 		return PCI_ERS_RESULT_DISCONNECT;
14400 	default:
14401 		/* Unknown state, prepare and request slot reset */
14402 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14403 				"0472 Unknown PCI error state: x%x\n", state);
14404 		lpfc_sli_prep_dev_for_reset(phba);
14405 		return PCI_ERS_RESULT_NEED_RESET;
14406 	}
14407 }
14408 
14409 /**
14410  * lpfc_io_slot_reset_s3 - Method for restarting PCI SLI-3 device from scratch.
14411  * @pdev: pointer to PCI device.
14412  *
14413  * This routine is called from the PCI subsystem for error handling to
14414  * device with SLI-3 interface spec. This is called after PCI bus has been
14415  * reset to restart the PCI card from scratch, as if from a cold-boot.
14416  * During the PCI subsystem error recovery, after driver returns
14417  * PCI_ERS_RESULT_NEED_RESET, the PCI subsystem will perform proper error
14418  * recovery and then call this routine before calling the .resume method
14419  * to recover the device. This function will initialize the HBA device,
14420  * enable the interrupt, but it will just put the HBA to offline state
14421  * without passing any I/O traffic.
14422  *
14423  * Return codes
14424  * 	PCI_ERS_RESULT_RECOVERED - the device has been recovered
14425  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
14426  */
14427 static pci_ers_result_t
14428 lpfc_io_slot_reset_s3(struct pci_dev *pdev)
14429 {
14430 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
14431 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14432 	struct lpfc_sli *psli = &phba->sli;
14433 	uint32_t intr_mode;
14434 
14435 	dev_printk(KERN_INFO, &pdev->dev, "recovering from a slot reset.\n");
14436 	if (pci_enable_device_mem(pdev)) {
14437 		printk(KERN_ERR "lpfc: Cannot re-enable "
14438 			"PCI device after reset.\n");
14439 		return PCI_ERS_RESULT_DISCONNECT;
14440 	}
14441 
14442 	pci_restore_state(pdev);
14443 
14444 	/*
14445 	 * As the new kernel behavior of pci_restore_state() API call clears
14446 	 * device saved_state flag, need to save the restored state again.
14447 	 */
14448 	pci_save_state(pdev);
14449 
14450 	if (pdev->is_busmaster)
14451 		pci_set_master(pdev);
14452 
14453 	spin_lock_irq(&phba->hbalock);
14454 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
14455 	spin_unlock_irq(&phba->hbalock);
14456 
14457 	/* Configure and enable interrupt */
14458 	intr_mode = lpfc_sli_enable_intr(phba, phba->intr_mode);
14459 	if (intr_mode == LPFC_INTR_ERROR) {
14460 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14461 				"0427 Cannot re-enable interrupt after "
14462 				"slot reset.\n");
14463 		return PCI_ERS_RESULT_DISCONNECT;
14464 	} else
14465 		phba->intr_mode = intr_mode;
14466 
14467 	/* Take device offline, it will perform cleanup */
14468 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
14469 	lpfc_offline(phba);
14470 	lpfc_sli_brdrestart(phba);
14471 
14472 	/* Log the current active interrupt mode */
14473 	lpfc_log_intr_mode(phba, phba->intr_mode);
14474 
14475 	return PCI_ERS_RESULT_RECOVERED;
14476 }
14477 
14478 /**
14479  * lpfc_io_resume_s3 - Method for resuming PCI I/O operation on SLI-3 device.
14480  * @pdev: pointer to PCI device
14481  *
14482  * This routine is called from the PCI subsystem for error handling to device
14483  * with SLI-3 interface spec. It is called when kernel error recovery tells
14484  * the lpfc driver that it is ok to resume normal PCI operation after PCI bus
14485  * error recovery. After this call, traffic can start to flow from this device
14486  * again.
14487  */
14488 static void
14489 lpfc_io_resume_s3(struct pci_dev *pdev)
14490 {
14491 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
14492 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14493 
14494 	/* Bring device online, it will be no-op for non-fatal error resume */
14495 	lpfc_online(phba);
14496 }
14497 
14498 /**
14499  * lpfc_sli4_get_els_iocb_cnt - Calculate the # of ELS IOCBs to reserve
14500  * @phba: pointer to lpfc hba data structure.
14501  *
14502  * returns the number of ELS/CT IOCBs to reserve
14503  **/
14504 int
14505 lpfc_sli4_get_els_iocb_cnt(struct lpfc_hba *phba)
14506 {
14507 	int max_xri = phba->sli4_hba.max_cfg_param.max_xri;
14508 
14509 	if (phba->sli_rev == LPFC_SLI_REV4) {
14510 		if (max_xri <= 100)
14511 			return 10;
14512 		else if (max_xri <= 256)
14513 			return 25;
14514 		else if (max_xri <= 512)
14515 			return 50;
14516 		else if (max_xri <= 1024)
14517 			return 100;
14518 		else if (max_xri <= 1536)
14519 			return 150;
14520 		else if (max_xri <= 2048)
14521 			return 200;
14522 		else
14523 			return 250;
14524 	} else
14525 		return 0;
14526 }
14527 
14528 /**
14529  * lpfc_sli4_get_iocb_cnt - Calculate the # of total IOCBs to reserve
14530  * @phba: pointer to lpfc hba data structure.
14531  *
14532  * returns the number of ELS/CT + NVMET IOCBs to reserve
14533  **/
14534 int
14535 lpfc_sli4_get_iocb_cnt(struct lpfc_hba *phba)
14536 {
14537 	int max_xri = lpfc_sli4_get_els_iocb_cnt(phba);
14538 
14539 	if (phba->nvmet_support)
14540 		max_xri += LPFC_NVMET_BUF_POST;
14541 	return max_xri;
14542 }
14543 
14544 
14545 static int
14546 lpfc_log_write_firmware_error(struct lpfc_hba *phba, uint32_t offset,
14547 	uint32_t magic_number, uint32_t ftype, uint32_t fid, uint32_t fsize,
14548 	const struct firmware *fw)
14549 {
14550 	int rc;
14551 	u8 sli_family;
14552 
14553 	sli_family = bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf);
14554 	/* Three cases:  (1) FW was not supported on the detected adapter.
14555 	 * (2) FW update has been locked out administratively.
14556 	 * (3) Some other error during FW update.
14557 	 * In each case, an unmaskable message is written to the console
14558 	 * for admin diagnosis.
14559 	 */
14560 	if (offset == ADD_STATUS_FW_NOT_SUPPORTED ||
14561 	    (sli_family == LPFC_SLI_INTF_FAMILY_G6 &&
14562 	     magic_number != MAGIC_NUMBER_G6) ||
14563 	    (sli_family == LPFC_SLI_INTF_FAMILY_G7 &&
14564 	     magic_number != MAGIC_NUMBER_G7) ||
14565 	    (sli_family == LPFC_SLI_INTF_FAMILY_G7P &&
14566 	     magic_number != MAGIC_NUMBER_G7P)) {
14567 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14568 				"3030 This firmware version is not supported on"
14569 				" this HBA model. Device:%x Magic:%x Type:%x "
14570 				"ID:%x Size %d %zd\n",
14571 				phba->pcidev->device, magic_number, ftype, fid,
14572 				fsize, fw->size);
14573 		rc = -EINVAL;
14574 	} else if (offset == ADD_STATUS_FW_DOWNLOAD_HW_DISABLED) {
14575 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14576 				"3021 Firmware downloads have been prohibited "
14577 				"by a system configuration setting on "
14578 				"Device:%x Magic:%x Type:%x ID:%x Size %d "
14579 				"%zd\n",
14580 				phba->pcidev->device, magic_number, ftype, fid,
14581 				fsize, fw->size);
14582 		rc = -EACCES;
14583 	} else {
14584 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14585 				"3022 FW Download failed. Add Status x%x "
14586 				"Device:%x Magic:%x Type:%x ID:%x Size %d "
14587 				"%zd\n",
14588 				offset, phba->pcidev->device, magic_number,
14589 				ftype, fid, fsize, fw->size);
14590 		rc = -EIO;
14591 	}
14592 	return rc;
14593 }
14594 
14595 /**
14596  * lpfc_write_firmware - attempt to write a firmware image to the port
14597  * @fw: pointer to firmware image returned from request_firmware.
14598  * @context: pointer to firmware image returned from request_firmware.
14599  *
14600  **/
14601 static void
14602 lpfc_write_firmware(const struct firmware *fw, void *context)
14603 {
14604 	struct lpfc_hba *phba = (struct lpfc_hba *)context;
14605 	char fwrev[FW_REV_STR_SIZE];
14606 	struct lpfc_grp_hdr *image;
14607 	struct list_head dma_buffer_list;
14608 	int i, rc = 0;
14609 	struct lpfc_dmabuf *dmabuf, *next;
14610 	uint32_t offset = 0, temp_offset = 0;
14611 	uint32_t magic_number, ftype, fid, fsize;
14612 
14613 	/* It can be null in no-wait mode, sanity check */
14614 	if (!fw) {
14615 		rc = -ENXIO;
14616 		goto out;
14617 	}
14618 	image = (struct lpfc_grp_hdr *)fw->data;
14619 
14620 	magic_number = be32_to_cpu(image->magic_number);
14621 	ftype = bf_get_be32(lpfc_grp_hdr_file_type, image);
14622 	fid = bf_get_be32(lpfc_grp_hdr_id, image);
14623 	fsize = be32_to_cpu(image->size);
14624 
14625 	INIT_LIST_HEAD(&dma_buffer_list);
14626 	lpfc_decode_firmware_rev(phba, fwrev, 1);
14627 	if (strncmp(fwrev, image->revision, strnlen(image->revision, 16))) {
14628 		lpfc_log_msg(phba, KERN_NOTICE, LOG_INIT | LOG_SLI,
14629 			     "3023 Updating Firmware, Current Version:%s "
14630 			     "New Version:%s\n",
14631 			     fwrev, image->revision);
14632 		for (i = 0; i < LPFC_MBX_WR_CONFIG_MAX_BDE; i++) {
14633 			dmabuf = kzalloc(sizeof(struct lpfc_dmabuf),
14634 					 GFP_KERNEL);
14635 			if (!dmabuf) {
14636 				rc = -ENOMEM;
14637 				goto release_out;
14638 			}
14639 			dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
14640 							  SLI4_PAGE_SIZE,
14641 							  &dmabuf->phys,
14642 							  GFP_KERNEL);
14643 			if (!dmabuf->virt) {
14644 				kfree(dmabuf);
14645 				rc = -ENOMEM;
14646 				goto release_out;
14647 			}
14648 			list_add_tail(&dmabuf->list, &dma_buffer_list);
14649 		}
14650 		while (offset < fw->size) {
14651 			temp_offset = offset;
14652 			list_for_each_entry(dmabuf, &dma_buffer_list, list) {
14653 				if (temp_offset + SLI4_PAGE_SIZE > fw->size) {
14654 					memcpy(dmabuf->virt,
14655 					       fw->data + temp_offset,
14656 					       fw->size - temp_offset);
14657 					temp_offset = fw->size;
14658 					break;
14659 				}
14660 				memcpy(dmabuf->virt, fw->data + temp_offset,
14661 				       SLI4_PAGE_SIZE);
14662 				temp_offset += SLI4_PAGE_SIZE;
14663 			}
14664 			rc = lpfc_wr_object(phba, &dma_buffer_list,
14665 				    (fw->size - offset), &offset);
14666 			if (rc) {
14667 				rc = lpfc_log_write_firmware_error(phba, offset,
14668 								   magic_number,
14669 								   ftype,
14670 								   fid,
14671 								   fsize,
14672 								   fw);
14673 				goto release_out;
14674 			}
14675 		}
14676 		rc = offset;
14677 	} else
14678 		lpfc_log_msg(phba, KERN_NOTICE, LOG_INIT | LOG_SLI,
14679 			     "3029 Skipped Firmware update, Current "
14680 			     "Version:%s New Version:%s\n",
14681 			     fwrev, image->revision);
14682 
14683 release_out:
14684 	list_for_each_entry_safe(dmabuf, next, &dma_buffer_list, list) {
14685 		list_del(&dmabuf->list);
14686 		dma_free_coherent(&phba->pcidev->dev, SLI4_PAGE_SIZE,
14687 				  dmabuf->virt, dmabuf->phys);
14688 		kfree(dmabuf);
14689 	}
14690 	release_firmware(fw);
14691 out:
14692 	if (rc < 0)
14693 		lpfc_log_msg(phba, KERN_ERR, LOG_INIT | LOG_SLI,
14694 			     "3062 Firmware update error, status %d.\n", rc);
14695 	else
14696 		lpfc_log_msg(phba, KERN_NOTICE, LOG_INIT | LOG_SLI,
14697 			     "3024 Firmware update success: size %d.\n", rc);
14698 }
14699 
14700 /**
14701  * lpfc_sli4_request_firmware_update - Request linux generic firmware upgrade
14702  * @phba: pointer to lpfc hba data structure.
14703  * @fw_upgrade: which firmware to update.
14704  *
14705  * This routine is called to perform Linux generic firmware upgrade on device
14706  * that supports such feature.
14707  **/
14708 int
14709 lpfc_sli4_request_firmware_update(struct lpfc_hba *phba, uint8_t fw_upgrade)
14710 {
14711 	char file_name[ELX_FW_NAME_SIZE] = {0};
14712 	int ret;
14713 	const struct firmware *fw;
14714 
14715 	/* Only supported on SLI4 interface type 2 for now */
14716 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) <
14717 	    LPFC_SLI_INTF_IF_TYPE_2)
14718 		return -EPERM;
14719 
14720 	scnprintf(file_name, sizeof(file_name), "%s.grp", phba->ModelName);
14721 
14722 	if (fw_upgrade == INT_FW_UPGRADE) {
14723 		ret = request_firmware_nowait(THIS_MODULE, FW_ACTION_UEVENT,
14724 					file_name, &phba->pcidev->dev,
14725 					GFP_KERNEL, (void *)phba,
14726 					lpfc_write_firmware);
14727 	} else if (fw_upgrade == RUN_FW_UPGRADE) {
14728 		ret = request_firmware(&fw, file_name, &phba->pcidev->dev);
14729 		if (!ret)
14730 			lpfc_write_firmware(fw, (void *)phba);
14731 	} else {
14732 		ret = -EINVAL;
14733 	}
14734 
14735 	return ret;
14736 }
14737 
14738 /**
14739  * lpfc_pci_probe_one_s4 - PCI probe func to reg SLI-4 device to PCI subsys
14740  * @pdev: pointer to PCI device
14741  * @pid: pointer to PCI device identifier
14742  *
14743  * This routine is called from the kernel's PCI subsystem to device with
14744  * SLI-4 interface spec. When an Emulex HBA with SLI-4 interface spec is
14745  * presented on PCI bus, the kernel PCI subsystem looks at PCI device-specific
14746  * information of the device and driver to see if the driver state that it
14747  * can support this kind of device. If the match is successful, the driver
14748  * core invokes this routine. If this routine determines it can claim the HBA,
14749  * it does all the initialization that it needs to do to handle the HBA
14750  * properly.
14751  *
14752  * Return code
14753  * 	0 - driver can claim the device
14754  * 	negative value - driver can not claim the device
14755  **/
14756 static int
14757 lpfc_pci_probe_one_s4(struct pci_dev *pdev, const struct pci_device_id *pid)
14758 {
14759 	struct lpfc_hba   *phba;
14760 	struct lpfc_vport *vport = NULL;
14761 	struct Scsi_Host  *shost = NULL;
14762 	int error;
14763 	uint32_t cfg_mode, intr_mode;
14764 
14765 	/* Allocate memory for HBA structure */
14766 	phba = lpfc_hba_alloc(pdev);
14767 	if (!phba)
14768 		return -ENOMEM;
14769 
14770 	INIT_LIST_HEAD(&phba->poll_list);
14771 
14772 	/* Perform generic PCI device enabling operation */
14773 	error = lpfc_enable_pci_dev(phba);
14774 	if (error)
14775 		goto out_free_phba;
14776 
14777 	/* Set up SLI API function jump table for PCI-device group-1 HBAs */
14778 	error = lpfc_api_table_setup(phba, LPFC_PCI_DEV_OC);
14779 	if (error)
14780 		goto out_disable_pci_dev;
14781 
14782 	/* Set up SLI-4 specific device PCI memory space */
14783 	error = lpfc_sli4_pci_mem_setup(phba);
14784 	if (error) {
14785 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14786 				"1410 Failed to set up pci memory space.\n");
14787 		goto out_disable_pci_dev;
14788 	}
14789 
14790 	/* Set up SLI-4 Specific device driver resources */
14791 	error = lpfc_sli4_driver_resource_setup(phba);
14792 	if (error) {
14793 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14794 				"1412 Failed to set up driver resource.\n");
14795 		goto out_unset_pci_mem_s4;
14796 	}
14797 
14798 	spin_lock_init(&phba->rrq_list_lock);
14799 	INIT_LIST_HEAD(&phba->active_rrq_list);
14800 	INIT_LIST_HEAD(&phba->fcf.fcf_pri_list);
14801 
14802 	/* Set up common device driver resources */
14803 	error = lpfc_setup_driver_resource_phase2(phba);
14804 	if (error) {
14805 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14806 				"1414 Failed to set up driver resource.\n");
14807 		goto out_unset_driver_resource_s4;
14808 	}
14809 
14810 	/* Get the default values for Model Name and Description */
14811 	lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
14812 
14813 	/* Now, trying to enable interrupt and bring up the device */
14814 	cfg_mode = phba->cfg_use_msi;
14815 
14816 	/* Put device to a known state before enabling interrupt */
14817 	phba->pport = NULL;
14818 	lpfc_stop_port(phba);
14819 
14820 	/* Init cpu_map array */
14821 	lpfc_cpu_map_array_init(phba);
14822 
14823 	/* Init hba_eq_hdl array */
14824 	lpfc_hba_eq_hdl_array_init(phba);
14825 
14826 	/* Configure and enable interrupt */
14827 	intr_mode = lpfc_sli4_enable_intr(phba, cfg_mode);
14828 	if (intr_mode == LPFC_INTR_ERROR) {
14829 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14830 				"0426 Failed to enable interrupt.\n");
14831 		error = -ENODEV;
14832 		goto out_unset_driver_resource;
14833 	}
14834 	/* Default to single EQ for non-MSI-X */
14835 	if (phba->intr_type != MSIX) {
14836 		phba->cfg_irq_chann = 1;
14837 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
14838 			if (phba->nvmet_support)
14839 				phba->cfg_nvmet_mrq = 1;
14840 		}
14841 	}
14842 	lpfc_cpu_affinity_check(phba, phba->cfg_irq_chann);
14843 
14844 	/* Create SCSI host to the physical port */
14845 	error = lpfc_create_shost(phba);
14846 	if (error) {
14847 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14848 				"1415 Failed to create scsi host.\n");
14849 		goto out_disable_intr;
14850 	}
14851 	vport = phba->pport;
14852 	shost = lpfc_shost_from_vport(vport); /* save shost for error cleanup */
14853 
14854 	/* Configure sysfs attributes */
14855 	error = lpfc_alloc_sysfs_attr(vport);
14856 	if (error) {
14857 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14858 				"1416 Failed to allocate sysfs attr\n");
14859 		goto out_destroy_shost;
14860 	}
14861 
14862 	/* Set up SLI-4 HBA */
14863 	if (lpfc_sli4_hba_setup(phba)) {
14864 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14865 				"1421 Failed to set up hba\n");
14866 		error = -ENODEV;
14867 		goto out_free_sysfs_attr;
14868 	}
14869 
14870 	/* Log the current active interrupt mode */
14871 	phba->intr_mode = intr_mode;
14872 	lpfc_log_intr_mode(phba, intr_mode);
14873 
14874 	/* Perform post initialization setup */
14875 	lpfc_post_init_setup(phba);
14876 
14877 	/* NVME support in FW earlier in the driver load corrects the
14878 	 * FC4 type making a check for nvme_support unnecessary.
14879 	 */
14880 	if (phba->nvmet_support == 0) {
14881 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
14882 			/* Create NVME binding with nvme_fc_transport. This
14883 			 * ensures the vport is initialized.  If the localport
14884 			 * create fails, it should not unload the driver to
14885 			 * support field issues.
14886 			 */
14887 			error = lpfc_nvme_create_localport(vport);
14888 			if (error) {
14889 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14890 						"6004 NVME registration "
14891 						"failed, error x%x\n",
14892 						error);
14893 			}
14894 		}
14895 	}
14896 
14897 	/* check for firmware upgrade or downgrade */
14898 	if (phba->cfg_request_firmware_upgrade)
14899 		lpfc_sli4_request_firmware_update(phba, INT_FW_UPGRADE);
14900 
14901 	/* Check if there are static vports to be created. */
14902 	lpfc_create_static_vport(phba);
14903 
14904 	timer_setup(&phba->cpuhp_poll_timer, lpfc_sli4_poll_hbtimer, 0);
14905 	cpuhp_state_add_instance_nocalls(lpfc_cpuhp_state, &phba->cpuhp);
14906 
14907 	return 0;
14908 
14909 out_free_sysfs_attr:
14910 	lpfc_free_sysfs_attr(vport);
14911 out_destroy_shost:
14912 	lpfc_destroy_shost(phba);
14913 out_disable_intr:
14914 	lpfc_sli4_disable_intr(phba);
14915 out_unset_driver_resource:
14916 	lpfc_unset_driver_resource_phase2(phba);
14917 out_unset_driver_resource_s4:
14918 	lpfc_sli4_driver_resource_unset(phba);
14919 out_unset_pci_mem_s4:
14920 	lpfc_sli4_pci_mem_unset(phba);
14921 out_disable_pci_dev:
14922 	lpfc_disable_pci_dev(phba);
14923 	if (shost)
14924 		scsi_host_put(shost);
14925 out_free_phba:
14926 	lpfc_hba_free(phba);
14927 	return error;
14928 }
14929 
14930 /**
14931  * lpfc_pci_remove_one_s4 - PCI func to unreg SLI-4 device from PCI subsystem
14932  * @pdev: pointer to PCI device
14933  *
14934  * This routine is called from the kernel's PCI subsystem to device with
14935  * SLI-4 interface spec. When an Emulex HBA with SLI-4 interface spec is
14936  * removed from PCI bus, it performs all the necessary cleanup for the HBA
14937  * device to be removed from the PCI subsystem properly.
14938  **/
14939 static void
14940 lpfc_pci_remove_one_s4(struct pci_dev *pdev)
14941 {
14942 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
14943 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
14944 	struct lpfc_vport **vports;
14945 	struct lpfc_hba *phba = vport->phba;
14946 	int i;
14947 
14948 	/* Mark the device unloading flag */
14949 	set_bit(FC_UNLOADING, &vport->load_flag);
14950 	if (phba->cgn_i)
14951 		lpfc_unreg_congestion_buf(phba);
14952 
14953 	lpfc_free_sysfs_attr(vport);
14954 
14955 	/* Release all the vports against this physical port */
14956 	vports = lpfc_create_vport_work_array(phba);
14957 	if (vports != NULL)
14958 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
14959 			if (vports[i]->port_type == LPFC_PHYSICAL_PORT)
14960 				continue;
14961 			fc_vport_terminate(vports[i]->fc_vport);
14962 		}
14963 	lpfc_destroy_vport_work_array(phba, vports);
14964 
14965 	/* Remove FC host with the physical port */
14966 	fc_remove_host(shost);
14967 	scsi_remove_host(shost);
14968 
14969 	/* Perform ndlp cleanup on the physical port.  The nvme and nvmet
14970 	 * localports are destroyed after to cleanup all transport memory.
14971 	 */
14972 	lpfc_cleanup(vport);
14973 	lpfc_nvmet_destroy_targetport(phba);
14974 	lpfc_nvme_destroy_localport(vport);
14975 
14976 	/* De-allocate multi-XRI pools */
14977 	if (phba->cfg_xri_rebalancing)
14978 		lpfc_destroy_multixri_pools(phba);
14979 
14980 	/*
14981 	 * Bring down the SLI Layer. This step disables all interrupts,
14982 	 * clears the rings, discards all mailbox commands, and resets
14983 	 * the HBA FCoE function.
14984 	 */
14985 	lpfc_debugfs_terminate(vport);
14986 
14987 	lpfc_stop_hba_timers(phba);
14988 	spin_lock_irq(&phba->port_list_lock);
14989 	list_del_init(&vport->listentry);
14990 	spin_unlock_irq(&phba->port_list_lock);
14991 
14992 	/* Perform scsi free before driver resource_unset since scsi
14993 	 * buffers are released to their corresponding pools here.
14994 	 */
14995 	lpfc_io_free(phba);
14996 	lpfc_free_iocb_list(phba);
14997 	lpfc_sli4_hba_unset(phba);
14998 
14999 	lpfc_unset_driver_resource_phase2(phba);
15000 	lpfc_sli4_driver_resource_unset(phba);
15001 
15002 	/* Unmap adapter Control and Doorbell registers */
15003 	lpfc_sli4_pci_mem_unset(phba);
15004 
15005 	/* Release PCI resources and disable device's PCI function */
15006 	scsi_host_put(shost);
15007 	lpfc_disable_pci_dev(phba);
15008 
15009 	/* Finally, free the driver's device data structure */
15010 	lpfc_hba_free(phba);
15011 
15012 	return;
15013 }
15014 
15015 /**
15016  * lpfc_pci_suspend_one_s4 - PCI func to suspend SLI-4 device for power mgmnt
15017  * @dev_d: pointer to device
15018  *
15019  * This routine is called from the kernel's PCI subsystem to support system
15020  * Power Management (PM) to device with SLI-4 interface spec. When PM invokes
15021  * this method, it quiesces the device by stopping the driver's worker
15022  * thread for the device, turning off device's interrupt and DMA, and bring
15023  * the device offline. Note that as the driver implements the minimum PM
15024  * requirements to a power-aware driver's PM support for suspend/resume -- all
15025  * the possible PM messages (SUSPEND, HIBERNATE, FREEZE) to the suspend()
15026  * method call will be treated as SUSPEND and the driver will fully
15027  * reinitialize its device during resume() method call, the driver will set
15028  * device to PCI_D3hot state in PCI config space instead of setting it
15029  * according to the @msg provided by the PM.
15030  *
15031  * Return code
15032  * 	0 - driver suspended the device
15033  * 	Error otherwise
15034  **/
15035 static int __maybe_unused
15036 lpfc_pci_suspend_one_s4(struct device *dev_d)
15037 {
15038 	struct Scsi_Host *shost = dev_get_drvdata(dev_d);
15039 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15040 
15041 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
15042 			"2843 PCI device Power Management suspend.\n");
15043 
15044 	/* Bring down the device */
15045 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
15046 	lpfc_offline(phba);
15047 	kthread_stop(phba->worker_thread);
15048 
15049 	/* Disable interrupt from device */
15050 	lpfc_sli4_disable_intr(phba);
15051 	lpfc_sli4_queue_destroy(phba);
15052 
15053 	return 0;
15054 }
15055 
15056 /**
15057  * lpfc_pci_resume_one_s4 - PCI func to resume SLI-4 device for power mgmnt
15058  * @dev_d: pointer to device
15059  *
15060  * This routine is called from the kernel's PCI subsystem to support system
15061  * Power Management (PM) to device with SLI-4 interface spac. When PM invokes
15062  * this method, it restores the device's PCI config space state and fully
15063  * reinitializes the device and brings it online. Note that as the driver
15064  * implements the minimum PM requirements to a power-aware driver's PM for
15065  * suspend/resume -- all the possible PM messages (SUSPEND, HIBERNATE, FREEZE)
15066  * to the suspend() method call will be treated as SUSPEND and the driver
15067  * will fully reinitialize its device during resume() method call, the device
15068  * will be set to PCI_D0 directly in PCI config space before restoring the
15069  * state.
15070  *
15071  * Return code
15072  * 	0 - driver suspended the device
15073  * 	Error otherwise
15074  **/
15075 static int __maybe_unused
15076 lpfc_pci_resume_one_s4(struct device *dev_d)
15077 {
15078 	struct Scsi_Host *shost = dev_get_drvdata(dev_d);
15079 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15080 	uint32_t intr_mode;
15081 	int error;
15082 
15083 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
15084 			"0292 PCI device Power Management resume.\n");
15085 
15086 	 /* Startup the kernel thread for this host adapter. */
15087 	phba->worker_thread = kthread_run(lpfc_do_work, phba,
15088 					"lpfc_worker_%d", phba->brd_no);
15089 	if (IS_ERR(phba->worker_thread)) {
15090 		error = PTR_ERR(phba->worker_thread);
15091 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15092 				"0293 PM resume failed to start worker "
15093 				"thread: error=x%x.\n", error);
15094 		return error;
15095 	}
15096 
15097 	/* Configure and enable interrupt */
15098 	intr_mode = lpfc_sli4_enable_intr(phba, phba->intr_mode);
15099 	if (intr_mode == LPFC_INTR_ERROR) {
15100 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15101 				"0294 PM resume Failed to enable interrupt\n");
15102 		return -EIO;
15103 	} else
15104 		phba->intr_mode = intr_mode;
15105 
15106 	/* Restart HBA and bring it online */
15107 	lpfc_sli_brdrestart(phba);
15108 	lpfc_online(phba);
15109 
15110 	/* Log the current active interrupt mode */
15111 	lpfc_log_intr_mode(phba, phba->intr_mode);
15112 
15113 	return 0;
15114 }
15115 
15116 /**
15117  * lpfc_sli4_prep_dev_for_recover - Prepare SLI4 device for pci slot recover
15118  * @phba: pointer to lpfc hba data structure.
15119  *
15120  * This routine is called to prepare the SLI4 device for PCI slot recover. It
15121  * aborts all the outstanding SCSI I/Os to the pci device.
15122  **/
15123 static void
15124 lpfc_sli4_prep_dev_for_recover(struct lpfc_hba *phba)
15125 {
15126 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15127 			"2828 PCI channel I/O abort preparing for recovery\n");
15128 	/*
15129 	 * There may be errored I/Os through HBA, abort all I/Os on txcmplq
15130 	 * and let the SCSI mid-layer to retry them to recover.
15131 	 */
15132 	lpfc_sli_abort_fcp_rings(phba);
15133 }
15134 
15135 /**
15136  * lpfc_sli4_prep_dev_for_reset - Prepare SLI4 device for pci slot reset
15137  * @phba: pointer to lpfc hba data structure.
15138  *
15139  * This routine is called to prepare the SLI4 device for PCI slot reset. It
15140  * disables the device interrupt and pci device, and aborts the internal FCP
15141  * pending I/Os.
15142  **/
15143 static void
15144 lpfc_sli4_prep_dev_for_reset(struct lpfc_hba *phba)
15145 {
15146 	int offline =  pci_channel_offline(phba->pcidev);
15147 
15148 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15149 			"2826 PCI channel disable preparing for reset offline"
15150 			" %d\n", offline);
15151 
15152 	/* Block any management I/Os to the device */
15153 	lpfc_block_mgmt_io(phba, LPFC_MBX_NO_WAIT);
15154 
15155 
15156 	/* HBA_PCI_ERR was set in io_error_detect */
15157 	lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
15158 	/* Flush all driver's outstanding I/Os as we are to reset */
15159 	lpfc_sli_flush_io_rings(phba);
15160 	lpfc_offline(phba);
15161 
15162 	/* stop all timers */
15163 	lpfc_stop_hba_timers(phba);
15164 
15165 	lpfc_sli4_queue_destroy(phba);
15166 	/* Disable interrupt and pci device */
15167 	lpfc_sli4_disable_intr(phba);
15168 	pci_disable_device(phba->pcidev);
15169 }
15170 
15171 /**
15172  * lpfc_sli4_prep_dev_for_perm_failure - Prepare SLI4 dev for pci slot disable
15173  * @phba: pointer to lpfc hba data structure.
15174  *
15175  * This routine is called to prepare the SLI4 device for PCI slot permanently
15176  * disabling. It blocks the SCSI transport layer traffic and flushes the FCP
15177  * pending I/Os.
15178  **/
15179 static void
15180 lpfc_sli4_prep_dev_for_perm_failure(struct lpfc_hba *phba)
15181 {
15182 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15183 			"2827 PCI channel permanent disable for failure\n");
15184 
15185 	/* Block all SCSI devices' I/Os on the host */
15186 	lpfc_scsi_dev_block(phba);
15187 
15188 	/* stop all timers */
15189 	lpfc_stop_hba_timers(phba);
15190 
15191 	/* Clean up all driver's outstanding I/Os */
15192 	lpfc_sli_flush_io_rings(phba);
15193 }
15194 
15195 /**
15196  * lpfc_io_error_detected_s4 - Method for handling PCI I/O error to SLI-4 device
15197  * @pdev: pointer to PCI device.
15198  * @state: the current PCI connection state.
15199  *
15200  * This routine is called from the PCI subsystem for error handling to device
15201  * with SLI-4 interface spec. This function is called by the PCI subsystem
15202  * after a PCI bus error affecting this device has been detected. When this
15203  * function is invoked, it will need to stop all the I/Os and interrupt(s)
15204  * to the device. Once that is done, it will return PCI_ERS_RESULT_NEED_RESET
15205  * for the PCI subsystem to perform proper recovery as desired.
15206  *
15207  * Return codes
15208  * 	PCI_ERS_RESULT_NEED_RESET - need to reset before recovery
15209  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15210  **/
15211 static pci_ers_result_t
15212 lpfc_io_error_detected_s4(struct pci_dev *pdev, pci_channel_state_t state)
15213 {
15214 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15215 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15216 	bool hba_pci_err;
15217 
15218 	switch (state) {
15219 	case pci_channel_io_normal:
15220 		/* Non-fatal error, prepare for recovery */
15221 		lpfc_sli4_prep_dev_for_recover(phba);
15222 		return PCI_ERS_RESULT_CAN_RECOVER;
15223 	case pci_channel_io_frozen:
15224 		hba_pci_err = test_and_set_bit(HBA_PCI_ERR, &phba->bit_flags);
15225 		/* Fatal error, prepare for slot reset */
15226 		if (!hba_pci_err)
15227 			lpfc_sli4_prep_dev_for_reset(phba);
15228 		else
15229 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15230 					"2832  Already handling PCI error "
15231 					"state: x%x\n", state);
15232 		return PCI_ERS_RESULT_NEED_RESET;
15233 	case pci_channel_io_perm_failure:
15234 		set_bit(HBA_PCI_ERR, &phba->bit_flags);
15235 		/* Permanent failure, prepare for device down */
15236 		lpfc_sli4_prep_dev_for_perm_failure(phba);
15237 		return PCI_ERS_RESULT_DISCONNECT;
15238 	default:
15239 		hba_pci_err = test_and_set_bit(HBA_PCI_ERR, &phba->bit_flags);
15240 		if (!hba_pci_err)
15241 			lpfc_sli4_prep_dev_for_reset(phba);
15242 		/* Unknown state, prepare and request slot reset */
15243 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15244 				"2825 Unknown PCI error state: x%x\n", state);
15245 		lpfc_sli4_prep_dev_for_reset(phba);
15246 		return PCI_ERS_RESULT_NEED_RESET;
15247 	}
15248 }
15249 
15250 /**
15251  * lpfc_io_slot_reset_s4 - Method for restart PCI SLI-4 device from scratch
15252  * @pdev: pointer to PCI device.
15253  *
15254  * This routine is called from the PCI subsystem for error handling to device
15255  * with SLI-4 interface spec. It is called after PCI bus has been reset to
15256  * restart the PCI card from scratch, as if from a cold-boot. During the
15257  * PCI subsystem error recovery, after the driver returns
15258  * PCI_ERS_RESULT_NEED_RESET, the PCI subsystem will perform proper error
15259  * recovery and then call this routine before calling the .resume method to
15260  * recover the device. This function will initialize the HBA device, enable
15261  * the interrupt, but it will just put the HBA to offline state without
15262  * passing any I/O traffic.
15263  *
15264  * Return codes
15265  * 	PCI_ERS_RESULT_RECOVERED - the device has been recovered
15266  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15267  */
15268 static pci_ers_result_t
15269 lpfc_io_slot_reset_s4(struct pci_dev *pdev)
15270 {
15271 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15272 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15273 	struct lpfc_sli *psli = &phba->sli;
15274 	uint32_t intr_mode;
15275 	bool hba_pci_err;
15276 
15277 	dev_printk(KERN_INFO, &pdev->dev, "recovering from a slot reset.\n");
15278 	if (pci_enable_device_mem(pdev)) {
15279 		printk(KERN_ERR "lpfc: Cannot re-enable "
15280 		       "PCI device after reset.\n");
15281 		return PCI_ERS_RESULT_DISCONNECT;
15282 	}
15283 
15284 	pci_restore_state(pdev);
15285 
15286 	hba_pci_err = test_and_clear_bit(HBA_PCI_ERR, &phba->bit_flags);
15287 	if (!hba_pci_err)
15288 		dev_info(&pdev->dev,
15289 			 "hba_pci_err was not set, recovering slot reset.\n");
15290 	/*
15291 	 * As the new kernel behavior of pci_restore_state() API call clears
15292 	 * device saved_state flag, need to save the restored state again.
15293 	 */
15294 	pci_save_state(pdev);
15295 
15296 	if (pdev->is_busmaster)
15297 		pci_set_master(pdev);
15298 
15299 	spin_lock_irq(&phba->hbalock);
15300 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
15301 	spin_unlock_irq(&phba->hbalock);
15302 
15303 	/* Init cpu_map array */
15304 	lpfc_cpu_map_array_init(phba);
15305 	/* Configure and enable interrupt */
15306 	intr_mode = lpfc_sli4_enable_intr(phba, phba->intr_mode);
15307 	if (intr_mode == LPFC_INTR_ERROR) {
15308 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15309 				"2824 Cannot re-enable interrupt after "
15310 				"slot reset.\n");
15311 		return PCI_ERS_RESULT_DISCONNECT;
15312 	} else
15313 		phba->intr_mode = intr_mode;
15314 	lpfc_cpu_affinity_check(phba, phba->cfg_irq_chann);
15315 
15316 	/* Log the current active interrupt mode */
15317 	lpfc_log_intr_mode(phba, phba->intr_mode);
15318 
15319 	return PCI_ERS_RESULT_RECOVERED;
15320 }
15321 
15322 /**
15323  * lpfc_io_resume_s4 - Method for resuming PCI I/O operation to SLI-4 device
15324  * @pdev: pointer to PCI device
15325  *
15326  * This routine is called from the PCI subsystem for error handling to device
15327  * with SLI-4 interface spec. It is called when kernel error recovery tells
15328  * the lpfc driver that it is ok to resume normal PCI operation after PCI bus
15329  * error recovery. After this call, traffic can start to flow from this device
15330  * again.
15331  **/
15332 static void
15333 lpfc_io_resume_s4(struct pci_dev *pdev)
15334 {
15335 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15336 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15337 
15338 	/*
15339 	 * In case of slot reset, as function reset is performed through
15340 	 * mailbox command which needs DMA to be enabled, this operation
15341 	 * has to be moved to the io resume phase. Taking device offline
15342 	 * will perform the necessary cleanup.
15343 	 */
15344 	if (!(phba->sli.sli_flag & LPFC_SLI_ACTIVE)) {
15345 		/* Perform device reset */
15346 		lpfc_sli_brdrestart(phba);
15347 		/* Bring the device back online */
15348 		lpfc_online(phba);
15349 	}
15350 }
15351 
15352 /**
15353  * lpfc_pci_probe_one - lpfc PCI probe func to reg dev to PCI subsystem
15354  * @pdev: pointer to PCI device
15355  * @pid: pointer to PCI device identifier
15356  *
15357  * This routine is to be registered to the kernel's PCI subsystem. When an
15358  * Emulex HBA device is presented on PCI bus, the kernel PCI subsystem looks
15359  * at PCI device-specific information of the device and driver to see if the
15360  * driver state that it can support this kind of device. If the match is
15361  * successful, the driver core invokes this routine. This routine dispatches
15362  * the action to the proper SLI-3 or SLI-4 device probing routine, which will
15363  * do all the initialization that it needs to do to handle the HBA device
15364  * properly.
15365  *
15366  * Return code
15367  * 	0 - driver can claim the device
15368  * 	negative value - driver can not claim the device
15369  **/
15370 static int
15371 lpfc_pci_probe_one(struct pci_dev *pdev, const struct pci_device_id *pid)
15372 {
15373 	int rc;
15374 	struct lpfc_sli_intf intf;
15375 
15376 	if (pci_read_config_dword(pdev, LPFC_SLI_INTF, &intf.word0))
15377 		return -ENODEV;
15378 
15379 	if ((bf_get(lpfc_sli_intf_valid, &intf) == LPFC_SLI_INTF_VALID) &&
15380 	    (bf_get(lpfc_sli_intf_slirev, &intf) == LPFC_SLI_INTF_REV_SLI4))
15381 		rc = lpfc_pci_probe_one_s4(pdev, pid);
15382 	else
15383 		rc = lpfc_pci_probe_one_s3(pdev, pid);
15384 
15385 	return rc;
15386 }
15387 
15388 /**
15389  * lpfc_pci_remove_one - lpfc PCI func to unreg dev from PCI subsystem
15390  * @pdev: pointer to PCI device
15391  *
15392  * This routine is to be registered to the kernel's PCI subsystem. When an
15393  * Emulex HBA is removed from PCI bus, the driver core invokes this routine.
15394  * This routine dispatches the action to the proper SLI-3 or SLI-4 device
15395  * remove routine, which will perform all the necessary cleanup for the
15396  * device to be removed from the PCI subsystem properly.
15397  **/
15398 static void
15399 lpfc_pci_remove_one(struct pci_dev *pdev)
15400 {
15401 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15402 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15403 
15404 	switch (phba->pci_dev_grp) {
15405 	case LPFC_PCI_DEV_LP:
15406 		lpfc_pci_remove_one_s3(pdev);
15407 		break;
15408 	case LPFC_PCI_DEV_OC:
15409 		lpfc_pci_remove_one_s4(pdev);
15410 		break;
15411 	default:
15412 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15413 				"1424 Invalid PCI device group: 0x%x\n",
15414 				phba->pci_dev_grp);
15415 		break;
15416 	}
15417 	return;
15418 }
15419 
15420 /**
15421  * lpfc_pci_suspend_one - lpfc PCI func to suspend dev for power management
15422  * @dev: pointer to device
15423  *
15424  * This routine is to be registered to the kernel's PCI subsystem to support
15425  * system Power Management (PM). When PM invokes this method, it dispatches
15426  * the action to the proper SLI-3 or SLI-4 device suspend routine, which will
15427  * suspend the device.
15428  *
15429  * Return code
15430  * 	0 - driver suspended the device
15431  * 	Error otherwise
15432  **/
15433 static int __maybe_unused
15434 lpfc_pci_suspend_one(struct device *dev)
15435 {
15436 	struct Scsi_Host *shost = dev_get_drvdata(dev);
15437 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15438 	int rc = -ENODEV;
15439 
15440 	switch (phba->pci_dev_grp) {
15441 	case LPFC_PCI_DEV_LP:
15442 		rc = lpfc_pci_suspend_one_s3(dev);
15443 		break;
15444 	case LPFC_PCI_DEV_OC:
15445 		rc = lpfc_pci_suspend_one_s4(dev);
15446 		break;
15447 	default:
15448 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15449 				"1425 Invalid PCI device group: 0x%x\n",
15450 				phba->pci_dev_grp);
15451 		break;
15452 	}
15453 	return rc;
15454 }
15455 
15456 /**
15457  * lpfc_pci_resume_one - lpfc PCI func to resume dev for power management
15458  * @dev: pointer to device
15459  *
15460  * This routine is to be registered to the kernel's PCI subsystem to support
15461  * system Power Management (PM). When PM invokes this method, it dispatches
15462  * the action to the proper SLI-3 or SLI-4 device resume routine, which will
15463  * resume the device.
15464  *
15465  * Return code
15466  * 	0 - driver suspended the device
15467  * 	Error otherwise
15468  **/
15469 static int __maybe_unused
15470 lpfc_pci_resume_one(struct device *dev)
15471 {
15472 	struct Scsi_Host *shost = dev_get_drvdata(dev);
15473 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15474 	int rc = -ENODEV;
15475 
15476 	switch (phba->pci_dev_grp) {
15477 	case LPFC_PCI_DEV_LP:
15478 		rc = lpfc_pci_resume_one_s3(dev);
15479 		break;
15480 	case LPFC_PCI_DEV_OC:
15481 		rc = lpfc_pci_resume_one_s4(dev);
15482 		break;
15483 	default:
15484 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15485 				"1426 Invalid PCI device group: 0x%x\n",
15486 				phba->pci_dev_grp);
15487 		break;
15488 	}
15489 	return rc;
15490 }
15491 
15492 /**
15493  * lpfc_io_error_detected - lpfc method for handling PCI I/O error
15494  * @pdev: pointer to PCI device.
15495  * @state: the current PCI connection state.
15496  *
15497  * This routine is registered to the PCI subsystem for error handling. This
15498  * function is called by the PCI subsystem after a PCI bus error affecting
15499  * this device has been detected. When this routine is invoked, it dispatches
15500  * the action to the proper SLI-3 or SLI-4 device error detected handling
15501  * routine, which will perform the proper error detected operation.
15502  *
15503  * Return codes
15504  * 	PCI_ERS_RESULT_NEED_RESET - need to reset before recovery
15505  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15506  **/
15507 static pci_ers_result_t
15508 lpfc_io_error_detected(struct pci_dev *pdev, pci_channel_state_t state)
15509 {
15510 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15511 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15512 	pci_ers_result_t rc = PCI_ERS_RESULT_DISCONNECT;
15513 
15514 	if (phba->link_state == LPFC_HBA_ERROR &&
15515 	    test_bit(HBA_IOQ_FLUSH, &phba->hba_flag))
15516 		return PCI_ERS_RESULT_NEED_RESET;
15517 
15518 	switch (phba->pci_dev_grp) {
15519 	case LPFC_PCI_DEV_LP:
15520 		rc = lpfc_io_error_detected_s3(pdev, state);
15521 		break;
15522 	case LPFC_PCI_DEV_OC:
15523 		rc = lpfc_io_error_detected_s4(pdev, state);
15524 		break;
15525 	default:
15526 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15527 				"1427 Invalid PCI device group: 0x%x\n",
15528 				phba->pci_dev_grp);
15529 		break;
15530 	}
15531 	return rc;
15532 }
15533 
15534 /**
15535  * lpfc_io_slot_reset - lpfc method for restart PCI dev from scratch
15536  * @pdev: pointer to PCI device.
15537  *
15538  * This routine is registered to the PCI subsystem for error handling. This
15539  * function is called after PCI bus has been reset to restart the PCI card
15540  * from scratch, as if from a cold-boot. When this routine is invoked, it
15541  * dispatches the action to the proper SLI-3 or SLI-4 device reset handling
15542  * routine, which will perform the proper device reset.
15543  *
15544  * Return codes
15545  * 	PCI_ERS_RESULT_RECOVERED - the device has been recovered
15546  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15547  **/
15548 static pci_ers_result_t
15549 lpfc_io_slot_reset(struct pci_dev *pdev)
15550 {
15551 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15552 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15553 	pci_ers_result_t rc = PCI_ERS_RESULT_DISCONNECT;
15554 
15555 	switch (phba->pci_dev_grp) {
15556 	case LPFC_PCI_DEV_LP:
15557 		rc = lpfc_io_slot_reset_s3(pdev);
15558 		break;
15559 	case LPFC_PCI_DEV_OC:
15560 		rc = lpfc_io_slot_reset_s4(pdev);
15561 		break;
15562 	default:
15563 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15564 				"1428 Invalid PCI device group: 0x%x\n",
15565 				phba->pci_dev_grp);
15566 		break;
15567 	}
15568 	return rc;
15569 }
15570 
15571 /**
15572  * lpfc_io_resume - lpfc method for resuming PCI I/O operation
15573  * @pdev: pointer to PCI device
15574  *
15575  * This routine is registered to the PCI subsystem for error handling. It
15576  * is called when kernel error recovery tells the lpfc driver that it is
15577  * OK to resume normal PCI operation after PCI bus error recovery. When
15578  * this routine is invoked, it dispatches the action to the proper SLI-3
15579  * or SLI-4 device io_resume routine, which will resume the device operation.
15580  **/
15581 static void
15582 lpfc_io_resume(struct pci_dev *pdev)
15583 {
15584 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15585 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15586 
15587 	switch (phba->pci_dev_grp) {
15588 	case LPFC_PCI_DEV_LP:
15589 		lpfc_io_resume_s3(pdev);
15590 		break;
15591 	case LPFC_PCI_DEV_OC:
15592 		lpfc_io_resume_s4(pdev);
15593 		break;
15594 	default:
15595 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15596 				"1429 Invalid PCI device group: 0x%x\n",
15597 				phba->pci_dev_grp);
15598 		break;
15599 	}
15600 	return;
15601 }
15602 
15603 /**
15604  * lpfc_sli4_oas_verify - Verify OAS is supported by this adapter
15605  * @phba: pointer to lpfc hba data structure.
15606  *
15607  * This routine checks to see if OAS is supported for this adapter. If
15608  * supported, the configure Flash Optimized Fabric flag is set.  Otherwise,
15609  * the enable oas flag is cleared and the pool created for OAS device data
15610  * is destroyed.
15611  *
15612  **/
15613 static void
15614 lpfc_sli4_oas_verify(struct lpfc_hba *phba)
15615 {
15616 
15617 	if (!phba->cfg_EnableXLane)
15618 		return;
15619 
15620 	if (phba->sli4_hba.pc_sli4_params.oas_supported) {
15621 		phba->cfg_fof = 1;
15622 	} else {
15623 		phba->cfg_fof = 0;
15624 		mempool_destroy(phba->device_data_mem_pool);
15625 		phba->device_data_mem_pool = NULL;
15626 	}
15627 
15628 	return;
15629 }
15630 
15631 /**
15632  * lpfc_sli4_ras_init - Verify RAS-FW log is supported by this adapter
15633  * @phba: pointer to lpfc hba data structure.
15634  *
15635  * This routine checks to see if RAS is supported by the adapter. Check the
15636  * function through which RAS support enablement is to be done.
15637  **/
15638 void
15639 lpfc_sli4_ras_init(struct lpfc_hba *phba)
15640 {
15641 	/* if ASIC_GEN_NUM >= 0xC) */
15642 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
15643 		    LPFC_SLI_INTF_IF_TYPE_6) ||
15644 	    (bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf) ==
15645 		    LPFC_SLI_INTF_FAMILY_G6)) {
15646 		phba->ras_fwlog.ras_hwsupport = true;
15647 		if (phba->cfg_ras_fwlog_func == PCI_FUNC(phba->pcidev->devfn) &&
15648 		    phba->cfg_ras_fwlog_buffsize)
15649 			phba->ras_fwlog.ras_enabled = true;
15650 		else
15651 			phba->ras_fwlog.ras_enabled = false;
15652 	} else {
15653 		phba->ras_fwlog.ras_hwsupport = false;
15654 	}
15655 }
15656 
15657 
15658 MODULE_DEVICE_TABLE(pci, lpfc_id_table);
15659 
15660 static const struct pci_error_handlers lpfc_err_handler = {
15661 	.error_detected = lpfc_io_error_detected,
15662 	.slot_reset = lpfc_io_slot_reset,
15663 	.resume = lpfc_io_resume,
15664 };
15665 
15666 static SIMPLE_DEV_PM_OPS(lpfc_pci_pm_ops_one,
15667 			 lpfc_pci_suspend_one,
15668 			 lpfc_pci_resume_one);
15669 
15670 static struct pci_driver lpfc_driver = {
15671 	.name		= LPFC_DRIVER_NAME,
15672 	.id_table	= lpfc_id_table,
15673 	.probe		= lpfc_pci_probe_one,
15674 	.remove		= lpfc_pci_remove_one,
15675 	.shutdown	= lpfc_pci_remove_one,
15676 	.driver.pm	= &lpfc_pci_pm_ops_one,
15677 	.err_handler    = &lpfc_err_handler,
15678 };
15679 
15680 static const struct file_operations lpfc_mgmt_fop = {
15681 	.owner = THIS_MODULE,
15682 };
15683 
15684 static struct miscdevice lpfc_mgmt_dev = {
15685 	.minor = MISC_DYNAMIC_MINOR,
15686 	.name = "lpfcmgmt",
15687 	.fops = &lpfc_mgmt_fop,
15688 };
15689 
15690 /**
15691  * lpfc_init - lpfc module initialization routine
15692  *
15693  * This routine is to be invoked when the lpfc module is loaded into the
15694  * kernel. The special kernel macro module_init() is used to indicate the
15695  * role of this routine to the kernel as lpfc module entry point.
15696  *
15697  * Return codes
15698  *   0 - successful
15699  *   -ENOMEM - FC attach transport failed
15700  *   all others - failed
15701  */
15702 static int __init
15703 lpfc_init(void)
15704 {
15705 	int error = 0;
15706 
15707 	pr_info(LPFC_MODULE_DESC "\n");
15708 	pr_info(LPFC_COPYRIGHT "\n");
15709 
15710 	error = misc_register(&lpfc_mgmt_dev);
15711 	if (error)
15712 		printk(KERN_ERR "Could not register lpfcmgmt device, "
15713 			"misc_register returned with status %d", error);
15714 
15715 	error = -ENOMEM;
15716 	lpfc_transport_functions.vport_create = lpfc_vport_create;
15717 	lpfc_transport_functions.vport_delete = lpfc_vport_delete;
15718 	lpfc_transport_template =
15719 				fc_attach_transport(&lpfc_transport_functions);
15720 	if (lpfc_transport_template == NULL)
15721 		goto unregister;
15722 	lpfc_vport_transport_template =
15723 		fc_attach_transport(&lpfc_vport_transport_functions);
15724 	if (lpfc_vport_transport_template == NULL) {
15725 		fc_release_transport(lpfc_transport_template);
15726 		goto unregister;
15727 	}
15728 	lpfc_wqe_cmd_template();
15729 	lpfc_nvmet_cmd_template();
15730 
15731 	/* Initialize in case vector mapping is needed */
15732 	lpfc_present_cpu = num_present_cpus();
15733 
15734 	lpfc_pldv_detect = false;
15735 
15736 	error = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN,
15737 					"lpfc/sli4:online",
15738 					lpfc_cpu_online, lpfc_cpu_offline);
15739 	if (error < 0)
15740 		goto cpuhp_failure;
15741 	lpfc_cpuhp_state = error;
15742 
15743 	error = pci_register_driver(&lpfc_driver);
15744 	if (error)
15745 		goto unwind;
15746 
15747 	return error;
15748 
15749 unwind:
15750 	cpuhp_remove_multi_state(lpfc_cpuhp_state);
15751 cpuhp_failure:
15752 	fc_release_transport(lpfc_transport_template);
15753 	fc_release_transport(lpfc_vport_transport_template);
15754 unregister:
15755 	misc_deregister(&lpfc_mgmt_dev);
15756 
15757 	return error;
15758 }
15759 
15760 void lpfc_dmp_dbg(struct lpfc_hba *phba)
15761 {
15762 	unsigned int start_idx;
15763 	unsigned int dbg_cnt;
15764 	unsigned int temp_idx;
15765 	int i;
15766 	int j = 0;
15767 	unsigned long rem_nsec;
15768 
15769 	if (atomic_cmpxchg(&phba->dbg_log_dmping, 0, 1) != 0)
15770 		return;
15771 
15772 	start_idx = (unsigned int)atomic_read(&phba->dbg_log_idx) % DBG_LOG_SZ;
15773 	dbg_cnt = (unsigned int)atomic_read(&phba->dbg_log_cnt);
15774 	if (!dbg_cnt)
15775 		goto out;
15776 	temp_idx = start_idx;
15777 	if (dbg_cnt >= DBG_LOG_SZ) {
15778 		dbg_cnt = DBG_LOG_SZ;
15779 		temp_idx -= 1;
15780 	} else {
15781 		if ((start_idx + dbg_cnt) > (DBG_LOG_SZ - 1)) {
15782 			temp_idx = (start_idx + dbg_cnt) % DBG_LOG_SZ;
15783 		} else {
15784 			if (start_idx < dbg_cnt)
15785 				start_idx = DBG_LOG_SZ - (dbg_cnt - start_idx);
15786 			else
15787 				start_idx -= dbg_cnt;
15788 		}
15789 	}
15790 	dev_info(&phba->pcidev->dev, "start %d end %d cnt %d\n",
15791 		 start_idx, temp_idx, dbg_cnt);
15792 
15793 	for (i = 0; i < dbg_cnt; i++) {
15794 		if ((start_idx + i) < DBG_LOG_SZ)
15795 			temp_idx = (start_idx + i) % DBG_LOG_SZ;
15796 		else
15797 			temp_idx = j++;
15798 		rem_nsec = do_div(phba->dbg_log[temp_idx].t_ns, NSEC_PER_SEC);
15799 		dev_info(&phba->pcidev->dev, "%d: [%5lu.%06lu] %s",
15800 			 temp_idx,
15801 			 (unsigned long)phba->dbg_log[temp_idx].t_ns,
15802 			 rem_nsec / 1000,
15803 			 phba->dbg_log[temp_idx].log);
15804 	}
15805 out:
15806 	atomic_set(&phba->dbg_log_cnt, 0);
15807 	atomic_set(&phba->dbg_log_dmping, 0);
15808 }
15809 
15810 __printf(2, 3)
15811 void lpfc_dbg_print(struct lpfc_hba *phba, const char *fmt, ...)
15812 {
15813 	unsigned int idx;
15814 	va_list args;
15815 	int dbg_dmping = atomic_read(&phba->dbg_log_dmping);
15816 	struct va_format vaf;
15817 
15818 
15819 	va_start(args, fmt);
15820 	if (unlikely(dbg_dmping)) {
15821 		vaf.fmt = fmt;
15822 		vaf.va = &args;
15823 		dev_info(&phba->pcidev->dev, "%pV", &vaf);
15824 		va_end(args);
15825 		return;
15826 	}
15827 	idx = (unsigned int)atomic_fetch_add(1, &phba->dbg_log_idx) %
15828 		DBG_LOG_SZ;
15829 
15830 	atomic_inc(&phba->dbg_log_cnt);
15831 
15832 	vscnprintf(phba->dbg_log[idx].log,
15833 		   sizeof(phba->dbg_log[idx].log), fmt, args);
15834 	va_end(args);
15835 
15836 	phba->dbg_log[idx].t_ns = local_clock();
15837 }
15838 
15839 /**
15840  * lpfc_exit - lpfc module removal routine
15841  *
15842  * This routine is invoked when the lpfc module is removed from the kernel.
15843  * The special kernel macro module_exit() is used to indicate the role of
15844  * this routine to the kernel as lpfc module exit point.
15845  */
15846 static void __exit
15847 lpfc_exit(void)
15848 {
15849 	misc_deregister(&lpfc_mgmt_dev);
15850 	pci_unregister_driver(&lpfc_driver);
15851 	cpuhp_remove_multi_state(lpfc_cpuhp_state);
15852 	fc_release_transport(lpfc_transport_template);
15853 	fc_release_transport(lpfc_vport_transport_template);
15854 	idr_destroy(&lpfc_hba_index);
15855 }
15856 
15857 module_init(lpfc_init);
15858 module_exit(lpfc_exit);
15859 MODULE_LICENSE("GPL");
15860 MODULE_DESCRIPTION(LPFC_MODULE_DESC);
15861 MODULE_AUTHOR("Broadcom");
15862 MODULE_VERSION("0:" LPFC_DRIVER_VERSION);
15863