xref: /openbmc/linux/drivers/scsi/lpfc/lpfc_init.c (revision 2fa5ebe3)
1 /*******************************************************************
2  * This file is part of the Emulex Linux Device Driver for         *
3  * Fibre Channel Host Bus Adapters.                                *
4  * Copyright (C) 2017-2023 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/aer.h>
36 #include <linux/slab.h>
37 #include <linux/firmware.h>
38 #include <linux/miscdevice.h>
39 #include <linux/percpu.h>
40 #include <linux/irq.h>
41 #include <linux/bitops.h>
42 #include <linux/crash_dump.h>
43 #include <linux/cpu.h>
44 #include <linux/cpuhotplug.h>
45 
46 #include <scsi/scsi.h>
47 #include <scsi/scsi_device.h>
48 #include <scsi/scsi_host.h>
49 #include <scsi/scsi_transport_fc.h>
50 #include <scsi/scsi_tcq.h>
51 #include <scsi/fc/fc_fs.h>
52 
53 #include "lpfc_hw4.h"
54 #include "lpfc_hw.h"
55 #include "lpfc_sli.h"
56 #include "lpfc_sli4.h"
57 #include "lpfc_nl.h"
58 #include "lpfc_disc.h"
59 #include "lpfc.h"
60 #include "lpfc_scsi.h"
61 #include "lpfc_nvme.h"
62 #include "lpfc_logmsg.h"
63 #include "lpfc_crtn.h"
64 #include "lpfc_vport.h"
65 #include "lpfc_version.h"
66 #include "lpfc_ids.h"
67 
68 static enum cpuhp_state lpfc_cpuhp_state;
69 /* Used when mapping IRQ vectors in a driver centric manner */
70 static uint32_t lpfc_present_cpu;
71 static bool lpfc_pldv_detect;
72 
73 static void __lpfc_cpuhp_remove(struct lpfc_hba *phba);
74 static void lpfc_cpuhp_remove(struct lpfc_hba *phba);
75 static void lpfc_cpuhp_add(struct lpfc_hba *phba);
76 static void lpfc_get_hba_model_desc(struct lpfc_hba *, uint8_t *, uint8_t *);
77 static int lpfc_post_rcv_buf(struct lpfc_hba *);
78 static int lpfc_sli4_queue_verify(struct lpfc_hba *);
79 static int lpfc_create_bootstrap_mbox(struct lpfc_hba *);
80 static int lpfc_setup_endian_order(struct lpfc_hba *);
81 static void lpfc_destroy_bootstrap_mbox(struct lpfc_hba *);
82 static void lpfc_free_els_sgl_list(struct lpfc_hba *);
83 static void lpfc_free_nvmet_sgl_list(struct lpfc_hba *);
84 static void lpfc_init_sgl_list(struct lpfc_hba *);
85 static int lpfc_init_active_sgl_array(struct lpfc_hba *);
86 static void lpfc_free_active_sgl(struct lpfc_hba *);
87 static int lpfc_hba_down_post_s3(struct lpfc_hba *phba);
88 static int lpfc_hba_down_post_s4(struct lpfc_hba *phba);
89 static int lpfc_sli4_cq_event_pool_create(struct lpfc_hba *);
90 static void lpfc_sli4_cq_event_pool_destroy(struct lpfc_hba *);
91 static void lpfc_sli4_cq_event_release_all(struct lpfc_hba *);
92 static void lpfc_sli4_disable_intr(struct lpfc_hba *);
93 static uint32_t lpfc_sli4_enable_intr(struct lpfc_hba *, uint32_t);
94 static void lpfc_sli4_oas_verify(struct lpfc_hba *phba);
95 static uint16_t lpfc_find_cpu_handle(struct lpfc_hba *, uint16_t, int);
96 static void lpfc_setup_bg(struct lpfc_hba *, struct Scsi_Host *);
97 static int lpfc_sli4_cgn_parm_chg_evt(struct lpfc_hba *);
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 
106 /**
107  * lpfc_config_port_prep - Perform lpfc initialization prior to config port
108  * @phba: pointer to lpfc hba data structure.
109  *
110  * This routine will do LPFC initialization prior to issuing the CONFIG_PORT
111  * mailbox command. It retrieves the revision information from the HBA and
112  * collects the Vital Product Data (VPD) about the HBA for preparing the
113  * configuration of the HBA.
114  *
115  * Return codes:
116  *   0 - success.
117  *   -ERESTART - requests the SLI layer to reset the HBA and try again.
118  *   Any other value - indicates an error.
119  **/
120 int
121 lpfc_config_port_prep(struct lpfc_hba *phba)
122 {
123 	lpfc_vpd_t *vp = &phba->vpd;
124 	int i = 0, rc;
125 	LPFC_MBOXQ_t *pmb;
126 	MAILBOX_t *mb;
127 	char *lpfc_vpd_data = NULL;
128 	uint16_t offset = 0;
129 	static char licensed[56] =
130 		    "key unlock for use with gnu public licensed code only\0";
131 	static int init_key = 1;
132 
133 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
134 	if (!pmb) {
135 		phba->link_state = LPFC_HBA_ERROR;
136 		return -ENOMEM;
137 	}
138 
139 	mb = &pmb->u.mb;
140 	phba->link_state = LPFC_INIT_MBX_CMDS;
141 
142 	if (lpfc_is_LC_HBA(phba->pcidev->device)) {
143 		if (init_key) {
144 			uint32_t *ptext = (uint32_t *) licensed;
145 
146 			for (i = 0; i < 56; i += sizeof (uint32_t), ptext++)
147 				*ptext = cpu_to_be32(*ptext);
148 			init_key = 0;
149 		}
150 
151 		lpfc_read_nv(phba, pmb);
152 		memset((char*)mb->un.varRDnvp.rsvd3, 0,
153 			sizeof (mb->un.varRDnvp.rsvd3));
154 		memcpy((char*)mb->un.varRDnvp.rsvd3, licensed,
155 			 sizeof (licensed));
156 
157 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
158 
159 		if (rc != MBX_SUCCESS) {
160 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
161 					"0324 Config Port initialization "
162 					"error, mbxCmd x%x READ_NVPARM, "
163 					"mbxStatus x%x\n",
164 					mb->mbxCommand, mb->mbxStatus);
165 			mempool_free(pmb, phba->mbox_mem_pool);
166 			return -ERESTART;
167 		}
168 		memcpy(phba->wwnn, (char *)mb->un.varRDnvp.nodename,
169 		       sizeof(phba->wwnn));
170 		memcpy(phba->wwpn, (char *)mb->un.varRDnvp.portname,
171 		       sizeof(phba->wwpn));
172 	}
173 
174 	/*
175 	 * Clear all option bits except LPFC_SLI3_BG_ENABLED,
176 	 * which was already set in lpfc_get_cfgparam()
177 	 */
178 	phba->sli3_options &= (uint32_t)LPFC_SLI3_BG_ENABLED;
179 
180 	/* Setup and issue mailbox READ REV command */
181 	lpfc_read_rev(phba, pmb);
182 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
183 	if (rc != MBX_SUCCESS) {
184 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
185 				"0439 Adapter failed to init, mbxCmd x%x "
186 				"READ_REV, mbxStatus x%x\n",
187 				mb->mbxCommand, mb->mbxStatus);
188 		mempool_free( pmb, phba->mbox_mem_pool);
189 		return -ERESTART;
190 	}
191 
192 
193 	/*
194 	 * The value of rr must be 1 since the driver set the cv field to 1.
195 	 * This setting requires the FW to set all revision fields.
196 	 */
197 	if (mb->un.varRdRev.rr == 0) {
198 		vp->rev.rBit = 0;
199 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
200 				"0440 Adapter failed to init, READ_REV has "
201 				"missing revision information.\n");
202 		mempool_free(pmb, phba->mbox_mem_pool);
203 		return -ERESTART;
204 	}
205 
206 	if (phba->sli_rev == 3 && !mb->un.varRdRev.v3rsp) {
207 		mempool_free(pmb, phba->mbox_mem_pool);
208 		return -EINVAL;
209 	}
210 
211 	/* Save information as VPD data */
212 	vp->rev.rBit = 1;
213 	memcpy(&vp->sli3Feat, &mb->un.varRdRev.sli3Feat, sizeof(uint32_t));
214 	vp->rev.sli1FwRev = mb->un.varRdRev.sli1FwRev;
215 	memcpy(vp->rev.sli1FwName, (char*) mb->un.varRdRev.sli1FwName, 16);
216 	vp->rev.sli2FwRev = mb->un.varRdRev.sli2FwRev;
217 	memcpy(vp->rev.sli2FwName, (char *) mb->un.varRdRev.sli2FwName, 16);
218 	vp->rev.biuRev = mb->un.varRdRev.biuRev;
219 	vp->rev.smRev = mb->un.varRdRev.smRev;
220 	vp->rev.smFwRev = mb->un.varRdRev.un.smFwRev;
221 	vp->rev.endecRev = mb->un.varRdRev.endecRev;
222 	vp->rev.fcphHigh = mb->un.varRdRev.fcphHigh;
223 	vp->rev.fcphLow = mb->un.varRdRev.fcphLow;
224 	vp->rev.feaLevelHigh = mb->un.varRdRev.feaLevelHigh;
225 	vp->rev.feaLevelLow = mb->un.varRdRev.feaLevelLow;
226 	vp->rev.postKernRev = mb->un.varRdRev.postKernRev;
227 	vp->rev.opFwRev = mb->un.varRdRev.opFwRev;
228 
229 	/* If the sli feature level is less then 9, we must
230 	 * tear down all RPIs and VPIs on link down if NPIV
231 	 * is enabled.
232 	 */
233 	if (vp->rev.feaLevelHigh < 9)
234 		phba->sli3_options |= LPFC_SLI3_VPORT_TEARDOWN;
235 
236 	if (lpfc_is_LC_HBA(phba->pcidev->device))
237 		memcpy(phba->RandomData, (char *)&mb->un.varWords[24],
238 						sizeof (phba->RandomData));
239 
240 	/* Get adapter VPD information */
241 	lpfc_vpd_data = kmalloc(DMP_VPD_SIZE, GFP_KERNEL);
242 	if (!lpfc_vpd_data)
243 		goto out_free_mbox;
244 	do {
245 		lpfc_dump_mem(phba, pmb, offset, DMP_REGION_VPD);
246 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
247 
248 		if (rc != MBX_SUCCESS) {
249 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
250 					"0441 VPD not present on adapter, "
251 					"mbxCmd x%x DUMP VPD, mbxStatus x%x\n",
252 					mb->mbxCommand, mb->mbxStatus);
253 			mb->un.varDmp.word_cnt = 0;
254 		}
255 		/* dump mem may return a zero when finished or we got a
256 		 * mailbox error, either way we are done.
257 		 */
258 		if (mb->un.varDmp.word_cnt == 0)
259 			break;
260 
261 		if (mb->un.varDmp.word_cnt > DMP_VPD_SIZE - offset)
262 			mb->un.varDmp.word_cnt = DMP_VPD_SIZE - offset;
263 		lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
264 				      lpfc_vpd_data + offset,
265 				      mb->un.varDmp.word_cnt);
266 		offset += mb->un.varDmp.word_cnt;
267 	} while (mb->un.varDmp.word_cnt && offset < DMP_VPD_SIZE);
268 
269 	lpfc_parse_vpd(phba, lpfc_vpd_data, offset);
270 
271 	kfree(lpfc_vpd_data);
272 out_free_mbox:
273 	mempool_free(pmb, phba->mbox_mem_pool);
274 	return 0;
275 }
276 
277 /**
278  * lpfc_config_async_cmpl - Completion handler for config async event mbox cmd
279  * @phba: pointer to lpfc hba data structure.
280  * @pmboxq: pointer to the driver internal queue element for mailbox command.
281  *
282  * This is the completion handler for driver's configuring asynchronous event
283  * mailbox command to the device. If the mailbox command returns successfully,
284  * it will set internal async event support flag to 1; otherwise, it will
285  * set internal async event support flag to 0.
286  **/
287 static void
288 lpfc_config_async_cmpl(struct lpfc_hba * phba, LPFC_MBOXQ_t * pmboxq)
289 {
290 	if (pmboxq->u.mb.mbxStatus == MBX_SUCCESS)
291 		phba->temp_sensor_support = 1;
292 	else
293 		phba->temp_sensor_support = 0;
294 	mempool_free(pmboxq, phba->mbox_mem_pool);
295 	return;
296 }
297 
298 /**
299  * lpfc_dump_wakeup_param_cmpl - dump memory mailbox command completion handler
300  * @phba: pointer to lpfc hba data structure.
301  * @pmboxq: pointer to the driver internal queue element for mailbox command.
302  *
303  * This is the completion handler for dump mailbox command for getting
304  * wake up parameters. When this command complete, the response contain
305  * Option rom version of the HBA. This function translate the version number
306  * into a human readable string and store it in OptionROMVersion.
307  **/
308 static void
309 lpfc_dump_wakeup_param_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
310 {
311 	struct prog_id *prg;
312 	uint32_t prog_id_word;
313 	char dist = ' ';
314 	/* character array used for decoding dist type. */
315 	char dist_char[] = "nabx";
316 
317 	if (pmboxq->u.mb.mbxStatus != MBX_SUCCESS) {
318 		mempool_free(pmboxq, phba->mbox_mem_pool);
319 		return;
320 	}
321 
322 	prg = (struct prog_id *) &prog_id_word;
323 
324 	/* word 7 contain option rom version */
325 	prog_id_word = pmboxq->u.mb.un.varWords[7];
326 
327 	/* Decode the Option rom version word to a readable string */
328 	dist = dist_char[prg->dist];
329 
330 	if ((prg->dist == 3) && (prg->num == 0))
331 		snprintf(phba->OptionROMVersion, 32, "%d.%d%d",
332 			prg->ver, prg->rev, prg->lev);
333 	else
334 		snprintf(phba->OptionROMVersion, 32, "%d.%d%d%c%d",
335 			prg->ver, prg->rev, prg->lev,
336 			dist, prg->num);
337 	mempool_free(pmboxq, phba->mbox_mem_pool);
338 	return;
339 }
340 
341 /**
342  * lpfc_update_vport_wwn - Updates the fc_nodename, fc_portname,
343  * @vport: pointer to lpfc vport data structure.
344  *
345  *
346  * Return codes
347  *   None.
348  **/
349 void
350 lpfc_update_vport_wwn(struct lpfc_vport *vport)
351 {
352 	struct lpfc_hba *phba = vport->phba;
353 
354 	/*
355 	 * If the name is empty or there exists a soft name
356 	 * then copy the service params name, otherwise use the fc name
357 	 */
358 	if (vport->fc_nodename.u.wwn[0] == 0)
359 		memcpy(&vport->fc_nodename, &vport->fc_sparam.nodeName,
360 			sizeof(struct lpfc_name));
361 	else
362 		memcpy(&vport->fc_sparam.nodeName, &vport->fc_nodename,
363 			sizeof(struct lpfc_name));
364 
365 	/*
366 	 * If the port name has changed, then set the Param changes flag
367 	 * to unreg the login
368 	 */
369 	if (vport->fc_portname.u.wwn[0] != 0 &&
370 		memcmp(&vport->fc_portname, &vport->fc_sparam.portName,
371 		       sizeof(struct lpfc_name))) {
372 		vport->vport_flag |= FAWWPN_PARAM_CHG;
373 
374 		if (phba->sli_rev == LPFC_SLI_REV4 &&
375 		    vport->port_type == LPFC_PHYSICAL_PORT &&
376 		    phba->sli4_hba.fawwpn_flag & LPFC_FAWWPN_FABRIC) {
377 			if (!(phba->sli4_hba.fawwpn_flag & LPFC_FAWWPN_CONFIG))
378 				phba->sli4_hba.fawwpn_flag &=
379 						~LPFC_FAWWPN_FABRIC;
380 			lpfc_printf_log(phba, KERN_INFO,
381 					LOG_SLI | LOG_DISCOVERY | LOG_ELS,
382 					"2701 FA-PWWN change WWPN from %llx to "
383 					"%llx: vflag x%x fawwpn_flag x%x\n",
384 					wwn_to_u64(vport->fc_portname.u.wwn),
385 					wwn_to_u64
386 					   (vport->fc_sparam.portName.u.wwn),
387 					vport->vport_flag,
388 					phba->sli4_hba.fawwpn_flag);
389 			memcpy(&vport->fc_portname, &vport->fc_sparam.portName,
390 			       sizeof(struct lpfc_name));
391 		}
392 	}
393 
394 	if (vport->fc_portname.u.wwn[0] == 0)
395 		memcpy(&vport->fc_portname, &vport->fc_sparam.portName,
396 		       sizeof(struct lpfc_name));
397 	else
398 		memcpy(&vport->fc_sparam.portName, &vport->fc_portname,
399 		       sizeof(struct lpfc_name));
400 }
401 
402 /**
403  * lpfc_config_port_post - Perform lpfc initialization after config port
404  * @phba: pointer to lpfc hba data structure.
405  *
406  * This routine will do LPFC initialization after the CONFIG_PORT mailbox
407  * command call. It performs all internal resource and state setups on the
408  * port: post IOCB buffers, enable appropriate host interrupt attentions,
409  * ELS ring timers, etc.
410  *
411  * Return codes
412  *   0 - success.
413  *   Any other value - error.
414  **/
415 int
416 lpfc_config_port_post(struct lpfc_hba *phba)
417 {
418 	struct lpfc_vport *vport = phba->pport;
419 	struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
420 	LPFC_MBOXQ_t *pmb;
421 	MAILBOX_t *mb;
422 	struct lpfc_dmabuf *mp;
423 	struct lpfc_sli *psli = &phba->sli;
424 	uint32_t status, timeout;
425 	int i, j;
426 	int rc;
427 
428 	spin_lock_irq(&phba->hbalock);
429 	/*
430 	 * If the Config port completed correctly the HBA is not
431 	 * over heated any more.
432 	 */
433 	if (phba->over_temp_state == HBA_OVER_TEMP)
434 		phba->over_temp_state = HBA_NORMAL_TEMP;
435 	spin_unlock_irq(&phba->hbalock);
436 
437 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
438 	if (!pmb) {
439 		phba->link_state = LPFC_HBA_ERROR;
440 		return -ENOMEM;
441 	}
442 	mb = &pmb->u.mb;
443 
444 	/* Get login parameters for NID.  */
445 	rc = lpfc_read_sparam(phba, pmb, 0);
446 	if (rc) {
447 		mempool_free(pmb, phba->mbox_mem_pool);
448 		return -ENOMEM;
449 	}
450 
451 	pmb->vport = vport;
452 	if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
453 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
454 				"0448 Adapter failed init, mbxCmd x%x "
455 				"READ_SPARM mbxStatus x%x\n",
456 				mb->mbxCommand, mb->mbxStatus);
457 		phba->link_state = LPFC_HBA_ERROR;
458 		lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
459 		return -EIO;
460 	}
461 
462 	mp = (struct lpfc_dmabuf *)pmb->ctx_buf;
463 
464 	/* This dmabuf was allocated by lpfc_read_sparam. The dmabuf is no
465 	 * longer needed.  Prevent unintended ctx_buf access as the mbox is
466 	 * reused.
467 	 */
468 	memcpy(&vport->fc_sparam, mp->virt, sizeof (struct serv_parm));
469 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
470 	kfree(mp);
471 	pmb->ctx_buf = NULL;
472 	lpfc_update_vport_wwn(vport);
473 
474 	/* Update the fc_host data structures with new wwn. */
475 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
476 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
477 	fc_host_max_npiv_vports(shost) = phba->max_vpi;
478 
479 	/* If no serial number in VPD data, use low 6 bytes of WWNN */
480 	/* This should be consolidated into parse_vpd ? - mr */
481 	if (phba->SerialNumber[0] == 0) {
482 		uint8_t *outptr;
483 
484 		outptr = &vport->fc_nodename.u.s.IEEE[0];
485 		for (i = 0; i < 12; i++) {
486 			status = *outptr++;
487 			j = ((status & 0xf0) >> 4);
488 			if (j <= 9)
489 				phba->SerialNumber[i] =
490 				    (char)((uint8_t) 0x30 + (uint8_t) j);
491 			else
492 				phba->SerialNumber[i] =
493 				    (char)((uint8_t) 0x61 + (uint8_t) (j - 10));
494 			i++;
495 			j = (status & 0xf);
496 			if (j <= 9)
497 				phba->SerialNumber[i] =
498 				    (char)((uint8_t) 0x30 + (uint8_t) j);
499 			else
500 				phba->SerialNumber[i] =
501 				    (char)((uint8_t) 0x61 + (uint8_t) (j - 10));
502 		}
503 	}
504 
505 	lpfc_read_config(phba, pmb);
506 	pmb->vport = vport;
507 	if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
508 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
509 				"0453 Adapter failed to init, mbxCmd x%x "
510 				"READ_CONFIG, mbxStatus x%x\n",
511 				mb->mbxCommand, mb->mbxStatus);
512 		phba->link_state = LPFC_HBA_ERROR;
513 		mempool_free( pmb, phba->mbox_mem_pool);
514 		return -EIO;
515 	}
516 
517 	/* Check if the port is disabled */
518 	lpfc_sli_read_link_ste(phba);
519 
520 	/* Reset the DFT_HBA_Q_DEPTH to the max xri  */
521 	if (phba->cfg_hba_queue_depth > mb->un.varRdConfig.max_xri) {
522 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
523 				"3359 HBA queue depth changed from %d to %d\n",
524 				phba->cfg_hba_queue_depth,
525 				mb->un.varRdConfig.max_xri);
526 		phba->cfg_hba_queue_depth = mb->un.varRdConfig.max_xri;
527 	}
528 
529 	phba->lmt = mb->un.varRdConfig.lmt;
530 
531 	/* Get the default values for Model Name and Description */
532 	lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
533 
534 	phba->link_state = LPFC_LINK_DOWN;
535 
536 	/* Only process IOCBs on ELS ring till hba_state is READY */
537 	if (psli->sli3_ring[LPFC_EXTRA_RING].sli.sli3.cmdringaddr)
538 		psli->sli3_ring[LPFC_EXTRA_RING].flag |= LPFC_STOP_IOCB_EVENT;
539 	if (psli->sli3_ring[LPFC_FCP_RING].sli.sli3.cmdringaddr)
540 		psli->sli3_ring[LPFC_FCP_RING].flag |= LPFC_STOP_IOCB_EVENT;
541 
542 	/* Post receive buffers for desired rings */
543 	if (phba->sli_rev != 3)
544 		lpfc_post_rcv_buf(phba);
545 
546 	/*
547 	 * Configure HBA MSI-X attention conditions to messages if MSI-X mode
548 	 */
549 	if (phba->intr_type == MSIX) {
550 		rc = lpfc_config_msi(phba, pmb);
551 		if (rc) {
552 			mempool_free(pmb, phba->mbox_mem_pool);
553 			return -EIO;
554 		}
555 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
556 		if (rc != MBX_SUCCESS) {
557 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
558 					"0352 Config MSI mailbox command "
559 					"failed, mbxCmd x%x, mbxStatus x%x\n",
560 					pmb->u.mb.mbxCommand,
561 					pmb->u.mb.mbxStatus);
562 			mempool_free(pmb, phba->mbox_mem_pool);
563 			return -EIO;
564 		}
565 	}
566 
567 	spin_lock_irq(&phba->hbalock);
568 	/* Initialize ERATT handling flag */
569 	phba->hba_flag &= ~HBA_ERATT_HANDLED;
570 
571 	/* Enable appropriate host interrupts */
572 	if (lpfc_readl(phba->HCregaddr, &status)) {
573 		spin_unlock_irq(&phba->hbalock);
574 		return -EIO;
575 	}
576 	status |= HC_MBINT_ENA | HC_ERINT_ENA | HC_LAINT_ENA;
577 	if (psli->num_rings > 0)
578 		status |= HC_R0INT_ENA;
579 	if (psli->num_rings > 1)
580 		status |= HC_R1INT_ENA;
581 	if (psli->num_rings > 2)
582 		status |= HC_R2INT_ENA;
583 	if (psli->num_rings > 3)
584 		status |= HC_R3INT_ENA;
585 
586 	if ((phba->cfg_poll & ENABLE_FCP_RING_POLLING) &&
587 	    (phba->cfg_poll & DISABLE_FCP_RING_INT))
588 		status &= ~(HC_R0INT_ENA);
589 
590 	writel(status, phba->HCregaddr);
591 	readl(phba->HCregaddr); /* flush */
592 	spin_unlock_irq(&phba->hbalock);
593 
594 	/* Set up ring-0 (ELS) timer */
595 	timeout = phba->fc_ratov * 2;
596 	mod_timer(&vport->els_tmofunc,
597 		  jiffies + msecs_to_jiffies(1000 * timeout));
598 	/* Set up heart beat (HB) timer */
599 	mod_timer(&phba->hb_tmofunc,
600 		  jiffies + msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
601 	phba->hba_flag &= ~(HBA_HBEAT_INP | HBA_HBEAT_TMO);
602 	phba->last_completion_time = jiffies;
603 	/* Set up error attention (ERATT) polling timer */
604 	mod_timer(&phba->eratt_poll,
605 		  jiffies + msecs_to_jiffies(1000 * phba->eratt_poll_interval));
606 
607 	if (phba->hba_flag & LINK_DISABLED) {
608 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
609 				"2598 Adapter Link is disabled.\n");
610 		lpfc_down_link(phba, pmb);
611 		pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
612 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
613 		if ((rc != MBX_SUCCESS) && (rc != MBX_BUSY)) {
614 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
615 					"2599 Adapter failed to issue DOWN_LINK"
616 					" mbox command rc 0x%x\n", rc);
617 
618 			mempool_free(pmb, phba->mbox_mem_pool);
619 			return -EIO;
620 		}
621 	} else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
622 		mempool_free(pmb, phba->mbox_mem_pool);
623 		rc = phba->lpfc_hba_init_link(phba, MBX_NOWAIT);
624 		if (rc)
625 			return rc;
626 	}
627 	/* MBOX buffer will be freed in mbox compl */
628 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
629 	if (!pmb) {
630 		phba->link_state = LPFC_HBA_ERROR;
631 		return -ENOMEM;
632 	}
633 
634 	lpfc_config_async(phba, pmb, LPFC_ELS_RING);
635 	pmb->mbox_cmpl = lpfc_config_async_cmpl;
636 	pmb->vport = phba->pport;
637 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
638 
639 	if ((rc != MBX_BUSY) && (rc != MBX_SUCCESS)) {
640 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
641 				"0456 Adapter failed to issue "
642 				"ASYNCEVT_ENABLE mbox status x%x\n",
643 				rc);
644 		mempool_free(pmb, phba->mbox_mem_pool);
645 	}
646 
647 	/* Get Option rom version */
648 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
649 	if (!pmb) {
650 		phba->link_state = LPFC_HBA_ERROR;
651 		return -ENOMEM;
652 	}
653 
654 	lpfc_dump_wakeup_param(phba, pmb);
655 	pmb->mbox_cmpl = lpfc_dump_wakeup_param_cmpl;
656 	pmb->vport = phba->pport;
657 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
658 
659 	if ((rc != MBX_BUSY) && (rc != MBX_SUCCESS)) {
660 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
661 				"0435 Adapter failed "
662 				"to get Option ROM version status x%x\n", rc);
663 		mempool_free(pmb, phba->mbox_mem_pool);
664 	}
665 
666 	return 0;
667 }
668 
669 /**
670  * lpfc_sli4_refresh_params - update driver copy of params.
671  * @phba: Pointer to HBA context object.
672  *
673  * This is called to refresh driver copy of dynamic fields from the
674  * common_get_sli4_parameters descriptor.
675  **/
676 int
677 lpfc_sli4_refresh_params(struct lpfc_hba *phba)
678 {
679 	LPFC_MBOXQ_t *mboxq;
680 	struct lpfc_mqe *mqe;
681 	struct lpfc_sli4_parameters *mbx_sli4_parameters;
682 	int length, rc;
683 
684 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
685 	if (!mboxq)
686 		return -ENOMEM;
687 
688 	mqe = &mboxq->u.mqe;
689 	/* Read the port's SLI4 Config Parameters */
690 	length = (sizeof(struct lpfc_mbx_get_sli4_parameters) -
691 		  sizeof(struct lpfc_sli4_cfg_mhdr));
692 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
693 			 LPFC_MBOX_OPCODE_GET_SLI4_PARAMETERS,
694 			 length, LPFC_SLI4_MBX_EMBED);
695 
696 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
697 	if (unlikely(rc)) {
698 		mempool_free(mboxq, phba->mbox_mem_pool);
699 		return rc;
700 	}
701 	mbx_sli4_parameters = &mqe->un.get_sli4_parameters.sli4_parameters;
702 	phba->sli4_hba.pc_sli4_params.mi_cap =
703 		bf_get(cfg_mi_ver, mbx_sli4_parameters);
704 
705 	/* Are we forcing MI off via module parameter? */
706 	if (phba->cfg_enable_mi)
707 		phba->sli4_hba.pc_sli4_params.mi_ver =
708 			bf_get(cfg_mi_ver, mbx_sli4_parameters);
709 	else
710 		phba->sli4_hba.pc_sli4_params.mi_ver = 0;
711 
712 	phba->sli4_hba.pc_sli4_params.cmf =
713 			bf_get(cfg_cmf, mbx_sli4_parameters);
714 	phba->sli4_hba.pc_sli4_params.pls =
715 			bf_get(cfg_pvl, mbx_sli4_parameters);
716 
717 	mempool_free(mboxq, phba->mbox_mem_pool);
718 	return rc;
719 }
720 
721 /**
722  * lpfc_hba_init_link - Initialize the FC link
723  * @phba: pointer to lpfc hba data structure.
724  * @flag: mailbox command issue mode - either MBX_POLL or MBX_NOWAIT
725  *
726  * This routine will issue the INIT_LINK mailbox command call.
727  * It is available to other drivers through the lpfc_hba data
728  * structure for use as a delayed link up mechanism with the
729  * module parameter lpfc_suppress_link_up.
730  *
731  * Return code
732  *		0 - success
733  *		Any other value - error
734  **/
735 static int
736 lpfc_hba_init_link(struct lpfc_hba *phba, uint32_t flag)
737 {
738 	return lpfc_hba_init_link_fc_topology(phba, phba->cfg_topology, flag);
739 }
740 
741 /**
742  * lpfc_hba_init_link_fc_topology - Initialize FC link with desired topology
743  * @phba: pointer to lpfc hba data structure.
744  * @fc_topology: desired fc topology.
745  * @flag: mailbox command issue mode - either MBX_POLL or MBX_NOWAIT
746  *
747  * This routine will issue the INIT_LINK mailbox command call.
748  * It is available to other drivers through the lpfc_hba data
749  * structure for use as a delayed link up mechanism with the
750  * module parameter lpfc_suppress_link_up.
751  *
752  * Return code
753  *              0 - success
754  *              Any other value - error
755  **/
756 int
757 lpfc_hba_init_link_fc_topology(struct lpfc_hba *phba, uint32_t fc_topology,
758 			       uint32_t flag)
759 {
760 	struct lpfc_vport *vport = phba->pport;
761 	LPFC_MBOXQ_t *pmb;
762 	MAILBOX_t *mb;
763 	int rc;
764 
765 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
766 	if (!pmb) {
767 		phba->link_state = LPFC_HBA_ERROR;
768 		return -ENOMEM;
769 	}
770 	mb = &pmb->u.mb;
771 	pmb->vport = vport;
772 
773 	if ((phba->cfg_link_speed > LPFC_USER_LINK_SPEED_MAX) ||
774 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_1G) &&
775 	     !(phba->lmt & LMT_1Gb)) ||
776 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_2G) &&
777 	     !(phba->lmt & LMT_2Gb)) ||
778 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_4G) &&
779 	     !(phba->lmt & LMT_4Gb)) ||
780 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_8G) &&
781 	     !(phba->lmt & LMT_8Gb)) ||
782 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_10G) &&
783 	     !(phba->lmt & LMT_10Gb)) ||
784 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_16G) &&
785 	     !(phba->lmt & LMT_16Gb)) ||
786 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_32G) &&
787 	     !(phba->lmt & LMT_32Gb)) ||
788 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_64G) &&
789 	     !(phba->lmt & LMT_64Gb))) {
790 		/* Reset link speed to auto */
791 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
792 				"1302 Invalid speed for this board:%d "
793 				"Reset link speed to auto.\n",
794 				phba->cfg_link_speed);
795 			phba->cfg_link_speed = LPFC_USER_LINK_SPEED_AUTO;
796 	}
797 	lpfc_init_link(phba, pmb, fc_topology, phba->cfg_link_speed);
798 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
799 	if (phba->sli_rev < LPFC_SLI_REV4)
800 		lpfc_set_loopback_flag(phba);
801 	rc = lpfc_sli_issue_mbox(phba, pmb, flag);
802 	if ((rc != MBX_BUSY) && (rc != MBX_SUCCESS)) {
803 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
804 				"0498 Adapter failed to init, mbxCmd x%x "
805 				"INIT_LINK, mbxStatus x%x\n",
806 				mb->mbxCommand, mb->mbxStatus);
807 		if (phba->sli_rev <= LPFC_SLI_REV3) {
808 			/* Clear all interrupt enable conditions */
809 			writel(0, phba->HCregaddr);
810 			readl(phba->HCregaddr); /* flush */
811 			/* Clear all pending interrupts */
812 			writel(0xffffffff, phba->HAregaddr);
813 			readl(phba->HAregaddr); /* flush */
814 		}
815 		phba->link_state = LPFC_HBA_ERROR;
816 		if (rc != MBX_BUSY || flag == MBX_POLL)
817 			mempool_free(pmb, phba->mbox_mem_pool);
818 		return -EIO;
819 	}
820 	phba->cfg_suppress_link_up = LPFC_INITIALIZE_LINK;
821 	if (flag == MBX_POLL)
822 		mempool_free(pmb, phba->mbox_mem_pool);
823 
824 	return 0;
825 }
826 
827 /**
828  * lpfc_hba_down_link - this routine downs the FC link
829  * @phba: pointer to lpfc hba data structure.
830  * @flag: mailbox command issue mode - either MBX_POLL or MBX_NOWAIT
831  *
832  * This routine will issue the DOWN_LINK mailbox command call.
833  * It is available to other drivers through the lpfc_hba data
834  * structure for use to stop the link.
835  *
836  * Return code
837  *		0 - success
838  *		Any other value - error
839  **/
840 static int
841 lpfc_hba_down_link(struct lpfc_hba *phba, uint32_t flag)
842 {
843 	LPFC_MBOXQ_t *pmb;
844 	int rc;
845 
846 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
847 	if (!pmb) {
848 		phba->link_state = LPFC_HBA_ERROR;
849 		return -ENOMEM;
850 	}
851 
852 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
853 			"0491 Adapter Link is disabled.\n");
854 	lpfc_down_link(phba, pmb);
855 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
856 	rc = lpfc_sli_issue_mbox(phba, pmb, flag);
857 	if ((rc != MBX_SUCCESS) && (rc != MBX_BUSY)) {
858 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
859 				"2522 Adapter failed to issue DOWN_LINK"
860 				" mbox command rc 0x%x\n", rc);
861 
862 		mempool_free(pmb, phba->mbox_mem_pool);
863 		return -EIO;
864 	}
865 	if (flag == MBX_POLL)
866 		mempool_free(pmb, phba->mbox_mem_pool);
867 
868 	return 0;
869 }
870 
871 /**
872  * lpfc_hba_down_prep - Perform lpfc uninitialization prior to HBA reset
873  * @phba: pointer to lpfc HBA data structure.
874  *
875  * This routine will do LPFC uninitialization before the HBA is reset when
876  * bringing down the SLI Layer.
877  *
878  * Return codes
879  *   0 - success.
880  *   Any other value - error.
881  **/
882 int
883 lpfc_hba_down_prep(struct lpfc_hba *phba)
884 {
885 	struct lpfc_vport **vports;
886 	int i;
887 
888 	if (phba->sli_rev <= LPFC_SLI_REV3) {
889 		/* Disable interrupts */
890 		writel(0, phba->HCregaddr);
891 		readl(phba->HCregaddr); /* flush */
892 	}
893 
894 	if (phba->pport->load_flag & FC_UNLOADING)
895 		lpfc_cleanup_discovery_resources(phba->pport);
896 	else {
897 		vports = lpfc_create_vport_work_array(phba);
898 		if (vports != NULL)
899 			for (i = 0; i <= phba->max_vports &&
900 				vports[i] != NULL; i++)
901 				lpfc_cleanup_discovery_resources(vports[i]);
902 		lpfc_destroy_vport_work_array(phba, vports);
903 	}
904 	return 0;
905 }
906 
907 /**
908  * lpfc_sli4_free_sp_events - Cleanup sp_queue_events to free
909  * rspiocb which got deferred
910  *
911  * @phba: pointer to lpfc HBA data structure.
912  *
913  * This routine will cleanup completed slow path events after HBA is reset
914  * when bringing down the SLI Layer.
915  *
916  *
917  * Return codes
918  *   void.
919  **/
920 static void
921 lpfc_sli4_free_sp_events(struct lpfc_hba *phba)
922 {
923 	struct lpfc_iocbq *rspiocbq;
924 	struct hbq_dmabuf *dmabuf;
925 	struct lpfc_cq_event *cq_event;
926 
927 	spin_lock_irq(&phba->hbalock);
928 	phba->hba_flag &= ~HBA_SP_QUEUE_EVT;
929 	spin_unlock_irq(&phba->hbalock);
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 = from_timer(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 	unsigned long iflag;
1231 
1232 	phba = from_timer(phba, t, rrq_tmr);
1233 	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
1234 	if (!(phba->pport->load_flag & FC_UNLOADING))
1235 		phba->hba_flag |= HBA_RRQ_ACTIVE;
1236 	else
1237 		phba->hba_flag &= ~HBA_RRQ_ACTIVE;
1238 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
1239 
1240 	if (!(phba->pport->load_flag & FC_UNLOADING))
1241 		lpfc_worker_wake_up(phba);
1242 }
1243 
1244 /**
1245  * lpfc_hb_mbox_cmpl - The lpfc heart-beat mailbox command callback function
1246  * @phba: pointer to lpfc hba data structure.
1247  * @pmboxq: pointer to the driver internal queue element for mailbox command.
1248  *
1249  * This is the callback function to the lpfc heart-beat mailbox command.
1250  * If configured, the lpfc driver issues the heart-beat mailbox command to
1251  * the HBA every LPFC_HB_MBOX_INTERVAL (current 5) seconds. At the time the
1252  * heart-beat mailbox command is issued, the driver shall set up heart-beat
1253  * timeout timer to LPFC_HB_MBOX_TIMEOUT (current 30) seconds and marks
1254  * heart-beat outstanding state. Once the mailbox command comes back and
1255  * no error conditions detected, the heart-beat mailbox command timer is
1256  * reset to LPFC_HB_MBOX_INTERVAL seconds and the heart-beat outstanding
1257  * state is cleared for the next heart-beat. If the timer expired with the
1258  * heart-beat outstanding state set, the driver will put the HBA offline.
1259  **/
1260 static void
1261 lpfc_hb_mbox_cmpl(struct lpfc_hba * phba, LPFC_MBOXQ_t * pmboxq)
1262 {
1263 	unsigned long drvr_flag;
1264 
1265 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
1266 	phba->hba_flag &= ~(HBA_HBEAT_INP | HBA_HBEAT_TMO);
1267 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
1268 
1269 	/* Check and reset heart-beat timer if necessary */
1270 	mempool_free(pmboxq, phba->mbox_mem_pool);
1271 	if (!(phba->pport->fc_flag & FC_OFFLINE_MODE) &&
1272 		!(phba->link_state == LPFC_HBA_ERROR) &&
1273 		!(phba->pport->load_flag & FC_UNLOADING))
1274 		mod_timer(&phba->hb_tmofunc,
1275 			  jiffies +
1276 			  msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
1277 	return;
1278 }
1279 
1280 /*
1281  * lpfc_idle_stat_delay_work - idle_stat tracking
1282  *
1283  * This routine tracks per-cq idle_stat and determines polling decisions.
1284  *
1285  * Return codes:
1286  *   None
1287  **/
1288 static void
1289 lpfc_idle_stat_delay_work(struct work_struct *work)
1290 {
1291 	struct lpfc_hba *phba = container_of(to_delayed_work(work),
1292 					     struct lpfc_hba,
1293 					     idle_stat_delay_work);
1294 	struct lpfc_queue *cq;
1295 	struct lpfc_sli4_hdw_queue *hdwq;
1296 	struct lpfc_idle_stat *idle_stat;
1297 	u32 i, idle_percent;
1298 	u64 wall, wall_idle, diff_wall, diff_idle, busy_time;
1299 
1300 	if (phba->pport->load_flag & FC_UNLOADING)
1301 		return;
1302 
1303 	if (phba->link_state == LPFC_HBA_ERROR ||
1304 	    phba->pport->fc_flag & FC_OFFLINE_MODE ||
1305 	    phba->cmf_active_mode != LPFC_CFG_OFF)
1306 		goto requeue;
1307 
1308 	for_each_present_cpu(i) {
1309 		hdwq = &phba->sli4_hba.hdwq[phba->sli4_hba.cpu_map[i].hdwq];
1310 		cq = hdwq->io_cq;
1311 
1312 		/* Skip if we've already handled this cq's primary CPU */
1313 		if (cq->chann != i)
1314 			continue;
1315 
1316 		idle_stat = &phba->sli4_hba.idle_stat[i];
1317 
1318 		/* get_cpu_idle_time returns values as running counters. Thus,
1319 		 * to know the amount for this period, the prior counter values
1320 		 * need to be subtracted from the current counter values.
1321 		 * From there, the idle time stat can be calculated as a
1322 		 * percentage of 100 - the sum of the other consumption times.
1323 		 */
1324 		wall_idle = get_cpu_idle_time(i, &wall, 1);
1325 		diff_idle = wall_idle - idle_stat->prev_idle;
1326 		diff_wall = wall - idle_stat->prev_wall;
1327 
1328 		if (diff_wall <= diff_idle)
1329 			busy_time = 0;
1330 		else
1331 			busy_time = diff_wall - diff_idle;
1332 
1333 		idle_percent = div64_u64(100 * busy_time, diff_wall);
1334 		idle_percent = 100 - idle_percent;
1335 
1336 		if (idle_percent < 15)
1337 			cq->poll_mode = LPFC_QUEUE_WORK;
1338 		else
1339 			cq->poll_mode = LPFC_IRQ_POLL;
1340 
1341 		idle_stat->prev_idle = wall_idle;
1342 		idle_stat->prev_wall = wall;
1343 	}
1344 
1345 requeue:
1346 	schedule_delayed_work(&phba->idle_stat_delay_work,
1347 			      msecs_to_jiffies(LPFC_IDLE_STAT_DELAY));
1348 }
1349 
1350 static void
1351 lpfc_hb_eq_delay_work(struct work_struct *work)
1352 {
1353 	struct lpfc_hba *phba = container_of(to_delayed_work(work),
1354 					     struct lpfc_hba, eq_delay_work);
1355 	struct lpfc_eq_intr_info *eqi, *eqi_new;
1356 	struct lpfc_queue *eq, *eq_next;
1357 	unsigned char *ena_delay = NULL;
1358 	uint32_t usdelay;
1359 	int i;
1360 
1361 	if (!phba->cfg_auto_imax || phba->pport->load_flag & FC_UNLOADING)
1362 		return;
1363 
1364 	if (phba->link_state == LPFC_HBA_ERROR ||
1365 	    phba->pport->fc_flag & FC_OFFLINE_MODE)
1366 		goto requeue;
1367 
1368 	ena_delay = kcalloc(phba->sli4_hba.num_possible_cpu, sizeof(*ena_delay),
1369 			    GFP_KERNEL);
1370 	if (!ena_delay)
1371 		goto requeue;
1372 
1373 	for (i = 0; i < phba->cfg_irq_chann; i++) {
1374 		/* Get the EQ corresponding to the IRQ vector */
1375 		eq = phba->sli4_hba.hba_eq_hdl[i].eq;
1376 		if (!eq)
1377 			continue;
1378 		if (eq->q_mode || eq->q_flag & HBA_EQ_DELAY_CHK) {
1379 			eq->q_flag &= ~HBA_EQ_DELAY_CHK;
1380 			ena_delay[eq->last_cpu] = 1;
1381 		}
1382 	}
1383 
1384 	for_each_present_cpu(i) {
1385 		eqi = per_cpu_ptr(phba->sli4_hba.eq_info, i);
1386 		if (ena_delay[i]) {
1387 			usdelay = (eqi->icnt >> 10) * LPFC_EQ_DELAY_STEP;
1388 			if (usdelay > LPFC_MAX_AUTO_EQ_DELAY)
1389 				usdelay = LPFC_MAX_AUTO_EQ_DELAY;
1390 		} else {
1391 			usdelay = 0;
1392 		}
1393 
1394 		eqi->icnt = 0;
1395 
1396 		list_for_each_entry_safe(eq, eq_next, &eqi->list, cpu_list) {
1397 			if (unlikely(eq->last_cpu != i)) {
1398 				eqi_new = per_cpu_ptr(phba->sli4_hba.eq_info,
1399 						      eq->last_cpu);
1400 				list_move_tail(&eq->cpu_list, &eqi_new->list);
1401 				continue;
1402 			}
1403 			if (usdelay != eq->q_mode)
1404 				lpfc_modify_hba_eq_delay(phba, eq->hdwq, 1,
1405 							 usdelay);
1406 		}
1407 	}
1408 
1409 	kfree(ena_delay);
1410 
1411 requeue:
1412 	queue_delayed_work(phba->wq, &phba->eq_delay_work,
1413 			   msecs_to_jiffies(LPFC_EQ_DELAY_MSECS));
1414 }
1415 
1416 /**
1417  * lpfc_hb_mxp_handler - Multi-XRI pools handler to adjust XRI distribution
1418  * @phba: pointer to lpfc hba data structure.
1419  *
1420  * For each heartbeat, this routine does some heuristic methods to adjust
1421  * XRI distribution. The goal is to fully utilize free XRIs.
1422  **/
1423 static void lpfc_hb_mxp_handler(struct lpfc_hba *phba)
1424 {
1425 	u32 i;
1426 	u32 hwq_count;
1427 
1428 	hwq_count = phba->cfg_hdw_queue;
1429 	for (i = 0; i < hwq_count; i++) {
1430 		/* Adjust XRIs in private pool */
1431 		lpfc_adjust_pvt_pool_count(phba, i);
1432 
1433 		/* Adjust high watermark */
1434 		lpfc_adjust_high_watermark(phba, i);
1435 
1436 #ifdef LPFC_MXP_STAT
1437 		/* Snapshot pbl, pvt and busy count */
1438 		lpfc_snapshot_mxp(phba, i);
1439 #endif
1440 	}
1441 }
1442 
1443 /**
1444  * lpfc_issue_hb_mbox - Issues heart-beat mailbox command
1445  * @phba: pointer to lpfc hba data structure.
1446  *
1447  * If a HB mbox is not already in progrees, this routine will allocate
1448  * a LPFC_MBOXQ_t, populate it with a MBX_HEARTBEAT (0x31) command,
1449  * and issue it. The HBA_HBEAT_INP flag means the command is in progress.
1450  **/
1451 int
1452 lpfc_issue_hb_mbox(struct lpfc_hba *phba)
1453 {
1454 	LPFC_MBOXQ_t *pmboxq;
1455 	int retval;
1456 
1457 	/* Is a Heartbeat mbox already in progress */
1458 	if (phba->hba_flag & HBA_HBEAT_INP)
1459 		return 0;
1460 
1461 	pmboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
1462 	if (!pmboxq)
1463 		return -ENOMEM;
1464 
1465 	lpfc_heart_beat(phba, pmboxq);
1466 	pmboxq->mbox_cmpl = lpfc_hb_mbox_cmpl;
1467 	pmboxq->vport = phba->pport;
1468 	retval = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
1469 
1470 	if (retval != MBX_BUSY && retval != MBX_SUCCESS) {
1471 		mempool_free(pmboxq, phba->mbox_mem_pool);
1472 		return -ENXIO;
1473 	}
1474 	phba->hba_flag |= HBA_HBEAT_INP;
1475 
1476 	return 0;
1477 }
1478 
1479 /**
1480  * lpfc_issue_hb_tmo - Signals heartbeat timer to issue mbox command
1481  * @phba: pointer to lpfc hba data structure.
1482  *
1483  * The heartbeat timer (every 5 sec) will fire. If the HBA_HBEAT_TMO
1484  * flag is set, it will force a MBX_HEARTBEAT mbox command, regardless
1485  * of the value of lpfc_enable_hba_heartbeat.
1486  * If lpfc_enable_hba_heartbeat is set, the timeout routine will always
1487  * try to issue a MBX_HEARTBEAT mbox command.
1488  **/
1489 void
1490 lpfc_issue_hb_tmo(struct lpfc_hba *phba)
1491 {
1492 	if (phba->cfg_enable_hba_heartbeat)
1493 		return;
1494 	phba->hba_flag |= HBA_HBEAT_TMO;
1495 }
1496 
1497 /**
1498  * lpfc_hb_timeout_handler - The HBA-timer timeout handler
1499  * @phba: pointer to lpfc hba data structure.
1500  *
1501  * This is the actual HBA-timer timeout handler to be invoked by the worker
1502  * thread whenever the HBA timer fired and HBA-timeout event posted. This
1503  * handler performs any periodic operations needed for the device. If such
1504  * periodic event has already been attended to either in the interrupt handler
1505  * or by processing slow-ring or fast-ring events within the HBA-timer
1506  * timeout window (LPFC_HB_MBOX_INTERVAL), this handler just simply resets
1507  * the timer for the next timeout period. If lpfc heart-beat mailbox command
1508  * is configured and there is no heart-beat mailbox command outstanding, a
1509  * heart-beat mailbox is issued and timer set properly. Otherwise, if there
1510  * has been a heart-beat mailbox command outstanding, the HBA shall be put
1511  * to offline.
1512  **/
1513 void
1514 lpfc_hb_timeout_handler(struct lpfc_hba *phba)
1515 {
1516 	struct lpfc_vport **vports;
1517 	struct lpfc_dmabuf *buf_ptr;
1518 	int retval = 0;
1519 	int i, tmo;
1520 	struct lpfc_sli *psli = &phba->sli;
1521 	LIST_HEAD(completions);
1522 
1523 	if (phba->cfg_xri_rebalancing) {
1524 		/* Multi-XRI pools handler */
1525 		lpfc_hb_mxp_handler(phba);
1526 	}
1527 
1528 	vports = lpfc_create_vport_work_array(phba);
1529 	if (vports != NULL)
1530 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
1531 			lpfc_rcv_seq_check_edtov(vports[i]);
1532 			lpfc_fdmi_change_check(vports[i]);
1533 		}
1534 	lpfc_destroy_vport_work_array(phba, vports);
1535 
1536 	if ((phba->link_state == LPFC_HBA_ERROR) ||
1537 		(phba->pport->load_flag & FC_UNLOADING) ||
1538 		(phba->pport->fc_flag & FC_OFFLINE_MODE))
1539 		return;
1540 
1541 	if (phba->elsbuf_cnt &&
1542 		(phba->elsbuf_cnt == phba->elsbuf_prev_cnt)) {
1543 		spin_lock_irq(&phba->hbalock);
1544 		list_splice_init(&phba->elsbuf, &completions);
1545 		phba->elsbuf_cnt = 0;
1546 		phba->elsbuf_prev_cnt = 0;
1547 		spin_unlock_irq(&phba->hbalock);
1548 
1549 		while (!list_empty(&completions)) {
1550 			list_remove_head(&completions, buf_ptr,
1551 				struct lpfc_dmabuf, list);
1552 			lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
1553 			kfree(buf_ptr);
1554 		}
1555 	}
1556 	phba->elsbuf_prev_cnt = phba->elsbuf_cnt;
1557 
1558 	/* If there is no heart beat outstanding, issue a heartbeat command */
1559 	if (phba->cfg_enable_hba_heartbeat) {
1560 		/* If IOs are completing, no need to issue a MBX_HEARTBEAT */
1561 		spin_lock_irq(&phba->pport->work_port_lock);
1562 		if (time_after(phba->last_completion_time +
1563 				msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL),
1564 				jiffies)) {
1565 			spin_unlock_irq(&phba->pport->work_port_lock);
1566 			if (phba->hba_flag & HBA_HBEAT_INP)
1567 				tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1568 			else
1569 				tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1570 			goto out;
1571 		}
1572 		spin_unlock_irq(&phba->pport->work_port_lock);
1573 
1574 		/* Check if a MBX_HEARTBEAT is already in progress */
1575 		if (phba->hba_flag & HBA_HBEAT_INP) {
1576 			/*
1577 			 * If heart beat timeout called with HBA_HBEAT_INP set
1578 			 * we need to give the hb mailbox cmd a chance to
1579 			 * complete or TMO.
1580 			 */
1581 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
1582 				"0459 Adapter heartbeat still outstanding: "
1583 				"last compl time was %d ms.\n",
1584 				jiffies_to_msecs(jiffies
1585 					 - phba->last_completion_time));
1586 			tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1587 		} else {
1588 			if ((!(psli->sli_flag & LPFC_SLI_MBOX_ACTIVE)) &&
1589 				(list_empty(&psli->mboxq))) {
1590 
1591 				retval = lpfc_issue_hb_mbox(phba);
1592 				if (retval) {
1593 					tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1594 					goto out;
1595 				}
1596 				phba->skipped_hb = 0;
1597 			} else if (time_before_eq(phba->last_completion_time,
1598 					phba->skipped_hb)) {
1599 				lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
1600 					"2857 Last completion time not "
1601 					" updated in %d ms\n",
1602 					jiffies_to_msecs(jiffies
1603 						 - phba->last_completion_time));
1604 			} else
1605 				phba->skipped_hb = jiffies;
1606 
1607 			tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1608 			goto out;
1609 		}
1610 	} else {
1611 		/* Check to see if we want to force a MBX_HEARTBEAT */
1612 		if (phba->hba_flag & HBA_HBEAT_TMO) {
1613 			retval = lpfc_issue_hb_mbox(phba);
1614 			if (retval)
1615 				tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1616 			else
1617 				tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1618 			goto out;
1619 		}
1620 		tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1621 	}
1622 out:
1623 	mod_timer(&phba->hb_tmofunc, jiffies + msecs_to_jiffies(tmo));
1624 }
1625 
1626 /**
1627  * lpfc_offline_eratt - Bring lpfc offline on hardware error attention
1628  * @phba: pointer to lpfc hba data structure.
1629  *
1630  * This routine is called to bring the HBA offline when HBA hardware error
1631  * other than Port Error 6 has been detected.
1632  **/
1633 static void
1634 lpfc_offline_eratt(struct lpfc_hba *phba)
1635 {
1636 	struct lpfc_sli   *psli = &phba->sli;
1637 
1638 	spin_lock_irq(&phba->hbalock);
1639 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1640 	spin_unlock_irq(&phba->hbalock);
1641 	lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
1642 
1643 	lpfc_offline(phba);
1644 	lpfc_reset_barrier(phba);
1645 	spin_lock_irq(&phba->hbalock);
1646 	lpfc_sli_brdreset(phba);
1647 	spin_unlock_irq(&phba->hbalock);
1648 	lpfc_hba_down_post(phba);
1649 	lpfc_sli_brdready(phba, HS_MBRDY);
1650 	lpfc_unblock_mgmt_io(phba);
1651 	phba->link_state = LPFC_HBA_ERROR;
1652 	return;
1653 }
1654 
1655 /**
1656  * lpfc_sli4_offline_eratt - Bring lpfc offline on SLI4 hardware error attention
1657  * @phba: pointer to lpfc hba data structure.
1658  *
1659  * This routine is called to bring a SLI4 HBA offline when HBA hardware error
1660  * other than Port Error 6 has been detected.
1661  **/
1662 void
1663 lpfc_sli4_offline_eratt(struct lpfc_hba *phba)
1664 {
1665 	spin_lock_irq(&phba->hbalock);
1666 	if (phba->link_state == LPFC_HBA_ERROR &&
1667 		test_bit(HBA_PCI_ERR, &phba->bit_flags)) {
1668 		spin_unlock_irq(&phba->hbalock);
1669 		return;
1670 	}
1671 	phba->link_state = LPFC_HBA_ERROR;
1672 	spin_unlock_irq(&phba->hbalock);
1673 
1674 	lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
1675 	lpfc_sli_flush_io_rings(phba);
1676 	lpfc_offline(phba);
1677 	lpfc_hba_down_post(phba);
1678 	lpfc_unblock_mgmt_io(phba);
1679 }
1680 
1681 /**
1682  * lpfc_handle_deferred_eratt - The HBA hardware deferred error handler
1683  * @phba: pointer to lpfc hba data structure.
1684  *
1685  * This routine is invoked to handle the deferred HBA hardware error
1686  * conditions. This type of error is indicated by HBA by setting ER1
1687  * and another ER bit in the host status register. The driver will
1688  * wait until the ER1 bit clears before handling the error condition.
1689  **/
1690 static void
1691 lpfc_handle_deferred_eratt(struct lpfc_hba *phba)
1692 {
1693 	uint32_t old_host_status = phba->work_hs;
1694 	struct lpfc_sli *psli = &phba->sli;
1695 
1696 	/* If the pci channel is offline, ignore possible errors,
1697 	 * since we cannot communicate with the pci card anyway.
1698 	 */
1699 	if (pci_channel_offline(phba->pcidev)) {
1700 		spin_lock_irq(&phba->hbalock);
1701 		phba->hba_flag &= ~DEFER_ERATT;
1702 		spin_unlock_irq(&phba->hbalock);
1703 		return;
1704 	}
1705 
1706 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1707 			"0479 Deferred Adapter Hardware Error "
1708 			"Data: x%x x%x x%x\n",
1709 			phba->work_hs, phba->work_status[0],
1710 			phba->work_status[1]);
1711 
1712 	spin_lock_irq(&phba->hbalock);
1713 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1714 	spin_unlock_irq(&phba->hbalock);
1715 
1716 
1717 	/*
1718 	 * Firmware stops when it triggred erratt. That could cause the I/Os
1719 	 * dropped by the firmware. Error iocb (I/O) on txcmplq and let the
1720 	 * SCSI layer retry it after re-establishing link.
1721 	 */
1722 	lpfc_sli_abort_fcp_rings(phba);
1723 
1724 	/*
1725 	 * There was a firmware error. Take the hba offline and then
1726 	 * attempt to restart it.
1727 	 */
1728 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
1729 	lpfc_offline(phba);
1730 
1731 	/* Wait for the ER1 bit to clear.*/
1732 	while (phba->work_hs & HS_FFER1) {
1733 		msleep(100);
1734 		if (lpfc_readl(phba->HSregaddr, &phba->work_hs)) {
1735 			phba->work_hs = UNPLUG_ERR ;
1736 			break;
1737 		}
1738 		/* If driver is unloading let the worker thread continue */
1739 		if (phba->pport->load_flag & FC_UNLOADING) {
1740 			phba->work_hs = 0;
1741 			break;
1742 		}
1743 	}
1744 
1745 	/*
1746 	 * This is to ptrotect against a race condition in which
1747 	 * first write to the host attention register clear the
1748 	 * host status register.
1749 	 */
1750 	if ((!phba->work_hs) && (!(phba->pport->load_flag & FC_UNLOADING)))
1751 		phba->work_hs = old_host_status & ~HS_FFER1;
1752 
1753 	spin_lock_irq(&phba->hbalock);
1754 	phba->hba_flag &= ~DEFER_ERATT;
1755 	spin_unlock_irq(&phba->hbalock);
1756 	phba->work_status[0] = readl(phba->MBslimaddr + 0xa8);
1757 	phba->work_status[1] = readl(phba->MBslimaddr + 0xac);
1758 }
1759 
1760 static void
1761 lpfc_board_errevt_to_mgmt(struct lpfc_hba *phba)
1762 {
1763 	struct lpfc_board_event_header board_event;
1764 	struct Scsi_Host *shost;
1765 
1766 	board_event.event_type = FC_REG_BOARD_EVENT;
1767 	board_event.subcategory = LPFC_EVENT_PORTINTERR;
1768 	shost = lpfc_shost_from_vport(phba->pport);
1769 	fc_host_post_vendor_event(shost, fc_get_event_number(),
1770 				  sizeof(board_event),
1771 				  (char *) &board_event,
1772 				  LPFC_NL_VENDOR_ID);
1773 }
1774 
1775 /**
1776  * lpfc_handle_eratt_s3 - The SLI3 HBA hardware error handler
1777  * @phba: pointer to lpfc hba data structure.
1778  *
1779  * This routine is invoked to handle the following HBA hardware error
1780  * conditions:
1781  * 1 - HBA error attention interrupt
1782  * 2 - DMA ring index out of range
1783  * 3 - Mailbox command came back as unknown
1784  **/
1785 static void
1786 lpfc_handle_eratt_s3(struct lpfc_hba *phba)
1787 {
1788 	struct lpfc_vport *vport = phba->pport;
1789 	struct lpfc_sli   *psli = &phba->sli;
1790 	uint32_t event_data;
1791 	unsigned long temperature;
1792 	struct temp_event temp_event_data;
1793 	struct Scsi_Host  *shost;
1794 
1795 	/* If the pci channel is offline, ignore possible errors,
1796 	 * since we cannot communicate with the pci card anyway.
1797 	 */
1798 	if (pci_channel_offline(phba->pcidev)) {
1799 		spin_lock_irq(&phba->hbalock);
1800 		phba->hba_flag &= ~DEFER_ERATT;
1801 		spin_unlock_irq(&phba->hbalock);
1802 		return;
1803 	}
1804 
1805 	/* If resets are disabled then leave the HBA alone and return */
1806 	if (!phba->cfg_enable_hba_reset)
1807 		return;
1808 
1809 	/* Send an internal error event to mgmt application */
1810 	lpfc_board_errevt_to_mgmt(phba);
1811 
1812 	if (phba->hba_flag & DEFER_ERATT)
1813 		lpfc_handle_deferred_eratt(phba);
1814 
1815 	if ((phba->work_hs & HS_FFER6) || (phba->work_hs & HS_FFER8)) {
1816 		if (phba->work_hs & HS_FFER6)
1817 			/* Re-establishing Link */
1818 			lpfc_printf_log(phba, KERN_INFO, LOG_LINK_EVENT,
1819 					"1301 Re-establishing Link "
1820 					"Data: x%x x%x x%x\n",
1821 					phba->work_hs, phba->work_status[0],
1822 					phba->work_status[1]);
1823 		if (phba->work_hs & HS_FFER8)
1824 			/* Device Zeroization */
1825 			lpfc_printf_log(phba, KERN_INFO, LOG_LINK_EVENT,
1826 					"2861 Host Authentication device "
1827 					"zeroization Data:x%x x%x x%x\n",
1828 					phba->work_hs, phba->work_status[0],
1829 					phba->work_status[1]);
1830 
1831 		spin_lock_irq(&phba->hbalock);
1832 		psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1833 		spin_unlock_irq(&phba->hbalock);
1834 
1835 		/*
1836 		* Firmware stops when it triggled erratt with HS_FFER6.
1837 		* That could cause the I/Os dropped by the firmware.
1838 		* Error iocb (I/O) on txcmplq and let the SCSI layer
1839 		* retry it after re-establishing link.
1840 		*/
1841 		lpfc_sli_abort_fcp_rings(phba);
1842 
1843 		/*
1844 		 * There was a firmware error.  Take the hba offline and then
1845 		 * attempt to restart it.
1846 		 */
1847 		lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
1848 		lpfc_offline(phba);
1849 		lpfc_sli_brdrestart(phba);
1850 		if (lpfc_online(phba) == 0) {	/* Initialize the HBA */
1851 			lpfc_unblock_mgmt_io(phba);
1852 			return;
1853 		}
1854 		lpfc_unblock_mgmt_io(phba);
1855 	} else if (phba->work_hs & HS_CRIT_TEMP) {
1856 		temperature = readl(phba->MBslimaddr + TEMPERATURE_OFFSET);
1857 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
1858 		temp_event_data.event_code = LPFC_CRIT_TEMP;
1859 		temp_event_data.data = (uint32_t)temperature;
1860 
1861 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1862 				"0406 Adapter maximum temperature exceeded "
1863 				"(%ld), taking this port offline "
1864 				"Data: x%x x%x x%x\n",
1865 				temperature, phba->work_hs,
1866 				phba->work_status[0], phba->work_status[1]);
1867 
1868 		shost = lpfc_shost_from_vport(phba->pport);
1869 		fc_host_post_vendor_event(shost, fc_get_event_number(),
1870 					  sizeof(temp_event_data),
1871 					  (char *) &temp_event_data,
1872 					  SCSI_NL_VID_TYPE_PCI
1873 					  | PCI_VENDOR_ID_EMULEX);
1874 
1875 		spin_lock_irq(&phba->hbalock);
1876 		phba->over_temp_state = HBA_OVER_TEMP;
1877 		spin_unlock_irq(&phba->hbalock);
1878 		lpfc_offline_eratt(phba);
1879 
1880 	} else {
1881 		/* The if clause above forces this code path when the status
1882 		 * failure is a value other than FFER6. Do not call the offline
1883 		 * twice. This is the adapter hardware error path.
1884 		 */
1885 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1886 				"0457 Adapter Hardware Error "
1887 				"Data: x%x x%x x%x\n",
1888 				phba->work_hs,
1889 				phba->work_status[0], phba->work_status[1]);
1890 
1891 		event_data = FC_REG_DUMP_EVENT;
1892 		shost = lpfc_shost_from_vport(vport);
1893 		fc_host_post_vendor_event(shost, fc_get_event_number(),
1894 				sizeof(event_data), (char *) &event_data,
1895 				SCSI_NL_VID_TYPE_PCI | PCI_VENDOR_ID_EMULEX);
1896 
1897 		lpfc_offline_eratt(phba);
1898 	}
1899 	return;
1900 }
1901 
1902 /**
1903  * lpfc_sli4_port_sta_fn_reset - The SLI4 function reset due to port status reg
1904  * @phba: pointer to lpfc hba data structure.
1905  * @mbx_action: flag for mailbox shutdown action.
1906  * @en_rn_msg: send reset/port recovery message.
1907  * This routine is invoked to perform an SLI4 port PCI function reset in
1908  * response to port status register polling attention. It waits for port
1909  * status register (ERR, RDY, RN) bits before proceeding with function reset.
1910  * During this process, interrupt vectors are freed and later requested
1911  * for handling possible port resource change.
1912  **/
1913 static int
1914 lpfc_sli4_port_sta_fn_reset(struct lpfc_hba *phba, int mbx_action,
1915 			    bool en_rn_msg)
1916 {
1917 	int rc;
1918 	uint32_t intr_mode;
1919 	LPFC_MBOXQ_t *mboxq;
1920 
1921 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) >=
1922 	    LPFC_SLI_INTF_IF_TYPE_2) {
1923 		/*
1924 		 * On error status condition, driver need to wait for port
1925 		 * ready before performing reset.
1926 		 */
1927 		rc = lpfc_sli4_pdev_status_reg_wait(phba);
1928 		if (rc)
1929 			return rc;
1930 	}
1931 
1932 	/* need reset: attempt for port recovery */
1933 	if (en_rn_msg)
1934 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
1935 				"2887 Reset Needed: Attempting Port "
1936 				"Recovery...\n");
1937 
1938 	/* If we are no wait, the HBA has been reset and is not
1939 	 * functional, thus we should clear
1940 	 * (LPFC_SLI_ACTIVE | LPFC_SLI_MBOX_ACTIVE) flags.
1941 	 */
1942 	if (mbx_action == LPFC_MBX_NO_WAIT) {
1943 		spin_lock_irq(&phba->hbalock);
1944 		phba->sli.sli_flag &= ~LPFC_SLI_ACTIVE;
1945 		if (phba->sli.mbox_active) {
1946 			mboxq = phba->sli.mbox_active;
1947 			mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
1948 			__lpfc_mbox_cmpl_put(phba, mboxq);
1949 			phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
1950 			phba->sli.mbox_active = NULL;
1951 		}
1952 		spin_unlock_irq(&phba->hbalock);
1953 	}
1954 
1955 	lpfc_offline_prep(phba, mbx_action);
1956 	lpfc_sli_flush_io_rings(phba);
1957 	lpfc_offline(phba);
1958 	/* release interrupt for possible resource change */
1959 	lpfc_sli4_disable_intr(phba);
1960 	rc = lpfc_sli_brdrestart(phba);
1961 	if (rc) {
1962 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1963 				"6309 Failed to restart board\n");
1964 		return rc;
1965 	}
1966 	/* request and enable interrupt */
1967 	intr_mode = lpfc_sli4_enable_intr(phba, phba->intr_mode);
1968 	if (intr_mode == LPFC_INTR_ERROR) {
1969 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1970 				"3175 Failed to enable interrupt\n");
1971 		return -EIO;
1972 	}
1973 	phba->intr_mode = intr_mode;
1974 	rc = lpfc_online(phba);
1975 	if (rc == 0)
1976 		lpfc_unblock_mgmt_io(phba);
1977 
1978 	return rc;
1979 }
1980 
1981 /**
1982  * lpfc_handle_eratt_s4 - The SLI4 HBA hardware error handler
1983  * @phba: pointer to lpfc hba data structure.
1984  *
1985  * This routine is invoked to handle the SLI4 HBA hardware error attention
1986  * conditions.
1987  **/
1988 static void
1989 lpfc_handle_eratt_s4(struct lpfc_hba *phba)
1990 {
1991 	struct lpfc_vport *vport = phba->pport;
1992 	uint32_t event_data;
1993 	struct Scsi_Host *shost;
1994 	uint32_t if_type;
1995 	struct lpfc_register portstat_reg = {0};
1996 	uint32_t reg_err1, reg_err2;
1997 	uint32_t uerrlo_reg, uemasklo_reg;
1998 	uint32_t smphr_port_status = 0, pci_rd_rc1, pci_rd_rc2;
1999 	bool en_rn_msg = true;
2000 	struct temp_event temp_event_data;
2001 	struct lpfc_register portsmphr_reg;
2002 	int rc, i;
2003 
2004 	/* If the pci channel is offline, ignore possible errors, since
2005 	 * we cannot communicate with the pci card anyway.
2006 	 */
2007 	if (pci_channel_offline(phba->pcidev)) {
2008 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2009 				"3166 pci channel is offline\n");
2010 		lpfc_sli_flush_io_rings(phba);
2011 		return;
2012 	}
2013 
2014 	memset(&portsmphr_reg, 0, sizeof(portsmphr_reg));
2015 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
2016 	switch (if_type) {
2017 	case LPFC_SLI_INTF_IF_TYPE_0:
2018 		pci_rd_rc1 = lpfc_readl(
2019 				phba->sli4_hba.u.if_type0.UERRLOregaddr,
2020 				&uerrlo_reg);
2021 		pci_rd_rc2 = lpfc_readl(
2022 				phba->sli4_hba.u.if_type0.UEMASKLOregaddr,
2023 				&uemasklo_reg);
2024 		/* consider PCI bus read error as pci_channel_offline */
2025 		if (pci_rd_rc1 == -EIO && pci_rd_rc2 == -EIO)
2026 			return;
2027 		if (!(phba->hba_flag & HBA_RECOVERABLE_UE)) {
2028 			lpfc_sli4_offline_eratt(phba);
2029 			return;
2030 		}
2031 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2032 				"7623 Checking UE recoverable");
2033 
2034 		for (i = 0; i < phba->sli4_hba.ue_to_sr / 1000; i++) {
2035 			if (lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
2036 				       &portsmphr_reg.word0))
2037 				continue;
2038 
2039 			smphr_port_status = bf_get(lpfc_port_smphr_port_status,
2040 						   &portsmphr_reg);
2041 			if ((smphr_port_status & LPFC_PORT_SEM_MASK) ==
2042 			    LPFC_PORT_SEM_UE_RECOVERABLE)
2043 				break;
2044 			/*Sleep for 1Sec, before checking SEMAPHORE */
2045 			msleep(1000);
2046 		}
2047 
2048 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2049 				"4827 smphr_port_status x%x : Waited %dSec",
2050 				smphr_port_status, i);
2051 
2052 		/* Recoverable UE, reset the HBA device */
2053 		if ((smphr_port_status & LPFC_PORT_SEM_MASK) ==
2054 		    LPFC_PORT_SEM_UE_RECOVERABLE) {
2055 			for (i = 0; i < 20; i++) {
2056 				msleep(1000);
2057 				if (!lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
2058 				    &portsmphr_reg.word0) &&
2059 				    (LPFC_POST_STAGE_PORT_READY ==
2060 				     bf_get(lpfc_port_smphr_port_status,
2061 				     &portsmphr_reg))) {
2062 					rc = lpfc_sli4_port_sta_fn_reset(phba,
2063 						LPFC_MBX_NO_WAIT, en_rn_msg);
2064 					if (rc == 0)
2065 						return;
2066 					lpfc_printf_log(phba, KERN_ERR,
2067 						LOG_TRACE_EVENT,
2068 						"4215 Failed to recover UE");
2069 					break;
2070 				}
2071 			}
2072 		}
2073 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2074 				"7624 Firmware not ready: Failing UE recovery,"
2075 				" waited %dSec", i);
2076 		phba->link_state = LPFC_HBA_ERROR;
2077 		break;
2078 
2079 	case LPFC_SLI_INTF_IF_TYPE_2:
2080 	case LPFC_SLI_INTF_IF_TYPE_6:
2081 		pci_rd_rc1 = lpfc_readl(
2082 				phba->sli4_hba.u.if_type2.STATUSregaddr,
2083 				&portstat_reg.word0);
2084 		/* consider PCI bus read error as pci_channel_offline */
2085 		if (pci_rd_rc1 == -EIO) {
2086 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2087 				"3151 PCI bus read access failure: x%x\n",
2088 				readl(phba->sli4_hba.u.if_type2.STATUSregaddr));
2089 			lpfc_sli4_offline_eratt(phba);
2090 			return;
2091 		}
2092 		reg_err1 = readl(phba->sli4_hba.u.if_type2.ERR1regaddr);
2093 		reg_err2 = readl(phba->sli4_hba.u.if_type2.ERR2regaddr);
2094 		if (bf_get(lpfc_sliport_status_oti, &portstat_reg)) {
2095 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2096 					"2889 Port Overtemperature event, "
2097 					"taking port offline Data: x%x x%x\n",
2098 					reg_err1, reg_err2);
2099 
2100 			phba->sfp_alarm |= LPFC_TRANSGRESSION_HIGH_TEMPERATURE;
2101 			temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
2102 			temp_event_data.event_code = LPFC_CRIT_TEMP;
2103 			temp_event_data.data = 0xFFFFFFFF;
2104 
2105 			shost = lpfc_shost_from_vport(phba->pport);
2106 			fc_host_post_vendor_event(shost, fc_get_event_number(),
2107 						  sizeof(temp_event_data),
2108 						  (char *)&temp_event_data,
2109 						  SCSI_NL_VID_TYPE_PCI
2110 						  | PCI_VENDOR_ID_EMULEX);
2111 
2112 			spin_lock_irq(&phba->hbalock);
2113 			phba->over_temp_state = HBA_OVER_TEMP;
2114 			spin_unlock_irq(&phba->hbalock);
2115 			lpfc_sli4_offline_eratt(phba);
2116 			return;
2117 		}
2118 		if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2119 		    reg_err2 == SLIPORT_ERR2_REG_FW_RESTART) {
2120 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2121 					"3143 Port Down: Firmware Update "
2122 					"Detected\n");
2123 			en_rn_msg = false;
2124 		} else if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2125 			 reg_err2 == SLIPORT_ERR2_REG_FORCED_DUMP)
2126 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2127 					"3144 Port Down: Debug Dump\n");
2128 		else if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2129 			 reg_err2 == SLIPORT_ERR2_REG_FUNC_PROVISON)
2130 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2131 					"3145 Port Down: Provisioning\n");
2132 
2133 		/* If resets are disabled then leave the HBA alone and return */
2134 		if (!phba->cfg_enable_hba_reset)
2135 			return;
2136 
2137 		/* Check port status register for function reset */
2138 		rc = lpfc_sli4_port_sta_fn_reset(phba, LPFC_MBX_NO_WAIT,
2139 				en_rn_msg);
2140 		if (rc == 0) {
2141 			/* don't report event on forced debug dump */
2142 			if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2143 			    reg_err2 == SLIPORT_ERR2_REG_FORCED_DUMP)
2144 				return;
2145 			else
2146 				break;
2147 		}
2148 		/* fall through for not able to recover */
2149 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2150 				"3152 Unrecoverable error\n");
2151 		phba->link_state = LPFC_HBA_ERROR;
2152 		break;
2153 	case LPFC_SLI_INTF_IF_TYPE_1:
2154 	default:
2155 		break;
2156 	}
2157 	lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
2158 			"3123 Report dump event to upper layer\n");
2159 	/* Send an internal error event to mgmt application */
2160 	lpfc_board_errevt_to_mgmt(phba);
2161 
2162 	event_data = FC_REG_DUMP_EVENT;
2163 	shost = lpfc_shost_from_vport(vport);
2164 	fc_host_post_vendor_event(shost, fc_get_event_number(),
2165 				  sizeof(event_data), (char *) &event_data,
2166 				  SCSI_NL_VID_TYPE_PCI | PCI_VENDOR_ID_EMULEX);
2167 }
2168 
2169 /**
2170  * lpfc_handle_eratt - Wrapper func for handling hba error attention
2171  * @phba: pointer to lpfc HBA data structure.
2172  *
2173  * This routine wraps the actual SLI3 or SLI4 hba error attention handling
2174  * routine from the API jump table function pointer from the lpfc_hba struct.
2175  *
2176  * Return codes
2177  *   0 - success.
2178  *   Any other value - error.
2179  **/
2180 void
2181 lpfc_handle_eratt(struct lpfc_hba *phba)
2182 {
2183 	(*phba->lpfc_handle_eratt)(phba);
2184 }
2185 
2186 /**
2187  * lpfc_handle_latt - The HBA link event handler
2188  * @phba: pointer to lpfc hba data structure.
2189  *
2190  * This routine is invoked from the worker thread to handle a HBA host
2191  * attention link event. SLI3 only.
2192  **/
2193 void
2194 lpfc_handle_latt(struct lpfc_hba *phba)
2195 {
2196 	struct lpfc_vport *vport = phba->pport;
2197 	struct lpfc_sli   *psli = &phba->sli;
2198 	LPFC_MBOXQ_t *pmb;
2199 	volatile uint32_t control;
2200 	int rc = 0;
2201 
2202 	pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
2203 	if (!pmb) {
2204 		rc = 1;
2205 		goto lpfc_handle_latt_err_exit;
2206 	}
2207 
2208 	rc = lpfc_mbox_rsrc_prep(phba, pmb);
2209 	if (rc) {
2210 		rc = 2;
2211 		mempool_free(pmb, phba->mbox_mem_pool);
2212 		goto lpfc_handle_latt_err_exit;
2213 	}
2214 
2215 	/* Cleanup any outstanding ELS commands */
2216 	lpfc_els_flush_all_cmd(phba);
2217 	psli->slistat.link_event++;
2218 	lpfc_read_topology(phba, pmb, (struct lpfc_dmabuf *)pmb->ctx_buf);
2219 	pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
2220 	pmb->vport = vport;
2221 	/* Block ELS IOCBs until we have processed this mbox command */
2222 	phba->sli.sli3_ring[LPFC_ELS_RING].flag |= LPFC_STOP_IOCB_EVENT;
2223 	rc = lpfc_sli_issue_mbox (phba, pmb, MBX_NOWAIT);
2224 	if (rc == MBX_NOT_FINISHED) {
2225 		rc = 4;
2226 		goto lpfc_handle_latt_free_mbuf;
2227 	}
2228 
2229 	/* Clear Link Attention in HA REG */
2230 	spin_lock_irq(&phba->hbalock);
2231 	writel(HA_LATT, phba->HAregaddr);
2232 	readl(phba->HAregaddr); /* flush */
2233 	spin_unlock_irq(&phba->hbalock);
2234 
2235 	return;
2236 
2237 lpfc_handle_latt_free_mbuf:
2238 	phba->sli.sli3_ring[LPFC_ELS_RING].flag &= ~LPFC_STOP_IOCB_EVENT;
2239 	lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
2240 lpfc_handle_latt_err_exit:
2241 	/* Enable Link attention interrupts */
2242 	spin_lock_irq(&phba->hbalock);
2243 	psli->sli_flag |= LPFC_PROCESS_LA;
2244 	control = readl(phba->HCregaddr);
2245 	control |= HC_LAINT_ENA;
2246 	writel(control, phba->HCregaddr);
2247 	readl(phba->HCregaddr); /* flush */
2248 
2249 	/* Clear Link Attention in HA REG */
2250 	writel(HA_LATT, phba->HAregaddr);
2251 	readl(phba->HAregaddr); /* flush */
2252 	spin_unlock_irq(&phba->hbalock);
2253 	lpfc_linkdown(phba);
2254 	phba->link_state = LPFC_HBA_ERROR;
2255 
2256 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2257 			"0300 LATT: Cannot issue READ_LA: Data:%d\n", rc);
2258 
2259 	return;
2260 }
2261 
2262 static void
2263 lpfc_fill_vpd(struct lpfc_hba *phba, uint8_t *vpd, int length, int *pindex)
2264 {
2265 	int i, j;
2266 
2267 	while (length > 0) {
2268 		/* Look for Serial Number */
2269 		if ((vpd[*pindex] == 'S') && (vpd[*pindex + 1] == 'N')) {
2270 			*pindex += 2;
2271 			i = vpd[*pindex];
2272 			*pindex += 1;
2273 			j = 0;
2274 			length -= (3+i);
2275 			while (i--) {
2276 				phba->SerialNumber[j++] = vpd[(*pindex)++];
2277 				if (j == 31)
2278 					break;
2279 			}
2280 			phba->SerialNumber[j] = 0;
2281 			continue;
2282 		} else if ((vpd[*pindex] == 'V') && (vpd[*pindex + 1] == '1')) {
2283 			phba->vpd_flag |= VPD_MODEL_DESC;
2284 			*pindex += 2;
2285 			i = vpd[*pindex];
2286 			*pindex += 1;
2287 			j = 0;
2288 			length -= (3+i);
2289 			while (i--) {
2290 				phba->ModelDesc[j++] = vpd[(*pindex)++];
2291 				if (j == 255)
2292 					break;
2293 			}
2294 			phba->ModelDesc[j] = 0;
2295 			continue;
2296 		} else if ((vpd[*pindex] == 'V') && (vpd[*pindex + 1] == '2')) {
2297 			phba->vpd_flag |= VPD_MODEL_NAME;
2298 			*pindex += 2;
2299 			i = vpd[*pindex];
2300 			*pindex += 1;
2301 			j = 0;
2302 			length -= (3+i);
2303 			while (i--) {
2304 				phba->ModelName[j++] = vpd[(*pindex)++];
2305 				if (j == 79)
2306 					break;
2307 			}
2308 			phba->ModelName[j] = 0;
2309 			continue;
2310 		} else if ((vpd[*pindex] == 'V') && (vpd[*pindex + 1] == '3')) {
2311 			phba->vpd_flag |= VPD_PROGRAM_TYPE;
2312 			*pindex += 2;
2313 			i = vpd[*pindex];
2314 			*pindex += 1;
2315 			j = 0;
2316 			length -= (3+i);
2317 			while (i--) {
2318 				phba->ProgramType[j++] = vpd[(*pindex)++];
2319 				if (j == 255)
2320 					break;
2321 			}
2322 			phba->ProgramType[j] = 0;
2323 			continue;
2324 		} else if ((vpd[*pindex] == 'V') && (vpd[*pindex + 1] == '4')) {
2325 			phba->vpd_flag |= VPD_PORT;
2326 			*pindex += 2;
2327 			i = vpd[*pindex];
2328 			*pindex += 1;
2329 			j = 0;
2330 			length -= (3 + i);
2331 			while (i--) {
2332 				if ((phba->sli_rev == LPFC_SLI_REV4) &&
2333 				    (phba->sli4_hba.pport_name_sta ==
2334 				     LPFC_SLI4_PPNAME_GET)) {
2335 					j++;
2336 					(*pindex)++;
2337 				} else
2338 					phba->Port[j++] = vpd[(*pindex)++];
2339 				if (j == 19)
2340 					break;
2341 			}
2342 			if ((phba->sli_rev != LPFC_SLI_REV4) ||
2343 			    (phba->sli4_hba.pport_name_sta ==
2344 			     LPFC_SLI4_PPNAME_NON))
2345 				phba->Port[j] = 0;
2346 			continue;
2347 		} else {
2348 			*pindex += 2;
2349 			i = vpd[*pindex];
2350 			*pindex += 1;
2351 			*pindex += i;
2352 			length -= (3 + i);
2353 		}
2354 	}
2355 }
2356 
2357 /**
2358  * lpfc_parse_vpd - Parse VPD (Vital Product Data)
2359  * @phba: pointer to lpfc hba data structure.
2360  * @vpd: pointer to the vital product data.
2361  * @len: length of the vital product data in bytes.
2362  *
2363  * This routine parses the Vital Product Data (VPD). The VPD is treated as
2364  * an array of characters. In this routine, the ModelName, ProgramType, and
2365  * ModelDesc, etc. fields of the phba data structure will be populated.
2366  *
2367  * Return codes
2368  *   0 - pointer to the VPD passed in is NULL
2369  *   1 - success
2370  **/
2371 int
2372 lpfc_parse_vpd(struct lpfc_hba *phba, uint8_t *vpd, int len)
2373 {
2374 	uint8_t lenlo, lenhi;
2375 	int Length;
2376 	int i;
2377 	int finished = 0;
2378 	int index = 0;
2379 
2380 	if (!vpd)
2381 		return 0;
2382 
2383 	/* Vital Product */
2384 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
2385 			"0455 Vital Product Data: x%x x%x x%x x%x\n",
2386 			(uint32_t) vpd[0], (uint32_t) vpd[1], (uint32_t) vpd[2],
2387 			(uint32_t) vpd[3]);
2388 	while (!finished && (index < (len - 4))) {
2389 		switch (vpd[index]) {
2390 		case 0x82:
2391 		case 0x91:
2392 			index += 1;
2393 			lenlo = vpd[index];
2394 			index += 1;
2395 			lenhi = vpd[index];
2396 			index += 1;
2397 			i = ((((unsigned short)lenhi) << 8) + lenlo);
2398 			index += i;
2399 			break;
2400 		case 0x90:
2401 			index += 1;
2402 			lenlo = vpd[index];
2403 			index += 1;
2404 			lenhi = vpd[index];
2405 			index += 1;
2406 			Length = ((((unsigned short)lenhi) << 8) + lenlo);
2407 			if (Length > len - index)
2408 				Length = len - index;
2409 
2410 			lpfc_fill_vpd(phba, vpd, Length, &index);
2411 			finished = 0;
2412 			break;
2413 		case 0x78:
2414 			finished = 1;
2415 			break;
2416 		default:
2417 			index ++;
2418 			break;
2419 		}
2420 	}
2421 
2422 	return(1);
2423 }
2424 
2425 /**
2426  * lpfc_get_atto_model_desc - Retrieve ATTO HBA device model name and description
2427  * @phba: pointer to lpfc hba data structure.
2428  * @mdp: pointer to the data structure to hold the derived model name.
2429  * @descp: pointer to the data structure to hold the derived description.
2430  *
2431  * This routine retrieves HBA's description based on its registered PCI device
2432  * ID. The @descp passed into this function points to an array of 256 chars. It
2433  * shall be returned with the model name, maximum speed, and the host bus type.
2434  * The @mdp passed into this function points to an array of 80 chars. When the
2435  * function returns, the @mdp will be filled with the model name.
2436  **/
2437 static void
2438 lpfc_get_atto_model_desc(struct lpfc_hba *phba, uint8_t *mdp, uint8_t *descp)
2439 {
2440 	uint16_t sub_dev_id = phba->pcidev->subsystem_device;
2441 	char *model = "<Unknown>";
2442 	int tbolt = 0;
2443 
2444 	switch (sub_dev_id) {
2445 	case PCI_DEVICE_ID_CLRY_161E:
2446 		model = "161E";
2447 		break;
2448 	case PCI_DEVICE_ID_CLRY_162E:
2449 		model = "162E";
2450 		break;
2451 	case PCI_DEVICE_ID_CLRY_164E:
2452 		model = "164E";
2453 		break;
2454 	case PCI_DEVICE_ID_CLRY_161P:
2455 		model = "161P";
2456 		break;
2457 	case PCI_DEVICE_ID_CLRY_162P:
2458 		model = "162P";
2459 		break;
2460 	case PCI_DEVICE_ID_CLRY_164P:
2461 		model = "164P";
2462 		break;
2463 	case PCI_DEVICE_ID_CLRY_321E:
2464 		model = "321E";
2465 		break;
2466 	case PCI_DEVICE_ID_CLRY_322E:
2467 		model = "322E";
2468 		break;
2469 	case PCI_DEVICE_ID_CLRY_324E:
2470 		model = "324E";
2471 		break;
2472 	case PCI_DEVICE_ID_CLRY_321P:
2473 		model = "321P";
2474 		break;
2475 	case PCI_DEVICE_ID_CLRY_322P:
2476 		model = "322P";
2477 		break;
2478 	case PCI_DEVICE_ID_CLRY_324P:
2479 		model = "324P";
2480 		break;
2481 	case PCI_DEVICE_ID_TLFC_2XX2:
2482 		model = "2XX2";
2483 		tbolt = 1;
2484 		break;
2485 	case PCI_DEVICE_ID_TLFC_3162:
2486 		model = "3162";
2487 		tbolt = 1;
2488 		break;
2489 	case PCI_DEVICE_ID_TLFC_3322:
2490 		model = "3322";
2491 		tbolt = 1;
2492 		break;
2493 	default:
2494 		model = "Unknown";
2495 		break;
2496 	}
2497 
2498 	if (mdp && mdp[0] == '\0')
2499 		snprintf(mdp, 79, "%s", model);
2500 
2501 	if (descp && descp[0] == '\0')
2502 		snprintf(descp, 255,
2503 			 "ATTO %s%s, Fibre Channel Adapter Initiator, Port %s",
2504 			 (tbolt) ? "ThunderLink FC " : "Celerity FC-",
2505 			 model,
2506 			 phba->Port);
2507 }
2508 
2509 /**
2510  * lpfc_get_hba_model_desc - Retrieve HBA device model name and description
2511  * @phba: pointer to lpfc hba data structure.
2512  * @mdp: pointer to the data structure to hold the derived model name.
2513  * @descp: pointer to the data structure to hold the derived description.
2514  *
2515  * This routine retrieves HBA's description based on its registered PCI device
2516  * ID. The @descp passed into this function points to an array of 256 chars. It
2517  * shall be returned with the model name, maximum speed, and the host bus type.
2518  * The @mdp passed into this function points to an array of 80 chars. When the
2519  * function returns, the @mdp will be filled with the model name.
2520  **/
2521 static void
2522 lpfc_get_hba_model_desc(struct lpfc_hba *phba, uint8_t *mdp, uint8_t *descp)
2523 {
2524 	lpfc_vpd_t *vp;
2525 	uint16_t dev_id = phba->pcidev->device;
2526 	int max_speed;
2527 	int GE = 0;
2528 	int oneConnect = 0; /* default is not a oneConnect */
2529 	struct {
2530 		char *name;
2531 		char *bus;
2532 		char *function;
2533 	} m = {"<Unknown>", "", ""};
2534 
2535 	if (mdp && mdp[0] != '\0'
2536 		&& descp && descp[0] != '\0')
2537 		return;
2538 
2539 	if (phba->pcidev->vendor == PCI_VENDOR_ID_ATTO) {
2540 		lpfc_get_atto_model_desc(phba, mdp, descp);
2541 		return;
2542 	}
2543 
2544 	if (phba->lmt & LMT_64Gb)
2545 		max_speed = 64;
2546 	else if (phba->lmt & LMT_32Gb)
2547 		max_speed = 32;
2548 	else if (phba->lmt & LMT_16Gb)
2549 		max_speed = 16;
2550 	else if (phba->lmt & LMT_10Gb)
2551 		max_speed = 10;
2552 	else if (phba->lmt & LMT_8Gb)
2553 		max_speed = 8;
2554 	else if (phba->lmt & LMT_4Gb)
2555 		max_speed = 4;
2556 	else if (phba->lmt & LMT_2Gb)
2557 		max_speed = 2;
2558 	else if (phba->lmt & LMT_1Gb)
2559 		max_speed = 1;
2560 	else
2561 		max_speed = 0;
2562 
2563 	vp = &phba->vpd;
2564 
2565 	switch (dev_id) {
2566 	case PCI_DEVICE_ID_FIREFLY:
2567 		m = (typeof(m)){"LP6000", "PCI",
2568 				"Obsolete, Unsupported Fibre Channel Adapter"};
2569 		break;
2570 	case PCI_DEVICE_ID_SUPERFLY:
2571 		if (vp->rev.biuRev >= 1 && vp->rev.biuRev <= 3)
2572 			m = (typeof(m)){"LP7000", "PCI", ""};
2573 		else
2574 			m = (typeof(m)){"LP7000E", "PCI", ""};
2575 		m.function = "Obsolete, Unsupported Fibre Channel Adapter";
2576 		break;
2577 	case PCI_DEVICE_ID_DRAGONFLY:
2578 		m = (typeof(m)){"LP8000", "PCI",
2579 				"Obsolete, Unsupported Fibre Channel Adapter"};
2580 		break;
2581 	case PCI_DEVICE_ID_CENTAUR:
2582 		if (FC_JEDEC_ID(vp->rev.biuRev) == CENTAUR_2G_JEDEC_ID)
2583 			m = (typeof(m)){"LP9002", "PCI", ""};
2584 		else
2585 			m = (typeof(m)){"LP9000", "PCI", ""};
2586 		m.function = "Obsolete, Unsupported Fibre Channel Adapter";
2587 		break;
2588 	case PCI_DEVICE_ID_RFLY:
2589 		m = (typeof(m)){"LP952", "PCI",
2590 				"Obsolete, Unsupported Fibre Channel Adapter"};
2591 		break;
2592 	case PCI_DEVICE_ID_PEGASUS:
2593 		m = (typeof(m)){"LP9802", "PCI-X",
2594 				"Obsolete, Unsupported Fibre Channel Adapter"};
2595 		break;
2596 	case PCI_DEVICE_ID_THOR:
2597 		m = (typeof(m)){"LP10000", "PCI-X",
2598 				"Obsolete, Unsupported Fibre Channel Adapter"};
2599 		break;
2600 	case PCI_DEVICE_ID_VIPER:
2601 		m = (typeof(m)){"LPX1000",  "PCI-X",
2602 				"Obsolete, Unsupported Fibre Channel Adapter"};
2603 		break;
2604 	case PCI_DEVICE_ID_PFLY:
2605 		m = (typeof(m)){"LP982", "PCI-X",
2606 				"Obsolete, Unsupported Fibre Channel Adapter"};
2607 		break;
2608 	case PCI_DEVICE_ID_TFLY:
2609 		m = (typeof(m)){"LP1050", "PCI-X",
2610 				"Obsolete, Unsupported Fibre Channel Adapter"};
2611 		break;
2612 	case PCI_DEVICE_ID_HELIOS:
2613 		m = (typeof(m)){"LP11000", "PCI-X2",
2614 				"Obsolete, Unsupported Fibre Channel Adapter"};
2615 		break;
2616 	case PCI_DEVICE_ID_HELIOS_SCSP:
2617 		m = (typeof(m)){"LP11000-SP", "PCI-X2",
2618 				"Obsolete, Unsupported Fibre Channel Adapter"};
2619 		break;
2620 	case PCI_DEVICE_ID_HELIOS_DCSP:
2621 		m = (typeof(m)){"LP11002-SP",  "PCI-X2",
2622 				"Obsolete, Unsupported Fibre Channel Adapter"};
2623 		break;
2624 	case PCI_DEVICE_ID_NEPTUNE:
2625 		m = (typeof(m)){"LPe1000", "PCIe",
2626 				"Obsolete, Unsupported Fibre Channel Adapter"};
2627 		break;
2628 	case PCI_DEVICE_ID_NEPTUNE_SCSP:
2629 		m = (typeof(m)){"LPe1000-SP", "PCIe",
2630 				"Obsolete, Unsupported Fibre Channel Adapter"};
2631 		break;
2632 	case PCI_DEVICE_ID_NEPTUNE_DCSP:
2633 		m = (typeof(m)){"LPe1002-SP", "PCIe",
2634 				"Obsolete, Unsupported Fibre Channel Adapter"};
2635 		break;
2636 	case PCI_DEVICE_ID_BMID:
2637 		m = (typeof(m)){"LP1150", "PCI-X2", "Fibre Channel Adapter"};
2638 		break;
2639 	case PCI_DEVICE_ID_BSMB:
2640 		m = (typeof(m)){"LP111", "PCI-X2",
2641 				"Obsolete, Unsupported Fibre Channel Adapter"};
2642 		break;
2643 	case PCI_DEVICE_ID_ZEPHYR:
2644 		m = (typeof(m)){"LPe11000", "PCIe", "Fibre Channel Adapter"};
2645 		break;
2646 	case PCI_DEVICE_ID_ZEPHYR_SCSP:
2647 		m = (typeof(m)){"LPe11000", "PCIe", "Fibre Channel Adapter"};
2648 		break;
2649 	case PCI_DEVICE_ID_ZEPHYR_DCSP:
2650 		m = (typeof(m)){"LP2105", "PCIe", "FCoE Adapter"};
2651 		GE = 1;
2652 		break;
2653 	case PCI_DEVICE_ID_ZMID:
2654 		m = (typeof(m)){"LPe1150", "PCIe", "Fibre Channel Adapter"};
2655 		break;
2656 	case PCI_DEVICE_ID_ZSMB:
2657 		m = (typeof(m)){"LPe111", "PCIe", "Fibre Channel Adapter"};
2658 		break;
2659 	case PCI_DEVICE_ID_LP101:
2660 		m = (typeof(m)){"LP101", "PCI-X",
2661 				"Obsolete, Unsupported Fibre Channel Adapter"};
2662 		break;
2663 	case PCI_DEVICE_ID_LP10000S:
2664 		m = (typeof(m)){"LP10000-S", "PCI",
2665 				"Obsolete, Unsupported Fibre Channel Adapter"};
2666 		break;
2667 	case PCI_DEVICE_ID_LP11000S:
2668 		m = (typeof(m)){"LP11000-S", "PCI-X2",
2669 				"Obsolete, Unsupported Fibre Channel Adapter"};
2670 		break;
2671 	case PCI_DEVICE_ID_LPE11000S:
2672 		m = (typeof(m)){"LPe11000-S", "PCIe",
2673 				"Obsolete, Unsupported Fibre Channel Adapter"};
2674 		break;
2675 	case PCI_DEVICE_ID_SAT:
2676 		m = (typeof(m)){"LPe12000", "PCIe", "Fibre Channel Adapter"};
2677 		break;
2678 	case PCI_DEVICE_ID_SAT_MID:
2679 		m = (typeof(m)){"LPe1250", "PCIe", "Fibre Channel Adapter"};
2680 		break;
2681 	case PCI_DEVICE_ID_SAT_SMB:
2682 		m = (typeof(m)){"LPe121", "PCIe", "Fibre Channel Adapter"};
2683 		break;
2684 	case PCI_DEVICE_ID_SAT_DCSP:
2685 		m = (typeof(m)){"LPe12002-SP", "PCIe", "Fibre Channel Adapter"};
2686 		break;
2687 	case PCI_DEVICE_ID_SAT_SCSP:
2688 		m = (typeof(m)){"LPe12000-SP", "PCIe", "Fibre Channel Adapter"};
2689 		break;
2690 	case PCI_DEVICE_ID_SAT_S:
2691 		m = (typeof(m)){"LPe12000-S", "PCIe", "Fibre Channel Adapter"};
2692 		break;
2693 	case PCI_DEVICE_ID_PROTEUS_VF:
2694 		m = (typeof(m)){"LPev12000", "PCIe IOV",
2695 				"Obsolete, Unsupported Fibre Channel Adapter"};
2696 		break;
2697 	case PCI_DEVICE_ID_PROTEUS_PF:
2698 		m = (typeof(m)){"LPev12000", "PCIe IOV",
2699 				"Obsolete, Unsupported Fibre Channel Adapter"};
2700 		break;
2701 	case PCI_DEVICE_ID_PROTEUS_S:
2702 		m = (typeof(m)){"LPemv12002-S", "PCIe IOV",
2703 				"Obsolete, Unsupported Fibre Channel Adapter"};
2704 		break;
2705 	case PCI_DEVICE_ID_TIGERSHARK:
2706 		oneConnect = 1;
2707 		m = (typeof(m)){"OCe10100", "PCIe", "FCoE"};
2708 		break;
2709 	case PCI_DEVICE_ID_TOMCAT:
2710 		oneConnect = 1;
2711 		m = (typeof(m)){"OCe11100", "PCIe", "FCoE"};
2712 		break;
2713 	case PCI_DEVICE_ID_FALCON:
2714 		m = (typeof(m)){"LPSe12002-ML1-E", "PCIe",
2715 				"EmulexSecure Fibre"};
2716 		break;
2717 	case PCI_DEVICE_ID_BALIUS:
2718 		m = (typeof(m)){"LPVe12002", "PCIe Shared I/O",
2719 				"Obsolete, Unsupported Fibre Channel Adapter"};
2720 		break;
2721 	case PCI_DEVICE_ID_LANCER_FC:
2722 		m = (typeof(m)){"LPe16000", "PCIe", "Fibre Channel Adapter"};
2723 		break;
2724 	case PCI_DEVICE_ID_LANCER_FC_VF:
2725 		m = (typeof(m)){"LPe16000", "PCIe",
2726 				"Obsolete, Unsupported Fibre Channel Adapter"};
2727 		break;
2728 	case PCI_DEVICE_ID_LANCER_FCOE:
2729 		oneConnect = 1;
2730 		m = (typeof(m)){"OCe15100", "PCIe", "FCoE"};
2731 		break;
2732 	case PCI_DEVICE_ID_LANCER_FCOE_VF:
2733 		oneConnect = 1;
2734 		m = (typeof(m)){"OCe15100", "PCIe",
2735 				"Obsolete, Unsupported FCoE"};
2736 		break;
2737 	case PCI_DEVICE_ID_LANCER_G6_FC:
2738 		m = (typeof(m)){"LPe32000", "PCIe", "Fibre Channel Adapter"};
2739 		break;
2740 	case PCI_DEVICE_ID_LANCER_G7_FC:
2741 		m = (typeof(m)){"LPe36000", "PCIe", "Fibre Channel Adapter"};
2742 		break;
2743 	case PCI_DEVICE_ID_LANCER_G7P_FC:
2744 		m = (typeof(m)){"LPe38000", "PCIe", "Fibre Channel Adapter"};
2745 		break;
2746 	case PCI_DEVICE_ID_SKYHAWK:
2747 	case PCI_DEVICE_ID_SKYHAWK_VF:
2748 		oneConnect = 1;
2749 		m = (typeof(m)){"OCe14000", "PCIe", "FCoE"};
2750 		break;
2751 	default:
2752 		m = (typeof(m)){"Unknown", "", ""};
2753 		break;
2754 	}
2755 
2756 	if (mdp && mdp[0] == '\0')
2757 		snprintf(mdp, 79,"%s", m.name);
2758 	/*
2759 	 * oneConnect hba requires special processing, they are all initiators
2760 	 * and we put the port number on the end
2761 	 */
2762 	if (descp && descp[0] == '\0') {
2763 		if (oneConnect)
2764 			snprintf(descp, 255,
2765 				"Emulex OneConnect %s, %s Initiator %s",
2766 				m.name, m.function,
2767 				phba->Port);
2768 		else if (max_speed == 0)
2769 			snprintf(descp, 255,
2770 				"Emulex %s %s %s",
2771 				m.name, m.bus, m.function);
2772 		else
2773 			snprintf(descp, 255,
2774 				"Emulex %s %d%s %s %s",
2775 				m.name, max_speed, (GE) ? "GE" : "Gb",
2776 				m.bus, m.function);
2777 	}
2778 }
2779 
2780 /**
2781  * lpfc_sli3_post_buffer - Post IOCB(s) with DMA buffer descriptor(s) to a IOCB ring
2782  * @phba: pointer to lpfc hba data structure.
2783  * @pring: pointer to a IOCB ring.
2784  * @cnt: the number of IOCBs to be posted to the IOCB ring.
2785  *
2786  * This routine posts a given number of IOCBs with the associated DMA buffer
2787  * descriptors specified by the cnt argument to the given IOCB ring.
2788  *
2789  * Return codes
2790  *   The number of IOCBs NOT able to be posted to the IOCB ring.
2791  **/
2792 int
2793 lpfc_sli3_post_buffer(struct lpfc_hba *phba, struct lpfc_sli_ring *pring, int cnt)
2794 {
2795 	IOCB_t *icmd;
2796 	struct lpfc_iocbq *iocb;
2797 	struct lpfc_dmabuf *mp1, *mp2;
2798 
2799 	cnt += pring->missbufcnt;
2800 
2801 	/* While there are buffers to post */
2802 	while (cnt > 0) {
2803 		/* Allocate buffer for  command iocb */
2804 		iocb = lpfc_sli_get_iocbq(phba);
2805 		if (iocb == NULL) {
2806 			pring->missbufcnt = cnt;
2807 			return cnt;
2808 		}
2809 		icmd = &iocb->iocb;
2810 
2811 		/* 2 buffers can be posted per command */
2812 		/* Allocate buffer to post */
2813 		mp1 = kmalloc(sizeof (struct lpfc_dmabuf), GFP_KERNEL);
2814 		if (mp1)
2815 		    mp1->virt = lpfc_mbuf_alloc(phba, MEM_PRI, &mp1->phys);
2816 		if (!mp1 || !mp1->virt) {
2817 			kfree(mp1);
2818 			lpfc_sli_release_iocbq(phba, iocb);
2819 			pring->missbufcnt = cnt;
2820 			return cnt;
2821 		}
2822 
2823 		INIT_LIST_HEAD(&mp1->list);
2824 		/* Allocate buffer to post */
2825 		if (cnt > 1) {
2826 			mp2 = kmalloc(sizeof (struct lpfc_dmabuf), GFP_KERNEL);
2827 			if (mp2)
2828 				mp2->virt = lpfc_mbuf_alloc(phba, MEM_PRI,
2829 							    &mp2->phys);
2830 			if (!mp2 || !mp2->virt) {
2831 				kfree(mp2);
2832 				lpfc_mbuf_free(phba, mp1->virt, mp1->phys);
2833 				kfree(mp1);
2834 				lpfc_sli_release_iocbq(phba, iocb);
2835 				pring->missbufcnt = cnt;
2836 				return cnt;
2837 			}
2838 
2839 			INIT_LIST_HEAD(&mp2->list);
2840 		} else {
2841 			mp2 = NULL;
2842 		}
2843 
2844 		icmd->un.cont64[0].addrHigh = putPaddrHigh(mp1->phys);
2845 		icmd->un.cont64[0].addrLow = putPaddrLow(mp1->phys);
2846 		icmd->un.cont64[0].tus.f.bdeSize = FCELSSIZE;
2847 		icmd->ulpBdeCount = 1;
2848 		cnt--;
2849 		if (mp2) {
2850 			icmd->un.cont64[1].addrHigh = putPaddrHigh(mp2->phys);
2851 			icmd->un.cont64[1].addrLow = putPaddrLow(mp2->phys);
2852 			icmd->un.cont64[1].tus.f.bdeSize = FCELSSIZE;
2853 			cnt--;
2854 			icmd->ulpBdeCount = 2;
2855 		}
2856 
2857 		icmd->ulpCommand = CMD_QUE_RING_BUF64_CN;
2858 		icmd->ulpLe = 1;
2859 
2860 		if (lpfc_sli_issue_iocb(phba, pring->ringno, iocb, 0) ==
2861 		    IOCB_ERROR) {
2862 			lpfc_mbuf_free(phba, mp1->virt, mp1->phys);
2863 			kfree(mp1);
2864 			cnt++;
2865 			if (mp2) {
2866 				lpfc_mbuf_free(phba, mp2->virt, mp2->phys);
2867 				kfree(mp2);
2868 				cnt++;
2869 			}
2870 			lpfc_sli_release_iocbq(phba, iocb);
2871 			pring->missbufcnt = cnt;
2872 			return cnt;
2873 		}
2874 		lpfc_sli_ringpostbuf_put(phba, pring, mp1);
2875 		if (mp2)
2876 			lpfc_sli_ringpostbuf_put(phba, pring, mp2);
2877 	}
2878 	pring->missbufcnt = 0;
2879 	return 0;
2880 }
2881 
2882 /**
2883  * lpfc_post_rcv_buf - Post the initial receive IOCB buffers to ELS ring
2884  * @phba: pointer to lpfc hba data structure.
2885  *
2886  * This routine posts initial receive IOCB buffers to the ELS ring. The
2887  * current number of initial IOCB buffers specified by LPFC_BUF_RING0 is
2888  * set to 64 IOCBs. SLI3 only.
2889  *
2890  * Return codes
2891  *   0 - success (currently always success)
2892  **/
2893 static int
2894 lpfc_post_rcv_buf(struct lpfc_hba *phba)
2895 {
2896 	struct lpfc_sli *psli = &phba->sli;
2897 
2898 	/* Ring 0, ELS / CT buffers */
2899 	lpfc_sli3_post_buffer(phba, &psli->sli3_ring[LPFC_ELS_RING], LPFC_BUF_RING0);
2900 	/* Ring 2 - FCP no buffers needed */
2901 
2902 	return 0;
2903 }
2904 
2905 #define S(N,V) (((V)<<(N))|((V)>>(32-(N))))
2906 
2907 /**
2908  * lpfc_sha_init - Set up initial array of hash table entries
2909  * @HashResultPointer: pointer to an array as hash table.
2910  *
2911  * This routine sets up the initial values to the array of hash table entries
2912  * for the LC HBAs.
2913  **/
2914 static void
2915 lpfc_sha_init(uint32_t * HashResultPointer)
2916 {
2917 	HashResultPointer[0] = 0x67452301;
2918 	HashResultPointer[1] = 0xEFCDAB89;
2919 	HashResultPointer[2] = 0x98BADCFE;
2920 	HashResultPointer[3] = 0x10325476;
2921 	HashResultPointer[4] = 0xC3D2E1F0;
2922 }
2923 
2924 /**
2925  * lpfc_sha_iterate - Iterate initial hash table with the working hash table
2926  * @HashResultPointer: pointer to an initial/result hash table.
2927  * @HashWorkingPointer: pointer to an working hash table.
2928  *
2929  * This routine iterates an initial hash table pointed by @HashResultPointer
2930  * with the values from the working hash table pointeed by @HashWorkingPointer.
2931  * The results are putting back to the initial hash table, returned through
2932  * the @HashResultPointer as the result hash table.
2933  **/
2934 static void
2935 lpfc_sha_iterate(uint32_t * HashResultPointer, uint32_t * HashWorkingPointer)
2936 {
2937 	int t;
2938 	uint32_t TEMP;
2939 	uint32_t A, B, C, D, E;
2940 	t = 16;
2941 	do {
2942 		HashWorkingPointer[t] =
2943 		    S(1,
2944 		      HashWorkingPointer[t - 3] ^ HashWorkingPointer[t -
2945 								     8] ^
2946 		      HashWorkingPointer[t - 14] ^ HashWorkingPointer[t - 16]);
2947 	} while (++t <= 79);
2948 	t = 0;
2949 	A = HashResultPointer[0];
2950 	B = HashResultPointer[1];
2951 	C = HashResultPointer[2];
2952 	D = HashResultPointer[3];
2953 	E = HashResultPointer[4];
2954 
2955 	do {
2956 		if (t < 20) {
2957 			TEMP = ((B & C) | ((~B) & D)) + 0x5A827999;
2958 		} else if (t < 40) {
2959 			TEMP = (B ^ C ^ D) + 0x6ED9EBA1;
2960 		} else if (t < 60) {
2961 			TEMP = ((B & C) | (B & D) | (C & D)) + 0x8F1BBCDC;
2962 		} else {
2963 			TEMP = (B ^ C ^ D) + 0xCA62C1D6;
2964 		}
2965 		TEMP += S(5, A) + E + HashWorkingPointer[t];
2966 		E = D;
2967 		D = C;
2968 		C = S(30, B);
2969 		B = A;
2970 		A = TEMP;
2971 	} while (++t <= 79);
2972 
2973 	HashResultPointer[0] += A;
2974 	HashResultPointer[1] += B;
2975 	HashResultPointer[2] += C;
2976 	HashResultPointer[3] += D;
2977 	HashResultPointer[4] += E;
2978 
2979 }
2980 
2981 /**
2982  * lpfc_challenge_key - Create challenge key based on WWPN of the HBA
2983  * @RandomChallenge: pointer to the entry of host challenge random number array.
2984  * @HashWorking: pointer to the entry of the working hash array.
2985  *
2986  * This routine calculates the working hash array referred by @HashWorking
2987  * from the challenge random numbers associated with the host, referred by
2988  * @RandomChallenge. The result is put into the entry of the working hash
2989  * array and returned by reference through @HashWorking.
2990  **/
2991 static void
2992 lpfc_challenge_key(uint32_t * RandomChallenge, uint32_t * HashWorking)
2993 {
2994 	*HashWorking = (*RandomChallenge ^ *HashWorking);
2995 }
2996 
2997 /**
2998  * lpfc_hba_init - Perform special handling for LC HBA initialization
2999  * @phba: pointer to lpfc hba data structure.
3000  * @hbainit: pointer to an array of unsigned 32-bit integers.
3001  *
3002  * This routine performs the special handling for LC HBA initialization.
3003  **/
3004 void
3005 lpfc_hba_init(struct lpfc_hba *phba, uint32_t *hbainit)
3006 {
3007 	int t;
3008 	uint32_t *HashWorking;
3009 	uint32_t *pwwnn = (uint32_t *) phba->wwnn;
3010 
3011 	HashWorking = kcalloc(80, sizeof(uint32_t), GFP_KERNEL);
3012 	if (!HashWorking)
3013 		return;
3014 
3015 	HashWorking[0] = HashWorking[78] = *pwwnn++;
3016 	HashWorking[1] = HashWorking[79] = *pwwnn;
3017 
3018 	for (t = 0; t < 7; t++)
3019 		lpfc_challenge_key(phba->RandomData + t, HashWorking + t);
3020 
3021 	lpfc_sha_init(hbainit);
3022 	lpfc_sha_iterate(hbainit, HashWorking);
3023 	kfree(HashWorking);
3024 }
3025 
3026 /**
3027  * lpfc_cleanup - Performs vport cleanups before deleting a vport
3028  * @vport: pointer to a virtual N_Port data structure.
3029  *
3030  * This routine performs the necessary cleanups before deleting the @vport.
3031  * It invokes the discovery state machine to perform necessary state
3032  * transitions and to release the ndlps associated with the @vport. Note,
3033  * the physical port is treated as @vport 0.
3034  **/
3035 void
3036 lpfc_cleanup(struct lpfc_vport *vport)
3037 {
3038 	struct lpfc_hba   *phba = vport->phba;
3039 	struct lpfc_nodelist *ndlp, *next_ndlp;
3040 	int i = 0;
3041 
3042 	if (phba->link_state > LPFC_LINK_DOWN)
3043 		lpfc_port_link_failure(vport);
3044 
3045 	/* Clean up VMID resources */
3046 	if (lpfc_is_vmid_enabled(phba))
3047 		lpfc_vmid_vport_cleanup(vport);
3048 
3049 	list_for_each_entry_safe(ndlp, next_ndlp, &vport->fc_nodes, nlp_listp) {
3050 		if (vport->port_type != LPFC_PHYSICAL_PORT &&
3051 		    ndlp->nlp_DID == Fabric_DID) {
3052 			/* Just free up ndlp with Fabric_DID for vports */
3053 			lpfc_nlp_put(ndlp);
3054 			continue;
3055 		}
3056 
3057 		if (ndlp->nlp_DID == Fabric_Cntl_DID &&
3058 		    ndlp->nlp_state == NLP_STE_UNUSED_NODE) {
3059 			lpfc_nlp_put(ndlp);
3060 			continue;
3061 		}
3062 
3063 		/* Fabric Ports not in UNMAPPED state are cleaned up in the
3064 		 * DEVICE_RM event.
3065 		 */
3066 		if (ndlp->nlp_type & NLP_FABRIC &&
3067 		    ndlp->nlp_state == NLP_STE_UNMAPPED_NODE)
3068 			lpfc_disc_state_machine(vport, ndlp, NULL,
3069 					NLP_EVT_DEVICE_RECOVERY);
3070 
3071 		if (!(ndlp->fc4_xpt_flags & (NVME_XPT_REGD|SCSI_XPT_REGD)))
3072 			lpfc_disc_state_machine(vport, ndlp, NULL,
3073 					NLP_EVT_DEVICE_RM);
3074 	}
3075 
3076 	/* This is a special case flush to return all
3077 	 * IOs before entering this loop. There are
3078 	 * two points in the code where a flush is
3079 	 * avoided if the FC_UNLOADING flag is set.
3080 	 * one is in the multipool destroy,
3081 	 * (this prevents a crash) and the other is
3082 	 * in the nvme abort handler, ( also prevents
3083 	 * a crash). Both of these exceptions are
3084 	 * cases where the slot is still accessible.
3085 	 * The flush here is only when the pci slot
3086 	 * is offline.
3087 	 */
3088 	if (vport->load_flag & FC_UNLOADING &&
3089 	    pci_channel_offline(phba->pcidev))
3090 		lpfc_sli_flush_io_rings(vport->phba);
3091 
3092 	/* At this point, ALL ndlp's should be gone
3093 	 * because of the previous NLP_EVT_DEVICE_RM.
3094 	 * Lets wait for this to happen, if needed.
3095 	 */
3096 	while (!list_empty(&vport->fc_nodes)) {
3097 		if (i++ > 3000) {
3098 			lpfc_printf_vlog(vport, KERN_ERR,
3099 					 LOG_TRACE_EVENT,
3100 				"0233 Nodelist not empty\n");
3101 			list_for_each_entry_safe(ndlp, next_ndlp,
3102 						&vport->fc_nodes, nlp_listp) {
3103 				lpfc_printf_vlog(ndlp->vport, KERN_ERR,
3104 						 LOG_DISCOVERY,
3105 						 "0282 did:x%x ndlp:x%px "
3106 						 "refcnt:%d xflags x%x nflag x%x\n",
3107 						 ndlp->nlp_DID, (void *)ndlp,
3108 						 kref_read(&ndlp->kref),
3109 						 ndlp->fc4_xpt_flags,
3110 						 ndlp->nlp_flag);
3111 			}
3112 			break;
3113 		}
3114 
3115 		/* Wait for any activity on ndlps to settle */
3116 		msleep(10);
3117 	}
3118 	lpfc_cleanup_vports_rrqs(vport, NULL);
3119 }
3120 
3121 /**
3122  * lpfc_stop_vport_timers - Stop all the timers associated with a vport
3123  * @vport: pointer to a virtual N_Port data structure.
3124  *
3125  * This routine stops all the timers associated with a @vport. This function
3126  * is invoked before disabling or deleting a @vport. Note that the physical
3127  * port is treated as @vport 0.
3128  **/
3129 void
3130 lpfc_stop_vport_timers(struct lpfc_vport *vport)
3131 {
3132 	del_timer_sync(&vport->els_tmofunc);
3133 	del_timer_sync(&vport->delayed_disc_tmo);
3134 	lpfc_can_disctmo(vport);
3135 	return;
3136 }
3137 
3138 /**
3139  * __lpfc_sli4_stop_fcf_redisc_wait_timer - Stop FCF rediscovery wait timer
3140  * @phba: pointer to lpfc hba data structure.
3141  *
3142  * This routine stops the SLI4 FCF rediscover wait timer if it's on. The
3143  * caller of this routine should already hold the host lock.
3144  **/
3145 void
3146 __lpfc_sli4_stop_fcf_redisc_wait_timer(struct lpfc_hba *phba)
3147 {
3148 	/* Clear pending FCF rediscovery wait flag */
3149 	phba->fcf.fcf_flag &= ~FCF_REDISC_PEND;
3150 
3151 	/* Now, try to stop the timer */
3152 	del_timer(&phba->fcf.redisc_wait);
3153 }
3154 
3155 /**
3156  * lpfc_sli4_stop_fcf_redisc_wait_timer - Stop FCF rediscovery wait timer
3157  * @phba: pointer to lpfc hba data structure.
3158  *
3159  * This routine stops the SLI4 FCF rediscover wait timer if it's on. It
3160  * checks whether the FCF rediscovery wait timer is pending with the host
3161  * lock held before proceeding with disabling the timer and clearing the
3162  * wait timer pendig flag.
3163  **/
3164 void
3165 lpfc_sli4_stop_fcf_redisc_wait_timer(struct lpfc_hba *phba)
3166 {
3167 	spin_lock_irq(&phba->hbalock);
3168 	if (!(phba->fcf.fcf_flag & FCF_REDISC_PEND)) {
3169 		/* FCF rediscovery timer already fired or stopped */
3170 		spin_unlock_irq(&phba->hbalock);
3171 		return;
3172 	}
3173 	__lpfc_sli4_stop_fcf_redisc_wait_timer(phba);
3174 	/* Clear failover in progress flags */
3175 	phba->fcf.fcf_flag &= ~(FCF_DEAD_DISC | FCF_ACVL_DISC);
3176 	spin_unlock_irq(&phba->hbalock);
3177 }
3178 
3179 /**
3180  * lpfc_cmf_stop - Stop CMF processing
3181  * @phba: pointer to lpfc hba data structure.
3182  *
3183  * This is called when the link goes down or if CMF mode is turned OFF.
3184  * It is also called when going offline or unloaded just before the
3185  * congestion info buffer is unregistered.
3186  **/
3187 void
3188 lpfc_cmf_stop(struct lpfc_hba *phba)
3189 {
3190 	int cpu;
3191 	struct lpfc_cgn_stat *cgs;
3192 
3193 	/* We only do something if CMF is enabled */
3194 	if (!phba->sli4_hba.pc_sli4_params.cmf)
3195 		return;
3196 
3197 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
3198 			"6221 Stop CMF / Cancel Timer\n");
3199 
3200 	/* Cancel the CMF timer */
3201 	hrtimer_cancel(&phba->cmf_timer);
3202 
3203 	/* Zero CMF counters */
3204 	atomic_set(&phba->cmf_busy, 0);
3205 	for_each_present_cpu(cpu) {
3206 		cgs = per_cpu_ptr(phba->cmf_stat, cpu);
3207 		atomic64_set(&cgs->total_bytes, 0);
3208 		atomic64_set(&cgs->rcv_bytes, 0);
3209 		atomic_set(&cgs->rx_io_cnt, 0);
3210 		atomic64_set(&cgs->rx_latency, 0);
3211 	}
3212 	atomic_set(&phba->cmf_bw_wait, 0);
3213 
3214 	/* Resume any blocked IO - Queue unblock on workqueue */
3215 	queue_work(phba->wq, &phba->unblock_request_work);
3216 }
3217 
3218 static inline uint64_t
3219 lpfc_get_max_line_rate(struct lpfc_hba *phba)
3220 {
3221 	uint64_t rate = lpfc_sli_port_speed_get(phba);
3222 
3223 	return ((((unsigned long)rate) * 1024 * 1024) / 10);
3224 }
3225 
3226 void
3227 lpfc_cmf_signal_init(struct lpfc_hba *phba)
3228 {
3229 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
3230 			"6223 Signal CMF init\n");
3231 
3232 	/* Use the new fc_linkspeed to recalculate */
3233 	phba->cmf_interval_rate = LPFC_CMF_INTERVAL;
3234 	phba->cmf_max_line_rate = lpfc_get_max_line_rate(phba);
3235 	phba->cmf_link_byte_count = div_u64(phba->cmf_max_line_rate *
3236 					    phba->cmf_interval_rate, 1000);
3237 	phba->cmf_max_bytes_per_interval = phba->cmf_link_byte_count;
3238 
3239 	/* This is a signal to firmware to sync up CMF BW with link speed */
3240 	lpfc_issue_cmf_sync_wqe(phba, 0, 0);
3241 }
3242 
3243 /**
3244  * lpfc_cmf_start - Start CMF processing
3245  * @phba: pointer to lpfc hba data structure.
3246  *
3247  * This is called when the link comes up or if CMF mode is turned OFF
3248  * to Monitor or Managed.
3249  **/
3250 void
3251 lpfc_cmf_start(struct lpfc_hba *phba)
3252 {
3253 	struct lpfc_cgn_stat *cgs;
3254 	int cpu;
3255 
3256 	/* We only do something if CMF is enabled */
3257 	if (!phba->sli4_hba.pc_sli4_params.cmf ||
3258 	    phba->cmf_active_mode == LPFC_CFG_OFF)
3259 		return;
3260 
3261 	/* Reinitialize congestion buffer info */
3262 	lpfc_init_congestion_buf(phba);
3263 
3264 	atomic_set(&phba->cgn_fabric_warn_cnt, 0);
3265 	atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
3266 	atomic_set(&phba->cgn_sync_alarm_cnt, 0);
3267 	atomic_set(&phba->cgn_sync_warn_cnt, 0);
3268 
3269 	atomic_set(&phba->cmf_busy, 0);
3270 	for_each_present_cpu(cpu) {
3271 		cgs = per_cpu_ptr(phba->cmf_stat, cpu);
3272 		atomic64_set(&cgs->total_bytes, 0);
3273 		atomic64_set(&cgs->rcv_bytes, 0);
3274 		atomic_set(&cgs->rx_io_cnt, 0);
3275 		atomic64_set(&cgs->rx_latency, 0);
3276 	}
3277 	phba->cmf_latency.tv_sec = 0;
3278 	phba->cmf_latency.tv_nsec = 0;
3279 
3280 	lpfc_cmf_signal_init(phba);
3281 
3282 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
3283 			"6222 Start CMF / Timer\n");
3284 
3285 	phba->cmf_timer_cnt = 0;
3286 	hrtimer_start(&phba->cmf_timer,
3287 		      ktime_set(0, LPFC_CMF_INTERVAL * 1000000),
3288 		      HRTIMER_MODE_REL);
3289 	/* Setup for latency check in IO cmpl routines */
3290 	ktime_get_real_ts64(&phba->cmf_latency);
3291 
3292 	atomic_set(&phba->cmf_bw_wait, 0);
3293 	atomic_set(&phba->cmf_stop_io, 0);
3294 }
3295 
3296 /**
3297  * lpfc_stop_hba_timers - Stop all the timers associated with an HBA
3298  * @phba: pointer to lpfc hba data structure.
3299  *
3300  * This routine stops all the timers associated with a HBA. This function is
3301  * invoked before either putting a HBA offline or unloading the driver.
3302  **/
3303 void
3304 lpfc_stop_hba_timers(struct lpfc_hba *phba)
3305 {
3306 	if (phba->pport)
3307 		lpfc_stop_vport_timers(phba->pport);
3308 	cancel_delayed_work_sync(&phba->eq_delay_work);
3309 	cancel_delayed_work_sync(&phba->idle_stat_delay_work);
3310 	del_timer_sync(&phba->sli.mbox_tmo);
3311 	del_timer_sync(&phba->fabric_block_timer);
3312 	del_timer_sync(&phba->eratt_poll);
3313 	del_timer_sync(&phba->hb_tmofunc);
3314 	if (phba->sli_rev == LPFC_SLI_REV4) {
3315 		del_timer_sync(&phba->rrq_tmr);
3316 		phba->hba_flag &= ~HBA_RRQ_ACTIVE;
3317 	}
3318 	phba->hba_flag &= ~(HBA_HBEAT_INP | HBA_HBEAT_TMO);
3319 
3320 	switch (phba->pci_dev_grp) {
3321 	case LPFC_PCI_DEV_LP:
3322 		/* Stop any LightPulse device specific driver timers */
3323 		del_timer_sync(&phba->fcp_poll_timer);
3324 		break;
3325 	case LPFC_PCI_DEV_OC:
3326 		/* Stop any OneConnect device specific driver timers */
3327 		lpfc_sli4_stop_fcf_redisc_wait_timer(phba);
3328 		break;
3329 	default:
3330 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3331 				"0297 Invalid device group (x%x)\n",
3332 				phba->pci_dev_grp);
3333 		break;
3334 	}
3335 	return;
3336 }
3337 
3338 /**
3339  * lpfc_block_mgmt_io - Mark a HBA's management interface as blocked
3340  * @phba: pointer to lpfc hba data structure.
3341  * @mbx_action: flag for mailbox no wait action.
3342  *
3343  * This routine marks a HBA's management interface as blocked. Once the HBA's
3344  * management interface is marked as blocked, all the user space access to
3345  * the HBA, whether they are from sysfs interface or libdfc interface will
3346  * all be blocked. The HBA is set to block the management interface when the
3347  * driver prepares the HBA interface for online or offline.
3348  **/
3349 static void
3350 lpfc_block_mgmt_io(struct lpfc_hba *phba, int mbx_action)
3351 {
3352 	unsigned long iflag;
3353 	uint8_t actcmd = MBX_HEARTBEAT;
3354 	unsigned long timeout;
3355 
3356 	spin_lock_irqsave(&phba->hbalock, iflag);
3357 	phba->sli.sli_flag |= LPFC_BLOCK_MGMT_IO;
3358 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3359 	if (mbx_action == LPFC_MBX_NO_WAIT)
3360 		return;
3361 	timeout = msecs_to_jiffies(LPFC_MBOX_TMO * 1000) + jiffies;
3362 	spin_lock_irqsave(&phba->hbalock, iflag);
3363 	if (phba->sli.mbox_active) {
3364 		actcmd = phba->sli.mbox_active->u.mb.mbxCommand;
3365 		/* Determine how long we might wait for the active mailbox
3366 		 * command to be gracefully completed by firmware.
3367 		 */
3368 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
3369 				phba->sli.mbox_active) * 1000) + jiffies;
3370 	}
3371 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3372 
3373 	/* Wait for the outstnading mailbox command to complete */
3374 	while (phba->sli.mbox_active) {
3375 		/* Check active mailbox complete status every 2ms */
3376 		msleep(2);
3377 		if (time_after(jiffies, timeout)) {
3378 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3379 					"2813 Mgmt IO is Blocked %x "
3380 					"- mbox cmd %x still active\n",
3381 					phba->sli.sli_flag, actcmd);
3382 			break;
3383 		}
3384 	}
3385 }
3386 
3387 /**
3388  * lpfc_sli4_node_prep - Assign RPIs for active nodes.
3389  * @phba: pointer to lpfc hba data structure.
3390  *
3391  * Allocate RPIs for all active remote nodes. This is needed whenever
3392  * an SLI4 adapter is reset and the driver is not unloading. Its purpose
3393  * is to fixup the temporary rpi assignments.
3394  **/
3395 void
3396 lpfc_sli4_node_prep(struct lpfc_hba *phba)
3397 {
3398 	struct lpfc_nodelist  *ndlp, *next_ndlp;
3399 	struct lpfc_vport **vports;
3400 	int i, rpi;
3401 
3402 	if (phba->sli_rev != LPFC_SLI_REV4)
3403 		return;
3404 
3405 	vports = lpfc_create_vport_work_array(phba);
3406 	if (vports == NULL)
3407 		return;
3408 
3409 	for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3410 		if (vports[i]->load_flag & FC_UNLOADING)
3411 			continue;
3412 
3413 		list_for_each_entry_safe(ndlp, next_ndlp,
3414 					 &vports[i]->fc_nodes,
3415 					 nlp_listp) {
3416 			rpi = lpfc_sli4_alloc_rpi(phba);
3417 			if (rpi == LPFC_RPI_ALLOC_ERROR) {
3418 				/* TODO print log? */
3419 				continue;
3420 			}
3421 			ndlp->nlp_rpi = rpi;
3422 			lpfc_printf_vlog(ndlp->vport, KERN_INFO,
3423 					 LOG_NODE | LOG_DISCOVERY,
3424 					 "0009 Assign RPI x%x to ndlp x%px "
3425 					 "DID:x%06x flg:x%x\n",
3426 					 ndlp->nlp_rpi, ndlp, ndlp->nlp_DID,
3427 					 ndlp->nlp_flag);
3428 		}
3429 	}
3430 	lpfc_destroy_vport_work_array(phba, vports);
3431 }
3432 
3433 /**
3434  * lpfc_create_expedite_pool - create expedite pool
3435  * @phba: pointer to lpfc hba data structure.
3436  *
3437  * This routine moves a batch of XRIs from lpfc_io_buf_list_put of HWQ 0
3438  * to expedite pool. Mark them as expedite.
3439  **/
3440 static void lpfc_create_expedite_pool(struct lpfc_hba *phba)
3441 {
3442 	struct lpfc_sli4_hdw_queue *qp;
3443 	struct lpfc_io_buf *lpfc_ncmd;
3444 	struct lpfc_io_buf *lpfc_ncmd_next;
3445 	struct lpfc_epd_pool *epd_pool;
3446 	unsigned long iflag;
3447 
3448 	epd_pool = &phba->epd_pool;
3449 	qp = &phba->sli4_hba.hdwq[0];
3450 
3451 	spin_lock_init(&epd_pool->lock);
3452 	spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3453 	spin_lock(&epd_pool->lock);
3454 	INIT_LIST_HEAD(&epd_pool->list);
3455 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3456 				 &qp->lpfc_io_buf_list_put, list) {
3457 		list_move_tail(&lpfc_ncmd->list, &epd_pool->list);
3458 		lpfc_ncmd->expedite = true;
3459 		qp->put_io_bufs--;
3460 		epd_pool->count++;
3461 		if (epd_pool->count >= XRI_BATCH)
3462 			break;
3463 	}
3464 	spin_unlock(&epd_pool->lock);
3465 	spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3466 }
3467 
3468 /**
3469  * lpfc_destroy_expedite_pool - destroy expedite pool
3470  * @phba: pointer to lpfc hba data structure.
3471  *
3472  * This routine returns XRIs from expedite pool to lpfc_io_buf_list_put
3473  * of HWQ 0. Clear the mark.
3474  **/
3475 static void lpfc_destroy_expedite_pool(struct lpfc_hba *phba)
3476 {
3477 	struct lpfc_sli4_hdw_queue *qp;
3478 	struct lpfc_io_buf *lpfc_ncmd;
3479 	struct lpfc_io_buf *lpfc_ncmd_next;
3480 	struct lpfc_epd_pool *epd_pool;
3481 	unsigned long iflag;
3482 
3483 	epd_pool = &phba->epd_pool;
3484 	qp = &phba->sli4_hba.hdwq[0];
3485 
3486 	spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3487 	spin_lock(&epd_pool->lock);
3488 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3489 				 &epd_pool->list, list) {
3490 		list_move_tail(&lpfc_ncmd->list,
3491 			       &qp->lpfc_io_buf_list_put);
3492 		lpfc_ncmd->flags = false;
3493 		qp->put_io_bufs++;
3494 		epd_pool->count--;
3495 	}
3496 	spin_unlock(&epd_pool->lock);
3497 	spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3498 }
3499 
3500 /**
3501  * lpfc_create_multixri_pools - create multi-XRI pools
3502  * @phba: pointer to lpfc hba data structure.
3503  *
3504  * This routine initialize public, private per HWQ. Then, move XRIs from
3505  * lpfc_io_buf_list_put to public pool. High and low watermark are also
3506  * Initialized.
3507  **/
3508 void lpfc_create_multixri_pools(struct lpfc_hba *phba)
3509 {
3510 	u32 i, j;
3511 	u32 hwq_count;
3512 	u32 count_per_hwq;
3513 	struct lpfc_io_buf *lpfc_ncmd;
3514 	struct lpfc_io_buf *lpfc_ncmd_next;
3515 	unsigned long iflag;
3516 	struct lpfc_sli4_hdw_queue *qp;
3517 	struct lpfc_multixri_pool *multixri_pool;
3518 	struct lpfc_pbl_pool *pbl_pool;
3519 	struct lpfc_pvt_pool *pvt_pool;
3520 
3521 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3522 			"1234 num_hdw_queue=%d num_present_cpu=%d common_xri_cnt=%d\n",
3523 			phba->cfg_hdw_queue, phba->sli4_hba.num_present_cpu,
3524 			phba->sli4_hba.io_xri_cnt);
3525 
3526 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
3527 		lpfc_create_expedite_pool(phba);
3528 
3529 	hwq_count = phba->cfg_hdw_queue;
3530 	count_per_hwq = phba->sli4_hba.io_xri_cnt / hwq_count;
3531 
3532 	for (i = 0; i < hwq_count; i++) {
3533 		multixri_pool = kzalloc(sizeof(*multixri_pool), GFP_KERNEL);
3534 
3535 		if (!multixri_pool) {
3536 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3537 					"1238 Failed to allocate memory for "
3538 					"multixri_pool\n");
3539 
3540 			if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
3541 				lpfc_destroy_expedite_pool(phba);
3542 
3543 			j = 0;
3544 			while (j < i) {
3545 				qp = &phba->sli4_hba.hdwq[j];
3546 				kfree(qp->p_multixri_pool);
3547 				j++;
3548 			}
3549 			phba->cfg_xri_rebalancing = 0;
3550 			return;
3551 		}
3552 
3553 		qp = &phba->sli4_hba.hdwq[i];
3554 		qp->p_multixri_pool = multixri_pool;
3555 
3556 		multixri_pool->xri_limit = count_per_hwq;
3557 		multixri_pool->rrb_next_hwqid = i;
3558 
3559 		/* Deal with public free xri pool */
3560 		pbl_pool = &multixri_pool->pbl_pool;
3561 		spin_lock_init(&pbl_pool->lock);
3562 		spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3563 		spin_lock(&pbl_pool->lock);
3564 		INIT_LIST_HEAD(&pbl_pool->list);
3565 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3566 					 &qp->lpfc_io_buf_list_put, list) {
3567 			list_move_tail(&lpfc_ncmd->list, &pbl_pool->list);
3568 			qp->put_io_bufs--;
3569 			pbl_pool->count++;
3570 		}
3571 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3572 				"1235 Moved %d buffers from PUT list over to pbl_pool[%d]\n",
3573 				pbl_pool->count, i);
3574 		spin_unlock(&pbl_pool->lock);
3575 		spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3576 
3577 		/* Deal with private free xri pool */
3578 		pvt_pool = &multixri_pool->pvt_pool;
3579 		pvt_pool->high_watermark = multixri_pool->xri_limit / 2;
3580 		pvt_pool->low_watermark = XRI_BATCH;
3581 		spin_lock_init(&pvt_pool->lock);
3582 		spin_lock_irqsave(&pvt_pool->lock, iflag);
3583 		INIT_LIST_HEAD(&pvt_pool->list);
3584 		pvt_pool->count = 0;
3585 		spin_unlock_irqrestore(&pvt_pool->lock, iflag);
3586 	}
3587 }
3588 
3589 /**
3590  * lpfc_destroy_multixri_pools - destroy multi-XRI pools
3591  * @phba: pointer to lpfc hba data structure.
3592  *
3593  * This routine returns XRIs from public/private to lpfc_io_buf_list_put.
3594  **/
3595 static void lpfc_destroy_multixri_pools(struct lpfc_hba *phba)
3596 {
3597 	u32 i;
3598 	u32 hwq_count;
3599 	struct lpfc_io_buf *lpfc_ncmd;
3600 	struct lpfc_io_buf *lpfc_ncmd_next;
3601 	unsigned long iflag;
3602 	struct lpfc_sli4_hdw_queue *qp;
3603 	struct lpfc_multixri_pool *multixri_pool;
3604 	struct lpfc_pbl_pool *pbl_pool;
3605 	struct lpfc_pvt_pool *pvt_pool;
3606 
3607 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
3608 		lpfc_destroy_expedite_pool(phba);
3609 
3610 	if (!(phba->pport->load_flag & FC_UNLOADING))
3611 		lpfc_sli_flush_io_rings(phba);
3612 
3613 	hwq_count = phba->cfg_hdw_queue;
3614 
3615 	for (i = 0; i < hwq_count; i++) {
3616 		qp = &phba->sli4_hba.hdwq[i];
3617 		multixri_pool = qp->p_multixri_pool;
3618 		if (!multixri_pool)
3619 			continue;
3620 
3621 		qp->p_multixri_pool = NULL;
3622 
3623 		spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3624 
3625 		/* Deal with public free xri pool */
3626 		pbl_pool = &multixri_pool->pbl_pool;
3627 		spin_lock(&pbl_pool->lock);
3628 
3629 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3630 				"1236 Moving %d buffers from pbl_pool[%d] TO PUT list\n",
3631 				pbl_pool->count, i);
3632 
3633 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3634 					 &pbl_pool->list, list) {
3635 			list_move_tail(&lpfc_ncmd->list,
3636 				       &qp->lpfc_io_buf_list_put);
3637 			qp->put_io_bufs++;
3638 			pbl_pool->count--;
3639 		}
3640 
3641 		INIT_LIST_HEAD(&pbl_pool->list);
3642 		pbl_pool->count = 0;
3643 
3644 		spin_unlock(&pbl_pool->lock);
3645 
3646 		/* Deal with private free xri pool */
3647 		pvt_pool = &multixri_pool->pvt_pool;
3648 		spin_lock(&pvt_pool->lock);
3649 
3650 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3651 				"1237 Moving %d buffers from pvt_pool[%d] TO PUT list\n",
3652 				pvt_pool->count, i);
3653 
3654 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3655 					 &pvt_pool->list, list) {
3656 			list_move_tail(&lpfc_ncmd->list,
3657 				       &qp->lpfc_io_buf_list_put);
3658 			qp->put_io_bufs++;
3659 			pvt_pool->count--;
3660 		}
3661 
3662 		INIT_LIST_HEAD(&pvt_pool->list);
3663 		pvt_pool->count = 0;
3664 
3665 		spin_unlock(&pvt_pool->lock);
3666 		spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3667 
3668 		kfree(multixri_pool);
3669 	}
3670 }
3671 
3672 /**
3673  * lpfc_online - Initialize and bring a HBA online
3674  * @phba: pointer to lpfc hba data structure.
3675  *
3676  * This routine initializes the HBA and brings a HBA online. During this
3677  * process, the management interface is blocked to prevent user space access
3678  * to the HBA interfering with the driver initialization.
3679  *
3680  * Return codes
3681  *   0 - successful
3682  *   1 - failed
3683  **/
3684 int
3685 lpfc_online(struct lpfc_hba *phba)
3686 {
3687 	struct lpfc_vport *vport;
3688 	struct lpfc_vport **vports;
3689 	int i, error = 0;
3690 	bool vpis_cleared = false;
3691 
3692 	if (!phba)
3693 		return 0;
3694 	vport = phba->pport;
3695 
3696 	if (!(vport->fc_flag & FC_OFFLINE_MODE))
3697 		return 0;
3698 
3699 	lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
3700 			"0458 Bring Adapter online\n");
3701 
3702 	lpfc_block_mgmt_io(phba, LPFC_MBX_WAIT);
3703 
3704 	if (phba->sli_rev == LPFC_SLI_REV4) {
3705 		if (lpfc_sli4_hba_setup(phba)) { /* Initialize SLI4 HBA */
3706 			lpfc_unblock_mgmt_io(phba);
3707 			return 1;
3708 		}
3709 		spin_lock_irq(&phba->hbalock);
3710 		if (!phba->sli4_hba.max_cfg_param.vpi_used)
3711 			vpis_cleared = true;
3712 		spin_unlock_irq(&phba->hbalock);
3713 
3714 		/* Reestablish the local initiator port.
3715 		 * The offline process destroyed the previous lport.
3716 		 */
3717 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME &&
3718 				!phba->nvmet_support) {
3719 			error = lpfc_nvme_create_localport(phba->pport);
3720 			if (error)
3721 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3722 					"6132 NVME restore reg failed "
3723 					"on nvmei error x%x\n", error);
3724 		}
3725 	} else {
3726 		lpfc_sli_queue_init(phba);
3727 		if (lpfc_sli_hba_setup(phba)) {	/* Initialize SLI2/SLI3 HBA */
3728 			lpfc_unblock_mgmt_io(phba);
3729 			return 1;
3730 		}
3731 	}
3732 
3733 	vports = lpfc_create_vport_work_array(phba);
3734 	if (vports != NULL) {
3735 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3736 			struct Scsi_Host *shost;
3737 			shost = lpfc_shost_from_vport(vports[i]);
3738 			spin_lock_irq(shost->host_lock);
3739 			vports[i]->fc_flag &= ~FC_OFFLINE_MODE;
3740 			if (phba->sli3_options & LPFC_SLI3_NPIV_ENABLED)
3741 				vports[i]->fc_flag |= FC_VPORT_NEEDS_REG_VPI;
3742 			if (phba->sli_rev == LPFC_SLI_REV4) {
3743 				vports[i]->fc_flag |= FC_VPORT_NEEDS_INIT_VPI;
3744 				if ((vpis_cleared) &&
3745 				    (vports[i]->port_type !=
3746 					LPFC_PHYSICAL_PORT))
3747 					vports[i]->vpi = 0;
3748 			}
3749 			spin_unlock_irq(shost->host_lock);
3750 		}
3751 	}
3752 	lpfc_destroy_vport_work_array(phba, vports);
3753 
3754 	if (phba->cfg_xri_rebalancing)
3755 		lpfc_create_multixri_pools(phba);
3756 
3757 	lpfc_cpuhp_add(phba);
3758 
3759 	lpfc_unblock_mgmt_io(phba);
3760 	return 0;
3761 }
3762 
3763 /**
3764  * lpfc_unblock_mgmt_io - Mark a HBA's management interface to be not blocked
3765  * @phba: pointer to lpfc hba data structure.
3766  *
3767  * This routine marks a HBA's management interface as not blocked. Once the
3768  * HBA's management interface is marked as not blocked, all the user space
3769  * access to the HBA, whether they are from sysfs interface or libdfc
3770  * interface will be allowed. The HBA is set to block the management interface
3771  * when the driver prepares the HBA interface for online or offline and then
3772  * set to unblock the management interface afterwards.
3773  **/
3774 void
3775 lpfc_unblock_mgmt_io(struct lpfc_hba * phba)
3776 {
3777 	unsigned long iflag;
3778 
3779 	spin_lock_irqsave(&phba->hbalock, iflag);
3780 	phba->sli.sli_flag &= ~LPFC_BLOCK_MGMT_IO;
3781 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3782 }
3783 
3784 /**
3785  * lpfc_offline_prep - Prepare a HBA to be brought offline
3786  * @phba: pointer to lpfc hba data structure.
3787  * @mbx_action: flag for mailbox shutdown action.
3788  *
3789  * This routine is invoked to prepare a HBA to be brought offline. It performs
3790  * unregistration login to all the nodes on all vports and flushes the mailbox
3791  * queue to make it ready to be brought offline.
3792  **/
3793 void
3794 lpfc_offline_prep(struct lpfc_hba *phba, int mbx_action)
3795 {
3796 	struct lpfc_vport *vport = phba->pport;
3797 	struct lpfc_nodelist  *ndlp, *next_ndlp;
3798 	struct lpfc_vport **vports;
3799 	struct Scsi_Host *shost;
3800 	int i;
3801 	int offline;
3802 	bool hba_pci_err;
3803 
3804 	if (vport->fc_flag & FC_OFFLINE_MODE)
3805 		return;
3806 
3807 	lpfc_block_mgmt_io(phba, mbx_action);
3808 
3809 	lpfc_linkdown(phba);
3810 
3811 	offline =  pci_channel_offline(phba->pcidev);
3812 	hba_pci_err = test_bit(HBA_PCI_ERR, &phba->bit_flags);
3813 
3814 	/* Issue an unreg_login to all nodes on all vports */
3815 	vports = lpfc_create_vport_work_array(phba);
3816 	if (vports != NULL) {
3817 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3818 			if (vports[i]->load_flag & FC_UNLOADING)
3819 				continue;
3820 			shost = lpfc_shost_from_vport(vports[i]);
3821 			spin_lock_irq(shost->host_lock);
3822 			vports[i]->vpi_state &= ~LPFC_VPI_REGISTERED;
3823 			vports[i]->fc_flag |= FC_VPORT_NEEDS_REG_VPI;
3824 			vports[i]->fc_flag &= ~FC_VFI_REGISTERED;
3825 			spin_unlock_irq(shost->host_lock);
3826 
3827 			shost =	lpfc_shost_from_vport(vports[i]);
3828 			list_for_each_entry_safe(ndlp, next_ndlp,
3829 						 &vports[i]->fc_nodes,
3830 						 nlp_listp) {
3831 
3832 				spin_lock_irq(&ndlp->lock);
3833 				ndlp->nlp_flag &= ~NLP_NPR_ADISC;
3834 				spin_unlock_irq(&ndlp->lock);
3835 
3836 				if (offline || hba_pci_err) {
3837 					spin_lock_irq(&ndlp->lock);
3838 					ndlp->nlp_flag &= ~(NLP_UNREG_INP |
3839 							    NLP_RPI_REGISTERED);
3840 					spin_unlock_irq(&ndlp->lock);
3841 					if (phba->sli_rev == LPFC_SLI_REV4)
3842 						lpfc_sli_rpi_release(vports[i],
3843 								     ndlp);
3844 				} else {
3845 					lpfc_unreg_rpi(vports[i], ndlp);
3846 				}
3847 				/*
3848 				 * Whenever an SLI4 port goes offline, free the
3849 				 * RPI. Get a new RPI when the adapter port
3850 				 * comes back online.
3851 				 */
3852 				if (phba->sli_rev == LPFC_SLI_REV4) {
3853 					lpfc_printf_vlog(vports[i], KERN_INFO,
3854 						 LOG_NODE | LOG_DISCOVERY,
3855 						 "0011 Free RPI x%x on "
3856 						 "ndlp: x%px did x%x\n",
3857 						 ndlp->nlp_rpi, ndlp,
3858 						 ndlp->nlp_DID);
3859 					lpfc_sli4_free_rpi(phba, ndlp->nlp_rpi);
3860 					ndlp->nlp_rpi = LPFC_RPI_ALLOC_ERROR;
3861 				}
3862 
3863 				if (ndlp->nlp_type & NLP_FABRIC) {
3864 					lpfc_disc_state_machine(vports[i], ndlp,
3865 						NULL, NLP_EVT_DEVICE_RECOVERY);
3866 
3867 					/* Don't remove the node unless the node
3868 					 * has been unregistered with the
3869 					 * transport, and we're not in recovery
3870 					 * before dev_loss_tmo triggered.
3871 					 * Otherwise, let dev_loss take care of
3872 					 * the node.
3873 					 */
3874 					if (!(ndlp->save_flags &
3875 					      NLP_IN_RECOV_POST_DEV_LOSS) &&
3876 					    !(ndlp->fc4_xpt_flags &
3877 					      (NVME_XPT_REGD | SCSI_XPT_REGD)))
3878 						lpfc_disc_state_machine
3879 							(vports[i], ndlp,
3880 							 NULL,
3881 							 NLP_EVT_DEVICE_RM);
3882 				}
3883 			}
3884 		}
3885 	}
3886 	lpfc_destroy_vport_work_array(phba, vports);
3887 
3888 	lpfc_sli_mbox_sys_shutdown(phba, mbx_action);
3889 
3890 	if (phba->wq)
3891 		flush_workqueue(phba->wq);
3892 }
3893 
3894 /**
3895  * lpfc_offline - Bring a HBA offline
3896  * @phba: pointer to lpfc hba data structure.
3897  *
3898  * This routine actually brings a HBA offline. It stops all the timers
3899  * associated with the HBA, brings down the SLI layer, and eventually
3900  * marks the HBA as in offline state for the upper layer protocol.
3901  **/
3902 void
3903 lpfc_offline(struct lpfc_hba *phba)
3904 {
3905 	struct Scsi_Host  *shost;
3906 	struct lpfc_vport **vports;
3907 	int i;
3908 
3909 	if (phba->pport->fc_flag & FC_OFFLINE_MODE)
3910 		return;
3911 
3912 	/* stop port and all timers associated with this hba */
3913 	lpfc_stop_port(phba);
3914 
3915 	/* Tear down the local and target port registrations.  The
3916 	 * nvme transports need to cleanup.
3917 	 */
3918 	lpfc_nvmet_destroy_targetport(phba);
3919 	lpfc_nvme_destroy_localport(phba->pport);
3920 
3921 	vports = lpfc_create_vport_work_array(phba);
3922 	if (vports != NULL)
3923 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++)
3924 			lpfc_stop_vport_timers(vports[i]);
3925 	lpfc_destroy_vport_work_array(phba, vports);
3926 	lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
3927 			"0460 Bring Adapter offline\n");
3928 	/* Bring down the SLI Layer and cleanup.  The HBA is offline
3929 	   now.  */
3930 	lpfc_sli_hba_down(phba);
3931 	spin_lock_irq(&phba->hbalock);
3932 	phba->work_ha = 0;
3933 	spin_unlock_irq(&phba->hbalock);
3934 	vports = lpfc_create_vport_work_array(phba);
3935 	if (vports != NULL)
3936 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3937 			shost = lpfc_shost_from_vport(vports[i]);
3938 			spin_lock_irq(shost->host_lock);
3939 			vports[i]->work_port_events = 0;
3940 			vports[i]->fc_flag |= FC_OFFLINE_MODE;
3941 			spin_unlock_irq(shost->host_lock);
3942 		}
3943 	lpfc_destroy_vport_work_array(phba, vports);
3944 	/* If OFFLINE flag is clear (i.e. unloading), cpuhp removal is handled
3945 	 * in hba_unset
3946 	 */
3947 	if (phba->pport->fc_flag & FC_OFFLINE_MODE)
3948 		__lpfc_cpuhp_remove(phba);
3949 
3950 	if (phba->cfg_xri_rebalancing)
3951 		lpfc_destroy_multixri_pools(phba);
3952 }
3953 
3954 /**
3955  * lpfc_scsi_free - Free all the SCSI buffers and IOCBs from driver lists
3956  * @phba: pointer to lpfc hba data structure.
3957  *
3958  * This routine is to free all the SCSI buffers and IOCBs from the driver
3959  * list back to kernel. It is called from lpfc_pci_remove_one to free
3960  * the internal resources before the device is removed from the system.
3961  **/
3962 static void
3963 lpfc_scsi_free(struct lpfc_hba *phba)
3964 {
3965 	struct lpfc_io_buf *sb, *sb_next;
3966 
3967 	if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP))
3968 		return;
3969 
3970 	spin_lock_irq(&phba->hbalock);
3971 
3972 	/* Release all the lpfc_scsi_bufs maintained by this host. */
3973 
3974 	spin_lock(&phba->scsi_buf_list_put_lock);
3975 	list_for_each_entry_safe(sb, sb_next, &phba->lpfc_scsi_buf_list_put,
3976 				 list) {
3977 		list_del(&sb->list);
3978 		dma_pool_free(phba->lpfc_sg_dma_buf_pool, sb->data,
3979 			      sb->dma_handle);
3980 		kfree(sb);
3981 		phba->total_scsi_bufs--;
3982 	}
3983 	spin_unlock(&phba->scsi_buf_list_put_lock);
3984 
3985 	spin_lock(&phba->scsi_buf_list_get_lock);
3986 	list_for_each_entry_safe(sb, sb_next, &phba->lpfc_scsi_buf_list_get,
3987 				 list) {
3988 		list_del(&sb->list);
3989 		dma_pool_free(phba->lpfc_sg_dma_buf_pool, sb->data,
3990 			      sb->dma_handle);
3991 		kfree(sb);
3992 		phba->total_scsi_bufs--;
3993 	}
3994 	spin_unlock(&phba->scsi_buf_list_get_lock);
3995 	spin_unlock_irq(&phba->hbalock);
3996 }
3997 
3998 /**
3999  * lpfc_io_free - Free all the IO buffers and IOCBs from driver lists
4000  * @phba: pointer to lpfc hba data structure.
4001  *
4002  * This routine is to free all the IO buffers and IOCBs from the driver
4003  * list back to kernel. It is called from lpfc_pci_remove_one to free
4004  * the internal resources before the device is removed from the system.
4005  **/
4006 void
4007 lpfc_io_free(struct lpfc_hba *phba)
4008 {
4009 	struct lpfc_io_buf *lpfc_ncmd, *lpfc_ncmd_next;
4010 	struct lpfc_sli4_hdw_queue *qp;
4011 	int idx;
4012 
4013 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
4014 		qp = &phba->sli4_hba.hdwq[idx];
4015 		/* Release all the lpfc_nvme_bufs maintained by this host. */
4016 		spin_lock(&qp->io_buf_list_put_lock);
4017 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
4018 					 &qp->lpfc_io_buf_list_put,
4019 					 list) {
4020 			list_del(&lpfc_ncmd->list);
4021 			qp->put_io_bufs--;
4022 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4023 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4024 			if (phba->cfg_xpsgl && !phba->nvmet_support)
4025 				lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
4026 			lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
4027 			kfree(lpfc_ncmd);
4028 			qp->total_io_bufs--;
4029 		}
4030 		spin_unlock(&qp->io_buf_list_put_lock);
4031 
4032 		spin_lock(&qp->io_buf_list_get_lock);
4033 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
4034 					 &qp->lpfc_io_buf_list_get,
4035 					 list) {
4036 			list_del(&lpfc_ncmd->list);
4037 			qp->get_io_bufs--;
4038 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4039 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4040 			if (phba->cfg_xpsgl && !phba->nvmet_support)
4041 				lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
4042 			lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
4043 			kfree(lpfc_ncmd);
4044 			qp->total_io_bufs--;
4045 		}
4046 		spin_unlock(&qp->io_buf_list_get_lock);
4047 	}
4048 }
4049 
4050 /**
4051  * lpfc_sli4_els_sgl_update - update ELS xri-sgl sizing and mapping
4052  * @phba: pointer to lpfc hba data structure.
4053  *
4054  * This routine first calculates the sizes of the current els and allocated
4055  * scsi sgl lists, and then goes through all sgls to updates the physical
4056  * XRIs assigned due to port function reset. During port initialization, the
4057  * current els and allocated scsi sgl lists are 0s.
4058  *
4059  * Return codes
4060  *   0 - successful (for now, it always returns 0)
4061  **/
4062 int
4063 lpfc_sli4_els_sgl_update(struct lpfc_hba *phba)
4064 {
4065 	struct lpfc_sglq *sglq_entry = NULL, *sglq_entry_next = NULL;
4066 	uint16_t i, lxri, xri_cnt, els_xri_cnt;
4067 	LIST_HEAD(els_sgl_list);
4068 	int rc;
4069 
4070 	/*
4071 	 * update on pci function's els xri-sgl list
4072 	 */
4073 	els_xri_cnt = lpfc_sli4_get_els_iocb_cnt(phba);
4074 
4075 	if (els_xri_cnt > phba->sli4_hba.els_xri_cnt) {
4076 		/* els xri-sgl expanded */
4077 		xri_cnt = els_xri_cnt - phba->sli4_hba.els_xri_cnt;
4078 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4079 				"3157 ELS xri-sgl count increased from "
4080 				"%d to %d\n", phba->sli4_hba.els_xri_cnt,
4081 				els_xri_cnt);
4082 		/* allocate the additional els sgls */
4083 		for (i = 0; i < xri_cnt; i++) {
4084 			sglq_entry = kzalloc(sizeof(struct lpfc_sglq),
4085 					     GFP_KERNEL);
4086 			if (sglq_entry == NULL) {
4087 				lpfc_printf_log(phba, KERN_ERR,
4088 						LOG_TRACE_EVENT,
4089 						"2562 Failure to allocate an "
4090 						"ELS sgl entry:%d\n", i);
4091 				rc = -ENOMEM;
4092 				goto out_free_mem;
4093 			}
4094 			sglq_entry->buff_type = GEN_BUFF_TYPE;
4095 			sglq_entry->virt = lpfc_mbuf_alloc(phba, 0,
4096 							   &sglq_entry->phys);
4097 			if (sglq_entry->virt == NULL) {
4098 				kfree(sglq_entry);
4099 				lpfc_printf_log(phba, KERN_ERR,
4100 						LOG_TRACE_EVENT,
4101 						"2563 Failure to allocate an "
4102 						"ELS mbuf:%d\n", i);
4103 				rc = -ENOMEM;
4104 				goto out_free_mem;
4105 			}
4106 			sglq_entry->sgl = sglq_entry->virt;
4107 			memset(sglq_entry->sgl, 0, LPFC_BPL_SIZE);
4108 			sglq_entry->state = SGL_FREED;
4109 			list_add_tail(&sglq_entry->list, &els_sgl_list);
4110 		}
4111 		spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
4112 		list_splice_init(&els_sgl_list,
4113 				 &phba->sli4_hba.lpfc_els_sgl_list);
4114 		spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
4115 	} else if (els_xri_cnt < phba->sli4_hba.els_xri_cnt) {
4116 		/* els xri-sgl shrinked */
4117 		xri_cnt = phba->sli4_hba.els_xri_cnt - els_xri_cnt;
4118 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4119 				"3158 ELS xri-sgl count decreased from "
4120 				"%d to %d\n", phba->sli4_hba.els_xri_cnt,
4121 				els_xri_cnt);
4122 		spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
4123 		list_splice_init(&phba->sli4_hba.lpfc_els_sgl_list,
4124 				 &els_sgl_list);
4125 		/* release extra els sgls from list */
4126 		for (i = 0; i < xri_cnt; i++) {
4127 			list_remove_head(&els_sgl_list,
4128 					 sglq_entry, struct lpfc_sglq, list);
4129 			if (sglq_entry) {
4130 				__lpfc_mbuf_free(phba, sglq_entry->virt,
4131 						 sglq_entry->phys);
4132 				kfree(sglq_entry);
4133 			}
4134 		}
4135 		list_splice_init(&els_sgl_list,
4136 				 &phba->sli4_hba.lpfc_els_sgl_list);
4137 		spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
4138 	} else
4139 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4140 				"3163 ELS xri-sgl count unchanged: %d\n",
4141 				els_xri_cnt);
4142 	phba->sli4_hba.els_xri_cnt = els_xri_cnt;
4143 
4144 	/* update xris to els sgls on the list */
4145 	sglq_entry = NULL;
4146 	sglq_entry_next = NULL;
4147 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
4148 				 &phba->sli4_hba.lpfc_els_sgl_list, list) {
4149 		lxri = lpfc_sli4_next_xritag(phba);
4150 		if (lxri == NO_XRI) {
4151 			lpfc_printf_log(phba, KERN_ERR,
4152 					LOG_TRACE_EVENT,
4153 					"2400 Failed to allocate xri for "
4154 					"ELS sgl\n");
4155 			rc = -ENOMEM;
4156 			goto out_free_mem;
4157 		}
4158 		sglq_entry->sli4_lxritag = lxri;
4159 		sglq_entry->sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4160 	}
4161 	return 0;
4162 
4163 out_free_mem:
4164 	lpfc_free_els_sgl_list(phba);
4165 	return rc;
4166 }
4167 
4168 /**
4169  * lpfc_sli4_nvmet_sgl_update - update xri-sgl sizing and mapping
4170  * @phba: pointer to lpfc hba data structure.
4171  *
4172  * This routine first calculates the sizes of the current els and allocated
4173  * scsi sgl lists, and then goes through all sgls to updates the physical
4174  * XRIs assigned due to port function reset. During port initialization, the
4175  * current els and allocated scsi sgl lists are 0s.
4176  *
4177  * Return codes
4178  *   0 - successful (for now, it always returns 0)
4179  **/
4180 int
4181 lpfc_sli4_nvmet_sgl_update(struct lpfc_hba *phba)
4182 {
4183 	struct lpfc_sglq *sglq_entry = NULL, *sglq_entry_next = NULL;
4184 	uint16_t i, lxri, xri_cnt, els_xri_cnt;
4185 	uint16_t nvmet_xri_cnt;
4186 	LIST_HEAD(nvmet_sgl_list);
4187 	int rc;
4188 
4189 	/*
4190 	 * update on pci function's nvmet xri-sgl list
4191 	 */
4192 	els_xri_cnt = lpfc_sli4_get_els_iocb_cnt(phba);
4193 
4194 	/* For NVMET, ALL remaining XRIs are dedicated for IO processing */
4195 	nvmet_xri_cnt = phba->sli4_hba.max_cfg_param.max_xri - els_xri_cnt;
4196 	if (nvmet_xri_cnt > phba->sli4_hba.nvmet_xri_cnt) {
4197 		/* els xri-sgl expanded */
4198 		xri_cnt = nvmet_xri_cnt - phba->sli4_hba.nvmet_xri_cnt;
4199 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4200 				"6302 NVMET xri-sgl cnt grew from %d to %d\n",
4201 				phba->sli4_hba.nvmet_xri_cnt, nvmet_xri_cnt);
4202 		/* allocate the additional nvmet sgls */
4203 		for (i = 0; i < xri_cnt; i++) {
4204 			sglq_entry = kzalloc(sizeof(struct lpfc_sglq),
4205 					     GFP_KERNEL);
4206 			if (sglq_entry == NULL) {
4207 				lpfc_printf_log(phba, KERN_ERR,
4208 						LOG_TRACE_EVENT,
4209 						"6303 Failure to allocate an "
4210 						"NVMET sgl entry:%d\n", i);
4211 				rc = -ENOMEM;
4212 				goto out_free_mem;
4213 			}
4214 			sglq_entry->buff_type = NVMET_BUFF_TYPE;
4215 			sglq_entry->virt = lpfc_nvmet_buf_alloc(phba, 0,
4216 							   &sglq_entry->phys);
4217 			if (sglq_entry->virt == NULL) {
4218 				kfree(sglq_entry);
4219 				lpfc_printf_log(phba, KERN_ERR,
4220 						LOG_TRACE_EVENT,
4221 						"6304 Failure to allocate an "
4222 						"NVMET buf:%d\n", i);
4223 				rc = -ENOMEM;
4224 				goto out_free_mem;
4225 			}
4226 			sglq_entry->sgl = sglq_entry->virt;
4227 			memset(sglq_entry->sgl, 0,
4228 			       phba->cfg_sg_dma_buf_size);
4229 			sglq_entry->state = SGL_FREED;
4230 			list_add_tail(&sglq_entry->list, &nvmet_sgl_list);
4231 		}
4232 		spin_lock_irq(&phba->hbalock);
4233 		spin_lock(&phba->sli4_hba.sgl_list_lock);
4234 		list_splice_init(&nvmet_sgl_list,
4235 				 &phba->sli4_hba.lpfc_nvmet_sgl_list);
4236 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
4237 		spin_unlock_irq(&phba->hbalock);
4238 	} else if (nvmet_xri_cnt < phba->sli4_hba.nvmet_xri_cnt) {
4239 		/* nvmet xri-sgl shrunk */
4240 		xri_cnt = phba->sli4_hba.nvmet_xri_cnt - nvmet_xri_cnt;
4241 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4242 				"6305 NVMET xri-sgl count decreased from "
4243 				"%d to %d\n", phba->sli4_hba.nvmet_xri_cnt,
4244 				nvmet_xri_cnt);
4245 		spin_lock_irq(&phba->hbalock);
4246 		spin_lock(&phba->sli4_hba.sgl_list_lock);
4247 		list_splice_init(&phba->sli4_hba.lpfc_nvmet_sgl_list,
4248 				 &nvmet_sgl_list);
4249 		/* release extra nvmet sgls from list */
4250 		for (i = 0; i < xri_cnt; i++) {
4251 			list_remove_head(&nvmet_sgl_list,
4252 					 sglq_entry, struct lpfc_sglq, list);
4253 			if (sglq_entry) {
4254 				lpfc_nvmet_buf_free(phba, sglq_entry->virt,
4255 						    sglq_entry->phys);
4256 				kfree(sglq_entry);
4257 			}
4258 		}
4259 		list_splice_init(&nvmet_sgl_list,
4260 				 &phba->sli4_hba.lpfc_nvmet_sgl_list);
4261 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
4262 		spin_unlock_irq(&phba->hbalock);
4263 	} else
4264 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4265 				"6306 NVMET xri-sgl count unchanged: %d\n",
4266 				nvmet_xri_cnt);
4267 	phba->sli4_hba.nvmet_xri_cnt = nvmet_xri_cnt;
4268 
4269 	/* update xris to nvmet sgls on the list */
4270 	sglq_entry = NULL;
4271 	sglq_entry_next = NULL;
4272 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
4273 				 &phba->sli4_hba.lpfc_nvmet_sgl_list, list) {
4274 		lxri = lpfc_sli4_next_xritag(phba);
4275 		if (lxri == NO_XRI) {
4276 			lpfc_printf_log(phba, KERN_ERR,
4277 					LOG_TRACE_EVENT,
4278 					"6307 Failed to allocate xri for "
4279 					"NVMET sgl\n");
4280 			rc = -ENOMEM;
4281 			goto out_free_mem;
4282 		}
4283 		sglq_entry->sli4_lxritag = lxri;
4284 		sglq_entry->sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4285 	}
4286 	return 0;
4287 
4288 out_free_mem:
4289 	lpfc_free_nvmet_sgl_list(phba);
4290 	return rc;
4291 }
4292 
4293 int
4294 lpfc_io_buf_flush(struct lpfc_hba *phba, struct list_head *cbuf)
4295 {
4296 	LIST_HEAD(blist);
4297 	struct lpfc_sli4_hdw_queue *qp;
4298 	struct lpfc_io_buf *lpfc_cmd;
4299 	struct lpfc_io_buf *iobufp, *prev_iobufp;
4300 	int idx, cnt, xri, inserted;
4301 
4302 	cnt = 0;
4303 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
4304 		qp = &phba->sli4_hba.hdwq[idx];
4305 		spin_lock_irq(&qp->io_buf_list_get_lock);
4306 		spin_lock(&qp->io_buf_list_put_lock);
4307 
4308 		/* Take everything off the get and put lists */
4309 		list_splice_init(&qp->lpfc_io_buf_list_get, &blist);
4310 		list_splice(&qp->lpfc_io_buf_list_put, &blist);
4311 		INIT_LIST_HEAD(&qp->lpfc_io_buf_list_get);
4312 		INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
4313 		cnt += qp->get_io_bufs + qp->put_io_bufs;
4314 		qp->get_io_bufs = 0;
4315 		qp->put_io_bufs = 0;
4316 		qp->total_io_bufs = 0;
4317 		spin_unlock(&qp->io_buf_list_put_lock);
4318 		spin_unlock_irq(&qp->io_buf_list_get_lock);
4319 	}
4320 
4321 	/*
4322 	 * Take IO buffers off blist and put on cbuf sorted by XRI.
4323 	 * This is because POST_SGL takes a sequential range of XRIs
4324 	 * to post to the firmware.
4325 	 */
4326 	for (idx = 0; idx < cnt; idx++) {
4327 		list_remove_head(&blist, lpfc_cmd, struct lpfc_io_buf, list);
4328 		if (!lpfc_cmd)
4329 			return cnt;
4330 		if (idx == 0) {
4331 			list_add_tail(&lpfc_cmd->list, cbuf);
4332 			continue;
4333 		}
4334 		xri = lpfc_cmd->cur_iocbq.sli4_xritag;
4335 		inserted = 0;
4336 		prev_iobufp = NULL;
4337 		list_for_each_entry(iobufp, cbuf, list) {
4338 			if (xri < iobufp->cur_iocbq.sli4_xritag) {
4339 				if (prev_iobufp)
4340 					list_add(&lpfc_cmd->list,
4341 						 &prev_iobufp->list);
4342 				else
4343 					list_add(&lpfc_cmd->list, cbuf);
4344 				inserted = 1;
4345 				break;
4346 			}
4347 			prev_iobufp = iobufp;
4348 		}
4349 		if (!inserted)
4350 			list_add_tail(&lpfc_cmd->list, cbuf);
4351 	}
4352 	return cnt;
4353 }
4354 
4355 int
4356 lpfc_io_buf_replenish(struct lpfc_hba *phba, struct list_head *cbuf)
4357 {
4358 	struct lpfc_sli4_hdw_queue *qp;
4359 	struct lpfc_io_buf *lpfc_cmd;
4360 	int idx, cnt;
4361 
4362 	qp = phba->sli4_hba.hdwq;
4363 	cnt = 0;
4364 	while (!list_empty(cbuf)) {
4365 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
4366 			list_remove_head(cbuf, lpfc_cmd,
4367 					 struct lpfc_io_buf, list);
4368 			if (!lpfc_cmd)
4369 				return cnt;
4370 			cnt++;
4371 			qp = &phba->sli4_hba.hdwq[idx];
4372 			lpfc_cmd->hdwq_no = idx;
4373 			lpfc_cmd->hdwq = qp;
4374 			lpfc_cmd->cur_iocbq.cmd_cmpl = NULL;
4375 			spin_lock(&qp->io_buf_list_put_lock);
4376 			list_add_tail(&lpfc_cmd->list,
4377 				      &qp->lpfc_io_buf_list_put);
4378 			qp->put_io_bufs++;
4379 			qp->total_io_bufs++;
4380 			spin_unlock(&qp->io_buf_list_put_lock);
4381 		}
4382 	}
4383 	return cnt;
4384 }
4385 
4386 /**
4387  * lpfc_sli4_io_sgl_update - update xri-sgl sizing and mapping
4388  * @phba: pointer to lpfc hba data structure.
4389  *
4390  * This routine first calculates the sizes of the current els and allocated
4391  * scsi sgl lists, and then goes through all sgls to updates the physical
4392  * XRIs assigned due to port function reset. During port initialization, the
4393  * current els and allocated scsi sgl lists are 0s.
4394  *
4395  * Return codes
4396  *   0 - successful (for now, it always returns 0)
4397  **/
4398 int
4399 lpfc_sli4_io_sgl_update(struct lpfc_hba *phba)
4400 {
4401 	struct lpfc_io_buf *lpfc_ncmd = NULL, *lpfc_ncmd_next = NULL;
4402 	uint16_t i, lxri, els_xri_cnt;
4403 	uint16_t io_xri_cnt, io_xri_max;
4404 	LIST_HEAD(io_sgl_list);
4405 	int rc, cnt;
4406 
4407 	/*
4408 	 * update on pci function's allocated nvme xri-sgl list
4409 	 */
4410 
4411 	/* maximum number of xris available for nvme buffers */
4412 	els_xri_cnt = lpfc_sli4_get_els_iocb_cnt(phba);
4413 	io_xri_max = phba->sli4_hba.max_cfg_param.max_xri - els_xri_cnt;
4414 	phba->sli4_hba.io_xri_max = io_xri_max;
4415 
4416 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4417 			"6074 Current allocated XRI sgl count:%d, "
4418 			"maximum XRI count:%d els_xri_cnt:%d\n\n",
4419 			phba->sli4_hba.io_xri_cnt,
4420 			phba->sli4_hba.io_xri_max,
4421 			els_xri_cnt);
4422 
4423 	cnt = lpfc_io_buf_flush(phba, &io_sgl_list);
4424 
4425 	if (phba->sli4_hba.io_xri_cnt > phba->sli4_hba.io_xri_max) {
4426 		/* max nvme xri shrunk below the allocated nvme buffers */
4427 		io_xri_cnt = phba->sli4_hba.io_xri_cnt -
4428 					phba->sli4_hba.io_xri_max;
4429 		/* release the extra allocated nvme buffers */
4430 		for (i = 0; i < io_xri_cnt; i++) {
4431 			list_remove_head(&io_sgl_list, lpfc_ncmd,
4432 					 struct lpfc_io_buf, list);
4433 			if (lpfc_ncmd) {
4434 				dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4435 					      lpfc_ncmd->data,
4436 					      lpfc_ncmd->dma_handle);
4437 				kfree(lpfc_ncmd);
4438 			}
4439 		}
4440 		phba->sli4_hba.io_xri_cnt -= io_xri_cnt;
4441 	}
4442 
4443 	/* update xris associated to remaining allocated nvme buffers */
4444 	lpfc_ncmd = NULL;
4445 	lpfc_ncmd_next = NULL;
4446 	phba->sli4_hba.io_xri_cnt = cnt;
4447 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
4448 				 &io_sgl_list, list) {
4449 		lxri = lpfc_sli4_next_xritag(phba);
4450 		if (lxri == NO_XRI) {
4451 			lpfc_printf_log(phba, KERN_ERR,
4452 					LOG_TRACE_EVENT,
4453 					"6075 Failed to allocate xri for "
4454 					"nvme buffer\n");
4455 			rc = -ENOMEM;
4456 			goto out_free_mem;
4457 		}
4458 		lpfc_ncmd->cur_iocbq.sli4_lxritag = lxri;
4459 		lpfc_ncmd->cur_iocbq.sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4460 	}
4461 	cnt = lpfc_io_buf_replenish(phba, &io_sgl_list);
4462 	return 0;
4463 
4464 out_free_mem:
4465 	lpfc_io_free(phba);
4466 	return rc;
4467 }
4468 
4469 /**
4470  * lpfc_new_io_buf - IO buffer allocator for HBA with SLI4 IF spec
4471  * @phba: Pointer to lpfc hba data structure.
4472  * @num_to_alloc: The requested number of buffers to allocate.
4473  *
4474  * This routine allocates nvme buffers for device with SLI-4 interface spec,
4475  * the nvme buffer contains all the necessary information needed to initiate
4476  * an I/O. After allocating up to @num_to_allocate IO buffers and put
4477  * them on a list, it post them to the port by using SGL block post.
4478  *
4479  * Return codes:
4480  *   int - number of IO buffers that were allocated and posted.
4481  *   0 = failure, less than num_to_alloc is a partial failure.
4482  **/
4483 int
4484 lpfc_new_io_buf(struct lpfc_hba *phba, int num_to_alloc)
4485 {
4486 	struct lpfc_io_buf *lpfc_ncmd;
4487 	struct lpfc_iocbq *pwqeq;
4488 	uint16_t iotag, lxri = 0;
4489 	int bcnt, num_posted;
4490 	LIST_HEAD(prep_nblist);
4491 	LIST_HEAD(post_nblist);
4492 	LIST_HEAD(nvme_nblist);
4493 
4494 	phba->sli4_hba.io_xri_cnt = 0;
4495 	for (bcnt = 0; bcnt < num_to_alloc; bcnt++) {
4496 		lpfc_ncmd = kzalloc(sizeof(*lpfc_ncmd), GFP_KERNEL);
4497 		if (!lpfc_ncmd)
4498 			break;
4499 		/*
4500 		 * Get memory from the pci pool to map the virt space to
4501 		 * pci bus space for an I/O. The DMA buffer includes the
4502 		 * number of SGE's necessary to support the sg_tablesize.
4503 		 */
4504 		lpfc_ncmd->data = dma_pool_zalloc(phba->lpfc_sg_dma_buf_pool,
4505 						  GFP_KERNEL,
4506 						  &lpfc_ncmd->dma_handle);
4507 		if (!lpfc_ncmd->data) {
4508 			kfree(lpfc_ncmd);
4509 			break;
4510 		}
4511 
4512 		if (phba->cfg_xpsgl && !phba->nvmet_support) {
4513 			INIT_LIST_HEAD(&lpfc_ncmd->dma_sgl_xtra_list);
4514 		} else {
4515 			/*
4516 			 * 4K Page alignment is CRITICAL to BlockGuard, double
4517 			 * check to be sure.
4518 			 */
4519 			if ((phba->sli3_options & LPFC_SLI3_BG_ENABLED) &&
4520 			    (((unsigned long)(lpfc_ncmd->data) &
4521 			    (unsigned long)(SLI4_PAGE_SIZE - 1)) != 0)) {
4522 				lpfc_printf_log(phba, KERN_ERR,
4523 						LOG_TRACE_EVENT,
4524 						"3369 Memory alignment err: "
4525 						"addr=%lx\n",
4526 						(unsigned long)lpfc_ncmd->data);
4527 				dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4528 					      lpfc_ncmd->data,
4529 					      lpfc_ncmd->dma_handle);
4530 				kfree(lpfc_ncmd);
4531 				break;
4532 			}
4533 		}
4534 
4535 		INIT_LIST_HEAD(&lpfc_ncmd->dma_cmd_rsp_list);
4536 
4537 		lxri = lpfc_sli4_next_xritag(phba);
4538 		if (lxri == NO_XRI) {
4539 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4540 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4541 			kfree(lpfc_ncmd);
4542 			break;
4543 		}
4544 		pwqeq = &lpfc_ncmd->cur_iocbq;
4545 
4546 		/* Allocate iotag for lpfc_ncmd->cur_iocbq. */
4547 		iotag = lpfc_sli_next_iotag(phba, pwqeq);
4548 		if (iotag == 0) {
4549 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4550 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4551 			kfree(lpfc_ncmd);
4552 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4553 					"6121 Failed to allocate IOTAG for"
4554 					" XRI:0x%x\n", lxri);
4555 			lpfc_sli4_free_xri(phba, lxri);
4556 			break;
4557 		}
4558 		pwqeq->sli4_lxritag = lxri;
4559 		pwqeq->sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4560 
4561 		/* Initialize local short-hand pointers. */
4562 		lpfc_ncmd->dma_sgl = lpfc_ncmd->data;
4563 		lpfc_ncmd->dma_phys_sgl = lpfc_ncmd->dma_handle;
4564 		lpfc_ncmd->cur_iocbq.io_buf = lpfc_ncmd;
4565 		spin_lock_init(&lpfc_ncmd->buf_lock);
4566 
4567 		/* add the nvme buffer to a post list */
4568 		list_add_tail(&lpfc_ncmd->list, &post_nblist);
4569 		phba->sli4_hba.io_xri_cnt++;
4570 	}
4571 	lpfc_printf_log(phba, KERN_INFO, LOG_NVME,
4572 			"6114 Allocate %d out of %d requested new NVME "
4573 			"buffers of size x%zu bytes\n", bcnt, num_to_alloc,
4574 			sizeof(*lpfc_ncmd));
4575 
4576 
4577 	/* post the list of nvme buffer sgls to port if available */
4578 	if (!list_empty(&post_nblist))
4579 		num_posted = lpfc_sli4_post_io_sgl_list(
4580 				phba, &post_nblist, bcnt);
4581 	else
4582 		num_posted = 0;
4583 
4584 	return num_posted;
4585 }
4586 
4587 static uint64_t
4588 lpfc_get_wwpn(struct lpfc_hba *phba)
4589 {
4590 	uint64_t wwn;
4591 	int rc;
4592 	LPFC_MBOXQ_t *mboxq;
4593 	MAILBOX_t *mb;
4594 
4595 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
4596 						GFP_KERNEL);
4597 	if (!mboxq)
4598 		return (uint64_t)-1;
4599 
4600 	/* First get WWN of HBA instance */
4601 	lpfc_read_nv(phba, mboxq);
4602 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
4603 	if (rc != MBX_SUCCESS) {
4604 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4605 				"6019 Mailbox failed , mbxCmd x%x "
4606 				"READ_NV, mbxStatus x%x\n",
4607 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
4608 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
4609 		mempool_free(mboxq, phba->mbox_mem_pool);
4610 		return (uint64_t) -1;
4611 	}
4612 	mb = &mboxq->u.mb;
4613 	memcpy(&wwn, (char *)mb->un.varRDnvp.portname, sizeof(uint64_t));
4614 	/* wwn is WWPN of HBA instance */
4615 	mempool_free(mboxq, phba->mbox_mem_pool);
4616 	if (phba->sli_rev == LPFC_SLI_REV4)
4617 		return be64_to_cpu(wwn);
4618 	else
4619 		return rol64(wwn, 32);
4620 }
4621 
4622 static unsigned short lpfc_get_sg_tablesize(struct lpfc_hba *phba)
4623 {
4624 	if (phba->sli_rev == LPFC_SLI_REV4)
4625 		if (phba->cfg_xpsgl && !phba->nvmet_support)
4626 			return LPFC_MAX_SG_TABLESIZE;
4627 		else
4628 			return phba->cfg_scsi_seg_cnt;
4629 	else
4630 		return phba->cfg_sg_seg_cnt;
4631 }
4632 
4633 /**
4634  * lpfc_vmid_res_alloc - Allocates resources for VMID
4635  * @phba: pointer to lpfc hba data structure.
4636  * @vport: pointer to vport data structure
4637  *
4638  * This routine allocated the resources needed for the VMID.
4639  *
4640  * Return codes
4641  *	0 on Success
4642  *	Non-0 on Failure
4643  */
4644 static int
4645 lpfc_vmid_res_alloc(struct lpfc_hba *phba, struct lpfc_vport *vport)
4646 {
4647 	/* VMID feature is supported only on SLI4 */
4648 	if (phba->sli_rev == LPFC_SLI_REV3) {
4649 		phba->cfg_vmid_app_header = 0;
4650 		phba->cfg_vmid_priority_tagging = 0;
4651 	}
4652 
4653 	if (lpfc_is_vmid_enabled(phba)) {
4654 		vport->vmid =
4655 		    kcalloc(phba->cfg_max_vmid, sizeof(struct lpfc_vmid),
4656 			    GFP_KERNEL);
4657 		if (!vport->vmid)
4658 			return -ENOMEM;
4659 
4660 		rwlock_init(&vport->vmid_lock);
4661 
4662 		/* Set the VMID parameters for the vport */
4663 		vport->vmid_priority_tagging = phba->cfg_vmid_priority_tagging;
4664 		vport->vmid_inactivity_timeout =
4665 		    phba->cfg_vmid_inactivity_timeout;
4666 		vport->max_vmid = phba->cfg_max_vmid;
4667 		vport->cur_vmid_cnt = 0;
4668 
4669 		vport->vmid_priority_range = bitmap_zalloc
4670 			(LPFC_VMID_MAX_PRIORITY_RANGE, GFP_KERNEL);
4671 
4672 		if (!vport->vmid_priority_range) {
4673 			kfree(vport->vmid);
4674 			return -ENOMEM;
4675 		}
4676 
4677 		hash_init(vport->hash_table);
4678 	}
4679 	return 0;
4680 }
4681 
4682 /**
4683  * lpfc_create_port - Create an FC port
4684  * @phba: pointer to lpfc hba data structure.
4685  * @instance: a unique integer ID to this FC port.
4686  * @dev: pointer to the device data structure.
4687  *
4688  * This routine creates a FC port for the upper layer protocol. The FC port
4689  * can be created on top of either a physical port or a virtual port provided
4690  * by the HBA. This routine also allocates a SCSI host data structure (shost)
4691  * and associates the FC port created before adding the shost into the SCSI
4692  * layer.
4693  *
4694  * Return codes
4695  *   @vport - pointer to the virtual N_Port data structure.
4696  *   NULL - port create failed.
4697  **/
4698 struct lpfc_vport *
4699 lpfc_create_port(struct lpfc_hba *phba, int instance, struct device *dev)
4700 {
4701 	struct lpfc_vport *vport;
4702 	struct Scsi_Host  *shost = NULL;
4703 	struct scsi_host_template *template;
4704 	int error = 0;
4705 	int i;
4706 	uint64_t wwn;
4707 	bool use_no_reset_hba = false;
4708 	int rc;
4709 
4710 	if (lpfc_no_hba_reset_cnt) {
4711 		if (phba->sli_rev < LPFC_SLI_REV4 &&
4712 		    dev == &phba->pcidev->dev) {
4713 			/* Reset the port first */
4714 			lpfc_sli_brdrestart(phba);
4715 			rc = lpfc_sli_chipset_init(phba);
4716 			if (rc)
4717 				return NULL;
4718 		}
4719 		wwn = lpfc_get_wwpn(phba);
4720 	}
4721 
4722 	for (i = 0; i < lpfc_no_hba_reset_cnt; i++) {
4723 		if (wwn == lpfc_no_hba_reset[i]) {
4724 			lpfc_printf_log(phba, KERN_ERR,
4725 					LOG_TRACE_EVENT,
4726 					"6020 Setting use_no_reset port=%llx\n",
4727 					wwn);
4728 			use_no_reset_hba = true;
4729 			break;
4730 		}
4731 	}
4732 
4733 	/* Seed template for SCSI host registration */
4734 	if (dev == &phba->pcidev->dev) {
4735 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP) {
4736 			/* Seed physical port template */
4737 			template = &lpfc_template;
4738 
4739 			if (use_no_reset_hba)
4740 				/* template is for a no reset SCSI Host */
4741 				template->eh_host_reset_handler = NULL;
4742 
4743 			/* Seed updated value of sg_tablesize */
4744 			template->sg_tablesize = lpfc_get_sg_tablesize(phba);
4745 		} else {
4746 			/* NVMET is for physical port only */
4747 			template = &lpfc_template_nvme;
4748 		}
4749 	} else {
4750 		/* Seed vport template */
4751 		template = &lpfc_vport_template;
4752 
4753 		/* Seed updated value of sg_tablesize */
4754 		template->sg_tablesize = lpfc_get_sg_tablesize(phba);
4755 	}
4756 
4757 	shost = scsi_host_alloc(template, sizeof(struct lpfc_vport));
4758 	if (!shost)
4759 		goto out;
4760 
4761 	vport = (struct lpfc_vport *) shost->hostdata;
4762 	vport->phba = phba;
4763 	vport->load_flag |= FC_LOADING;
4764 	vport->fc_flag |= FC_VPORT_NEEDS_REG_VPI;
4765 	vport->fc_rscn_flush = 0;
4766 	lpfc_get_vport_cfgparam(vport);
4767 
4768 	/* Adjust value in vport */
4769 	vport->cfg_enable_fc4_type = phba->cfg_enable_fc4_type;
4770 
4771 	shost->unique_id = instance;
4772 	shost->max_id = LPFC_MAX_TARGET;
4773 	shost->max_lun = vport->cfg_max_luns;
4774 	shost->this_id = -1;
4775 	shost->max_cmd_len = 16;
4776 
4777 	if (phba->sli_rev == LPFC_SLI_REV4) {
4778 		if (!phba->cfg_fcp_mq_threshold ||
4779 		    phba->cfg_fcp_mq_threshold > phba->cfg_hdw_queue)
4780 			phba->cfg_fcp_mq_threshold = phba->cfg_hdw_queue;
4781 
4782 		shost->nr_hw_queues = min_t(int, 2 * num_possible_nodes(),
4783 					    phba->cfg_fcp_mq_threshold);
4784 
4785 		shost->dma_boundary =
4786 			phba->sli4_hba.pc_sli4_params.sge_supp_len-1;
4787 	} else
4788 		/* SLI-3 has a limited number of hardware queues (3),
4789 		 * thus there is only one for FCP processing.
4790 		 */
4791 		shost->nr_hw_queues = 1;
4792 
4793 	/*
4794 	 * Set initial can_queue value since 0 is no longer supported and
4795 	 * scsi_add_host will fail. This will be adjusted later based on the
4796 	 * max xri value determined in hba setup.
4797 	 */
4798 	shost->can_queue = phba->cfg_hba_queue_depth - 10;
4799 	if (dev != &phba->pcidev->dev) {
4800 		shost->transportt = lpfc_vport_transport_template;
4801 		vport->port_type = LPFC_NPIV_PORT;
4802 	} else {
4803 		shost->transportt = lpfc_transport_template;
4804 		vport->port_type = LPFC_PHYSICAL_PORT;
4805 	}
4806 
4807 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP,
4808 			"9081 CreatePort TMPLATE type %x TBLsize %d "
4809 			"SEGcnt %d/%d\n",
4810 			vport->port_type, shost->sg_tablesize,
4811 			phba->cfg_scsi_seg_cnt, phba->cfg_sg_seg_cnt);
4812 
4813 	/* Allocate the resources for VMID */
4814 	rc = lpfc_vmid_res_alloc(phba, vport);
4815 
4816 	if (rc)
4817 		goto out_put_shost;
4818 
4819 	/* Initialize all internally managed lists. */
4820 	INIT_LIST_HEAD(&vport->fc_nodes);
4821 	INIT_LIST_HEAD(&vport->rcv_buffer_list);
4822 	spin_lock_init(&vport->work_port_lock);
4823 
4824 	timer_setup(&vport->fc_disctmo, lpfc_disc_timeout, 0);
4825 
4826 	timer_setup(&vport->els_tmofunc, lpfc_els_timeout, 0);
4827 
4828 	timer_setup(&vport->delayed_disc_tmo, lpfc_delayed_disc_tmo, 0);
4829 
4830 	if (phba->sli3_options & LPFC_SLI3_BG_ENABLED)
4831 		lpfc_setup_bg(phba, shost);
4832 
4833 	error = scsi_add_host_with_dma(shost, dev, &phba->pcidev->dev);
4834 	if (error)
4835 		goto out_free_vmid;
4836 
4837 	spin_lock_irq(&phba->port_list_lock);
4838 	list_add_tail(&vport->listentry, &phba->port_list);
4839 	spin_unlock_irq(&phba->port_list_lock);
4840 	return vport;
4841 
4842 out_free_vmid:
4843 	kfree(vport->vmid);
4844 	bitmap_free(vport->vmid_priority_range);
4845 out_put_shost:
4846 	scsi_host_put(shost);
4847 out:
4848 	return NULL;
4849 }
4850 
4851 /**
4852  * destroy_port -  destroy an FC port
4853  * @vport: pointer to an lpfc virtual N_Port data structure.
4854  *
4855  * This routine destroys a FC port from the upper layer protocol. All the
4856  * resources associated with the port are released.
4857  **/
4858 void
4859 destroy_port(struct lpfc_vport *vport)
4860 {
4861 	struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
4862 	struct lpfc_hba  *phba = vport->phba;
4863 
4864 	lpfc_debugfs_terminate(vport);
4865 	fc_remove_host(shost);
4866 	scsi_remove_host(shost);
4867 
4868 	spin_lock_irq(&phba->port_list_lock);
4869 	list_del_init(&vport->listentry);
4870 	spin_unlock_irq(&phba->port_list_lock);
4871 
4872 	lpfc_cleanup(vport);
4873 	return;
4874 }
4875 
4876 /**
4877  * lpfc_get_instance - Get a unique integer ID
4878  *
4879  * This routine allocates a unique integer ID from lpfc_hba_index pool. It
4880  * uses the kernel idr facility to perform the task.
4881  *
4882  * Return codes:
4883  *   instance - a unique integer ID allocated as the new instance.
4884  *   -1 - lpfc get instance failed.
4885  **/
4886 int
4887 lpfc_get_instance(void)
4888 {
4889 	int ret;
4890 
4891 	ret = idr_alloc(&lpfc_hba_index, NULL, 0, 0, GFP_KERNEL);
4892 	return ret < 0 ? -1 : ret;
4893 }
4894 
4895 /**
4896  * lpfc_scan_finished - method for SCSI layer to detect whether scan is done
4897  * @shost: pointer to SCSI host data structure.
4898  * @time: elapsed time of the scan in jiffies.
4899  *
4900  * This routine is called by the SCSI layer with a SCSI host to determine
4901  * whether the scan host is finished.
4902  *
4903  * Note: there is no scan_start function as adapter initialization will have
4904  * asynchronously kicked off the link initialization.
4905  *
4906  * Return codes
4907  *   0 - SCSI host scan is not over yet.
4908  *   1 - SCSI host scan is over.
4909  **/
4910 int lpfc_scan_finished(struct Scsi_Host *shost, unsigned long time)
4911 {
4912 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
4913 	struct lpfc_hba   *phba = vport->phba;
4914 	int stat = 0;
4915 
4916 	spin_lock_irq(shost->host_lock);
4917 
4918 	if (vport->load_flag & FC_UNLOADING) {
4919 		stat = 1;
4920 		goto finished;
4921 	}
4922 	if (time >= msecs_to_jiffies(30 * 1000)) {
4923 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4924 				"0461 Scanning longer than 30 "
4925 				"seconds.  Continuing initialization\n");
4926 		stat = 1;
4927 		goto finished;
4928 	}
4929 	if (time >= msecs_to_jiffies(15 * 1000) &&
4930 	    phba->link_state <= LPFC_LINK_DOWN) {
4931 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4932 				"0465 Link down longer than 15 "
4933 				"seconds.  Continuing initialization\n");
4934 		stat = 1;
4935 		goto finished;
4936 	}
4937 
4938 	if (vport->port_state != LPFC_VPORT_READY)
4939 		goto finished;
4940 	if (vport->num_disc_nodes || vport->fc_prli_sent)
4941 		goto finished;
4942 	if (vport->fc_map_cnt == 0 && time < msecs_to_jiffies(2 * 1000))
4943 		goto finished;
4944 	if ((phba->sli.sli_flag & LPFC_SLI_MBOX_ACTIVE) != 0)
4945 		goto finished;
4946 
4947 	stat = 1;
4948 
4949 finished:
4950 	spin_unlock_irq(shost->host_lock);
4951 	return stat;
4952 }
4953 
4954 static void lpfc_host_supported_speeds_set(struct Scsi_Host *shost)
4955 {
4956 	struct lpfc_vport *vport = (struct lpfc_vport *)shost->hostdata;
4957 	struct lpfc_hba   *phba = vport->phba;
4958 
4959 	fc_host_supported_speeds(shost) = 0;
4960 	/*
4961 	 * Avoid reporting supported link speed for FCoE as it can't be
4962 	 * controlled via FCoE.
4963 	 */
4964 	if (phba->hba_flag & HBA_FCOE_MODE)
4965 		return;
4966 
4967 	if (phba->lmt & LMT_256Gb)
4968 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_256GBIT;
4969 	if (phba->lmt & LMT_128Gb)
4970 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_128GBIT;
4971 	if (phba->lmt & LMT_64Gb)
4972 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_64GBIT;
4973 	if (phba->lmt & LMT_32Gb)
4974 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_32GBIT;
4975 	if (phba->lmt & LMT_16Gb)
4976 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_16GBIT;
4977 	if (phba->lmt & LMT_10Gb)
4978 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_10GBIT;
4979 	if (phba->lmt & LMT_8Gb)
4980 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_8GBIT;
4981 	if (phba->lmt & LMT_4Gb)
4982 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_4GBIT;
4983 	if (phba->lmt & LMT_2Gb)
4984 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_2GBIT;
4985 	if (phba->lmt & LMT_1Gb)
4986 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_1GBIT;
4987 }
4988 
4989 /**
4990  * lpfc_host_attrib_init - Initialize SCSI host attributes on a FC port
4991  * @shost: pointer to SCSI host data structure.
4992  *
4993  * This routine initializes a given SCSI host attributes on a FC port. The
4994  * SCSI host can be either on top of a physical port or a virtual port.
4995  **/
4996 void lpfc_host_attrib_init(struct Scsi_Host *shost)
4997 {
4998 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
4999 	struct lpfc_hba   *phba = vport->phba;
5000 	/*
5001 	 * Set fixed host attributes.  Must done after lpfc_sli_hba_setup().
5002 	 */
5003 
5004 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
5005 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
5006 	fc_host_supported_classes(shost) = FC_COS_CLASS3;
5007 
5008 	memset(fc_host_supported_fc4s(shost), 0,
5009 	       sizeof(fc_host_supported_fc4s(shost)));
5010 	fc_host_supported_fc4s(shost)[2] = 1;
5011 	fc_host_supported_fc4s(shost)[7] = 1;
5012 
5013 	lpfc_vport_symbolic_node_name(vport, fc_host_symbolic_name(shost),
5014 				 sizeof fc_host_symbolic_name(shost));
5015 
5016 	lpfc_host_supported_speeds_set(shost);
5017 
5018 	fc_host_maxframe_size(shost) =
5019 		(((uint32_t) vport->fc_sparam.cmn.bbRcvSizeMsb & 0x0F) << 8) |
5020 		(uint32_t) vport->fc_sparam.cmn.bbRcvSizeLsb;
5021 
5022 	fc_host_dev_loss_tmo(shost) = vport->cfg_devloss_tmo;
5023 
5024 	/* This value is also unchanging */
5025 	memset(fc_host_active_fc4s(shost), 0,
5026 	       sizeof(fc_host_active_fc4s(shost)));
5027 	fc_host_active_fc4s(shost)[2] = 1;
5028 	fc_host_active_fc4s(shost)[7] = 1;
5029 
5030 	fc_host_max_npiv_vports(shost) = phba->max_vpi;
5031 	spin_lock_irq(shost->host_lock);
5032 	vport->load_flag &= ~FC_LOADING;
5033 	spin_unlock_irq(shost->host_lock);
5034 }
5035 
5036 /**
5037  * lpfc_stop_port_s3 - Stop SLI3 device port
5038  * @phba: pointer to lpfc hba data structure.
5039  *
5040  * This routine is invoked to stop an SLI3 device port, it stops the device
5041  * from generating interrupts and stops the device driver's timers for the
5042  * device.
5043  **/
5044 static void
5045 lpfc_stop_port_s3(struct lpfc_hba *phba)
5046 {
5047 	/* Clear all interrupt enable conditions */
5048 	writel(0, phba->HCregaddr);
5049 	readl(phba->HCregaddr); /* flush */
5050 	/* Clear all pending interrupts */
5051 	writel(0xffffffff, phba->HAregaddr);
5052 	readl(phba->HAregaddr); /* flush */
5053 
5054 	/* Reset some HBA SLI setup states */
5055 	lpfc_stop_hba_timers(phba);
5056 	phba->pport->work_port_events = 0;
5057 }
5058 
5059 /**
5060  * lpfc_stop_port_s4 - Stop SLI4 device port
5061  * @phba: pointer to lpfc hba data structure.
5062  *
5063  * This routine is invoked to stop an SLI4 device port, it stops the device
5064  * from generating interrupts and stops the device driver's timers for the
5065  * device.
5066  **/
5067 static void
5068 lpfc_stop_port_s4(struct lpfc_hba *phba)
5069 {
5070 	/* Reset some HBA SLI4 setup states */
5071 	lpfc_stop_hba_timers(phba);
5072 	if (phba->pport)
5073 		phba->pport->work_port_events = 0;
5074 	phba->sli4_hba.intr_enable = 0;
5075 }
5076 
5077 /**
5078  * lpfc_stop_port - Wrapper function for stopping hba port
5079  * @phba: Pointer to HBA context object.
5080  *
5081  * This routine wraps the actual SLI3 or SLI4 hba stop port routine from
5082  * the API jump table function pointer from the lpfc_hba struct.
5083  **/
5084 void
5085 lpfc_stop_port(struct lpfc_hba *phba)
5086 {
5087 	phba->lpfc_stop_port(phba);
5088 
5089 	if (phba->wq)
5090 		flush_workqueue(phba->wq);
5091 }
5092 
5093 /**
5094  * lpfc_fcf_redisc_wait_start_timer - Start fcf rediscover wait timer
5095  * @phba: Pointer to hba for which this call is being executed.
5096  *
5097  * This routine starts the timer waiting for the FCF rediscovery to complete.
5098  **/
5099 void
5100 lpfc_fcf_redisc_wait_start_timer(struct lpfc_hba *phba)
5101 {
5102 	unsigned long fcf_redisc_wait_tmo =
5103 		(jiffies + msecs_to_jiffies(LPFC_FCF_REDISCOVER_WAIT_TMO));
5104 	/* Start fcf rediscovery wait period timer */
5105 	mod_timer(&phba->fcf.redisc_wait, fcf_redisc_wait_tmo);
5106 	spin_lock_irq(&phba->hbalock);
5107 	/* Allow action to new fcf asynchronous event */
5108 	phba->fcf.fcf_flag &= ~(FCF_AVAILABLE | FCF_SCAN_DONE);
5109 	/* Mark the FCF rediscovery pending state */
5110 	phba->fcf.fcf_flag |= FCF_REDISC_PEND;
5111 	spin_unlock_irq(&phba->hbalock);
5112 }
5113 
5114 /**
5115  * lpfc_sli4_fcf_redisc_wait_tmo - FCF table rediscover wait timeout
5116  * @t: Timer context used to obtain the pointer to lpfc hba data structure.
5117  *
5118  * This routine is invoked when waiting for FCF table rediscover has been
5119  * timed out. If new FCF record(s) has (have) been discovered during the
5120  * wait period, a new FCF event shall be added to the FCOE async event
5121  * list, and then worker thread shall be waked up for processing from the
5122  * worker thread context.
5123  **/
5124 static void
5125 lpfc_sli4_fcf_redisc_wait_tmo(struct timer_list *t)
5126 {
5127 	struct lpfc_hba *phba = from_timer(phba, t, fcf.redisc_wait);
5128 
5129 	/* Don't send FCF rediscovery event if timer cancelled */
5130 	spin_lock_irq(&phba->hbalock);
5131 	if (!(phba->fcf.fcf_flag & FCF_REDISC_PEND)) {
5132 		spin_unlock_irq(&phba->hbalock);
5133 		return;
5134 	}
5135 	/* Clear FCF rediscovery timer pending flag */
5136 	phba->fcf.fcf_flag &= ~FCF_REDISC_PEND;
5137 	/* FCF rediscovery event to worker thread */
5138 	phba->fcf.fcf_flag |= FCF_REDISC_EVT;
5139 	spin_unlock_irq(&phba->hbalock);
5140 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
5141 			"2776 FCF rediscover quiescent timer expired\n");
5142 	/* wake up worker thread */
5143 	lpfc_worker_wake_up(phba);
5144 }
5145 
5146 /**
5147  * lpfc_vmid_poll - VMID timeout detection
5148  * @t: Timer context used to obtain the pointer to lpfc hba data structure.
5149  *
5150  * This routine is invoked when there is no I/O on by a VM for the specified
5151  * amount of time. When this situation is detected, the VMID has to be
5152  * deregistered from the switch and all the local resources freed. The VMID
5153  * will be reassigned to the VM once the I/O begins.
5154  **/
5155 static void
5156 lpfc_vmid_poll(struct timer_list *t)
5157 {
5158 	struct lpfc_hba *phba = from_timer(phba, t, inactive_vmid_poll);
5159 	u32 wake_up = 0;
5160 
5161 	/* check if there is a need to issue QFPA */
5162 	if (phba->pport->vmid_priority_tagging) {
5163 		wake_up = 1;
5164 		phba->pport->work_port_events |= WORKER_CHECK_VMID_ISSUE_QFPA;
5165 	}
5166 
5167 	/* Is the vmid inactivity timer enabled */
5168 	if (phba->pport->vmid_inactivity_timeout ||
5169 	    phba->pport->load_flag & FC_DEREGISTER_ALL_APP_ID) {
5170 		wake_up = 1;
5171 		phba->pport->work_port_events |= WORKER_CHECK_INACTIVE_VMID;
5172 	}
5173 
5174 	if (wake_up)
5175 		lpfc_worker_wake_up(phba);
5176 
5177 	/* restart the timer for the next iteration */
5178 	mod_timer(&phba->inactive_vmid_poll, jiffies + msecs_to_jiffies(1000 *
5179 							LPFC_VMID_TIMER));
5180 }
5181 
5182 /**
5183  * lpfc_sli4_parse_latt_fault - Parse sli4 link-attention link fault code
5184  * @phba: pointer to lpfc hba data structure.
5185  * @acqe_link: pointer to the async link completion queue entry.
5186  *
5187  * This routine is to parse the SLI4 link-attention link fault code.
5188  **/
5189 static void
5190 lpfc_sli4_parse_latt_fault(struct lpfc_hba *phba,
5191 			   struct lpfc_acqe_link *acqe_link)
5192 {
5193 	switch (bf_get(lpfc_acqe_fc_la_att_type, acqe_link)) {
5194 	case LPFC_FC_LA_TYPE_LINK_DOWN:
5195 	case LPFC_FC_LA_TYPE_TRUNKING_EVENT:
5196 	case LPFC_FC_LA_TYPE_ACTIVATE_FAIL:
5197 	case LPFC_FC_LA_TYPE_LINK_RESET_PRTCL_EVT:
5198 		break;
5199 	default:
5200 		switch (bf_get(lpfc_acqe_link_fault, acqe_link)) {
5201 		case LPFC_ASYNC_LINK_FAULT_NONE:
5202 		case LPFC_ASYNC_LINK_FAULT_LOCAL:
5203 		case LPFC_ASYNC_LINK_FAULT_REMOTE:
5204 		case LPFC_ASYNC_LINK_FAULT_LR_LRR:
5205 			break;
5206 		default:
5207 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5208 					"0398 Unknown link fault code: x%x\n",
5209 					bf_get(lpfc_acqe_link_fault, acqe_link));
5210 			break;
5211 		}
5212 		break;
5213 	}
5214 }
5215 
5216 /**
5217  * lpfc_sli4_parse_latt_type - Parse sli4 link attention type
5218  * @phba: pointer to lpfc hba data structure.
5219  * @acqe_link: pointer to the async link completion queue entry.
5220  *
5221  * This routine is to parse the SLI4 link attention type and translate it
5222  * into the base driver's link attention type coding.
5223  *
5224  * Return: Link attention type in terms of base driver's coding.
5225  **/
5226 static uint8_t
5227 lpfc_sli4_parse_latt_type(struct lpfc_hba *phba,
5228 			  struct lpfc_acqe_link *acqe_link)
5229 {
5230 	uint8_t att_type;
5231 
5232 	switch (bf_get(lpfc_acqe_link_status, acqe_link)) {
5233 	case LPFC_ASYNC_LINK_STATUS_DOWN:
5234 	case LPFC_ASYNC_LINK_STATUS_LOGICAL_DOWN:
5235 		att_type = LPFC_ATT_LINK_DOWN;
5236 		break;
5237 	case LPFC_ASYNC_LINK_STATUS_UP:
5238 		/* Ignore physical link up events - wait for logical link up */
5239 		att_type = LPFC_ATT_RESERVED;
5240 		break;
5241 	case LPFC_ASYNC_LINK_STATUS_LOGICAL_UP:
5242 		att_type = LPFC_ATT_LINK_UP;
5243 		break;
5244 	default:
5245 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5246 				"0399 Invalid link attention type: x%x\n",
5247 				bf_get(lpfc_acqe_link_status, acqe_link));
5248 		att_type = LPFC_ATT_RESERVED;
5249 		break;
5250 	}
5251 	return att_type;
5252 }
5253 
5254 /**
5255  * lpfc_sli_port_speed_get - Get sli3 link speed code to link speed
5256  * @phba: pointer to lpfc hba data structure.
5257  *
5258  * This routine is to get an SLI3 FC port's link speed in Mbps.
5259  *
5260  * Return: link speed in terms of Mbps.
5261  **/
5262 uint32_t
5263 lpfc_sli_port_speed_get(struct lpfc_hba *phba)
5264 {
5265 	uint32_t link_speed;
5266 
5267 	if (!lpfc_is_link_up(phba))
5268 		return 0;
5269 
5270 	if (phba->sli_rev <= LPFC_SLI_REV3) {
5271 		switch (phba->fc_linkspeed) {
5272 		case LPFC_LINK_SPEED_1GHZ:
5273 			link_speed = 1000;
5274 			break;
5275 		case LPFC_LINK_SPEED_2GHZ:
5276 			link_speed = 2000;
5277 			break;
5278 		case LPFC_LINK_SPEED_4GHZ:
5279 			link_speed = 4000;
5280 			break;
5281 		case LPFC_LINK_SPEED_8GHZ:
5282 			link_speed = 8000;
5283 			break;
5284 		case LPFC_LINK_SPEED_10GHZ:
5285 			link_speed = 10000;
5286 			break;
5287 		case LPFC_LINK_SPEED_16GHZ:
5288 			link_speed = 16000;
5289 			break;
5290 		default:
5291 			link_speed = 0;
5292 		}
5293 	} else {
5294 		if (phba->sli4_hba.link_state.logical_speed)
5295 			link_speed =
5296 			      phba->sli4_hba.link_state.logical_speed;
5297 		else
5298 			link_speed = phba->sli4_hba.link_state.speed;
5299 	}
5300 	return link_speed;
5301 }
5302 
5303 /**
5304  * lpfc_sli4_port_speed_parse - Parse async evt link speed code to link speed
5305  * @phba: pointer to lpfc hba data structure.
5306  * @evt_code: asynchronous event code.
5307  * @speed_code: asynchronous event link speed code.
5308  *
5309  * This routine is to parse the giving SLI4 async event link speed code into
5310  * value of Mbps for the link speed.
5311  *
5312  * Return: link speed in terms of Mbps.
5313  **/
5314 static uint32_t
5315 lpfc_sli4_port_speed_parse(struct lpfc_hba *phba, uint32_t evt_code,
5316 			   uint8_t speed_code)
5317 {
5318 	uint32_t port_speed;
5319 
5320 	switch (evt_code) {
5321 	case LPFC_TRAILER_CODE_LINK:
5322 		switch (speed_code) {
5323 		case LPFC_ASYNC_LINK_SPEED_ZERO:
5324 			port_speed = 0;
5325 			break;
5326 		case LPFC_ASYNC_LINK_SPEED_10MBPS:
5327 			port_speed = 10;
5328 			break;
5329 		case LPFC_ASYNC_LINK_SPEED_100MBPS:
5330 			port_speed = 100;
5331 			break;
5332 		case LPFC_ASYNC_LINK_SPEED_1GBPS:
5333 			port_speed = 1000;
5334 			break;
5335 		case LPFC_ASYNC_LINK_SPEED_10GBPS:
5336 			port_speed = 10000;
5337 			break;
5338 		case LPFC_ASYNC_LINK_SPEED_20GBPS:
5339 			port_speed = 20000;
5340 			break;
5341 		case LPFC_ASYNC_LINK_SPEED_25GBPS:
5342 			port_speed = 25000;
5343 			break;
5344 		case LPFC_ASYNC_LINK_SPEED_40GBPS:
5345 			port_speed = 40000;
5346 			break;
5347 		case LPFC_ASYNC_LINK_SPEED_100GBPS:
5348 			port_speed = 100000;
5349 			break;
5350 		default:
5351 			port_speed = 0;
5352 		}
5353 		break;
5354 	case LPFC_TRAILER_CODE_FC:
5355 		switch (speed_code) {
5356 		case LPFC_FC_LA_SPEED_UNKNOWN:
5357 			port_speed = 0;
5358 			break;
5359 		case LPFC_FC_LA_SPEED_1G:
5360 			port_speed = 1000;
5361 			break;
5362 		case LPFC_FC_LA_SPEED_2G:
5363 			port_speed = 2000;
5364 			break;
5365 		case LPFC_FC_LA_SPEED_4G:
5366 			port_speed = 4000;
5367 			break;
5368 		case LPFC_FC_LA_SPEED_8G:
5369 			port_speed = 8000;
5370 			break;
5371 		case LPFC_FC_LA_SPEED_10G:
5372 			port_speed = 10000;
5373 			break;
5374 		case LPFC_FC_LA_SPEED_16G:
5375 			port_speed = 16000;
5376 			break;
5377 		case LPFC_FC_LA_SPEED_32G:
5378 			port_speed = 32000;
5379 			break;
5380 		case LPFC_FC_LA_SPEED_64G:
5381 			port_speed = 64000;
5382 			break;
5383 		case LPFC_FC_LA_SPEED_128G:
5384 			port_speed = 128000;
5385 			break;
5386 		case LPFC_FC_LA_SPEED_256G:
5387 			port_speed = 256000;
5388 			break;
5389 		default:
5390 			port_speed = 0;
5391 		}
5392 		break;
5393 	default:
5394 		port_speed = 0;
5395 	}
5396 	return port_speed;
5397 }
5398 
5399 /**
5400  * lpfc_sli4_async_link_evt - Process the asynchronous FCoE link event
5401  * @phba: pointer to lpfc hba data structure.
5402  * @acqe_link: pointer to the async link completion queue entry.
5403  *
5404  * This routine is to handle the SLI4 asynchronous FCoE link event.
5405  **/
5406 static void
5407 lpfc_sli4_async_link_evt(struct lpfc_hba *phba,
5408 			 struct lpfc_acqe_link *acqe_link)
5409 {
5410 	LPFC_MBOXQ_t *pmb;
5411 	MAILBOX_t *mb;
5412 	struct lpfc_mbx_read_top *la;
5413 	uint8_t att_type;
5414 	int rc;
5415 
5416 	att_type = lpfc_sli4_parse_latt_type(phba, acqe_link);
5417 	if (att_type != LPFC_ATT_LINK_DOWN && att_type != LPFC_ATT_LINK_UP)
5418 		return;
5419 	phba->fcoe_eventtag = acqe_link->event_tag;
5420 	pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5421 	if (!pmb) {
5422 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5423 				"0395 The mboxq allocation failed\n");
5424 		return;
5425 	}
5426 
5427 	rc = lpfc_mbox_rsrc_prep(phba, pmb);
5428 	if (rc) {
5429 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5430 				"0396 mailbox allocation failed\n");
5431 		goto out_free_pmb;
5432 	}
5433 
5434 	/* Cleanup any outstanding ELS commands */
5435 	lpfc_els_flush_all_cmd(phba);
5436 
5437 	/* Block ELS IOCBs until we have done process link event */
5438 	phba->sli4_hba.els_wq->pring->flag |= LPFC_STOP_IOCB_EVENT;
5439 
5440 	/* Update link event statistics */
5441 	phba->sli.slistat.link_event++;
5442 
5443 	/* Create lpfc_handle_latt mailbox command from link ACQE */
5444 	lpfc_read_topology(phba, pmb, (struct lpfc_dmabuf *)pmb->ctx_buf);
5445 	pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
5446 	pmb->vport = phba->pport;
5447 
5448 	/* Keep the link status for extra SLI4 state machine reference */
5449 	phba->sli4_hba.link_state.speed =
5450 			lpfc_sli4_port_speed_parse(phba, LPFC_TRAILER_CODE_LINK,
5451 				bf_get(lpfc_acqe_link_speed, acqe_link));
5452 	phba->sli4_hba.link_state.duplex =
5453 				bf_get(lpfc_acqe_link_duplex, acqe_link);
5454 	phba->sli4_hba.link_state.status =
5455 				bf_get(lpfc_acqe_link_status, acqe_link);
5456 	phba->sli4_hba.link_state.type =
5457 				bf_get(lpfc_acqe_link_type, acqe_link);
5458 	phba->sli4_hba.link_state.number =
5459 				bf_get(lpfc_acqe_link_number, acqe_link);
5460 	phba->sli4_hba.link_state.fault =
5461 				bf_get(lpfc_acqe_link_fault, acqe_link);
5462 	phba->sli4_hba.link_state.logical_speed =
5463 			bf_get(lpfc_acqe_logical_link_speed, acqe_link) * 10;
5464 
5465 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5466 			"2900 Async FC/FCoE Link event - Speed:%dGBit "
5467 			"duplex:x%x LA Type:x%x Port Type:%d Port Number:%d "
5468 			"Logical speed:%dMbps Fault:%d\n",
5469 			phba->sli4_hba.link_state.speed,
5470 			phba->sli4_hba.link_state.topology,
5471 			phba->sli4_hba.link_state.status,
5472 			phba->sli4_hba.link_state.type,
5473 			phba->sli4_hba.link_state.number,
5474 			phba->sli4_hba.link_state.logical_speed,
5475 			phba->sli4_hba.link_state.fault);
5476 	/*
5477 	 * For FC Mode: issue the READ_TOPOLOGY mailbox command to fetch
5478 	 * topology info. Note: Optional for non FC-AL ports.
5479 	 */
5480 	if (!(phba->hba_flag & HBA_FCOE_MODE)) {
5481 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
5482 		if (rc == MBX_NOT_FINISHED)
5483 			goto out_free_pmb;
5484 		return;
5485 	}
5486 	/*
5487 	 * For FCoE Mode: fill in all the topology information we need and call
5488 	 * the READ_TOPOLOGY completion routine to continue without actually
5489 	 * sending the READ_TOPOLOGY mailbox command to the port.
5490 	 */
5491 	/* Initialize completion status */
5492 	mb = &pmb->u.mb;
5493 	mb->mbxStatus = MBX_SUCCESS;
5494 
5495 	/* Parse port fault information field */
5496 	lpfc_sli4_parse_latt_fault(phba, acqe_link);
5497 
5498 	/* Parse and translate link attention fields */
5499 	la = (struct lpfc_mbx_read_top *) &pmb->u.mb.un.varReadTop;
5500 	la->eventTag = acqe_link->event_tag;
5501 	bf_set(lpfc_mbx_read_top_att_type, la, att_type);
5502 	bf_set(lpfc_mbx_read_top_link_spd, la,
5503 	       (bf_get(lpfc_acqe_link_speed, acqe_link)));
5504 
5505 	/* Fake the following irrelevant fields */
5506 	bf_set(lpfc_mbx_read_top_topology, la, LPFC_TOPOLOGY_PT_PT);
5507 	bf_set(lpfc_mbx_read_top_alpa_granted, la, 0);
5508 	bf_set(lpfc_mbx_read_top_il, la, 0);
5509 	bf_set(lpfc_mbx_read_top_pb, la, 0);
5510 	bf_set(lpfc_mbx_read_top_fa, la, 0);
5511 	bf_set(lpfc_mbx_read_top_mm, la, 0);
5512 
5513 	/* Invoke the lpfc_handle_latt mailbox command callback function */
5514 	lpfc_mbx_cmpl_read_topology(phba, pmb);
5515 
5516 	return;
5517 
5518 out_free_pmb:
5519 	lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
5520 }
5521 
5522 /**
5523  * lpfc_async_link_speed_to_read_top - Parse async evt link speed code to read
5524  * topology.
5525  * @phba: pointer to lpfc hba data structure.
5526  * @speed_code: asynchronous event link speed code.
5527  *
5528  * This routine is to parse the giving SLI4 async event link speed code into
5529  * value of Read topology link speed.
5530  *
5531  * Return: link speed in terms of Read topology.
5532  **/
5533 static uint8_t
5534 lpfc_async_link_speed_to_read_top(struct lpfc_hba *phba, uint8_t speed_code)
5535 {
5536 	uint8_t port_speed;
5537 
5538 	switch (speed_code) {
5539 	case LPFC_FC_LA_SPEED_1G:
5540 		port_speed = LPFC_LINK_SPEED_1GHZ;
5541 		break;
5542 	case LPFC_FC_LA_SPEED_2G:
5543 		port_speed = LPFC_LINK_SPEED_2GHZ;
5544 		break;
5545 	case LPFC_FC_LA_SPEED_4G:
5546 		port_speed = LPFC_LINK_SPEED_4GHZ;
5547 		break;
5548 	case LPFC_FC_LA_SPEED_8G:
5549 		port_speed = LPFC_LINK_SPEED_8GHZ;
5550 		break;
5551 	case LPFC_FC_LA_SPEED_16G:
5552 		port_speed = LPFC_LINK_SPEED_16GHZ;
5553 		break;
5554 	case LPFC_FC_LA_SPEED_32G:
5555 		port_speed = LPFC_LINK_SPEED_32GHZ;
5556 		break;
5557 	case LPFC_FC_LA_SPEED_64G:
5558 		port_speed = LPFC_LINK_SPEED_64GHZ;
5559 		break;
5560 	case LPFC_FC_LA_SPEED_128G:
5561 		port_speed = LPFC_LINK_SPEED_128GHZ;
5562 		break;
5563 	case LPFC_FC_LA_SPEED_256G:
5564 		port_speed = LPFC_LINK_SPEED_256GHZ;
5565 		break;
5566 	default:
5567 		port_speed = 0;
5568 		break;
5569 	}
5570 
5571 	return port_speed;
5572 }
5573 
5574 void
5575 lpfc_cgn_dump_rxmonitor(struct lpfc_hba *phba)
5576 {
5577 	if (!phba->rx_monitor) {
5578 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5579 				"4411 Rx Monitor Info is empty.\n");
5580 	} else {
5581 		lpfc_rx_monitor_report(phba, phba->rx_monitor, NULL, 0,
5582 				       LPFC_MAX_RXMONITOR_DUMP);
5583 	}
5584 }
5585 
5586 /**
5587  * lpfc_cgn_update_stat - Save data into congestion stats buffer
5588  * @phba: pointer to lpfc hba data structure.
5589  * @dtag: FPIN descriptor received
5590  *
5591  * Increment the FPIN received counter/time when it happens.
5592  */
5593 void
5594 lpfc_cgn_update_stat(struct lpfc_hba *phba, uint32_t dtag)
5595 {
5596 	struct lpfc_cgn_info *cp;
5597 	struct tm broken;
5598 	struct timespec64 cur_time;
5599 	u32 cnt;
5600 	u32 value;
5601 
5602 	/* Make sure we have a congestion info buffer */
5603 	if (!phba->cgn_i)
5604 		return;
5605 	cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
5606 	ktime_get_real_ts64(&cur_time);
5607 	time64_to_tm(cur_time.tv_sec, 0, &broken);
5608 
5609 	/* Update congestion statistics */
5610 	switch (dtag) {
5611 	case ELS_DTAG_LNK_INTEGRITY:
5612 		cnt = le32_to_cpu(cp->link_integ_notification);
5613 		cnt++;
5614 		cp->link_integ_notification = cpu_to_le32(cnt);
5615 
5616 		cp->cgn_stat_lnk_month = broken.tm_mon + 1;
5617 		cp->cgn_stat_lnk_day = broken.tm_mday;
5618 		cp->cgn_stat_lnk_year = broken.tm_year - 100;
5619 		cp->cgn_stat_lnk_hour = broken.tm_hour;
5620 		cp->cgn_stat_lnk_min = broken.tm_min;
5621 		cp->cgn_stat_lnk_sec = broken.tm_sec;
5622 		break;
5623 	case ELS_DTAG_DELIVERY:
5624 		cnt = le32_to_cpu(cp->delivery_notification);
5625 		cnt++;
5626 		cp->delivery_notification = cpu_to_le32(cnt);
5627 
5628 		cp->cgn_stat_del_month = broken.tm_mon + 1;
5629 		cp->cgn_stat_del_day = broken.tm_mday;
5630 		cp->cgn_stat_del_year = broken.tm_year - 100;
5631 		cp->cgn_stat_del_hour = broken.tm_hour;
5632 		cp->cgn_stat_del_min = broken.tm_min;
5633 		cp->cgn_stat_del_sec = broken.tm_sec;
5634 		break;
5635 	case ELS_DTAG_PEER_CONGEST:
5636 		cnt = le32_to_cpu(cp->cgn_peer_notification);
5637 		cnt++;
5638 		cp->cgn_peer_notification = cpu_to_le32(cnt);
5639 
5640 		cp->cgn_stat_peer_month = broken.tm_mon + 1;
5641 		cp->cgn_stat_peer_day = broken.tm_mday;
5642 		cp->cgn_stat_peer_year = broken.tm_year - 100;
5643 		cp->cgn_stat_peer_hour = broken.tm_hour;
5644 		cp->cgn_stat_peer_min = broken.tm_min;
5645 		cp->cgn_stat_peer_sec = broken.tm_sec;
5646 		break;
5647 	case ELS_DTAG_CONGESTION:
5648 		cnt = le32_to_cpu(cp->cgn_notification);
5649 		cnt++;
5650 		cp->cgn_notification = cpu_to_le32(cnt);
5651 
5652 		cp->cgn_stat_cgn_month = broken.tm_mon + 1;
5653 		cp->cgn_stat_cgn_day = broken.tm_mday;
5654 		cp->cgn_stat_cgn_year = broken.tm_year - 100;
5655 		cp->cgn_stat_cgn_hour = broken.tm_hour;
5656 		cp->cgn_stat_cgn_min = broken.tm_min;
5657 		cp->cgn_stat_cgn_sec = broken.tm_sec;
5658 	}
5659 	if (phba->cgn_fpin_frequency &&
5660 	    phba->cgn_fpin_frequency != LPFC_FPIN_INIT_FREQ) {
5661 		value = LPFC_CGN_TIMER_TO_MIN / phba->cgn_fpin_frequency;
5662 		cp->cgn_stat_npm = value;
5663 	}
5664 	value = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ,
5665 				    LPFC_CGN_CRC32_SEED);
5666 	cp->cgn_info_crc = cpu_to_le32(value);
5667 }
5668 
5669 /**
5670  * lpfc_cgn_save_evt_cnt - Save data into registered congestion buffer
5671  * @phba: pointer to lpfc hba data structure.
5672  *
5673  * Save the congestion event data every minute.
5674  * On the hour collapse all the minute data into hour data. Every day
5675  * collapse all the hour data into daily data. Separate driver
5676  * and fabrc congestion event counters that will be saved out
5677  * to the registered congestion buffer every minute.
5678  */
5679 static void
5680 lpfc_cgn_save_evt_cnt(struct lpfc_hba *phba)
5681 {
5682 	struct lpfc_cgn_info *cp;
5683 	struct tm broken;
5684 	struct timespec64 cur_time;
5685 	uint32_t i, index;
5686 	uint16_t value, mvalue;
5687 	uint64_t bps;
5688 	uint32_t mbps;
5689 	uint32_t dvalue, wvalue, lvalue, avalue;
5690 	uint64_t latsum;
5691 	__le16 *ptr;
5692 	__le32 *lptr;
5693 	__le16 *mptr;
5694 
5695 	/* Make sure we have a congestion info buffer */
5696 	if (!phba->cgn_i)
5697 		return;
5698 	cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
5699 
5700 	if (time_before(jiffies, phba->cgn_evt_timestamp))
5701 		return;
5702 	phba->cgn_evt_timestamp = jiffies +
5703 			msecs_to_jiffies(LPFC_CGN_TIMER_TO_MIN);
5704 	phba->cgn_evt_minute++;
5705 
5706 	/* We should get to this point in the routine on 1 minute intervals */
5707 
5708 	ktime_get_real_ts64(&cur_time);
5709 	time64_to_tm(cur_time.tv_sec, 0, &broken);
5710 
5711 	if (phba->cgn_fpin_frequency &&
5712 	    phba->cgn_fpin_frequency != LPFC_FPIN_INIT_FREQ) {
5713 		value = LPFC_CGN_TIMER_TO_MIN / phba->cgn_fpin_frequency;
5714 		cp->cgn_stat_npm = value;
5715 	}
5716 
5717 	/* Read and clear the latency counters for this minute */
5718 	lvalue = atomic_read(&phba->cgn_latency_evt_cnt);
5719 	latsum = atomic64_read(&phba->cgn_latency_evt);
5720 	atomic_set(&phba->cgn_latency_evt_cnt, 0);
5721 	atomic64_set(&phba->cgn_latency_evt, 0);
5722 
5723 	/* We need to store MB/sec bandwidth in the congestion information.
5724 	 * block_cnt is count of 512 byte blocks for the entire minute,
5725 	 * bps will get bytes per sec before finally converting to MB/sec.
5726 	 */
5727 	bps = div_u64(phba->rx_block_cnt, LPFC_SEC_MIN) * 512;
5728 	phba->rx_block_cnt = 0;
5729 	mvalue = bps / (1024 * 1024); /* convert to MB/sec */
5730 
5731 	/* Every minute */
5732 	/* cgn parameters */
5733 	cp->cgn_info_mode = phba->cgn_p.cgn_param_mode;
5734 	cp->cgn_info_level0 = phba->cgn_p.cgn_param_level0;
5735 	cp->cgn_info_level1 = phba->cgn_p.cgn_param_level1;
5736 	cp->cgn_info_level2 = phba->cgn_p.cgn_param_level2;
5737 
5738 	/* Fill in default LUN qdepth */
5739 	value = (uint16_t)(phba->pport->cfg_lun_queue_depth);
5740 	cp->cgn_lunq = cpu_to_le16(value);
5741 
5742 	/* Record congestion buffer info - every minute
5743 	 * cgn_driver_evt_cnt (Driver events)
5744 	 * cgn_fabric_warn_cnt (Congestion Warnings)
5745 	 * cgn_latency_evt_cnt / cgn_latency_evt (IO Latency)
5746 	 * cgn_fabric_alarm_cnt (Congestion Alarms)
5747 	 */
5748 	index = ++cp->cgn_index_minute;
5749 	if (cp->cgn_index_minute == LPFC_MIN_HOUR) {
5750 		cp->cgn_index_minute = 0;
5751 		index = 0;
5752 	}
5753 
5754 	/* Get the number of driver events in this sample and reset counter */
5755 	dvalue = atomic_read(&phba->cgn_driver_evt_cnt);
5756 	atomic_set(&phba->cgn_driver_evt_cnt, 0);
5757 
5758 	/* Get the number of warning events - FPIN and Signal for this minute */
5759 	wvalue = 0;
5760 	if ((phba->cgn_reg_fpin & LPFC_CGN_FPIN_WARN) ||
5761 	    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY ||
5762 	    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM)
5763 		wvalue = atomic_read(&phba->cgn_fabric_warn_cnt);
5764 	atomic_set(&phba->cgn_fabric_warn_cnt, 0);
5765 
5766 	/* Get the number of alarm events - FPIN and Signal for this minute */
5767 	avalue = 0;
5768 	if ((phba->cgn_reg_fpin & LPFC_CGN_FPIN_ALARM) ||
5769 	    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM)
5770 		avalue = atomic_read(&phba->cgn_fabric_alarm_cnt);
5771 	atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
5772 
5773 	/* Collect the driver, warning, alarm and latency counts for this
5774 	 * minute into the driver congestion buffer.
5775 	 */
5776 	ptr = &cp->cgn_drvr_min[index];
5777 	value = (uint16_t)dvalue;
5778 	*ptr = cpu_to_le16(value);
5779 
5780 	ptr = &cp->cgn_warn_min[index];
5781 	value = (uint16_t)wvalue;
5782 	*ptr = cpu_to_le16(value);
5783 
5784 	ptr = &cp->cgn_alarm_min[index];
5785 	value = (uint16_t)avalue;
5786 	*ptr = cpu_to_le16(value);
5787 
5788 	lptr = &cp->cgn_latency_min[index];
5789 	if (lvalue) {
5790 		lvalue = (uint32_t)div_u64(latsum, lvalue);
5791 		*lptr = cpu_to_le32(lvalue);
5792 	} else {
5793 		*lptr = 0;
5794 	}
5795 
5796 	/* Collect the bandwidth value into the driver's congesion buffer. */
5797 	mptr = &cp->cgn_bw_min[index];
5798 	*mptr = cpu_to_le16(mvalue);
5799 
5800 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5801 			"2418 Congestion Info - minute (%d): %d %d %d %d %d\n",
5802 			index, dvalue, wvalue, *lptr, mvalue, avalue);
5803 
5804 	/* Every hour */
5805 	if ((phba->cgn_evt_minute % LPFC_MIN_HOUR) == 0) {
5806 		/* Record congestion buffer info - every hour
5807 		 * Collapse all minutes into an hour
5808 		 */
5809 		index = ++cp->cgn_index_hour;
5810 		if (cp->cgn_index_hour == LPFC_HOUR_DAY) {
5811 			cp->cgn_index_hour = 0;
5812 			index = 0;
5813 		}
5814 
5815 		dvalue = 0;
5816 		wvalue = 0;
5817 		lvalue = 0;
5818 		avalue = 0;
5819 		mvalue = 0;
5820 		mbps = 0;
5821 		for (i = 0; i < LPFC_MIN_HOUR; i++) {
5822 			dvalue += le16_to_cpu(cp->cgn_drvr_min[i]);
5823 			wvalue += le16_to_cpu(cp->cgn_warn_min[i]);
5824 			lvalue += le32_to_cpu(cp->cgn_latency_min[i]);
5825 			mbps += le16_to_cpu(cp->cgn_bw_min[i]);
5826 			avalue += le16_to_cpu(cp->cgn_alarm_min[i]);
5827 		}
5828 		if (lvalue)		/* Avg of latency averages */
5829 			lvalue /= LPFC_MIN_HOUR;
5830 		if (mbps)		/* Avg of Bandwidth averages */
5831 			mvalue = mbps / LPFC_MIN_HOUR;
5832 
5833 		lptr = &cp->cgn_drvr_hr[index];
5834 		*lptr = cpu_to_le32(dvalue);
5835 		lptr = &cp->cgn_warn_hr[index];
5836 		*lptr = cpu_to_le32(wvalue);
5837 		lptr = &cp->cgn_latency_hr[index];
5838 		*lptr = cpu_to_le32(lvalue);
5839 		mptr = &cp->cgn_bw_hr[index];
5840 		*mptr = cpu_to_le16(mvalue);
5841 		lptr = &cp->cgn_alarm_hr[index];
5842 		*lptr = cpu_to_le32(avalue);
5843 
5844 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5845 				"2419 Congestion Info - hour "
5846 				"(%d): %d %d %d %d %d\n",
5847 				index, dvalue, wvalue, lvalue, mvalue, avalue);
5848 	}
5849 
5850 	/* Every day */
5851 	if ((phba->cgn_evt_minute % LPFC_MIN_DAY) == 0) {
5852 		/* Record congestion buffer info - every hour
5853 		 * Collapse all hours into a day. Rotate days
5854 		 * after LPFC_MAX_CGN_DAYS.
5855 		 */
5856 		index = ++cp->cgn_index_day;
5857 		if (cp->cgn_index_day == LPFC_MAX_CGN_DAYS) {
5858 			cp->cgn_index_day = 0;
5859 			index = 0;
5860 		}
5861 
5862 		/* Anytime we overwrite daily index 0, after we wrap,
5863 		 * we will be overwriting the oldest day, so we must
5864 		 * update the congestion data start time for that day.
5865 		 * That start time should have previously been saved after
5866 		 * we wrote the last days worth of data.
5867 		 */
5868 		if ((phba->hba_flag & HBA_CGN_DAY_WRAP) && index == 0) {
5869 			time64_to_tm(phba->cgn_daily_ts.tv_sec, 0, &broken);
5870 
5871 			cp->cgn_info_month = broken.tm_mon + 1;
5872 			cp->cgn_info_day = broken.tm_mday;
5873 			cp->cgn_info_year = broken.tm_year - 100;
5874 			cp->cgn_info_hour = broken.tm_hour;
5875 			cp->cgn_info_minute = broken.tm_min;
5876 			cp->cgn_info_second = broken.tm_sec;
5877 
5878 			lpfc_printf_log
5879 				(phba, KERN_INFO, LOG_CGN_MGMT,
5880 				"2646 CGNInfo idx0 Start Time: "
5881 				"%d/%d/%d %d:%d:%d\n",
5882 				cp->cgn_info_day, cp->cgn_info_month,
5883 				cp->cgn_info_year, cp->cgn_info_hour,
5884 				cp->cgn_info_minute, cp->cgn_info_second);
5885 		}
5886 
5887 		dvalue = 0;
5888 		wvalue = 0;
5889 		lvalue = 0;
5890 		mvalue = 0;
5891 		mbps = 0;
5892 		avalue = 0;
5893 		for (i = 0; i < LPFC_HOUR_DAY; i++) {
5894 			dvalue += le32_to_cpu(cp->cgn_drvr_hr[i]);
5895 			wvalue += le32_to_cpu(cp->cgn_warn_hr[i]);
5896 			lvalue += le32_to_cpu(cp->cgn_latency_hr[i]);
5897 			mbps += le16_to_cpu(cp->cgn_bw_hr[i]);
5898 			avalue += le32_to_cpu(cp->cgn_alarm_hr[i]);
5899 		}
5900 		if (lvalue)		/* Avg of latency averages */
5901 			lvalue /= LPFC_HOUR_DAY;
5902 		if (mbps)		/* Avg of Bandwidth averages */
5903 			mvalue = mbps / LPFC_HOUR_DAY;
5904 
5905 		lptr = &cp->cgn_drvr_day[index];
5906 		*lptr = cpu_to_le32(dvalue);
5907 		lptr = &cp->cgn_warn_day[index];
5908 		*lptr = cpu_to_le32(wvalue);
5909 		lptr = &cp->cgn_latency_day[index];
5910 		*lptr = cpu_to_le32(lvalue);
5911 		mptr = &cp->cgn_bw_day[index];
5912 		*mptr = cpu_to_le16(mvalue);
5913 		lptr = &cp->cgn_alarm_day[index];
5914 		*lptr = cpu_to_le32(avalue);
5915 
5916 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5917 				"2420 Congestion Info - daily (%d): "
5918 				"%d %d %d %d %d\n",
5919 				index, dvalue, wvalue, lvalue, mvalue, avalue);
5920 
5921 		/* We just wrote LPFC_MAX_CGN_DAYS of data,
5922 		 * so we are wrapped on any data after this.
5923 		 * Save this as the start time for the next day.
5924 		 */
5925 		if (index == (LPFC_MAX_CGN_DAYS - 1)) {
5926 			phba->hba_flag |= HBA_CGN_DAY_WRAP;
5927 			ktime_get_real_ts64(&phba->cgn_daily_ts);
5928 		}
5929 	}
5930 
5931 	/* Use the frequency found in the last rcv'ed FPIN */
5932 	value = phba->cgn_fpin_frequency;
5933 	cp->cgn_warn_freq = cpu_to_le16(value);
5934 	cp->cgn_alarm_freq = cpu_to_le16(value);
5935 
5936 	lvalue = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ,
5937 				     LPFC_CGN_CRC32_SEED);
5938 	cp->cgn_info_crc = cpu_to_le32(lvalue);
5939 }
5940 
5941 /**
5942  * lpfc_calc_cmf_latency - latency from start of rxate timer interval
5943  * @phba: The Hba for which this call is being executed.
5944  *
5945  * The routine calculates the latency from the beginning of the CMF timer
5946  * interval to the current point in time. It is called from IO completion
5947  * when we exceed our Bandwidth limitation for the time interval.
5948  */
5949 uint32_t
5950 lpfc_calc_cmf_latency(struct lpfc_hba *phba)
5951 {
5952 	struct timespec64 cmpl_time;
5953 	uint32_t msec = 0;
5954 
5955 	ktime_get_real_ts64(&cmpl_time);
5956 
5957 	/* This routine works on a ms granularity so sec and usec are
5958 	 * converted accordingly.
5959 	 */
5960 	if (cmpl_time.tv_sec == phba->cmf_latency.tv_sec) {
5961 		msec = (cmpl_time.tv_nsec - phba->cmf_latency.tv_nsec) /
5962 			NSEC_PER_MSEC;
5963 	} else {
5964 		if (cmpl_time.tv_nsec >= phba->cmf_latency.tv_nsec) {
5965 			msec = (cmpl_time.tv_sec -
5966 				phba->cmf_latency.tv_sec) * MSEC_PER_SEC;
5967 			msec += ((cmpl_time.tv_nsec -
5968 				  phba->cmf_latency.tv_nsec) / NSEC_PER_MSEC);
5969 		} else {
5970 			msec = (cmpl_time.tv_sec - phba->cmf_latency.tv_sec -
5971 				1) * MSEC_PER_SEC;
5972 			msec += (((NSEC_PER_SEC - phba->cmf_latency.tv_nsec) +
5973 				 cmpl_time.tv_nsec) / NSEC_PER_MSEC);
5974 		}
5975 	}
5976 	return msec;
5977 }
5978 
5979 /**
5980  * lpfc_cmf_timer -  This is the timer function for one congestion
5981  * rate interval.
5982  * @timer: Pointer to the high resolution timer that expired
5983  */
5984 static enum hrtimer_restart
5985 lpfc_cmf_timer(struct hrtimer *timer)
5986 {
5987 	struct lpfc_hba *phba = container_of(timer, struct lpfc_hba,
5988 					     cmf_timer);
5989 	struct rx_info_entry entry;
5990 	uint32_t io_cnt;
5991 	uint32_t busy, max_read;
5992 	uint64_t total, rcv, lat, mbpi, extra, cnt;
5993 	int timer_interval = LPFC_CMF_INTERVAL;
5994 	uint32_t ms;
5995 	struct lpfc_cgn_stat *cgs;
5996 	int cpu;
5997 
5998 	/* Only restart the timer if congestion mgmt is on */
5999 	if (phba->cmf_active_mode == LPFC_CFG_OFF ||
6000 	    !phba->cmf_latency.tv_sec) {
6001 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
6002 				"6224 CMF timer exit: %d %lld\n",
6003 				phba->cmf_active_mode,
6004 				(uint64_t)phba->cmf_latency.tv_sec);
6005 		return HRTIMER_NORESTART;
6006 	}
6007 
6008 	/* If pport is not ready yet, just exit and wait for
6009 	 * the next timer cycle to hit.
6010 	 */
6011 	if (!phba->pport)
6012 		goto skip;
6013 
6014 	/* Do not block SCSI IO while in the timer routine since
6015 	 * total_bytes will be cleared
6016 	 */
6017 	atomic_set(&phba->cmf_stop_io, 1);
6018 
6019 	/* First we need to calculate the actual ms between
6020 	 * the last timer interrupt and this one. We ask for
6021 	 * LPFC_CMF_INTERVAL, however the actual time may
6022 	 * vary depending on system overhead.
6023 	 */
6024 	ms = lpfc_calc_cmf_latency(phba);
6025 
6026 
6027 	/* Immediately after we calculate the time since the last
6028 	 * timer interrupt, set the start time for the next
6029 	 * interrupt
6030 	 */
6031 	ktime_get_real_ts64(&phba->cmf_latency);
6032 
6033 	phba->cmf_link_byte_count =
6034 		div_u64(phba->cmf_max_line_rate * LPFC_CMF_INTERVAL, 1000);
6035 
6036 	/* Collect all the stats from the prior timer interval */
6037 	total = 0;
6038 	io_cnt = 0;
6039 	lat = 0;
6040 	rcv = 0;
6041 	for_each_present_cpu(cpu) {
6042 		cgs = per_cpu_ptr(phba->cmf_stat, cpu);
6043 		total += atomic64_xchg(&cgs->total_bytes, 0);
6044 		io_cnt += atomic_xchg(&cgs->rx_io_cnt, 0);
6045 		lat += atomic64_xchg(&cgs->rx_latency, 0);
6046 		rcv += atomic64_xchg(&cgs->rcv_bytes, 0);
6047 	}
6048 
6049 	/* Before we issue another CMF_SYNC_WQE, retrieve the BW
6050 	 * returned from the last CMF_SYNC_WQE issued, from
6051 	 * cmf_last_sync_bw. This will be the target BW for
6052 	 * this next timer interval.
6053 	 */
6054 	if (phba->cmf_active_mode == LPFC_CFG_MANAGED &&
6055 	    phba->link_state != LPFC_LINK_DOWN &&
6056 	    phba->hba_flag & HBA_SETUP) {
6057 		mbpi = phba->cmf_last_sync_bw;
6058 		phba->cmf_last_sync_bw = 0;
6059 		extra = 0;
6060 
6061 		/* Calculate any extra bytes needed to account for the
6062 		 * timer accuracy. If we are less than LPFC_CMF_INTERVAL
6063 		 * calculate the adjustment needed for total to reflect
6064 		 * a full LPFC_CMF_INTERVAL.
6065 		 */
6066 		if (ms && ms < LPFC_CMF_INTERVAL) {
6067 			cnt = div_u64(total, ms); /* bytes per ms */
6068 			cnt *= LPFC_CMF_INTERVAL; /* what total should be */
6069 
6070 			/* If the timeout is scheduled to be shorter,
6071 			 * this value may skew the data, so cap it at mbpi.
6072 			 */
6073 			if ((phba->hba_flag & HBA_SHORT_CMF) && cnt > mbpi)
6074 				cnt = mbpi;
6075 
6076 			extra = cnt - total;
6077 		}
6078 		lpfc_issue_cmf_sync_wqe(phba, LPFC_CMF_INTERVAL, total + extra);
6079 	} else {
6080 		/* For Monitor mode or link down we want mbpi
6081 		 * to be the full link speed
6082 		 */
6083 		mbpi = phba->cmf_link_byte_count;
6084 		extra = 0;
6085 	}
6086 	phba->cmf_timer_cnt++;
6087 
6088 	if (io_cnt) {
6089 		/* Update congestion info buffer latency in us */
6090 		atomic_add(io_cnt, &phba->cgn_latency_evt_cnt);
6091 		atomic64_add(lat, &phba->cgn_latency_evt);
6092 	}
6093 	busy = atomic_xchg(&phba->cmf_busy, 0);
6094 	max_read = atomic_xchg(&phba->rx_max_read_cnt, 0);
6095 
6096 	/* Calculate MBPI for the next timer interval */
6097 	if (mbpi) {
6098 		if (mbpi > phba->cmf_link_byte_count ||
6099 		    phba->cmf_active_mode == LPFC_CFG_MONITOR)
6100 			mbpi = phba->cmf_link_byte_count;
6101 
6102 		/* Change max_bytes_per_interval to what the prior
6103 		 * CMF_SYNC_WQE cmpl indicated.
6104 		 */
6105 		if (mbpi != phba->cmf_max_bytes_per_interval)
6106 			phba->cmf_max_bytes_per_interval = mbpi;
6107 	}
6108 
6109 	/* Save rxmonitor information for debug */
6110 	if (phba->rx_monitor) {
6111 		entry.total_bytes = total;
6112 		entry.cmf_bytes = total + extra;
6113 		entry.rcv_bytes = rcv;
6114 		entry.cmf_busy = busy;
6115 		entry.cmf_info = phba->cmf_active_info;
6116 		if (io_cnt) {
6117 			entry.avg_io_latency = div_u64(lat, io_cnt);
6118 			entry.avg_io_size = div_u64(rcv, io_cnt);
6119 		} else {
6120 			entry.avg_io_latency = 0;
6121 			entry.avg_io_size = 0;
6122 		}
6123 		entry.max_read_cnt = max_read;
6124 		entry.io_cnt = io_cnt;
6125 		entry.max_bytes_per_interval = mbpi;
6126 		if (phba->cmf_active_mode == LPFC_CFG_MANAGED)
6127 			entry.timer_utilization = phba->cmf_last_ts;
6128 		else
6129 			entry.timer_utilization = ms;
6130 		entry.timer_interval = ms;
6131 		phba->cmf_last_ts = 0;
6132 
6133 		lpfc_rx_monitor_record(phba->rx_monitor, &entry);
6134 	}
6135 
6136 	if (phba->cmf_active_mode == LPFC_CFG_MONITOR) {
6137 		/* If Monitor mode, check if we are oversubscribed
6138 		 * against the full line rate.
6139 		 */
6140 		if (mbpi && total > mbpi)
6141 			atomic_inc(&phba->cgn_driver_evt_cnt);
6142 	}
6143 	phba->rx_block_cnt += div_u64(rcv, 512);  /* save 512 byte block cnt */
6144 
6145 	/* Each minute save Fabric and Driver congestion information */
6146 	lpfc_cgn_save_evt_cnt(phba);
6147 
6148 	phba->hba_flag &= ~HBA_SHORT_CMF;
6149 
6150 	/* Since we need to call lpfc_cgn_save_evt_cnt every minute, on the
6151 	 * minute, adjust our next timer interval, if needed, to ensure a
6152 	 * 1 minute granularity when we get the next timer interrupt.
6153 	 */
6154 	if (time_after(jiffies + msecs_to_jiffies(LPFC_CMF_INTERVAL),
6155 		       phba->cgn_evt_timestamp)) {
6156 		timer_interval = jiffies_to_msecs(phba->cgn_evt_timestamp -
6157 						  jiffies);
6158 		if (timer_interval <= 0)
6159 			timer_interval = LPFC_CMF_INTERVAL;
6160 		else
6161 			phba->hba_flag |= HBA_SHORT_CMF;
6162 
6163 		/* If we adjust timer_interval, max_bytes_per_interval
6164 		 * needs to be adjusted as well.
6165 		 */
6166 		phba->cmf_link_byte_count = div_u64(phba->cmf_max_line_rate *
6167 						    timer_interval, 1000);
6168 		if (phba->cmf_active_mode == LPFC_CFG_MONITOR)
6169 			phba->cmf_max_bytes_per_interval =
6170 				phba->cmf_link_byte_count;
6171 	}
6172 
6173 	/* Since total_bytes has already been zero'ed, its okay to unblock
6174 	 * after max_bytes_per_interval is setup.
6175 	 */
6176 	if (atomic_xchg(&phba->cmf_bw_wait, 0))
6177 		queue_work(phba->wq, &phba->unblock_request_work);
6178 
6179 	/* SCSI IO is now unblocked */
6180 	atomic_set(&phba->cmf_stop_io, 0);
6181 
6182 skip:
6183 	hrtimer_forward_now(timer,
6184 			    ktime_set(0, timer_interval * NSEC_PER_MSEC));
6185 	return HRTIMER_RESTART;
6186 }
6187 
6188 #define trunk_link_status(__idx)\
6189 	bf_get(lpfc_acqe_fc_la_trunk_config_port##__idx, acqe_fc) ?\
6190 	       ((phba->trunk_link.link##__idx.state == LPFC_LINK_UP) ?\
6191 		"Link up" : "Link down") : "NA"
6192 /* Did port __idx reported an error */
6193 #define trunk_port_fault(__idx)\
6194 	bf_get(lpfc_acqe_fc_la_trunk_config_port##__idx, acqe_fc) ?\
6195 	       (port_fault & (1 << __idx) ? "YES" : "NO") : "NA"
6196 
6197 static void
6198 lpfc_update_trunk_link_status(struct lpfc_hba *phba,
6199 			      struct lpfc_acqe_fc_la *acqe_fc)
6200 {
6201 	uint8_t port_fault = bf_get(lpfc_acqe_fc_la_trunk_linkmask, acqe_fc);
6202 	uint8_t err = bf_get(lpfc_acqe_fc_la_trunk_fault, acqe_fc);
6203 	u8 cnt = 0;
6204 
6205 	phba->sli4_hba.link_state.speed =
6206 		lpfc_sli4_port_speed_parse(phba, LPFC_TRAILER_CODE_FC,
6207 				bf_get(lpfc_acqe_fc_la_speed, acqe_fc));
6208 
6209 	phba->sli4_hba.link_state.logical_speed =
6210 				bf_get(lpfc_acqe_fc_la_llink_spd, acqe_fc) * 10;
6211 	/* We got FC link speed, convert to fc_linkspeed (READ_TOPOLOGY) */
6212 	phba->fc_linkspeed =
6213 		 lpfc_async_link_speed_to_read_top(
6214 				phba,
6215 				bf_get(lpfc_acqe_fc_la_speed, acqe_fc));
6216 
6217 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port0, acqe_fc)) {
6218 		phba->trunk_link.link0.state =
6219 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port0, acqe_fc)
6220 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
6221 		phba->trunk_link.link0.fault = port_fault & 0x1 ? err : 0;
6222 		cnt++;
6223 	}
6224 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port1, acqe_fc)) {
6225 		phba->trunk_link.link1.state =
6226 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port1, acqe_fc)
6227 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
6228 		phba->trunk_link.link1.fault = port_fault & 0x2 ? err : 0;
6229 		cnt++;
6230 	}
6231 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port2, acqe_fc)) {
6232 		phba->trunk_link.link2.state =
6233 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port2, acqe_fc)
6234 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
6235 		phba->trunk_link.link2.fault = port_fault & 0x4 ? err : 0;
6236 		cnt++;
6237 	}
6238 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port3, acqe_fc)) {
6239 		phba->trunk_link.link3.state =
6240 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port3, acqe_fc)
6241 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
6242 		phba->trunk_link.link3.fault = port_fault & 0x8 ? err : 0;
6243 		cnt++;
6244 	}
6245 
6246 	if (cnt)
6247 		phba->trunk_link.phy_lnk_speed =
6248 			phba->sli4_hba.link_state.logical_speed / (cnt * 1000);
6249 	else
6250 		phba->trunk_link.phy_lnk_speed = LPFC_LINK_SPEED_UNKNOWN;
6251 
6252 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6253 			"2910 Async FC Trunking Event - Speed:%d\n"
6254 			"\tLogical speed:%d "
6255 			"port0: %s port1: %s port2: %s port3: %s\n",
6256 			phba->sli4_hba.link_state.speed,
6257 			phba->sli4_hba.link_state.logical_speed,
6258 			trunk_link_status(0), trunk_link_status(1),
6259 			trunk_link_status(2), trunk_link_status(3));
6260 
6261 	if (phba->cmf_active_mode != LPFC_CFG_OFF)
6262 		lpfc_cmf_signal_init(phba);
6263 
6264 	if (port_fault)
6265 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6266 				"3202 trunk error:0x%x (%s) seen on port0:%s "
6267 				/*
6268 				 * SLI-4: We have only 0xA error codes
6269 				 * defined as of now. print an appropriate
6270 				 * message in case driver needs to be updated.
6271 				 */
6272 				"port1:%s port2:%s port3:%s\n", err, err > 0xA ?
6273 				"UNDEFINED. update driver." : trunk_errmsg[err],
6274 				trunk_port_fault(0), trunk_port_fault(1),
6275 				trunk_port_fault(2), trunk_port_fault(3));
6276 }
6277 
6278 
6279 /**
6280  * lpfc_sli4_async_fc_evt - Process the asynchronous FC link event
6281  * @phba: pointer to lpfc hba data structure.
6282  * @acqe_fc: pointer to the async fc completion queue entry.
6283  *
6284  * This routine is to handle the SLI4 asynchronous FC event. It will simply log
6285  * that the event was received and then issue a read_topology mailbox command so
6286  * that the rest of the driver will treat it the same as SLI3.
6287  **/
6288 static void
6289 lpfc_sli4_async_fc_evt(struct lpfc_hba *phba, struct lpfc_acqe_fc_la *acqe_fc)
6290 {
6291 	LPFC_MBOXQ_t *pmb;
6292 	MAILBOX_t *mb;
6293 	struct lpfc_mbx_read_top *la;
6294 	char *log_level;
6295 	int rc;
6296 
6297 	if (bf_get(lpfc_trailer_type, acqe_fc) !=
6298 	    LPFC_FC_LA_EVENT_TYPE_FC_LINK) {
6299 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6300 				"2895 Non FC link Event detected.(%d)\n",
6301 				bf_get(lpfc_trailer_type, acqe_fc));
6302 		return;
6303 	}
6304 
6305 	if (bf_get(lpfc_acqe_fc_la_att_type, acqe_fc) ==
6306 	    LPFC_FC_LA_TYPE_TRUNKING_EVENT) {
6307 		lpfc_update_trunk_link_status(phba, acqe_fc);
6308 		return;
6309 	}
6310 
6311 	/* Keep the link status for extra SLI4 state machine reference */
6312 	phba->sli4_hba.link_state.speed =
6313 			lpfc_sli4_port_speed_parse(phba, LPFC_TRAILER_CODE_FC,
6314 				bf_get(lpfc_acqe_fc_la_speed, acqe_fc));
6315 	phba->sli4_hba.link_state.duplex = LPFC_ASYNC_LINK_DUPLEX_FULL;
6316 	phba->sli4_hba.link_state.topology =
6317 				bf_get(lpfc_acqe_fc_la_topology, acqe_fc);
6318 	phba->sli4_hba.link_state.status =
6319 				bf_get(lpfc_acqe_fc_la_att_type, acqe_fc);
6320 	phba->sli4_hba.link_state.type =
6321 				bf_get(lpfc_acqe_fc_la_port_type, acqe_fc);
6322 	phba->sli4_hba.link_state.number =
6323 				bf_get(lpfc_acqe_fc_la_port_number, acqe_fc);
6324 	phba->sli4_hba.link_state.fault =
6325 				bf_get(lpfc_acqe_link_fault, acqe_fc);
6326 	phba->sli4_hba.link_state.link_status =
6327 				bf_get(lpfc_acqe_fc_la_link_status, acqe_fc);
6328 
6329 	/*
6330 	 * Only select attention types need logical speed modification to what
6331 	 * was previously set.
6332 	 */
6333 	if (phba->sli4_hba.link_state.status >= LPFC_FC_LA_TYPE_LINK_UP &&
6334 	    phba->sli4_hba.link_state.status < LPFC_FC_LA_TYPE_ACTIVATE_FAIL) {
6335 		if (bf_get(lpfc_acqe_fc_la_att_type, acqe_fc) ==
6336 		    LPFC_FC_LA_TYPE_LINK_DOWN)
6337 			phba->sli4_hba.link_state.logical_speed = 0;
6338 		else if (!phba->sli4_hba.conf_trunk)
6339 			phba->sli4_hba.link_state.logical_speed =
6340 				bf_get(lpfc_acqe_fc_la_llink_spd, acqe_fc) * 10;
6341 	}
6342 
6343 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6344 			"2896 Async FC event - Speed:%dGBaud Topology:x%x "
6345 			"LA Type:x%x Port Type:%d Port Number:%d Logical speed:"
6346 			"%dMbps Fault:x%x Link Status:x%x\n",
6347 			phba->sli4_hba.link_state.speed,
6348 			phba->sli4_hba.link_state.topology,
6349 			phba->sli4_hba.link_state.status,
6350 			phba->sli4_hba.link_state.type,
6351 			phba->sli4_hba.link_state.number,
6352 			phba->sli4_hba.link_state.logical_speed,
6353 			phba->sli4_hba.link_state.fault,
6354 			phba->sli4_hba.link_state.link_status);
6355 
6356 	/*
6357 	 * The following attention types are informational only, providing
6358 	 * further details about link status.  Overwrite the value of
6359 	 * link_state.status appropriately.  No further action is required.
6360 	 */
6361 	if (phba->sli4_hba.link_state.status >= LPFC_FC_LA_TYPE_ACTIVATE_FAIL) {
6362 		switch (phba->sli4_hba.link_state.status) {
6363 		case LPFC_FC_LA_TYPE_ACTIVATE_FAIL:
6364 			log_level = KERN_WARNING;
6365 			phba->sli4_hba.link_state.status =
6366 					LPFC_FC_LA_TYPE_LINK_DOWN;
6367 			break;
6368 		case LPFC_FC_LA_TYPE_LINK_RESET_PRTCL_EVT:
6369 			/*
6370 			 * During bb credit recovery establishment, receiving
6371 			 * this attention type is normal.  Link Up attention
6372 			 * type is expected to occur before this informational
6373 			 * attention type so keep the Link Up status.
6374 			 */
6375 			log_level = KERN_INFO;
6376 			phba->sli4_hba.link_state.status =
6377 					LPFC_FC_LA_TYPE_LINK_UP;
6378 			break;
6379 		default:
6380 			log_level = KERN_INFO;
6381 			break;
6382 		}
6383 		lpfc_log_msg(phba, log_level, LOG_SLI,
6384 			     "2992 Async FC event - Informational Link "
6385 			     "Attention Type x%x\n",
6386 			     bf_get(lpfc_acqe_fc_la_att_type, acqe_fc));
6387 		return;
6388 	}
6389 
6390 	pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6391 	if (!pmb) {
6392 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6393 				"2897 The mboxq allocation failed\n");
6394 		return;
6395 	}
6396 	rc = lpfc_mbox_rsrc_prep(phba, pmb);
6397 	if (rc) {
6398 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6399 				"2898 The mboxq prep failed\n");
6400 		goto out_free_pmb;
6401 	}
6402 
6403 	/* Cleanup any outstanding ELS commands */
6404 	lpfc_els_flush_all_cmd(phba);
6405 
6406 	/* Block ELS IOCBs until we have done process link event */
6407 	phba->sli4_hba.els_wq->pring->flag |= LPFC_STOP_IOCB_EVENT;
6408 
6409 	/* Update link event statistics */
6410 	phba->sli.slistat.link_event++;
6411 
6412 	/* Create lpfc_handle_latt mailbox command from link ACQE */
6413 	lpfc_read_topology(phba, pmb, (struct lpfc_dmabuf *)pmb->ctx_buf);
6414 	pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
6415 	pmb->vport = phba->pport;
6416 
6417 	if (phba->sli4_hba.link_state.status != LPFC_FC_LA_TYPE_LINK_UP) {
6418 		phba->link_flag &= ~(LS_MDS_LINK_DOWN | LS_MDS_LOOPBACK);
6419 
6420 		switch (phba->sli4_hba.link_state.status) {
6421 		case LPFC_FC_LA_TYPE_MDS_LINK_DOWN:
6422 			phba->link_flag |= LS_MDS_LINK_DOWN;
6423 			break;
6424 		case LPFC_FC_LA_TYPE_MDS_LOOPBACK:
6425 			phba->link_flag |= LS_MDS_LOOPBACK;
6426 			break;
6427 		default:
6428 			break;
6429 		}
6430 
6431 		/* Initialize completion status */
6432 		mb = &pmb->u.mb;
6433 		mb->mbxStatus = MBX_SUCCESS;
6434 
6435 		/* Parse port fault information field */
6436 		lpfc_sli4_parse_latt_fault(phba, (void *)acqe_fc);
6437 
6438 		/* Parse and translate link attention fields */
6439 		la = (struct lpfc_mbx_read_top *)&pmb->u.mb.un.varReadTop;
6440 		la->eventTag = acqe_fc->event_tag;
6441 
6442 		if (phba->sli4_hba.link_state.status ==
6443 		    LPFC_FC_LA_TYPE_UNEXP_WWPN) {
6444 			bf_set(lpfc_mbx_read_top_att_type, la,
6445 			       LPFC_FC_LA_TYPE_UNEXP_WWPN);
6446 		} else {
6447 			bf_set(lpfc_mbx_read_top_att_type, la,
6448 			       LPFC_FC_LA_TYPE_LINK_DOWN);
6449 		}
6450 		/* Invoke the mailbox command callback function */
6451 		lpfc_mbx_cmpl_read_topology(phba, pmb);
6452 
6453 		return;
6454 	}
6455 
6456 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
6457 	if (rc == MBX_NOT_FINISHED)
6458 		goto out_free_pmb;
6459 	return;
6460 
6461 out_free_pmb:
6462 	lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
6463 }
6464 
6465 /**
6466  * lpfc_sli4_async_sli_evt - Process the asynchronous SLI link event
6467  * @phba: pointer to lpfc hba data structure.
6468  * @acqe_sli: pointer to the async SLI completion queue entry.
6469  *
6470  * This routine is to handle the SLI4 asynchronous SLI events.
6471  **/
6472 static void
6473 lpfc_sli4_async_sli_evt(struct lpfc_hba *phba, struct lpfc_acqe_sli *acqe_sli)
6474 {
6475 	char port_name;
6476 	char message[128];
6477 	uint8_t status;
6478 	uint8_t evt_type;
6479 	uint8_t operational = 0;
6480 	struct temp_event temp_event_data;
6481 	struct lpfc_acqe_misconfigured_event *misconfigured;
6482 	struct lpfc_acqe_cgn_signal *cgn_signal;
6483 	struct Scsi_Host  *shost;
6484 	struct lpfc_vport **vports;
6485 	int rc, i, cnt;
6486 
6487 	evt_type = bf_get(lpfc_trailer_type, acqe_sli);
6488 
6489 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6490 			"2901 Async SLI event - Type:%d, Event Data: x%08x "
6491 			"x%08x x%08x x%08x\n", evt_type,
6492 			acqe_sli->event_data1, acqe_sli->event_data2,
6493 			acqe_sli->event_data3, acqe_sli->trailer);
6494 
6495 	port_name = phba->Port[0];
6496 	if (port_name == 0x00)
6497 		port_name = '?'; /* get port name is empty */
6498 
6499 	switch (evt_type) {
6500 	case LPFC_SLI_EVENT_TYPE_OVER_TEMP:
6501 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
6502 		temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
6503 		temp_event_data.data = (uint32_t)acqe_sli->event_data1;
6504 
6505 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6506 				"3190 Over Temperature:%d Celsius- Port Name %c\n",
6507 				acqe_sli->event_data1, port_name);
6508 
6509 		phba->sfp_warning |= LPFC_TRANSGRESSION_HIGH_TEMPERATURE;
6510 		shost = lpfc_shost_from_vport(phba->pport);
6511 		fc_host_post_vendor_event(shost, fc_get_event_number(),
6512 					  sizeof(temp_event_data),
6513 					  (char *)&temp_event_data,
6514 					  SCSI_NL_VID_TYPE_PCI
6515 					  | PCI_VENDOR_ID_EMULEX);
6516 		break;
6517 	case LPFC_SLI_EVENT_TYPE_NORM_TEMP:
6518 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
6519 		temp_event_data.event_code = LPFC_NORMAL_TEMP;
6520 		temp_event_data.data = (uint32_t)acqe_sli->event_data1;
6521 
6522 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI | LOG_LDS_EVENT,
6523 				"3191 Normal Temperature:%d Celsius - Port Name %c\n",
6524 				acqe_sli->event_data1, port_name);
6525 
6526 		shost = lpfc_shost_from_vport(phba->pport);
6527 		fc_host_post_vendor_event(shost, fc_get_event_number(),
6528 					  sizeof(temp_event_data),
6529 					  (char *)&temp_event_data,
6530 					  SCSI_NL_VID_TYPE_PCI
6531 					  | PCI_VENDOR_ID_EMULEX);
6532 		break;
6533 	case LPFC_SLI_EVENT_TYPE_MISCONFIGURED:
6534 		misconfigured = (struct lpfc_acqe_misconfigured_event *)
6535 					&acqe_sli->event_data1;
6536 
6537 		/* fetch the status for this port */
6538 		switch (phba->sli4_hba.lnk_info.lnk_no) {
6539 		case LPFC_LINK_NUMBER_0:
6540 			status = bf_get(lpfc_sli_misconfigured_port0_state,
6541 					&misconfigured->theEvent);
6542 			operational = bf_get(lpfc_sli_misconfigured_port0_op,
6543 					&misconfigured->theEvent);
6544 			break;
6545 		case LPFC_LINK_NUMBER_1:
6546 			status = bf_get(lpfc_sli_misconfigured_port1_state,
6547 					&misconfigured->theEvent);
6548 			operational = bf_get(lpfc_sli_misconfigured_port1_op,
6549 					&misconfigured->theEvent);
6550 			break;
6551 		case LPFC_LINK_NUMBER_2:
6552 			status = bf_get(lpfc_sli_misconfigured_port2_state,
6553 					&misconfigured->theEvent);
6554 			operational = bf_get(lpfc_sli_misconfigured_port2_op,
6555 					&misconfigured->theEvent);
6556 			break;
6557 		case LPFC_LINK_NUMBER_3:
6558 			status = bf_get(lpfc_sli_misconfigured_port3_state,
6559 					&misconfigured->theEvent);
6560 			operational = bf_get(lpfc_sli_misconfigured_port3_op,
6561 					&misconfigured->theEvent);
6562 			break;
6563 		default:
6564 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6565 					"3296 "
6566 					"LPFC_SLI_EVENT_TYPE_MISCONFIGURED "
6567 					"event: Invalid link %d",
6568 					phba->sli4_hba.lnk_info.lnk_no);
6569 			return;
6570 		}
6571 
6572 		/* Skip if optic state unchanged */
6573 		if (phba->sli4_hba.lnk_info.optic_state == status)
6574 			return;
6575 
6576 		switch (status) {
6577 		case LPFC_SLI_EVENT_STATUS_VALID:
6578 			sprintf(message, "Physical Link is functional");
6579 			break;
6580 		case LPFC_SLI_EVENT_STATUS_NOT_PRESENT:
6581 			sprintf(message, "Optics faulted/incorrectly "
6582 				"installed/not installed - Reseat optics, "
6583 				"if issue not resolved, replace.");
6584 			break;
6585 		case LPFC_SLI_EVENT_STATUS_WRONG_TYPE:
6586 			sprintf(message,
6587 				"Optics of two types installed - Remove one "
6588 				"optic or install matching pair of optics.");
6589 			break;
6590 		case LPFC_SLI_EVENT_STATUS_UNSUPPORTED:
6591 			sprintf(message, "Incompatible optics - Replace with "
6592 				"compatible optics for card to function.");
6593 			break;
6594 		case LPFC_SLI_EVENT_STATUS_UNQUALIFIED:
6595 			sprintf(message, "Unqualified optics - Replace with "
6596 				"Avago optics for Warranty and Technical "
6597 				"Support - Link is%s operational",
6598 				(operational) ? " not" : "");
6599 			break;
6600 		case LPFC_SLI_EVENT_STATUS_UNCERTIFIED:
6601 			sprintf(message, "Uncertified optics - Replace with "
6602 				"Avago-certified optics to enable link "
6603 				"operation - Link is%s operational",
6604 				(operational) ? " not" : "");
6605 			break;
6606 		default:
6607 			/* firmware is reporting a status we don't know about */
6608 			sprintf(message, "Unknown event status x%02x", status);
6609 			break;
6610 		}
6611 
6612 		/* Issue READ_CONFIG mbox command to refresh supported speeds */
6613 		rc = lpfc_sli4_read_config(phba);
6614 		if (rc) {
6615 			phba->lmt = 0;
6616 			lpfc_printf_log(phba, KERN_ERR,
6617 					LOG_TRACE_EVENT,
6618 					"3194 Unable to retrieve supported "
6619 					"speeds, rc = 0x%x\n", rc);
6620 		}
6621 		rc = lpfc_sli4_refresh_params(phba);
6622 		if (rc) {
6623 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6624 					"3174 Unable to update pls support, "
6625 					"rc x%x\n", rc);
6626 		}
6627 		vports = lpfc_create_vport_work_array(phba);
6628 		if (vports != NULL) {
6629 			for (i = 0; i <= phba->max_vports && vports[i] != NULL;
6630 					i++) {
6631 				shost = lpfc_shost_from_vport(vports[i]);
6632 				lpfc_host_supported_speeds_set(shost);
6633 			}
6634 		}
6635 		lpfc_destroy_vport_work_array(phba, vports);
6636 
6637 		phba->sli4_hba.lnk_info.optic_state = status;
6638 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6639 				"3176 Port Name %c %s\n", port_name, message);
6640 		break;
6641 	case LPFC_SLI_EVENT_TYPE_REMOTE_DPORT:
6642 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6643 				"3192 Remote DPort Test Initiated - "
6644 				"Event Data1:x%08x Event Data2: x%08x\n",
6645 				acqe_sli->event_data1, acqe_sli->event_data2);
6646 		break;
6647 	case LPFC_SLI_EVENT_TYPE_PORT_PARAMS_CHG:
6648 		/* Call FW to obtain active parms */
6649 		lpfc_sli4_cgn_parm_chg_evt(phba);
6650 		break;
6651 	case LPFC_SLI_EVENT_TYPE_MISCONF_FAWWN:
6652 		/* Misconfigured WWN. Reports that the SLI Port is configured
6653 		 * to use FA-WWN, but the attached device doesn’t support it.
6654 		 * Event Data1 - N.A, Event Data2 - N.A
6655 		 * This event only happens on the physical port.
6656 		 */
6657 		lpfc_log_msg(phba, KERN_WARNING, LOG_SLI | LOG_DISCOVERY,
6658 			     "2699 Misconfigured FA-PWWN - Attached device "
6659 			     "does not support FA-PWWN\n");
6660 		phba->sli4_hba.fawwpn_flag &= ~LPFC_FAWWPN_FABRIC;
6661 		memset(phba->pport->fc_portname.u.wwn, 0,
6662 		       sizeof(struct lpfc_name));
6663 		break;
6664 	case LPFC_SLI_EVENT_TYPE_EEPROM_FAILURE:
6665 		/* EEPROM failure. No driver action is required */
6666 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6667 			     "2518 EEPROM failure - "
6668 			     "Event Data1: x%08x Event Data2: x%08x\n",
6669 			     acqe_sli->event_data1, acqe_sli->event_data2);
6670 		break;
6671 	case LPFC_SLI_EVENT_TYPE_CGN_SIGNAL:
6672 		if (phba->cmf_active_mode == LPFC_CFG_OFF)
6673 			break;
6674 		cgn_signal = (struct lpfc_acqe_cgn_signal *)
6675 					&acqe_sli->event_data1;
6676 		phba->cgn_acqe_cnt++;
6677 
6678 		cnt = bf_get(lpfc_warn_acqe, cgn_signal);
6679 		atomic64_add(cnt, &phba->cgn_acqe_stat.warn);
6680 		atomic64_add(cgn_signal->alarm_cnt, &phba->cgn_acqe_stat.alarm);
6681 
6682 		/* no threshold for CMF, even 1 signal will trigger an event */
6683 
6684 		/* Alarm overrides warning, so check that first */
6685 		if (cgn_signal->alarm_cnt) {
6686 			if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
6687 				/* Keep track of alarm cnt for CMF_SYNC_WQE */
6688 				atomic_add(cgn_signal->alarm_cnt,
6689 					   &phba->cgn_sync_alarm_cnt);
6690 			}
6691 		} else if (cnt) {
6692 			/* signal action needs to be taken */
6693 			if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY ||
6694 			    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
6695 				/* Keep track of warning cnt for CMF_SYNC_WQE */
6696 				atomic_add(cnt, &phba->cgn_sync_warn_cnt);
6697 			}
6698 		}
6699 		break;
6700 	case LPFC_SLI_EVENT_TYPE_RD_SIGNAL:
6701 		/* May be accompanied by a temperature event */
6702 		lpfc_printf_log(phba, KERN_INFO,
6703 				LOG_SLI | LOG_LINK_EVENT | LOG_LDS_EVENT,
6704 				"2902 Remote Degrade Signaling: x%08x x%08x "
6705 				"x%08x\n",
6706 				acqe_sli->event_data1, acqe_sli->event_data2,
6707 				acqe_sli->event_data3);
6708 		break;
6709 	default:
6710 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6711 				"3193 Unrecognized SLI event, type: 0x%x",
6712 				evt_type);
6713 		break;
6714 	}
6715 }
6716 
6717 /**
6718  * lpfc_sli4_perform_vport_cvl - Perform clear virtual link on a vport
6719  * @vport: pointer to vport data structure.
6720  *
6721  * This routine is to perform Clear Virtual Link (CVL) on a vport in
6722  * response to a CVL event.
6723  *
6724  * Return the pointer to the ndlp with the vport if successful, otherwise
6725  * return NULL.
6726  **/
6727 static struct lpfc_nodelist *
6728 lpfc_sli4_perform_vport_cvl(struct lpfc_vport *vport)
6729 {
6730 	struct lpfc_nodelist *ndlp;
6731 	struct Scsi_Host *shost;
6732 	struct lpfc_hba *phba;
6733 
6734 	if (!vport)
6735 		return NULL;
6736 	phba = vport->phba;
6737 	if (!phba)
6738 		return NULL;
6739 	ndlp = lpfc_findnode_did(vport, Fabric_DID);
6740 	if (!ndlp) {
6741 		/* Cannot find existing Fabric ndlp, so allocate a new one */
6742 		ndlp = lpfc_nlp_init(vport, Fabric_DID);
6743 		if (!ndlp)
6744 			return NULL;
6745 		/* Set the node type */
6746 		ndlp->nlp_type |= NLP_FABRIC;
6747 		/* Put ndlp onto node list */
6748 		lpfc_enqueue_node(vport, ndlp);
6749 	}
6750 	if ((phba->pport->port_state < LPFC_FLOGI) &&
6751 		(phba->pport->port_state != LPFC_VPORT_FAILED))
6752 		return NULL;
6753 	/* If virtual link is not yet instantiated ignore CVL */
6754 	if ((vport != phba->pport) && (vport->port_state < LPFC_FDISC)
6755 		&& (vport->port_state != LPFC_VPORT_FAILED))
6756 		return NULL;
6757 	shost = lpfc_shost_from_vport(vport);
6758 	if (!shost)
6759 		return NULL;
6760 	lpfc_linkdown_port(vport);
6761 	lpfc_cleanup_pending_mbox(vport);
6762 	spin_lock_irq(shost->host_lock);
6763 	vport->fc_flag |= FC_VPORT_CVL_RCVD;
6764 	spin_unlock_irq(shost->host_lock);
6765 
6766 	return ndlp;
6767 }
6768 
6769 /**
6770  * lpfc_sli4_perform_all_vport_cvl - Perform clear virtual link on all vports
6771  * @phba: pointer to lpfc hba data structure.
6772  *
6773  * This routine is to perform Clear Virtual Link (CVL) on all vports in
6774  * response to a FCF dead event.
6775  **/
6776 static void
6777 lpfc_sli4_perform_all_vport_cvl(struct lpfc_hba *phba)
6778 {
6779 	struct lpfc_vport **vports;
6780 	int i;
6781 
6782 	vports = lpfc_create_vport_work_array(phba);
6783 	if (vports)
6784 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++)
6785 			lpfc_sli4_perform_vport_cvl(vports[i]);
6786 	lpfc_destroy_vport_work_array(phba, vports);
6787 }
6788 
6789 /**
6790  * lpfc_sli4_async_fip_evt - Process the asynchronous FCoE FIP event
6791  * @phba: pointer to lpfc hba data structure.
6792  * @acqe_fip: pointer to the async fcoe completion queue entry.
6793  *
6794  * This routine is to handle the SLI4 asynchronous fcoe event.
6795  **/
6796 static void
6797 lpfc_sli4_async_fip_evt(struct lpfc_hba *phba,
6798 			struct lpfc_acqe_fip *acqe_fip)
6799 {
6800 	uint8_t event_type = bf_get(lpfc_trailer_type, acqe_fip);
6801 	int rc;
6802 	struct lpfc_vport *vport;
6803 	struct lpfc_nodelist *ndlp;
6804 	int active_vlink_present;
6805 	struct lpfc_vport **vports;
6806 	int i;
6807 
6808 	phba->fc_eventTag = acqe_fip->event_tag;
6809 	phba->fcoe_eventtag = acqe_fip->event_tag;
6810 	switch (event_type) {
6811 	case LPFC_FIP_EVENT_TYPE_NEW_FCF:
6812 	case LPFC_FIP_EVENT_TYPE_FCF_PARAM_MOD:
6813 		if (event_type == LPFC_FIP_EVENT_TYPE_NEW_FCF)
6814 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6815 					"2546 New FCF event, evt_tag:x%x, "
6816 					"index:x%x\n",
6817 					acqe_fip->event_tag,
6818 					acqe_fip->index);
6819 		else
6820 			lpfc_printf_log(phba, KERN_WARNING, LOG_FIP |
6821 					LOG_DISCOVERY,
6822 					"2788 FCF param modified event, "
6823 					"evt_tag:x%x, index:x%x\n",
6824 					acqe_fip->event_tag,
6825 					acqe_fip->index);
6826 		if (phba->fcf.fcf_flag & FCF_DISCOVERY) {
6827 			/*
6828 			 * During period of FCF discovery, read the FCF
6829 			 * table record indexed by the event to update
6830 			 * FCF roundrobin failover eligible FCF bmask.
6831 			 */
6832 			lpfc_printf_log(phba, KERN_INFO, LOG_FIP |
6833 					LOG_DISCOVERY,
6834 					"2779 Read FCF (x%x) for updating "
6835 					"roundrobin FCF failover bmask\n",
6836 					acqe_fip->index);
6837 			rc = lpfc_sli4_read_fcf_rec(phba, acqe_fip->index);
6838 		}
6839 
6840 		/* If the FCF discovery is in progress, do nothing. */
6841 		spin_lock_irq(&phba->hbalock);
6842 		if (phba->hba_flag & FCF_TS_INPROG) {
6843 			spin_unlock_irq(&phba->hbalock);
6844 			break;
6845 		}
6846 		/* If fast FCF failover rescan event is pending, do nothing */
6847 		if (phba->fcf.fcf_flag & (FCF_REDISC_EVT | FCF_REDISC_PEND)) {
6848 			spin_unlock_irq(&phba->hbalock);
6849 			break;
6850 		}
6851 
6852 		/* If the FCF has been in discovered state, do nothing. */
6853 		if (phba->fcf.fcf_flag & FCF_SCAN_DONE) {
6854 			spin_unlock_irq(&phba->hbalock);
6855 			break;
6856 		}
6857 		spin_unlock_irq(&phba->hbalock);
6858 
6859 		/* Otherwise, scan the entire FCF table and re-discover SAN */
6860 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
6861 				"2770 Start FCF table scan per async FCF "
6862 				"event, evt_tag:x%x, index:x%x\n",
6863 				acqe_fip->event_tag, acqe_fip->index);
6864 		rc = lpfc_sli4_fcf_scan_read_fcf_rec(phba,
6865 						     LPFC_FCOE_FCF_GET_FIRST);
6866 		if (rc)
6867 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6868 					"2547 Issue FCF scan read FCF mailbox "
6869 					"command failed (x%x)\n", rc);
6870 		break;
6871 
6872 	case LPFC_FIP_EVENT_TYPE_FCF_TABLE_FULL:
6873 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6874 				"2548 FCF Table full count 0x%x tag 0x%x\n",
6875 				bf_get(lpfc_acqe_fip_fcf_count, acqe_fip),
6876 				acqe_fip->event_tag);
6877 		break;
6878 
6879 	case LPFC_FIP_EVENT_TYPE_FCF_DEAD:
6880 		phba->fcoe_cvl_eventtag = acqe_fip->event_tag;
6881 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6882 				"2549 FCF (x%x) disconnected from network, "
6883 				 "tag:x%x\n", acqe_fip->index,
6884 				 acqe_fip->event_tag);
6885 		/*
6886 		 * If we are in the middle of FCF failover process, clear
6887 		 * the corresponding FCF bit in the roundrobin bitmap.
6888 		 */
6889 		spin_lock_irq(&phba->hbalock);
6890 		if ((phba->fcf.fcf_flag & FCF_DISCOVERY) &&
6891 		    (phba->fcf.current_rec.fcf_indx != acqe_fip->index)) {
6892 			spin_unlock_irq(&phba->hbalock);
6893 			/* Update FLOGI FCF failover eligible FCF bmask */
6894 			lpfc_sli4_fcf_rr_index_clear(phba, acqe_fip->index);
6895 			break;
6896 		}
6897 		spin_unlock_irq(&phba->hbalock);
6898 
6899 		/* If the event is not for currently used fcf do nothing */
6900 		if (phba->fcf.current_rec.fcf_indx != acqe_fip->index)
6901 			break;
6902 
6903 		/*
6904 		 * Otherwise, request the port to rediscover the entire FCF
6905 		 * table for a fast recovery from case that the current FCF
6906 		 * is no longer valid as we are not in the middle of FCF
6907 		 * failover process already.
6908 		 */
6909 		spin_lock_irq(&phba->hbalock);
6910 		/* Mark the fast failover process in progress */
6911 		phba->fcf.fcf_flag |= FCF_DEAD_DISC;
6912 		spin_unlock_irq(&phba->hbalock);
6913 
6914 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
6915 				"2771 Start FCF fast failover process due to "
6916 				"FCF DEAD event: evt_tag:x%x, fcf_index:x%x "
6917 				"\n", acqe_fip->event_tag, acqe_fip->index);
6918 		rc = lpfc_sli4_redisc_fcf_table(phba);
6919 		if (rc) {
6920 			lpfc_printf_log(phba, KERN_ERR, LOG_FIP |
6921 					LOG_TRACE_EVENT,
6922 					"2772 Issue FCF rediscover mailbox "
6923 					"command failed, fail through to FCF "
6924 					"dead event\n");
6925 			spin_lock_irq(&phba->hbalock);
6926 			phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
6927 			spin_unlock_irq(&phba->hbalock);
6928 			/*
6929 			 * Last resort will fail over by treating this
6930 			 * as a link down to FCF registration.
6931 			 */
6932 			lpfc_sli4_fcf_dead_failthrough(phba);
6933 		} else {
6934 			/* Reset FCF roundrobin bmask for new discovery */
6935 			lpfc_sli4_clear_fcf_rr_bmask(phba);
6936 			/*
6937 			 * Handling fast FCF failover to a DEAD FCF event is
6938 			 * considered equalivant to receiving CVL to all vports.
6939 			 */
6940 			lpfc_sli4_perform_all_vport_cvl(phba);
6941 		}
6942 		break;
6943 	case LPFC_FIP_EVENT_TYPE_CVL:
6944 		phba->fcoe_cvl_eventtag = acqe_fip->event_tag;
6945 		lpfc_printf_log(phba, KERN_ERR,
6946 				LOG_TRACE_EVENT,
6947 			"2718 Clear Virtual Link Received for VPI 0x%x"
6948 			" tag 0x%x\n", acqe_fip->index, acqe_fip->event_tag);
6949 
6950 		vport = lpfc_find_vport_by_vpid(phba,
6951 						acqe_fip->index);
6952 		ndlp = lpfc_sli4_perform_vport_cvl(vport);
6953 		if (!ndlp)
6954 			break;
6955 		active_vlink_present = 0;
6956 
6957 		vports = lpfc_create_vport_work_array(phba);
6958 		if (vports) {
6959 			for (i = 0; i <= phba->max_vports && vports[i] != NULL;
6960 					i++) {
6961 				if ((!(vports[i]->fc_flag &
6962 					FC_VPORT_CVL_RCVD)) &&
6963 					(vports[i]->port_state > LPFC_FDISC)) {
6964 					active_vlink_present = 1;
6965 					break;
6966 				}
6967 			}
6968 			lpfc_destroy_vport_work_array(phba, vports);
6969 		}
6970 
6971 		/*
6972 		 * Don't re-instantiate if vport is marked for deletion.
6973 		 * If we are here first then vport_delete is going to wait
6974 		 * for discovery to complete.
6975 		 */
6976 		if (!(vport->load_flag & FC_UNLOADING) &&
6977 					active_vlink_present) {
6978 			/*
6979 			 * If there are other active VLinks present,
6980 			 * re-instantiate the Vlink using FDISC.
6981 			 */
6982 			mod_timer(&ndlp->nlp_delayfunc,
6983 				  jiffies + msecs_to_jiffies(1000));
6984 			spin_lock_irq(&ndlp->lock);
6985 			ndlp->nlp_flag |= NLP_DELAY_TMO;
6986 			spin_unlock_irq(&ndlp->lock);
6987 			ndlp->nlp_last_elscmd = ELS_CMD_FDISC;
6988 			vport->port_state = LPFC_FDISC;
6989 		} else {
6990 			/*
6991 			 * Otherwise, we request port to rediscover
6992 			 * the entire FCF table for a fast recovery
6993 			 * from possible case that the current FCF
6994 			 * is no longer valid if we are not already
6995 			 * in the FCF failover process.
6996 			 */
6997 			spin_lock_irq(&phba->hbalock);
6998 			if (phba->fcf.fcf_flag & FCF_DISCOVERY) {
6999 				spin_unlock_irq(&phba->hbalock);
7000 				break;
7001 			}
7002 			/* Mark the fast failover process in progress */
7003 			phba->fcf.fcf_flag |= FCF_ACVL_DISC;
7004 			spin_unlock_irq(&phba->hbalock);
7005 			lpfc_printf_log(phba, KERN_INFO, LOG_FIP |
7006 					LOG_DISCOVERY,
7007 					"2773 Start FCF failover per CVL, "
7008 					"evt_tag:x%x\n", acqe_fip->event_tag);
7009 			rc = lpfc_sli4_redisc_fcf_table(phba);
7010 			if (rc) {
7011 				lpfc_printf_log(phba, KERN_ERR, LOG_FIP |
7012 						LOG_TRACE_EVENT,
7013 						"2774 Issue FCF rediscover "
7014 						"mailbox command failed, "
7015 						"through to CVL event\n");
7016 				spin_lock_irq(&phba->hbalock);
7017 				phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
7018 				spin_unlock_irq(&phba->hbalock);
7019 				/*
7020 				 * Last resort will be re-try on the
7021 				 * the current registered FCF entry.
7022 				 */
7023 				lpfc_retry_pport_discovery(phba);
7024 			} else
7025 				/*
7026 				 * Reset FCF roundrobin bmask for new
7027 				 * discovery.
7028 				 */
7029 				lpfc_sli4_clear_fcf_rr_bmask(phba);
7030 		}
7031 		break;
7032 	default:
7033 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7034 				"0288 Unknown FCoE event type 0x%x event tag "
7035 				"0x%x\n", event_type, acqe_fip->event_tag);
7036 		break;
7037 	}
7038 }
7039 
7040 /**
7041  * lpfc_sli4_async_dcbx_evt - Process the asynchronous dcbx event
7042  * @phba: pointer to lpfc hba data structure.
7043  * @acqe_dcbx: pointer to the async dcbx completion queue entry.
7044  *
7045  * This routine is to handle the SLI4 asynchronous dcbx event.
7046  **/
7047 static void
7048 lpfc_sli4_async_dcbx_evt(struct lpfc_hba *phba,
7049 			 struct lpfc_acqe_dcbx *acqe_dcbx)
7050 {
7051 	phba->fc_eventTag = acqe_dcbx->event_tag;
7052 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7053 			"0290 The SLI4 DCBX asynchronous event is not "
7054 			"handled yet\n");
7055 }
7056 
7057 /**
7058  * lpfc_sli4_async_grp5_evt - Process the asynchronous group5 event
7059  * @phba: pointer to lpfc hba data structure.
7060  * @acqe_grp5: pointer to the async grp5 completion queue entry.
7061  *
7062  * This routine is to handle the SLI4 asynchronous grp5 event. A grp5 event
7063  * is an asynchronous notified of a logical link speed change.  The Port
7064  * reports the logical link speed in units of 10Mbps.
7065  **/
7066 static void
7067 lpfc_sli4_async_grp5_evt(struct lpfc_hba *phba,
7068 			 struct lpfc_acqe_grp5 *acqe_grp5)
7069 {
7070 	uint16_t prev_ll_spd;
7071 
7072 	phba->fc_eventTag = acqe_grp5->event_tag;
7073 	phba->fcoe_eventtag = acqe_grp5->event_tag;
7074 	prev_ll_spd = phba->sli4_hba.link_state.logical_speed;
7075 	phba->sli4_hba.link_state.logical_speed =
7076 		(bf_get(lpfc_acqe_grp5_llink_spd, acqe_grp5)) * 10;
7077 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
7078 			"2789 GRP5 Async Event: Updating logical link speed "
7079 			"from %dMbps to %dMbps\n", prev_ll_spd,
7080 			phba->sli4_hba.link_state.logical_speed);
7081 }
7082 
7083 /**
7084  * lpfc_sli4_async_cmstat_evt - Process the asynchronous cmstat event
7085  * @phba: pointer to lpfc hba data structure.
7086  *
7087  * This routine is to handle the SLI4 asynchronous cmstat event. A cmstat event
7088  * is an asynchronous notification of a request to reset CM stats.
7089  **/
7090 static void
7091 lpfc_sli4_async_cmstat_evt(struct lpfc_hba *phba)
7092 {
7093 	if (!phba->cgn_i)
7094 		return;
7095 	lpfc_init_congestion_stat(phba);
7096 }
7097 
7098 /**
7099  * lpfc_cgn_params_val - Validate FW congestion parameters.
7100  * @phba: pointer to lpfc hba data structure.
7101  * @p_cfg_param: pointer to FW provided congestion parameters.
7102  *
7103  * This routine validates the congestion parameters passed
7104  * by the FW to the driver via an ACQE event.
7105  **/
7106 static void
7107 lpfc_cgn_params_val(struct lpfc_hba *phba, struct lpfc_cgn_param *p_cfg_param)
7108 {
7109 	spin_lock_irq(&phba->hbalock);
7110 
7111 	if (!lpfc_rangecheck(p_cfg_param->cgn_param_mode, LPFC_CFG_OFF,
7112 			     LPFC_CFG_MONITOR)) {
7113 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT,
7114 				"6225 CMF mode param out of range: %d\n",
7115 				 p_cfg_param->cgn_param_mode);
7116 		p_cfg_param->cgn_param_mode = LPFC_CFG_OFF;
7117 	}
7118 
7119 	spin_unlock_irq(&phba->hbalock);
7120 }
7121 
7122 static const char * const lpfc_cmf_mode_to_str[] = {
7123 	"OFF",
7124 	"MANAGED",
7125 	"MONITOR",
7126 };
7127 
7128 /**
7129  * lpfc_cgn_params_parse - Process a FW cong parm change event
7130  * @phba: pointer to lpfc hba data structure.
7131  * @p_cgn_param: pointer to a data buffer with the FW cong params.
7132  * @len: the size of pdata in bytes.
7133  *
7134  * This routine validates the congestion management buffer signature
7135  * from the FW, validates the contents and makes corrections for
7136  * valid, in-range values.  If the signature magic is correct and
7137  * after parameter validation, the contents are copied to the driver's
7138  * @phba structure. If the magic is incorrect, an error message is
7139  * logged.
7140  **/
7141 static void
7142 lpfc_cgn_params_parse(struct lpfc_hba *phba,
7143 		      struct lpfc_cgn_param *p_cgn_param, uint32_t len)
7144 {
7145 	struct lpfc_cgn_info *cp;
7146 	uint32_t crc, oldmode;
7147 	char acr_string[4] = {0};
7148 
7149 	/* Make sure the FW has encoded the correct magic number to
7150 	 * validate the congestion parameter in FW memory.
7151 	 */
7152 	if (p_cgn_param->cgn_param_magic == LPFC_CFG_PARAM_MAGIC_NUM) {
7153 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT | LOG_INIT,
7154 				"4668 FW cgn parm buffer data: "
7155 				"magic 0x%x version %d mode %d "
7156 				"level0 %d level1 %d "
7157 				"level2 %d byte13 %d "
7158 				"byte14 %d byte15 %d "
7159 				"byte11 %d byte12 %d activeMode %d\n",
7160 				p_cgn_param->cgn_param_magic,
7161 				p_cgn_param->cgn_param_version,
7162 				p_cgn_param->cgn_param_mode,
7163 				p_cgn_param->cgn_param_level0,
7164 				p_cgn_param->cgn_param_level1,
7165 				p_cgn_param->cgn_param_level2,
7166 				p_cgn_param->byte13,
7167 				p_cgn_param->byte14,
7168 				p_cgn_param->byte15,
7169 				p_cgn_param->byte11,
7170 				p_cgn_param->byte12,
7171 				phba->cmf_active_mode);
7172 
7173 		oldmode = phba->cmf_active_mode;
7174 
7175 		/* Any parameters out of range are corrected to defaults
7176 		 * by this routine.  No need to fail.
7177 		 */
7178 		lpfc_cgn_params_val(phba, p_cgn_param);
7179 
7180 		/* Parameters are verified, move them into driver storage */
7181 		spin_lock_irq(&phba->hbalock);
7182 		memcpy(&phba->cgn_p, p_cgn_param,
7183 		       sizeof(struct lpfc_cgn_param));
7184 
7185 		/* Update parameters in congestion info buffer now */
7186 		if (phba->cgn_i) {
7187 			cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
7188 			cp->cgn_info_mode = phba->cgn_p.cgn_param_mode;
7189 			cp->cgn_info_level0 = phba->cgn_p.cgn_param_level0;
7190 			cp->cgn_info_level1 = phba->cgn_p.cgn_param_level1;
7191 			cp->cgn_info_level2 = phba->cgn_p.cgn_param_level2;
7192 			crc = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ,
7193 						  LPFC_CGN_CRC32_SEED);
7194 			cp->cgn_info_crc = cpu_to_le32(crc);
7195 		}
7196 		spin_unlock_irq(&phba->hbalock);
7197 
7198 		phba->cmf_active_mode = phba->cgn_p.cgn_param_mode;
7199 
7200 		switch (oldmode) {
7201 		case LPFC_CFG_OFF:
7202 			if (phba->cgn_p.cgn_param_mode != LPFC_CFG_OFF) {
7203 				/* Turning CMF on */
7204 				lpfc_cmf_start(phba);
7205 
7206 				if (phba->link_state >= LPFC_LINK_UP) {
7207 					phba->cgn_reg_fpin =
7208 						phba->cgn_init_reg_fpin;
7209 					phba->cgn_reg_signal =
7210 						phba->cgn_init_reg_signal;
7211 					lpfc_issue_els_edc(phba->pport, 0);
7212 				}
7213 			}
7214 			break;
7215 		case LPFC_CFG_MANAGED:
7216 			switch (phba->cgn_p.cgn_param_mode) {
7217 			case LPFC_CFG_OFF:
7218 				/* Turning CMF off */
7219 				lpfc_cmf_stop(phba);
7220 				if (phba->link_state >= LPFC_LINK_UP)
7221 					lpfc_issue_els_edc(phba->pport, 0);
7222 				break;
7223 			case LPFC_CFG_MONITOR:
7224 				phba->cmf_max_bytes_per_interval =
7225 					phba->cmf_link_byte_count;
7226 
7227 				/* Resume blocked IO - unblock on workqueue */
7228 				queue_work(phba->wq,
7229 					   &phba->unblock_request_work);
7230 				break;
7231 			}
7232 			break;
7233 		case LPFC_CFG_MONITOR:
7234 			switch (phba->cgn_p.cgn_param_mode) {
7235 			case LPFC_CFG_OFF:
7236 				/* Turning CMF off */
7237 				lpfc_cmf_stop(phba);
7238 				if (phba->link_state >= LPFC_LINK_UP)
7239 					lpfc_issue_els_edc(phba->pport, 0);
7240 				break;
7241 			case LPFC_CFG_MANAGED:
7242 				lpfc_cmf_signal_init(phba);
7243 				break;
7244 			}
7245 			break;
7246 		}
7247 		if (oldmode != LPFC_CFG_OFF ||
7248 		    oldmode != phba->cgn_p.cgn_param_mode) {
7249 			if (phba->cgn_p.cgn_param_mode == LPFC_CFG_MANAGED)
7250 				scnprintf(acr_string, sizeof(acr_string), "%u",
7251 					  phba->cgn_p.cgn_param_level0);
7252 			else
7253 				scnprintf(acr_string, sizeof(acr_string), "NA");
7254 
7255 			dev_info(&phba->pcidev->dev, "%d: "
7256 				 "4663 CMF: Mode %s acr %s\n",
7257 				 phba->brd_no,
7258 				 lpfc_cmf_mode_to_str
7259 				 [phba->cgn_p.cgn_param_mode],
7260 				 acr_string);
7261 		}
7262 	} else {
7263 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7264 				"4669 FW cgn parm buf wrong magic 0x%x "
7265 				"version %d\n", p_cgn_param->cgn_param_magic,
7266 				p_cgn_param->cgn_param_version);
7267 	}
7268 }
7269 
7270 /**
7271  * lpfc_sli4_cgn_params_read - Read and Validate FW congestion parameters.
7272  * @phba: pointer to lpfc hba data structure.
7273  *
7274  * This routine issues a read_object mailbox command to
7275  * get the congestion management parameters from the FW
7276  * parses it and updates the driver maintained values.
7277  *
7278  * Returns
7279  *  0     if the object was empty
7280  *  -Eval if an error was encountered
7281  *  Count if bytes were read from object
7282  **/
7283 int
7284 lpfc_sli4_cgn_params_read(struct lpfc_hba *phba)
7285 {
7286 	int ret = 0;
7287 	struct lpfc_cgn_param *p_cgn_param = NULL;
7288 	u32 *pdata = NULL;
7289 	u32 len = 0;
7290 
7291 	/* Find out if the FW has a new set of congestion parameters. */
7292 	len = sizeof(struct lpfc_cgn_param);
7293 	pdata = kzalloc(len, GFP_KERNEL);
7294 	if (!pdata)
7295 		return -ENOMEM;
7296 	ret = lpfc_read_object(phba, (char *)LPFC_PORT_CFG_NAME,
7297 			       pdata, len);
7298 
7299 	/* 0 means no data.  A negative means error.  A positive means
7300 	 * bytes were copied.
7301 	 */
7302 	if (!ret) {
7303 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7304 				"4670 CGN RD OBJ returns no data\n");
7305 		goto rd_obj_err;
7306 	} else if (ret < 0) {
7307 		/* Some error.  Just exit and return it to the caller.*/
7308 		goto rd_obj_err;
7309 	}
7310 
7311 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT | LOG_INIT,
7312 			"6234 READ CGN PARAMS Successful %d\n", len);
7313 
7314 	/* Parse data pointer over len and update the phba congestion
7315 	 * parameters with values passed back.  The receive rate values
7316 	 * may have been altered in FW, but take no action here.
7317 	 */
7318 	p_cgn_param = (struct lpfc_cgn_param *)pdata;
7319 	lpfc_cgn_params_parse(phba, p_cgn_param, len);
7320 
7321  rd_obj_err:
7322 	kfree(pdata);
7323 	return ret;
7324 }
7325 
7326 /**
7327  * lpfc_sli4_cgn_parm_chg_evt - Process a FW congestion param change event
7328  * @phba: pointer to lpfc hba data structure.
7329  *
7330  * The FW generated Async ACQE SLI event calls this routine when
7331  * the event type is an SLI Internal Port Event and the Event Code
7332  * indicates a change to the FW maintained congestion parameters.
7333  *
7334  * This routine executes a Read_Object mailbox call to obtain the
7335  * current congestion parameters maintained in FW and corrects
7336  * the driver's active congestion parameters.
7337  *
7338  * The acqe event is not passed because there is no further data
7339  * required.
7340  *
7341  * Returns nonzero error if event processing encountered an error.
7342  * Zero otherwise for success.
7343  **/
7344 static int
7345 lpfc_sli4_cgn_parm_chg_evt(struct lpfc_hba *phba)
7346 {
7347 	int ret = 0;
7348 
7349 	if (!phba->sli4_hba.pc_sli4_params.cmf) {
7350 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7351 				"4664 Cgn Evt when E2E off. Drop event\n");
7352 		return -EACCES;
7353 	}
7354 
7355 	/* If the event is claiming an empty object, it's ok.  A write
7356 	 * could have cleared it.  Only error is a negative return
7357 	 * status.
7358 	 */
7359 	ret = lpfc_sli4_cgn_params_read(phba);
7360 	if (ret < 0) {
7361 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7362 				"4667 Error reading Cgn Params (%d)\n",
7363 				ret);
7364 	} else if (!ret) {
7365 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7366 				"4673 CGN Event empty object.\n");
7367 	}
7368 	return ret;
7369 }
7370 
7371 /**
7372  * lpfc_sli4_async_event_proc - Process all the pending asynchronous event
7373  * @phba: pointer to lpfc hba data structure.
7374  *
7375  * This routine is invoked by the worker thread to process all the pending
7376  * SLI4 asynchronous events.
7377  **/
7378 void lpfc_sli4_async_event_proc(struct lpfc_hba *phba)
7379 {
7380 	struct lpfc_cq_event *cq_event;
7381 	unsigned long iflags;
7382 
7383 	/* First, declare the async event has been handled */
7384 	spin_lock_irqsave(&phba->hbalock, iflags);
7385 	phba->hba_flag &= ~ASYNC_EVENT;
7386 	spin_unlock_irqrestore(&phba->hbalock, iflags);
7387 
7388 	/* Now, handle all the async events */
7389 	spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
7390 	while (!list_empty(&phba->sli4_hba.sp_asynce_work_queue)) {
7391 		list_remove_head(&phba->sli4_hba.sp_asynce_work_queue,
7392 				 cq_event, struct lpfc_cq_event, list);
7393 		spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock,
7394 				       iflags);
7395 
7396 		/* Process the asynchronous event */
7397 		switch (bf_get(lpfc_trailer_code, &cq_event->cqe.mcqe_cmpl)) {
7398 		case LPFC_TRAILER_CODE_LINK:
7399 			lpfc_sli4_async_link_evt(phba,
7400 						 &cq_event->cqe.acqe_link);
7401 			break;
7402 		case LPFC_TRAILER_CODE_FCOE:
7403 			lpfc_sli4_async_fip_evt(phba, &cq_event->cqe.acqe_fip);
7404 			break;
7405 		case LPFC_TRAILER_CODE_DCBX:
7406 			lpfc_sli4_async_dcbx_evt(phba,
7407 						 &cq_event->cqe.acqe_dcbx);
7408 			break;
7409 		case LPFC_TRAILER_CODE_GRP5:
7410 			lpfc_sli4_async_grp5_evt(phba,
7411 						 &cq_event->cqe.acqe_grp5);
7412 			break;
7413 		case LPFC_TRAILER_CODE_FC:
7414 			lpfc_sli4_async_fc_evt(phba, &cq_event->cqe.acqe_fc);
7415 			break;
7416 		case LPFC_TRAILER_CODE_SLI:
7417 			lpfc_sli4_async_sli_evt(phba, &cq_event->cqe.acqe_sli);
7418 			break;
7419 		case LPFC_TRAILER_CODE_CMSTAT:
7420 			lpfc_sli4_async_cmstat_evt(phba);
7421 			break;
7422 		default:
7423 			lpfc_printf_log(phba, KERN_ERR,
7424 					LOG_TRACE_EVENT,
7425 					"1804 Invalid asynchronous event code: "
7426 					"x%x\n", bf_get(lpfc_trailer_code,
7427 					&cq_event->cqe.mcqe_cmpl));
7428 			break;
7429 		}
7430 
7431 		/* Free the completion event processed to the free pool */
7432 		lpfc_sli4_cq_event_release(phba, cq_event);
7433 		spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
7434 	}
7435 	spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock, iflags);
7436 }
7437 
7438 /**
7439  * lpfc_sli4_fcf_redisc_event_proc - Process fcf table rediscovery event
7440  * @phba: pointer to lpfc hba data structure.
7441  *
7442  * This routine is invoked by the worker thread to process FCF table
7443  * rediscovery pending completion event.
7444  **/
7445 void lpfc_sli4_fcf_redisc_event_proc(struct lpfc_hba *phba)
7446 {
7447 	int rc;
7448 
7449 	spin_lock_irq(&phba->hbalock);
7450 	/* Clear FCF rediscovery timeout event */
7451 	phba->fcf.fcf_flag &= ~FCF_REDISC_EVT;
7452 	/* Clear driver fast failover FCF record flag */
7453 	phba->fcf.failover_rec.flag = 0;
7454 	/* Set state for FCF fast failover */
7455 	phba->fcf.fcf_flag |= FCF_REDISC_FOV;
7456 	spin_unlock_irq(&phba->hbalock);
7457 
7458 	/* Scan FCF table from the first entry to re-discover SAN */
7459 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
7460 			"2777 Start post-quiescent FCF table scan\n");
7461 	rc = lpfc_sli4_fcf_scan_read_fcf_rec(phba, LPFC_FCOE_FCF_GET_FIRST);
7462 	if (rc)
7463 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7464 				"2747 Issue FCF scan read FCF mailbox "
7465 				"command failed 0x%x\n", rc);
7466 }
7467 
7468 /**
7469  * lpfc_api_table_setup - Set up per hba pci-device group func api jump table
7470  * @phba: pointer to lpfc hba data structure.
7471  * @dev_grp: The HBA PCI-Device group number.
7472  *
7473  * This routine is invoked to set up the per HBA PCI-Device group function
7474  * API jump table entries.
7475  *
7476  * Return: 0 if success, otherwise -ENODEV
7477  **/
7478 int
7479 lpfc_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
7480 {
7481 	int rc;
7482 
7483 	/* Set up lpfc PCI-device group */
7484 	phba->pci_dev_grp = dev_grp;
7485 
7486 	/* The LPFC_PCI_DEV_OC uses SLI4 */
7487 	if (dev_grp == LPFC_PCI_DEV_OC)
7488 		phba->sli_rev = LPFC_SLI_REV4;
7489 
7490 	/* Set up device INIT API function jump table */
7491 	rc = lpfc_init_api_table_setup(phba, dev_grp);
7492 	if (rc)
7493 		return -ENODEV;
7494 	/* Set up SCSI API function jump table */
7495 	rc = lpfc_scsi_api_table_setup(phba, dev_grp);
7496 	if (rc)
7497 		return -ENODEV;
7498 	/* Set up SLI API function jump table */
7499 	rc = lpfc_sli_api_table_setup(phba, dev_grp);
7500 	if (rc)
7501 		return -ENODEV;
7502 	/* Set up MBOX API function jump table */
7503 	rc = lpfc_mbox_api_table_setup(phba, dev_grp);
7504 	if (rc)
7505 		return -ENODEV;
7506 
7507 	return 0;
7508 }
7509 
7510 /**
7511  * lpfc_log_intr_mode - Log the active interrupt mode
7512  * @phba: pointer to lpfc hba data structure.
7513  * @intr_mode: active interrupt mode adopted.
7514  *
7515  * This routine it invoked to log the currently used active interrupt mode
7516  * to the device.
7517  **/
7518 static void lpfc_log_intr_mode(struct lpfc_hba *phba, uint32_t intr_mode)
7519 {
7520 	switch (intr_mode) {
7521 	case 0:
7522 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7523 				"0470 Enable INTx interrupt mode.\n");
7524 		break;
7525 	case 1:
7526 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7527 				"0481 Enabled MSI interrupt mode.\n");
7528 		break;
7529 	case 2:
7530 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7531 				"0480 Enabled MSI-X interrupt mode.\n");
7532 		break;
7533 	default:
7534 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7535 				"0482 Illegal interrupt mode.\n");
7536 		break;
7537 	}
7538 	return;
7539 }
7540 
7541 /**
7542  * lpfc_enable_pci_dev - Enable a generic PCI device.
7543  * @phba: pointer to lpfc hba data structure.
7544  *
7545  * This routine is invoked to enable the PCI device that is common to all
7546  * PCI devices.
7547  *
7548  * Return codes
7549  * 	0 - successful
7550  * 	other values - error
7551  **/
7552 static int
7553 lpfc_enable_pci_dev(struct lpfc_hba *phba)
7554 {
7555 	struct pci_dev *pdev;
7556 
7557 	/* Obtain PCI device reference */
7558 	if (!phba->pcidev)
7559 		goto out_error;
7560 	else
7561 		pdev = phba->pcidev;
7562 	/* Enable PCI device */
7563 	if (pci_enable_device_mem(pdev))
7564 		goto out_error;
7565 	/* Request PCI resource for the device */
7566 	if (pci_request_mem_regions(pdev, LPFC_DRIVER_NAME))
7567 		goto out_disable_device;
7568 	/* Set up device as PCI master and save state for EEH */
7569 	pci_set_master(pdev);
7570 	pci_try_set_mwi(pdev);
7571 	pci_save_state(pdev);
7572 
7573 	/* PCIe EEH recovery on powerpc platforms needs fundamental reset */
7574 	if (pci_is_pcie(pdev))
7575 		pdev->needs_freset = 1;
7576 
7577 	return 0;
7578 
7579 out_disable_device:
7580 	pci_disable_device(pdev);
7581 out_error:
7582 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7583 			"1401 Failed to enable pci device\n");
7584 	return -ENODEV;
7585 }
7586 
7587 /**
7588  * lpfc_disable_pci_dev - Disable a generic PCI device.
7589  * @phba: pointer to lpfc hba data structure.
7590  *
7591  * This routine is invoked to disable the PCI device that is common to all
7592  * PCI devices.
7593  **/
7594 static void
7595 lpfc_disable_pci_dev(struct lpfc_hba *phba)
7596 {
7597 	struct pci_dev *pdev;
7598 
7599 	/* Obtain PCI device reference */
7600 	if (!phba->pcidev)
7601 		return;
7602 	else
7603 		pdev = phba->pcidev;
7604 	/* Release PCI resource and disable PCI device */
7605 	pci_release_mem_regions(pdev);
7606 	pci_disable_device(pdev);
7607 
7608 	return;
7609 }
7610 
7611 /**
7612  * lpfc_reset_hba - Reset a hba
7613  * @phba: pointer to lpfc hba data structure.
7614  *
7615  * This routine is invoked to reset a hba device. It brings the HBA
7616  * offline, performs a board restart, and then brings the board back
7617  * online. The lpfc_offline calls lpfc_sli_hba_down which will clean up
7618  * on outstanding mailbox commands.
7619  **/
7620 void
7621 lpfc_reset_hba(struct lpfc_hba *phba)
7622 {
7623 	/* If resets are disabled then set error state and return. */
7624 	if (!phba->cfg_enable_hba_reset) {
7625 		phba->link_state = LPFC_HBA_ERROR;
7626 		return;
7627 	}
7628 
7629 	/* If not LPFC_SLI_ACTIVE, force all IO to be flushed */
7630 	if (phba->sli.sli_flag & LPFC_SLI_ACTIVE) {
7631 		lpfc_offline_prep(phba, LPFC_MBX_WAIT);
7632 	} else {
7633 		lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
7634 		lpfc_sli_flush_io_rings(phba);
7635 	}
7636 	lpfc_offline(phba);
7637 	lpfc_sli_brdrestart(phba);
7638 	lpfc_online(phba);
7639 	lpfc_unblock_mgmt_io(phba);
7640 }
7641 
7642 /**
7643  * lpfc_sli_sriov_nr_virtfn_get - Get the number of sr-iov virtual functions
7644  * @phba: pointer to lpfc hba data structure.
7645  *
7646  * This function enables the PCI SR-IOV virtual functions to a physical
7647  * function. It invokes the PCI SR-IOV api with the @nr_vfn provided to
7648  * enable the number of virtual functions to the physical function. As
7649  * not all devices support SR-IOV, the return code from the pci_enable_sriov()
7650  * API call does not considered as an error condition for most of the device.
7651  **/
7652 uint16_t
7653 lpfc_sli_sriov_nr_virtfn_get(struct lpfc_hba *phba)
7654 {
7655 	struct pci_dev *pdev = phba->pcidev;
7656 	uint16_t nr_virtfn;
7657 	int pos;
7658 
7659 	pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_SRIOV);
7660 	if (pos == 0)
7661 		return 0;
7662 
7663 	pci_read_config_word(pdev, pos + PCI_SRIOV_TOTAL_VF, &nr_virtfn);
7664 	return nr_virtfn;
7665 }
7666 
7667 /**
7668  * lpfc_sli_probe_sriov_nr_virtfn - Enable a number of sr-iov virtual functions
7669  * @phba: pointer to lpfc hba data structure.
7670  * @nr_vfn: number of virtual functions to be enabled.
7671  *
7672  * This function enables the PCI SR-IOV virtual functions to a physical
7673  * function. It invokes the PCI SR-IOV api with the @nr_vfn provided to
7674  * enable the number of virtual functions to the physical function. As
7675  * not all devices support SR-IOV, the return code from the pci_enable_sriov()
7676  * API call does not considered as an error condition for most of the device.
7677  **/
7678 int
7679 lpfc_sli_probe_sriov_nr_virtfn(struct lpfc_hba *phba, int nr_vfn)
7680 {
7681 	struct pci_dev *pdev = phba->pcidev;
7682 	uint16_t max_nr_vfn;
7683 	int rc;
7684 
7685 	max_nr_vfn = lpfc_sli_sriov_nr_virtfn_get(phba);
7686 	if (nr_vfn > max_nr_vfn) {
7687 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7688 				"3057 Requested vfs (%d) greater than "
7689 				"supported vfs (%d)", nr_vfn, max_nr_vfn);
7690 		return -EINVAL;
7691 	}
7692 
7693 	rc = pci_enable_sriov(pdev, nr_vfn);
7694 	if (rc) {
7695 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7696 				"2806 Failed to enable sriov on this device "
7697 				"with vfn number nr_vf:%d, rc:%d\n",
7698 				nr_vfn, rc);
7699 	} else
7700 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7701 				"2807 Successful enable sriov on this device "
7702 				"with vfn number nr_vf:%d\n", nr_vfn);
7703 	return rc;
7704 }
7705 
7706 static void
7707 lpfc_unblock_requests_work(struct work_struct *work)
7708 {
7709 	struct lpfc_hba *phba = container_of(work, struct lpfc_hba,
7710 					     unblock_request_work);
7711 
7712 	lpfc_unblock_requests(phba);
7713 }
7714 
7715 /**
7716  * lpfc_setup_driver_resource_phase1 - Phase1 etup driver internal resources.
7717  * @phba: pointer to lpfc hba data structure.
7718  *
7719  * This routine is invoked to set up the driver internal resources before the
7720  * device specific resource setup to support the HBA device it attached to.
7721  *
7722  * Return codes
7723  *	0 - successful
7724  *	other values - error
7725  **/
7726 static int
7727 lpfc_setup_driver_resource_phase1(struct lpfc_hba *phba)
7728 {
7729 	struct lpfc_sli *psli = &phba->sli;
7730 
7731 	/*
7732 	 * Driver resources common to all SLI revisions
7733 	 */
7734 	atomic_set(&phba->fast_event_count, 0);
7735 	atomic_set(&phba->dbg_log_idx, 0);
7736 	atomic_set(&phba->dbg_log_cnt, 0);
7737 	atomic_set(&phba->dbg_log_dmping, 0);
7738 	spin_lock_init(&phba->hbalock);
7739 
7740 	/* Initialize port_list spinlock */
7741 	spin_lock_init(&phba->port_list_lock);
7742 	INIT_LIST_HEAD(&phba->port_list);
7743 
7744 	INIT_LIST_HEAD(&phba->work_list);
7745 
7746 	/* Initialize the wait queue head for the kernel thread */
7747 	init_waitqueue_head(&phba->work_waitq);
7748 
7749 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7750 			"1403 Protocols supported %s %s %s\n",
7751 			((phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP) ?
7752 				"SCSI" : " "),
7753 			((phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) ?
7754 				"NVME" : " "),
7755 			(phba->nvmet_support ? "NVMET" : " "));
7756 
7757 	/* Initialize the IO buffer list used by driver for SLI3 SCSI */
7758 	spin_lock_init(&phba->scsi_buf_list_get_lock);
7759 	INIT_LIST_HEAD(&phba->lpfc_scsi_buf_list_get);
7760 	spin_lock_init(&phba->scsi_buf_list_put_lock);
7761 	INIT_LIST_HEAD(&phba->lpfc_scsi_buf_list_put);
7762 
7763 	/* Initialize the fabric iocb list */
7764 	INIT_LIST_HEAD(&phba->fabric_iocb_list);
7765 
7766 	/* Initialize list to save ELS buffers */
7767 	INIT_LIST_HEAD(&phba->elsbuf);
7768 
7769 	/* Initialize FCF connection rec list */
7770 	INIT_LIST_HEAD(&phba->fcf_conn_rec_list);
7771 
7772 	/* Initialize OAS configuration list */
7773 	spin_lock_init(&phba->devicelock);
7774 	INIT_LIST_HEAD(&phba->luns);
7775 
7776 	/* MBOX heartbeat timer */
7777 	timer_setup(&psli->mbox_tmo, lpfc_mbox_timeout, 0);
7778 	/* Fabric block timer */
7779 	timer_setup(&phba->fabric_block_timer, lpfc_fabric_block_timeout, 0);
7780 	/* EA polling mode timer */
7781 	timer_setup(&phba->eratt_poll, lpfc_poll_eratt, 0);
7782 	/* Heartbeat timer */
7783 	timer_setup(&phba->hb_tmofunc, lpfc_hb_timeout, 0);
7784 
7785 	INIT_DELAYED_WORK(&phba->eq_delay_work, lpfc_hb_eq_delay_work);
7786 
7787 	INIT_DELAYED_WORK(&phba->idle_stat_delay_work,
7788 			  lpfc_idle_stat_delay_work);
7789 	INIT_WORK(&phba->unblock_request_work, lpfc_unblock_requests_work);
7790 	return 0;
7791 }
7792 
7793 /**
7794  * lpfc_sli_driver_resource_setup - Setup driver internal resources for SLI3 dev
7795  * @phba: pointer to lpfc hba data structure.
7796  *
7797  * This routine is invoked to set up the driver internal resources specific to
7798  * support the SLI-3 HBA device it attached to.
7799  *
7800  * Return codes
7801  * 0 - successful
7802  * other values - error
7803  **/
7804 static int
7805 lpfc_sli_driver_resource_setup(struct lpfc_hba *phba)
7806 {
7807 	int rc, entry_sz;
7808 
7809 	/*
7810 	 * Initialize timers used by driver
7811 	 */
7812 
7813 	/* FCP polling mode timer */
7814 	timer_setup(&phba->fcp_poll_timer, lpfc_poll_timeout, 0);
7815 
7816 	/* Host attention work mask setup */
7817 	phba->work_ha_mask = (HA_ERATT | HA_MBATT | HA_LATT);
7818 	phba->work_ha_mask |= (HA_RXMASK << (LPFC_ELS_RING * 4));
7819 
7820 	/* Get all the module params for configuring this host */
7821 	lpfc_get_cfgparam(phba);
7822 	/* Set up phase-1 common device driver resources */
7823 
7824 	rc = lpfc_setup_driver_resource_phase1(phba);
7825 	if (rc)
7826 		return -ENODEV;
7827 
7828 	if (!phba->sli.sli3_ring)
7829 		phba->sli.sli3_ring = kcalloc(LPFC_SLI3_MAX_RING,
7830 					      sizeof(struct lpfc_sli_ring),
7831 					      GFP_KERNEL);
7832 	if (!phba->sli.sli3_ring)
7833 		return -ENOMEM;
7834 
7835 	/*
7836 	 * Since lpfc_sg_seg_cnt is module parameter, the sg_dma_buf_size
7837 	 * used to create the sg_dma_buf_pool must be dynamically calculated.
7838 	 */
7839 
7840 	if (phba->sli_rev == LPFC_SLI_REV4)
7841 		entry_sz = sizeof(struct sli4_sge);
7842 	else
7843 		entry_sz = sizeof(struct ulp_bde64);
7844 
7845 	/* There are going to be 2 reserved BDEs: 1 FCP cmnd + 1 FCP rsp */
7846 	if (phba->cfg_enable_bg) {
7847 		/*
7848 		 * The scsi_buf for a T10-DIF I/O will hold the FCP cmnd,
7849 		 * the FCP rsp, and a BDE for each. Sice we have no control
7850 		 * over how many protection data segments the SCSI Layer
7851 		 * will hand us (ie: there could be one for every block
7852 		 * in the IO), we just allocate enough BDEs to accomidate
7853 		 * our max amount and we need to limit lpfc_sg_seg_cnt to
7854 		 * minimize the risk of running out.
7855 		 */
7856 		phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd) +
7857 			sizeof(struct fcp_rsp) +
7858 			(LPFC_MAX_SG_SEG_CNT * entry_sz);
7859 
7860 		if (phba->cfg_sg_seg_cnt > LPFC_MAX_SG_SEG_CNT_DIF)
7861 			phba->cfg_sg_seg_cnt = LPFC_MAX_SG_SEG_CNT_DIF;
7862 
7863 		/* Total BDEs in BPL for scsi_sg_list and scsi_sg_prot_list */
7864 		phba->cfg_total_seg_cnt = LPFC_MAX_SG_SEG_CNT;
7865 	} else {
7866 		/*
7867 		 * The scsi_buf for a regular I/O will hold the FCP cmnd,
7868 		 * the FCP rsp, a BDE for each, and a BDE for up to
7869 		 * cfg_sg_seg_cnt data segments.
7870 		 */
7871 		phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd) +
7872 			sizeof(struct fcp_rsp) +
7873 			((phba->cfg_sg_seg_cnt + 2) * entry_sz);
7874 
7875 		/* Total BDEs in BPL for scsi_sg_list */
7876 		phba->cfg_total_seg_cnt = phba->cfg_sg_seg_cnt + 2;
7877 	}
7878 
7879 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP,
7880 			"9088 INIT sg_tablesize:%d dmabuf_size:%d total_bde:%d\n",
7881 			phba->cfg_sg_seg_cnt, phba->cfg_sg_dma_buf_size,
7882 			phba->cfg_total_seg_cnt);
7883 
7884 	phba->max_vpi = LPFC_MAX_VPI;
7885 	/* This will be set to correct value after config_port mbox */
7886 	phba->max_vports = 0;
7887 
7888 	/*
7889 	 * Initialize the SLI Layer to run with lpfc HBAs.
7890 	 */
7891 	lpfc_sli_setup(phba);
7892 	lpfc_sli_queue_init(phba);
7893 
7894 	/* Allocate device driver memory */
7895 	if (lpfc_mem_alloc(phba, BPL_ALIGN_SZ))
7896 		return -ENOMEM;
7897 
7898 	phba->lpfc_sg_dma_buf_pool =
7899 		dma_pool_create("lpfc_sg_dma_buf_pool",
7900 				&phba->pcidev->dev, phba->cfg_sg_dma_buf_size,
7901 				BPL_ALIGN_SZ, 0);
7902 
7903 	if (!phba->lpfc_sg_dma_buf_pool)
7904 		goto fail_free_mem;
7905 
7906 	phba->lpfc_cmd_rsp_buf_pool =
7907 			dma_pool_create("lpfc_cmd_rsp_buf_pool",
7908 					&phba->pcidev->dev,
7909 					sizeof(struct fcp_cmnd) +
7910 					sizeof(struct fcp_rsp),
7911 					BPL_ALIGN_SZ, 0);
7912 
7913 	if (!phba->lpfc_cmd_rsp_buf_pool)
7914 		goto fail_free_dma_buf_pool;
7915 
7916 	/*
7917 	 * Enable sr-iov virtual functions if supported and configured
7918 	 * through the module parameter.
7919 	 */
7920 	if (phba->cfg_sriov_nr_virtfn > 0) {
7921 		rc = lpfc_sli_probe_sriov_nr_virtfn(phba,
7922 						 phba->cfg_sriov_nr_virtfn);
7923 		if (rc) {
7924 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7925 					"2808 Requested number of SR-IOV "
7926 					"virtual functions (%d) is not "
7927 					"supported\n",
7928 					phba->cfg_sriov_nr_virtfn);
7929 			phba->cfg_sriov_nr_virtfn = 0;
7930 		}
7931 	}
7932 
7933 	return 0;
7934 
7935 fail_free_dma_buf_pool:
7936 	dma_pool_destroy(phba->lpfc_sg_dma_buf_pool);
7937 	phba->lpfc_sg_dma_buf_pool = NULL;
7938 fail_free_mem:
7939 	lpfc_mem_free(phba);
7940 	return -ENOMEM;
7941 }
7942 
7943 /**
7944  * lpfc_sli_driver_resource_unset - Unset drvr internal resources for SLI3 dev
7945  * @phba: pointer to lpfc hba data structure.
7946  *
7947  * This routine is invoked to unset the driver internal resources set up
7948  * specific for supporting the SLI-3 HBA device it attached to.
7949  **/
7950 static void
7951 lpfc_sli_driver_resource_unset(struct lpfc_hba *phba)
7952 {
7953 	/* Free device driver memory allocated */
7954 	lpfc_mem_free_all(phba);
7955 
7956 	return;
7957 }
7958 
7959 /**
7960  * lpfc_sli4_driver_resource_setup - Setup drvr internal resources for SLI4 dev
7961  * @phba: pointer to lpfc hba data structure.
7962  *
7963  * This routine is invoked to set up the driver internal resources specific to
7964  * support the SLI-4 HBA device it attached to.
7965  *
7966  * Return codes
7967  * 	0 - successful
7968  * 	other values - error
7969  **/
7970 static int
7971 lpfc_sli4_driver_resource_setup(struct lpfc_hba *phba)
7972 {
7973 	LPFC_MBOXQ_t *mboxq;
7974 	MAILBOX_t *mb;
7975 	int rc, i, max_buf_size;
7976 	int longs;
7977 	int extra;
7978 	uint64_t wwn;
7979 	u32 if_type;
7980 	u32 if_fam;
7981 
7982 	phba->sli4_hba.num_present_cpu = lpfc_present_cpu;
7983 	phba->sli4_hba.num_possible_cpu = cpumask_last(cpu_possible_mask) + 1;
7984 	phba->sli4_hba.curr_disp_cpu = 0;
7985 
7986 	/* Get all the module params for configuring this host */
7987 	lpfc_get_cfgparam(phba);
7988 
7989 	/* Set up phase-1 common device driver resources */
7990 	rc = lpfc_setup_driver_resource_phase1(phba);
7991 	if (rc)
7992 		return -ENODEV;
7993 
7994 	/* Before proceed, wait for POST done and device ready */
7995 	rc = lpfc_sli4_post_status_check(phba);
7996 	if (rc)
7997 		return -ENODEV;
7998 
7999 	/* Allocate all driver workqueues here */
8000 
8001 	/* The lpfc_wq workqueue for deferred irq use */
8002 	phba->wq = alloc_workqueue("lpfc_wq", WQ_MEM_RECLAIM, 0);
8003 	if (!phba->wq)
8004 		return -ENOMEM;
8005 
8006 	/*
8007 	 * Initialize timers used by driver
8008 	 */
8009 
8010 	timer_setup(&phba->rrq_tmr, lpfc_rrq_timeout, 0);
8011 
8012 	/* FCF rediscover timer */
8013 	timer_setup(&phba->fcf.redisc_wait, lpfc_sli4_fcf_redisc_wait_tmo, 0);
8014 
8015 	/* CMF congestion timer */
8016 	hrtimer_init(&phba->cmf_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
8017 	phba->cmf_timer.function = lpfc_cmf_timer;
8018 
8019 	/*
8020 	 * Control structure for handling external multi-buffer mailbox
8021 	 * command pass-through.
8022 	 */
8023 	memset((uint8_t *)&phba->mbox_ext_buf_ctx, 0,
8024 		sizeof(struct lpfc_mbox_ext_buf_ctx));
8025 	INIT_LIST_HEAD(&phba->mbox_ext_buf_ctx.ext_dmabuf_list);
8026 
8027 	phba->max_vpi = LPFC_MAX_VPI;
8028 
8029 	/* This will be set to correct value after the read_config mbox */
8030 	phba->max_vports = 0;
8031 
8032 	/* Program the default value of vlan_id and fc_map */
8033 	phba->valid_vlan = 0;
8034 	phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
8035 	phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
8036 	phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
8037 
8038 	/*
8039 	 * For SLI4, instead of using ring 0 (LPFC_FCP_RING) for FCP commands
8040 	 * we will associate a new ring, for each EQ/CQ/WQ tuple.
8041 	 * The WQ create will allocate the ring.
8042 	 */
8043 
8044 	/* Initialize buffer queue management fields */
8045 	INIT_LIST_HEAD(&phba->hbqs[LPFC_ELS_HBQ].hbq_buffer_list);
8046 	phba->hbqs[LPFC_ELS_HBQ].hbq_alloc_buffer = lpfc_sli4_rb_alloc;
8047 	phba->hbqs[LPFC_ELS_HBQ].hbq_free_buffer = lpfc_sli4_rb_free;
8048 
8049 	/* for VMID idle timeout if VMID is enabled */
8050 	if (lpfc_is_vmid_enabled(phba))
8051 		timer_setup(&phba->inactive_vmid_poll, lpfc_vmid_poll, 0);
8052 
8053 	/*
8054 	 * Initialize the SLI Layer to run with lpfc SLI4 HBAs.
8055 	 */
8056 	/* Initialize the Abort buffer list used by driver */
8057 	spin_lock_init(&phba->sli4_hba.abts_io_buf_list_lock);
8058 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_io_buf_list);
8059 
8060 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
8061 		/* Initialize the Abort nvme buffer list used by driver */
8062 		spin_lock_init(&phba->sli4_hba.abts_nvmet_buf_list_lock);
8063 		INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
8064 		INIT_LIST_HEAD(&phba->sli4_hba.lpfc_nvmet_io_wait_list);
8065 		spin_lock_init(&phba->sli4_hba.t_active_list_lock);
8066 		INIT_LIST_HEAD(&phba->sli4_hba.t_active_ctx_list);
8067 	}
8068 
8069 	/* This abort list used by worker thread */
8070 	spin_lock_init(&phba->sli4_hba.sgl_list_lock);
8071 	spin_lock_init(&phba->sli4_hba.nvmet_io_wait_lock);
8072 	spin_lock_init(&phba->sli4_hba.asynce_list_lock);
8073 	spin_lock_init(&phba->sli4_hba.els_xri_abrt_list_lock);
8074 
8075 	/*
8076 	 * Initialize driver internal slow-path work queues
8077 	 */
8078 
8079 	/* Driver internel slow-path CQ Event pool */
8080 	INIT_LIST_HEAD(&phba->sli4_hba.sp_cqe_event_pool);
8081 	/* Response IOCB work queue list */
8082 	INIT_LIST_HEAD(&phba->sli4_hba.sp_queue_event);
8083 	/* Asynchronous event CQ Event work queue list */
8084 	INIT_LIST_HEAD(&phba->sli4_hba.sp_asynce_work_queue);
8085 	/* Slow-path XRI aborted CQ Event work queue list */
8086 	INIT_LIST_HEAD(&phba->sli4_hba.sp_els_xri_aborted_work_queue);
8087 	/* Receive queue CQ Event work queue list */
8088 	INIT_LIST_HEAD(&phba->sli4_hba.sp_unsol_work_queue);
8089 
8090 	/* Initialize extent block lists. */
8091 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_rpi_blk_list);
8092 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_xri_blk_list);
8093 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_vfi_blk_list);
8094 	INIT_LIST_HEAD(&phba->lpfc_vpi_blk_list);
8095 
8096 	/* Initialize mboxq lists. If the early init routines fail
8097 	 * these lists need to be correctly initialized.
8098 	 */
8099 	INIT_LIST_HEAD(&phba->sli.mboxq);
8100 	INIT_LIST_HEAD(&phba->sli.mboxq_cmpl);
8101 
8102 	/* initialize optic_state to 0xFF */
8103 	phba->sli4_hba.lnk_info.optic_state = 0xff;
8104 
8105 	/* Allocate device driver memory */
8106 	rc = lpfc_mem_alloc(phba, SGL_ALIGN_SZ);
8107 	if (rc)
8108 		goto out_destroy_workqueue;
8109 
8110 	/* IF Type 2 ports get initialized now. */
8111 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) >=
8112 	    LPFC_SLI_INTF_IF_TYPE_2) {
8113 		rc = lpfc_pci_function_reset(phba);
8114 		if (unlikely(rc)) {
8115 			rc = -ENODEV;
8116 			goto out_free_mem;
8117 		}
8118 		phba->temp_sensor_support = 1;
8119 	}
8120 
8121 	/* Create the bootstrap mailbox command */
8122 	rc = lpfc_create_bootstrap_mbox(phba);
8123 	if (unlikely(rc))
8124 		goto out_free_mem;
8125 
8126 	/* Set up the host's endian order with the device. */
8127 	rc = lpfc_setup_endian_order(phba);
8128 	if (unlikely(rc))
8129 		goto out_free_bsmbx;
8130 
8131 	/* Set up the hba's configuration parameters. */
8132 	rc = lpfc_sli4_read_config(phba);
8133 	if (unlikely(rc))
8134 		goto out_free_bsmbx;
8135 
8136 	if (phba->sli4_hba.fawwpn_flag & LPFC_FAWWPN_CONFIG) {
8137 		/* Right now the link is down, if FA-PWWN is configured the
8138 		 * firmware will try FLOGI before the driver gets a link up.
8139 		 * If it fails, the driver should get a MISCONFIGURED async
8140 		 * event which will clear this flag. The only notification
8141 		 * the driver gets is if it fails, if it succeeds there is no
8142 		 * notification given. Assume success.
8143 		 */
8144 		phba->sli4_hba.fawwpn_flag |= LPFC_FAWWPN_FABRIC;
8145 	}
8146 
8147 	rc = lpfc_mem_alloc_active_rrq_pool_s4(phba);
8148 	if (unlikely(rc))
8149 		goto out_free_bsmbx;
8150 
8151 	/* IF Type 0 ports get initialized now. */
8152 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
8153 	    LPFC_SLI_INTF_IF_TYPE_0) {
8154 		rc = lpfc_pci_function_reset(phba);
8155 		if (unlikely(rc))
8156 			goto out_free_bsmbx;
8157 	}
8158 
8159 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
8160 						       GFP_KERNEL);
8161 	if (!mboxq) {
8162 		rc = -ENOMEM;
8163 		goto out_free_bsmbx;
8164 	}
8165 
8166 	/* Check for NVMET being configured */
8167 	phba->nvmet_support = 0;
8168 	if (lpfc_enable_nvmet_cnt) {
8169 
8170 		/* First get WWN of HBA instance */
8171 		lpfc_read_nv(phba, mboxq);
8172 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8173 		if (rc != MBX_SUCCESS) {
8174 			lpfc_printf_log(phba, KERN_ERR,
8175 					LOG_TRACE_EVENT,
8176 					"6016 Mailbox failed , mbxCmd x%x "
8177 					"READ_NV, mbxStatus x%x\n",
8178 					bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8179 					bf_get(lpfc_mqe_status, &mboxq->u.mqe));
8180 			mempool_free(mboxq, phba->mbox_mem_pool);
8181 			rc = -EIO;
8182 			goto out_free_bsmbx;
8183 		}
8184 		mb = &mboxq->u.mb;
8185 		memcpy(&wwn, (char *)mb->un.varRDnvp.nodename,
8186 		       sizeof(uint64_t));
8187 		wwn = cpu_to_be64(wwn);
8188 		phba->sli4_hba.wwnn.u.name = wwn;
8189 		memcpy(&wwn, (char *)mb->un.varRDnvp.portname,
8190 		       sizeof(uint64_t));
8191 		/* wwn is WWPN of HBA instance */
8192 		wwn = cpu_to_be64(wwn);
8193 		phba->sli4_hba.wwpn.u.name = wwn;
8194 
8195 		/* Check to see if it matches any module parameter */
8196 		for (i = 0; i < lpfc_enable_nvmet_cnt; i++) {
8197 			if (wwn == lpfc_enable_nvmet[i]) {
8198 #if (IS_ENABLED(CONFIG_NVME_TARGET_FC))
8199 				if (lpfc_nvmet_mem_alloc(phba))
8200 					break;
8201 
8202 				phba->nvmet_support = 1; /* a match */
8203 
8204 				lpfc_printf_log(phba, KERN_ERR,
8205 						LOG_TRACE_EVENT,
8206 						"6017 NVME Target %016llx\n",
8207 						wwn);
8208 #else
8209 				lpfc_printf_log(phba, KERN_ERR,
8210 						LOG_TRACE_EVENT,
8211 						"6021 Can't enable NVME Target."
8212 						" NVME_TARGET_FC infrastructure"
8213 						" is not in kernel\n");
8214 #endif
8215 				/* Not supported for NVMET */
8216 				phba->cfg_xri_rebalancing = 0;
8217 				if (phba->irq_chann_mode == NHT_MODE) {
8218 					phba->cfg_irq_chann =
8219 						phba->sli4_hba.num_present_cpu;
8220 					phba->cfg_hdw_queue =
8221 						phba->sli4_hba.num_present_cpu;
8222 					phba->irq_chann_mode = NORMAL_MODE;
8223 				}
8224 				break;
8225 			}
8226 		}
8227 	}
8228 
8229 	lpfc_nvme_mod_param_dep(phba);
8230 
8231 	/*
8232 	 * Get sli4 parameters that override parameters from Port capabilities.
8233 	 * If this call fails, it isn't critical unless the SLI4 parameters come
8234 	 * back in conflict.
8235 	 */
8236 	rc = lpfc_get_sli4_parameters(phba, mboxq);
8237 	if (rc) {
8238 		if_type = bf_get(lpfc_sli_intf_if_type,
8239 				 &phba->sli4_hba.sli_intf);
8240 		if_fam = bf_get(lpfc_sli_intf_sli_family,
8241 				&phba->sli4_hba.sli_intf);
8242 		if (phba->sli4_hba.extents_in_use &&
8243 		    phba->sli4_hba.rpi_hdrs_in_use) {
8244 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8245 					"2999 Unsupported SLI4 Parameters "
8246 					"Extents and RPI headers enabled.\n");
8247 			if (if_type == LPFC_SLI_INTF_IF_TYPE_0 &&
8248 			    if_fam ==  LPFC_SLI_INTF_FAMILY_BE2) {
8249 				mempool_free(mboxq, phba->mbox_mem_pool);
8250 				rc = -EIO;
8251 				goto out_free_bsmbx;
8252 			}
8253 		}
8254 		if (!(if_type == LPFC_SLI_INTF_IF_TYPE_0 &&
8255 		      if_fam == LPFC_SLI_INTF_FAMILY_BE2)) {
8256 			mempool_free(mboxq, phba->mbox_mem_pool);
8257 			rc = -EIO;
8258 			goto out_free_bsmbx;
8259 		}
8260 	}
8261 
8262 	/*
8263 	 * 1 for cmd, 1 for rsp, NVME adds an extra one
8264 	 * for boundary conditions in its max_sgl_segment template.
8265 	 */
8266 	extra = 2;
8267 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
8268 		extra++;
8269 
8270 	/*
8271 	 * It doesn't matter what family our adapter is in, we are
8272 	 * limited to 2 Pages, 512 SGEs, for our SGL.
8273 	 * There are going to be 2 reserved SGEs: 1 FCP cmnd + 1 FCP rsp
8274 	 */
8275 	max_buf_size = (2 * SLI4_PAGE_SIZE);
8276 
8277 	/*
8278 	 * Since lpfc_sg_seg_cnt is module param, the sg_dma_buf_size
8279 	 * used to create the sg_dma_buf_pool must be calculated.
8280 	 */
8281 	if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
8282 		/* Both cfg_enable_bg and cfg_external_dif code paths */
8283 
8284 		/*
8285 		 * The scsi_buf for a T10-DIF I/O holds the FCP cmnd,
8286 		 * the FCP rsp, and a SGE. Sice we have no control
8287 		 * over how many protection segments the SCSI Layer
8288 		 * will hand us (ie: there could be one for every block
8289 		 * in the IO), just allocate enough SGEs to accomidate
8290 		 * our max amount and we need to limit lpfc_sg_seg_cnt
8291 		 * to minimize the risk of running out.
8292 		 */
8293 		phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd) +
8294 				sizeof(struct fcp_rsp) + max_buf_size;
8295 
8296 		/* Total SGEs for scsi_sg_list and scsi_sg_prot_list */
8297 		phba->cfg_total_seg_cnt = LPFC_MAX_SGL_SEG_CNT;
8298 
8299 		/*
8300 		 * If supporting DIF, reduce the seg count for scsi to
8301 		 * allow room for the DIF sges.
8302 		 */
8303 		if (phba->cfg_enable_bg &&
8304 		    phba->cfg_sg_seg_cnt > LPFC_MAX_BG_SLI4_SEG_CNT_DIF)
8305 			phba->cfg_scsi_seg_cnt = LPFC_MAX_BG_SLI4_SEG_CNT_DIF;
8306 		else
8307 			phba->cfg_scsi_seg_cnt = phba->cfg_sg_seg_cnt;
8308 
8309 	} else {
8310 		/*
8311 		 * The scsi_buf for a regular I/O holds the FCP cmnd,
8312 		 * the FCP rsp, a SGE for each, and a SGE for up to
8313 		 * cfg_sg_seg_cnt data segments.
8314 		 */
8315 		phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd) +
8316 				sizeof(struct fcp_rsp) +
8317 				((phba->cfg_sg_seg_cnt + extra) *
8318 				sizeof(struct sli4_sge));
8319 
8320 		/* Total SGEs for scsi_sg_list */
8321 		phba->cfg_total_seg_cnt = phba->cfg_sg_seg_cnt + extra;
8322 		phba->cfg_scsi_seg_cnt = phba->cfg_sg_seg_cnt;
8323 
8324 		/*
8325 		 * NOTE: if (phba->cfg_sg_seg_cnt + extra) <= 256 we only
8326 		 * need to post 1 page for the SGL.
8327 		 */
8328 	}
8329 
8330 	if (phba->cfg_xpsgl && !phba->nvmet_support)
8331 		phba->cfg_sg_dma_buf_size = LPFC_DEFAULT_XPSGL_SIZE;
8332 	else if (phba->cfg_sg_dma_buf_size  <= LPFC_MIN_SG_SLI4_BUF_SZ)
8333 		phba->cfg_sg_dma_buf_size = LPFC_MIN_SG_SLI4_BUF_SZ;
8334 	else
8335 		phba->cfg_sg_dma_buf_size =
8336 				SLI4_PAGE_ALIGN(phba->cfg_sg_dma_buf_size);
8337 
8338 	phba->border_sge_num = phba->cfg_sg_dma_buf_size /
8339 			       sizeof(struct sli4_sge);
8340 
8341 	/* Limit to LPFC_MAX_NVME_SEG_CNT for NVME. */
8342 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
8343 		if (phba->cfg_sg_seg_cnt > LPFC_MAX_NVME_SEG_CNT) {
8344 			lpfc_printf_log(phba, KERN_INFO, LOG_NVME | LOG_INIT,
8345 					"6300 Reducing NVME sg segment "
8346 					"cnt to %d\n",
8347 					LPFC_MAX_NVME_SEG_CNT);
8348 			phba->cfg_nvme_seg_cnt = LPFC_MAX_NVME_SEG_CNT;
8349 		} else
8350 			phba->cfg_nvme_seg_cnt = phba->cfg_sg_seg_cnt;
8351 	}
8352 
8353 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP,
8354 			"9087 sg_seg_cnt:%d dmabuf_size:%d "
8355 			"total:%d scsi:%d nvme:%d\n",
8356 			phba->cfg_sg_seg_cnt, phba->cfg_sg_dma_buf_size,
8357 			phba->cfg_total_seg_cnt,  phba->cfg_scsi_seg_cnt,
8358 			phba->cfg_nvme_seg_cnt);
8359 
8360 	if (phba->cfg_sg_dma_buf_size < SLI4_PAGE_SIZE)
8361 		i = phba->cfg_sg_dma_buf_size;
8362 	else
8363 		i = SLI4_PAGE_SIZE;
8364 
8365 	phba->lpfc_sg_dma_buf_pool =
8366 			dma_pool_create("lpfc_sg_dma_buf_pool",
8367 					&phba->pcidev->dev,
8368 					phba->cfg_sg_dma_buf_size,
8369 					i, 0);
8370 	if (!phba->lpfc_sg_dma_buf_pool) {
8371 		rc = -ENOMEM;
8372 		goto out_free_bsmbx;
8373 	}
8374 
8375 	phba->lpfc_cmd_rsp_buf_pool =
8376 			dma_pool_create("lpfc_cmd_rsp_buf_pool",
8377 					&phba->pcidev->dev,
8378 					sizeof(struct fcp_cmnd) +
8379 					sizeof(struct fcp_rsp),
8380 					i, 0);
8381 	if (!phba->lpfc_cmd_rsp_buf_pool) {
8382 		rc = -ENOMEM;
8383 		goto out_free_sg_dma_buf;
8384 	}
8385 
8386 	mempool_free(mboxq, phba->mbox_mem_pool);
8387 
8388 	/* Verify OAS is supported */
8389 	lpfc_sli4_oas_verify(phba);
8390 
8391 	/* Verify RAS support on adapter */
8392 	lpfc_sli4_ras_init(phba);
8393 
8394 	/* Verify all the SLI4 queues */
8395 	rc = lpfc_sli4_queue_verify(phba);
8396 	if (rc)
8397 		goto out_free_cmd_rsp_buf;
8398 
8399 	/* Create driver internal CQE event pool */
8400 	rc = lpfc_sli4_cq_event_pool_create(phba);
8401 	if (rc)
8402 		goto out_free_cmd_rsp_buf;
8403 
8404 	/* Initialize sgl lists per host */
8405 	lpfc_init_sgl_list(phba);
8406 
8407 	/* Allocate and initialize active sgl array */
8408 	rc = lpfc_init_active_sgl_array(phba);
8409 	if (rc) {
8410 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8411 				"1430 Failed to initialize sgl list.\n");
8412 		goto out_destroy_cq_event_pool;
8413 	}
8414 	rc = lpfc_sli4_init_rpi_hdrs(phba);
8415 	if (rc) {
8416 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8417 				"1432 Failed to initialize rpi headers.\n");
8418 		goto out_free_active_sgl;
8419 	}
8420 
8421 	/* Allocate eligible FCF bmask memory for FCF roundrobin failover */
8422 	longs = (LPFC_SLI4_FCF_TBL_INDX_MAX + BITS_PER_LONG - 1)/BITS_PER_LONG;
8423 	phba->fcf.fcf_rr_bmask = kcalloc(longs, sizeof(unsigned long),
8424 					 GFP_KERNEL);
8425 	if (!phba->fcf.fcf_rr_bmask) {
8426 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8427 				"2759 Failed allocate memory for FCF round "
8428 				"robin failover bmask\n");
8429 		rc = -ENOMEM;
8430 		goto out_remove_rpi_hdrs;
8431 	}
8432 
8433 	phba->sli4_hba.hba_eq_hdl = kcalloc(phba->cfg_irq_chann,
8434 					    sizeof(struct lpfc_hba_eq_hdl),
8435 					    GFP_KERNEL);
8436 	if (!phba->sli4_hba.hba_eq_hdl) {
8437 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8438 				"2572 Failed allocate memory for "
8439 				"fast-path per-EQ handle array\n");
8440 		rc = -ENOMEM;
8441 		goto out_free_fcf_rr_bmask;
8442 	}
8443 
8444 	phba->sli4_hba.cpu_map = kcalloc(phba->sli4_hba.num_possible_cpu,
8445 					sizeof(struct lpfc_vector_map_info),
8446 					GFP_KERNEL);
8447 	if (!phba->sli4_hba.cpu_map) {
8448 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8449 				"3327 Failed allocate memory for msi-x "
8450 				"interrupt vector mapping\n");
8451 		rc = -ENOMEM;
8452 		goto out_free_hba_eq_hdl;
8453 	}
8454 
8455 	phba->sli4_hba.eq_info = alloc_percpu(struct lpfc_eq_intr_info);
8456 	if (!phba->sli4_hba.eq_info) {
8457 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8458 				"3321 Failed allocation for per_cpu stats\n");
8459 		rc = -ENOMEM;
8460 		goto out_free_hba_cpu_map;
8461 	}
8462 
8463 	phba->sli4_hba.idle_stat = kcalloc(phba->sli4_hba.num_possible_cpu,
8464 					   sizeof(*phba->sli4_hba.idle_stat),
8465 					   GFP_KERNEL);
8466 	if (!phba->sli4_hba.idle_stat) {
8467 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8468 				"3390 Failed allocation for idle_stat\n");
8469 		rc = -ENOMEM;
8470 		goto out_free_hba_eq_info;
8471 	}
8472 
8473 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
8474 	phba->sli4_hba.c_stat = alloc_percpu(struct lpfc_hdwq_stat);
8475 	if (!phba->sli4_hba.c_stat) {
8476 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8477 				"3332 Failed allocating per cpu hdwq stats\n");
8478 		rc = -ENOMEM;
8479 		goto out_free_hba_idle_stat;
8480 	}
8481 #endif
8482 
8483 	phba->cmf_stat = alloc_percpu(struct lpfc_cgn_stat);
8484 	if (!phba->cmf_stat) {
8485 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8486 				"3331 Failed allocating per cpu cgn stats\n");
8487 		rc = -ENOMEM;
8488 		goto out_free_hba_hdwq_info;
8489 	}
8490 
8491 	/*
8492 	 * Enable sr-iov virtual functions if supported and configured
8493 	 * through the module parameter.
8494 	 */
8495 	if (phba->cfg_sriov_nr_virtfn > 0) {
8496 		rc = lpfc_sli_probe_sriov_nr_virtfn(phba,
8497 						 phba->cfg_sriov_nr_virtfn);
8498 		if (rc) {
8499 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
8500 					"3020 Requested number of SR-IOV "
8501 					"virtual functions (%d) is not "
8502 					"supported\n",
8503 					phba->cfg_sriov_nr_virtfn);
8504 			phba->cfg_sriov_nr_virtfn = 0;
8505 		}
8506 	}
8507 
8508 	return 0;
8509 
8510 out_free_hba_hdwq_info:
8511 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
8512 	free_percpu(phba->sli4_hba.c_stat);
8513 out_free_hba_idle_stat:
8514 #endif
8515 	kfree(phba->sli4_hba.idle_stat);
8516 out_free_hba_eq_info:
8517 	free_percpu(phba->sli4_hba.eq_info);
8518 out_free_hba_cpu_map:
8519 	kfree(phba->sli4_hba.cpu_map);
8520 out_free_hba_eq_hdl:
8521 	kfree(phba->sli4_hba.hba_eq_hdl);
8522 out_free_fcf_rr_bmask:
8523 	kfree(phba->fcf.fcf_rr_bmask);
8524 out_remove_rpi_hdrs:
8525 	lpfc_sli4_remove_rpi_hdrs(phba);
8526 out_free_active_sgl:
8527 	lpfc_free_active_sgl(phba);
8528 out_destroy_cq_event_pool:
8529 	lpfc_sli4_cq_event_pool_destroy(phba);
8530 out_free_cmd_rsp_buf:
8531 	dma_pool_destroy(phba->lpfc_cmd_rsp_buf_pool);
8532 	phba->lpfc_cmd_rsp_buf_pool = NULL;
8533 out_free_sg_dma_buf:
8534 	dma_pool_destroy(phba->lpfc_sg_dma_buf_pool);
8535 	phba->lpfc_sg_dma_buf_pool = NULL;
8536 out_free_bsmbx:
8537 	lpfc_destroy_bootstrap_mbox(phba);
8538 out_free_mem:
8539 	lpfc_mem_free(phba);
8540 out_destroy_workqueue:
8541 	destroy_workqueue(phba->wq);
8542 	phba->wq = NULL;
8543 	return rc;
8544 }
8545 
8546 /**
8547  * lpfc_sli4_driver_resource_unset - Unset drvr internal resources for SLI4 dev
8548  * @phba: pointer to lpfc hba data structure.
8549  *
8550  * This routine is invoked to unset the driver internal resources set up
8551  * specific for supporting the SLI-4 HBA device it attached to.
8552  **/
8553 static void
8554 lpfc_sli4_driver_resource_unset(struct lpfc_hba *phba)
8555 {
8556 	struct lpfc_fcf_conn_entry *conn_entry, *next_conn_entry;
8557 
8558 	free_percpu(phba->sli4_hba.eq_info);
8559 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
8560 	free_percpu(phba->sli4_hba.c_stat);
8561 #endif
8562 	free_percpu(phba->cmf_stat);
8563 	kfree(phba->sli4_hba.idle_stat);
8564 
8565 	/* Free memory allocated for msi-x interrupt vector to CPU mapping */
8566 	kfree(phba->sli4_hba.cpu_map);
8567 	phba->sli4_hba.num_possible_cpu = 0;
8568 	phba->sli4_hba.num_present_cpu = 0;
8569 	phba->sli4_hba.curr_disp_cpu = 0;
8570 	cpumask_clear(&phba->sli4_hba.irq_aff_mask);
8571 
8572 	/* Free memory allocated for fast-path work queue handles */
8573 	kfree(phba->sli4_hba.hba_eq_hdl);
8574 
8575 	/* Free the allocated rpi headers. */
8576 	lpfc_sli4_remove_rpi_hdrs(phba);
8577 	lpfc_sli4_remove_rpis(phba);
8578 
8579 	/* Free eligible FCF index bmask */
8580 	kfree(phba->fcf.fcf_rr_bmask);
8581 
8582 	/* Free the ELS sgl list */
8583 	lpfc_free_active_sgl(phba);
8584 	lpfc_free_els_sgl_list(phba);
8585 	lpfc_free_nvmet_sgl_list(phba);
8586 
8587 	/* Free the completion queue EQ event pool */
8588 	lpfc_sli4_cq_event_release_all(phba);
8589 	lpfc_sli4_cq_event_pool_destroy(phba);
8590 
8591 	/* Release resource identifiers. */
8592 	lpfc_sli4_dealloc_resource_identifiers(phba);
8593 
8594 	/* Free the bsmbx region. */
8595 	lpfc_destroy_bootstrap_mbox(phba);
8596 
8597 	/* Free the SLI Layer memory with SLI4 HBAs */
8598 	lpfc_mem_free_all(phba);
8599 
8600 	/* Free the current connect table */
8601 	list_for_each_entry_safe(conn_entry, next_conn_entry,
8602 		&phba->fcf_conn_rec_list, list) {
8603 		list_del_init(&conn_entry->list);
8604 		kfree(conn_entry);
8605 	}
8606 
8607 	return;
8608 }
8609 
8610 /**
8611  * lpfc_init_api_table_setup - Set up init api function jump table
8612  * @phba: The hba struct for which this call is being executed.
8613  * @dev_grp: The HBA PCI-Device group number.
8614  *
8615  * This routine sets up the device INIT interface API function jump table
8616  * in @phba struct.
8617  *
8618  * Returns: 0 - success, -ENODEV - failure.
8619  **/
8620 int
8621 lpfc_init_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
8622 {
8623 	phba->lpfc_hba_init_link = lpfc_hba_init_link;
8624 	phba->lpfc_hba_down_link = lpfc_hba_down_link;
8625 	phba->lpfc_selective_reset = lpfc_selective_reset;
8626 	switch (dev_grp) {
8627 	case LPFC_PCI_DEV_LP:
8628 		phba->lpfc_hba_down_post = lpfc_hba_down_post_s3;
8629 		phba->lpfc_handle_eratt = lpfc_handle_eratt_s3;
8630 		phba->lpfc_stop_port = lpfc_stop_port_s3;
8631 		break;
8632 	case LPFC_PCI_DEV_OC:
8633 		phba->lpfc_hba_down_post = lpfc_hba_down_post_s4;
8634 		phba->lpfc_handle_eratt = lpfc_handle_eratt_s4;
8635 		phba->lpfc_stop_port = lpfc_stop_port_s4;
8636 		break;
8637 	default:
8638 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8639 				"1431 Invalid HBA PCI-device group: 0x%x\n",
8640 				dev_grp);
8641 		return -ENODEV;
8642 	}
8643 	return 0;
8644 }
8645 
8646 /**
8647  * lpfc_setup_driver_resource_phase2 - Phase2 setup driver internal resources.
8648  * @phba: pointer to lpfc hba data structure.
8649  *
8650  * This routine is invoked to set up the driver internal resources after the
8651  * device specific resource setup to support the HBA device it attached to.
8652  *
8653  * Return codes
8654  * 	0 - successful
8655  * 	other values - error
8656  **/
8657 static int
8658 lpfc_setup_driver_resource_phase2(struct lpfc_hba *phba)
8659 {
8660 	int error;
8661 
8662 	/* Startup the kernel thread for this host adapter. */
8663 	phba->worker_thread = kthread_run(lpfc_do_work, phba,
8664 					  "lpfc_worker_%d", phba->brd_no);
8665 	if (IS_ERR(phba->worker_thread)) {
8666 		error = PTR_ERR(phba->worker_thread);
8667 		return error;
8668 	}
8669 
8670 	return 0;
8671 }
8672 
8673 /**
8674  * lpfc_unset_driver_resource_phase2 - Phase2 unset driver internal resources.
8675  * @phba: pointer to lpfc hba data structure.
8676  *
8677  * This routine is invoked to unset the driver internal resources set up after
8678  * the device specific resource setup for supporting the HBA device it
8679  * attached to.
8680  **/
8681 static void
8682 lpfc_unset_driver_resource_phase2(struct lpfc_hba *phba)
8683 {
8684 	if (phba->wq) {
8685 		destroy_workqueue(phba->wq);
8686 		phba->wq = NULL;
8687 	}
8688 
8689 	/* Stop kernel worker thread */
8690 	if (phba->worker_thread)
8691 		kthread_stop(phba->worker_thread);
8692 }
8693 
8694 /**
8695  * lpfc_free_iocb_list - Free iocb list.
8696  * @phba: pointer to lpfc hba data structure.
8697  *
8698  * This routine is invoked to free the driver's IOCB list and memory.
8699  **/
8700 void
8701 lpfc_free_iocb_list(struct lpfc_hba *phba)
8702 {
8703 	struct lpfc_iocbq *iocbq_entry = NULL, *iocbq_next = NULL;
8704 
8705 	spin_lock_irq(&phba->hbalock);
8706 	list_for_each_entry_safe(iocbq_entry, iocbq_next,
8707 				 &phba->lpfc_iocb_list, list) {
8708 		list_del(&iocbq_entry->list);
8709 		kfree(iocbq_entry);
8710 		phba->total_iocbq_bufs--;
8711 	}
8712 	spin_unlock_irq(&phba->hbalock);
8713 
8714 	return;
8715 }
8716 
8717 /**
8718  * lpfc_init_iocb_list - Allocate and initialize iocb list.
8719  * @phba: pointer to lpfc hba data structure.
8720  * @iocb_count: number of requested iocbs
8721  *
8722  * This routine is invoked to allocate and initizlize the driver's IOCB
8723  * list and set up the IOCB tag array accordingly.
8724  *
8725  * Return codes
8726  *	0 - successful
8727  *	other values - error
8728  **/
8729 int
8730 lpfc_init_iocb_list(struct lpfc_hba *phba, int iocb_count)
8731 {
8732 	struct lpfc_iocbq *iocbq_entry = NULL;
8733 	uint16_t iotag;
8734 	int i;
8735 
8736 	/* Initialize and populate the iocb list per host.  */
8737 	INIT_LIST_HEAD(&phba->lpfc_iocb_list);
8738 	for (i = 0; i < iocb_count; i++) {
8739 		iocbq_entry = kzalloc(sizeof(struct lpfc_iocbq), GFP_KERNEL);
8740 		if (iocbq_entry == NULL) {
8741 			printk(KERN_ERR "%s: only allocated %d iocbs of "
8742 				"expected %d count. Unloading driver.\n",
8743 				__func__, i, iocb_count);
8744 			goto out_free_iocbq;
8745 		}
8746 
8747 		iotag = lpfc_sli_next_iotag(phba, iocbq_entry);
8748 		if (iotag == 0) {
8749 			kfree(iocbq_entry);
8750 			printk(KERN_ERR "%s: failed to allocate IOTAG. "
8751 				"Unloading driver.\n", __func__);
8752 			goto out_free_iocbq;
8753 		}
8754 		iocbq_entry->sli4_lxritag = NO_XRI;
8755 		iocbq_entry->sli4_xritag = NO_XRI;
8756 
8757 		spin_lock_irq(&phba->hbalock);
8758 		list_add(&iocbq_entry->list, &phba->lpfc_iocb_list);
8759 		phba->total_iocbq_bufs++;
8760 		spin_unlock_irq(&phba->hbalock);
8761 	}
8762 
8763 	return 0;
8764 
8765 out_free_iocbq:
8766 	lpfc_free_iocb_list(phba);
8767 
8768 	return -ENOMEM;
8769 }
8770 
8771 /**
8772  * lpfc_free_sgl_list - Free a given sgl list.
8773  * @phba: pointer to lpfc hba data structure.
8774  * @sglq_list: pointer to the head of sgl list.
8775  *
8776  * This routine is invoked to free a give sgl list and memory.
8777  **/
8778 void
8779 lpfc_free_sgl_list(struct lpfc_hba *phba, struct list_head *sglq_list)
8780 {
8781 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
8782 
8783 	list_for_each_entry_safe(sglq_entry, sglq_next, sglq_list, list) {
8784 		list_del(&sglq_entry->list);
8785 		lpfc_mbuf_free(phba, sglq_entry->virt, sglq_entry->phys);
8786 		kfree(sglq_entry);
8787 	}
8788 }
8789 
8790 /**
8791  * lpfc_free_els_sgl_list - Free els sgl list.
8792  * @phba: pointer to lpfc hba data structure.
8793  *
8794  * This routine is invoked to free the driver's els sgl list and memory.
8795  **/
8796 static void
8797 lpfc_free_els_sgl_list(struct lpfc_hba *phba)
8798 {
8799 	LIST_HEAD(sglq_list);
8800 
8801 	/* Retrieve all els sgls from driver list */
8802 	spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
8803 	list_splice_init(&phba->sli4_hba.lpfc_els_sgl_list, &sglq_list);
8804 	spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
8805 
8806 	/* Now free the sgl list */
8807 	lpfc_free_sgl_list(phba, &sglq_list);
8808 }
8809 
8810 /**
8811  * lpfc_free_nvmet_sgl_list - Free nvmet sgl list.
8812  * @phba: pointer to lpfc hba data structure.
8813  *
8814  * This routine is invoked to free the driver's nvmet sgl list and memory.
8815  **/
8816 static void
8817 lpfc_free_nvmet_sgl_list(struct lpfc_hba *phba)
8818 {
8819 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
8820 	LIST_HEAD(sglq_list);
8821 
8822 	/* Retrieve all nvmet sgls from driver list */
8823 	spin_lock_irq(&phba->hbalock);
8824 	spin_lock(&phba->sli4_hba.sgl_list_lock);
8825 	list_splice_init(&phba->sli4_hba.lpfc_nvmet_sgl_list, &sglq_list);
8826 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
8827 	spin_unlock_irq(&phba->hbalock);
8828 
8829 	/* Now free the sgl list */
8830 	list_for_each_entry_safe(sglq_entry, sglq_next, &sglq_list, list) {
8831 		list_del(&sglq_entry->list);
8832 		lpfc_nvmet_buf_free(phba, sglq_entry->virt, sglq_entry->phys);
8833 		kfree(sglq_entry);
8834 	}
8835 
8836 	/* Update the nvmet_xri_cnt to reflect no current sgls.
8837 	 * The next initialization cycle sets the count and allocates
8838 	 * the sgls over again.
8839 	 */
8840 	phba->sli4_hba.nvmet_xri_cnt = 0;
8841 }
8842 
8843 /**
8844  * lpfc_init_active_sgl_array - Allocate the buf to track active ELS XRIs.
8845  * @phba: pointer to lpfc hba data structure.
8846  *
8847  * This routine is invoked to allocate the driver's active sgl memory.
8848  * This array will hold the sglq_entry's for active IOs.
8849  **/
8850 static int
8851 lpfc_init_active_sgl_array(struct lpfc_hba *phba)
8852 {
8853 	int size;
8854 	size = sizeof(struct lpfc_sglq *);
8855 	size *= phba->sli4_hba.max_cfg_param.max_xri;
8856 
8857 	phba->sli4_hba.lpfc_sglq_active_list =
8858 		kzalloc(size, GFP_KERNEL);
8859 	if (!phba->sli4_hba.lpfc_sglq_active_list)
8860 		return -ENOMEM;
8861 	return 0;
8862 }
8863 
8864 /**
8865  * lpfc_free_active_sgl - Free the buf that tracks active ELS XRIs.
8866  * @phba: pointer to lpfc hba data structure.
8867  *
8868  * This routine is invoked to walk through the array of active sglq entries
8869  * and free all of the resources.
8870  * This is just a place holder for now.
8871  **/
8872 static void
8873 lpfc_free_active_sgl(struct lpfc_hba *phba)
8874 {
8875 	kfree(phba->sli4_hba.lpfc_sglq_active_list);
8876 }
8877 
8878 /**
8879  * lpfc_init_sgl_list - Allocate and initialize sgl list.
8880  * @phba: pointer to lpfc hba data structure.
8881  *
8882  * This routine is invoked to allocate and initizlize the driver's sgl
8883  * list and set up the sgl xritag tag array accordingly.
8884  *
8885  **/
8886 static void
8887 lpfc_init_sgl_list(struct lpfc_hba *phba)
8888 {
8889 	/* Initialize and populate the sglq list per host/VF. */
8890 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_els_sgl_list);
8891 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_els_sgl_list);
8892 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_nvmet_sgl_list);
8893 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
8894 
8895 	/* els xri-sgl book keeping */
8896 	phba->sli4_hba.els_xri_cnt = 0;
8897 
8898 	/* nvme xri-buffer book keeping */
8899 	phba->sli4_hba.io_xri_cnt = 0;
8900 }
8901 
8902 /**
8903  * lpfc_sli4_init_rpi_hdrs - Post the rpi header memory region to the port
8904  * @phba: pointer to lpfc hba data structure.
8905  *
8906  * This routine is invoked to post rpi header templates to the
8907  * port for those SLI4 ports that do not support extents.  This routine
8908  * posts a PAGE_SIZE memory region to the port to hold up to
8909  * PAGE_SIZE modulo 64 rpi context headers.  This is an initialization routine
8910  * and should be called only when interrupts are disabled.
8911  *
8912  * Return codes
8913  * 	0 - successful
8914  *	-ERROR - otherwise.
8915  **/
8916 int
8917 lpfc_sli4_init_rpi_hdrs(struct lpfc_hba *phba)
8918 {
8919 	int rc = 0;
8920 	struct lpfc_rpi_hdr *rpi_hdr;
8921 
8922 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_rpi_hdr_list);
8923 	if (!phba->sli4_hba.rpi_hdrs_in_use)
8924 		return rc;
8925 	if (phba->sli4_hba.extents_in_use)
8926 		return -EIO;
8927 
8928 	rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
8929 	if (!rpi_hdr) {
8930 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8931 				"0391 Error during rpi post operation\n");
8932 		lpfc_sli4_remove_rpis(phba);
8933 		rc = -ENODEV;
8934 	}
8935 
8936 	return rc;
8937 }
8938 
8939 /**
8940  * lpfc_sli4_create_rpi_hdr - Allocate an rpi header memory region
8941  * @phba: pointer to lpfc hba data structure.
8942  *
8943  * This routine is invoked to allocate a single 4KB memory region to
8944  * support rpis and stores them in the phba.  This single region
8945  * provides support for up to 64 rpis.  The region is used globally
8946  * by the device.
8947  *
8948  * Returns:
8949  *   A valid rpi hdr on success.
8950  *   A NULL pointer on any failure.
8951  **/
8952 struct lpfc_rpi_hdr *
8953 lpfc_sli4_create_rpi_hdr(struct lpfc_hba *phba)
8954 {
8955 	uint16_t rpi_limit, curr_rpi_range;
8956 	struct lpfc_dmabuf *dmabuf;
8957 	struct lpfc_rpi_hdr *rpi_hdr;
8958 
8959 	/*
8960 	 * If the SLI4 port supports extents, posting the rpi header isn't
8961 	 * required.  Set the expected maximum count and let the actual value
8962 	 * get set when extents are fully allocated.
8963 	 */
8964 	if (!phba->sli4_hba.rpi_hdrs_in_use)
8965 		return NULL;
8966 	if (phba->sli4_hba.extents_in_use)
8967 		return NULL;
8968 
8969 	/* The limit on the logical index is just the max_rpi count. */
8970 	rpi_limit = phba->sli4_hba.max_cfg_param.max_rpi;
8971 
8972 	spin_lock_irq(&phba->hbalock);
8973 	/*
8974 	 * Establish the starting RPI in this header block.  The starting
8975 	 * rpi is normalized to a zero base because the physical rpi is
8976 	 * port based.
8977 	 */
8978 	curr_rpi_range = phba->sli4_hba.next_rpi;
8979 	spin_unlock_irq(&phba->hbalock);
8980 
8981 	/* Reached full RPI range */
8982 	if (curr_rpi_range == rpi_limit)
8983 		return NULL;
8984 
8985 	/*
8986 	 * First allocate the protocol header region for the port.  The
8987 	 * port expects a 4KB DMA-mapped memory region that is 4K aligned.
8988 	 */
8989 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
8990 	if (!dmabuf)
8991 		return NULL;
8992 
8993 	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
8994 					  LPFC_HDR_TEMPLATE_SIZE,
8995 					  &dmabuf->phys, GFP_KERNEL);
8996 	if (!dmabuf->virt) {
8997 		rpi_hdr = NULL;
8998 		goto err_free_dmabuf;
8999 	}
9000 
9001 	if (!IS_ALIGNED(dmabuf->phys, LPFC_HDR_TEMPLATE_SIZE)) {
9002 		rpi_hdr = NULL;
9003 		goto err_free_coherent;
9004 	}
9005 
9006 	/* Save the rpi header data for cleanup later. */
9007 	rpi_hdr = kzalloc(sizeof(struct lpfc_rpi_hdr), GFP_KERNEL);
9008 	if (!rpi_hdr)
9009 		goto err_free_coherent;
9010 
9011 	rpi_hdr->dmabuf = dmabuf;
9012 	rpi_hdr->len = LPFC_HDR_TEMPLATE_SIZE;
9013 	rpi_hdr->page_count = 1;
9014 	spin_lock_irq(&phba->hbalock);
9015 
9016 	/* The rpi_hdr stores the logical index only. */
9017 	rpi_hdr->start_rpi = curr_rpi_range;
9018 	rpi_hdr->next_rpi = phba->sli4_hba.next_rpi + LPFC_RPI_HDR_COUNT;
9019 	list_add_tail(&rpi_hdr->list, &phba->sli4_hba.lpfc_rpi_hdr_list);
9020 
9021 	spin_unlock_irq(&phba->hbalock);
9022 	return rpi_hdr;
9023 
9024  err_free_coherent:
9025 	dma_free_coherent(&phba->pcidev->dev, LPFC_HDR_TEMPLATE_SIZE,
9026 			  dmabuf->virt, dmabuf->phys);
9027  err_free_dmabuf:
9028 	kfree(dmabuf);
9029 	return NULL;
9030 }
9031 
9032 /**
9033  * lpfc_sli4_remove_rpi_hdrs - Remove all rpi header memory regions
9034  * @phba: pointer to lpfc hba data structure.
9035  *
9036  * This routine is invoked to remove all memory resources allocated
9037  * to support rpis for SLI4 ports not supporting extents. This routine
9038  * presumes the caller has released all rpis consumed by fabric or port
9039  * logins and is prepared to have the header pages removed.
9040  **/
9041 void
9042 lpfc_sli4_remove_rpi_hdrs(struct lpfc_hba *phba)
9043 {
9044 	struct lpfc_rpi_hdr *rpi_hdr, *next_rpi_hdr;
9045 
9046 	if (!phba->sli4_hba.rpi_hdrs_in_use)
9047 		goto exit;
9048 
9049 	list_for_each_entry_safe(rpi_hdr, next_rpi_hdr,
9050 				 &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
9051 		list_del(&rpi_hdr->list);
9052 		dma_free_coherent(&phba->pcidev->dev, rpi_hdr->len,
9053 				  rpi_hdr->dmabuf->virt, rpi_hdr->dmabuf->phys);
9054 		kfree(rpi_hdr->dmabuf);
9055 		kfree(rpi_hdr);
9056 	}
9057  exit:
9058 	/* There are no rpis available to the port now. */
9059 	phba->sli4_hba.next_rpi = 0;
9060 }
9061 
9062 /**
9063  * lpfc_hba_alloc - Allocate driver hba data structure for a device.
9064  * @pdev: pointer to pci device data structure.
9065  *
9066  * This routine is invoked to allocate the driver hba data structure for an
9067  * HBA device. If the allocation is successful, the phba reference to the
9068  * PCI device data structure is set.
9069  *
9070  * Return codes
9071  *      pointer to @phba - successful
9072  *      NULL - error
9073  **/
9074 static struct lpfc_hba *
9075 lpfc_hba_alloc(struct pci_dev *pdev)
9076 {
9077 	struct lpfc_hba *phba;
9078 
9079 	/* Allocate memory for HBA structure */
9080 	phba = kzalloc(sizeof(struct lpfc_hba), GFP_KERNEL);
9081 	if (!phba) {
9082 		dev_err(&pdev->dev, "failed to allocate hba struct\n");
9083 		return NULL;
9084 	}
9085 
9086 	/* Set reference to PCI device in HBA structure */
9087 	phba->pcidev = pdev;
9088 
9089 	/* Assign an unused board number */
9090 	phba->brd_no = lpfc_get_instance();
9091 	if (phba->brd_no < 0) {
9092 		kfree(phba);
9093 		return NULL;
9094 	}
9095 	phba->eratt_poll_interval = LPFC_ERATT_POLL_INTERVAL;
9096 
9097 	spin_lock_init(&phba->ct_ev_lock);
9098 	INIT_LIST_HEAD(&phba->ct_ev_waiters);
9099 
9100 	return phba;
9101 }
9102 
9103 /**
9104  * lpfc_hba_free - Free driver hba data structure with a device.
9105  * @phba: pointer to lpfc hba data structure.
9106  *
9107  * This routine is invoked to free the driver hba data structure with an
9108  * HBA device.
9109  **/
9110 static void
9111 lpfc_hba_free(struct lpfc_hba *phba)
9112 {
9113 	if (phba->sli_rev == LPFC_SLI_REV4)
9114 		kfree(phba->sli4_hba.hdwq);
9115 
9116 	/* Release the driver assigned board number */
9117 	idr_remove(&lpfc_hba_index, phba->brd_no);
9118 
9119 	/* Free memory allocated with sli3 rings */
9120 	kfree(phba->sli.sli3_ring);
9121 	phba->sli.sli3_ring = NULL;
9122 
9123 	kfree(phba);
9124 	return;
9125 }
9126 
9127 /**
9128  * lpfc_setup_fdmi_mask - Setup initial FDMI mask for HBA and Port attributes
9129  * @vport: pointer to lpfc vport data structure.
9130  *
9131  * This routine is will setup initial FDMI attribute masks for
9132  * FDMI2 or SmartSAN depending on module parameters. The driver will attempt
9133  * to get these attributes first before falling back, the attribute
9134  * fallback hierarchy is SmartSAN -> FDMI2 -> FMDI1
9135  **/
9136 void
9137 lpfc_setup_fdmi_mask(struct lpfc_vport *vport)
9138 {
9139 	struct lpfc_hba *phba = vport->phba;
9140 
9141 	vport->load_flag |= FC_ALLOW_FDMI;
9142 	if (phba->cfg_enable_SmartSAN ||
9143 	    phba->cfg_fdmi_on == LPFC_FDMI_SUPPORT) {
9144 		/* Setup appropriate attribute masks */
9145 		vport->fdmi_hba_mask = LPFC_FDMI2_HBA_ATTR;
9146 		if (phba->cfg_enable_SmartSAN)
9147 			vport->fdmi_port_mask = LPFC_FDMI2_SMART_ATTR;
9148 		else
9149 			vport->fdmi_port_mask = LPFC_FDMI2_PORT_ATTR;
9150 	}
9151 
9152 	lpfc_printf_log(phba, KERN_INFO, LOG_DISCOVERY,
9153 			"6077 Setup FDMI mask: hba x%x port x%x\n",
9154 			vport->fdmi_hba_mask, vport->fdmi_port_mask);
9155 }
9156 
9157 /**
9158  * lpfc_create_shost - Create hba physical port with associated scsi host.
9159  * @phba: pointer to lpfc hba data structure.
9160  *
9161  * This routine is invoked to create HBA physical port and associate a SCSI
9162  * host with it.
9163  *
9164  * Return codes
9165  *      0 - successful
9166  *      other values - error
9167  **/
9168 static int
9169 lpfc_create_shost(struct lpfc_hba *phba)
9170 {
9171 	struct lpfc_vport *vport;
9172 	struct Scsi_Host  *shost;
9173 
9174 	/* Initialize HBA FC structure */
9175 	phba->fc_edtov = FF_DEF_EDTOV;
9176 	phba->fc_ratov = FF_DEF_RATOV;
9177 	phba->fc_altov = FF_DEF_ALTOV;
9178 	phba->fc_arbtov = FF_DEF_ARBTOV;
9179 
9180 	atomic_set(&phba->sdev_cnt, 0);
9181 	vport = lpfc_create_port(phba, phba->brd_no, &phba->pcidev->dev);
9182 	if (!vport)
9183 		return -ENODEV;
9184 
9185 	shost = lpfc_shost_from_vport(vport);
9186 	phba->pport = vport;
9187 
9188 	if (phba->nvmet_support) {
9189 		/* Only 1 vport (pport) will support NVME target */
9190 		phba->targetport = NULL;
9191 		phba->cfg_enable_fc4_type = LPFC_ENABLE_NVME;
9192 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_NVME_DISC,
9193 				"6076 NVME Target Found\n");
9194 	}
9195 
9196 	lpfc_debugfs_initialize(vport);
9197 	/* Put reference to SCSI host to driver's device private data */
9198 	pci_set_drvdata(phba->pcidev, shost);
9199 
9200 	lpfc_setup_fdmi_mask(vport);
9201 
9202 	/*
9203 	 * At this point we are fully registered with PSA. In addition,
9204 	 * any initial discovery should be completed.
9205 	 */
9206 	return 0;
9207 }
9208 
9209 /**
9210  * lpfc_destroy_shost - Destroy hba physical port with associated scsi host.
9211  * @phba: pointer to lpfc hba data structure.
9212  *
9213  * This routine is invoked to destroy HBA physical port and the associated
9214  * SCSI host.
9215  **/
9216 static void
9217 lpfc_destroy_shost(struct lpfc_hba *phba)
9218 {
9219 	struct lpfc_vport *vport = phba->pport;
9220 
9221 	/* Destroy physical port that associated with the SCSI host */
9222 	destroy_port(vport);
9223 
9224 	return;
9225 }
9226 
9227 /**
9228  * lpfc_setup_bg - Setup Block guard structures and debug areas.
9229  * @phba: pointer to lpfc hba data structure.
9230  * @shost: the shost to be used to detect Block guard settings.
9231  *
9232  * This routine sets up the local Block guard protocol settings for @shost.
9233  * This routine also allocates memory for debugging bg buffers.
9234  **/
9235 static void
9236 lpfc_setup_bg(struct lpfc_hba *phba, struct Scsi_Host *shost)
9237 {
9238 	uint32_t old_mask;
9239 	uint32_t old_guard;
9240 
9241 	if (phba->cfg_prot_mask && phba->cfg_prot_guard) {
9242 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9243 				"1478 Registering BlockGuard with the "
9244 				"SCSI layer\n");
9245 
9246 		old_mask = phba->cfg_prot_mask;
9247 		old_guard = phba->cfg_prot_guard;
9248 
9249 		/* Only allow supported values */
9250 		phba->cfg_prot_mask &= (SHOST_DIF_TYPE1_PROTECTION |
9251 			SHOST_DIX_TYPE0_PROTECTION |
9252 			SHOST_DIX_TYPE1_PROTECTION);
9253 		phba->cfg_prot_guard &= (SHOST_DIX_GUARD_IP |
9254 					 SHOST_DIX_GUARD_CRC);
9255 
9256 		/* DIF Type 1 protection for profiles AST1/C1 is end to end */
9257 		if (phba->cfg_prot_mask == SHOST_DIX_TYPE1_PROTECTION)
9258 			phba->cfg_prot_mask |= SHOST_DIF_TYPE1_PROTECTION;
9259 
9260 		if (phba->cfg_prot_mask && phba->cfg_prot_guard) {
9261 			if ((old_mask != phba->cfg_prot_mask) ||
9262 				(old_guard != phba->cfg_prot_guard))
9263 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9264 					"1475 Registering BlockGuard with the "
9265 					"SCSI layer: mask %d  guard %d\n",
9266 					phba->cfg_prot_mask,
9267 					phba->cfg_prot_guard);
9268 
9269 			scsi_host_set_prot(shost, phba->cfg_prot_mask);
9270 			scsi_host_set_guard(shost, phba->cfg_prot_guard);
9271 		} else
9272 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9273 				"1479 Not Registering BlockGuard with the SCSI "
9274 				"layer, Bad protection parameters: %d %d\n",
9275 				old_mask, old_guard);
9276 	}
9277 }
9278 
9279 /**
9280  * lpfc_post_init_setup - Perform necessary device post initialization setup.
9281  * @phba: pointer to lpfc hba data structure.
9282  *
9283  * This routine is invoked to perform all the necessary post initialization
9284  * setup for the device.
9285  **/
9286 static void
9287 lpfc_post_init_setup(struct lpfc_hba *phba)
9288 {
9289 	struct Scsi_Host  *shost;
9290 	struct lpfc_adapter_event_header adapter_event;
9291 
9292 	/* Get the default values for Model Name and Description */
9293 	lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
9294 
9295 	/*
9296 	 * hba setup may have changed the hba_queue_depth so we need to
9297 	 * adjust the value of can_queue.
9298 	 */
9299 	shost = pci_get_drvdata(phba->pcidev);
9300 	shost->can_queue = phba->cfg_hba_queue_depth - 10;
9301 
9302 	lpfc_host_attrib_init(shost);
9303 
9304 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
9305 		spin_lock_irq(shost->host_lock);
9306 		lpfc_poll_start_timer(phba);
9307 		spin_unlock_irq(shost->host_lock);
9308 	}
9309 
9310 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9311 			"0428 Perform SCSI scan\n");
9312 	/* Send board arrival event to upper layer */
9313 	adapter_event.event_type = FC_REG_ADAPTER_EVENT;
9314 	adapter_event.subcategory = LPFC_EVENT_ARRIVAL;
9315 	fc_host_post_vendor_event(shost, fc_get_event_number(),
9316 				  sizeof(adapter_event),
9317 				  (char *) &adapter_event,
9318 				  LPFC_NL_VENDOR_ID);
9319 	return;
9320 }
9321 
9322 /**
9323  * lpfc_sli_pci_mem_setup - Setup SLI3 HBA PCI memory space.
9324  * @phba: pointer to lpfc hba data structure.
9325  *
9326  * This routine is invoked to set up the PCI device memory space for device
9327  * with SLI-3 interface spec.
9328  *
9329  * Return codes
9330  * 	0 - successful
9331  * 	other values - error
9332  **/
9333 static int
9334 lpfc_sli_pci_mem_setup(struct lpfc_hba *phba)
9335 {
9336 	struct pci_dev *pdev = phba->pcidev;
9337 	unsigned long bar0map_len, bar2map_len;
9338 	int i, hbq_count;
9339 	void *ptr;
9340 	int error;
9341 
9342 	if (!pdev)
9343 		return -ENODEV;
9344 
9345 	/* Set the device DMA mask size */
9346 	error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
9347 	if (error)
9348 		error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32));
9349 	if (error)
9350 		return error;
9351 	error = -ENODEV;
9352 
9353 	/* Get the bus address of Bar0 and Bar2 and the number of bytes
9354 	 * required by each mapping.
9355 	 */
9356 	phba->pci_bar0_map = pci_resource_start(pdev, 0);
9357 	bar0map_len = pci_resource_len(pdev, 0);
9358 
9359 	phba->pci_bar2_map = pci_resource_start(pdev, 2);
9360 	bar2map_len = pci_resource_len(pdev, 2);
9361 
9362 	/* Map HBA SLIM to a kernel virtual address. */
9363 	phba->slim_memmap_p = ioremap(phba->pci_bar0_map, bar0map_len);
9364 	if (!phba->slim_memmap_p) {
9365 		dev_printk(KERN_ERR, &pdev->dev,
9366 			   "ioremap failed for SLIM memory.\n");
9367 		goto out;
9368 	}
9369 
9370 	/* Map HBA Control Registers to a kernel virtual address. */
9371 	phba->ctrl_regs_memmap_p = ioremap(phba->pci_bar2_map, bar2map_len);
9372 	if (!phba->ctrl_regs_memmap_p) {
9373 		dev_printk(KERN_ERR, &pdev->dev,
9374 			   "ioremap failed for HBA control registers.\n");
9375 		goto out_iounmap_slim;
9376 	}
9377 
9378 	/* Allocate memory for SLI-2 structures */
9379 	phba->slim2p.virt = dma_alloc_coherent(&pdev->dev, SLI2_SLIM_SIZE,
9380 					       &phba->slim2p.phys, GFP_KERNEL);
9381 	if (!phba->slim2p.virt)
9382 		goto out_iounmap;
9383 
9384 	phba->mbox = phba->slim2p.virt + offsetof(struct lpfc_sli2_slim, mbx);
9385 	phba->mbox_ext = (phba->slim2p.virt +
9386 		offsetof(struct lpfc_sli2_slim, mbx_ext_words));
9387 	phba->pcb = (phba->slim2p.virt + offsetof(struct lpfc_sli2_slim, pcb));
9388 	phba->IOCBs = (phba->slim2p.virt +
9389 		       offsetof(struct lpfc_sli2_slim, IOCBs));
9390 
9391 	phba->hbqslimp.virt = dma_alloc_coherent(&pdev->dev,
9392 						 lpfc_sli_hbq_size(),
9393 						 &phba->hbqslimp.phys,
9394 						 GFP_KERNEL);
9395 	if (!phba->hbqslimp.virt)
9396 		goto out_free_slim;
9397 
9398 	hbq_count = lpfc_sli_hbq_count();
9399 	ptr = phba->hbqslimp.virt;
9400 	for (i = 0; i < hbq_count; ++i) {
9401 		phba->hbqs[i].hbq_virt = ptr;
9402 		INIT_LIST_HEAD(&phba->hbqs[i].hbq_buffer_list);
9403 		ptr += (lpfc_hbq_defs[i]->entry_count *
9404 			sizeof(struct lpfc_hbq_entry));
9405 	}
9406 	phba->hbqs[LPFC_ELS_HBQ].hbq_alloc_buffer = lpfc_els_hbq_alloc;
9407 	phba->hbqs[LPFC_ELS_HBQ].hbq_free_buffer = lpfc_els_hbq_free;
9408 
9409 	memset(phba->hbqslimp.virt, 0, lpfc_sli_hbq_size());
9410 
9411 	phba->MBslimaddr = phba->slim_memmap_p;
9412 	phba->HAregaddr = phba->ctrl_regs_memmap_p + HA_REG_OFFSET;
9413 	phba->CAregaddr = phba->ctrl_regs_memmap_p + CA_REG_OFFSET;
9414 	phba->HSregaddr = phba->ctrl_regs_memmap_p + HS_REG_OFFSET;
9415 	phba->HCregaddr = phba->ctrl_regs_memmap_p + HC_REG_OFFSET;
9416 
9417 	return 0;
9418 
9419 out_free_slim:
9420 	dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
9421 			  phba->slim2p.virt, phba->slim2p.phys);
9422 out_iounmap:
9423 	iounmap(phba->ctrl_regs_memmap_p);
9424 out_iounmap_slim:
9425 	iounmap(phba->slim_memmap_p);
9426 out:
9427 	return error;
9428 }
9429 
9430 /**
9431  * lpfc_sli_pci_mem_unset - Unset SLI3 HBA PCI memory space.
9432  * @phba: pointer to lpfc hba data structure.
9433  *
9434  * This routine is invoked to unset the PCI device memory space for device
9435  * with SLI-3 interface spec.
9436  **/
9437 static void
9438 lpfc_sli_pci_mem_unset(struct lpfc_hba *phba)
9439 {
9440 	struct pci_dev *pdev;
9441 
9442 	/* Obtain PCI device reference */
9443 	if (!phba->pcidev)
9444 		return;
9445 	else
9446 		pdev = phba->pcidev;
9447 
9448 	/* Free coherent DMA memory allocated */
9449 	dma_free_coherent(&pdev->dev, lpfc_sli_hbq_size(),
9450 			  phba->hbqslimp.virt, phba->hbqslimp.phys);
9451 	dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
9452 			  phba->slim2p.virt, phba->slim2p.phys);
9453 
9454 	/* I/O memory unmap */
9455 	iounmap(phba->ctrl_regs_memmap_p);
9456 	iounmap(phba->slim_memmap_p);
9457 
9458 	return;
9459 }
9460 
9461 /**
9462  * lpfc_sli4_post_status_check - Wait for SLI4 POST done and check status
9463  * @phba: pointer to lpfc hba data structure.
9464  *
9465  * This routine is invoked to wait for SLI4 device Power On Self Test (POST)
9466  * done and check status.
9467  *
9468  * Return 0 if successful, otherwise -ENODEV.
9469  **/
9470 int
9471 lpfc_sli4_post_status_check(struct lpfc_hba *phba)
9472 {
9473 	struct lpfc_register portsmphr_reg, uerrlo_reg, uerrhi_reg;
9474 	struct lpfc_register reg_data;
9475 	int i, port_error = 0;
9476 	uint32_t if_type;
9477 
9478 	memset(&portsmphr_reg, 0, sizeof(portsmphr_reg));
9479 	memset(&reg_data, 0, sizeof(reg_data));
9480 	if (!phba->sli4_hba.PSMPHRregaddr)
9481 		return -ENODEV;
9482 
9483 	/* Wait up to 30 seconds for the SLI Port POST done and ready */
9484 	for (i = 0; i < 3000; i++) {
9485 		if (lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
9486 			&portsmphr_reg.word0) ||
9487 			(bf_get(lpfc_port_smphr_perr, &portsmphr_reg))) {
9488 			/* Port has a fatal POST error, break out */
9489 			port_error = -ENODEV;
9490 			break;
9491 		}
9492 		if (LPFC_POST_STAGE_PORT_READY ==
9493 		    bf_get(lpfc_port_smphr_port_status, &portsmphr_reg))
9494 			break;
9495 		msleep(10);
9496 	}
9497 
9498 	/*
9499 	 * If there was a port error during POST, then don't proceed with
9500 	 * other register reads as the data may not be valid.  Just exit.
9501 	 */
9502 	if (port_error) {
9503 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9504 			"1408 Port Failed POST - portsmphr=0x%x, "
9505 			"perr=x%x, sfi=x%x, nip=x%x, ipc=x%x, scr1=x%x, "
9506 			"scr2=x%x, hscratch=x%x, pstatus=x%x\n",
9507 			portsmphr_reg.word0,
9508 			bf_get(lpfc_port_smphr_perr, &portsmphr_reg),
9509 			bf_get(lpfc_port_smphr_sfi, &portsmphr_reg),
9510 			bf_get(lpfc_port_smphr_nip, &portsmphr_reg),
9511 			bf_get(lpfc_port_smphr_ipc, &portsmphr_reg),
9512 			bf_get(lpfc_port_smphr_scr1, &portsmphr_reg),
9513 			bf_get(lpfc_port_smphr_scr2, &portsmphr_reg),
9514 			bf_get(lpfc_port_smphr_host_scratch, &portsmphr_reg),
9515 			bf_get(lpfc_port_smphr_port_status, &portsmphr_reg));
9516 	} else {
9517 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9518 				"2534 Device Info: SLIFamily=0x%x, "
9519 				"SLIRev=0x%x, IFType=0x%x, SLIHint_1=0x%x, "
9520 				"SLIHint_2=0x%x, FT=0x%x\n",
9521 				bf_get(lpfc_sli_intf_sli_family,
9522 				       &phba->sli4_hba.sli_intf),
9523 				bf_get(lpfc_sli_intf_slirev,
9524 				       &phba->sli4_hba.sli_intf),
9525 				bf_get(lpfc_sli_intf_if_type,
9526 				       &phba->sli4_hba.sli_intf),
9527 				bf_get(lpfc_sli_intf_sli_hint1,
9528 				       &phba->sli4_hba.sli_intf),
9529 				bf_get(lpfc_sli_intf_sli_hint2,
9530 				       &phba->sli4_hba.sli_intf),
9531 				bf_get(lpfc_sli_intf_func_type,
9532 				       &phba->sli4_hba.sli_intf));
9533 		/*
9534 		 * Check for other Port errors during the initialization
9535 		 * process.  Fail the load if the port did not come up
9536 		 * correctly.
9537 		 */
9538 		if_type = bf_get(lpfc_sli_intf_if_type,
9539 				 &phba->sli4_hba.sli_intf);
9540 		switch (if_type) {
9541 		case LPFC_SLI_INTF_IF_TYPE_0:
9542 			phba->sli4_hba.ue_mask_lo =
9543 			      readl(phba->sli4_hba.u.if_type0.UEMASKLOregaddr);
9544 			phba->sli4_hba.ue_mask_hi =
9545 			      readl(phba->sli4_hba.u.if_type0.UEMASKHIregaddr);
9546 			uerrlo_reg.word0 =
9547 			      readl(phba->sli4_hba.u.if_type0.UERRLOregaddr);
9548 			uerrhi_reg.word0 =
9549 				readl(phba->sli4_hba.u.if_type0.UERRHIregaddr);
9550 			if ((~phba->sli4_hba.ue_mask_lo & uerrlo_reg.word0) ||
9551 			    (~phba->sli4_hba.ue_mask_hi & uerrhi_reg.word0)) {
9552 				lpfc_printf_log(phba, KERN_ERR,
9553 						LOG_TRACE_EVENT,
9554 						"1422 Unrecoverable Error "
9555 						"Detected during POST "
9556 						"uerr_lo_reg=0x%x, "
9557 						"uerr_hi_reg=0x%x, "
9558 						"ue_mask_lo_reg=0x%x, "
9559 						"ue_mask_hi_reg=0x%x\n",
9560 						uerrlo_reg.word0,
9561 						uerrhi_reg.word0,
9562 						phba->sli4_hba.ue_mask_lo,
9563 						phba->sli4_hba.ue_mask_hi);
9564 				port_error = -ENODEV;
9565 			}
9566 			break;
9567 		case LPFC_SLI_INTF_IF_TYPE_2:
9568 		case LPFC_SLI_INTF_IF_TYPE_6:
9569 			/* Final checks.  The port status should be clean. */
9570 			if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
9571 				&reg_data.word0) ||
9572 				(bf_get(lpfc_sliport_status_err, &reg_data) &&
9573 				 !bf_get(lpfc_sliport_status_rn, &reg_data))) {
9574 				phba->work_status[0] =
9575 					readl(phba->sli4_hba.u.if_type2.
9576 					      ERR1regaddr);
9577 				phba->work_status[1] =
9578 					readl(phba->sli4_hba.u.if_type2.
9579 					      ERR2regaddr);
9580 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9581 					"2888 Unrecoverable port error "
9582 					"following POST: port status reg "
9583 					"0x%x, port_smphr reg 0x%x, "
9584 					"error 1=0x%x, error 2=0x%x\n",
9585 					reg_data.word0,
9586 					portsmphr_reg.word0,
9587 					phba->work_status[0],
9588 					phba->work_status[1]);
9589 				port_error = -ENODEV;
9590 				break;
9591 			}
9592 
9593 			if (lpfc_pldv_detect &&
9594 			    bf_get(lpfc_sli_intf_sli_family,
9595 				   &phba->sli4_hba.sli_intf) ==
9596 					LPFC_SLI_INTF_FAMILY_G6)
9597 				pci_write_config_byte(phba->pcidev,
9598 						      LPFC_SLI_INTF, CFG_PLD);
9599 			break;
9600 		case LPFC_SLI_INTF_IF_TYPE_1:
9601 		default:
9602 			break;
9603 		}
9604 	}
9605 	return port_error;
9606 }
9607 
9608 /**
9609  * lpfc_sli4_bar0_register_memmap - Set up SLI4 BAR0 register memory map.
9610  * @phba: pointer to lpfc hba data structure.
9611  * @if_type:  The SLI4 interface type getting configured.
9612  *
9613  * This routine is invoked to set up SLI4 BAR0 PCI config space register
9614  * memory map.
9615  **/
9616 static void
9617 lpfc_sli4_bar0_register_memmap(struct lpfc_hba *phba, uint32_t if_type)
9618 {
9619 	switch (if_type) {
9620 	case LPFC_SLI_INTF_IF_TYPE_0:
9621 		phba->sli4_hba.u.if_type0.UERRLOregaddr =
9622 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UERR_STATUS_LO;
9623 		phba->sli4_hba.u.if_type0.UERRHIregaddr =
9624 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UERR_STATUS_HI;
9625 		phba->sli4_hba.u.if_type0.UEMASKLOregaddr =
9626 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UE_MASK_LO;
9627 		phba->sli4_hba.u.if_type0.UEMASKHIregaddr =
9628 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UE_MASK_HI;
9629 		phba->sli4_hba.SLIINTFregaddr =
9630 			phba->sli4_hba.conf_regs_memmap_p + LPFC_SLI_INTF;
9631 		break;
9632 	case LPFC_SLI_INTF_IF_TYPE_2:
9633 		phba->sli4_hba.u.if_type2.EQDregaddr =
9634 			phba->sli4_hba.conf_regs_memmap_p +
9635 						LPFC_CTL_PORT_EQ_DELAY_OFFSET;
9636 		phba->sli4_hba.u.if_type2.ERR1regaddr =
9637 			phba->sli4_hba.conf_regs_memmap_p +
9638 						LPFC_CTL_PORT_ER1_OFFSET;
9639 		phba->sli4_hba.u.if_type2.ERR2regaddr =
9640 			phba->sli4_hba.conf_regs_memmap_p +
9641 						LPFC_CTL_PORT_ER2_OFFSET;
9642 		phba->sli4_hba.u.if_type2.CTRLregaddr =
9643 			phba->sli4_hba.conf_regs_memmap_p +
9644 						LPFC_CTL_PORT_CTL_OFFSET;
9645 		phba->sli4_hba.u.if_type2.STATUSregaddr =
9646 			phba->sli4_hba.conf_regs_memmap_p +
9647 						LPFC_CTL_PORT_STA_OFFSET;
9648 		phba->sli4_hba.SLIINTFregaddr =
9649 			phba->sli4_hba.conf_regs_memmap_p + LPFC_SLI_INTF;
9650 		phba->sli4_hba.PSMPHRregaddr =
9651 			phba->sli4_hba.conf_regs_memmap_p +
9652 						LPFC_CTL_PORT_SEM_OFFSET;
9653 		phba->sli4_hba.RQDBregaddr =
9654 			phba->sli4_hba.conf_regs_memmap_p +
9655 						LPFC_ULP0_RQ_DOORBELL;
9656 		phba->sli4_hba.WQDBregaddr =
9657 			phba->sli4_hba.conf_regs_memmap_p +
9658 						LPFC_ULP0_WQ_DOORBELL;
9659 		phba->sli4_hba.CQDBregaddr =
9660 			phba->sli4_hba.conf_regs_memmap_p + LPFC_EQCQ_DOORBELL;
9661 		phba->sli4_hba.EQDBregaddr = phba->sli4_hba.CQDBregaddr;
9662 		phba->sli4_hba.MQDBregaddr =
9663 			phba->sli4_hba.conf_regs_memmap_p + LPFC_MQ_DOORBELL;
9664 		phba->sli4_hba.BMBXregaddr =
9665 			phba->sli4_hba.conf_regs_memmap_p + LPFC_BMBX;
9666 		break;
9667 	case LPFC_SLI_INTF_IF_TYPE_6:
9668 		phba->sli4_hba.u.if_type2.EQDregaddr =
9669 			phba->sli4_hba.conf_regs_memmap_p +
9670 						LPFC_CTL_PORT_EQ_DELAY_OFFSET;
9671 		phba->sli4_hba.u.if_type2.ERR1regaddr =
9672 			phba->sli4_hba.conf_regs_memmap_p +
9673 						LPFC_CTL_PORT_ER1_OFFSET;
9674 		phba->sli4_hba.u.if_type2.ERR2regaddr =
9675 			phba->sli4_hba.conf_regs_memmap_p +
9676 						LPFC_CTL_PORT_ER2_OFFSET;
9677 		phba->sli4_hba.u.if_type2.CTRLregaddr =
9678 			phba->sli4_hba.conf_regs_memmap_p +
9679 						LPFC_CTL_PORT_CTL_OFFSET;
9680 		phba->sli4_hba.u.if_type2.STATUSregaddr =
9681 			phba->sli4_hba.conf_regs_memmap_p +
9682 						LPFC_CTL_PORT_STA_OFFSET;
9683 		phba->sli4_hba.PSMPHRregaddr =
9684 			phba->sli4_hba.conf_regs_memmap_p +
9685 						LPFC_CTL_PORT_SEM_OFFSET;
9686 		phba->sli4_hba.BMBXregaddr =
9687 			phba->sli4_hba.conf_regs_memmap_p + LPFC_BMBX;
9688 		break;
9689 	case LPFC_SLI_INTF_IF_TYPE_1:
9690 	default:
9691 		dev_printk(KERN_ERR, &phba->pcidev->dev,
9692 			   "FATAL - unsupported SLI4 interface type - %d\n",
9693 			   if_type);
9694 		break;
9695 	}
9696 }
9697 
9698 /**
9699  * lpfc_sli4_bar1_register_memmap - Set up SLI4 BAR1 register memory map.
9700  * @phba: pointer to lpfc hba data structure.
9701  * @if_type: sli if type to operate on.
9702  *
9703  * This routine is invoked to set up SLI4 BAR1 register memory map.
9704  **/
9705 static void
9706 lpfc_sli4_bar1_register_memmap(struct lpfc_hba *phba, uint32_t if_type)
9707 {
9708 	switch (if_type) {
9709 	case LPFC_SLI_INTF_IF_TYPE_0:
9710 		phba->sli4_hba.PSMPHRregaddr =
9711 			phba->sli4_hba.ctrl_regs_memmap_p +
9712 			LPFC_SLIPORT_IF0_SMPHR;
9713 		phba->sli4_hba.ISRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
9714 			LPFC_HST_ISR0;
9715 		phba->sli4_hba.IMRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
9716 			LPFC_HST_IMR0;
9717 		phba->sli4_hba.ISCRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
9718 			LPFC_HST_ISCR0;
9719 		break;
9720 	case LPFC_SLI_INTF_IF_TYPE_6:
9721 		phba->sli4_hba.RQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9722 			LPFC_IF6_RQ_DOORBELL;
9723 		phba->sli4_hba.WQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9724 			LPFC_IF6_WQ_DOORBELL;
9725 		phba->sli4_hba.CQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9726 			LPFC_IF6_CQ_DOORBELL;
9727 		phba->sli4_hba.EQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9728 			LPFC_IF6_EQ_DOORBELL;
9729 		phba->sli4_hba.MQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9730 			LPFC_IF6_MQ_DOORBELL;
9731 		break;
9732 	case LPFC_SLI_INTF_IF_TYPE_2:
9733 	case LPFC_SLI_INTF_IF_TYPE_1:
9734 	default:
9735 		dev_err(&phba->pcidev->dev,
9736 			   "FATAL - unsupported SLI4 interface type - %d\n",
9737 			   if_type);
9738 		break;
9739 	}
9740 }
9741 
9742 /**
9743  * lpfc_sli4_bar2_register_memmap - Set up SLI4 BAR2 register memory map.
9744  * @phba: pointer to lpfc hba data structure.
9745  * @vf: virtual function number
9746  *
9747  * This routine is invoked to set up SLI4 BAR2 doorbell register memory map
9748  * based on the given viftual function number, @vf.
9749  *
9750  * Return 0 if successful, otherwise -ENODEV.
9751  **/
9752 static int
9753 lpfc_sli4_bar2_register_memmap(struct lpfc_hba *phba, uint32_t vf)
9754 {
9755 	if (vf > LPFC_VIR_FUNC_MAX)
9756 		return -ENODEV;
9757 
9758 	phba->sli4_hba.RQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9759 				vf * LPFC_VFR_PAGE_SIZE +
9760 					LPFC_ULP0_RQ_DOORBELL);
9761 	phba->sli4_hba.WQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9762 				vf * LPFC_VFR_PAGE_SIZE +
9763 					LPFC_ULP0_WQ_DOORBELL);
9764 	phba->sli4_hba.CQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9765 				vf * LPFC_VFR_PAGE_SIZE +
9766 					LPFC_EQCQ_DOORBELL);
9767 	phba->sli4_hba.EQDBregaddr = phba->sli4_hba.CQDBregaddr;
9768 	phba->sli4_hba.MQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9769 				vf * LPFC_VFR_PAGE_SIZE + LPFC_MQ_DOORBELL);
9770 	phba->sli4_hba.BMBXregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9771 				vf * LPFC_VFR_PAGE_SIZE + LPFC_BMBX);
9772 	return 0;
9773 }
9774 
9775 /**
9776  * lpfc_create_bootstrap_mbox - Create the bootstrap mailbox
9777  * @phba: pointer to lpfc hba data structure.
9778  *
9779  * This routine is invoked to create the bootstrap mailbox
9780  * region consistent with the SLI-4 interface spec.  This
9781  * routine allocates all memory necessary to communicate
9782  * mailbox commands to the port and sets up all alignment
9783  * needs.  No locks are expected to be held when calling
9784  * this routine.
9785  *
9786  * Return codes
9787  * 	0 - successful
9788  * 	-ENOMEM - could not allocated memory.
9789  **/
9790 static int
9791 lpfc_create_bootstrap_mbox(struct lpfc_hba *phba)
9792 {
9793 	uint32_t bmbx_size;
9794 	struct lpfc_dmabuf *dmabuf;
9795 	struct dma_address *dma_address;
9796 	uint32_t pa_addr;
9797 	uint64_t phys_addr;
9798 
9799 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
9800 	if (!dmabuf)
9801 		return -ENOMEM;
9802 
9803 	/*
9804 	 * The bootstrap mailbox region is comprised of 2 parts
9805 	 * plus an alignment restriction of 16 bytes.
9806 	 */
9807 	bmbx_size = sizeof(struct lpfc_bmbx_create) + (LPFC_ALIGN_16_BYTE - 1);
9808 	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev, bmbx_size,
9809 					  &dmabuf->phys, GFP_KERNEL);
9810 	if (!dmabuf->virt) {
9811 		kfree(dmabuf);
9812 		return -ENOMEM;
9813 	}
9814 
9815 	/*
9816 	 * Initialize the bootstrap mailbox pointers now so that the register
9817 	 * operations are simple later.  The mailbox dma address is required
9818 	 * to be 16-byte aligned.  Also align the virtual memory as each
9819 	 * maibox is copied into the bmbx mailbox region before issuing the
9820 	 * command to the port.
9821 	 */
9822 	phba->sli4_hba.bmbx.dmabuf = dmabuf;
9823 	phba->sli4_hba.bmbx.bmbx_size = bmbx_size;
9824 
9825 	phba->sli4_hba.bmbx.avirt = PTR_ALIGN(dmabuf->virt,
9826 					      LPFC_ALIGN_16_BYTE);
9827 	phba->sli4_hba.bmbx.aphys = ALIGN(dmabuf->phys,
9828 					      LPFC_ALIGN_16_BYTE);
9829 
9830 	/*
9831 	 * Set the high and low physical addresses now.  The SLI4 alignment
9832 	 * requirement is 16 bytes and the mailbox is posted to the port
9833 	 * as two 30-bit addresses.  The other data is a bit marking whether
9834 	 * the 30-bit address is the high or low address.
9835 	 * Upcast bmbx aphys to 64bits so shift instruction compiles
9836 	 * clean on 32 bit machines.
9837 	 */
9838 	dma_address = &phba->sli4_hba.bmbx.dma_address;
9839 	phys_addr = (uint64_t)phba->sli4_hba.bmbx.aphys;
9840 	pa_addr = (uint32_t) ((phys_addr >> 34) & 0x3fffffff);
9841 	dma_address->addr_hi = (uint32_t) ((pa_addr << 2) |
9842 					   LPFC_BMBX_BIT1_ADDR_HI);
9843 
9844 	pa_addr = (uint32_t) ((phba->sli4_hba.bmbx.aphys >> 4) & 0x3fffffff);
9845 	dma_address->addr_lo = (uint32_t) ((pa_addr << 2) |
9846 					   LPFC_BMBX_BIT1_ADDR_LO);
9847 	return 0;
9848 }
9849 
9850 /**
9851  * lpfc_destroy_bootstrap_mbox - Destroy all bootstrap mailbox resources
9852  * @phba: pointer to lpfc hba data structure.
9853  *
9854  * This routine is invoked to teardown the bootstrap mailbox
9855  * region and release all host resources. This routine requires
9856  * the caller to ensure all mailbox commands recovered, no
9857  * additional mailbox comands are sent, and interrupts are disabled
9858  * before calling this routine.
9859  *
9860  **/
9861 static void
9862 lpfc_destroy_bootstrap_mbox(struct lpfc_hba *phba)
9863 {
9864 	dma_free_coherent(&phba->pcidev->dev,
9865 			  phba->sli4_hba.bmbx.bmbx_size,
9866 			  phba->sli4_hba.bmbx.dmabuf->virt,
9867 			  phba->sli4_hba.bmbx.dmabuf->phys);
9868 
9869 	kfree(phba->sli4_hba.bmbx.dmabuf);
9870 	memset(&phba->sli4_hba.bmbx, 0, sizeof(struct lpfc_bmbx));
9871 }
9872 
9873 static const char * const lpfc_topo_to_str[] = {
9874 	"Loop then P2P",
9875 	"Loopback",
9876 	"P2P Only",
9877 	"Unsupported",
9878 	"Loop Only",
9879 	"Unsupported",
9880 	"P2P then Loop",
9881 };
9882 
9883 #define	LINK_FLAGS_DEF	0x0
9884 #define	LINK_FLAGS_P2P	0x1
9885 #define	LINK_FLAGS_LOOP	0x2
9886 /**
9887  * lpfc_map_topology - Map the topology read from READ_CONFIG
9888  * @phba: pointer to lpfc hba data structure.
9889  * @rd_config: pointer to read config data
9890  *
9891  * This routine is invoked to map the topology values as read
9892  * from the read config mailbox command. If the persistent
9893  * topology feature is supported, the firmware will provide the
9894  * saved topology information to be used in INIT_LINK
9895  **/
9896 static void
9897 lpfc_map_topology(struct lpfc_hba *phba, struct lpfc_mbx_read_config *rd_config)
9898 {
9899 	u8 ptv, tf, pt;
9900 
9901 	ptv = bf_get(lpfc_mbx_rd_conf_ptv, rd_config);
9902 	tf = bf_get(lpfc_mbx_rd_conf_tf, rd_config);
9903 	pt = bf_get(lpfc_mbx_rd_conf_pt, rd_config);
9904 
9905 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9906 			"2027 Read Config Data : ptv:0x%x, tf:0x%x pt:0x%x",
9907 			 ptv, tf, pt);
9908 	if (!ptv) {
9909 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9910 				"2019 FW does not support persistent topology "
9911 				"Using driver parameter defined value [%s]",
9912 				lpfc_topo_to_str[phba->cfg_topology]);
9913 		return;
9914 	}
9915 	/* FW supports persistent topology - override module parameter value */
9916 	phba->hba_flag |= HBA_PERSISTENT_TOPO;
9917 
9918 	/* if ASIC_GEN_NUM >= 0xC) */
9919 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
9920 		    LPFC_SLI_INTF_IF_TYPE_6) ||
9921 	    (bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf) ==
9922 		    LPFC_SLI_INTF_FAMILY_G6)) {
9923 		if (!tf) {
9924 			phba->cfg_topology = ((pt == LINK_FLAGS_LOOP)
9925 					? FLAGS_TOPOLOGY_MODE_LOOP
9926 					: FLAGS_TOPOLOGY_MODE_PT_PT);
9927 		} else {
9928 			phba->hba_flag &= ~HBA_PERSISTENT_TOPO;
9929 		}
9930 	} else { /* G5 */
9931 		if (tf) {
9932 			/* If topology failover set - pt is '0' or '1' */
9933 			phba->cfg_topology = (pt ? FLAGS_TOPOLOGY_MODE_PT_LOOP :
9934 					      FLAGS_TOPOLOGY_MODE_LOOP_PT);
9935 		} else {
9936 			phba->cfg_topology = ((pt == LINK_FLAGS_P2P)
9937 					? FLAGS_TOPOLOGY_MODE_PT_PT
9938 					: FLAGS_TOPOLOGY_MODE_LOOP);
9939 		}
9940 	}
9941 	if (phba->hba_flag & HBA_PERSISTENT_TOPO) {
9942 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9943 				"2020 Using persistent topology value [%s]",
9944 				lpfc_topo_to_str[phba->cfg_topology]);
9945 	} else {
9946 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9947 				"2021 Invalid topology values from FW "
9948 				"Using driver parameter defined value [%s]",
9949 				lpfc_topo_to_str[phba->cfg_topology]);
9950 	}
9951 }
9952 
9953 /**
9954  * lpfc_sli4_read_config - Get the config parameters.
9955  * @phba: pointer to lpfc hba data structure.
9956  *
9957  * This routine is invoked to read the configuration parameters from the HBA.
9958  * The configuration parameters are used to set the base and maximum values
9959  * for RPI's XRI's VPI's VFI's and FCFIs. These values also affect the resource
9960  * allocation for the port.
9961  *
9962  * Return codes
9963  * 	0 - successful
9964  * 	-ENOMEM - No available memory
9965  *      -EIO - The mailbox failed to complete successfully.
9966  **/
9967 int
9968 lpfc_sli4_read_config(struct lpfc_hba *phba)
9969 {
9970 	LPFC_MBOXQ_t *pmb;
9971 	struct lpfc_mbx_read_config *rd_config;
9972 	union  lpfc_sli4_cfg_shdr *shdr;
9973 	uint32_t shdr_status, shdr_add_status;
9974 	struct lpfc_mbx_get_func_cfg *get_func_cfg;
9975 	struct lpfc_rsrc_desc_fcfcoe *desc;
9976 	char *pdesc_0;
9977 	uint16_t forced_link_speed;
9978 	uint32_t if_type, qmin, fawwpn;
9979 	int length, i, rc = 0, rc2;
9980 
9981 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
9982 	if (!pmb) {
9983 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9984 				"2011 Unable to allocate memory for issuing "
9985 				"SLI_CONFIG_SPECIAL mailbox command\n");
9986 		return -ENOMEM;
9987 	}
9988 
9989 	lpfc_read_config(phba, pmb);
9990 
9991 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
9992 	if (rc != MBX_SUCCESS) {
9993 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9994 				"2012 Mailbox failed , mbxCmd x%x "
9995 				"READ_CONFIG, mbxStatus x%x\n",
9996 				bf_get(lpfc_mqe_command, &pmb->u.mqe),
9997 				bf_get(lpfc_mqe_status, &pmb->u.mqe));
9998 		rc = -EIO;
9999 	} else {
10000 		rd_config = &pmb->u.mqe.un.rd_config;
10001 		if (bf_get(lpfc_mbx_rd_conf_lnk_ldv, rd_config)) {
10002 			phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL;
10003 			phba->sli4_hba.lnk_info.lnk_tp =
10004 				bf_get(lpfc_mbx_rd_conf_lnk_type, rd_config);
10005 			phba->sli4_hba.lnk_info.lnk_no =
10006 				bf_get(lpfc_mbx_rd_conf_lnk_numb, rd_config);
10007 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10008 					"3081 lnk_type:%d, lnk_numb:%d\n",
10009 					phba->sli4_hba.lnk_info.lnk_tp,
10010 					phba->sli4_hba.lnk_info.lnk_no);
10011 		} else
10012 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
10013 					"3082 Mailbox (x%x) returned ldv:x0\n",
10014 					bf_get(lpfc_mqe_command, &pmb->u.mqe));
10015 		if (bf_get(lpfc_mbx_rd_conf_bbscn_def, rd_config)) {
10016 			phba->bbcredit_support = 1;
10017 			phba->sli4_hba.bbscn_params.word0 = rd_config->word8;
10018 		}
10019 
10020 		fawwpn = bf_get(lpfc_mbx_rd_conf_fawwpn, rd_config);
10021 
10022 		if (fawwpn) {
10023 			lpfc_printf_log(phba, KERN_INFO,
10024 					LOG_INIT | LOG_DISCOVERY,
10025 					"2702 READ_CONFIG: FA-PWWN is "
10026 					"configured on\n");
10027 			phba->sli4_hba.fawwpn_flag |= LPFC_FAWWPN_CONFIG;
10028 		} else {
10029 			/* Clear FW configured flag, preserve driver flag */
10030 			phba->sli4_hba.fawwpn_flag &= ~LPFC_FAWWPN_CONFIG;
10031 		}
10032 
10033 		phba->sli4_hba.conf_trunk =
10034 			bf_get(lpfc_mbx_rd_conf_trunk, rd_config);
10035 		phba->sli4_hba.extents_in_use =
10036 			bf_get(lpfc_mbx_rd_conf_extnts_inuse, rd_config);
10037 
10038 		phba->sli4_hba.max_cfg_param.max_xri =
10039 			bf_get(lpfc_mbx_rd_conf_xri_count, rd_config);
10040 		/* Reduce resource usage in kdump environment */
10041 		if (is_kdump_kernel() &&
10042 		    phba->sli4_hba.max_cfg_param.max_xri > 512)
10043 			phba->sli4_hba.max_cfg_param.max_xri = 512;
10044 		phba->sli4_hba.max_cfg_param.xri_base =
10045 			bf_get(lpfc_mbx_rd_conf_xri_base, rd_config);
10046 		phba->sli4_hba.max_cfg_param.max_vpi =
10047 			bf_get(lpfc_mbx_rd_conf_vpi_count, rd_config);
10048 		/* Limit the max we support */
10049 		if (phba->sli4_hba.max_cfg_param.max_vpi > LPFC_MAX_VPORTS)
10050 			phba->sli4_hba.max_cfg_param.max_vpi = LPFC_MAX_VPORTS;
10051 		phba->sli4_hba.max_cfg_param.vpi_base =
10052 			bf_get(lpfc_mbx_rd_conf_vpi_base, rd_config);
10053 		phba->sli4_hba.max_cfg_param.max_rpi =
10054 			bf_get(lpfc_mbx_rd_conf_rpi_count, rd_config);
10055 		phba->sli4_hba.max_cfg_param.rpi_base =
10056 			bf_get(lpfc_mbx_rd_conf_rpi_base, rd_config);
10057 		phba->sli4_hba.max_cfg_param.max_vfi =
10058 			bf_get(lpfc_mbx_rd_conf_vfi_count, rd_config);
10059 		phba->sli4_hba.max_cfg_param.vfi_base =
10060 			bf_get(lpfc_mbx_rd_conf_vfi_base, rd_config);
10061 		phba->sli4_hba.max_cfg_param.max_fcfi =
10062 			bf_get(lpfc_mbx_rd_conf_fcfi_count, rd_config);
10063 		phba->sli4_hba.max_cfg_param.max_eq =
10064 			bf_get(lpfc_mbx_rd_conf_eq_count, rd_config);
10065 		phba->sli4_hba.max_cfg_param.max_rq =
10066 			bf_get(lpfc_mbx_rd_conf_rq_count, rd_config);
10067 		phba->sli4_hba.max_cfg_param.max_wq =
10068 			bf_get(lpfc_mbx_rd_conf_wq_count, rd_config);
10069 		phba->sli4_hba.max_cfg_param.max_cq =
10070 			bf_get(lpfc_mbx_rd_conf_cq_count, rd_config);
10071 		phba->lmt = bf_get(lpfc_mbx_rd_conf_lmt, rd_config);
10072 		phba->sli4_hba.next_xri = phba->sli4_hba.max_cfg_param.xri_base;
10073 		phba->vpi_base = phba->sli4_hba.max_cfg_param.vpi_base;
10074 		phba->vfi_base = phba->sli4_hba.max_cfg_param.vfi_base;
10075 		phba->max_vpi = (phba->sli4_hba.max_cfg_param.max_vpi > 0) ?
10076 				(phba->sli4_hba.max_cfg_param.max_vpi - 1) : 0;
10077 		phba->max_vports = phba->max_vpi;
10078 
10079 		/* Next decide on FPIN or Signal E2E CGN support
10080 		 * For congestion alarms and warnings valid combination are:
10081 		 * 1. FPIN alarms / FPIN warnings
10082 		 * 2. Signal alarms / Signal warnings
10083 		 * 3. FPIN alarms / Signal warnings
10084 		 * 4. Signal alarms / FPIN warnings
10085 		 *
10086 		 * Initialize the adapter frequency to 100 mSecs
10087 		 */
10088 		phba->cgn_reg_fpin = LPFC_CGN_FPIN_BOTH;
10089 		phba->cgn_reg_signal = EDC_CG_SIG_NOTSUPPORTED;
10090 		phba->cgn_sig_freq = lpfc_fabric_cgn_frequency;
10091 
10092 		if (lpfc_use_cgn_signal) {
10093 			if (bf_get(lpfc_mbx_rd_conf_wcs, rd_config)) {
10094 				phba->cgn_reg_signal = EDC_CG_SIG_WARN_ONLY;
10095 				phba->cgn_reg_fpin &= ~LPFC_CGN_FPIN_WARN;
10096 			}
10097 			if (bf_get(lpfc_mbx_rd_conf_acs, rd_config)) {
10098 				/* MUST support both alarm and warning
10099 				 * because EDC does not support alarm alone.
10100 				 */
10101 				if (phba->cgn_reg_signal !=
10102 				    EDC_CG_SIG_WARN_ONLY) {
10103 					/* Must support both or none */
10104 					phba->cgn_reg_fpin = LPFC_CGN_FPIN_BOTH;
10105 					phba->cgn_reg_signal =
10106 						EDC_CG_SIG_NOTSUPPORTED;
10107 				} else {
10108 					phba->cgn_reg_signal =
10109 						EDC_CG_SIG_WARN_ALARM;
10110 					phba->cgn_reg_fpin =
10111 						LPFC_CGN_FPIN_NONE;
10112 				}
10113 			}
10114 		}
10115 
10116 		/* Set the congestion initial signal and fpin values. */
10117 		phba->cgn_init_reg_fpin = phba->cgn_reg_fpin;
10118 		phba->cgn_init_reg_signal = phba->cgn_reg_signal;
10119 
10120 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
10121 				"6446 READ_CONFIG reg_sig x%x reg_fpin:x%x\n",
10122 				phba->cgn_reg_signal, phba->cgn_reg_fpin);
10123 
10124 		lpfc_map_topology(phba, rd_config);
10125 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10126 				"2003 cfg params Extents? %d "
10127 				"XRI(B:%d M:%d), "
10128 				"VPI(B:%d M:%d) "
10129 				"VFI(B:%d M:%d) "
10130 				"RPI(B:%d M:%d) "
10131 				"FCFI:%d EQ:%d CQ:%d WQ:%d RQ:%d lmt:x%x\n",
10132 				phba->sli4_hba.extents_in_use,
10133 				phba->sli4_hba.max_cfg_param.xri_base,
10134 				phba->sli4_hba.max_cfg_param.max_xri,
10135 				phba->sli4_hba.max_cfg_param.vpi_base,
10136 				phba->sli4_hba.max_cfg_param.max_vpi,
10137 				phba->sli4_hba.max_cfg_param.vfi_base,
10138 				phba->sli4_hba.max_cfg_param.max_vfi,
10139 				phba->sli4_hba.max_cfg_param.rpi_base,
10140 				phba->sli4_hba.max_cfg_param.max_rpi,
10141 				phba->sli4_hba.max_cfg_param.max_fcfi,
10142 				phba->sli4_hba.max_cfg_param.max_eq,
10143 				phba->sli4_hba.max_cfg_param.max_cq,
10144 				phba->sli4_hba.max_cfg_param.max_wq,
10145 				phba->sli4_hba.max_cfg_param.max_rq,
10146 				phba->lmt);
10147 
10148 		/*
10149 		 * Calculate queue resources based on how
10150 		 * many WQ/CQ/EQs are available.
10151 		 */
10152 		qmin = phba->sli4_hba.max_cfg_param.max_wq;
10153 		if (phba->sli4_hba.max_cfg_param.max_cq < qmin)
10154 			qmin = phba->sli4_hba.max_cfg_param.max_cq;
10155 		/*
10156 		 * Reserve 4 (ELS, NVME LS, MBOX, plus one extra) and
10157 		 * the remainder can be used for NVME / FCP.
10158 		 */
10159 		qmin -= 4;
10160 		if (phba->sli4_hba.max_cfg_param.max_eq < qmin)
10161 			qmin = phba->sli4_hba.max_cfg_param.max_eq;
10162 
10163 		/* Check to see if there is enough for default cfg */
10164 		if ((phba->cfg_irq_chann > qmin) ||
10165 		    (phba->cfg_hdw_queue > qmin)) {
10166 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10167 					"2005 Reducing Queues - "
10168 					"FW resource limitation: "
10169 					"WQ %d CQ %d EQ %d: min %d: "
10170 					"IRQ %d HDWQ %d\n",
10171 					phba->sli4_hba.max_cfg_param.max_wq,
10172 					phba->sli4_hba.max_cfg_param.max_cq,
10173 					phba->sli4_hba.max_cfg_param.max_eq,
10174 					qmin, phba->cfg_irq_chann,
10175 					phba->cfg_hdw_queue);
10176 
10177 			if (phba->cfg_irq_chann > qmin)
10178 				phba->cfg_irq_chann = qmin;
10179 			if (phba->cfg_hdw_queue > qmin)
10180 				phba->cfg_hdw_queue = qmin;
10181 		}
10182 	}
10183 
10184 	if (rc)
10185 		goto read_cfg_out;
10186 
10187 	/* Update link speed if forced link speed is supported */
10188 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
10189 	if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
10190 		forced_link_speed =
10191 			bf_get(lpfc_mbx_rd_conf_link_speed, rd_config);
10192 		if (forced_link_speed) {
10193 			phba->hba_flag |= HBA_FORCED_LINK_SPEED;
10194 
10195 			switch (forced_link_speed) {
10196 			case LINK_SPEED_1G:
10197 				phba->cfg_link_speed =
10198 					LPFC_USER_LINK_SPEED_1G;
10199 				break;
10200 			case LINK_SPEED_2G:
10201 				phba->cfg_link_speed =
10202 					LPFC_USER_LINK_SPEED_2G;
10203 				break;
10204 			case LINK_SPEED_4G:
10205 				phba->cfg_link_speed =
10206 					LPFC_USER_LINK_SPEED_4G;
10207 				break;
10208 			case LINK_SPEED_8G:
10209 				phba->cfg_link_speed =
10210 					LPFC_USER_LINK_SPEED_8G;
10211 				break;
10212 			case LINK_SPEED_10G:
10213 				phba->cfg_link_speed =
10214 					LPFC_USER_LINK_SPEED_10G;
10215 				break;
10216 			case LINK_SPEED_16G:
10217 				phba->cfg_link_speed =
10218 					LPFC_USER_LINK_SPEED_16G;
10219 				break;
10220 			case LINK_SPEED_32G:
10221 				phba->cfg_link_speed =
10222 					LPFC_USER_LINK_SPEED_32G;
10223 				break;
10224 			case LINK_SPEED_64G:
10225 				phba->cfg_link_speed =
10226 					LPFC_USER_LINK_SPEED_64G;
10227 				break;
10228 			case 0xffff:
10229 				phba->cfg_link_speed =
10230 					LPFC_USER_LINK_SPEED_AUTO;
10231 				break;
10232 			default:
10233 				lpfc_printf_log(phba, KERN_ERR,
10234 						LOG_TRACE_EVENT,
10235 						"0047 Unrecognized link "
10236 						"speed : %d\n",
10237 						forced_link_speed);
10238 				phba->cfg_link_speed =
10239 					LPFC_USER_LINK_SPEED_AUTO;
10240 			}
10241 		}
10242 	}
10243 
10244 	/* Reset the DFT_HBA_Q_DEPTH to the max xri  */
10245 	length = phba->sli4_hba.max_cfg_param.max_xri -
10246 			lpfc_sli4_get_els_iocb_cnt(phba);
10247 	if (phba->cfg_hba_queue_depth > length) {
10248 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
10249 				"3361 HBA queue depth changed from %d to %d\n",
10250 				phba->cfg_hba_queue_depth, length);
10251 		phba->cfg_hba_queue_depth = length;
10252 	}
10253 
10254 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) <
10255 	    LPFC_SLI_INTF_IF_TYPE_2)
10256 		goto read_cfg_out;
10257 
10258 	/* get the pf# and vf# for SLI4 if_type 2 port */
10259 	length = (sizeof(struct lpfc_mbx_get_func_cfg) -
10260 		  sizeof(struct lpfc_sli4_cfg_mhdr));
10261 	lpfc_sli4_config(phba, pmb, LPFC_MBOX_SUBSYSTEM_COMMON,
10262 			 LPFC_MBOX_OPCODE_GET_FUNCTION_CONFIG,
10263 			 length, LPFC_SLI4_MBX_EMBED);
10264 
10265 	rc2 = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
10266 	shdr = (union lpfc_sli4_cfg_shdr *)
10267 				&pmb->u.mqe.un.sli4_config.header.cfg_shdr;
10268 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
10269 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
10270 	if (rc2 || shdr_status || shdr_add_status) {
10271 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10272 				"3026 Mailbox failed , mbxCmd x%x "
10273 				"GET_FUNCTION_CONFIG, mbxStatus x%x\n",
10274 				bf_get(lpfc_mqe_command, &pmb->u.mqe),
10275 				bf_get(lpfc_mqe_status, &pmb->u.mqe));
10276 		goto read_cfg_out;
10277 	}
10278 
10279 	/* search for fc_fcoe resrouce descriptor */
10280 	get_func_cfg = &pmb->u.mqe.un.get_func_cfg;
10281 
10282 	pdesc_0 = (char *)&get_func_cfg->func_cfg.desc[0];
10283 	desc = (struct lpfc_rsrc_desc_fcfcoe *)pdesc_0;
10284 	length = bf_get(lpfc_rsrc_desc_fcfcoe_length, desc);
10285 	if (length == LPFC_RSRC_DESC_TYPE_FCFCOE_V0_RSVD)
10286 		length = LPFC_RSRC_DESC_TYPE_FCFCOE_V0_LENGTH;
10287 	else if (length != LPFC_RSRC_DESC_TYPE_FCFCOE_V1_LENGTH)
10288 		goto read_cfg_out;
10289 
10290 	for (i = 0; i < LPFC_RSRC_DESC_MAX_NUM; i++) {
10291 		desc = (struct lpfc_rsrc_desc_fcfcoe *)(pdesc_0 + length * i);
10292 		if (LPFC_RSRC_DESC_TYPE_FCFCOE ==
10293 		    bf_get(lpfc_rsrc_desc_fcfcoe_type, desc)) {
10294 			phba->sli4_hba.iov.pf_number =
10295 				bf_get(lpfc_rsrc_desc_fcfcoe_pfnum, desc);
10296 			phba->sli4_hba.iov.vf_number =
10297 				bf_get(lpfc_rsrc_desc_fcfcoe_vfnum, desc);
10298 			break;
10299 		}
10300 	}
10301 
10302 	if (i < LPFC_RSRC_DESC_MAX_NUM)
10303 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10304 				"3027 GET_FUNCTION_CONFIG: pf_number:%d, "
10305 				"vf_number:%d\n", phba->sli4_hba.iov.pf_number,
10306 				phba->sli4_hba.iov.vf_number);
10307 	else
10308 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10309 				"3028 GET_FUNCTION_CONFIG: failed to find "
10310 				"Resource Descriptor:x%x\n",
10311 				LPFC_RSRC_DESC_TYPE_FCFCOE);
10312 
10313 read_cfg_out:
10314 	mempool_free(pmb, phba->mbox_mem_pool);
10315 	return rc;
10316 }
10317 
10318 /**
10319  * lpfc_setup_endian_order - Write endian order to an SLI4 if_type 0 port.
10320  * @phba: pointer to lpfc hba data structure.
10321  *
10322  * This routine is invoked to setup the port-side endian order when
10323  * the port if_type is 0.  This routine has no function for other
10324  * if_types.
10325  *
10326  * Return codes
10327  * 	0 - successful
10328  * 	-ENOMEM - No available memory
10329  *      -EIO - The mailbox failed to complete successfully.
10330  **/
10331 static int
10332 lpfc_setup_endian_order(struct lpfc_hba *phba)
10333 {
10334 	LPFC_MBOXQ_t *mboxq;
10335 	uint32_t if_type, rc = 0;
10336 	uint32_t endian_mb_data[2] = {HOST_ENDIAN_LOW_WORD0,
10337 				      HOST_ENDIAN_HIGH_WORD1};
10338 
10339 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
10340 	switch (if_type) {
10341 	case LPFC_SLI_INTF_IF_TYPE_0:
10342 		mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
10343 						       GFP_KERNEL);
10344 		if (!mboxq) {
10345 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10346 					"0492 Unable to allocate memory for "
10347 					"issuing SLI_CONFIG_SPECIAL mailbox "
10348 					"command\n");
10349 			return -ENOMEM;
10350 		}
10351 
10352 		/*
10353 		 * The SLI4_CONFIG_SPECIAL mailbox command requires the first
10354 		 * two words to contain special data values and no other data.
10355 		 */
10356 		memset(mboxq, 0, sizeof(LPFC_MBOXQ_t));
10357 		memcpy(&mboxq->u.mqe, &endian_mb_data, sizeof(endian_mb_data));
10358 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
10359 		if (rc != MBX_SUCCESS) {
10360 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10361 					"0493 SLI_CONFIG_SPECIAL mailbox "
10362 					"failed with status x%x\n",
10363 					rc);
10364 			rc = -EIO;
10365 		}
10366 		mempool_free(mboxq, phba->mbox_mem_pool);
10367 		break;
10368 	case LPFC_SLI_INTF_IF_TYPE_6:
10369 	case LPFC_SLI_INTF_IF_TYPE_2:
10370 	case LPFC_SLI_INTF_IF_TYPE_1:
10371 	default:
10372 		break;
10373 	}
10374 	return rc;
10375 }
10376 
10377 /**
10378  * lpfc_sli4_queue_verify - Verify and update EQ counts
10379  * @phba: pointer to lpfc hba data structure.
10380  *
10381  * This routine is invoked to check the user settable queue counts for EQs.
10382  * After this routine is called the counts will be set to valid values that
10383  * adhere to the constraints of the system's interrupt vectors and the port's
10384  * queue resources.
10385  *
10386  * Return codes
10387  *      0 - successful
10388  *      -ENOMEM - No available memory
10389  **/
10390 static int
10391 lpfc_sli4_queue_verify(struct lpfc_hba *phba)
10392 {
10393 	/*
10394 	 * Sanity check for configured queue parameters against the run-time
10395 	 * device parameters
10396 	 */
10397 
10398 	if (phba->nvmet_support) {
10399 		if (phba->cfg_hdw_queue < phba->cfg_nvmet_mrq)
10400 			phba->cfg_nvmet_mrq = phba->cfg_hdw_queue;
10401 		if (phba->cfg_nvmet_mrq > LPFC_NVMET_MRQ_MAX)
10402 			phba->cfg_nvmet_mrq = LPFC_NVMET_MRQ_MAX;
10403 	}
10404 
10405 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10406 			"2574 IO channels: hdwQ %d IRQ %d MRQ: %d\n",
10407 			phba->cfg_hdw_queue, phba->cfg_irq_chann,
10408 			phba->cfg_nvmet_mrq);
10409 
10410 	/* Get EQ depth from module parameter, fake the default for now */
10411 	phba->sli4_hba.eq_esize = LPFC_EQE_SIZE_4B;
10412 	phba->sli4_hba.eq_ecount = LPFC_EQE_DEF_COUNT;
10413 
10414 	/* Get CQ depth from module parameter, fake the default for now */
10415 	phba->sli4_hba.cq_esize = LPFC_CQE_SIZE;
10416 	phba->sli4_hba.cq_ecount = LPFC_CQE_DEF_COUNT;
10417 	return 0;
10418 }
10419 
10420 static int
10421 lpfc_alloc_io_wq_cq(struct lpfc_hba *phba, int idx)
10422 {
10423 	struct lpfc_queue *qdesc;
10424 	u32 wqesize;
10425 	int cpu;
10426 
10427 	cpu = lpfc_find_cpu_handle(phba, idx, LPFC_FIND_BY_HDWQ);
10428 	/* Create Fast Path IO CQs */
10429 	if (phba->enab_exp_wqcq_pages)
10430 		/* Increase the CQ size when WQEs contain an embedded cdb */
10431 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_EXPANDED_PAGE_SIZE,
10432 					      phba->sli4_hba.cq_esize,
10433 					      LPFC_CQE_EXP_COUNT, cpu);
10434 
10435 	else
10436 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10437 					      phba->sli4_hba.cq_esize,
10438 					      phba->sli4_hba.cq_ecount, cpu);
10439 	if (!qdesc) {
10440 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10441 				"0499 Failed allocate fast-path IO CQ (%d)\n",
10442 				idx);
10443 		return 1;
10444 	}
10445 	qdesc->qe_valid = 1;
10446 	qdesc->hdwq = idx;
10447 	qdesc->chann = cpu;
10448 	phba->sli4_hba.hdwq[idx].io_cq = qdesc;
10449 
10450 	/* Create Fast Path IO WQs */
10451 	if (phba->enab_exp_wqcq_pages) {
10452 		/* Increase the WQ size when WQEs contain an embedded cdb */
10453 		wqesize = (phba->fcp_embed_io) ?
10454 			LPFC_WQE128_SIZE : phba->sli4_hba.wq_esize;
10455 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_EXPANDED_PAGE_SIZE,
10456 					      wqesize,
10457 					      LPFC_WQE_EXP_COUNT, cpu);
10458 	} else
10459 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10460 					      phba->sli4_hba.wq_esize,
10461 					      phba->sli4_hba.wq_ecount, cpu);
10462 
10463 	if (!qdesc) {
10464 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10465 				"0503 Failed allocate fast-path IO WQ (%d)\n",
10466 				idx);
10467 		return 1;
10468 	}
10469 	qdesc->hdwq = idx;
10470 	qdesc->chann = cpu;
10471 	phba->sli4_hba.hdwq[idx].io_wq = qdesc;
10472 	list_add_tail(&qdesc->wq_list, &phba->sli4_hba.lpfc_wq_list);
10473 	return 0;
10474 }
10475 
10476 /**
10477  * lpfc_sli4_queue_create - Create all the SLI4 queues
10478  * @phba: pointer to lpfc hba data structure.
10479  *
10480  * This routine is invoked to allocate all the SLI4 queues for the FCoE HBA
10481  * operation. For each SLI4 queue type, the parameters such as queue entry
10482  * count (queue depth) shall be taken from the module parameter. For now,
10483  * we just use some constant number as place holder.
10484  *
10485  * Return codes
10486  *      0 - successful
10487  *      -ENOMEM - No availble memory
10488  *      -EIO - The mailbox failed to complete successfully.
10489  **/
10490 int
10491 lpfc_sli4_queue_create(struct lpfc_hba *phba)
10492 {
10493 	struct lpfc_queue *qdesc;
10494 	int idx, cpu, eqcpu;
10495 	struct lpfc_sli4_hdw_queue *qp;
10496 	struct lpfc_vector_map_info *cpup;
10497 	struct lpfc_vector_map_info *eqcpup;
10498 	struct lpfc_eq_intr_info *eqi;
10499 
10500 	/*
10501 	 * Create HBA Record arrays.
10502 	 * Both NVME and FCP will share that same vectors / EQs
10503 	 */
10504 	phba->sli4_hba.mq_esize = LPFC_MQE_SIZE;
10505 	phba->sli4_hba.mq_ecount = LPFC_MQE_DEF_COUNT;
10506 	phba->sli4_hba.wq_esize = LPFC_WQE_SIZE;
10507 	phba->sli4_hba.wq_ecount = LPFC_WQE_DEF_COUNT;
10508 	phba->sli4_hba.rq_esize = LPFC_RQE_SIZE;
10509 	phba->sli4_hba.rq_ecount = LPFC_RQE_DEF_COUNT;
10510 	phba->sli4_hba.eq_esize = LPFC_EQE_SIZE_4B;
10511 	phba->sli4_hba.eq_ecount = LPFC_EQE_DEF_COUNT;
10512 	phba->sli4_hba.cq_esize = LPFC_CQE_SIZE;
10513 	phba->sli4_hba.cq_ecount = LPFC_CQE_DEF_COUNT;
10514 
10515 	if (!phba->sli4_hba.hdwq) {
10516 		phba->sli4_hba.hdwq = kcalloc(
10517 			phba->cfg_hdw_queue, sizeof(struct lpfc_sli4_hdw_queue),
10518 			GFP_KERNEL);
10519 		if (!phba->sli4_hba.hdwq) {
10520 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10521 					"6427 Failed allocate memory for "
10522 					"fast-path Hardware Queue array\n");
10523 			goto out_error;
10524 		}
10525 		/* Prepare hardware queues to take IO buffers */
10526 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10527 			qp = &phba->sli4_hba.hdwq[idx];
10528 			spin_lock_init(&qp->io_buf_list_get_lock);
10529 			spin_lock_init(&qp->io_buf_list_put_lock);
10530 			INIT_LIST_HEAD(&qp->lpfc_io_buf_list_get);
10531 			INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
10532 			qp->get_io_bufs = 0;
10533 			qp->put_io_bufs = 0;
10534 			qp->total_io_bufs = 0;
10535 			spin_lock_init(&qp->abts_io_buf_list_lock);
10536 			INIT_LIST_HEAD(&qp->lpfc_abts_io_buf_list);
10537 			qp->abts_scsi_io_bufs = 0;
10538 			qp->abts_nvme_io_bufs = 0;
10539 			INIT_LIST_HEAD(&qp->sgl_list);
10540 			INIT_LIST_HEAD(&qp->cmd_rsp_buf_list);
10541 			spin_lock_init(&qp->hdwq_lock);
10542 		}
10543 	}
10544 
10545 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
10546 		if (phba->nvmet_support) {
10547 			phba->sli4_hba.nvmet_cqset = kcalloc(
10548 					phba->cfg_nvmet_mrq,
10549 					sizeof(struct lpfc_queue *),
10550 					GFP_KERNEL);
10551 			if (!phba->sli4_hba.nvmet_cqset) {
10552 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10553 					"3121 Fail allocate memory for "
10554 					"fast-path CQ set array\n");
10555 				goto out_error;
10556 			}
10557 			phba->sli4_hba.nvmet_mrq_hdr = kcalloc(
10558 					phba->cfg_nvmet_mrq,
10559 					sizeof(struct lpfc_queue *),
10560 					GFP_KERNEL);
10561 			if (!phba->sli4_hba.nvmet_mrq_hdr) {
10562 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10563 					"3122 Fail allocate memory for "
10564 					"fast-path RQ set hdr array\n");
10565 				goto out_error;
10566 			}
10567 			phba->sli4_hba.nvmet_mrq_data = kcalloc(
10568 					phba->cfg_nvmet_mrq,
10569 					sizeof(struct lpfc_queue *),
10570 					GFP_KERNEL);
10571 			if (!phba->sli4_hba.nvmet_mrq_data) {
10572 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10573 					"3124 Fail allocate memory for "
10574 					"fast-path RQ set data array\n");
10575 				goto out_error;
10576 			}
10577 		}
10578 	}
10579 
10580 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_wq_list);
10581 
10582 	/* Create HBA Event Queues (EQs) */
10583 	for_each_present_cpu(cpu) {
10584 		/* We only want to create 1 EQ per vector, even though
10585 		 * multiple CPUs might be using that vector. so only
10586 		 * selects the CPUs that are LPFC_CPU_FIRST_IRQ.
10587 		 */
10588 		cpup = &phba->sli4_hba.cpu_map[cpu];
10589 		if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
10590 			continue;
10591 
10592 		/* Get a ptr to the Hardware Queue associated with this CPU */
10593 		qp = &phba->sli4_hba.hdwq[cpup->hdwq];
10594 
10595 		/* Allocate an EQ */
10596 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10597 					      phba->sli4_hba.eq_esize,
10598 					      phba->sli4_hba.eq_ecount, cpu);
10599 		if (!qdesc) {
10600 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10601 					"0497 Failed allocate EQ (%d)\n",
10602 					cpup->hdwq);
10603 			goto out_error;
10604 		}
10605 		qdesc->qe_valid = 1;
10606 		qdesc->hdwq = cpup->hdwq;
10607 		qdesc->chann = cpu; /* First CPU this EQ is affinitized to */
10608 		qdesc->last_cpu = qdesc->chann;
10609 
10610 		/* Save the allocated EQ in the Hardware Queue */
10611 		qp->hba_eq = qdesc;
10612 
10613 		eqi = per_cpu_ptr(phba->sli4_hba.eq_info, qdesc->last_cpu);
10614 		list_add(&qdesc->cpu_list, &eqi->list);
10615 	}
10616 
10617 	/* Now we need to populate the other Hardware Queues, that share
10618 	 * an IRQ vector, with the associated EQ ptr.
10619 	 */
10620 	for_each_present_cpu(cpu) {
10621 		cpup = &phba->sli4_hba.cpu_map[cpu];
10622 
10623 		/* Check for EQ already allocated in previous loop */
10624 		if (cpup->flag & LPFC_CPU_FIRST_IRQ)
10625 			continue;
10626 
10627 		/* Check for multiple CPUs per hdwq */
10628 		qp = &phba->sli4_hba.hdwq[cpup->hdwq];
10629 		if (qp->hba_eq)
10630 			continue;
10631 
10632 		/* We need to share an EQ for this hdwq */
10633 		eqcpu = lpfc_find_cpu_handle(phba, cpup->eq, LPFC_FIND_BY_EQ);
10634 		eqcpup = &phba->sli4_hba.cpu_map[eqcpu];
10635 		qp->hba_eq = phba->sli4_hba.hdwq[eqcpup->hdwq].hba_eq;
10636 	}
10637 
10638 	/* Allocate IO Path SLI4 CQ/WQs */
10639 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10640 		if (lpfc_alloc_io_wq_cq(phba, idx))
10641 			goto out_error;
10642 	}
10643 
10644 	if (phba->nvmet_support) {
10645 		for (idx = 0; idx < phba->cfg_nvmet_mrq; idx++) {
10646 			cpu = lpfc_find_cpu_handle(phba, idx,
10647 						   LPFC_FIND_BY_HDWQ);
10648 			qdesc = lpfc_sli4_queue_alloc(phba,
10649 						      LPFC_DEFAULT_PAGE_SIZE,
10650 						      phba->sli4_hba.cq_esize,
10651 						      phba->sli4_hba.cq_ecount,
10652 						      cpu);
10653 			if (!qdesc) {
10654 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10655 						"3142 Failed allocate NVME "
10656 						"CQ Set (%d)\n", idx);
10657 				goto out_error;
10658 			}
10659 			qdesc->qe_valid = 1;
10660 			qdesc->hdwq = idx;
10661 			qdesc->chann = cpu;
10662 			phba->sli4_hba.nvmet_cqset[idx] = qdesc;
10663 		}
10664 	}
10665 
10666 	/*
10667 	 * Create Slow Path Completion Queues (CQs)
10668 	 */
10669 
10670 	cpu = lpfc_find_cpu_handle(phba, 0, LPFC_FIND_BY_EQ);
10671 	/* Create slow-path Mailbox Command Complete Queue */
10672 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10673 				      phba->sli4_hba.cq_esize,
10674 				      phba->sli4_hba.cq_ecount, cpu);
10675 	if (!qdesc) {
10676 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10677 				"0500 Failed allocate slow-path mailbox CQ\n");
10678 		goto out_error;
10679 	}
10680 	qdesc->qe_valid = 1;
10681 	phba->sli4_hba.mbx_cq = qdesc;
10682 
10683 	/* Create slow-path ELS Complete Queue */
10684 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10685 				      phba->sli4_hba.cq_esize,
10686 				      phba->sli4_hba.cq_ecount, cpu);
10687 	if (!qdesc) {
10688 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10689 				"0501 Failed allocate slow-path ELS CQ\n");
10690 		goto out_error;
10691 	}
10692 	qdesc->qe_valid = 1;
10693 	qdesc->chann = cpu;
10694 	phba->sli4_hba.els_cq = qdesc;
10695 
10696 
10697 	/*
10698 	 * Create Slow Path Work Queues (WQs)
10699 	 */
10700 
10701 	/* Create Mailbox Command Queue */
10702 
10703 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10704 				      phba->sli4_hba.mq_esize,
10705 				      phba->sli4_hba.mq_ecount, cpu);
10706 	if (!qdesc) {
10707 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10708 				"0505 Failed allocate slow-path MQ\n");
10709 		goto out_error;
10710 	}
10711 	qdesc->chann = cpu;
10712 	phba->sli4_hba.mbx_wq = qdesc;
10713 
10714 	/*
10715 	 * Create ELS Work Queues
10716 	 */
10717 
10718 	/* Create slow-path ELS Work Queue */
10719 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10720 				      phba->sli4_hba.wq_esize,
10721 				      phba->sli4_hba.wq_ecount, cpu);
10722 	if (!qdesc) {
10723 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10724 				"0504 Failed allocate slow-path ELS WQ\n");
10725 		goto out_error;
10726 	}
10727 	qdesc->chann = cpu;
10728 	phba->sli4_hba.els_wq = qdesc;
10729 	list_add_tail(&qdesc->wq_list, &phba->sli4_hba.lpfc_wq_list);
10730 
10731 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
10732 		/* Create NVME LS Complete Queue */
10733 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10734 					      phba->sli4_hba.cq_esize,
10735 					      phba->sli4_hba.cq_ecount, cpu);
10736 		if (!qdesc) {
10737 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10738 					"6079 Failed allocate NVME LS CQ\n");
10739 			goto out_error;
10740 		}
10741 		qdesc->chann = cpu;
10742 		qdesc->qe_valid = 1;
10743 		phba->sli4_hba.nvmels_cq = qdesc;
10744 
10745 		/* Create NVME LS Work Queue */
10746 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10747 					      phba->sli4_hba.wq_esize,
10748 					      phba->sli4_hba.wq_ecount, cpu);
10749 		if (!qdesc) {
10750 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10751 					"6080 Failed allocate NVME LS WQ\n");
10752 			goto out_error;
10753 		}
10754 		qdesc->chann = cpu;
10755 		phba->sli4_hba.nvmels_wq = qdesc;
10756 		list_add_tail(&qdesc->wq_list, &phba->sli4_hba.lpfc_wq_list);
10757 	}
10758 
10759 	/*
10760 	 * Create Receive Queue (RQ)
10761 	 */
10762 
10763 	/* Create Receive Queue for header */
10764 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10765 				      phba->sli4_hba.rq_esize,
10766 				      phba->sli4_hba.rq_ecount, cpu);
10767 	if (!qdesc) {
10768 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10769 				"0506 Failed allocate receive HRQ\n");
10770 		goto out_error;
10771 	}
10772 	phba->sli4_hba.hdr_rq = qdesc;
10773 
10774 	/* Create Receive Queue for data */
10775 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10776 				      phba->sli4_hba.rq_esize,
10777 				      phba->sli4_hba.rq_ecount, cpu);
10778 	if (!qdesc) {
10779 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10780 				"0507 Failed allocate receive DRQ\n");
10781 		goto out_error;
10782 	}
10783 	phba->sli4_hba.dat_rq = qdesc;
10784 
10785 	if ((phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) &&
10786 	    phba->nvmet_support) {
10787 		for (idx = 0; idx < phba->cfg_nvmet_mrq; idx++) {
10788 			cpu = lpfc_find_cpu_handle(phba, idx,
10789 						   LPFC_FIND_BY_HDWQ);
10790 			/* Create NVMET Receive Queue for header */
10791 			qdesc = lpfc_sli4_queue_alloc(phba,
10792 						      LPFC_DEFAULT_PAGE_SIZE,
10793 						      phba->sli4_hba.rq_esize,
10794 						      LPFC_NVMET_RQE_DEF_COUNT,
10795 						      cpu);
10796 			if (!qdesc) {
10797 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10798 						"3146 Failed allocate "
10799 						"receive HRQ\n");
10800 				goto out_error;
10801 			}
10802 			qdesc->hdwq = idx;
10803 			phba->sli4_hba.nvmet_mrq_hdr[idx] = qdesc;
10804 
10805 			/* Only needed for header of RQ pair */
10806 			qdesc->rqbp = kzalloc_node(sizeof(*qdesc->rqbp),
10807 						   GFP_KERNEL,
10808 						   cpu_to_node(cpu));
10809 			if (qdesc->rqbp == NULL) {
10810 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10811 						"6131 Failed allocate "
10812 						"Header RQBP\n");
10813 				goto out_error;
10814 			}
10815 
10816 			/* Put list in known state in case driver load fails. */
10817 			INIT_LIST_HEAD(&qdesc->rqbp->rqb_buffer_list);
10818 
10819 			/* Create NVMET Receive Queue for data */
10820 			qdesc = lpfc_sli4_queue_alloc(phba,
10821 						      LPFC_DEFAULT_PAGE_SIZE,
10822 						      phba->sli4_hba.rq_esize,
10823 						      LPFC_NVMET_RQE_DEF_COUNT,
10824 						      cpu);
10825 			if (!qdesc) {
10826 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10827 						"3156 Failed allocate "
10828 						"receive DRQ\n");
10829 				goto out_error;
10830 			}
10831 			qdesc->hdwq = idx;
10832 			phba->sli4_hba.nvmet_mrq_data[idx] = qdesc;
10833 		}
10834 	}
10835 
10836 	/* Clear NVME stats */
10837 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
10838 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10839 			memset(&phba->sli4_hba.hdwq[idx].nvme_cstat, 0,
10840 			       sizeof(phba->sli4_hba.hdwq[idx].nvme_cstat));
10841 		}
10842 	}
10843 
10844 	/* Clear SCSI stats */
10845 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP) {
10846 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10847 			memset(&phba->sli4_hba.hdwq[idx].scsi_cstat, 0,
10848 			       sizeof(phba->sli4_hba.hdwq[idx].scsi_cstat));
10849 		}
10850 	}
10851 
10852 	return 0;
10853 
10854 out_error:
10855 	lpfc_sli4_queue_destroy(phba);
10856 	return -ENOMEM;
10857 }
10858 
10859 static inline void
10860 __lpfc_sli4_release_queue(struct lpfc_queue **qp)
10861 {
10862 	if (*qp != NULL) {
10863 		lpfc_sli4_queue_free(*qp);
10864 		*qp = NULL;
10865 	}
10866 }
10867 
10868 static inline void
10869 lpfc_sli4_release_queues(struct lpfc_queue ***qs, int max)
10870 {
10871 	int idx;
10872 
10873 	if (*qs == NULL)
10874 		return;
10875 
10876 	for (idx = 0; idx < max; idx++)
10877 		__lpfc_sli4_release_queue(&(*qs)[idx]);
10878 
10879 	kfree(*qs);
10880 	*qs = NULL;
10881 }
10882 
10883 static inline void
10884 lpfc_sli4_release_hdwq(struct lpfc_hba *phba)
10885 {
10886 	struct lpfc_sli4_hdw_queue *hdwq;
10887 	struct lpfc_queue *eq;
10888 	uint32_t idx;
10889 
10890 	hdwq = phba->sli4_hba.hdwq;
10891 
10892 	/* Loop thru all Hardware Queues */
10893 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10894 		/* Free the CQ/WQ corresponding to the Hardware Queue */
10895 		lpfc_sli4_queue_free(hdwq[idx].io_cq);
10896 		lpfc_sli4_queue_free(hdwq[idx].io_wq);
10897 		hdwq[idx].hba_eq = NULL;
10898 		hdwq[idx].io_cq = NULL;
10899 		hdwq[idx].io_wq = NULL;
10900 		if (phba->cfg_xpsgl && !phba->nvmet_support)
10901 			lpfc_free_sgl_per_hdwq(phba, &hdwq[idx]);
10902 		lpfc_free_cmd_rsp_buf_per_hdwq(phba, &hdwq[idx]);
10903 	}
10904 	/* Loop thru all IRQ vectors */
10905 	for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
10906 		/* Free the EQ corresponding to the IRQ vector */
10907 		eq = phba->sli4_hba.hba_eq_hdl[idx].eq;
10908 		lpfc_sli4_queue_free(eq);
10909 		phba->sli4_hba.hba_eq_hdl[idx].eq = NULL;
10910 	}
10911 }
10912 
10913 /**
10914  * lpfc_sli4_queue_destroy - Destroy all the SLI4 queues
10915  * @phba: pointer to lpfc hba data structure.
10916  *
10917  * This routine is invoked to release all the SLI4 queues with the FCoE HBA
10918  * operation.
10919  *
10920  * Return codes
10921  *      0 - successful
10922  *      -ENOMEM - No available memory
10923  *      -EIO - The mailbox failed to complete successfully.
10924  **/
10925 void
10926 lpfc_sli4_queue_destroy(struct lpfc_hba *phba)
10927 {
10928 	/*
10929 	 * Set FREE_INIT before beginning to free the queues.
10930 	 * Wait until the users of queues to acknowledge to
10931 	 * release queues by clearing FREE_WAIT.
10932 	 */
10933 	spin_lock_irq(&phba->hbalock);
10934 	phba->sli.sli_flag |= LPFC_QUEUE_FREE_INIT;
10935 	while (phba->sli.sli_flag & LPFC_QUEUE_FREE_WAIT) {
10936 		spin_unlock_irq(&phba->hbalock);
10937 		msleep(20);
10938 		spin_lock_irq(&phba->hbalock);
10939 	}
10940 	spin_unlock_irq(&phba->hbalock);
10941 
10942 	lpfc_sli4_cleanup_poll_list(phba);
10943 
10944 	/* Release HBA eqs */
10945 	if (phba->sli4_hba.hdwq)
10946 		lpfc_sli4_release_hdwq(phba);
10947 
10948 	if (phba->nvmet_support) {
10949 		lpfc_sli4_release_queues(&phba->sli4_hba.nvmet_cqset,
10950 					 phba->cfg_nvmet_mrq);
10951 
10952 		lpfc_sli4_release_queues(&phba->sli4_hba.nvmet_mrq_hdr,
10953 					 phba->cfg_nvmet_mrq);
10954 		lpfc_sli4_release_queues(&phba->sli4_hba.nvmet_mrq_data,
10955 					 phba->cfg_nvmet_mrq);
10956 	}
10957 
10958 	/* Release mailbox command work queue */
10959 	__lpfc_sli4_release_queue(&phba->sli4_hba.mbx_wq);
10960 
10961 	/* Release ELS work queue */
10962 	__lpfc_sli4_release_queue(&phba->sli4_hba.els_wq);
10963 
10964 	/* Release ELS work queue */
10965 	__lpfc_sli4_release_queue(&phba->sli4_hba.nvmels_wq);
10966 
10967 	/* Release unsolicited receive queue */
10968 	__lpfc_sli4_release_queue(&phba->sli4_hba.hdr_rq);
10969 	__lpfc_sli4_release_queue(&phba->sli4_hba.dat_rq);
10970 
10971 	/* Release ELS complete queue */
10972 	__lpfc_sli4_release_queue(&phba->sli4_hba.els_cq);
10973 
10974 	/* Release NVME LS complete queue */
10975 	__lpfc_sli4_release_queue(&phba->sli4_hba.nvmels_cq);
10976 
10977 	/* Release mailbox command complete queue */
10978 	__lpfc_sli4_release_queue(&phba->sli4_hba.mbx_cq);
10979 
10980 	/* Everything on this list has been freed */
10981 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_wq_list);
10982 
10983 	/* Done with freeing the queues */
10984 	spin_lock_irq(&phba->hbalock);
10985 	phba->sli.sli_flag &= ~LPFC_QUEUE_FREE_INIT;
10986 	spin_unlock_irq(&phba->hbalock);
10987 }
10988 
10989 int
10990 lpfc_free_rq_buffer(struct lpfc_hba *phba, struct lpfc_queue *rq)
10991 {
10992 	struct lpfc_rqb *rqbp;
10993 	struct lpfc_dmabuf *h_buf;
10994 	struct rqb_dmabuf *rqb_buffer;
10995 
10996 	rqbp = rq->rqbp;
10997 	while (!list_empty(&rqbp->rqb_buffer_list)) {
10998 		list_remove_head(&rqbp->rqb_buffer_list, h_buf,
10999 				 struct lpfc_dmabuf, list);
11000 
11001 		rqb_buffer = container_of(h_buf, struct rqb_dmabuf, hbuf);
11002 		(rqbp->rqb_free_buffer)(phba, rqb_buffer);
11003 		rqbp->buffer_count--;
11004 	}
11005 	return 1;
11006 }
11007 
11008 static int
11009 lpfc_create_wq_cq(struct lpfc_hba *phba, struct lpfc_queue *eq,
11010 	struct lpfc_queue *cq, struct lpfc_queue *wq, uint16_t *cq_map,
11011 	int qidx, uint32_t qtype)
11012 {
11013 	struct lpfc_sli_ring *pring;
11014 	int rc;
11015 
11016 	if (!eq || !cq || !wq) {
11017 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11018 			"6085 Fast-path %s (%d) not allocated\n",
11019 			((eq) ? ((cq) ? "WQ" : "CQ") : "EQ"), qidx);
11020 		return -ENOMEM;
11021 	}
11022 
11023 	/* create the Cq first */
11024 	rc = lpfc_cq_create(phba, cq, eq,
11025 			(qtype == LPFC_MBOX) ? LPFC_MCQ : LPFC_WCQ, qtype);
11026 	if (rc) {
11027 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11028 				"6086 Failed setup of CQ (%d), rc = 0x%x\n",
11029 				qidx, (uint32_t)rc);
11030 		return rc;
11031 	}
11032 
11033 	if (qtype != LPFC_MBOX) {
11034 		/* Setup cq_map for fast lookup */
11035 		if (cq_map)
11036 			*cq_map = cq->queue_id;
11037 
11038 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11039 			"6087 CQ setup: cq[%d]-id=%d, parent eq[%d]-id=%d\n",
11040 			qidx, cq->queue_id, qidx, eq->queue_id);
11041 
11042 		/* create the wq */
11043 		rc = lpfc_wq_create(phba, wq, cq, qtype);
11044 		if (rc) {
11045 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11046 				"4618 Fail setup fastpath WQ (%d), rc = 0x%x\n",
11047 				qidx, (uint32_t)rc);
11048 			/* no need to tear down cq - caller will do so */
11049 			return rc;
11050 		}
11051 
11052 		/* Bind this CQ/WQ to the NVME ring */
11053 		pring = wq->pring;
11054 		pring->sli.sli4.wqp = (void *)wq;
11055 		cq->pring = pring;
11056 
11057 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11058 			"2593 WQ setup: wq[%d]-id=%d assoc=%d, cq[%d]-id=%d\n",
11059 			qidx, wq->queue_id, wq->assoc_qid, qidx, cq->queue_id);
11060 	} else {
11061 		rc = lpfc_mq_create(phba, wq, cq, LPFC_MBOX);
11062 		if (rc) {
11063 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11064 					"0539 Failed setup of slow-path MQ: "
11065 					"rc = 0x%x\n", rc);
11066 			/* no need to tear down cq - caller will do so */
11067 			return rc;
11068 		}
11069 
11070 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11071 			"2589 MBX MQ setup: wq-id=%d, parent cq-id=%d\n",
11072 			phba->sli4_hba.mbx_wq->queue_id,
11073 			phba->sli4_hba.mbx_cq->queue_id);
11074 	}
11075 
11076 	return 0;
11077 }
11078 
11079 /**
11080  * lpfc_setup_cq_lookup - Setup the CQ lookup table
11081  * @phba: pointer to lpfc hba data structure.
11082  *
11083  * This routine will populate the cq_lookup table by all
11084  * available CQ queue_id's.
11085  **/
11086 static void
11087 lpfc_setup_cq_lookup(struct lpfc_hba *phba)
11088 {
11089 	struct lpfc_queue *eq, *childq;
11090 	int qidx;
11091 
11092 	memset(phba->sli4_hba.cq_lookup, 0,
11093 	       (sizeof(struct lpfc_queue *) * (phba->sli4_hba.cq_max + 1)));
11094 	/* Loop thru all IRQ vectors */
11095 	for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
11096 		/* Get the EQ corresponding to the IRQ vector */
11097 		eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
11098 		if (!eq)
11099 			continue;
11100 		/* Loop through all CQs associated with that EQ */
11101 		list_for_each_entry(childq, &eq->child_list, list) {
11102 			if (childq->queue_id > phba->sli4_hba.cq_max)
11103 				continue;
11104 			if (childq->subtype == LPFC_IO)
11105 				phba->sli4_hba.cq_lookup[childq->queue_id] =
11106 					childq;
11107 		}
11108 	}
11109 }
11110 
11111 /**
11112  * lpfc_sli4_queue_setup - Set up all the SLI4 queues
11113  * @phba: pointer to lpfc hba data structure.
11114  *
11115  * This routine is invoked to set up all the SLI4 queues for the FCoE HBA
11116  * operation.
11117  *
11118  * Return codes
11119  *      0 - successful
11120  *      -ENOMEM - No available memory
11121  *      -EIO - The mailbox failed to complete successfully.
11122  **/
11123 int
11124 lpfc_sli4_queue_setup(struct lpfc_hba *phba)
11125 {
11126 	uint32_t shdr_status, shdr_add_status;
11127 	union lpfc_sli4_cfg_shdr *shdr;
11128 	struct lpfc_vector_map_info *cpup;
11129 	struct lpfc_sli4_hdw_queue *qp;
11130 	LPFC_MBOXQ_t *mboxq;
11131 	int qidx, cpu;
11132 	uint32_t length, usdelay;
11133 	int rc = -ENOMEM;
11134 
11135 	/* Check for dual-ULP support */
11136 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
11137 	if (!mboxq) {
11138 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11139 				"3249 Unable to allocate memory for "
11140 				"QUERY_FW_CFG mailbox command\n");
11141 		return -ENOMEM;
11142 	}
11143 	length = (sizeof(struct lpfc_mbx_query_fw_config) -
11144 		  sizeof(struct lpfc_sli4_cfg_mhdr));
11145 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
11146 			 LPFC_MBOX_OPCODE_QUERY_FW_CFG,
11147 			 length, LPFC_SLI4_MBX_EMBED);
11148 
11149 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
11150 
11151 	shdr = (union lpfc_sli4_cfg_shdr *)
11152 			&mboxq->u.mqe.un.sli4_config.header.cfg_shdr;
11153 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
11154 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
11155 	if (shdr_status || shdr_add_status || rc) {
11156 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11157 				"3250 QUERY_FW_CFG mailbox failed with status "
11158 				"x%x add_status x%x, mbx status x%x\n",
11159 				shdr_status, shdr_add_status, rc);
11160 		mempool_free(mboxq, phba->mbox_mem_pool);
11161 		rc = -ENXIO;
11162 		goto out_error;
11163 	}
11164 
11165 	phba->sli4_hba.fw_func_mode =
11166 			mboxq->u.mqe.un.query_fw_cfg.rsp.function_mode;
11167 	phba->sli4_hba.ulp0_mode = mboxq->u.mqe.un.query_fw_cfg.rsp.ulp0_mode;
11168 	phba->sli4_hba.ulp1_mode = mboxq->u.mqe.un.query_fw_cfg.rsp.ulp1_mode;
11169 	phba->sli4_hba.physical_port =
11170 			mboxq->u.mqe.un.query_fw_cfg.rsp.physical_port;
11171 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11172 			"3251 QUERY_FW_CFG: func_mode:x%x, ulp0_mode:x%x, "
11173 			"ulp1_mode:x%x\n", phba->sli4_hba.fw_func_mode,
11174 			phba->sli4_hba.ulp0_mode, phba->sli4_hba.ulp1_mode);
11175 
11176 	mempool_free(mboxq, phba->mbox_mem_pool);
11177 
11178 	/*
11179 	 * Set up HBA Event Queues (EQs)
11180 	 */
11181 	qp = phba->sli4_hba.hdwq;
11182 
11183 	/* Set up HBA event queue */
11184 	if (!qp) {
11185 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11186 				"3147 Fast-path EQs not allocated\n");
11187 		rc = -ENOMEM;
11188 		goto out_error;
11189 	}
11190 
11191 	/* Loop thru all IRQ vectors */
11192 	for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
11193 		/* Create HBA Event Queues (EQs) in order */
11194 		for_each_present_cpu(cpu) {
11195 			cpup = &phba->sli4_hba.cpu_map[cpu];
11196 
11197 			/* Look for the CPU thats using that vector with
11198 			 * LPFC_CPU_FIRST_IRQ set.
11199 			 */
11200 			if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
11201 				continue;
11202 			if (qidx != cpup->eq)
11203 				continue;
11204 
11205 			/* Create an EQ for that vector */
11206 			rc = lpfc_eq_create(phba, qp[cpup->hdwq].hba_eq,
11207 					    phba->cfg_fcp_imax);
11208 			if (rc) {
11209 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11210 						"0523 Failed setup of fast-path"
11211 						" EQ (%d), rc = 0x%x\n",
11212 						cpup->eq, (uint32_t)rc);
11213 				goto out_destroy;
11214 			}
11215 
11216 			/* Save the EQ for that vector in the hba_eq_hdl */
11217 			phba->sli4_hba.hba_eq_hdl[cpup->eq].eq =
11218 				qp[cpup->hdwq].hba_eq;
11219 
11220 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11221 					"2584 HBA EQ setup: queue[%d]-id=%d\n",
11222 					cpup->eq,
11223 					qp[cpup->hdwq].hba_eq->queue_id);
11224 		}
11225 	}
11226 
11227 	/* Loop thru all Hardware Queues */
11228 	for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
11229 		cpu = lpfc_find_cpu_handle(phba, qidx, LPFC_FIND_BY_HDWQ);
11230 		cpup = &phba->sli4_hba.cpu_map[cpu];
11231 
11232 		/* Create the CQ/WQ corresponding to the Hardware Queue */
11233 		rc = lpfc_create_wq_cq(phba,
11234 				       phba->sli4_hba.hdwq[cpup->hdwq].hba_eq,
11235 				       qp[qidx].io_cq,
11236 				       qp[qidx].io_wq,
11237 				       &phba->sli4_hba.hdwq[qidx].io_cq_map,
11238 				       qidx,
11239 				       LPFC_IO);
11240 		if (rc) {
11241 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11242 					"0535 Failed to setup fastpath "
11243 					"IO WQ/CQ (%d), rc = 0x%x\n",
11244 					qidx, (uint32_t)rc);
11245 			goto out_destroy;
11246 		}
11247 	}
11248 
11249 	/*
11250 	 * Set up Slow Path Complete Queues (CQs)
11251 	 */
11252 
11253 	/* Set up slow-path MBOX CQ/MQ */
11254 
11255 	if (!phba->sli4_hba.mbx_cq || !phba->sli4_hba.mbx_wq) {
11256 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11257 				"0528 %s not allocated\n",
11258 				phba->sli4_hba.mbx_cq ?
11259 				"Mailbox WQ" : "Mailbox CQ");
11260 		rc = -ENOMEM;
11261 		goto out_destroy;
11262 	}
11263 
11264 	rc = lpfc_create_wq_cq(phba, qp[0].hba_eq,
11265 			       phba->sli4_hba.mbx_cq,
11266 			       phba->sli4_hba.mbx_wq,
11267 			       NULL, 0, LPFC_MBOX);
11268 	if (rc) {
11269 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11270 			"0529 Failed setup of mailbox WQ/CQ: rc = 0x%x\n",
11271 			(uint32_t)rc);
11272 		goto out_destroy;
11273 	}
11274 	if (phba->nvmet_support) {
11275 		if (!phba->sli4_hba.nvmet_cqset) {
11276 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11277 					"3165 Fast-path NVME CQ Set "
11278 					"array not allocated\n");
11279 			rc = -ENOMEM;
11280 			goto out_destroy;
11281 		}
11282 		if (phba->cfg_nvmet_mrq > 1) {
11283 			rc = lpfc_cq_create_set(phba,
11284 					phba->sli4_hba.nvmet_cqset,
11285 					qp,
11286 					LPFC_WCQ, LPFC_NVMET);
11287 			if (rc) {
11288 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11289 						"3164 Failed setup of NVME CQ "
11290 						"Set, rc = 0x%x\n",
11291 						(uint32_t)rc);
11292 				goto out_destroy;
11293 			}
11294 		} else {
11295 			/* Set up NVMET Receive Complete Queue */
11296 			rc = lpfc_cq_create(phba, phba->sli4_hba.nvmet_cqset[0],
11297 					    qp[0].hba_eq,
11298 					    LPFC_WCQ, LPFC_NVMET);
11299 			if (rc) {
11300 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11301 						"6089 Failed setup NVMET CQ: "
11302 						"rc = 0x%x\n", (uint32_t)rc);
11303 				goto out_destroy;
11304 			}
11305 			phba->sli4_hba.nvmet_cqset[0]->chann = 0;
11306 
11307 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11308 					"6090 NVMET CQ setup: cq-id=%d, "
11309 					"parent eq-id=%d\n",
11310 					phba->sli4_hba.nvmet_cqset[0]->queue_id,
11311 					qp[0].hba_eq->queue_id);
11312 		}
11313 	}
11314 
11315 	/* Set up slow-path ELS WQ/CQ */
11316 	if (!phba->sli4_hba.els_cq || !phba->sli4_hba.els_wq) {
11317 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11318 				"0530 ELS %s not allocated\n",
11319 				phba->sli4_hba.els_cq ? "WQ" : "CQ");
11320 		rc = -ENOMEM;
11321 		goto out_destroy;
11322 	}
11323 	rc = lpfc_create_wq_cq(phba, qp[0].hba_eq,
11324 			       phba->sli4_hba.els_cq,
11325 			       phba->sli4_hba.els_wq,
11326 			       NULL, 0, LPFC_ELS);
11327 	if (rc) {
11328 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11329 				"0525 Failed setup of ELS WQ/CQ: rc = 0x%x\n",
11330 				(uint32_t)rc);
11331 		goto out_destroy;
11332 	}
11333 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11334 			"2590 ELS WQ setup: wq-id=%d, parent cq-id=%d\n",
11335 			phba->sli4_hba.els_wq->queue_id,
11336 			phba->sli4_hba.els_cq->queue_id);
11337 
11338 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
11339 		/* Set up NVME LS Complete Queue */
11340 		if (!phba->sli4_hba.nvmels_cq || !phba->sli4_hba.nvmels_wq) {
11341 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11342 					"6091 LS %s not allocated\n",
11343 					phba->sli4_hba.nvmels_cq ? "WQ" : "CQ");
11344 			rc = -ENOMEM;
11345 			goto out_destroy;
11346 		}
11347 		rc = lpfc_create_wq_cq(phba, qp[0].hba_eq,
11348 				       phba->sli4_hba.nvmels_cq,
11349 				       phba->sli4_hba.nvmels_wq,
11350 				       NULL, 0, LPFC_NVME_LS);
11351 		if (rc) {
11352 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11353 					"0526 Failed setup of NVVME LS WQ/CQ: "
11354 					"rc = 0x%x\n", (uint32_t)rc);
11355 			goto out_destroy;
11356 		}
11357 
11358 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11359 				"6096 ELS WQ setup: wq-id=%d, "
11360 				"parent cq-id=%d\n",
11361 				phba->sli4_hba.nvmels_wq->queue_id,
11362 				phba->sli4_hba.nvmels_cq->queue_id);
11363 	}
11364 
11365 	/*
11366 	 * Create NVMET Receive Queue (RQ)
11367 	 */
11368 	if (phba->nvmet_support) {
11369 		if ((!phba->sli4_hba.nvmet_cqset) ||
11370 		    (!phba->sli4_hba.nvmet_mrq_hdr) ||
11371 		    (!phba->sli4_hba.nvmet_mrq_data)) {
11372 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11373 					"6130 MRQ CQ Queues not "
11374 					"allocated\n");
11375 			rc = -ENOMEM;
11376 			goto out_destroy;
11377 		}
11378 		if (phba->cfg_nvmet_mrq > 1) {
11379 			rc = lpfc_mrq_create(phba,
11380 					     phba->sli4_hba.nvmet_mrq_hdr,
11381 					     phba->sli4_hba.nvmet_mrq_data,
11382 					     phba->sli4_hba.nvmet_cqset,
11383 					     LPFC_NVMET);
11384 			if (rc) {
11385 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11386 						"6098 Failed setup of NVMET "
11387 						"MRQ: rc = 0x%x\n",
11388 						(uint32_t)rc);
11389 				goto out_destroy;
11390 			}
11391 
11392 		} else {
11393 			rc = lpfc_rq_create(phba,
11394 					    phba->sli4_hba.nvmet_mrq_hdr[0],
11395 					    phba->sli4_hba.nvmet_mrq_data[0],
11396 					    phba->sli4_hba.nvmet_cqset[0],
11397 					    LPFC_NVMET);
11398 			if (rc) {
11399 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11400 						"6057 Failed setup of NVMET "
11401 						"Receive Queue: rc = 0x%x\n",
11402 						(uint32_t)rc);
11403 				goto out_destroy;
11404 			}
11405 
11406 			lpfc_printf_log(
11407 				phba, KERN_INFO, LOG_INIT,
11408 				"6099 NVMET RQ setup: hdr-rq-id=%d, "
11409 				"dat-rq-id=%d parent cq-id=%d\n",
11410 				phba->sli4_hba.nvmet_mrq_hdr[0]->queue_id,
11411 				phba->sli4_hba.nvmet_mrq_data[0]->queue_id,
11412 				phba->sli4_hba.nvmet_cqset[0]->queue_id);
11413 
11414 		}
11415 	}
11416 
11417 	if (!phba->sli4_hba.hdr_rq || !phba->sli4_hba.dat_rq) {
11418 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11419 				"0540 Receive Queue not allocated\n");
11420 		rc = -ENOMEM;
11421 		goto out_destroy;
11422 	}
11423 
11424 	rc = lpfc_rq_create(phba, phba->sli4_hba.hdr_rq, phba->sli4_hba.dat_rq,
11425 			    phba->sli4_hba.els_cq, LPFC_USOL);
11426 	if (rc) {
11427 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11428 				"0541 Failed setup of Receive Queue: "
11429 				"rc = 0x%x\n", (uint32_t)rc);
11430 		goto out_destroy;
11431 	}
11432 
11433 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11434 			"2592 USL RQ setup: hdr-rq-id=%d, dat-rq-id=%d "
11435 			"parent cq-id=%d\n",
11436 			phba->sli4_hba.hdr_rq->queue_id,
11437 			phba->sli4_hba.dat_rq->queue_id,
11438 			phba->sli4_hba.els_cq->queue_id);
11439 
11440 	if (phba->cfg_fcp_imax)
11441 		usdelay = LPFC_SEC_TO_USEC / phba->cfg_fcp_imax;
11442 	else
11443 		usdelay = 0;
11444 
11445 	for (qidx = 0; qidx < phba->cfg_irq_chann;
11446 	     qidx += LPFC_MAX_EQ_DELAY_EQID_CNT)
11447 		lpfc_modify_hba_eq_delay(phba, qidx, LPFC_MAX_EQ_DELAY_EQID_CNT,
11448 					 usdelay);
11449 
11450 	if (phba->sli4_hba.cq_max) {
11451 		kfree(phba->sli4_hba.cq_lookup);
11452 		phba->sli4_hba.cq_lookup = kcalloc((phba->sli4_hba.cq_max + 1),
11453 			sizeof(struct lpfc_queue *), GFP_KERNEL);
11454 		if (!phba->sli4_hba.cq_lookup) {
11455 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11456 					"0549 Failed setup of CQ Lookup table: "
11457 					"size 0x%x\n", phba->sli4_hba.cq_max);
11458 			rc = -ENOMEM;
11459 			goto out_destroy;
11460 		}
11461 		lpfc_setup_cq_lookup(phba);
11462 	}
11463 	return 0;
11464 
11465 out_destroy:
11466 	lpfc_sli4_queue_unset(phba);
11467 out_error:
11468 	return rc;
11469 }
11470 
11471 /**
11472  * lpfc_sli4_queue_unset - Unset all the SLI4 queues
11473  * @phba: pointer to lpfc hba data structure.
11474  *
11475  * This routine is invoked to unset all the SLI4 queues with the FCoE HBA
11476  * operation.
11477  *
11478  * Return codes
11479  *      0 - successful
11480  *      -ENOMEM - No available memory
11481  *      -EIO - The mailbox failed to complete successfully.
11482  **/
11483 void
11484 lpfc_sli4_queue_unset(struct lpfc_hba *phba)
11485 {
11486 	struct lpfc_sli4_hdw_queue *qp;
11487 	struct lpfc_queue *eq;
11488 	int qidx;
11489 
11490 	/* Unset mailbox command work queue */
11491 	if (phba->sli4_hba.mbx_wq)
11492 		lpfc_mq_destroy(phba, phba->sli4_hba.mbx_wq);
11493 
11494 	/* Unset NVME LS work queue */
11495 	if (phba->sli4_hba.nvmels_wq)
11496 		lpfc_wq_destroy(phba, phba->sli4_hba.nvmels_wq);
11497 
11498 	/* Unset ELS work queue */
11499 	if (phba->sli4_hba.els_wq)
11500 		lpfc_wq_destroy(phba, phba->sli4_hba.els_wq);
11501 
11502 	/* Unset unsolicited receive queue */
11503 	if (phba->sli4_hba.hdr_rq)
11504 		lpfc_rq_destroy(phba, phba->sli4_hba.hdr_rq,
11505 				phba->sli4_hba.dat_rq);
11506 
11507 	/* Unset mailbox command complete queue */
11508 	if (phba->sli4_hba.mbx_cq)
11509 		lpfc_cq_destroy(phba, phba->sli4_hba.mbx_cq);
11510 
11511 	/* Unset ELS complete queue */
11512 	if (phba->sli4_hba.els_cq)
11513 		lpfc_cq_destroy(phba, phba->sli4_hba.els_cq);
11514 
11515 	/* Unset NVME LS complete queue */
11516 	if (phba->sli4_hba.nvmels_cq)
11517 		lpfc_cq_destroy(phba, phba->sli4_hba.nvmels_cq);
11518 
11519 	if (phba->nvmet_support) {
11520 		/* Unset NVMET MRQ queue */
11521 		if (phba->sli4_hba.nvmet_mrq_hdr) {
11522 			for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++)
11523 				lpfc_rq_destroy(
11524 					phba,
11525 					phba->sli4_hba.nvmet_mrq_hdr[qidx],
11526 					phba->sli4_hba.nvmet_mrq_data[qidx]);
11527 		}
11528 
11529 		/* Unset NVMET CQ Set complete queue */
11530 		if (phba->sli4_hba.nvmet_cqset) {
11531 			for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++)
11532 				lpfc_cq_destroy(
11533 					phba, phba->sli4_hba.nvmet_cqset[qidx]);
11534 		}
11535 	}
11536 
11537 	/* Unset fast-path SLI4 queues */
11538 	if (phba->sli4_hba.hdwq) {
11539 		/* Loop thru all Hardware Queues */
11540 		for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
11541 			/* Destroy the CQ/WQ corresponding to Hardware Queue */
11542 			qp = &phba->sli4_hba.hdwq[qidx];
11543 			lpfc_wq_destroy(phba, qp->io_wq);
11544 			lpfc_cq_destroy(phba, qp->io_cq);
11545 		}
11546 		/* Loop thru all IRQ vectors */
11547 		for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
11548 			/* Destroy the EQ corresponding to the IRQ vector */
11549 			eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
11550 			lpfc_eq_destroy(phba, eq);
11551 		}
11552 	}
11553 
11554 	kfree(phba->sli4_hba.cq_lookup);
11555 	phba->sli4_hba.cq_lookup = NULL;
11556 	phba->sli4_hba.cq_max = 0;
11557 }
11558 
11559 /**
11560  * lpfc_sli4_cq_event_pool_create - Create completion-queue event free pool
11561  * @phba: pointer to lpfc hba data structure.
11562  *
11563  * This routine is invoked to allocate and set up a pool of completion queue
11564  * events. The body of the completion queue event is a completion queue entry
11565  * CQE. For now, this pool is used for the interrupt service routine to queue
11566  * the following HBA completion queue events for the worker thread to process:
11567  *   - Mailbox asynchronous events
11568  *   - Receive queue completion unsolicited events
11569  * Later, this can be used for all the slow-path events.
11570  *
11571  * Return codes
11572  *      0 - successful
11573  *      -ENOMEM - No available memory
11574  **/
11575 static int
11576 lpfc_sli4_cq_event_pool_create(struct lpfc_hba *phba)
11577 {
11578 	struct lpfc_cq_event *cq_event;
11579 	int i;
11580 
11581 	for (i = 0; i < (4 * phba->sli4_hba.cq_ecount); i++) {
11582 		cq_event = kmalloc(sizeof(struct lpfc_cq_event), GFP_KERNEL);
11583 		if (!cq_event)
11584 			goto out_pool_create_fail;
11585 		list_add_tail(&cq_event->list,
11586 			      &phba->sli4_hba.sp_cqe_event_pool);
11587 	}
11588 	return 0;
11589 
11590 out_pool_create_fail:
11591 	lpfc_sli4_cq_event_pool_destroy(phba);
11592 	return -ENOMEM;
11593 }
11594 
11595 /**
11596  * lpfc_sli4_cq_event_pool_destroy - Free completion-queue event free pool
11597  * @phba: pointer to lpfc hba data structure.
11598  *
11599  * This routine is invoked to free the pool of completion queue events at
11600  * driver unload time. Note that, it is the responsibility of the driver
11601  * cleanup routine to free all the outstanding completion-queue events
11602  * allocated from this pool back into the pool before invoking this routine
11603  * to destroy the pool.
11604  **/
11605 static void
11606 lpfc_sli4_cq_event_pool_destroy(struct lpfc_hba *phba)
11607 {
11608 	struct lpfc_cq_event *cq_event, *next_cq_event;
11609 
11610 	list_for_each_entry_safe(cq_event, next_cq_event,
11611 				 &phba->sli4_hba.sp_cqe_event_pool, list) {
11612 		list_del(&cq_event->list);
11613 		kfree(cq_event);
11614 	}
11615 }
11616 
11617 /**
11618  * __lpfc_sli4_cq_event_alloc - Allocate a completion-queue event from free pool
11619  * @phba: pointer to lpfc hba data structure.
11620  *
11621  * This routine is the lock free version of the API invoked to allocate a
11622  * completion-queue event from the free pool.
11623  *
11624  * Return: Pointer to the newly allocated completion-queue event if successful
11625  *         NULL otherwise.
11626  **/
11627 struct lpfc_cq_event *
11628 __lpfc_sli4_cq_event_alloc(struct lpfc_hba *phba)
11629 {
11630 	struct lpfc_cq_event *cq_event = NULL;
11631 
11632 	list_remove_head(&phba->sli4_hba.sp_cqe_event_pool, cq_event,
11633 			 struct lpfc_cq_event, list);
11634 	return cq_event;
11635 }
11636 
11637 /**
11638  * lpfc_sli4_cq_event_alloc - Allocate a completion-queue event from free pool
11639  * @phba: pointer to lpfc hba data structure.
11640  *
11641  * This routine is the lock version of the API invoked to allocate a
11642  * completion-queue event from the free pool.
11643  *
11644  * Return: Pointer to the newly allocated completion-queue event if successful
11645  *         NULL otherwise.
11646  **/
11647 struct lpfc_cq_event *
11648 lpfc_sli4_cq_event_alloc(struct lpfc_hba *phba)
11649 {
11650 	struct lpfc_cq_event *cq_event;
11651 	unsigned long iflags;
11652 
11653 	spin_lock_irqsave(&phba->hbalock, iflags);
11654 	cq_event = __lpfc_sli4_cq_event_alloc(phba);
11655 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11656 	return cq_event;
11657 }
11658 
11659 /**
11660  * __lpfc_sli4_cq_event_release - Release a completion-queue event to free pool
11661  * @phba: pointer to lpfc hba data structure.
11662  * @cq_event: pointer to the completion queue event to be freed.
11663  *
11664  * This routine is the lock free version of the API invoked to release a
11665  * completion-queue event back into the free pool.
11666  **/
11667 void
11668 __lpfc_sli4_cq_event_release(struct lpfc_hba *phba,
11669 			     struct lpfc_cq_event *cq_event)
11670 {
11671 	list_add_tail(&cq_event->list, &phba->sli4_hba.sp_cqe_event_pool);
11672 }
11673 
11674 /**
11675  * lpfc_sli4_cq_event_release - Release a completion-queue event to free pool
11676  * @phba: pointer to lpfc hba data structure.
11677  * @cq_event: pointer to the completion queue event to be freed.
11678  *
11679  * This routine is the lock version of the API invoked to release a
11680  * completion-queue event back into the free pool.
11681  **/
11682 void
11683 lpfc_sli4_cq_event_release(struct lpfc_hba *phba,
11684 			   struct lpfc_cq_event *cq_event)
11685 {
11686 	unsigned long iflags;
11687 	spin_lock_irqsave(&phba->hbalock, iflags);
11688 	__lpfc_sli4_cq_event_release(phba, cq_event);
11689 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11690 }
11691 
11692 /**
11693  * lpfc_sli4_cq_event_release_all - Release all cq events to the free pool
11694  * @phba: pointer to lpfc hba data structure.
11695  *
11696  * This routine is to free all the pending completion-queue events to the
11697  * back into the free pool for device reset.
11698  **/
11699 static void
11700 lpfc_sli4_cq_event_release_all(struct lpfc_hba *phba)
11701 {
11702 	LIST_HEAD(cq_event_list);
11703 	struct lpfc_cq_event *cq_event;
11704 	unsigned long iflags;
11705 
11706 	/* Retrieve all the pending WCQEs from pending WCQE lists */
11707 
11708 	/* Pending ELS XRI abort events */
11709 	spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
11710 	list_splice_init(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
11711 			 &cq_event_list);
11712 	spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
11713 
11714 	/* Pending asynnc events */
11715 	spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
11716 	list_splice_init(&phba->sli4_hba.sp_asynce_work_queue,
11717 			 &cq_event_list);
11718 	spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock, iflags);
11719 
11720 	while (!list_empty(&cq_event_list)) {
11721 		list_remove_head(&cq_event_list, cq_event,
11722 				 struct lpfc_cq_event, list);
11723 		lpfc_sli4_cq_event_release(phba, cq_event);
11724 	}
11725 }
11726 
11727 /**
11728  * lpfc_pci_function_reset - Reset pci function.
11729  * @phba: pointer to lpfc hba data structure.
11730  *
11731  * This routine is invoked to request a PCI function reset. It will destroys
11732  * all resources assigned to the PCI function which originates this request.
11733  *
11734  * Return codes
11735  *      0 - successful
11736  *      -ENOMEM - No available memory
11737  *      -EIO - The mailbox failed to complete successfully.
11738  **/
11739 int
11740 lpfc_pci_function_reset(struct lpfc_hba *phba)
11741 {
11742 	LPFC_MBOXQ_t *mboxq;
11743 	uint32_t rc = 0, if_type;
11744 	uint32_t shdr_status, shdr_add_status;
11745 	uint32_t rdy_chk;
11746 	uint32_t port_reset = 0;
11747 	union lpfc_sli4_cfg_shdr *shdr;
11748 	struct lpfc_register reg_data;
11749 	uint16_t devid;
11750 
11751 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
11752 	switch (if_type) {
11753 	case LPFC_SLI_INTF_IF_TYPE_0:
11754 		mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
11755 						       GFP_KERNEL);
11756 		if (!mboxq) {
11757 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11758 					"0494 Unable to allocate memory for "
11759 					"issuing SLI_FUNCTION_RESET mailbox "
11760 					"command\n");
11761 			return -ENOMEM;
11762 		}
11763 
11764 		/* Setup PCI function reset mailbox-ioctl command */
11765 		lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
11766 				 LPFC_MBOX_OPCODE_FUNCTION_RESET, 0,
11767 				 LPFC_SLI4_MBX_EMBED);
11768 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
11769 		shdr = (union lpfc_sli4_cfg_shdr *)
11770 			&mboxq->u.mqe.un.sli4_config.header.cfg_shdr;
11771 		shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
11772 		shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
11773 					 &shdr->response);
11774 		mempool_free(mboxq, phba->mbox_mem_pool);
11775 		if (shdr_status || shdr_add_status || rc) {
11776 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11777 					"0495 SLI_FUNCTION_RESET mailbox "
11778 					"failed with status x%x add_status x%x,"
11779 					" mbx status x%x\n",
11780 					shdr_status, shdr_add_status, rc);
11781 			rc = -ENXIO;
11782 		}
11783 		break;
11784 	case LPFC_SLI_INTF_IF_TYPE_2:
11785 	case LPFC_SLI_INTF_IF_TYPE_6:
11786 wait:
11787 		/*
11788 		 * Poll the Port Status Register and wait for RDY for
11789 		 * up to 30 seconds. If the port doesn't respond, treat
11790 		 * it as an error.
11791 		 */
11792 		for (rdy_chk = 0; rdy_chk < 1500; rdy_chk++) {
11793 			if (lpfc_readl(phba->sli4_hba.u.if_type2.
11794 				STATUSregaddr, &reg_data.word0)) {
11795 				rc = -ENODEV;
11796 				goto out;
11797 			}
11798 			if (bf_get(lpfc_sliport_status_rdy, &reg_data))
11799 				break;
11800 			msleep(20);
11801 		}
11802 
11803 		if (!bf_get(lpfc_sliport_status_rdy, &reg_data)) {
11804 			phba->work_status[0] = readl(
11805 				phba->sli4_hba.u.if_type2.ERR1regaddr);
11806 			phba->work_status[1] = readl(
11807 				phba->sli4_hba.u.if_type2.ERR2regaddr);
11808 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11809 					"2890 Port not ready, port status reg "
11810 					"0x%x error 1=0x%x, error 2=0x%x\n",
11811 					reg_data.word0,
11812 					phba->work_status[0],
11813 					phba->work_status[1]);
11814 			rc = -ENODEV;
11815 			goto out;
11816 		}
11817 
11818 		if (bf_get(lpfc_sliport_status_pldv, &reg_data))
11819 			lpfc_pldv_detect = true;
11820 
11821 		if (!port_reset) {
11822 			/*
11823 			 * Reset the port now
11824 			 */
11825 			reg_data.word0 = 0;
11826 			bf_set(lpfc_sliport_ctrl_end, &reg_data,
11827 			       LPFC_SLIPORT_LITTLE_ENDIAN);
11828 			bf_set(lpfc_sliport_ctrl_ip, &reg_data,
11829 			       LPFC_SLIPORT_INIT_PORT);
11830 			writel(reg_data.word0, phba->sli4_hba.u.if_type2.
11831 			       CTRLregaddr);
11832 			/* flush */
11833 			pci_read_config_word(phba->pcidev,
11834 					     PCI_DEVICE_ID, &devid);
11835 
11836 			port_reset = 1;
11837 			msleep(20);
11838 			goto wait;
11839 		} else if (bf_get(lpfc_sliport_status_rn, &reg_data)) {
11840 			rc = -ENODEV;
11841 			goto out;
11842 		}
11843 		break;
11844 
11845 	case LPFC_SLI_INTF_IF_TYPE_1:
11846 	default:
11847 		break;
11848 	}
11849 
11850 out:
11851 	/* Catch the not-ready port failure after a port reset. */
11852 	if (rc) {
11853 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11854 				"3317 HBA not functional: IP Reset Failed "
11855 				"try: echo fw_reset > board_mode\n");
11856 		rc = -ENODEV;
11857 	}
11858 
11859 	return rc;
11860 }
11861 
11862 /**
11863  * lpfc_sli4_pci_mem_setup - Setup SLI4 HBA PCI memory space.
11864  * @phba: pointer to lpfc hba data structure.
11865  *
11866  * This routine is invoked to set up the PCI device memory space for device
11867  * with SLI-4 interface spec.
11868  *
11869  * Return codes
11870  * 	0 - successful
11871  * 	other values - error
11872  **/
11873 static int
11874 lpfc_sli4_pci_mem_setup(struct lpfc_hba *phba)
11875 {
11876 	struct pci_dev *pdev = phba->pcidev;
11877 	unsigned long bar0map_len, bar1map_len, bar2map_len;
11878 	int error;
11879 	uint32_t if_type;
11880 
11881 	if (!pdev)
11882 		return -ENODEV;
11883 
11884 	/* Set the device DMA mask size */
11885 	error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
11886 	if (error)
11887 		error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32));
11888 	if (error)
11889 		return error;
11890 
11891 	/*
11892 	 * The BARs and register set definitions and offset locations are
11893 	 * dependent on the if_type.
11894 	 */
11895 	if (pci_read_config_dword(pdev, LPFC_SLI_INTF,
11896 				  &phba->sli4_hba.sli_intf.word0)) {
11897 		return -ENODEV;
11898 	}
11899 
11900 	/* There is no SLI3 failback for SLI4 devices. */
11901 	if (bf_get(lpfc_sli_intf_valid, &phba->sli4_hba.sli_intf) !=
11902 	    LPFC_SLI_INTF_VALID) {
11903 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11904 				"2894 SLI_INTF reg contents invalid "
11905 				"sli_intf reg 0x%x\n",
11906 				phba->sli4_hba.sli_intf.word0);
11907 		return -ENODEV;
11908 	}
11909 
11910 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
11911 	/*
11912 	 * Get the bus address of SLI4 device Bar regions and the
11913 	 * number of bytes required by each mapping. The mapping of the
11914 	 * particular PCI BARs regions is dependent on the type of
11915 	 * SLI4 device.
11916 	 */
11917 	if (pci_resource_start(pdev, PCI_64BIT_BAR0)) {
11918 		phba->pci_bar0_map = pci_resource_start(pdev, PCI_64BIT_BAR0);
11919 		bar0map_len = pci_resource_len(pdev, PCI_64BIT_BAR0);
11920 
11921 		/*
11922 		 * Map SLI4 PCI Config Space Register base to a kernel virtual
11923 		 * addr
11924 		 */
11925 		phba->sli4_hba.conf_regs_memmap_p =
11926 			ioremap(phba->pci_bar0_map, bar0map_len);
11927 		if (!phba->sli4_hba.conf_regs_memmap_p) {
11928 			dev_printk(KERN_ERR, &pdev->dev,
11929 				   "ioremap failed for SLI4 PCI config "
11930 				   "registers.\n");
11931 			return -ENODEV;
11932 		}
11933 		phba->pci_bar0_memmap_p = phba->sli4_hba.conf_regs_memmap_p;
11934 		/* Set up BAR0 PCI config space register memory map */
11935 		lpfc_sli4_bar0_register_memmap(phba, if_type);
11936 	} else {
11937 		phba->pci_bar0_map = pci_resource_start(pdev, 1);
11938 		bar0map_len = pci_resource_len(pdev, 1);
11939 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
11940 			dev_printk(KERN_ERR, &pdev->dev,
11941 			   "FATAL - No BAR0 mapping for SLI4, if_type 2\n");
11942 			return -ENODEV;
11943 		}
11944 		phba->sli4_hba.conf_regs_memmap_p =
11945 				ioremap(phba->pci_bar0_map, bar0map_len);
11946 		if (!phba->sli4_hba.conf_regs_memmap_p) {
11947 			dev_printk(KERN_ERR, &pdev->dev,
11948 				"ioremap failed for SLI4 PCI config "
11949 				"registers.\n");
11950 			return -ENODEV;
11951 		}
11952 		lpfc_sli4_bar0_register_memmap(phba, if_type);
11953 	}
11954 
11955 	if (if_type == LPFC_SLI_INTF_IF_TYPE_0) {
11956 		if (pci_resource_start(pdev, PCI_64BIT_BAR2)) {
11957 			/*
11958 			 * Map SLI4 if type 0 HBA Control Register base to a
11959 			 * kernel virtual address and setup the registers.
11960 			 */
11961 			phba->pci_bar1_map = pci_resource_start(pdev,
11962 								PCI_64BIT_BAR2);
11963 			bar1map_len = pci_resource_len(pdev, PCI_64BIT_BAR2);
11964 			phba->sli4_hba.ctrl_regs_memmap_p =
11965 					ioremap(phba->pci_bar1_map,
11966 						bar1map_len);
11967 			if (!phba->sli4_hba.ctrl_regs_memmap_p) {
11968 				dev_err(&pdev->dev,
11969 					   "ioremap failed for SLI4 HBA "
11970 					    "control registers.\n");
11971 				error = -ENOMEM;
11972 				goto out_iounmap_conf;
11973 			}
11974 			phba->pci_bar2_memmap_p =
11975 					 phba->sli4_hba.ctrl_regs_memmap_p;
11976 			lpfc_sli4_bar1_register_memmap(phba, if_type);
11977 		} else {
11978 			error = -ENOMEM;
11979 			goto out_iounmap_conf;
11980 		}
11981 	}
11982 
11983 	if ((if_type == LPFC_SLI_INTF_IF_TYPE_6) &&
11984 	    (pci_resource_start(pdev, PCI_64BIT_BAR2))) {
11985 		/*
11986 		 * Map SLI4 if type 6 HBA Doorbell Register base to a kernel
11987 		 * virtual address and setup the registers.
11988 		 */
11989 		phba->pci_bar1_map = pci_resource_start(pdev, PCI_64BIT_BAR2);
11990 		bar1map_len = pci_resource_len(pdev, PCI_64BIT_BAR2);
11991 		phba->sli4_hba.drbl_regs_memmap_p =
11992 				ioremap(phba->pci_bar1_map, bar1map_len);
11993 		if (!phba->sli4_hba.drbl_regs_memmap_p) {
11994 			dev_err(&pdev->dev,
11995 			   "ioremap failed for SLI4 HBA doorbell registers.\n");
11996 			error = -ENOMEM;
11997 			goto out_iounmap_conf;
11998 		}
11999 		phba->pci_bar2_memmap_p = phba->sli4_hba.drbl_regs_memmap_p;
12000 		lpfc_sli4_bar1_register_memmap(phba, if_type);
12001 	}
12002 
12003 	if (if_type == LPFC_SLI_INTF_IF_TYPE_0) {
12004 		if (pci_resource_start(pdev, PCI_64BIT_BAR4)) {
12005 			/*
12006 			 * Map SLI4 if type 0 HBA Doorbell Register base to
12007 			 * a kernel virtual address and setup the registers.
12008 			 */
12009 			phba->pci_bar2_map = pci_resource_start(pdev,
12010 								PCI_64BIT_BAR4);
12011 			bar2map_len = pci_resource_len(pdev, PCI_64BIT_BAR4);
12012 			phba->sli4_hba.drbl_regs_memmap_p =
12013 					ioremap(phba->pci_bar2_map,
12014 						bar2map_len);
12015 			if (!phba->sli4_hba.drbl_regs_memmap_p) {
12016 				dev_err(&pdev->dev,
12017 					   "ioremap failed for SLI4 HBA"
12018 					   " doorbell registers.\n");
12019 				error = -ENOMEM;
12020 				goto out_iounmap_ctrl;
12021 			}
12022 			phba->pci_bar4_memmap_p =
12023 					phba->sli4_hba.drbl_regs_memmap_p;
12024 			error = lpfc_sli4_bar2_register_memmap(phba, LPFC_VF0);
12025 			if (error)
12026 				goto out_iounmap_all;
12027 		} else {
12028 			error = -ENOMEM;
12029 			goto out_iounmap_all;
12030 		}
12031 	}
12032 
12033 	if (if_type == LPFC_SLI_INTF_IF_TYPE_6 &&
12034 	    pci_resource_start(pdev, PCI_64BIT_BAR4)) {
12035 		/*
12036 		 * Map SLI4 if type 6 HBA DPP Register base to a kernel
12037 		 * virtual address and setup the registers.
12038 		 */
12039 		phba->pci_bar2_map = pci_resource_start(pdev, PCI_64BIT_BAR4);
12040 		bar2map_len = pci_resource_len(pdev, PCI_64BIT_BAR4);
12041 		phba->sli4_hba.dpp_regs_memmap_p =
12042 				ioremap(phba->pci_bar2_map, bar2map_len);
12043 		if (!phba->sli4_hba.dpp_regs_memmap_p) {
12044 			dev_err(&pdev->dev,
12045 			   "ioremap failed for SLI4 HBA dpp registers.\n");
12046 			error = -ENOMEM;
12047 			goto out_iounmap_ctrl;
12048 		}
12049 		phba->pci_bar4_memmap_p = phba->sli4_hba.dpp_regs_memmap_p;
12050 	}
12051 
12052 	/* Set up the EQ/CQ register handeling functions now */
12053 	switch (if_type) {
12054 	case LPFC_SLI_INTF_IF_TYPE_0:
12055 	case LPFC_SLI_INTF_IF_TYPE_2:
12056 		phba->sli4_hba.sli4_eq_clr_intr = lpfc_sli4_eq_clr_intr;
12057 		phba->sli4_hba.sli4_write_eq_db = lpfc_sli4_write_eq_db;
12058 		phba->sli4_hba.sli4_write_cq_db = lpfc_sli4_write_cq_db;
12059 		break;
12060 	case LPFC_SLI_INTF_IF_TYPE_6:
12061 		phba->sli4_hba.sli4_eq_clr_intr = lpfc_sli4_if6_eq_clr_intr;
12062 		phba->sli4_hba.sli4_write_eq_db = lpfc_sli4_if6_write_eq_db;
12063 		phba->sli4_hba.sli4_write_cq_db = lpfc_sli4_if6_write_cq_db;
12064 		break;
12065 	default:
12066 		break;
12067 	}
12068 
12069 	return 0;
12070 
12071 out_iounmap_all:
12072 	iounmap(phba->sli4_hba.drbl_regs_memmap_p);
12073 out_iounmap_ctrl:
12074 	iounmap(phba->sli4_hba.ctrl_regs_memmap_p);
12075 out_iounmap_conf:
12076 	iounmap(phba->sli4_hba.conf_regs_memmap_p);
12077 
12078 	return error;
12079 }
12080 
12081 /**
12082  * lpfc_sli4_pci_mem_unset - Unset SLI4 HBA PCI memory space.
12083  * @phba: pointer to lpfc hba data structure.
12084  *
12085  * This routine is invoked to unset the PCI device memory space for device
12086  * with SLI-4 interface spec.
12087  **/
12088 static void
12089 lpfc_sli4_pci_mem_unset(struct lpfc_hba *phba)
12090 {
12091 	uint32_t if_type;
12092 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
12093 
12094 	switch (if_type) {
12095 	case LPFC_SLI_INTF_IF_TYPE_0:
12096 		iounmap(phba->sli4_hba.drbl_regs_memmap_p);
12097 		iounmap(phba->sli4_hba.ctrl_regs_memmap_p);
12098 		iounmap(phba->sli4_hba.conf_regs_memmap_p);
12099 		break;
12100 	case LPFC_SLI_INTF_IF_TYPE_2:
12101 		iounmap(phba->sli4_hba.conf_regs_memmap_p);
12102 		break;
12103 	case LPFC_SLI_INTF_IF_TYPE_6:
12104 		iounmap(phba->sli4_hba.drbl_regs_memmap_p);
12105 		iounmap(phba->sli4_hba.conf_regs_memmap_p);
12106 		if (phba->sli4_hba.dpp_regs_memmap_p)
12107 			iounmap(phba->sli4_hba.dpp_regs_memmap_p);
12108 		break;
12109 	case LPFC_SLI_INTF_IF_TYPE_1:
12110 	default:
12111 		dev_printk(KERN_ERR, &phba->pcidev->dev,
12112 			   "FATAL - unsupported SLI4 interface type - %d\n",
12113 			   if_type);
12114 		break;
12115 	}
12116 }
12117 
12118 /**
12119  * lpfc_sli_enable_msix - Enable MSI-X interrupt mode on SLI-3 device
12120  * @phba: pointer to lpfc hba data structure.
12121  *
12122  * This routine is invoked to enable the MSI-X interrupt vectors to device
12123  * with SLI-3 interface specs.
12124  *
12125  * Return codes
12126  *   0 - successful
12127  *   other values - error
12128  **/
12129 static int
12130 lpfc_sli_enable_msix(struct lpfc_hba *phba)
12131 {
12132 	int rc;
12133 	LPFC_MBOXQ_t *pmb;
12134 
12135 	/* Set up MSI-X multi-message vectors */
12136 	rc = pci_alloc_irq_vectors(phba->pcidev,
12137 			LPFC_MSIX_VECTORS, LPFC_MSIX_VECTORS, PCI_IRQ_MSIX);
12138 	if (rc < 0) {
12139 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12140 				"0420 PCI enable MSI-X failed (%d)\n", rc);
12141 		goto vec_fail_out;
12142 	}
12143 
12144 	/*
12145 	 * Assign MSI-X vectors to interrupt handlers
12146 	 */
12147 
12148 	/* vector-0 is associated to slow-path handler */
12149 	rc = request_irq(pci_irq_vector(phba->pcidev, 0),
12150 			 &lpfc_sli_sp_intr_handler, 0,
12151 			 LPFC_SP_DRIVER_HANDLER_NAME, phba);
12152 	if (rc) {
12153 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
12154 				"0421 MSI-X slow-path request_irq failed "
12155 				"(%d)\n", rc);
12156 		goto msi_fail_out;
12157 	}
12158 
12159 	/* vector-1 is associated to fast-path handler */
12160 	rc = request_irq(pci_irq_vector(phba->pcidev, 1),
12161 			 &lpfc_sli_fp_intr_handler, 0,
12162 			 LPFC_FP_DRIVER_HANDLER_NAME, phba);
12163 
12164 	if (rc) {
12165 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
12166 				"0429 MSI-X fast-path request_irq failed "
12167 				"(%d)\n", rc);
12168 		goto irq_fail_out;
12169 	}
12170 
12171 	/*
12172 	 * Configure HBA MSI-X attention conditions to messages
12173 	 */
12174 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
12175 
12176 	if (!pmb) {
12177 		rc = -ENOMEM;
12178 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12179 				"0474 Unable to allocate memory for issuing "
12180 				"MBOX_CONFIG_MSI command\n");
12181 		goto mem_fail_out;
12182 	}
12183 	rc = lpfc_config_msi(phba, pmb);
12184 	if (rc)
12185 		goto mbx_fail_out;
12186 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
12187 	if (rc != MBX_SUCCESS) {
12188 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX,
12189 				"0351 Config MSI mailbox command failed, "
12190 				"mbxCmd x%x, mbxStatus x%x\n",
12191 				pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus);
12192 		goto mbx_fail_out;
12193 	}
12194 
12195 	/* Free memory allocated for mailbox command */
12196 	mempool_free(pmb, phba->mbox_mem_pool);
12197 	return rc;
12198 
12199 mbx_fail_out:
12200 	/* Free memory allocated for mailbox command */
12201 	mempool_free(pmb, phba->mbox_mem_pool);
12202 
12203 mem_fail_out:
12204 	/* free the irq already requested */
12205 	free_irq(pci_irq_vector(phba->pcidev, 1), phba);
12206 
12207 irq_fail_out:
12208 	/* free the irq already requested */
12209 	free_irq(pci_irq_vector(phba->pcidev, 0), phba);
12210 
12211 msi_fail_out:
12212 	/* Unconfigure MSI-X capability structure */
12213 	pci_free_irq_vectors(phba->pcidev);
12214 
12215 vec_fail_out:
12216 	return rc;
12217 }
12218 
12219 /**
12220  * lpfc_sli_enable_msi - Enable MSI interrupt mode on SLI-3 device.
12221  * @phba: pointer to lpfc hba data structure.
12222  *
12223  * This routine is invoked to enable the MSI interrupt mode to device with
12224  * SLI-3 interface spec. The kernel function pci_enable_msi() is called to
12225  * enable the MSI vector. The device driver is responsible for calling the
12226  * request_irq() to register MSI vector with a interrupt the handler, which
12227  * is done in this function.
12228  *
12229  * Return codes
12230  * 	0 - successful
12231  * 	other values - error
12232  */
12233 static int
12234 lpfc_sli_enable_msi(struct lpfc_hba *phba)
12235 {
12236 	int rc;
12237 
12238 	rc = pci_enable_msi(phba->pcidev);
12239 	if (!rc)
12240 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12241 				"0012 PCI enable MSI mode success.\n");
12242 	else {
12243 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12244 				"0471 PCI enable MSI mode failed (%d)\n", rc);
12245 		return rc;
12246 	}
12247 
12248 	rc = request_irq(phba->pcidev->irq, lpfc_sli_intr_handler,
12249 			 0, LPFC_DRIVER_NAME, phba);
12250 	if (rc) {
12251 		pci_disable_msi(phba->pcidev);
12252 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
12253 				"0478 MSI request_irq failed (%d)\n", rc);
12254 	}
12255 	return rc;
12256 }
12257 
12258 /**
12259  * lpfc_sli_enable_intr - Enable device interrupt to SLI-3 device.
12260  * @phba: pointer to lpfc hba data structure.
12261  * @cfg_mode: Interrupt configuration mode (INTx, MSI or MSI-X).
12262  *
12263  * This routine is invoked to enable device interrupt and associate driver's
12264  * interrupt handler(s) to interrupt vector(s) to device with SLI-3 interface
12265  * spec. Depends on the interrupt mode configured to the driver, the driver
12266  * will try to fallback from the configured interrupt mode to an interrupt
12267  * mode which is supported by the platform, kernel, and device in the order
12268  * of:
12269  * MSI-X -> MSI -> IRQ.
12270  *
12271  * Return codes
12272  *   0 - successful
12273  *   other values - error
12274  **/
12275 static uint32_t
12276 lpfc_sli_enable_intr(struct lpfc_hba *phba, uint32_t cfg_mode)
12277 {
12278 	uint32_t intr_mode = LPFC_INTR_ERROR;
12279 	int retval;
12280 
12281 	/* Need to issue conf_port mbox cmd before conf_msi mbox cmd */
12282 	retval = lpfc_sli_config_port(phba, LPFC_SLI_REV3);
12283 	if (retval)
12284 		return intr_mode;
12285 	phba->hba_flag &= ~HBA_NEEDS_CFG_PORT;
12286 
12287 	if (cfg_mode == 2) {
12288 		/* Now, try to enable MSI-X interrupt mode */
12289 		retval = lpfc_sli_enable_msix(phba);
12290 		if (!retval) {
12291 			/* Indicate initialization to MSI-X mode */
12292 			phba->intr_type = MSIX;
12293 			intr_mode = 2;
12294 		}
12295 	}
12296 
12297 	/* Fallback to MSI if MSI-X initialization failed */
12298 	if (cfg_mode >= 1 && phba->intr_type == NONE) {
12299 		retval = lpfc_sli_enable_msi(phba);
12300 		if (!retval) {
12301 			/* Indicate initialization to MSI mode */
12302 			phba->intr_type = MSI;
12303 			intr_mode = 1;
12304 		}
12305 	}
12306 
12307 	/* Fallback to INTx if both MSI-X/MSI initalization failed */
12308 	if (phba->intr_type == NONE) {
12309 		retval = request_irq(phba->pcidev->irq, lpfc_sli_intr_handler,
12310 				     IRQF_SHARED, LPFC_DRIVER_NAME, phba);
12311 		if (!retval) {
12312 			/* Indicate initialization to INTx mode */
12313 			phba->intr_type = INTx;
12314 			intr_mode = 0;
12315 		}
12316 	}
12317 	return intr_mode;
12318 }
12319 
12320 /**
12321  * lpfc_sli_disable_intr - Disable device interrupt to SLI-3 device.
12322  * @phba: pointer to lpfc hba data structure.
12323  *
12324  * This routine is invoked to disable device interrupt and disassociate the
12325  * driver's interrupt handler(s) from interrupt vector(s) to device with
12326  * SLI-3 interface spec. Depending on the interrupt mode, the driver will
12327  * release the interrupt vector(s) for the message signaled interrupt.
12328  **/
12329 static void
12330 lpfc_sli_disable_intr(struct lpfc_hba *phba)
12331 {
12332 	int nr_irqs, i;
12333 
12334 	if (phba->intr_type == MSIX)
12335 		nr_irqs = LPFC_MSIX_VECTORS;
12336 	else
12337 		nr_irqs = 1;
12338 
12339 	for (i = 0; i < nr_irqs; i++)
12340 		free_irq(pci_irq_vector(phba->pcidev, i), phba);
12341 	pci_free_irq_vectors(phba->pcidev);
12342 
12343 	/* Reset interrupt management states */
12344 	phba->intr_type = NONE;
12345 	phba->sli.slistat.sli_intr = 0;
12346 }
12347 
12348 /**
12349  * lpfc_find_cpu_handle - Find the CPU that corresponds to the specified Queue
12350  * @phba: pointer to lpfc hba data structure.
12351  * @id: EQ vector index or Hardware Queue index
12352  * @match: LPFC_FIND_BY_EQ = match by EQ
12353  *         LPFC_FIND_BY_HDWQ = match by Hardware Queue
12354  * Return the CPU that matches the selection criteria
12355  */
12356 static uint16_t
12357 lpfc_find_cpu_handle(struct lpfc_hba *phba, uint16_t id, int match)
12358 {
12359 	struct lpfc_vector_map_info *cpup;
12360 	int cpu;
12361 
12362 	/* Loop through all CPUs */
12363 	for_each_present_cpu(cpu) {
12364 		cpup = &phba->sli4_hba.cpu_map[cpu];
12365 
12366 		/* If we are matching by EQ, there may be multiple CPUs using
12367 		 * using the same vector, so select the one with
12368 		 * LPFC_CPU_FIRST_IRQ set.
12369 		 */
12370 		if ((match == LPFC_FIND_BY_EQ) &&
12371 		    (cpup->flag & LPFC_CPU_FIRST_IRQ) &&
12372 		    (cpup->eq == id))
12373 			return cpu;
12374 
12375 		/* If matching by HDWQ, select the first CPU that matches */
12376 		if ((match == LPFC_FIND_BY_HDWQ) && (cpup->hdwq == id))
12377 			return cpu;
12378 	}
12379 	return 0;
12380 }
12381 
12382 #ifdef CONFIG_X86
12383 /**
12384  * lpfc_find_hyper - Determine if the CPU map entry is hyper-threaded
12385  * @phba: pointer to lpfc hba data structure.
12386  * @cpu: CPU map index
12387  * @phys_id: CPU package physical id
12388  * @core_id: CPU core id
12389  */
12390 static int
12391 lpfc_find_hyper(struct lpfc_hba *phba, int cpu,
12392 		uint16_t phys_id, uint16_t core_id)
12393 {
12394 	struct lpfc_vector_map_info *cpup;
12395 	int idx;
12396 
12397 	for_each_present_cpu(idx) {
12398 		cpup = &phba->sli4_hba.cpu_map[idx];
12399 		/* Does the cpup match the one we are looking for */
12400 		if ((cpup->phys_id == phys_id) &&
12401 		    (cpup->core_id == core_id) &&
12402 		    (cpu != idx))
12403 			return 1;
12404 	}
12405 	return 0;
12406 }
12407 #endif
12408 
12409 /*
12410  * lpfc_assign_eq_map_info - Assigns eq for vector_map structure
12411  * @phba: pointer to lpfc hba data structure.
12412  * @eqidx: index for eq and irq vector
12413  * @flag: flags to set for vector_map structure
12414  * @cpu: cpu used to index vector_map structure
12415  *
12416  * The routine assigns eq info into vector_map structure
12417  */
12418 static inline void
12419 lpfc_assign_eq_map_info(struct lpfc_hba *phba, uint16_t eqidx, uint16_t flag,
12420 			unsigned int cpu)
12421 {
12422 	struct lpfc_vector_map_info *cpup = &phba->sli4_hba.cpu_map[cpu];
12423 	struct lpfc_hba_eq_hdl *eqhdl = lpfc_get_eq_hdl(eqidx);
12424 
12425 	cpup->eq = eqidx;
12426 	cpup->flag |= flag;
12427 
12428 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12429 			"3336 Set Affinity: CPU %d irq %d eq %d flag x%x\n",
12430 			cpu, eqhdl->irq, cpup->eq, cpup->flag);
12431 }
12432 
12433 /**
12434  * lpfc_cpu_map_array_init - Initialize cpu_map structure
12435  * @phba: pointer to lpfc hba data structure.
12436  *
12437  * The routine initializes the cpu_map array structure
12438  */
12439 static void
12440 lpfc_cpu_map_array_init(struct lpfc_hba *phba)
12441 {
12442 	struct lpfc_vector_map_info *cpup;
12443 	struct lpfc_eq_intr_info *eqi;
12444 	int cpu;
12445 
12446 	for_each_possible_cpu(cpu) {
12447 		cpup = &phba->sli4_hba.cpu_map[cpu];
12448 		cpup->phys_id = LPFC_VECTOR_MAP_EMPTY;
12449 		cpup->core_id = LPFC_VECTOR_MAP_EMPTY;
12450 		cpup->hdwq = LPFC_VECTOR_MAP_EMPTY;
12451 		cpup->eq = LPFC_VECTOR_MAP_EMPTY;
12452 		cpup->flag = 0;
12453 		eqi = per_cpu_ptr(phba->sli4_hba.eq_info, cpu);
12454 		INIT_LIST_HEAD(&eqi->list);
12455 		eqi->icnt = 0;
12456 	}
12457 }
12458 
12459 /**
12460  * lpfc_hba_eq_hdl_array_init - Initialize hba_eq_hdl structure
12461  * @phba: pointer to lpfc hba data structure.
12462  *
12463  * The routine initializes the hba_eq_hdl array structure
12464  */
12465 static void
12466 lpfc_hba_eq_hdl_array_init(struct lpfc_hba *phba)
12467 {
12468 	struct lpfc_hba_eq_hdl *eqhdl;
12469 	int i;
12470 
12471 	for (i = 0; i < phba->cfg_irq_chann; i++) {
12472 		eqhdl = lpfc_get_eq_hdl(i);
12473 		eqhdl->irq = LPFC_IRQ_EMPTY;
12474 		eqhdl->phba = phba;
12475 	}
12476 }
12477 
12478 /**
12479  * lpfc_cpu_affinity_check - Check vector CPU affinity mappings
12480  * @phba: pointer to lpfc hba data structure.
12481  * @vectors: number of msix vectors allocated.
12482  *
12483  * The routine will figure out the CPU affinity assignment for every
12484  * MSI-X vector allocated for the HBA.
12485  * In addition, the CPU to IO channel mapping will be calculated
12486  * and the phba->sli4_hba.cpu_map array will reflect this.
12487  */
12488 static void
12489 lpfc_cpu_affinity_check(struct lpfc_hba *phba, int vectors)
12490 {
12491 	int i, cpu, idx, next_idx, new_cpu, start_cpu, first_cpu;
12492 	int max_phys_id, min_phys_id;
12493 	int max_core_id, min_core_id;
12494 	struct lpfc_vector_map_info *cpup;
12495 	struct lpfc_vector_map_info *new_cpup;
12496 #ifdef CONFIG_X86
12497 	struct cpuinfo_x86 *cpuinfo;
12498 #endif
12499 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
12500 	struct lpfc_hdwq_stat *c_stat;
12501 #endif
12502 
12503 	max_phys_id = 0;
12504 	min_phys_id = LPFC_VECTOR_MAP_EMPTY;
12505 	max_core_id = 0;
12506 	min_core_id = LPFC_VECTOR_MAP_EMPTY;
12507 
12508 	/* Update CPU map with physical id and core id of each CPU */
12509 	for_each_present_cpu(cpu) {
12510 		cpup = &phba->sli4_hba.cpu_map[cpu];
12511 #ifdef CONFIG_X86
12512 		cpuinfo = &cpu_data(cpu);
12513 		cpup->phys_id = cpuinfo->phys_proc_id;
12514 		cpup->core_id = cpuinfo->cpu_core_id;
12515 		if (lpfc_find_hyper(phba, cpu, cpup->phys_id, cpup->core_id))
12516 			cpup->flag |= LPFC_CPU_MAP_HYPER;
12517 #else
12518 		/* No distinction between CPUs for other platforms */
12519 		cpup->phys_id = 0;
12520 		cpup->core_id = cpu;
12521 #endif
12522 
12523 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12524 				"3328 CPU %d physid %d coreid %d flag x%x\n",
12525 				cpu, cpup->phys_id, cpup->core_id, cpup->flag);
12526 
12527 		if (cpup->phys_id > max_phys_id)
12528 			max_phys_id = cpup->phys_id;
12529 		if (cpup->phys_id < min_phys_id)
12530 			min_phys_id = cpup->phys_id;
12531 
12532 		if (cpup->core_id > max_core_id)
12533 			max_core_id = cpup->core_id;
12534 		if (cpup->core_id < min_core_id)
12535 			min_core_id = cpup->core_id;
12536 	}
12537 
12538 	/* After looking at each irq vector assigned to this pcidev, its
12539 	 * possible to see that not ALL CPUs have been accounted for.
12540 	 * Next we will set any unassigned (unaffinitized) cpu map
12541 	 * entries to a IRQ on the same phys_id.
12542 	 */
12543 	first_cpu = cpumask_first(cpu_present_mask);
12544 	start_cpu = first_cpu;
12545 
12546 	for_each_present_cpu(cpu) {
12547 		cpup = &phba->sli4_hba.cpu_map[cpu];
12548 
12549 		/* Is this CPU entry unassigned */
12550 		if (cpup->eq == LPFC_VECTOR_MAP_EMPTY) {
12551 			/* Mark CPU as IRQ not assigned by the kernel */
12552 			cpup->flag |= LPFC_CPU_MAP_UNASSIGN;
12553 
12554 			/* If so, find a new_cpup that is on the SAME
12555 			 * phys_id as cpup. start_cpu will start where we
12556 			 * left off so all unassigned entries don't get assgined
12557 			 * the IRQ of the first entry.
12558 			 */
12559 			new_cpu = start_cpu;
12560 			for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12561 				new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12562 				if (!(new_cpup->flag & LPFC_CPU_MAP_UNASSIGN) &&
12563 				    (new_cpup->eq != LPFC_VECTOR_MAP_EMPTY) &&
12564 				    (new_cpup->phys_id == cpup->phys_id))
12565 					goto found_same;
12566 				new_cpu = cpumask_next(
12567 					new_cpu, cpu_present_mask);
12568 				if (new_cpu >= nr_cpu_ids)
12569 					new_cpu = first_cpu;
12570 			}
12571 			/* At this point, we leave the CPU as unassigned */
12572 			continue;
12573 found_same:
12574 			/* We found a matching phys_id, so copy the IRQ info */
12575 			cpup->eq = new_cpup->eq;
12576 
12577 			/* Bump start_cpu to the next slot to minmize the
12578 			 * chance of having multiple unassigned CPU entries
12579 			 * selecting the same IRQ.
12580 			 */
12581 			start_cpu = cpumask_next(new_cpu, cpu_present_mask);
12582 			if (start_cpu >= nr_cpu_ids)
12583 				start_cpu = first_cpu;
12584 
12585 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12586 					"3337 Set Affinity: CPU %d "
12587 					"eq %d from peer cpu %d same "
12588 					"phys_id (%d)\n",
12589 					cpu, cpup->eq, new_cpu,
12590 					cpup->phys_id);
12591 		}
12592 	}
12593 
12594 	/* Set any unassigned cpu map entries to a IRQ on any phys_id */
12595 	start_cpu = first_cpu;
12596 
12597 	for_each_present_cpu(cpu) {
12598 		cpup = &phba->sli4_hba.cpu_map[cpu];
12599 
12600 		/* Is this entry unassigned */
12601 		if (cpup->eq == LPFC_VECTOR_MAP_EMPTY) {
12602 			/* Mark it as IRQ not assigned by the kernel */
12603 			cpup->flag |= LPFC_CPU_MAP_UNASSIGN;
12604 
12605 			/* If so, find a new_cpup thats on ANY phys_id
12606 			 * as the cpup. start_cpu will start where we
12607 			 * left off so all unassigned entries don't get
12608 			 * assigned the IRQ of the first entry.
12609 			 */
12610 			new_cpu = start_cpu;
12611 			for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12612 				new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12613 				if (!(new_cpup->flag & LPFC_CPU_MAP_UNASSIGN) &&
12614 				    (new_cpup->eq != LPFC_VECTOR_MAP_EMPTY))
12615 					goto found_any;
12616 				new_cpu = cpumask_next(
12617 					new_cpu, cpu_present_mask);
12618 				if (new_cpu >= nr_cpu_ids)
12619 					new_cpu = first_cpu;
12620 			}
12621 			/* We should never leave an entry unassigned */
12622 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12623 					"3339 Set Affinity: CPU %d "
12624 					"eq %d UNASSIGNED\n",
12625 					cpup->hdwq, cpup->eq);
12626 			continue;
12627 found_any:
12628 			/* We found an available entry, copy the IRQ info */
12629 			cpup->eq = new_cpup->eq;
12630 
12631 			/* Bump start_cpu to the next slot to minmize the
12632 			 * chance of having multiple unassigned CPU entries
12633 			 * selecting the same IRQ.
12634 			 */
12635 			start_cpu = cpumask_next(new_cpu, cpu_present_mask);
12636 			if (start_cpu >= nr_cpu_ids)
12637 				start_cpu = first_cpu;
12638 
12639 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12640 					"3338 Set Affinity: CPU %d "
12641 					"eq %d from peer cpu %d (%d/%d)\n",
12642 					cpu, cpup->eq, new_cpu,
12643 					new_cpup->phys_id, new_cpup->core_id);
12644 		}
12645 	}
12646 
12647 	/* Assign hdwq indices that are unique across all cpus in the map
12648 	 * that are also FIRST_CPUs.
12649 	 */
12650 	idx = 0;
12651 	for_each_present_cpu(cpu) {
12652 		cpup = &phba->sli4_hba.cpu_map[cpu];
12653 
12654 		/* Only FIRST IRQs get a hdwq index assignment. */
12655 		if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
12656 			continue;
12657 
12658 		/* 1 to 1, the first LPFC_CPU_FIRST_IRQ cpus to a unique hdwq */
12659 		cpup->hdwq = idx;
12660 		idx++;
12661 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12662 				"3333 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 	/* Associate a hdwq with each cpu_map entry
12668 	 * This will be 1 to 1 - hdwq to cpu, unless there are less
12669 	 * hardware queues then CPUs. For that case we will just round-robin
12670 	 * the available hardware queues as they get assigned to CPUs.
12671 	 * The next_idx is the idx from the FIRST_CPU loop above to account
12672 	 * for irq_chann < hdwq.  The idx is used for round-robin assignments
12673 	 * and needs to start at 0.
12674 	 */
12675 	next_idx = idx;
12676 	start_cpu = 0;
12677 	idx = 0;
12678 	for_each_present_cpu(cpu) {
12679 		cpup = &phba->sli4_hba.cpu_map[cpu];
12680 
12681 		/* FIRST cpus are already mapped. */
12682 		if (cpup->flag & LPFC_CPU_FIRST_IRQ)
12683 			continue;
12684 
12685 		/* If the cfg_irq_chann < cfg_hdw_queue, set the hdwq
12686 		 * of the unassigned cpus to the next idx so that all
12687 		 * hdw queues are fully utilized.
12688 		 */
12689 		if (next_idx < phba->cfg_hdw_queue) {
12690 			cpup->hdwq = next_idx;
12691 			next_idx++;
12692 			continue;
12693 		}
12694 
12695 		/* Not a First CPU and all hdw_queues are used.  Reuse a
12696 		 * Hardware Queue for another CPU, so be smart about it
12697 		 * and pick one that has its IRQ/EQ mapped to the same phys_id
12698 		 * (CPU package) and core_id.
12699 		 */
12700 		new_cpu = start_cpu;
12701 		for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12702 			new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12703 			if (new_cpup->hdwq != LPFC_VECTOR_MAP_EMPTY &&
12704 			    new_cpup->phys_id == cpup->phys_id &&
12705 			    new_cpup->core_id == cpup->core_id) {
12706 				goto found_hdwq;
12707 			}
12708 			new_cpu = cpumask_next(new_cpu, cpu_present_mask);
12709 			if (new_cpu >= nr_cpu_ids)
12710 				new_cpu = first_cpu;
12711 		}
12712 
12713 		/* If we can't match both phys_id and core_id,
12714 		 * settle for just a phys_id match.
12715 		 */
12716 		new_cpu = start_cpu;
12717 		for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12718 			new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12719 			if (new_cpup->hdwq != LPFC_VECTOR_MAP_EMPTY &&
12720 			    new_cpup->phys_id == cpup->phys_id)
12721 				goto found_hdwq;
12722 
12723 			new_cpu = cpumask_next(new_cpu, cpu_present_mask);
12724 			if (new_cpu >= nr_cpu_ids)
12725 				new_cpu = first_cpu;
12726 		}
12727 
12728 		/* Otherwise just round robin on cfg_hdw_queue */
12729 		cpup->hdwq = idx % phba->cfg_hdw_queue;
12730 		idx++;
12731 		goto logit;
12732  found_hdwq:
12733 		/* We found an available entry, copy the IRQ info */
12734 		start_cpu = cpumask_next(new_cpu, cpu_present_mask);
12735 		if (start_cpu >= nr_cpu_ids)
12736 			start_cpu = first_cpu;
12737 		cpup->hdwq = new_cpup->hdwq;
12738  logit:
12739 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12740 				"3335 Set Affinity: CPU %d (phys %d core %d): "
12741 				"hdwq %d eq %d flg x%x\n",
12742 				cpu, cpup->phys_id, cpup->core_id,
12743 				cpup->hdwq, cpup->eq, cpup->flag);
12744 	}
12745 
12746 	/*
12747 	 * Initialize the cpu_map slots for not-present cpus in case
12748 	 * a cpu is hot-added. Perform a simple hdwq round robin assignment.
12749 	 */
12750 	idx = 0;
12751 	for_each_possible_cpu(cpu) {
12752 		cpup = &phba->sli4_hba.cpu_map[cpu];
12753 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
12754 		c_stat = per_cpu_ptr(phba->sli4_hba.c_stat, cpu);
12755 		c_stat->hdwq_no = cpup->hdwq;
12756 #endif
12757 		if (cpup->hdwq != LPFC_VECTOR_MAP_EMPTY)
12758 			continue;
12759 
12760 		cpup->hdwq = idx++ % phba->cfg_hdw_queue;
12761 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
12762 		c_stat->hdwq_no = cpup->hdwq;
12763 #endif
12764 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12765 				"3340 Set Affinity: not present "
12766 				"CPU %d hdwq %d\n",
12767 				cpu, cpup->hdwq);
12768 	}
12769 
12770 	/* The cpu_map array will be used later during initialization
12771 	 * when EQ / CQ / WQs are allocated and configured.
12772 	 */
12773 	return;
12774 }
12775 
12776 /**
12777  * lpfc_cpuhp_get_eq
12778  *
12779  * @phba:   pointer to lpfc hba data structure.
12780  * @cpu:    cpu going offline
12781  * @eqlist: eq list to append to
12782  */
12783 static int
12784 lpfc_cpuhp_get_eq(struct lpfc_hba *phba, unsigned int cpu,
12785 		  struct list_head *eqlist)
12786 {
12787 	const struct cpumask *maskp;
12788 	struct lpfc_queue *eq;
12789 	struct cpumask *tmp;
12790 	u16 idx;
12791 
12792 	tmp = kzalloc(cpumask_size(), GFP_KERNEL);
12793 	if (!tmp)
12794 		return -ENOMEM;
12795 
12796 	for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
12797 		maskp = pci_irq_get_affinity(phba->pcidev, idx);
12798 		if (!maskp)
12799 			continue;
12800 		/*
12801 		 * if irq is not affinitized to the cpu going
12802 		 * then we don't need to poll the eq attached
12803 		 * to it.
12804 		 */
12805 		if (!cpumask_and(tmp, maskp, cpumask_of(cpu)))
12806 			continue;
12807 		/* get the cpus that are online and are affini-
12808 		 * tized to this irq vector.  If the count is
12809 		 * more than 1 then cpuhp is not going to shut-
12810 		 * down this vector.  Since this cpu has not
12811 		 * gone offline yet, we need >1.
12812 		 */
12813 		cpumask_and(tmp, maskp, cpu_online_mask);
12814 		if (cpumask_weight(tmp) > 1)
12815 			continue;
12816 
12817 		/* Now that we have an irq to shutdown, get the eq
12818 		 * mapped to this irq.  Note: multiple hdwq's in
12819 		 * the software can share an eq, but eventually
12820 		 * only eq will be mapped to this vector
12821 		 */
12822 		eq = phba->sli4_hba.hba_eq_hdl[idx].eq;
12823 		list_add(&eq->_poll_list, eqlist);
12824 	}
12825 	kfree(tmp);
12826 	return 0;
12827 }
12828 
12829 static void __lpfc_cpuhp_remove(struct lpfc_hba *phba)
12830 {
12831 	if (phba->sli_rev != LPFC_SLI_REV4)
12832 		return;
12833 
12834 	cpuhp_state_remove_instance_nocalls(lpfc_cpuhp_state,
12835 					    &phba->cpuhp);
12836 	/*
12837 	 * unregistering the instance doesn't stop the polling
12838 	 * timer. Wait for the poll timer to retire.
12839 	 */
12840 	synchronize_rcu();
12841 	del_timer_sync(&phba->cpuhp_poll_timer);
12842 }
12843 
12844 static void lpfc_cpuhp_remove(struct lpfc_hba *phba)
12845 {
12846 	if (phba->pport && (phba->pport->fc_flag & FC_OFFLINE_MODE))
12847 		return;
12848 
12849 	__lpfc_cpuhp_remove(phba);
12850 }
12851 
12852 static void lpfc_cpuhp_add(struct lpfc_hba *phba)
12853 {
12854 	if (phba->sli_rev != LPFC_SLI_REV4)
12855 		return;
12856 
12857 	rcu_read_lock();
12858 
12859 	if (!list_empty(&phba->poll_list))
12860 		mod_timer(&phba->cpuhp_poll_timer,
12861 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
12862 
12863 	rcu_read_unlock();
12864 
12865 	cpuhp_state_add_instance_nocalls(lpfc_cpuhp_state,
12866 					 &phba->cpuhp);
12867 }
12868 
12869 static int __lpfc_cpuhp_checks(struct lpfc_hba *phba, int *retval)
12870 {
12871 	if (phba->pport->load_flag & FC_UNLOADING) {
12872 		*retval = -EAGAIN;
12873 		return true;
12874 	}
12875 
12876 	if (phba->sli_rev != LPFC_SLI_REV4) {
12877 		*retval = 0;
12878 		return true;
12879 	}
12880 
12881 	/* proceed with the hotplug */
12882 	return false;
12883 }
12884 
12885 /**
12886  * lpfc_irq_set_aff - set IRQ affinity
12887  * @eqhdl: EQ handle
12888  * @cpu: cpu to set affinity
12889  *
12890  **/
12891 static inline void
12892 lpfc_irq_set_aff(struct lpfc_hba_eq_hdl *eqhdl, unsigned int cpu)
12893 {
12894 	cpumask_clear(&eqhdl->aff_mask);
12895 	cpumask_set_cpu(cpu, &eqhdl->aff_mask);
12896 	irq_set_status_flags(eqhdl->irq, IRQ_NO_BALANCING);
12897 	irq_set_affinity(eqhdl->irq, &eqhdl->aff_mask);
12898 }
12899 
12900 /**
12901  * lpfc_irq_clear_aff - clear IRQ affinity
12902  * @eqhdl: EQ handle
12903  *
12904  **/
12905 static inline void
12906 lpfc_irq_clear_aff(struct lpfc_hba_eq_hdl *eqhdl)
12907 {
12908 	cpumask_clear(&eqhdl->aff_mask);
12909 	irq_clear_status_flags(eqhdl->irq, IRQ_NO_BALANCING);
12910 }
12911 
12912 /**
12913  * lpfc_irq_rebalance - rebalances IRQ affinity according to cpuhp event
12914  * @phba: pointer to HBA context object.
12915  * @cpu: cpu going offline/online
12916  * @offline: true, cpu is going offline. false, cpu is coming online.
12917  *
12918  * If cpu is going offline, we'll try our best effort to find the next
12919  * online cpu on the phba's original_mask and migrate all offlining IRQ
12920  * affinities.
12921  *
12922  * If cpu is coming online, reaffinitize the IRQ back to the onlining cpu.
12923  *
12924  * Note: Call only if NUMA or NHT mode is enabled, otherwise rely on
12925  *	 PCI_IRQ_AFFINITY to auto-manage IRQ affinity.
12926  *
12927  **/
12928 static void
12929 lpfc_irq_rebalance(struct lpfc_hba *phba, unsigned int cpu, bool offline)
12930 {
12931 	struct lpfc_vector_map_info *cpup;
12932 	struct cpumask *aff_mask;
12933 	unsigned int cpu_select, cpu_next, idx;
12934 	const struct cpumask *orig_mask;
12935 
12936 	if (phba->irq_chann_mode == NORMAL_MODE)
12937 		return;
12938 
12939 	orig_mask = &phba->sli4_hba.irq_aff_mask;
12940 
12941 	if (!cpumask_test_cpu(cpu, orig_mask))
12942 		return;
12943 
12944 	cpup = &phba->sli4_hba.cpu_map[cpu];
12945 
12946 	if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
12947 		return;
12948 
12949 	if (offline) {
12950 		/* Find next online CPU on original mask */
12951 		cpu_next = cpumask_next_wrap(cpu, orig_mask, cpu, true);
12952 		cpu_select = lpfc_next_online_cpu(orig_mask, cpu_next);
12953 
12954 		/* Found a valid CPU */
12955 		if ((cpu_select < nr_cpu_ids) && (cpu_select != cpu)) {
12956 			/* Go through each eqhdl and ensure offlining
12957 			 * cpu aff_mask is migrated
12958 			 */
12959 			for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
12960 				aff_mask = lpfc_get_aff_mask(idx);
12961 
12962 				/* Migrate affinity */
12963 				if (cpumask_test_cpu(cpu, aff_mask))
12964 					lpfc_irq_set_aff(lpfc_get_eq_hdl(idx),
12965 							 cpu_select);
12966 			}
12967 		} else {
12968 			/* Rely on irqbalance if no online CPUs left on NUMA */
12969 			for (idx = 0; idx < phba->cfg_irq_chann; idx++)
12970 				lpfc_irq_clear_aff(lpfc_get_eq_hdl(idx));
12971 		}
12972 	} else {
12973 		/* Migrate affinity back to this CPU */
12974 		lpfc_irq_set_aff(lpfc_get_eq_hdl(cpup->eq), cpu);
12975 	}
12976 }
12977 
12978 static int lpfc_cpu_offline(unsigned int cpu, struct hlist_node *node)
12979 {
12980 	struct lpfc_hba *phba = hlist_entry_safe(node, struct lpfc_hba, cpuhp);
12981 	struct lpfc_queue *eq, *next;
12982 	LIST_HEAD(eqlist);
12983 	int retval;
12984 
12985 	if (!phba) {
12986 		WARN_ONCE(!phba, "cpu: %u. phba:NULL", raw_smp_processor_id());
12987 		return 0;
12988 	}
12989 
12990 	if (__lpfc_cpuhp_checks(phba, &retval))
12991 		return retval;
12992 
12993 	lpfc_irq_rebalance(phba, cpu, true);
12994 
12995 	retval = lpfc_cpuhp_get_eq(phba, cpu, &eqlist);
12996 	if (retval)
12997 		return retval;
12998 
12999 	/* start polling on these eq's */
13000 	list_for_each_entry_safe(eq, next, &eqlist, _poll_list) {
13001 		list_del_init(&eq->_poll_list);
13002 		lpfc_sli4_start_polling(eq);
13003 	}
13004 
13005 	return 0;
13006 }
13007 
13008 static int lpfc_cpu_online(unsigned int cpu, struct hlist_node *node)
13009 {
13010 	struct lpfc_hba *phba = hlist_entry_safe(node, struct lpfc_hba, cpuhp);
13011 	struct lpfc_queue *eq, *next;
13012 	unsigned int n;
13013 	int retval;
13014 
13015 	if (!phba) {
13016 		WARN_ONCE(!phba, "cpu: %u. phba:NULL", raw_smp_processor_id());
13017 		return 0;
13018 	}
13019 
13020 	if (__lpfc_cpuhp_checks(phba, &retval))
13021 		return retval;
13022 
13023 	lpfc_irq_rebalance(phba, cpu, false);
13024 
13025 	list_for_each_entry_safe(eq, next, &phba->poll_list, _poll_list) {
13026 		n = lpfc_find_cpu_handle(phba, eq->hdwq, LPFC_FIND_BY_HDWQ);
13027 		if (n == cpu)
13028 			lpfc_sli4_stop_polling(eq);
13029 	}
13030 
13031 	return 0;
13032 }
13033 
13034 /**
13035  * lpfc_sli4_enable_msix - Enable MSI-X interrupt mode to SLI-4 device
13036  * @phba: pointer to lpfc hba data structure.
13037  *
13038  * This routine is invoked to enable the MSI-X interrupt vectors to device
13039  * with SLI-4 interface spec.  It also allocates MSI-X vectors and maps them
13040  * to cpus on the system.
13041  *
13042  * When cfg_irq_numa is enabled, the adapter will only allocate vectors for
13043  * the number of cpus on the same numa node as this adapter.  The vectors are
13044  * allocated without requesting OS affinity mapping.  A vector will be
13045  * allocated and assigned to each online and offline cpu.  If the cpu is
13046  * online, then affinity will be set to that cpu.  If the cpu is offline, then
13047  * affinity will be set to the nearest peer cpu within the numa node that is
13048  * online.  If there are no online cpus within the numa node, affinity is not
13049  * assigned and the OS may do as it pleases. Note: cpu vector affinity mapping
13050  * is consistent with the way cpu online/offline is handled when cfg_irq_numa is
13051  * configured.
13052  *
13053  * If numa mode is not enabled and there is more than 1 vector allocated, then
13054  * the driver relies on the managed irq interface where the OS assigns vector to
13055  * cpu affinity.  The driver will then use that affinity mapping to setup its
13056  * cpu mapping table.
13057  *
13058  * Return codes
13059  * 0 - successful
13060  * other values - error
13061  **/
13062 static int
13063 lpfc_sli4_enable_msix(struct lpfc_hba *phba)
13064 {
13065 	int vectors, rc, index;
13066 	char *name;
13067 	const struct cpumask *aff_mask = NULL;
13068 	unsigned int cpu = 0, cpu_cnt = 0, cpu_select = nr_cpu_ids;
13069 	struct lpfc_vector_map_info *cpup;
13070 	struct lpfc_hba_eq_hdl *eqhdl;
13071 	const struct cpumask *maskp;
13072 	unsigned int flags = PCI_IRQ_MSIX;
13073 
13074 	/* Set up MSI-X multi-message vectors */
13075 	vectors = phba->cfg_irq_chann;
13076 
13077 	if (phba->irq_chann_mode != NORMAL_MODE)
13078 		aff_mask = &phba->sli4_hba.irq_aff_mask;
13079 
13080 	if (aff_mask) {
13081 		cpu_cnt = cpumask_weight(aff_mask);
13082 		vectors = min(phba->cfg_irq_chann, cpu_cnt);
13083 
13084 		/* cpu: iterates over aff_mask including offline or online
13085 		 * cpu_select: iterates over online aff_mask to set affinity
13086 		 */
13087 		cpu = cpumask_first(aff_mask);
13088 		cpu_select = lpfc_next_online_cpu(aff_mask, cpu);
13089 	} else {
13090 		flags |= PCI_IRQ_AFFINITY;
13091 	}
13092 
13093 	rc = pci_alloc_irq_vectors(phba->pcidev, 1, vectors, flags);
13094 	if (rc < 0) {
13095 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13096 				"0484 PCI enable MSI-X failed (%d)\n", rc);
13097 		goto vec_fail_out;
13098 	}
13099 	vectors = rc;
13100 
13101 	/* Assign MSI-X vectors to interrupt handlers */
13102 	for (index = 0; index < vectors; index++) {
13103 		eqhdl = lpfc_get_eq_hdl(index);
13104 		name = eqhdl->handler_name;
13105 		memset(name, 0, LPFC_SLI4_HANDLER_NAME_SZ);
13106 		snprintf(name, LPFC_SLI4_HANDLER_NAME_SZ,
13107 			 LPFC_DRIVER_HANDLER_NAME"%d", index);
13108 
13109 		eqhdl->idx = index;
13110 		rc = pci_irq_vector(phba->pcidev, index);
13111 		if (rc < 0) {
13112 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13113 					"0489 MSI-X fast-path (%d) "
13114 					"pci_irq_vec failed (%d)\n", index, rc);
13115 			goto cfg_fail_out;
13116 		}
13117 		eqhdl->irq = rc;
13118 
13119 		rc = request_irq(eqhdl->irq, &lpfc_sli4_hba_intr_handler, 0,
13120 				 name, eqhdl);
13121 		if (rc) {
13122 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13123 					"0486 MSI-X fast-path (%d) "
13124 					"request_irq failed (%d)\n", index, rc);
13125 			goto cfg_fail_out;
13126 		}
13127 
13128 		if (aff_mask) {
13129 			/* If found a neighboring online cpu, set affinity */
13130 			if (cpu_select < nr_cpu_ids)
13131 				lpfc_irq_set_aff(eqhdl, cpu_select);
13132 
13133 			/* Assign EQ to cpu_map */
13134 			lpfc_assign_eq_map_info(phba, index,
13135 						LPFC_CPU_FIRST_IRQ,
13136 						cpu);
13137 
13138 			/* Iterate to next offline or online cpu in aff_mask */
13139 			cpu = cpumask_next(cpu, aff_mask);
13140 
13141 			/* Find next online cpu in aff_mask to set affinity */
13142 			cpu_select = lpfc_next_online_cpu(aff_mask, cpu);
13143 		} else if (vectors == 1) {
13144 			cpu = cpumask_first(cpu_present_mask);
13145 			lpfc_assign_eq_map_info(phba, index, LPFC_CPU_FIRST_IRQ,
13146 						cpu);
13147 		} else {
13148 			maskp = pci_irq_get_affinity(phba->pcidev, index);
13149 
13150 			/* Loop through all CPUs associated with vector index */
13151 			for_each_cpu_and(cpu, maskp, cpu_present_mask) {
13152 				cpup = &phba->sli4_hba.cpu_map[cpu];
13153 
13154 				/* If this is the first CPU thats assigned to
13155 				 * this vector, set LPFC_CPU_FIRST_IRQ.
13156 				 *
13157 				 * With certain platforms its possible that irq
13158 				 * vectors are affinitized to all the cpu's.
13159 				 * This can result in each cpu_map.eq to be set
13160 				 * to the last vector, resulting in overwrite
13161 				 * of all the previous cpu_map.eq.  Ensure that
13162 				 * each vector receives a place in cpu_map.
13163 				 * Later call to lpfc_cpu_affinity_check will
13164 				 * ensure we are nicely balanced out.
13165 				 */
13166 				if (cpup->eq != LPFC_VECTOR_MAP_EMPTY)
13167 					continue;
13168 				lpfc_assign_eq_map_info(phba, index,
13169 							LPFC_CPU_FIRST_IRQ,
13170 							cpu);
13171 				break;
13172 			}
13173 		}
13174 	}
13175 
13176 	if (vectors != phba->cfg_irq_chann) {
13177 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13178 				"3238 Reducing IO channels to match number of "
13179 				"MSI-X vectors, requested %d got %d\n",
13180 				phba->cfg_irq_chann, vectors);
13181 		if (phba->cfg_irq_chann > vectors)
13182 			phba->cfg_irq_chann = vectors;
13183 	}
13184 
13185 	return rc;
13186 
13187 cfg_fail_out:
13188 	/* free the irq already requested */
13189 	for (--index; index >= 0; index--) {
13190 		eqhdl = lpfc_get_eq_hdl(index);
13191 		lpfc_irq_clear_aff(eqhdl);
13192 		free_irq(eqhdl->irq, eqhdl);
13193 	}
13194 
13195 	/* Unconfigure MSI-X capability structure */
13196 	pci_free_irq_vectors(phba->pcidev);
13197 
13198 vec_fail_out:
13199 	return rc;
13200 }
13201 
13202 /**
13203  * lpfc_sli4_enable_msi - Enable MSI interrupt mode to SLI-4 device
13204  * @phba: pointer to lpfc hba data structure.
13205  *
13206  * This routine is invoked to enable the MSI interrupt mode to device with
13207  * SLI-4 interface spec. The kernel function pci_alloc_irq_vectors() is
13208  * called to enable the MSI vector. The device driver is responsible for
13209  * calling the request_irq() to register MSI vector with a interrupt the
13210  * handler, which is done in this function.
13211  *
13212  * Return codes
13213  * 	0 - successful
13214  * 	other values - error
13215  **/
13216 static int
13217 lpfc_sli4_enable_msi(struct lpfc_hba *phba)
13218 {
13219 	int rc, index;
13220 	unsigned int cpu;
13221 	struct lpfc_hba_eq_hdl *eqhdl;
13222 
13223 	rc = pci_alloc_irq_vectors(phba->pcidev, 1, 1,
13224 				   PCI_IRQ_MSI | PCI_IRQ_AFFINITY);
13225 	if (rc > 0)
13226 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13227 				"0487 PCI enable MSI mode success.\n");
13228 	else {
13229 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13230 				"0488 PCI enable MSI mode failed (%d)\n", rc);
13231 		return rc ? rc : -1;
13232 	}
13233 
13234 	rc = request_irq(phba->pcidev->irq, lpfc_sli4_intr_handler,
13235 			 0, LPFC_DRIVER_NAME, phba);
13236 	if (rc) {
13237 		pci_free_irq_vectors(phba->pcidev);
13238 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13239 				"0490 MSI request_irq failed (%d)\n", rc);
13240 		return rc;
13241 	}
13242 
13243 	eqhdl = lpfc_get_eq_hdl(0);
13244 	rc = pci_irq_vector(phba->pcidev, 0);
13245 	if (rc < 0) {
13246 		pci_free_irq_vectors(phba->pcidev);
13247 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13248 				"0496 MSI pci_irq_vec failed (%d)\n", rc);
13249 		return rc;
13250 	}
13251 	eqhdl->irq = rc;
13252 
13253 	cpu = cpumask_first(cpu_present_mask);
13254 	lpfc_assign_eq_map_info(phba, 0, LPFC_CPU_FIRST_IRQ, cpu);
13255 
13256 	for (index = 0; index < phba->cfg_irq_chann; index++) {
13257 		eqhdl = lpfc_get_eq_hdl(index);
13258 		eqhdl->idx = index;
13259 	}
13260 
13261 	return 0;
13262 }
13263 
13264 /**
13265  * lpfc_sli4_enable_intr - Enable device interrupt to SLI-4 device
13266  * @phba: pointer to lpfc hba data structure.
13267  * @cfg_mode: Interrupt configuration mode (INTx, MSI or MSI-X).
13268  *
13269  * This routine is invoked to enable device interrupt and associate driver's
13270  * interrupt handler(s) to interrupt vector(s) to device with SLI-4
13271  * interface spec. Depends on the interrupt mode configured to the driver,
13272  * the driver will try to fallback from the configured interrupt mode to an
13273  * interrupt mode which is supported by the platform, kernel, and device in
13274  * the order of:
13275  * MSI-X -> MSI -> IRQ.
13276  *
13277  * Return codes
13278  *	Interrupt mode (2, 1, 0) - successful
13279  *	LPFC_INTR_ERROR - error
13280  **/
13281 static uint32_t
13282 lpfc_sli4_enable_intr(struct lpfc_hba *phba, uint32_t cfg_mode)
13283 {
13284 	uint32_t intr_mode = LPFC_INTR_ERROR;
13285 	int retval, idx;
13286 
13287 	if (cfg_mode == 2) {
13288 		/* Preparation before conf_msi mbox cmd */
13289 		retval = 0;
13290 		if (!retval) {
13291 			/* Now, try to enable MSI-X interrupt mode */
13292 			retval = lpfc_sli4_enable_msix(phba);
13293 			if (!retval) {
13294 				/* Indicate initialization to MSI-X mode */
13295 				phba->intr_type = MSIX;
13296 				intr_mode = 2;
13297 			}
13298 		}
13299 	}
13300 
13301 	/* Fallback to MSI if MSI-X initialization failed */
13302 	if (cfg_mode >= 1 && phba->intr_type == NONE) {
13303 		retval = lpfc_sli4_enable_msi(phba);
13304 		if (!retval) {
13305 			/* Indicate initialization to MSI mode */
13306 			phba->intr_type = MSI;
13307 			intr_mode = 1;
13308 		}
13309 	}
13310 
13311 	/* Fallback to INTx if both MSI-X/MSI initalization failed */
13312 	if (phba->intr_type == NONE) {
13313 		retval = request_irq(phba->pcidev->irq, lpfc_sli4_intr_handler,
13314 				     IRQF_SHARED, LPFC_DRIVER_NAME, phba);
13315 		if (!retval) {
13316 			struct lpfc_hba_eq_hdl *eqhdl;
13317 			unsigned int cpu;
13318 
13319 			/* Indicate initialization to INTx mode */
13320 			phba->intr_type = INTx;
13321 			intr_mode = 0;
13322 
13323 			eqhdl = lpfc_get_eq_hdl(0);
13324 			retval = pci_irq_vector(phba->pcidev, 0);
13325 			if (retval < 0) {
13326 				lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13327 					"0502 INTR pci_irq_vec failed (%d)\n",
13328 					 retval);
13329 				return LPFC_INTR_ERROR;
13330 			}
13331 			eqhdl->irq = retval;
13332 
13333 			cpu = cpumask_first(cpu_present_mask);
13334 			lpfc_assign_eq_map_info(phba, 0, LPFC_CPU_FIRST_IRQ,
13335 						cpu);
13336 			for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
13337 				eqhdl = lpfc_get_eq_hdl(idx);
13338 				eqhdl->idx = idx;
13339 			}
13340 		}
13341 	}
13342 	return intr_mode;
13343 }
13344 
13345 /**
13346  * lpfc_sli4_disable_intr - Disable device interrupt to SLI-4 device
13347  * @phba: pointer to lpfc hba data structure.
13348  *
13349  * This routine is invoked to disable device interrupt and disassociate
13350  * the driver's interrupt handler(s) from interrupt vector(s) to device
13351  * with SLI-4 interface spec. Depending on the interrupt mode, the driver
13352  * will release the interrupt vector(s) for the message signaled interrupt.
13353  **/
13354 static void
13355 lpfc_sli4_disable_intr(struct lpfc_hba *phba)
13356 {
13357 	/* Disable the currently initialized interrupt mode */
13358 	if (phba->intr_type == MSIX) {
13359 		int index;
13360 		struct lpfc_hba_eq_hdl *eqhdl;
13361 
13362 		/* Free up MSI-X multi-message vectors */
13363 		for (index = 0; index < phba->cfg_irq_chann; index++) {
13364 			eqhdl = lpfc_get_eq_hdl(index);
13365 			lpfc_irq_clear_aff(eqhdl);
13366 			free_irq(eqhdl->irq, eqhdl);
13367 		}
13368 	} else {
13369 		free_irq(phba->pcidev->irq, phba);
13370 	}
13371 
13372 	pci_free_irq_vectors(phba->pcidev);
13373 
13374 	/* Reset interrupt management states */
13375 	phba->intr_type = NONE;
13376 	phba->sli.slistat.sli_intr = 0;
13377 }
13378 
13379 /**
13380  * lpfc_unset_hba - Unset SLI3 hba device initialization
13381  * @phba: pointer to lpfc hba data structure.
13382  *
13383  * This routine is invoked to unset the HBA device initialization steps to
13384  * a device with SLI-3 interface spec.
13385  **/
13386 static void
13387 lpfc_unset_hba(struct lpfc_hba *phba)
13388 {
13389 	struct lpfc_vport *vport = phba->pport;
13390 	struct Scsi_Host  *shost = lpfc_shost_from_vport(vport);
13391 
13392 	spin_lock_irq(shost->host_lock);
13393 	vport->load_flag |= FC_UNLOADING;
13394 	spin_unlock_irq(shost->host_lock);
13395 
13396 	kfree(phba->vpi_bmask);
13397 	kfree(phba->vpi_ids);
13398 
13399 	lpfc_stop_hba_timers(phba);
13400 
13401 	phba->pport->work_port_events = 0;
13402 
13403 	lpfc_sli_hba_down(phba);
13404 
13405 	lpfc_sli_brdrestart(phba);
13406 
13407 	lpfc_sli_disable_intr(phba);
13408 
13409 	return;
13410 }
13411 
13412 /**
13413  * lpfc_sli4_xri_exchange_busy_wait - Wait for device XRI exchange busy
13414  * @phba: Pointer to HBA context object.
13415  *
13416  * This function is called in the SLI4 code path to wait for completion
13417  * of device's XRIs exchange busy. It will check the XRI exchange busy
13418  * on outstanding FCP and ELS I/Os every 10ms for up to 10 seconds; after
13419  * that, it will check the XRI exchange busy on outstanding FCP and ELS
13420  * I/Os every 30 seconds, log error message, and wait forever. Only when
13421  * all XRI exchange busy complete, the driver unload shall proceed with
13422  * invoking the function reset ioctl mailbox command to the CNA and the
13423  * the rest of the driver unload resource release.
13424  **/
13425 static void
13426 lpfc_sli4_xri_exchange_busy_wait(struct lpfc_hba *phba)
13427 {
13428 	struct lpfc_sli4_hdw_queue *qp;
13429 	int idx, ccnt;
13430 	int wait_time = 0;
13431 	int io_xri_cmpl = 1;
13432 	int nvmet_xri_cmpl = 1;
13433 	int els_xri_cmpl = list_empty(&phba->sli4_hba.lpfc_abts_els_sgl_list);
13434 
13435 	/* Driver just aborted IOs during the hba_unset process.  Pause
13436 	 * here to give the HBA time to complete the IO and get entries
13437 	 * into the abts lists.
13438 	 */
13439 	msleep(LPFC_XRI_EXCH_BUSY_WAIT_T1 * 5);
13440 
13441 	/* Wait for NVME pending IO to flush back to transport. */
13442 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
13443 		lpfc_nvme_wait_for_io_drain(phba);
13444 
13445 	ccnt = 0;
13446 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
13447 		qp = &phba->sli4_hba.hdwq[idx];
13448 		io_xri_cmpl = list_empty(&qp->lpfc_abts_io_buf_list);
13449 		if (!io_xri_cmpl) /* if list is NOT empty */
13450 			ccnt++;
13451 	}
13452 	if (ccnt)
13453 		io_xri_cmpl = 0;
13454 
13455 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13456 		nvmet_xri_cmpl =
13457 			list_empty(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
13458 	}
13459 
13460 	while (!els_xri_cmpl || !io_xri_cmpl || !nvmet_xri_cmpl) {
13461 		if (wait_time > LPFC_XRI_EXCH_BUSY_WAIT_TMO) {
13462 			if (!nvmet_xri_cmpl)
13463 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13464 						"6424 NVMET XRI exchange busy "
13465 						"wait time: %d seconds.\n",
13466 						wait_time/1000);
13467 			if (!io_xri_cmpl)
13468 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13469 						"6100 IO XRI exchange busy "
13470 						"wait time: %d seconds.\n",
13471 						wait_time/1000);
13472 			if (!els_xri_cmpl)
13473 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13474 						"2878 ELS XRI exchange busy "
13475 						"wait time: %d seconds.\n",
13476 						wait_time/1000);
13477 			msleep(LPFC_XRI_EXCH_BUSY_WAIT_T2);
13478 			wait_time += LPFC_XRI_EXCH_BUSY_WAIT_T2;
13479 		} else {
13480 			msleep(LPFC_XRI_EXCH_BUSY_WAIT_T1);
13481 			wait_time += LPFC_XRI_EXCH_BUSY_WAIT_T1;
13482 		}
13483 
13484 		ccnt = 0;
13485 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
13486 			qp = &phba->sli4_hba.hdwq[idx];
13487 			io_xri_cmpl = list_empty(
13488 			    &qp->lpfc_abts_io_buf_list);
13489 			if (!io_xri_cmpl) /* if list is NOT empty */
13490 				ccnt++;
13491 		}
13492 		if (ccnt)
13493 			io_xri_cmpl = 0;
13494 
13495 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13496 			nvmet_xri_cmpl = list_empty(
13497 				&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
13498 		}
13499 		els_xri_cmpl =
13500 			list_empty(&phba->sli4_hba.lpfc_abts_els_sgl_list);
13501 
13502 	}
13503 }
13504 
13505 /**
13506  * lpfc_sli4_hba_unset - Unset the fcoe hba
13507  * @phba: Pointer to HBA context object.
13508  *
13509  * This function is called in the SLI4 code path to reset the HBA's FCoE
13510  * function. The caller is not required to hold any lock. This routine
13511  * issues PCI function reset mailbox command to reset the FCoE function.
13512  * At the end of the function, it calls lpfc_hba_down_post function to
13513  * free any pending commands.
13514  **/
13515 static void
13516 lpfc_sli4_hba_unset(struct lpfc_hba *phba)
13517 {
13518 	int wait_cnt = 0;
13519 	LPFC_MBOXQ_t *mboxq;
13520 	struct pci_dev *pdev = phba->pcidev;
13521 
13522 	lpfc_stop_hba_timers(phba);
13523 	hrtimer_cancel(&phba->cmf_timer);
13524 
13525 	if (phba->pport)
13526 		phba->sli4_hba.intr_enable = 0;
13527 
13528 	/*
13529 	 * Gracefully wait out the potential current outstanding asynchronous
13530 	 * mailbox command.
13531 	 */
13532 
13533 	/* First, block any pending async mailbox command from posted */
13534 	spin_lock_irq(&phba->hbalock);
13535 	phba->sli.sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
13536 	spin_unlock_irq(&phba->hbalock);
13537 	/* Now, trying to wait it out if we can */
13538 	while (phba->sli.sli_flag & LPFC_SLI_MBOX_ACTIVE) {
13539 		msleep(10);
13540 		if (++wait_cnt > LPFC_ACTIVE_MBOX_WAIT_CNT)
13541 			break;
13542 	}
13543 	/* Forcefully release the outstanding mailbox command if timed out */
13544 	if (phba->sli.sli_flag & LPFC_SLI_MBOX_ACTIVE) {
13545 		spin_lock_irq(&phba->hbalock);
13546 		mboxq = phba->sli.mbox_active;
13547 		mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
13548 		__lpfc_mbox_cmpl_put(phba, mboxq);
13549 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
13550 		phba->sli.mbox_active = NULL;
13551 		spin_unlock_irq(&phba->hbalock);
13552 	}
13553 
13554 	/* Abort all iocbs associated with the hba */
13555 	lpfc_sli_hba_iocb_abort(phba);
13556 
13557 	if (!pci_channel_offline(phba->pcidev))
13558 		/* Wait for completion of device XRI exchange busy */
13559 		lpfc_sli4_xri_exchange_busy_wait(phba);
13560 
13561 	/* per-phba callback de-registration for hotplug event */
13562 	if (phba->pport)
13563 		lpfc_cpuhp_remove(phba);
13564 
13565 	/* Disable PCI subsystem interrupt */
13566 	lpfc_sli4_disable_intr(phba);
13567 
13568 	/* Disable SR-IOV if enabled */
13569 	if (phba->cfg_sriov_nr_virtfn)
13570 		pci_disable_sriov(pdev);
13571 
13572 	/* Stop kthread signal shall trigger work_done one more time */
13573 	kthread_stop(phba->worker_thread);
13574 
13575 	/* Disable FW logging to host memory */
13576 	lpfc_ras_stop_fwlog(phba);
13577 
13578 	/* Reset SLI4 HBA FCoE function */
13579 	lpfc_pci_function_reset(phba);
13580 
13581 	/* release all queue allocated resources. */
13582 	lpfc_sli4_queue_destroy(phba);
13583 
13584 	/* Free RAS DMA memory */
13585 	if (phba->ras_fwlog.ras_enabled)
13586 		lpfc_sli4_ras_dma_free(phba);
13587 
13588 	/* Stop the SLI4 device port */
13589 	if (phba->pport)
13590 		phba->pport->work_port_events = 0;
13591 }
13592 
13593 static uint32_t
13594 lpfc_cgn_crc32(uint32_t crc, u8 byte)
13595 {
13596 	uint32_t msb = 0;
13597 	uint32_t bit;
13598 
13599 	for (bit = 0; bit < 8; bit++) {
13600 		msb = (crc >> 31) & 1;
13601 		crc <<= 1;
13602 
13603 		if (msb ^ (byte & 1)) {
13604 			crc ^= LPFC_CGN_CRC32_MAGIC_NUMBER;
13605 			crc |= 1;
13606 		}
13607 		byte >>= 1;
13608 	}
13609 	return crc;
13610 }
13611 
13612 static uint32_t
13613 lpfc_cgn_reverse_bits(uint32_t wd)
13614 {
13615 	uint32_t result = 0;
13616 	uint32_t i;
13617 
13618 	for (i = 0; i < 32; i++) {
13619 		result <<= 1;
13620 		result |= (1 & (wd >> i));
13621 	}
13622 	return result;
13623 }
13624 
13625 /*
13626  * The routine corresponds with the algorithm the HBA firmware
13627  * uses to validate the data integrity.
13628  */
13629 uint32_t
13630 lpfc_cgn_calc_crc32(void *ptr, uint32_t byteLen, uint32_t crc)
13631 {
13632 	uint32_t  i;
13633 	uint32_t result;
13634 	uint8_t  *data = (uint8_t *)ptr;
13635 
13636 	for (i = 0; i < byteLen; ++i)
13637 		crc = lpfc_cgn_crc32(crc, data[i]);
13638 
13639 	result = ~lpfc_cgn_reverse_bits(crc);
13640 	return result;
13641 }
13642 
13643 void
13644 lpfc_init_congestion_buf(struct lpfc_hba *phba)
13645 {
13646 	struct lpfc_cgn_info *cp;
13647 	struct timespec64 cmpl_time;
13648 	struct tm broken;
13649 	uint16_t size;
13650 	uint32_t crc;
13651 
13652 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
13653 			"6235 INIT Congestion Buffer %p\n", phba->cgn_i);
13654 
13655 	if (!phba->cgn_i)
13656 		return;
13657 	cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
13658 
13659 	atomic_set(&phba->cgn_fabric_warn_cnt, 0);
13660 	atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
13661 	atomic_set(&phba->cgn_sync_alarm_cnt, 0);
13662 	atomic_set(&phba->cgn_sync_warn_cnt, 0);
13663 
13664 	atomic_set(&phba->cgn_driver_evt_cnt, 0);
13665 	atomic_set(&phba->cgn_latency_evt_cnt, 0);
13666 	atomic64_set(&phba->cgn_latency_evt, 0);
13667 	phba->cgn_evt_minute = 0;
13668 	phba->hba_flag &= ~HBA_CGN_DAY_WRAP;
13669 
13670 	memset(cp, 0xff, offsetof(struct lpfc_cgn_info, cgn_stat));
13671 	cp->cgn_info_size = cpu_to_le16(LPFC_CGN_INFO_SZ);
13672 	cp->cgn_info_version = LPFC_CGN_INFO_V3;
13673 
13674 	/* cgn parameters */
13675 	cp->cgn_info_mode = phba->cgn_p.cgn_param_mode;
13676 	cp->cgn_info_level0 = phba->cgn_p.cgn_param_level0;
13677 	cp->cgn_info_level1 = phba->cgn_p.cgn_param_level1;
13678 	cp->cgn_info_level2 = phba->cgn_p.cgn_param_level2;
13679 
13680 	ktime_get_real_ts64(&cmpl_time);
13681 	time64_to_tm(cmpl_time.tv_sec, 0, &broken);
13682 
13683 	cp->cgn_info_month = broken.tm_mon + 1;
13684 	cp->cgn_info_day = broken.tm_mday;
13685 	cp->cgn_info_year = broken.tm_year - 100; /* relative to 2000 */
13686 	cp->cgn_info_hour = broken.tm_hour;
13687 	cp->cgn_info_minute = broken.tm_min;
13688 	cp->cgn_info_second = broken.tm_sec;
13689 
13690 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT | LOG_INIT,
13691 			"2643 CGNInfo Init: Start Time "
13692 			"%d/%d/%d %d:%d:%d\n",
13693 			cp->cgn_info_day, cp->cgn_info_month,
13694 			cp->cgn_info_year, cp->cgn_info_hour,
13695 			cp->cgn_info_minute, cp->cgn_info_second);
13696 
13697 	/* Fill in default LUN qdepth */
13698 	if (phba->pport) {
13699 		size = (uint16_t)(phba->pport->cfg_lun_queue_depth);
13700 		cp->cgn_lunq = cpu_to_le16(size);
13701 	}
13702 
13703 	/* last used Index initialized to 0xff already */
13704 
13705 	cp->cgn_warn_freq = cpu_to_le16(LPFC_FPIN_INIT_FREQ);
13706 	cp->cgn_alarm_freq = cpu_to_le16(LPFC_FPIN_INIT_FREQ);
13707 	crc = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ, LPFC_CGN_CRC32_SEED);
13708 	cp->cgn_info_crc = cpu_to_le32(crc);
13709 
13710 	phba->cgn_evt_timestamp = jiffies +
13711 		msecs_to_jiffies(LPFC_CGN_TIMER_TO_MIN);
13712 }
13713 
13714 void
13715 lpfc_init_congestion_stat(struct lpfc_hba *phba)
13716 {
13717 	struct lpfc_cgn_info *cp;
13718 	struct timespec64 cmpl_time;
13719 	struct tm broken;
13720 	uint32_t crc;
13721 
13722 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
13723 			"6236 INIT Congestion Stat %p\n", phba->cgn_i);
13724 
13725 	if (!phba->cgn_i)
13726 		return;
13727 
13728 	cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
13729 	memset(&cp->cgn_stat, 0, sizeof(cp->cgn_stat));
13730 
13731 	ktime_get_real_ts64(&cmpl_time);
13732 	time64_to_tm(cmpl_time.tv_sec, 0, &broken);
13733 
13734 	cp->cgn_stat_month = broken.tm_mon + 1;
13735 	cp->cgn_stat_day = broken.tm_mday;
13736 	cp->cgn_stat_year = broken.tm_year - 100; /* relative to 2000 */
13737 	cp->cgn_stat_hour = broken.tm_hour;
13738 	cp->cgn_stat_minute = broken.tm_min;
13739 
13740 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT | LOG_INIT,
13741 			"2647 CGNstat Init: Start Time "
13742 			"%d/%d/%d %d:%d\n",
13743 			cp->cgn_stat_day, cp->cgn_stat_month,
13744 			cp->cgn_stat_year, cp->cgn_stat_hour,
13745 			cp->cgn_stat_minute);
13746 
13747 	crc = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ, LPFC_CGN_CRC32_SEED);
13748 	cp->cgn_info_crc = cpu_to_le32(crc);
13749 }
13750 
13751 /**
13752  * __lpfc_reg_congestion_buf - register congestion info buffer with HBA
13753  * @phba: Pointer to hba context object.
13754  * @reg: flag to determine register or unregister.
13755  */
13756 static int
13757 __lpfc_reg_congestion_buf(struct lpfc_hba *phba, int reg)
13758 {
13759 	struct lpfc_mbx_reg_congestion_buf *reg_congestion_buf;
13760 	union  lpfc_sli4_cfg_shdr *shdr;
13761 	uint32_t shdr_status, shdr_add_status;
13762 	LPFC_MBOXQ_t *mboxq;
13763 	int length, rc;
13764 
13765 	if (!phba->cgn_i)
13766 		return -ENXIO;
13767 
13768 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
13769 	if (!mboxq) {
13770 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX,
13771 				"2641 REG_CONGESTION_BUF mbox allocation fail: "
13772 				"HBA state x%x reg %d\n",
13773 				phba->pport->port_state, reg);
13774 		return -ENOMEM;
13775 	}
13776 
13777 	length = (sizeof(struct lpfc_mbx_reg_congestion_buf) -
13778 		sizeof(struct lpfc_sli4_cfg_mhdr));
13779 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
13780 			 LPFC_MBOX_OPCODE_REG_CONGESTION_BUF, length,
13781 			 LPFC_SLI4_MBX_EMBED);
13782 	reg_congestion_buf = &mboxq->u.mqe.un.reg_congestion_buf;
13783 	bf_set(lpfc_mbx_reg_cgn_buf_type, reg_congestion_buf, 1);
13784 	if (reg > 0)
13785 		bf_set(lpfc_mbx_reg_cgn_buf_cnt, reg_congestion_buf, 1);
13786 	else
13787 		bf_set(lpfc_mbx_reg_cgn_buf_cnt, reg_congestion_buf, 0);
13788 	reg_congestion_buf->length = sizeof(struct lpfc_cgn_info);
13789 	reg_congestion_buf->addr_lo =
13790 		putPaddrLow(phba->cgn_i->phys);
13791 	reg_congestion_buf->addr_hi =
13792 		putPaddrHigh(phba->cgn_i->phys);
13793 
13794 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
13795 	shdr = (union lpfc_sli4_cfg_shdr *)
13796 		&mboxq->u.mqe.un.sli4_config.header.cfg_shdr;
13797 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13798 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
13799 				 &shdr->response);
13800 	mempool_free(mboxq, phba->mbox_mem_pool);
13801 	if (shdr_status || shdr_add_status || rc) {
13802 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13803 				"2642 REG_CONGESTION_BUF mailbox "
13804 				"failed with status x%x add_status x%x,"
13805 				" mbx status x%x reg %d\n",
13806 				shdr_status, shdr_add_status, rc, reg);
13807 		return -ENXIO;
13808 	}
13809 	return 0;
13810 }
13811 
13812 int
13813 lpfc_unreg_congestion_buf(struct lpfc_hba *phba)
13814 {
13815 	lpfc_cmf_stop(phba);
13816 	return __lpfc_reg_congestion_buf(phba, 0);
13817 }
13818 
13819 int
13820 lpfc_reg_congestion_buf(struct lpfc_hba *phba)
13821 {
13822 	return __lpfc_reg_congestion_buf(phba, 1);
13823 }
13824 
13825 /**
13826  * lpfc_get_sli4_parameters - Get the SLI4 Config PARAMETERS.
13827  * @phba: Pointer to HBA context object.
13828  * @mboxq: Pointer to the mailboxq memory for the mailbox command response.
13829  *
13830  * This function is called in the SLI4 code path to read the port's
13831  * sli4 capabilities.
13832  *
13833  * This function may be be called from any context that can block-wait
13834  * for the completion.  The expectation is that this routine is called
13835  * typically from probe_one or from the online routine.
13836  **/
13837 int
13838 lpfc_get_sli4_parameters(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
13839 {
13840 	int rc;
13841 	struct lpfc_mqe *mqe = &mboxq->u.mqe;
13842 	struct lpfc_pc_sli4_params *sli4_params;
13843 	uint32_t mbox_tmo;
13844 	int length;
13845 	bool exp_wqcq_pages = true;
13846 	struct lpfc_sli4_parameters *mbx_sli4_parameters;
13847 
13848 	/*
13849 	 * By default, the driver assumes the SLI4 port requires RPI
13850 	 * header postings.  The SLI4_PARAM response will correct this
13851 	 * assumption.
13852 	 */
13853 	phba->sli4_hba.rpi_hdrs_in_use = 1;
13854 
13855 	/* Read the port's SLI4 Config Parameters */
13856 	length = (sizeof(struct lpfc_mbx_get_sli4_parameters) -
13857 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13858 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
13859 			 LPFC_MBOX_OPCODE_GET_SLI4_PARAMETERS,
13860 			 length, LPFC_SLI4_MBX_EMBED);
13861 	if (!phba->sli4_hba.intr_enable)
13862 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
13863 	else {
13864 		mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
13865 		rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
13866 	}
13867 	if (unlikely(rc))
13868 		return rc;
13869 	sli4_params = &phba->sli4_hba.pc_sli4_params;
13870 	mbx_sli4_parameters = &mqe->un.get_sli4_parameters.sli4_parameters;
13871 	sli4_params->if_type = bf_get(cfg_if_type, mbx_sli4_parameters);
13872 	sli4_params->sli_rev = bf_get(cfg_sli_rev, mbx_sli4_parameters);
13873 	sli4_params->sli_family = bf_get(cfg_sli_family, mbx_sli4_parameters);
13874 	sli4_params->featurelevel_1 = bf_get(cfg_sli_hint_1,
13875 					     mbx_sli4_parameters);
13876 	sli4_params->featurelevel_2 = bf_get(cfg_sli_hint_2,
13877 					     mbx_sli4_parameters);
13878 	if (bf_get(cfg_phwq, mbx_sli4_parameters))
13879 		phba->sli3_options |= LPFC_SLI4_PHWQ_ENABLED;
13880 	else
13881 		phba->sli3_options &= ~LPFC_SLI4_PHWQ_ENABLED;
13882 	sli4_params->sge_supp_len = mbx_sli4_parameters->sge_supp_len;
13883 	sli4_params->loopbk_scope = bf_get(cfg_loopbk_scope,
13884 					   mbx_sli4_parameters);
13885 	sli4_params->oas_supported = bf_get(cfg_oas, mbx_sli4_parameters);
13886 	sli4_params->cqv = bf_get(cfg_cqv, mbx_sli4_parameters);
13887 	sli4_params->mqv = bf_get(cfg_mqv, mbx_sli4_parameters);
13888 	sli4_params->wqv = bf_get(cfg_wqv, mbx_sli4_parameters);
13889 	sli4_params->rqv = bf_get(cfg_rqv, mbx_sli4_parameters);
13890 	sli4_params->eqav = bf_get(cfg_eqav, mbx_sli4_parameters);
13891 	sli4_params->cqav = bf_get(cfg_cqav, mbx_sli4_parameters);
13892 	sli4_params->wqsize = bf_get(cfg_wqsize, mbx_sli4_parameters);
13893 	sli4_params->bv1s = bf_get(cfg_bv1s, mbx_sli4_parameters);
13894 	sli4_params->pls = bf_get(cfg_pvl, mbx_sli4_parameters);
13895 	sli4_params->sgl_pages_max = bf_get(cfg_sgl_page_cnt,
13896 					    mbx_sli4_parameters);
13897 	sli4_params->wqpcnt = bf_get(cfg_wqpcnt, mbx_sli4_parameters);
13898 	sli4_params->sgl_pp_align = bf_get(cfg_sgl_pp_align,
13899 					   mbx_sli4_parameters);
13900 	phba->sli4_hba.extents_in_use = bf_get(cfg_ext, mbx_sli4_parameters);
13901 	phba->sli4_hba.rpi_hdrs_in_use = bf_get(cfg_hdrr, mbx_sli4_parameters);
13902 	sli4_params->mi_cap = bf_get(cfg_mi_ver, mbx_sli4_parameters);
13903 
13904 	/* Check for Extended Pre-Registered SGL support */
13905 	phba->cfg_xpsgl = bf_get(cfg_xpsgl, mbx_sli4_parameters);
13906 
13907 	/* Check for firmware nvme support */
13908 	rc = (bf_get(cfg_nvme, mbx_sli4_parameters) &&
13909 		     bf_get(cfg_xib, mbx_sli4_parameters));
13910 
13911 	if (rc) {
13912 		/* Save this to indicate the Firmware supports NVME */
13913 		sli4_params->nvme = 1;
13914 
13915 		/* Firmware NVME support, check driver FC4 NVME support */
13916 		if (phba->cfg_enable_fc4_type == LPFC_ENABLE_FCP) {
13917 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_NVME,
13918 					"6133 Disabling NVME support: "
13919 					"FC4 type not supported: x%x\n",
13920 					phba->cfg_enable_fc4_type);
13921 			goto fcponly;
13922 		}
13923 	} else {
13924 		/* No firmware NVME support, check driver FC4 NVME support */
13925 		sli4_params->nvme = 0;
13926 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13927 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_NVME,
13928 					"6101 Disabling NVME support: Not "
13929 					"supported by firmware (%d %d) x%x\n",
13930 					bf_get(cfg_nvme, mbx_sli4_parameters),
13931 					bf_get(cfg_xib, mbx_sli4_parameters),
13932 					phba->cfg_enable_fc4_type);
13933 fcponly:
13934 			phba->nvmet_support = 0;
13935 			phba->cfg_nvmet_mrq = 0;
13936 			phba->cfg_nvme_seg_cnt = 0;
13937 
13938 			/* If no FC4 type support, move to just SCSI support */
13939 			if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP))
13940 				return -ENODEV;
13941 			phba->cfg_enable_fc4_type = LPFC_ENABLE_FCP;
13942 		}
13943 	}
13944 
13945 	/* If the NVME FC4 type is enabled, scale the sg_seg_cnt to
13946 	 * accommodate 512K and 1M IOs in a single nvme buf.
13947 	 */
13948 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
13949 		phba->cfg_sg_seg_cnt = LPFC_MAX_NVME_SEG_CNT;
13950 
13951 	/* Enable embedded Payload BDE if support is indicated */
13952 	if (bf_get(cfg_pbde, mbx_sli4_parameters))
13953 		phba->cfg_enable_pbde = 1;
13954 	else
13955 		phba->cfg_enable_pbde = 0;
13956 
13957 	/*
13958 	 * To support Suppress Response feature we must satisfy 3 conditions.
13959 	 * lpfc_suppress_rsp module parameter must be set (default).
13960 	 * In SLI4-Parameters Descriptor:
13961 	 * Extended Inline Buffers (XIB) must be supported.
13962 	 * Suppress Response IU Not Supported (SRIUNS) must NOT be supported
13963 	 * (double negative).
13964 	 */
13965 	if (phba->cfg_suppress_rsp && bf_get(cfg_xib, mbx_sli4_parameters) &&
13966 	    !(bf_get(cfg_nosr, mbx_sli4_parameters)))
13967 		phba->sli.sli_flag |= LPFC_SLI_SUPPRESS_RSP;
13968 	else
13969 		phba->cfg_suppress_rsp = 0;
13970 
13971 	if (bf_get(cfg_eqdr, mbx_sli4_parameters))
13972 		phba->sli.sli_flag |= LPFC_SLI_USE_EQDR;
13973 
13974 	/* Make sure that sge_supp_len can be handled by the driver */
13975 	if (sli4_params->sge_supp_len > LPFC_MAX_SGE_SIZE)
13976 		sli4_params->sge_supp_len = LPFC_MAX_SGE_SIZE;
13977 
13978 	rc = dma_set_max_seg_size(&phba->pcidev->dev, sli4_params->sge_supp_len);
13979 	if (unlikely(rc)) {
13980 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13981 				"6400 Can't set dma maximum segment size\n");
13982 		return rc;
13983 	}
13984 
13985 	/*
13986 	 * Check whether the adapter supports an embedded copy of the
13987 	 * FCP CMD IU within the WQE for FCP_Ixxx commands. In order
13988 	 * to use this option, 128-byte WQEs must be used.
13989 	 */
13990 	if (bf_get(cfg_ext_embed_cb, mbx_sli4_parameters))
13991 		phba->fcp_embed_io = 1;
13992 	else
13993 		phba->fcp_embed_io = 0;
13994 
13995 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_NVME,
13996 			"6422 XIB %d PBDE %d: FCP %d NVME %d %d %d\n",
13997 			bf_get(cfg_xib, mbx_sli4_parameters),
13998 			phba->cfg_enable_pbde,
13999 			phba->fcp_embed_io, sli4_params->nvme,
14000 			phba->cfg_nvme_embed_cmd, phba->cfg_suppress_rsp);
14001 
14002 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
14003 	    LPFC_SLI_INTF_IF_TYPE_2) &&
14004 	    (bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf) ==
14005 		 LPFC_SLI_INTF_FAMILY_LNCR_A0))
14006 		exp_wqcq_pages = false;
14007 
14008 	if ((bf_get(cfg_cqpsize, mbx_sli4_parameters) & LPFC_CQ_16K_PAGE_SZ) &&
14009 	    (bf_get(cfg_wqpsize, mbx_sli4_parameters) & LPFC_WQ_16K_PAGE_SZ) &&
14010 	    exp_wqcq_pages &&
14011 	    (sli4_params->wqsize & LPFC_WQ_SZ128_SUPPORT))
14012 		phba->enab_exp_wqcq_pages = 1;
14013 	else
14014 		phba->enab_exp_wqcq_pages = 0;
14015 	/*
14016 	 * Check if the SLI port supports MDS Diagnostics
14017 	 */
14018 	if (bf_get(cfg_mds_diags, mbx_sli4_parameters))
14019 		phba->mds_diags_support = 1;
14020 	else
14021 		phba->mds_diags_support = 0;
14022 
14023 	/*
14024 	 * Check if the SLI port supports NSLER
14025 	 */
14026 	if (bf_get(cfg_nsler, mbx_sli4_parameters))
14027 		phba->nsler = 1;
14028 	else
14029 		phba->nsler = 0;
14030 
14031 	return 0;
14032 }
14033 
14034 /**
14035  * lpfc_pci_probe_one_s3 - PCI probe func to reg SLI-3 device to PCI subsystem.
14036  * @pdev: pointer to PCI device
14037  * @pid: pointer to PCI device identifier
14038  *
14039  * This routine is to be called to attach a device with SLI-3 interface spec
14040  * to the PCI subsystem. When an Emulex HBA with SLI-3 interface spec is
14041  * presented on PCI bus, the kernel PCI subsystem looks at PCI device-specific
14042  * information of the device and driver to see if the driver state that it can
14043  * support this kind of device. If the match is successful, the driver core
14044  * invokes this routine. If this routine determines it can claim the HBA, it
14045  * does all the initialization that it needs to do to handle the HBA properly.
14046  *
14047  * Return code
14048  * 	0 - driver can claim the device
14049  * 	negative value - driver can not claim the device
14050  **/
14051 static int
14052 lpfc_pci_probe_one_s3(struct pci_dev *pdev, const struct pci_device_id *pid)
14053 {
14054 	struct lpfc_hba   *phba;
14055 	struct lpfc_vport *vport = NULL;
14056 	struct Scsi_Host  *shost = NULL;
14057 	int error;
14058 	uint32_t cfg_mode, intr_mode;
14059 
14060 	/* Allocate memory for HBA structure */
14061 	phba = lpfc_hba_alloc(pdev);
14062 	if (!phba)
14063 		return -ENOMEM;
14064 
14065 	/* Perform generic PCI device enabling operation */
14066 	error = lpfc_enable_pci_dev(phba);
14067 	if (error)
14068 		goto out_free_phba;
14069 
14070 	/* Set up SLI API function jump table for PCI-device group-0 HBAs */
14071 	error = lpfc_api_table_setup(phba, LPFC_PCI_DEV_LP);
14072 	if (error)
14073 		goto out_disable_pci_dev;
14074 
14075 	/* Set up SLI-3 specific device PCI memory space */
14076 	error = lpfc_sli_pci_mem_setup(phba);
14077 	if (error) {
14078 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14079 				"1402 Failed to set up pci memory space.\n");
14080 		goto out_disable_pci_dev;
14081 	}
14082 
14083 	/* Set up SLI-3 specific device driver resources */
14084 	error = lpfc_sli_driver_resource_setup(phba);
14085 	if (error) {
14086 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14087 				"1404 Failed to set up driver resource.\n");
14088 		goto out_unset_pci_mem_s3;
14089 	}
14090 
14091 	/* Initialize and populate the iocb list per host */
14092 
14093 	error = lpfc_init_iocb_list(phba, LPFC_IOCB_LIST_CNT);
14094 	if (error) {
14095 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14096 				"1405 Failed to initialize iocb list.\n");
14097 		goto out_unset_driver_resource_s3;
14098 	}
14099 
14100 	/* Set up common device driver resources */
14101 	error = lpfc_setup_driver_resource_phase2(phba);
14102 	if (error) {
14103 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14104 				"1406 Failed to set up driver resource.\n");
14105 		goto out_free_iocb_list;
14106 	}
14107 
14108 	/* Get the default values for Model Name and Description */
14109 	lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
14110 
14111 	/* Create SCSI host to the physical port */
14112 	error = lpfc_create_shost(phba);
14113 	if (error) {
14114 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14115 				"1407 Failed to create scsi host.\n");
14116 		goto out_unset_driver_resource;
14117 	}
14118 
14119 	/* Configure sysfs attributes */
14120 	vport = phba->pport;
14121 	error = lpfc_alloc_sysfs_attr(vport);
14122 	if (error) {
14123 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14124 				"1476 Failed to allocate sysfs attr\n");
14125 		goto out_destroy_shost;
14126 	}
14127 
14128 	shost = lpfc_shost_from_vport(vport); /* save shost for error cleanup */
14129 	/* Now, trying to enable interrupt and bring up the device */
14130 	cfg_mode = phba->cfg_use_msi;
14131 	while (true) {
14132 		/* Put device to a known state before enabling interrupt */
14133 		lpfc_stop_port(phba);
14134 		/* Configure and enable interrupt */
14135 		intr_mode = lpfc_sli_enable_intr(phba, cfg_mode);
14136 		if (intr_mode == LPFC_INTR_ERROR) {
14137 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14138 					"0431 Failed to enable interrupt.\n");
14139 			error = -ENODEV;
14140 			goto out_free_sysfs_attr;
14141 		}
14142 		/* SLI-3 HBA setup */
14143 		if (lpfc_sli_hba_setup(phba)) {
14144 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14145 					"1477 Failed to set up hba\n");
14146 			error = -ENODEV;
14147 			goto out_remove_device;
14148 		}
14149 
14150 		/* Wait 50ms for the interrupts of previous mailbox commands */
14151 		msleep(50);
14152 		/* Check active interrupts on message signaled interrupts */
14153 		if (intr_mode == 0 ||
14154 		    phba->sli.slistat.sli_intr > LPFC_MSIX_VECTORS) {
14155 			/* Log the current active interrupt mode */
14156 			phba->intr_mode = intr_mode;
14157 			lpfc_log_intr_mode(phba, intr_mode);
14158 			break;
14159 		} else {
14160 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
14161 					"0447 Configure interrupt mode (%d) "
14162 					"failed active interrupt test.\n",
14163 					intr_mode);
14164 			/* Disable the current interrupt mode */
14165 			lpfc_sli_disable_intr(phba);
14166 			/* Try next level of interrupt mode */
14167 			cfg_mode = --intr_mode;
14168 		}
14169 	}
14170 
14171 	/* Perform post initialization setup */
14172 	lpfc_post_init_setup(phba);
14173 
14174 	/* Check if there are static vports to be created. */
14175 	lpfc_create_static_vport(phba);
14176 
14177 	return 0;
14178 
14179 out_remove_device:
14180 	lpfc_unset_hba(phba);
14181 out_free_sysfs_attr:
14182 	lpfc_free_sysfs_attr(vport);
14183 out_destroy_shost:
14184 	lpfc_destroy_shost(phba);
14185 out_unset_driver_resource:
14186 	lpfc_unset_driver_resource_phase2(phba);
14187 out_free_iocb_list:
14188 	lpfc_free_iocb_list(phba);
14189 out_unset_driver_resource_s3:
14190 	lpfc_sli_driver_resource_unset(phba);
14191 out_unset_pci_mem_s3:
14192 	lpfc_sli_pci_mem_unset(phba);
14193 out_disable_pci_dev:
14194 	lpfc_disable_pci_dev(phba);
14195 	if (shost)
14196 		scsi_host_put(shost);
14197 out_free_phba:
14198 	lpfc_hba_free(phba);
14199 	return error;
14200 }
14201 
14202 /**
14203  * lpfc_pci_remove_one_s3 - PCI func to unreg SLI-3 device from PCI subsystem.
14204  * @pdev: pointer to PCI device
14205  *
14206  * This routine is to be called to disattach a device with SLI-3 interface
14207  * spec from PCI subsystem. When an Emulex HBA with SLI-3 interface spec is
14208  * removed from PCI bus, it performs all the necessary cleanup for the HBA
14209  * device to be removed from the PCI subsystem properly.
14210  **/
14211 static void
14212 lpfc_pci_remove_one_s3(struct pci_dev *pdev)
14213 {
14214 	struct Scsi_Host  *shost = pci_get_drvdata(pdev);
14215 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
14216 	struct lpfc_vport **vports;
14217 	struct lpfc_hba   *phba = vport->phba;
14218 	int i;
14219 
14220 	spin_lock_irq(&phba->hbalock);
14221 	vport->load_flag |= FC_UNLOADING;
14222 	spin_unlock_irq(&phba->hbalock);
14223 
14224 	lpfc_free_sysfs_attr(vport);
14225 
14226 	/* Release all the vports against this physical port */
14227 	vports = lpfc_create_vport_work_array(phba);
14228 	if (vports != NULL)
14229 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
14230 			if (vports[i]->port_type == LPFC_PHYSICAL_PORT)
14231 				continue;
14232 			fc_vport_terminate(vports[i]->fc_vport);
14233 		}
14234 	lpfc_destroy_vport_work_array(phba, vports);
14235 
14236 	/* Remove FC host with the physical port */
14237 	fc_remove_host(shost);
14238 	scsi_remove_host(shost);
14239 
14240 	/* Clean up all nodes, mailboxes and IOs. */
14241 	lpfc_cleanup(vport);
14242 
14243 	/*
14244 	 * Bring down the SLI Layer. This step disable all interrupts,
14245 	 * clears the rings, discards all mailbox commands, and resets
14246 	 * the HBA.
14247 	 */
14248 
14249 	/* HBA interrupt will be disabled after this call */
14250 	lpfc_sli_hba_down(phba);
14251 	/* Stop kthread signal shall trigger work_done one more time */
14252 	kthread_stop(phba->worker_thread);
14253 	/* Final cleanup of txcmplq and reset the HBA */
14254 	lpfc_sli_brdrestart(phba);
14255 
14256 	kfree(phba->vpi_bmask);
14257 	kfree(phba->vpi_ids);
14258 
14259 	lpfc_stop_hba_timers(phba);
14260 	spin_lock_irq(&phba->port_list_lock);
14261 	list_del_init(&vport->listentry);
14262 	spin_unlock_irq(&phba->port_list_lock);
14263 
14264 	lpfc_debugfs_terminate(vport);
14265 
14266 	/* Disable SR-IOV if enabled */
14267 	if (phba->cfg_sriov_nr_virtfn)
14268 		pci_disable_sriov(pdev);
14269 
14270 	/* Disable interrupt */
14271 	lpfc_sli_disable_intr(phba);
14272 
14273 	scsi_host_put(shost);
14274 
14275 	/*
14276 	 * Call scsi_free before mem_free since scsi bufs are released to their
14277 	 * corresponding pools here.
14278 	 */
14279 	lpfc_scsi_free(phba);
14280 	lpfc_free_iocb_list(phba);
14281 
14282 	lpfc_mem_free_all(phba);
14283 
14284 	dma_free_coherent(&pdev->dev, lpfc_sli_hbq_size(),
14285 			  phba->hbqslimp.virt, phba->hbqslimp.phys);
14286 
14287 	/* Free resources associated with SLI2 interface */
14288 	dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
14289 			  phba->slim2p.virt, phba->slim2p.phys);
14290 
14291 	/* unmap adapter SLIM and Control Registers */
14292 	iounmap(phba->ctrl_regs_memmap_p);
14293 	iounmap(phba->slim_memmap_p);
14294 
14295 	lpfc_hba_free(phba);
14296 
14297 	pci_release_mem_regions(pdev);
14298 	pci_disable_device(pdev);
14299 }
14300 
14301 /**
14302  * lpfc_pci_suspend_one_s3 - PCI func to suspend SLI-3 device for power mgmnt
14303  * @dev_d: pointer to device
14304  *
14305  * This routine is to be called from the kernel's PCI subsystem to support
14306  * system Power Management (PM) to device with SLI-3 interface spec. When
14307  * PM invokes this method, it quiesces the device by stopping the driver's
14308  * worker thread for the device, turning off device's interrupt and DMA,
14309  * and bring the device offline. Note that as the driver implements the
14310  * minimum PM requirements to a power-aware driver's PM support for the
14311  * suspend/resume -- all the possible PM messages (SUSPEND, HIBERNATE, FREEZE)
14312  * to the suspend() method call will be treated as SUSPEND and the driver will
14313  * fully reinitialize its device during resume() method call, the driver will
14314  * set device to PCI_D3hot state in PCI config space instead of setting it
14315  * according to the @msg provided by the PM.
14316  *
14317  * Return code
14318  * 	0 - driver suspended the device
14319  * 	Error otherwise
14320  **/
14321 static int __maybe_unused
14322 lpfc_pci_suspend_one_s3(struct device *dev_d)
14323 {
14324 	struct Scsi_Host *shost = dev_get_drvdata(dev_d);
14325 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14326 
14327 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
14328 			"0473 PCI device Power Management suspend.\n");
14329 
14330 	/* Bring down the device */
14331 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
14332 	lpfc_offline(phba);
14333 	kthread_stop(phba->worker_thread);
14334 
14335 	/* Disable interrupt from device */
14336 	lpfc_sli_disable_intr(phba);
14337 
14338 	return 0;
14339 }
14340 
14341 /**
14342  * lpfc_pci_resume_one_s3 - PCI func to resume SLI-3 device for power mgmnt
14343  * @dev_d: pointer to device
14344  *
14345  * This routine is to be called from the kernel's PCI subsystem to support
14346  * system Power Management (PM) to device with SLI-3 interface spec. When PM
14347  * invokes this method, it restores the device's PCI config space state and
14348  * fully reinitializes the device and brings it online. Note that as the
14349  * driver implements the minimum PM requirements to a power-aware driver's
14350  * PM for suspend/resume -- all the possible PM messages (SUSPEND, HIBERNATE,
14351  * FREEZE) to the suspend() method call will be treated as SUSPEND and the
14352  * driver will fully reinitialize its device during resume() method call,
14353  * the device will be set to PCI_D0 directly in PCI config space before
14354  * restoring the state.
14355  *
14356  * Return code
14357  * 	0 - driver suspended the device
14358  * 	Error otherwise
14359  **/
14360 static int __maybe_unused
14361 lpfc_pci_resume_one_s3(struct device *dev_d)
14362 {
14363 	struct Scsi_Host *shost = dev_get_drvdata(dev_d);
14364 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14365 	uint32_t intr_mode;
14366 	int error;
14367 
14368 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
14369 			"0452 PCI device Power Management resume.\n");
14370 
14371 	/* Startup the kernel thread for this host adapter. */
14372 	phba->worker_thread = kthread_run(lpfc_do_work, phba,
14373 					"lpfc_worker_%d", phba->brd_no);
14374 	if (IS_ERR(phba->worker_thread)) {
14375 		error = PTR_ERR(phba->worker_thread);
14376 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14377 				"0434 PM resume failed to start worker "
14378 				"thread: error=x%x.\n", error);
14379 		return error;
14380 	}
14381 
14382 	/* Init cpu_map array */
14383 	lpfc_cpu_map_array_init(phba);
14384 	/* Init hba_eq_hdl array */
14385 	lpfc_hba_eq_hdl_array_init(phba);
14386 	/* Configure and enable interrupt */
14387 	intr_mode = lpfc_sli_enable_intr(phba, phba->intr_mode);
14388 	if (intr_mode == LPFC_INTR_ERROR) {
14389 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14390 				"0430 PM resume Failed to enable interrupt\n");
14391 		return -EIO;
14392 	} else
14393 		phba->intr_mode = intr_mode;
14394 
14395 	/* Restart HBA and bring it online */
14396 	lpfc_sli_brdrestart(phba);
14397 	lpfc_online(phba);
14398 
14399 	/* Log the current active interrupt mode */
14400 	lpfc_log_intr_mode(phba, phba->intr_mode);
14401 
14402 	return 0;
14403 }
14404 
14405 /**
14406  * lpfc_sli_prep_dev_for_recover - Prepare SLI3 device for pci slot recover
14407  * @phba: pointer to lpfc hba data structure.
14408  *
14409  * This routine is called to prepare the SLI3 device for PCI slot recover. It
14410  * aborts all the outstanding SCSI I/Os to the pci device.
14411  **/
14412 static void
14413 lpfc_sli_prep_dev_for_recover(struct lpfc_hba *phba)
14414 {
14415 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14416 			"2723 PCI channel I/O abort preparing for recovery\n");
14417 
14418 	/*
14419 	 * There may be errored I/Os through HBA, abort all I/Os on txcmplq
14420 	 * and let the SCSI mid-layer to retry them to recover.
14421 	 */
14422 	lpfc_sli_abort_fcp_rings(phba);
14423 }
14424 
14425 /**
14426  * lpfc_sli_prep_dev_for_reset - Prepare SLI3 device for pci slot reset
14427  * @phba: pointer to lpfc hba data structure.
14428  *
14429  * This routine is called to prepare the SLI3 device for PCI slot reset. It
14430  * disables the device interrupt and pci device, and aborts the internal FCP
14431  * pending I/Os.
14432  **/
14433 static void
14434 lpfc_sli_prep_dev_for_reset(struct lpfc_hba *phba)
14435 {
14436 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14437 			"2710 PCI channel disable preparing for reset\n");
14438 
14439 	/* Block any management I/Os to the device */
14440 	lpfc_block_mgmt_io(phba, LPFC_MBX_WAIT);
14441 
14442 	/* Block all SCSI devices' I/Os on the host */
14443 	lpfc_scsi_dev_block(phba);
14444 
14445 	/* Flush all driver's outstanding SCSI I/Os as we are to reset */
14446 	lpfc_sli_flush_io_rings(phba);
14447 
14448 	/* stop all timers */
14449 	lpfc_stop_hba_timers(phba);
14450 
14451 	/* Disable interrupt and pci device */
14452 	lpfc_sli_disable_intr(phba);
14453 	pci_disable_device(phba->pcidev);
14454 }
14455 
14456 /**
14457  * lpfc_sli_prep_dev_for_perm_failure - Prepare SLI3 dev for pci slot disable
14458  * @phba: pointer to lpfc hba data structure.
14459  *
14460  * This routine is called to prepare the SLI3 device for PCI slot permanently
14461  * disabling. It blocks the SCSI transport layer traffic and flushes the FCP
14462  * pending I/Os.
14463  **/
14464 static void
14465 lpfc_sli_prep_dev_for_perm_failure(struct lpfc_hba *phba)
14466 {
14467 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14468 			"2711 PCI channel permanent disable for failure\n");
14469 	/* Block all SCSI devices' I/Os on the host */
14470 	lpfc_scsi_dev_block(phba);
14471 	lpfc_sli4_prep_dev_for_reset(phba);
14472 
14473 	/* stop all timers */
14474 	lpfc_stop_hba_timers(phba);
14475 
14476 	/* Clean up all driver's outstanding SCSI I/Os */
14477 	lpfc_sli_flush_io_rings(phba);
14478 }
14479 
14480 /**
14481  * lpfc_io_error_detected_s3 - Method for handling SLI-3 device PCI I/O error
14482  * @pdev: pointer to PCI device.
14483  * @state: the current PCI connection state.
14484  *
14485  * This routine is called from the PCI subsystem for I/O error handling to
14486  * device with SLI-3 interface spec. This function is called by the PCI
14487  * subsystem after a PCI bus error affecting this device has been detected.
14488  * When this function is invoked, it will need to stop all the I/Os and
14489  * interrupt(s) to the device. Once that is done, it will return
14490  * PCI_ERS_RESULT_NEED_RESET for the PCI subsystem to perform proper recovery
14491  * as desired.
14492  *
14493  * Return codes
14494  * 	PCI_ERS_RESULT_CAN_RECOVER - can be recovered with reset_link
14495  * 	PCI_ERS_RESULT_NEED_RESET - need to reset before recovery
14496  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
14497  **/
14498 static pci_ers_result_t
14499 lpfc_io_error_detected_s3(struct pci_dev *pdev, pci_channel_state_t state)
14500 {
14501 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
14502 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14503 
14504 	switch (state) {
14505 	case pci_channel_io_normal:
14506 		/* Non-fatal error, prepare for recovery */
14507 		lpfc_sli_prep_dev_for_recover(phba);
14508 		return PCI_ERS_RESULT_CAN_RECOVER;
14509 	case pci_channel_io_frozen:
14510 		/* Fatal error, prepare for slot reset */
14511 		lpfc_sli_prep_dev_for_reset(phba);
14512 		return PCI_ERS_RESULT_NEED_RESET;
14513 	case pci_channel_io_perm_failure:
14514 		/* Permanent failure, prepare for device down */
14515 		lpfc_sli_prep_dev_for_perm_failure(phba);
14516 		return PCI_ERS_RESULT_DISCONNECT;
14517 	default:
14518 		/* Unknown state, prepare and request slot reset */
14519 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14520 				"0472 Unknown PCI error state: x%x\n", state);
14521 		lpfc_sli_prep_dev_for_reset(phba);
14522 		return PCI_ERS_RESULT_NEED_RESET;
14523 	}
14524 }
14525 
14526 /**
14527  * lpfc_io_slot_reset_s3 - Method for restarting PCI SLI-3 device from scratch.
14528  * @pdev: pointer to PCI device.
14529  *
14530  * This routine is called from the PCI subsystem for error handling to
14531  * device with SLI-3 interface spec. This is called after PCI bus has been
14532  * reset to restart the PCI card from scratch, as if from a cold-boot.
14533  * During the PCI subsystem error recovery, after driver returns
14534  * PCI_ERS_RESULT_NEED_RESET, the PCI subsystem will perform proper error
14535  * recovery and then call this routine before calling the .resume method
14536  * to recover the device. This function will initialize the HBA device,
14537  * enable the interrupt, but it will just put the HBA to offline state
14538  * without passing any I/O traffic.
14539  *
14540  * Return codes
14541  * 	PCI_ERS_RESULT_RECOVERED - the device has been recovered
14542  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
14543  */
14544 static pci_ers_result_t
14545 lpfc_io_slot_reset_s3(struct pci_dev *pdev)
14546 {
14547 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
14548 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14549 	struct lpfc_sli *psli = &phba->sli;
14550 	uint32_t intr_mode;
14551 
14552 	dev_printk(KERN_INFO, &pdev->dev, "recovering from a slot reset.\n");
14553 	if (pci_enable_device_mem(pdev)) {
14554 		printk(KERN_ERR "lpfc: Cannot re-enable "
14555 			"PCI device after reset.\n");
14556 		return PCI_ERS_RESULT_DISCONNECT;
14557 	}
14558 
14559 	pci_restore_state(pdev);
14560 
14561 	/*
14562 	 * As the new kernel behavior of pci_restore_state() API call clears
14563 	 * device saved_state flag, need to save the restored state again.
14564 	 */
14565 	pci_save_state(pdev);
14566 
14567 	if (pdev->is_busmaster)
14568 		pci_set_master(pdev);
14569 
14570 	spin_lock_irq(&phba->hbalock);
14571 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
14572 	spin_unlock_irq(&phba->hbalock);
14573 
14574 	/* Configure and enable interrupt */
14575 	intr_mode = lpfc_sli_enable_intr(phba, phba->intr_mode);
14576 	if (intr_mode == LPFC_INTR_ERROR) {
14577 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14578 				"0427 Cannot re-enable interrupt after "
14579 				"slot reset.\n");
14580 		return PCI_ERS_RESULT_DISCONNECT;
14581 	} else
14582 		phba->intr_mode = intr_mode;
14583 
14584 	/* Take device offline, it will perform cleanup */
14585 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
14586 	lpfc_offline(phba);
14587 	lpfc_sli_brdrestart(phba);
14588 
14589 	/* Log the current active interrupt mode */
14590 	lpfc_log_intr_mode(phba, phba->intr_mode);
14591 
14592 	return PCI_ERS_RESULT_RECOVERED;
14593 }
14594 
14595 /**
14596  * lpfc_io_resume_s3 - Method for resuming PCI I/O operation on SLI-3 device.
14597  * @pdev: pointer to PCI device
14598  *
14599  * This routine is called from the PCI subsystem for error handling to device
14600  * with SLI-3 interface spec. It is called when kernel error recovery tells
14601  * the lpfc driver that it is ok to resume normal PCI operation after PCI bus
14602  * error recovery. After this call, traffic can start to flow from this device
14603  * again.
14604  */
14605 static void
14606 lpfc_io_resume_s3(struct pci_dev *pdev)
14607 {
14608 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
14609 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14610 
14611 	/* Bring device online, it will be no-op for non-fatal error resume */
14612 	lpfc_online(phba);
14613 }
14614 
14615 /**
14616  * lpfc_sli4_get_els_iocb_cnt - Calculate the # of ELS IOCBs to reserve
14617  * @phba: pointer to lpfc hba data structure.
14618  *
14619  * returns the number of ELS/CT IOCBs to reserve
14620  **/
14621 int
14622 lpfc_sli4_get_els_iocb_cnt(struct lpfc_hba *phba)
14623 {
14624 	int max_xri = phba->sli4_hba.max_cfg_param.max_xri;
14625 
14626 	if (phba->sli_rev == LPFC_SLI_REV4) {
14627 		if (max_xri <= 100)
14628 			return 10;
14629 		else if (max_xri <= 256)
14630 			return 25;
14631 		else if (max_xri <= 512)
14632 			return 50;
14633 		else if (max_xri <= 1024)
14634 			return 100;
14635 		else if (max_xri <= 1536)
14636 			return 150;
14637 		else if (max_xri <= 2048)
14638 			return 200;
14639 		else
14640 			return 250;
14641 	} else
14642 		return 0;
14643 }
14644 
14645 /**
14646  * lpfc_sli4_get_iocb_cnt - Calculate the # of total IOCBs to reserve
14647  * @phba: pointer to lpfc hba data structure.
14648  *
14649  * returns the number of ELS/CT + NVMET IOCBs to reserve
14650  **/
14651 int
14652 lpfc_sli4_get_iocb_cnt(struct lpfc_hba *phba)
14653 {
14654 	int max_xri = lpfc_sli4_get_els_iocb_cnt(phba);
14655 
14656 	if (phba->nvmet_support)
14657 		max_xri += LPFC_NVMET_BUF_POST;
14658 	return max_xri;
14659 }
14660 
14661 
14662 static int
14663 lpfc_log_write_firmware_error(struct lpfc_hba *phba, uint32_t offset,
14664 	uint32_t magic_number, uint32_t ftype, uint32_t fid, uint32_t fsize,
14665 	const struct firmware *fw)
14666 {
14667 	int rc;
14668 	u8 sli_family;
14669 
14670 	sli_family = bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf);
14671 	/* Three cases:  (1) FW was not supported on the detected adapter.
14672 	 * (2) FW update has been locked out administratively.
14673 	 * (3) Some other error during FW update.
14674 	 * In each case, an unmaskable message is written to the console
14675 	 * for admin diagnosis.
14676 	 */
14677 	if (offset == ADD_STATUS_FW_NOT_SUPPORTED ||
14678 	    (sli_family == LPFC_SLI_INTF_FAMILY_G6 &&
14679 	     magic_number != MAGIC_NUMBER_G6) ||
14680 	    (sli_family == LPFC_SLI_INTF_FAMILY_G7 &&
14681 	     magic_number != MAGIC_NUMBER_G7) ||
14682 	    (sli_family == LPFC_SLI_INTF_FAMILY_G7P &&
14683 	     magic_number != MAGIC_NUMBER_G7P)) {
14684 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14685 				"3030 This firmware version is not supported on"
14686 				" this HBA model. Device:%x Magic:%x Type:%x "
14687 				"ID:%x Size %d %zd\n",
14688 				phba->pcidev->device, magic_number, ftype, fid,
14689 				fsize, fw->size);
14690 		rc = -EINVAL;
14691 	} else if (offset == ADD_STATUS_FW_DOWNLOAD_HW_DISABLED) {
14692 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14693 				"3021 Firmware downloads have been prohibited "
14694 				"by a system configuration setting on "
14695 				"Device:%x Magic:%x Type:%x ID:%x Size %d "
14696 				"%zd\n",
14697 				phba->pcidev->device, magic_number, ftype, fid,
14698 				fsize, fw->size);
14699 		rc = -EACCES;
14700 	} else {
14701 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14702 				"3022 FW Download failed. Add Status x%x "
14703 				"Device:%x Magic:%x Type:%x ID:%x Size %d "
14704 				"%zd\n",
14705 				offset, phba->pcidev->device, magic_number,
14706 				ftype, fid, fsize, fw->size);
14707 		rc = -EIO;
14708 	}
14709 	return rc;
14710 }
14711 
14712 /**
14713  * lpfc_write_firmware - attempt to write a firmware image to the port
14714  * @fw: pointer to firmware image returned from request_firmware.
14715  * @context: pointer to firmware image returned from request_firmware.
14716  *
14717  **/
14718 static void
14719 lpfc_write_firmware(const struct firmware *fw, void *context)
14720 {
14721 	struct lpfc_hba *phba = (struct lpfc_hba *)context;
14722 	char fwrev[FW_REV_STR_SIZE];
14723 	struct lpfc_grp_hdr *image;
14724 	struct list_head dma_buffer_list;
14725 	int i, rc = 0;
14726 	struct lpfc_dmabuf *dmabuf, *next;
14727 	uint32_t offset = 0, temp_offset = 0;
14728 	uint32_t magic_number, ftype, fid, fsize;
14729 
14730 	/* It can be null in no-wait mode, sanity check */
14731 	if (!fw) {
14732 		rc = -ENXIO;
14733 		goto out;
14734 	}
14735 	image = (struct lpfc_grp_hdr *)fw->data;
14736 
14737 	magic_number = be32_to_cpu(image->magic_number);
14738 	ftype = bf_get_be32(lpfc_grp_hdr_file_type, image);
14739 	fid = bf_get_be32(lpfc_grp_hdr_id, image);
14740 	fsize = be32_to_cpu(image->size);
14741 
14742 	INIT_LIST_HEAD(&dma_buffer_list);
14743 	lpfc_decode_firmware_rev(phba, fwrev, 1);
14744 	if (strncmp(fwrev, image->revision, strnlen(image->revision, 16))) {
14745 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14746 				"3023 Updating Firmware, Current Version:%s "
14747 				"New Version:%s\n",
14748 				fwrev, image->revision);
14749 		for (i = 0; i < LPFC_MBX_WR_CONFIG_MAX_BDE; i++) {
14750 			dmabuf = kzalloc(sizeof(struct lpfc_dmabuf),
14751 					 GFP_KERNEL);
14752 			if (!dmabuf) {
14753 				rc = -ENOMEM;
14754 				goto release_out;
14755 			}
14756 			dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
14757 							  SLI4_PAGE_SIZE,
14758 							  &dmabuf->phys,
14759 							  GFP_KERNEL);
14760 			if (!dmabuf->virt) {
14761 				kfree(dmabuf);
14762 				rc = -ENOMEM;
14763 				goto release_out;
14764 			}
14765 			list_add_tail(&dmabuf->list, &dma_buffer_list);
14766 		}
14767 		while (offset < fw->size) {
14768 			temp_offset = offset;
14769 			list_for_each_entry(dmabuf, &dma_buffer_list, list) {
14770 				if (temp_offset + SLI4_PAGE_SIZE > fw->size) {
14771 					memcpy(dmabuf->virt,
14772 					       fw->data + temp_offset,
14773 					       fw->size - temp_offset);
14774 					temp_offset = fw->size;
14775 					break;
14776 				}
14777 				memcpy(dmabuf->virt, fw->data + temp_offset,
14778 				       SLI4_PAGE_SIZE);
14779 				temp_offset += SLI4_PAGE_SIZE;
14780 			}
14781 			rc = lpfc_wr_object(phba, &dma_buffer_list,
14782 				    (fw->size - offset), &offset);
14783 			if (rc) {
14784 				rc = lpfc_log_write_firmware_error(phba, offset,
14785 								   magic_number,
14786 								   ftype,
14787 								   fid,
14788 								   fsize,
14789 								   fw);
14790 				goto release_out;
14791 			}
14792 		}
14793 		rc = offset;
14794 	} else
14795 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14796 				"3029 Skipped Firmware update, Current "
14797 				"Version:%s New Version:%s\n",
14798 				fwrev, image->revision);
14799 
14800 release_out:
14801 	list_for_each_entry_safe(dmabuf, next, &dma_buffer_list, list) {
14802 		list_del(&dmabuf->list);
14803 		dma_free_coherent(&phba->pcidev->dev, SLI4_PAGE_SIZE,
14804 				  dmabuf->virt, dmabuf->phys);
14805 		kfree(dmabuf);
14806 	}
14807 	release_firmware(fw);
14808 out:
14809 	if (rc < 0)
14810 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14811 				"3062 Firmware update error, status %d.\n", rc);
14812 	else
14813 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14814 				"3024 Firmware update success: size %d.\n", rc);
14815 }
14816 
14817 /**
14818  * lpfc_sli4_request_firmware_update - Request linux generic firmware upgrade
14819  * @phba: pointer to lpfc hba data structure.
14820  * @fw_upgrade: which firmware to update.
14821  *
14822  * This routine is called to perform Linux generic firmware upgrade on device
14823  * that supports such feature.
14824  **/
14825 int
14826 lpfc_sli4_request_firmware_update(struct lpfc_hba *phba, uint8_t fw_upgrade)
14827 {
14828 	uint8_t file_name[ELX_MODEL_NAME_SIZE];
14829 	int ret;
14830 	const struct firmware *fw;
14831 
14832 	/* Only supported on SLI4 interface type 2 for now */
14833 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) <
14834 	    LPFC_SLI_INTF_IF_TYPE_2)
14835 		return -EPERM;
14836 
14837 	snprintf(file_name, ELX_MODEL_NAME_SIZE, "%s.grp", phba->ModelName);
14838 
14839 	if (fw_upgrade == INT_FW_UPGRADE) {
14840 		ret = request_firmware_nowait(THIS_MODULE, FW_ACTION_UEVENT,
14841 					file_name, &phba->pcidev->dev,
14842 					GFP_KERNEL, (void *)phba,
14843 					lpfc_write_firmware);
14844 	} else if (fw_upgrade == RUN_FW_UPGRADE) {
14845 		ret = request_firmware(&fw, file_name, &phba->pcidev->dev);
14846 		if (!ret)
14847 			lpfc_write_firmware(fw, (void *)phba);
14848 	} else {
14849 		ret = -EINVAL;
14850 	}
14851 
14852 	return ret;
14853 }
14854 
14855 /**
14856  * lpfc_pci_probe_one_s4 - PCI probe func to reg SLI-4 device to PCI subsys
14857  * @pdev: pointer to PCI device
14858  * @pid: pointer to PCI device identifier
14859  *
14860  * This routine is called from the kernel's PCI subsystem to device with
14861  * SLI-4 interface spec. When an Emulex HBA with SLI-4 interface spec is
14862  * presented on PCI bus, the kernel PCI subsystem looks at PCI device-specific
14863  * information of the device and driver to see if the driver state that it
14864  * can support this kind of device. If the match is successful, the driver
14865  * core invokes this routine. If this routine determines it can claim the HBA,
14866  * it does all the initialization that it needs to do to handle the HBA
14867  * properly.
14868  *
14869  * Return code
14870  * 	0 - driver can claim the device
14871  * 	negative value - driver can not claim the device
14872  **/
14873 static int
14874 lpfc_pci_probe_one_s4(struct pci_dev *pdev, const struct pci_device_id *pid)
14875 {
14876 	struct lpfc_hba   *phba;
14877 	struct lpfc_vport *vport = NULL;
14878 	struct Scsi_Host  *shost = NULL;
14879 	int error;
14880 	uint32_t cfg_mode, intr_mode;
14881 
14882 	/* Allocate memory for HBA structure */
14883 	phba = lpfc_hba_alloc(pdev);
14884 	if (!phba)
14885 		return -ENOMEM;
14886 
14887 	INIT_LIST_HEAD(&phba->poll_list);
14888 
14889 	/* Perform generic PCI device enabling operation */
14890 	error = lpfc_enable_pci_dev(phba);
14891 	if (error)
14892 		goto out_free_phba;
14893 
14894 	/* Set up SLI API function jump table for PCI-device group-1 HBAs */
14895 	error = lpfc_api_table_setup(phba, LPFC_PCI_DEV_OC);
14896 	if (error)
14897 		goto out_disable_pci_dev;
14898 
14899 	/* Set up SLI-4 specific device PCI memory space */
14900 	error = lpfc_sli4_pci_mem_setup(phba);
14901 	if (error) {
14902 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14903 				"1410 Failed to set up pci memory space.\n");
14904 		goto out_disable_pci_dev;
14905 	}
14906 
14907 	/* Set up SLI-4 Specific device driver resources */
14908 	error = lpfc_sli4_driver_resource_setup(phba);
14909 	if (error) {
14910 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14911 				"1412 Failed to set up driver resource.\n");
14912 		goto out_unset_pci_mem_s4;
14913 	}
14914 
14915 	INIT_LIST_HEAD(&phba->active_rrq_list);
14916 	INIT_LIST_HEAD(&phba->fcf.fcf_pri_list);
14917 
14918 	/* Set up common device driver resources */
14919 	error = lpfc_setup_driver_resource_phase2(phba);
14920 	if (error) {
14921 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14922 				"1414 Failed to set up driver resource.\n");
14923 		goto out_unset_driver_resource_s4;
14924 	}
14925 
14926 	/* Get the default values for Model Name and Description */
14927 	lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
14928 
14929 	/* Now, trying to enable interrupt and bring up the device */
14930 	cfg_mode = phba->cfg_use_msi;
14931 
14932 	/* Put device to a known state before enabling interrupt */
14933 	phba->pport = NULL;
14934 	lpfc_stop_port(phba);
14935 
14936 	/* Init cpu_map array */
14937 	lpfc_cpu_map_array_init(phba);
14938 
14939 	/* Init hba_eq_hdl array */
14940 	lpfc_hba_eq_hdl_array_init(phba);
14941 
14942 	/* Configure and enable interrupt */
14943 	intr_mode = lpfc_sli4_enable_intr(phba, cfg_mode);
14944 	if (intr_mode == LPFC_INTR_ERROR) {
14945 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14946 				"0426 Failed to enable interrupt.\n");
14947 		error = -ENODEV;
14948 		goto out_unset_driver_resource;
14949 	}
14950 	/* Default to single EQ for non-MSI-X */
14951 	if (phba->intr_type != MSIX) {
14952 		phba->cfg_irq_chann = 1;
14953 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
14954 			if (phba->nvmet_support)
14955 				phba->cfg_nvmet_mrq = 1;
14956 		}
14957 	}
14958 	lpfc_cpu_affinity_check(phba, phba->cfg_irq_chann);
14959 
14960 	/* Create SCSI host to the physical port */
14961 	error = lpfc_create_shost(phba);
14962 	if (error) {
14963 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14964 				"1415 Failed to create scsi host.\n");
14965 		goto out_disable_intr;
14966 	}
14967 	vport = phba->pport;
14968 	shost = lpfc_shost_from_vport(vport); /* save shost for error cleanup */
14969 
14970 	/* Configure sysfs attributes */
14971 	error = lpfc_alloc_sysfs_attr(vport);
14972 	if (error) {
14973 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14974 				"1416 Failed to allocate sysfs attr\n");
14975 		goto out_destroy_shost;
14976 	}
14977 
14978 	/* Set up SLI-4 HBA */
14979 	if (lpfc_sli4_hba_setup(phba)) {
14980 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14981 				"1421 Failed to set up hba\n");
14982 		error = -ENODEV;
14983 		goto out_free_sysfs_attr;
14984 	}
14985 
14986 	/* Log the current active interrupt mode */
14987 	phba->intr_mode = intr_mode;
14988 	lpfc_log_intr_mode(phba, intr_mode);
14989 
14990 	/* Perform post initialization setup */
14991 	lpfc_post_init_setup(phba);
14992 
14993 	/* NVME support in FW earlier in the driver load corrects the
14994 	 * FC4 type making a check for nvme_support unnecessary.
14995 	 */
14996 	if (phba->nvmet_support == 0) {
14997 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
14998 			/* Create NVME binding with nvme_fc_transport. This
14999 			 * ensures the vport is initialized.  If the localport
15000 			 * create fails, it should not unload the driver to
15001 			 * support field issues.
15002 			 */
15003 			error = lpfc_nvme_create_localport(vport);
15004 			if (error) {
15005 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15006 						"6004 NVME registration "
15007 						"failed, error x%x\n",
15008 						error);
15009 			}
15010 		}
15011 	}
15012 
15013 	/* check for firmware upgrade or downgrade */
15014 	if (phba->cfg_request_firmware_upgrade)
15015 		lpfc_sli4_request_firmware_update(phba, INT_FW_UPGRADE);
15016 
15017 	/* Check if there are static vports to be created. */
15018 	lpfc_create_static_vport(phba);
15019 
15020 	timer_setup(&phba->cpuhp_poll_timer, lpfc_sli4_poll_hbtimer, 0);
15021 	cpuhp_state_add_instance_nocalls(lpfc_cpuhp_state, &phba->cpuhp);
15022 
15023 	return 0;
15024 
15025 out_free_sysfs_attr:
15026 	lpfc_free_sysfs_attr(vport);
15027 out_destroy_shost:
15028 	lpfc_destroy_shost(phba);
15029 out_disable_intr:
15030 	lpfc_sli4_disable_intr(phba);
15031 out_unset_driver_resource:
15032 	lpfc_unset_driver_resource_phase2(phba);
15033 out_unset_driver_resource_s4:
15034 	lpfc_sli4_driver_resource_unset(phba);
15035 out_unset_pci_mem_s4:
15036 	lpfc_sli4_pci_mem_unset(phba);
15037 out_disable_pci_dev:
15038 	lpfc_disable_pci_dev(phba);
15039 	if (shost)
15040 		scsi_host_put(shost);
15041 out_free_phba:
15042 	lpfc_hba_free(phba);
15043 	return error;
15044 }
15045 
15046 /**
15047  * lpfc_pci_remove_one_s4 - PCI func to unreg SLI-4 device from PCI subsystem
15048  * @pdev: pointer to PCI device
15049  *
15050  * This routine is called from the kernel's PCI subsystem to device with
15051  * SLI-4 interface spec. When an Emulex HBA with SLI-4 interface spec is
15052  * removed from PCI bus, it performs all the necessary cleanup for the HBA
15053  * device to be removed from the PCI subsystem properly.
15054  **/
15055 static void
15056 lpfc_pci_remove_one_s4(struct pci_dev *pdev)
15057 {
15058 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15059 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
15060 	struct lpfc_vport **vports;
15061 	struct lpfc_hba *phba = vport->phba;
15062 	int i;
15063 
15064 	/* Mark the device unloading flag */
15065 	spin_lock_irq(&phba->hbalock);
15066 	vport->load_flag |= FC_UNLOADING;
15067 	spin_unlock_irq(&phba->hbalock);
15068 	if (phba->cgn_i)
15069 		lpfc_unreg_congestion_buf(phba);
15070 
15071 	lpfc_free_sysfs_attr(vport);
15072 
15073 	/* Release all the vports against this physical port */
15074 	vports = lpfc_create_vport_work_array(phba);
15075 	if (vports != NULL)
15076 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
15077 			if (vports[i]->port_type == LPFC_PHYSICAL_PORT)
15078 				continue;
15079 			fc_vport_terminate(vports[i]->fc_vport);
15080 		}
15081 	lpfc_destroy_vport_work_array(phba, vports);
15082 
15083 	/* Remove FC host with the physical port */
15084 	fc_remove_host(shost);
15085 	scsi_remove_host(shost);
15086 
15087 	/* Perform ndlp cleanup on the physical port.  The nvme and nvmet
15088 	 * localports are destroyed after to cleanup all transport memory.
15089 	 */
15090 	lpfc_cleanup(vport);
15091 	lpfc_nvmet_destroy_targetport(phba);
15092 	lpfc_nvme_destroy_localport(vport);
15093 
15094 	/* De-allocate multi-XRI pools */
15095 	if (phba->cfg_xri_rebalancing)
15096 		lpfc_destroy_multixri_pools(phba);
15097 
15098 	/*
15099 	 * Bring down the SLI Layer. This step disables all interrupts,
15100 	 * clears the rings, discards all mailbox commands, and resets
15101 	 * the HBA FCoE function.
15102 	 */
15103 	lpfc_debugfs_terminate(vport);
15104 
15105 	lpfc_stop_hba_timers(phba);
15106 	spin_lock_irq(&phba->port_list_lock);
15107 	list_del_init(&vport->listentry);
15108 	spin_unlock_irq(&phba->port_list_lock);
15109 
15110 	/* Perform scsi free before driver resource_unset since scsi
15111 	 * buffers are released to their corresponding pools here.
15112 	 */
15113 	lpfc_io_free(phba);
15114 	lpfc_free_iocb_list(phba);
15115 	lpfc_sli4_hba_unset(phba);
15116 
15117 	lpfc_unset_driver_resource_phase2(phba);
15118 	lpfc_sli4_driver_resource_unset(phba);
15119 
15120 	/* Unmap adapter Control and Doorbell registers */
15121 	lpfc_sli4_pci_mem_unset(phba);
15122 
15123 	/* Release PCI resources and disable device's PCI function */
15124 	scsi_host_put(shost);
15125 	lpfc_disable_pci_dev(phba);
15126 
15127 	/* Finally, free the driver's device data structure */
15128 	lpfc_hba_free(phba);
15129 
15130 	return;
15131 }
15132 
15133 /**
15134  * lpfc_pci_suspend_one_s4 - PCI func to suspend SLI-4 device for power mgmnt
15135  * @dev_d: pointer to device
15136  *
15137  * This routine is called from the kernel's PCI subsystem to support system
15138  * Power Management (PM) to device with SLI-4 interface spec. When PM invokes
15139  * this method, it quiesces the device by stopping the driver's worker
15140  * thread for the device, turning off device's interrupt and DMA, and bring
15141  * the device offline. Note that as the driver implements the minimum PM
15142  * requirements to a power-aware driver's PM support for suspend/resume -- all
15143  * the possible PM messages (SUSPEND, HIBERNATE, FREEZE) to the suspend()
15144  * method call will be treated as SUSPEND and the driver will fully
15145  * reinitialize its device during resume() method call, the driver will set
15146  * device to PCI_D3hot state in PCI config space instead of setting it
15147  * according to the @msg provided by the PM.
15148  *
15149  * Return code
15150  * 	0 - driver suspended the device
15151  * 	Error otherwise
15152  **/
15153 static int __maybe_unused
15154 lpfc_pci_suspend_one_s4(struct device *dev_d)
15155 {
15156 	struct Scsi_Host *shost = dev_get_drvdata(dev_d);
15157 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15158 
15159 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
15160 			"2843 PCI device Power Management suspend.\n");
15161 
15162 	/* Bring down the device */
15163 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
15164 	lpfc_offline(phba);
15165 	kthread_stop(phba->worker_thread);
15166 
15167 	/* Disable interrupt from device */
15168 	lpfc_sli4_disable_intr(phba);
15169 	lpfc_sli4_queue_destroy(phba);
15170 
15171 	return 0;
15172 }
15173 
15174 /**
15175  * lpfc_pci_resume_one_s4 - PCI func to resume SLI-4 device for power mgmnt
15176  * @dev_d: pointer to device
15177  *
15178  * This routine is called from the kernel's PCI subsystem to support system
15179  * Power Management (PM) to device with SLI-4 interface spac. When PM invokes
15180  * this method, it restores the device's PCI config space state and fully
15181  * reinitializes the device and brings it online. Note that as the driver
15182  * implements the minimum PM requirements to a power-aware driver's PM for
15183  * suspend/resume -- all the possible PM messages (SUSPEND, HIBERNATE, FREEZE)
15184  * to the suspend() method call will be treated as SUSPEND and the driver
15185  * will fully reinitialize its device during resume() method call, the device
15186  * will be set to PCI_D0 directly in PCI config space before restoring the
15187  * state.
15188  *
15189  * Return code
15190  * 	0 - driver suspended the device
15191  * 	Error otherwise
15192  **/
15193 static int __maybe_unused
15194 lpfc_pci_resume_one_s4(struct device *dev_d)
15195 {
15196 	struct Scsi_Host *shost = dev_get_drvdata(dev_d);
15197 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15198 	uint32_t intr_mode;
15199 	int error;
15200 
15201 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
15202 			"0292 PCI device Power Management resume.\n");
15203 
15204 	 /* Startup the kernel thread for this host adapter. */
15205 	phba->worker_thread = kthread_run(lpfc_do_work, phba,
15206 					"lpfc_worker_%d", phba->brd_no);
15207 	if (IS_ERR(phba->worker_thread)) {
15208 		error = PTR_ERR(phba->worker_thread);
15209 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15210 				"0293 PM resume failed to start worker "
15211 				"thread: error=x%x.\n", error);
15212 		return error;
15213 	}
15214 
15215 	/* Configure and enable interrupt */
15216 	intr_mode = lpfc_sli4_enable_intr(phba, phba->intr_mode);
15217 	if (intr_mode == LPFC_INTR_ERROR) {
15218 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15219 				"0294 PM resume Failed to enable interrupt\n");
15220 		return -EIO;
15221 	} else
15222 		phba->intr_mode = intr_mode;
15223 
15224 	/* Restart HBA and bring it online */
15225 	lpfc_sli_brdrestart(phba);
15226 	lpfc_online(phba);
15227 
15228 	/* Log the current active interrupt mode */
15229 	lpfc_log_intr_mode(phba, phba->intr_mode);
15230 
15231 	return 0;
15232 }
15233 
15234 /**
15235  * lpfc_sli4_prep_dev_for_recover - Prepare SLI4 device for pci slot recover
15236  * @phba: pointer to lpfc hba data structure.
15237  *
15238  * This routine is called to prepare the SLI4 device for PCI slot recover. It
15239  * aborts all the outstanding SCSI I/Os to the pci device.
15240  **/
15241 static void
15242 lpfc_sli4_prep_dev_for_recover(struct lpfc_hba *phba)
15243 {
15244 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15245 			"2828 PCI channel I/O abort preparing for recovery\n");
15246 	/*
15247 	 * There may be errored I/Os through HBA, abort all I/Os on txcmplq
15248 	 * and let the SCSI mid-layer to retry them to recover.
15249 	 */
15250 	lpfc_sli_abort_fcp_rings(phba);
15251 }
15252 
15253 /**
15254  * lpfc_sli4_prep_dev_for_reset - Prepare SLI4 device for pci slot reset
15255  * @phba: pointer to lpfc hba data structure.
15256  *
15257  * This routine is called to prepare the SLI4 device for PCI slot reset. It
15258  * disables the device interrupt and pci device, and aborts the internal FCP
15259  * pending I/Os.
15260  **/
15261 static void
15262 lpfc_sli4_prep_dev_for_reset(struct lpfc_hba *phba)
15263 {
15264 	int offline =  pci_channel_offline(phba->pcidev);
15265 
15266 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15267 			"2826 PCI channel disable preparing for reset offline"
15268 			" %d\n", offline);
15269 
15270 	/* Block any management I/Os to the device */
15271 	lpfc_block_mgmt_io(phba, LPFC_MBX_NO_WAIT);
15272 
15273 
15274 	/* HBA_PCI_ERR was set in io_error_detect */
15275 	lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
15276 	/* Flush all driver's outstanding I/Os as we are to reset */
15277 	lpfc_sli_flush_io_rings(phba);
15278 	lpfc_offline(phba);
15279 
15280 	/* stop all timers */
15281 	lpfc_stop_hba_timers(phba);
15282 
15283 	lpfc_sli4_queue_destroy(phba);
15284 	/* Disable interrupt and pci device */
15285 	lpfc_sli4_disable_intr(phba);
15286 	pci_disable_device(phba->pcidev);
15287 }
15288 
15289 /**
15290  * lpfc_sli4_prep_dev_for_perm_failure - Prepare SLI4 dev for pci slot disable
15291  * @phba: pointer to lpfc hba data structure.
15292  *
15293  * This routine is called to prepare the SLI4 device for PCI slot permanently
15294  * disabling. It blocks the SCSI transport layer traffic and flushes the FCP
15295  * pending I/Os.
15296  **/
15297 static void
15298 lpfc_sli4_prep_dev_for_perm_failure(struct lpfc_hba *phba)
15299 {
15300 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15301 			"2827 PCI channel permanent disable for failure\n");
15302 
15303 	/* Block all SCSI devices' I/Os on the host */
15304 	lpfc_scsi_dev_block(phba);
15305 
15306 	/* stop all timers */
15307 	lpfc_stop_hba_timers(phba);
15308 
15309 	/* Clean up all driver's outstanding I/Os */
15310 	lpfc_sli_flush_io_rings(phba);
15311 }
15312 
15313 /**
15314  * lpfc_io_error_detected_s4 - Method for handling PCI I/O error to SLI-4 device
15315  * @pdev: pointer to PCI device.
15316  * @state: the current PCI connection state.
15317  *
15318  * This routine is called from the PCI subsystem for error handling to device
15319  * with SLI-4 interface spec. This function is called by the PCI subsystem
15320  * after a PCI bus error affecting this device has been detected. When this
15321  * function is invoked, it will need to stop all the I/Os and interrupt(s)
15322  * to the device. Once that is done, it will return PCI_ERS_RESULT_NEED_RESET
15323  * for the PCI subsystem to perform proper recovery as desired.
15324  *
15325  * Return codes
15326  * 	PCI_ERS_RESULT_NEED_RESET - need to reset before recovery
15327  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15328  **/
15329 static pci_ers_result_t
15330 lpfc_io_error_detected_s4(struct pci_dev *pdev, pci_channel_state_t state)
15331 {
15332 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15333 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15334 	bool hba_pci_err;
15335 
15336 	switch (state) {
15337 	case pci_channel_io_normal:
15338 		/* Non-fatal error, prepare for recovery */
15339 		lpfc_sli4_prep_dev_for_recover(phba);
15340 		return PCI_ERS_RESULT_CAN_RECOVER;
15341 	case pci_channel_io_frozen:
15342 		hba_pci_err = test_and_set_bit(HBA_PCI_ERR, &phba->bit_flags);
15343 		/* Fatal error, prepare for slot reset */
15344 		if (!hba_pci_err)
15345 			lpfc_sli4_prep_dev_for_reset(phba);
15346 		else
15347 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15348 					"2832  Already handling PCI error "
15349 					"state: x%x\n", state);
15350 		return PCI_ERS_RESULT_NEED_RESET;
15351 	case pci_channel_io_perm_failure:
15352 		set_bit(HBA_PCI_ERR, &phba->bit_flags);
15353 		/* Permanent failure, prepare for device down */
15354 		lpfc_sli4_prep_dev_for_perm_failure(phba);
15355 		return PCI_ERS_RESULT_DISCONNECT;
15356 	default:
15357 		hba_pci_err = test_and_set_bit(HBA_PCI_ERR, &phba->bit_flags);
15358 		if (!hba_pci_err)
15359 			lpfc_sli4_prep_dev_for_reset(phba);
15360 		/* Unknown state, prepare and request slot reset */
15361 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15362 				"2825 Unknown PCI error state: x%x\n", state);
15363 		lpfc_sli4_prep_dev_for_reset(phba);
15364 		return PCI_ERS_RESULT_NEED_RESET;
15365 	}
15366 }
15367 
15368 /**
15369  * lpfc_io_slot_reset_s4 - Method for restart PCI SLI-4 device from scratch
15370  * @pdev: pointer to PCI device.
15371  *
15372  * This routine is called from the PCI subsystem for error handling to device
15373  * with SLI-4 interface spec. It is called after PCI bus has been reset to
15374  * restart the PCI card from scratch, as if from a cold-boot. During the
15375  * PCI subsystem error recovery, after the driver returns
15376  * PCI_ERS_RESULT_NEED_RESET, the PCI subsystem will perform proper error
15377  * recovery and then call this routine before calling the .resume method to
15378  * recover the device. This function will initialize the HBA device, enable
15379  * the interrupt, but it will just put the HBA to offline state without
15380  * passing any I/O traffic.
15381  *
15382  * Return codes
15383  * 	PCI_ERS_RESULT_RECOVERED - the device has been recovered
15384  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15385  */
15386 static pci_ers_result_t
15387 lpfc_io_slot_reset_s4(struct pci_dev *pdev)
15388 {
15389 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15390 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15391 	struct lpfc_sli *psli = &phba->sli;
15392 	uint32_t intr_mode;
15393 	bool hba_pci_err;
15394 
15395 	dev_printk(KERN_INFO, &pdev->dev, "recovering from a slot reset.\n");
15396 	if (pci_enable_device_mem(pdev)) {
15397 		printk(KERN_ERR "lpfc: Cannot re-enable "
15398 		       "PCI device after reset.\n");
15399 		return PCI_ERS_RESULT_DISCONNECT;
15400 	}
15401 
15402 	pci_restore_state(pdev);
15403 
15404 	hba_pci_err = test_and_clear_bit(HBA_PCI_ERR, &phba->bit_flags);
15405 	if (!hba_pci_err)
15406 		dev_info(&pdev->dev,
15407 			 "hba_pci_err was not set, recovering slot reset.\n");
15408 	/*
15409 	 * As the new kernel behavior of pci_restore_state() API call clears
15410 	 * device saved_state flag, need to save the restored state again.
15411 	 */
15412 	pci_save_state(pdev);
15413 
15414 	if (pdev->is_busmaster)
15415 		pci_set_master(pdev);
15416 
15417 	spin_lock_irq(&phba->hbalock);
15418 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
15419 	spin_unlock_irq(&phba->hbalock);
15420 
15421 	/* Init cpu_map array */
15422 	lpfc_cpu_map_array_init(phba);
15423 	/* Configure and enable interrupt */
15424 	intr_mode = lpfc_sli4_enable_intr(phba, phba->intr_mode);
15425 	if (intr_mode == LPFC_INTR_ERROR) {
15426 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15427 				"2824 Cannot re-enable interrupt after "
15428 				"slot reset.\n");
15429 		return PCI_ERS_RESULT_DISCONNECT;
15430 	} else
15431 		phba->intr_mode = intr_mode;
15432 	lpfc_cpu_affinity_check(phba, phba->cfg_irq_chann);
15433 
15434 	/* Log the current active interrupt mode */
15435 	lpfc_log_intr_mode(phba, phba->intr_mode);
15436 
15437 	return PCI_ERS_RESULT_RECOVERED;
15438 }
15439 
15440 /**
15441  * lpfc_io_resume_s4 - Method for resuming PCI I/O operation to SLI-4 device
15442  * @pdev: pointer to PCI device
15443  *
15444  * This routine is called from the PCI subsystem for error handling to device
15445  * with SLI-4 interface spec. It is called when kernel error recovery tells
15446  * the lpfc driver that it is ok to resume normal PCI operation after PCI bus
15447  * error recovery. After this call, traffic can start to flow from this device
15448  * again.
15449  **/
15450 static void
15451 lpfc_io_resume_s4(struct pci_dev *pdev)
15452 {
15453 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15454 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15455 
15456 	/*
15457 	 * In case of slot reset, as function reset is performed through
15458 	 * mailbox command which needs DMA to be enabled, this operation
15459 	 * has to be moved to the io resume phase. Taking device offline
15460 	 * will perform the necessary cleanup.
15461 	 */
15462 	if (!(phba->sli.sli_flag & LPFC_SLI_ACTIVE)) {
15463 		/* Perform device reset */
15464 		lpfc_sli_brdrestart(phba);
15465 		/* Bring the device back online */
15466 		lpfc_online(phba);
15467 	}
15468 }
15469 
15470 /**
15471  * lpfc_pci_probe_one - lpfc PCI probe func to reg dev to PCI subsystem
15472  * @pdev: pointer to PCI device
15473  * @pid: pointer to PCI device identifier
15474  *
15475  * This routine is to be registered to the kernel's PCI subsystem. When an
15476  * Emulex HBA device is presented on PCI bus, the kernel PCI subsystem looks
15477  * at PCI device-specific information of the device and driver to see if the
15478  * driver state that it can support this kind of device. If the match is
15479  * successful, the driver core invokes this routine. This routine dispatches
15480  * the action to the proper SLI-3 or SLI-4 device probing routine, which will
15481  * do all the initialization that it needs to do to handle the HBA device
15482  * properly.
15483  *
15484  * Return code
15485  * 	0 - driver can claim the device
15486  * 	negative value - driver can not claim the device
15487  **/
15488 static int
15489 lpfc_pci_probe_one(struct pci_dev *pdev, const struct pci_device_id *pid)
15490 {
15491 	int rc;
15492 	struct lpfc_sli_intf intf;
15493 
15494 	if (pci_read_config_dword(pdev, LPFC_SLI_INTF, &intf.word0))
15495 		return -ENODEV;
15496 
15497 	if ((bf_get(lpfc_sli_intf_valid, &intf) == LPFC_SLI_INTF_VALID) &&
15498 	    (bf_get(lpfc_sli_intf_slirev, &intf) == LPFC_SLI_INTF_REV_SLI4))
15499 		rc = lpfc_pci_probe_one_s4(pdev, pid);
15500 	else
15501 		rc = lpfc_pci_probe_one_s3(pdev, pid);
15502 
15503 	return rc;
15504 }
15505 
15506 /**
15507  * lpfc_pci_remove_one - lpfc PCI func to unreg dev from PCI subsystem
15508  * @pdev: pointer to PCI device
15509  *
15510  * This routine is to be registered to the kernel's PCI subsystem. When an
15511  * Emulex HBA is removed from PCI bus, the driver core invokes this routine.
15512  * This routine dispatches the action to the proper SLI-3 or SLI-4 device
15513  * remove routine, which will perform all the necessary cleanup for the
15514  * device to be removed from the PCI subsystem properly.
15515  **/
15516 static void
15517 lpfc_pci_remove_one(struct pci_dev *pdev)
15518 {
15519 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15520 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15521 
15522 	switch (phba->pci_dev_grp) {
15523 	case LPFC_PCI_DEV_LP:
15524 		lpfc_pci_remove_one_s3(pdev);
15525 		break;
15526 	case LPFC_PCI_DEV_OC:
15527 		lpfc_pci_remove_one_s4(pdev);
15528 		break;
15529 	default:
15530 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15531 				"1424 Invalid PCI device group: 0x%x\n",
15532 				phba->pci_dev_grp);
15533 		break;
15534 	}
15535 	return;
15536 }
15537 
15538 /**
15539  * lpfc_pci_suspend_one - lpfc PCI func to suspend dev for power management
15540  * @dev: pointer to device
15541  *
15542  * This routine is to be registered to the kernel's PCI subsystem to support
15543  * system Power Management (PM). When PM invokes this method, it dispatches
15544  * the action to the proper SLI-3 or SLI-4 device suspend routine, which will
15545  * suspend the device.
15546  *
15547  * Return code
15548  * 	0 - driver suspended the device
15549  * 	Error otherwise
15550  **/
15551 static int __maybe_unused
15552 lpfc_pci_suspend_one(struct device *dev)
15553 {
15554 	struct Scsi_Host *shost = dev_get_drvdata(dev);
15555 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15556 	int rc = -ENODEV;
15557 
15558 	switch (phba->pci_dev_grp) {
15559 	case LPFC_PCI_DEV_LP:
15560 		rc = lpfc_pci_suspend_one_s3(dev);
15561 		break;
15562 	case LPFC_PCI_DEV_OC:
15563 		rc = lpfc_pci_suspend_one_s4(dev);
15564 		break;
15565 	default:
15566 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15567 				"1425 Invalid PCI device group: 0x%x\n",
15568 				phba->pci_dev_grp);
15569 		break;
15570 	}
15571 	return rc;
15572 }
15573 
15574 /**
15575  * lpfc_pci_resume_one - lpfc PCI func to resume dev for power management
15576  * @dev: pointer to device
15577  *
15578  * This routine is to be registered to the kernel's PCI subsystem to support
15579  * system Power Management (PM). When PM invokes this method, it dispatches
15580  * the action to the proper SLI-3 or SLI-4 device resume routine, which will
15581  * resume the device.
15582  *
15583  * Return code
15584  * 	0 - driver suspended the device
15585  * 	Error otherwise
15586  **/
15587 static int __maybe_unused
15588 lpfc_pci_resume_one(struct device *dev)
15589 {
15590 	struct Scsi_Host *shost = dev_get_drvdata(dev);
15591 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15592 	int rc = -ENODEV;
15593 
15594 	switch (phba->pci_dev_grp) {
15595 	case LPFC_PCI_DEV_LP:
15596 		rc = lpfc_pci_resume_one_s3(dev);
15597 		break;
15598 	case LPFC_PCI_DEV_OC:
15599 		rc = lpfc_pci_resume_one_s4(dev);
15600 		break;
15601 	default:
15602 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15603 				"1426 Invalid PCI device group: 0x%x\n",
15604 				phba->pci_dev_grp);
15605 		break;
15606 	}
15607 	return rc;
15608 }
15609 
15610 /**
15611  * lpfc_io_error_detected - lpfc method for handling PCI I/O error
15612  * @pdev: pointer to PCI device.
15613  * @state: the current PCI connection state.
15614  *
15615  * This routine is registered to the PCI subsystem for error handling. This
15616  * function is called by the PCI subsystem after a PCI bus error affecting
15617  * this device has been detected. When this routine is invoked, it dispatches
15618  * the action to the proper SLI-3 or SLI-4 device error detected handling
15619  * routine, which will perform the proper error detected operation.
15620  *
15621  * Return codes
15622  * 	PCI_ERS_RESULT_NEED_RESET - need to reset before recovery
15623  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15624  **/
15625 static pci_ers_result_t
15626 lpfc_io_error_detected(struct pci_dev *pdev, pci_channel_state_t state)
15627 {
15628 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15629 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15630 	pci_ers_result_t rc = PCI_ERS_RESULT_DISCONNECT;
15631 
15632 	if (phba->link_state == LPFC_HBA_ERROR &&
15633 	    phba->hba_flag & HBA_IOQ_FLUSH)
15634 		return PCI_ERS_RESULT_NEED_RESET;
15635 
15636 	switch (phba->pci_dev_grp) {
15637 	case LPFC_PCI_DEV_LP:
15638 		rc = lpfc_io_error_detected_s3(pdev, state);
15639 		break;
15640 	case LPFC_PCI_DEV_OC:
15641 		rc = lpfc_io_error_detected_s4(pdev, state);
15642 		break;
15643 	default:
15644 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15645 				"1427 Invalid PCI device group: 0x%x\n",
15646 				phba->pci_dev_grp);
15647 		break;
15648 	}
15649 	return rc;
15650 }
15651 
15652 /**
15653  * lpfc_io_slot_reset - lpfc method for restart PCI dev from scratch
15654  * @pdev: pointer to PCI device.
15655  *
15656  * This routine is registered to the PCI subsystem for error handling. This
15657  * function is called after PCI bus has been reset to restart the PCI card
15658  * from scratch, as if from a cold-boot. When this routine is invoked, it
15659  * dispatches the action to the proper SLI-3 or SLI-4 device reset handling
15660  * routine, which will perform the proper device reset.
15661  *
15662  * Return codes
15663  * 	PCI_ERS_RESULT_RECOVERED - the device has been recovered
15664  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15665  **/
15666 static pci_ers_result_t
15667 lpfc_io_slot_reset(struct pci_dev *pdev)
15668 {
15669 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15670 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15671 	pci_ers_result_t rc = PCI_ERS_RESULT_DISCONNECT;
15672 
15673 	switch (phba->pci_dev_grp) {
15674 	case LPFC_PCI_DEV_LP:
15675 		rc = lpfc_io_slot_reset_s3(pdev);
15676 		break;
15677 	case LPFC_PCI_DEV_OC:
15678 		rc = lpfc_io_slot_reset_s4(pdev);
15679 		break;
15680 	default:
15681 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15682 				"1428 Invalid PCI device group: 0x%x\n",
15683 				phba->pci_dev_grp);
15684 		break;
15685 	}
15686 	return rc;
15687 }
15688 
15689 /**
15690  * lpfc_io_resume - lpfc method for resuming PCI I/O operation
15691  * @pdev: pointer to PCI device
15692  *
15693  * This routine is registered to the PCI subsystem for error handling. It
15694  * is called when kernel error recovery tells the lpfc driver that it is
15695  * OK to resume normal PCI operation after PCI bus error recovery. When
15696  * this routine is invoked, it dispatches the action to the proper SLI-3
15697  * or SLI-4 device io_resume routine, which will resume the device operation.
15698  **/
15699 static void
15700 lpfc_io_resume(struct pci_dev *pdev)
15701 {
15702 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15703 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15704 
15705 	switch (phba->pci_dev_grp) {
15706 	case LPFC_PCI_DEV_LP:
15707 		lpfc_io_resume_s3(pdev);
15708 		break;
15709 	case LPFC_PCI_DEV_OC:
15710 		lpfc_io_resume_s4(pdev);
15711 		break;
15712 	default:
15713 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15714 				"1429 Invalid PCI device group: 0x%x\n",
15715 				phba->pci_dev_grp);
15716 		break;
15717 	}
15718 	return;
15719 }
15720 
15721 /**
15722  * lpfc_sli4_oas_verify - Verify OAS is supported by this adapter
15723  * @phba: pointer to lpfc hba data structure.
15724  *
15725  * This routine checks to see if OAS is supported for this adapter. If
15726  * supported, the configure Flash Optimized Fabric flag is set.  Otherwise,
15727  * the enable oas flag is cleared and the pool created for OAS device data
15728  * is destroyed.
15729  *
15730  **/
15731 static void
15732 lpfc_sli4_oas_verify(struct lpfc_hba *phba)
15733 {
15734 
15735 	if (!phba->cfg_EnableXLane)
15736 		return;
15737 
15738 	if (phba->sli4_hba.pc_sli4_params.oas_supported) {
15739 		phba->cfg_fof = 1;
15740 	} else {
15741 		phba->cfg_fof = 0;
15742 		mempool_destroy(phba->device_data_mem_pool);
15743 		phba->device_data_mem_pool = NULL;
15744 	}
15745 
15746 	return;
15747 }
15748 
15749 /**
15750  * lpfc_sli4_ras_init - Verify RAS-FW log is supported by this adapter
15751  * @phba: pointer to lpfc hba data structure.
15752  *
15753  * This routine checks to see if RAS is supported by the adapter. Check the
15754  * function through which RAS support enablement is to be done.
15755  **/
15756 void
15757 lpfc_sli4_ras_init(struct lpfc_hba *phba)
15758 {
15759 	/* if ASIC_GEN_NUM >= 0xC) */
15760 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
15761 		    LPFC_SLI_INTF_IF_TYPE_6) ||
15762 	    (bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf) ==
15763 		    LPFC_SLI_INTF_FAMILY_G6)) {
15764 		phba->ras_fwlog.ras_hwsupport = true;
15765 		if (phba->cfg_ras_fwlog_func == PCI_FUNC(phba->pcidev->devfn) &&
15766 		    phba->cfg_ras_fwlog_buffsize)
15767 			phba->ras_fwlog.ras_enabled = true;
15768 		else
15769 			phba->ras_fwlog.ras_enabled = false;
15770 	} else {
15771 		phba->ras_fwlog.ras_hwsupport = false;
15772 	}
15773 }
15774 
15775 
15776 MODULE_DEVICE_TABLE(pci, lpfc_id_table);
15777 
15778 static const struct pci_error_handlers lpfc_err_handler = {
15779 	.error_detected = lpfc_io_error_detected,
15780 	.slot_reset = lpfc_io_slot_reset,
15781 	.resume = lpfc_io_resume,
15782 };
15783 
15784 static SIMPLE_DEV_PM_OPS(lpfc_pci_pm_ops_one,
15785 			 lpfc_pci_suspend_one,
15786 			 lpfc_pci_resume_one);
15787 
15788 static struct pci_driver lpfc_driver = {
15789 	.name		= LPFC_DRIVER_NAME,
15790 	.id_table	= lpfc_id_table,
15791 	.probe		= lpfc_pci_probe_one,
15792 	.remove		= lpfc_pci_remove_one,
15793 	.shutdown	= lpfc_pci_remove_one,
15794 	.driver.pm	= &lpfc_pci_pm_ops_one,
15795 	.err_handler    = &lpfc_err_handler,
15796 };
15797 
15798 static const struct file_operations lpfc_mgmt_fop = {
15799 	.owner = THIS_MODULE,
15800 };
15801 
15802 static struct miscdevice lpfc_mgmt_dev = {
15803 	.minor = MISC_DYNAMIC_MINOR,
15804 	.name = "lpfcmgmt",
15805 	.fops = &lpfc_mgmt_fop,
15806 };
15807 
15808 /**
15809  * lpfc_init - lpfc module initialization routine
15810  *
15811  * This routine is to be invoked when the lpfc module is loaded into the
15812  * kernel. The special kernel macro module_init() is used to indicate the
15813  * role of this routine to the kernel as lpfc module entry point.
15814  *
15815  * Return codes
15816  *   0 - successful
15817  *   -ENOMEM - FC attach transport failed
15818  *   all others - failed
15819  */
15820 static int __init
15821 lpfc_init(void)
15822 {
15823 	int error = 0;
15824 
15825 	pr_info(LPFC_MODULE_DESC "\n");
15826 	pr_info(LPFC_COPYRIGHT "\n");
15827 
15828 	error = misc_register(&lpfc_mgmt_dev);
15829 	if (error)
15830 		printk(KERN_ERR "Could not register lpfcmgmt device, "
15831 			"misc_register returned with status %d", error);
15832 
15833 	error = -ENOMEM;
15834 	lpfc_transport_functions.vport_create = lpfc_vport_create;
15835 	lpfc_transport_functions.vport_delete = lpfc_vport_delete;
15836 	lpfc_transport_template =
15837 				fc_attach_transport(&lpfc_transport_functions);
15838 	if (lpfc_transport_template == NULL)
15839 		goto unregister;
15840 	lpfc_vport_transport_template =
15841 		fc_attach_transport(&lpfc_vport_transport_functions);
15842 	if (lpfc_vport_transport_template == NULL) {
15843 		fc_release_transport(lpfc_transport_template);
15844 		goto unregister;
15845 	}
15846 	lpfc_wqe_cmd_template();
15847 	lpfc_nvmet_cmd_template();
15848 
15849 	/* Initialize in case vector mapping is needed */
15850 	lpfc_present_cpu = num_present_cpus();
15851 
15852 	lpfc_pldv_detect = false;
15853 
15854 	error = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN,
15855 					"lpfc/sli4:online",
15856 					lpfc_cpu_online, lpfc_cpu_offline);
15857 	if (error < 0)
15858 		goto cpuhp_failure;
15859 	lpfc_cpuhp_state = error;
15860 
15861 	error = pci_register_driver(&lpfc_driver);
15862 	if (error)
15863 		goto unwind;
15864 
15865 	return error;
15866 
15867 unwind:
15868 	cpuhp_remove_multi_state(lpfc_cpuhp_state);
15869 cpuhp_failure:
15870 	fc_release_transport(lpfc_transport_template);
15871 	fc_release_transport(lpfc_vport_transport_template);
15872 unregister:
15873 	misc_deregister(&lpfc_mgmt_dev);
15874 
15875 	return error;
15876 }
15877 
15878 void lpfc_dmp_dbg(struct lpfc_hba *phba)
15879 {
15880 	unsigned int start_idx;
15881 	unsigned int dbg_cnt;
15882 	unsigned int temp_idx;
15883 	int i;
15884 	int j = 0;
15885 	unsigned long rem_nsec;
15886 
15887 	if (atomic_cmpxchg(&phba->dbg_log_dmping, 0, 1) != 0)
15888 		return;
15889 
15890 	start_idx = (unsigned int)atomic_read(&phba->dbg_log_idx) % DBG_LOG_SZ;
15891 	dbg_cnt = (unsigned int)atomic_read(&phba->dbg_log_cnt);
15892 	if (!dbg_cnt)
15893 		goto out;
15894 	temp_idx = start_idx;
15895 	if (dbg_cnt >= DBG_LOG_SZ) {
15896 		dbg_cnt = DBG_LOG_SZ;
15897 		temp_idx -= 1;
15898 	} else {
15899 		if ((start_idx + dbg_cnt) > (DBG_LOG_SZ - 1)) {
15900 			temp_idx = (start_idx + dbg_cnt) % DBG_LOG_SZ;
15901 		} else {
15902 			if (start_idx < dbg_cnt)
15903 				start_idx = DBG_LOG_SZ - (dbg_cnt - start_idx);
15904 			else
15905 				start_idx -= dbg_cnt;
15906 		}
15907 	}
15908 	dev_info(&phba->pcidev->dev, "start %d end %d cnt %d\n",
15909 		 start_idx, temp_idx, dbg_cnt);
15910 
15911 	for (i = 0; i < dbg_cnt; i++) {
15912 		if ((start_idx + i) < DBG_LOG_SZ)
15913 			temp_idx = (start_idx + i) % DBG_LOG_SZ;
15914 		else
15915 			temp_idx = j++;
15916 		rem_nsec = do_div(phba->dbg_log[temp_idx].t_ns, NSEC_PER_SEC);
15917 		dev_info(&phba->pcidev->dev, "%d: [%5lu.%06lu] %s",
15918 			 temp_idx,
15919 			 (unsigned long)phba->dbg_log[temp_idx].t_ns,
15920 			 rem_nsec / 1000,
15921 			 phba->dbg_log[temp_idx].log);
15922 	}
15923 out:
15924 	atomic_set(&phba->dbg_log_cnt, 0);
15925 	atomic_set(&phba->dbg_log_dmping, 0);
15926 }
15927 
15928 __printf(2, 3)
15929 void lpfc_dbg_print(struct lpfc_hba *phba, const char *fmt, ...)
15930 {
15931 	unsigned int idx;
15932 	va_list args;
15933 	int dbg_dmping = atomic_read(&phba->dbg_log_dmping);
15934 	struct va_format vaf;
15935 
15936 
15937 	va_start(args, fmt);
15938 	if (unlikely(dbg_dmping)) {
15939 		vaf.fmt = fmt;
15940 		vaf.va = &args;
15941 		dev_info(&phba->pcidev->dev, "%pV", &vaf);
15942 		va_end(args);
15943 		return;
15944 	}
15945 	idx = (unsigned int)atomic_fetch_add(1, &phba->dbg_log_idx) %
15946 		DBG_LOG_SZ;
15947 
15948 	atomic_inc(&phba->dbg_log_cnt);
15949 
15950 	vscnprintf(phba->dbg_log[idx].log,
15951 		   sizeof(phba->dbg_log[idx].log), fmt, args);
15952 	va_end(args);
15953 
15954 	phba->dbg_log[idx].t_ns = local_clock();
15955 }
15956 
15957 /**
15958  * lpfc_exit - lpfc module removal routine
15959  *
15960  * This routine is invoked when the lpfc module is removed from the kernel.
15961  * The special kernel macro module_exit() is used to indicate the role of
15962  * this routine to the kernel as lpfc module exit point.
15963  */
15964 static void __exit
15965 lpfc_exit(void)
15966 {
15967 	misc_deregister(&lpfc_mgmt_dev);
15968 	pci_unregister_driver(&lpfc_driver);
15969 	cpuhp_remove_multi_state(lpfc_cpuhp_state);
15970 	fc_release_transport(lpfc_transport_template);
15971 	fc_release_transport(lpfc_vport_transport_template);
15972 	idr_destroy(&lpfc_hba_index);
15973 }
15974 
15975 module_init(lpfc_init);
15976 module_exit(lpfc_exit);
15977 MODULE_LICENSE("GPL");
15978 MODULE_DESCRIPTION(LPFC_MODULE_DESC);
15979 MODULE_AUTHOR("Broadcom");
15980 MODULE_VERSION("0:" LPFC_DRIVER_VERSION);
15981