xref: /openbmc/linux/drivers/scsi/lpfc/lpfc_init.c (revision fadbafc1)
1 /*******************************************************************
2  * This file is part of the Emulex Linux Device Driver for         *
3  * Fibre Channel Host Bus Adapters.                                *
4  * Copyright (C) 2017-2022 Broadcom. All Rights Reserved. The term *
5  * “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.  *
6  * Copyright (C) 2004-2016 Emulex.  All rights reserved.           *
7  * EMULEX and SLI are trademarks of Emulex.                        *
8  * www.broadcom.com                                                *
9  * Portions Copyright (C) 2004-2005 Christoph Hellwig              *
10  *                                                                 *
11  * This program is free software; you can redistribute it and/or   *
12  * modify it under the terms of version 2 of the GNU General       *
13  * Public License as published by the Free Software Foundation.    *
14  * This program is distributed in the hope that it will be useful. *
15  * ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND          *
16  * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,  *
17  * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE      *
18  * DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD *
19  * TO BE LEGALLY INVALID.  See the GNU General Public License for  *
20  * more details, a copy of which can be found in the file COPYING  *
21  * included with this package.                                     *
22  *******************************************************************/
23 
24 #include <linux/blkdev.h>
25 #include <linux/delay.h>
26 #include <linux/dma-mapping.h>
27 #include <linux/idr.h>
28 #include <linux/interrupt.h>
29 #include <linux/module.h>
30 #include <linux/kthread.h>
31 #include <linux/pci.h>
32 #include <linux/spinlock.h>
33 #include <linux/ctype.h>
34 #include <linux/aer.h>
35 #include <linux/slab.h>
36 #include <linux/firmware.h>
37 #include <linux/miscdevice.h>
38 #include <linux/percpu.h>
39 #include <linux/msi.h>
40 #include <linux/irq.h>
41 #include <linux/bitops.h>
42 #include <linux/crash_dump.h>
43 #include <linux/cpu.h>
44 #include <linux/cpuhotplug.h>
45 
46 #include <scsi/scsi.h>
47 #include <scsi/scsi_device.h>
48 #include <scsi/scsi_host.h>
49 #include <scsi/scsi_transport_fc.h>
50 #include <scsi/scsi_tcq.h>
51 #include <scsi/fc/fc_fs.h>
52 
53 #include "lpfc_hw4.h"
54 #include "lpfc_hw.h"
55 #include "lpfc_sli.h"
56 #include "lpfc_sli4.h"
57 #include "lpfc_nl.h"
58 #include "lpfc_disc.h"
59 #include "lpfc.h"
60 #include "lpfc_scsi.h"
61 #include "lpfc_nvme.h"
62 #include "lpfc_logmsg.h"
63 #include "lpfc_crtn.h"
64 #include "lpfc_vport.h"
65 #include "lpfc_version.h"
66 #include "lpfc_ids.h"
67 
68 static enum cpuhp_state lpfc_cpuhp_state;
69 /* Used when mapping IRQ vectors in a driver centric manner */
70 static uint32_t lpfc_present_cpu;
71 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 
703 	/* Are we forcing MI off via module parameter? */
704 	if (phba->cfg_enable_mi)
705 		phba->sli4_hba.pc_sli4_params.mi_ver =
706 			bf_get(cfg_mi_ver, mbx_sli4_parameters);
707 	else
708 		phba->sli4_hba.pc_sli4_params.mi_ver = 0;
709 
710 	phba->sli4_hba.pc_sli4_params.cmf =
711 			bf_get(cfg_cmf, mbx_sli4_parameters);
712 	phba->sli4_hba.pc_sli4_params.pls =
713 			bf_get(cfg_pvl, mbx_sli4_parameters);
714 
715 	mempool_free(mboxq, phba->mbox_mem_pool);
716 	return rc;
717 }
718 
719 /**
720  * lpfc_hba_init_link - Initialize the FC link
721  * @phba: pointer to lpfc hba data structure.
722  * @flag: mailbox command issue mode - either MBX_POLL or MBX_NOWAIT
723  *
724  * This routine will issue the INIT_LINK mailbox command call.
725  * It is available to other drivers through the lpfc_hba data
726  * structure for use as a delayed link up mechanism with the
727  * module parameter lpfc_suppress_link_up.
728  *
729  * Return code
730  *		0 - success
731  *		Any other value - error
732  **/
733 static int
734 lpfc_hba_init_link(struct lpfc_hba *phba, uint32_t flag)
735 {
736 	return lpfc_hba_init_link_fc_topology(phba, phba->cfg_topology, flag);
737 }
738 
739 /**
740  * lpfc_hba_init_link_fc_topology - Initialize FC link with desired topology
741  * @phba: pointer to lpfc hba data structure.
742  * @fc_topology: desired fc topology.
743  * @flag: mailbox command issue mode - either MBX_POLL or MBX_NOWAIT
744  *
745  * This routine will issue the INIT_LINK mailbox command call.
746  * It is available to other drivers through the lpfc_hba data
747  * structure for use as a delayed link up mechanism with the
748  * module parameter lpfc_suppress_link_up.
749  *
750  * Return code
751  *              0 - success
752  *              Any other value - error
753  **/
754 int
755 lpfc_hba_init_link_fc_topology(struct lpfc_hba *phba, uint32_t fc_topology,
756 			       uint32_t flag)
757 {
758 	struct lpfc_vport *vport = phba->pport;
759 	LPFC_MBOXQ_t *pmb;
760 	MAILBOX_t *mb;
761 	int rc;
762 
763 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
764 	if (!pmb) {
765 		phba->link_state = LPFC_HBA_ERROR;
766 		return -ENOMEM;
767 	}
768 	mb = &pmb->u.mb;
769 	pmb->vport = vport;
770 
771 	if ((phba->cfg_link_speed > LPFC_USER_LINK_SPEED_MAX) ||
772 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_1G) &&
773 	     !(phba->lmt & LMT_1Gb)) ||
774 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_2G) &&
775 	     !(phba->lmt & LMT_2Gb)) ||
776 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_4G) &&
777 	     !(phba->lmt & LMT_4Gb)) ||
778 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_8G) &&
779 	     !(phba->lmt & LMT_8Gb)) ||
780 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_10G) &&
781 	     !(phba->lmt & LMT_10Gb)) ||
782 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_16G) &&
783 	     !(phba->lmt & LMT_16Gb)) ||
784 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_32G) &&
785 	     !(phba->lmt & LMT_32Gb)) ||
786 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_64G) &&
787 	     !(phba->lmt & LMT_64Gb))) {
788 		/* Reset link speed to auto */
789 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
790 				"1302 Invalid speed for this board:%d "
791 				"Reset link speed to auto.\n",
792 				phba->cfg_link_speed);
793 			phba->cfg_link_speed = LPFC_USER_LINK_SPEED_AUTO;
794 	}
795 	lpfc_init_link(phba, pmb, fc_topology, phba->cfg_link_speed);
796 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
797 	if (phba->sli_rev < LPFC_SLI_REV4)
798 		lpfc_set_loopback_flag(phba);
799 	rc = lpfc_sli_issue_mbox(phba, pmb, flag);
800 	if ((rc != MBX_BUSY) && (rc != MBX_SUCCESS)) {
801 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
802 				"0498 Adapter failed to init, mbxCmd x%x "
803 				"INIT_LINK, mbxStatus x%x\n",
804 				mb->mbxCommand, mb->mbxStatus);
805 		if (phba->sli_rev <= LPFC_SLI_REV3) {
806 			/* Clear all interrupt enable conditions */
807 			writel(0, phba->HCregaddr);
808 			readl(phba->HCregaddr); /* flush */
809 			/* Clear all pending interrupts */
810 			writel(0xffffffff, phba->HAregaddr);
811 			readl(phba->HAregaddr); /* flush */
812 		}
813 		phba->link_state = LPFC_HBA_ERROR;
814 		if (rc != MBX_BUSY || flag == MBX_POLL)
815 			mempool_free(pmb, phba->mbox_mem_pool);
816 		return -EIO;
817 	}
818 	phba->cfg_suppress_link_up = LPFC_INITIALIZE_LINK;
819 	if (flag == MBX_POLL)
820 		mempool_free(pmb, phba->mbox_mem_pool);
821 
822 	return 0;
823 }
824 
825 /**
826  * lpfc_hba_down_link - this routine downs the FC link
827  * @phba: pointer to lpfc hba data structure.
828  * @flag: mailbox command issue mode - either MBX_POLL or MBX_NOWAIT
829  *
830  * This routine will issue the DOWN_LINK mailbox command call.
831  * It is available to other drivers through the lpfc_hba data
832  * structure for use to stop the link.
833  *
834  * Return code
835  *		0 - success
836  *		Any other value - error
837  **/
838 static int
839 lpfc_hba_down_link(struct lpfc_hba *phba, uint32_t flag)
840 {
841 	LPFC_MBOXQ_t *pmb;
842 	int rc;
843 
844 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
845 	if (!pmb) {
846 		phba->link_state = LPFC_HBA_ERROR;
847 		return -ENOMEM;
848 	}
849 
850 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
851 			"0491 Adapter Link is disabled.\n");
852 	lpfc_down_link(phba, pmb);
853 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
854 	rc = lpfc_sli_issue_mbox(phba, pmb, flag);
855 	if ((rc != MBX_SUCCESS) && (rc != MBX_BUSY)) {
856 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
857 				"2522 Adapter failed to issue DOWN_LINK"
858 				" mbox command rc 0x%x\n", rc);
859 
860 		mempool_free(pmb, phba->mbox_mem_pool);
861 		return -EIO;
862 	}
863 	if (flag == MBX_POLL)
864 		mempool_free(pmb, phba->mbox_mem_pool);
865 
866 	return 0;
867 }
868 
869 /**
870  * lpfc_hba_down_prep - Perform lpfc uninitialization prior to HBA reset
871  * @phba: pointer to lpfc HBA data structure.
872  *
873  * This routine will do LPFC uninitialization before the HBA is reset when
874  * bringing down the SLI Layer.
875  *
876  * Return codes
877  *   0 - success.
878  *   Any other value - error.
879  **/
880 int
881 lpfc_hba_down_prep(struct lpfc_hba *phba)
882 {
883 	struct lpfc_vport **vports;
884 	int i;
885 
886 	if (phba->sli_rev <= LPFC_SLI_REV3) {
887 		/* Disable interrupts */
888 		writel(0, phba->HCregaddr);
889 		readl(phba->HCregaddr); /* flush */
890 	}
891 
892 	if (phba->pport->load_flag & FC_UNLOADING)
893 		lpfc_cleanup_discovery_resources(phba->pport);
894 	else {
895 		vports = lpfc_create_vport_work_array(phba);
896 		if (vports != NULL)
897 			for (i = 0; i <= phba->max_vports &&
898 				vports[i] != NULL; i++)
899 				lpfc_cleanup_discovery_resources(vports[i]);
900 		lpfc_destroy_vport_work_array(phba, vports);
901 	}
902 	return 0;
903 }
904 
905 /**
906  * lpfc_sli4_free_sp_events - Cleanup sp_queue_events to free
907  * rspiocb which got deferred
908  *
909  * @phba: pointer to lpfc HBA data structure.
910  *
911  * This routine will cleanup completed slow path events after HBA is reset
912  * when bringing down the SLI Layer.
913  *
914  *
915  * Return codes
916  *   void.
917  **/
918 static void
919 lpfc_sli4_free_sp_events(struct lpfc_hba *phba)
920 {
921 	struct lpfc_iocbq *rspiocbq;
922 	struct hbq_dmabuf *dmabuf;
923 	struct lpfc_cq_event *cq_event;
924 
925 	spin_lock_irq(&phba->hbalock);
926 	phba->hba_flag &= ~HBA_SP_QUEUE_EVT;
927 	spin_unlock_irq(&phba->hbalock);
928 
929 	while (!list_empty(&phba->sli4_hba.sp_queue_event)) {
930 		/* Get the response iocb from the head of work queue */
931 		spin_lock_irq(&phba->hbalock);
932 		list_remove_head(&phba->sli4_hba.sp_queue_event,
933 				 cq_event, struct lpfc_cq_event, list);
934 		spin_unlock_irq(&phba->hbalock);
935 
936 		switch (bf_get(lpfc_wcqe_c_code, &cq_event->cqe.wcqe_cmpl)) {
937 		case CQE_CODE_COMPL_WQE:
938 			rspiocbq = container_of(cq_event, struct lpfc_iocbq,
939 						 cq_event);
940 			lpfc_sli_release_iocbq(phba, rspiocbq);
941 			break;
942 		case CQE_CODE_RECEIVE:
943 		case CQE_CODE_RECEIVE_V1:
944 			dmabuf = container_of(cq_event, struct hbq_dmabuf,
945 					      cq_event);
946 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
947 		}
948 	}
949 }
950 
951 /**
952  * lpfc_hba_free_post_buf - Perform lpfc uninitialization after HBA reset
953  * @phba: pointer to lpfc HBA data structure.
954  *
955  * This routine will cleanup posted ELS buffers after the HBA is reset
956  * when bringing down the SLI Layer.
957  *
958  *
959  * Return codes
960  *   void.
961  **/
962 static void
963 lpfc_hba_free_post_buf(struct lpfc_hba *phba)
964 {
965 	struct lpfc_sli *psli = &phba->sli;
966 	struct lpfc_sli_ring *pring;
967 	struct lpfc_dmabuf *mp, *next_mp;
968 	LIST_HEAD(buflist);
969 	int count;
970 
971 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)
972 		lpfc_sli_hbqbuf_free_all(phba);
973 	else {
974 		/* Cleanup preposted buffers on the ELS ring */
975 		pring = &psli->sli3_ring[LPFC_ELS_RING];
976 		spin_lock_irq(&phba->hbalock);
977 		list_splice_init(&pring->postbufq, &buflist);
978 		spin_unlock_irq(&phba->hbalock);
979 
980 		count = 0;
981 		list_for_each_entry_safe(mp, next_mp, &buflist, list) {
982 			list_del(&mp->list);
983 			count++;
984 			lpfc_mbuf_free(phba, mp->virt, mp->phys);
985 			kfree(mp);
986 		}
987 
988 		spin_lock_irq(&phba->hbalock);
989 		pring->postbufq_cnt -= count;
990 		spin_unlock_irq(&phba->hbalock);
991 	}
992 }
993 
994 /**
995  * lpfc_hba_clean_txcmplq - Perform lpfc uninitialization after HBA reset
996  * @phba: pointer to lpfc HBA data structure.
997  *
998  * This routine will cleanup the txcmplq after the HBA is reset when bringing
999  * down the SLI Layer.
1000  *
1001  * Return codes
1002  *   void
1003  **/
1004 static void
1005 lpfc_hba_clean_txcmplq(struct lpfc_hba *phba)
1006 {
1007 	struct lpfc_sli *psli = &phba->sli;
1008 	struct lpfc_queue *qp = NULL;
1009 	struct lpfc_sli_ring *pring;
1010 	LIST_HEAD(completions);
1011 	int i;
1012 	struct lpfc_iocbq *piocb, *next_iocb;
1013 
1014 	if (phba->sli_rev != LPFC_SLI_REV4) {
1015 		for (i = 0; i < psli->num_rings; i++) {
1016 			pring = &psli->sli3_ring[i];
1017 			spin_lock_irq(&phba->hbalock);
1018 			/* At this point in time the HBA is either reset or DOA
1019 			 * Nothing should be on txcmplq as it will
1020 			 * NEVER complete.
1021 			 */
1022 			list_splice_init(&pring->txcmplq, &completions);
1023 			pring->txcmplq_cnt = 0;
1024 			spin_unlock_irq(&phba->hbalock);
1025 
1026 			lpfc_sli_abort_iocb_ring(phba, pring);
1027 		}
1028 		/* Cancel all the IOCBs from the completions list */
1029 		lpfc_sli_cancel_iocbs(phba, &completions,
1030 				      IOSTAT_LOCAL_REJECT, IOERR_SLI_ABORTED);
1031 		return;
1032 	}
1033 	list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
1034 		pring = qp->pring;
1035 		if (!pring)
1036 			continue;
1037 		spin_lock_irq(&pring->ring_lock);
1038 		list_for_each_entry_safe(piocb, next_iocb,
1039 					 &pring->txcmplq, list)
1040 			piocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
1041 		list_splice_init(&pring->txcmplq, &completions);
1042 		pring->txcmplq_cnt = 0;
1043 		spin_unlock_irq(&pring->ring_lock);
1044 		lpfc_sli_abort_iocb_ring(phba, pring);
1045 	}
1046 	/* Cancel all the IOCBs from the completions list */
1047 	lpfc_sli_cancel_iocbs(phba, &completions,
1048 			      IOSTAT_LOCAL_REJECT, IOERR_SLI_ABORTED);
1049 }
1050 
1051 /**
1052  * lpfc_hba_down_post_s3 - Perform lpfc uninitialization after HBA reset
1053  * @phba: pointer to lpfc HBA data structure.
1054  *
1055  * This routine will do uninitialization after the HBA is reset when bring
1056  * down the SLI Layer.
1057  *
1058  * Return codes
1059  *   0 - success.
1060  *   Any other value - error.
1061  **/
1062 static int
1063 lpfc_hba_down_post_s3(struct lpfc_hba *phba)
1064 {
1065 	lpfc_hba_free_post_buf(phba);
1066 	lpfc_hba_clean_txcmplq(phba);
1067 	return 0;
1068 }
1069 
1070 /**
1071  * lpfc_hba_down_post_s4 - Perform lpfc uninitialization after HBA reset
1072  * @phba: pointer to lpfc HBA data structure.
1073  *
1074  * This routine will do uninitialization after the HBA is reset when bring
1075  * down the SLI Layer.
1076  *
1077  * Return codes
1078  *   0 - success.
1079  *   Any other value - error.
1080  **/
1081 static int
1082 lpfc_hba_down_post_s4(struct lpfc_hba *phba)
1083 {
1084 	struct lpfc_io_buf *psb, *psb_next;
1085 	struct lpfc_async_xchg_ctx *ctxp, *ctxp_next;
1086 	struct lpfc_sli4_hdw_queue *qp;
1087 	LIST_HEAD(aborts);
1088 	LIST_HEAD(nvme_aborts);
1089 	LIST_HEAD(nvmet_aborts);
1090 	struct lpfc_sglq *sglq_entry = NULL;
1091 	int cnt, idx;
1092 
1093 
1094 	lpfc_sli_hbqbuf_free_all(phba);
1095 	lpfc_hba_clean_txcmplq(phba);
1096 
1097 	/* At this point in time the HBA is either reset or DOA. Either
1098 	 * way, nothing should be on lpfc_abts_els_sgl_list, it needs to be
1099 	 * on the lpfc_els_sgl_list so that it can either be freed if the
1100 	 * driver is unloading or reposted if the driver is restarting
1101 	 * the port.
1102 	 */
1103 
1104 	/* sgl_list_lock required because worker thread uses this
1105 	 * list.
1106 	 */
1107 	spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
1108 	list_for_each_entry(sglq_entry,
1109 		&phba->sli4_hba.lpfc_abts_els_sgl_list, list)
1110 		sglq_entry->state = SGL_FREED;
1111 
1112 	list_splice_init(&phba->sli4_hba.lpfc_abts_els_sgl_list,
1113 			&phba->sli4_hba.lpfc_els_sgl_list);
1114 
1115 
1116 	spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
1117 
1118 	/* abts_xxxx_buf_list_lock required because worker thread uses this
1119 	 * list.
1120 	 */
1121 	spin_lock_irq(&phba->hbalock);
1122 	cnt = 0;
1123 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
1124 		qp = &phba->sli4_hba.hdwq[idx];
1125 
1126 		spin_lock(&qp->abts_io_buf_list_lock);
1127 		list_splice_init(&qp->lpfc_abts_io_buf_list,
1128 				 &aborts);
1129 
1130 		list_for_each_entry_safe(psb, psb_next, &aborts, list) {
1131 			psb->pCmd = NULL;
1132 			psb->status = IOSTAT_SUCCESS;
1133 			cnt++;
1134 		}
1135 		spin_lock(&qp->io_buf_list_put_lock);
1136 		list_splice_init(&aborts, &qp->lpfc_io_buf_list_put);
1137 		qp->put_io_bufs += qp->abts_scsi_io_bufs;
1138 		qp->put_io_bufs += qp->abts_nvme_io_bufs;
1139 		qp->abts_scsi_io_bufs = 0;
1140 		qp->abts_nvme_io_bufs = 0;
1141 		spin_unlock(&qp->io_buf_list_put_lock);
1142 		spin_unlock(&qp->abts_io_buf_list_lock);
1143 	}
1144 	spin_unlock_irq(&phba->hbalock);
1145 
1146 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
1147 		spin_lock_irq(&phba->sli4_hba.abts_nvmet_buf_list_lock);
1148 		list_splice_init(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list,
1149 				 &nvmet_aborts);
1150 		spin_unlock_irq(&phba->sli4_hba.abts_nvmet_buf_list_lock);
1151 		list_for_each_entry_safe(ctxp, ctxp_next, &nvmet_aborts, list) {
1152 			ctxp->flag &= ~(LPFC_NVME_XBUSY | LPFC_NVME_ABORT_OP);
1153 			lpfc_nvmet_ctxbuf_post(phba, ctxp->ctxbuf);
1154 		}
1155 	}
1156 
1157 	lpfc_sli4_free_sp_events(phba);
1158 	return cnt;
1159 }
1160 
1161 /**
1162  * lpfc_hba_down_post - Wrapper func for hba down post routine
1163  * @phba: pointer to lpfc HBA data structure.
1164  *
1165  * This routine wraps the actual SLI3 or SLI4 routine for performing
1166  * uninitialization after the HBA is reset when bring down the SLI Layer.
1167  *
1168  * Return codes
1169  *   0 - success.
1170  *   Any other value - error.
1171  **/
1172 int
1173 lpfc_hba_down_post(struct lpfc_hba *phba)
1174 {
1175 	return (*phba->lpfc_hba_down_post)(phba);
1176 }
1177 
1178 /**
1179  * lpfc_hb_timeout - The HBA-timer timeout handler
1180  * @t: timer context used to obtain the pointer to lpfc hba data structure.
1181  *
1182  * This is the HBA-timer timeout handler registered to the lpfc driver. When
1183  * this timer fires, a HBA timeout event shall be posted to the lpfc driver
1184  * work-port-events bitmap and the worker thread is notified. This timeout
1185  * event will be used by the worker thread to invoke the actual timeout
1186  * handler routine, lpfc_hb_timeout_handler. Any periodical operations will
1187  * be performed in the timeout handler and the HBA timeout event bit shall
1188  * be cleared by the worker thread after it has taken the event bitmap out.
1189  **/
1190 static void
1191 lpfc_hb_timeout(struct timer_list *t)
1192 {
1193 	struct lpfc_hba *phba;
1194 	uint32_t tmo_posted;
1195 	unsigned long iflag;
1196 
1197 	phba = from_timer(phba, t, hb_tmofunc);
1198 
1199 	/* Check for heart beat timeout conditions */
1200 	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
1201 	tmo_posted = phba->pport->work_port_events & WORKER_HB_TMO;
1202 	if (!tmo_posted)
1203 		phba->pport->work_port_events |= WORKER_HB_TMO;
1204 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
1205 
1206 	/* Tell the worker thread there is work to do */
1207 	if (!tmo_posted)
1208 		lpfc_worker_wake_up(phba);
1209 	return;
1210 }
1211 
1212 /**
1213  * lpfc_rrq_timeout - The RRQ-timer timeout handler
1214  * @t: timer context used to obtain the pointer to lpfc hba data structure.
1215  *
1216  * This is the RRQ-timer timeout handler registered to the lpfc driver. When
1217  * this timer fires, a RRQ timeout event shall be posted to the lpfc driver
1218  * work-port-events bitmap and the worker thread is notified. This timeout
1219  * event will be used by the worker thread to invoke the actual timeout
1220  * handler routine, lpfc_rrq_handler. Any periodical operations will
1221  * be performed in the timeout handler and the RRQ timeout event bit shall
1222  * be cleared by the worker thread after it has taken the event bitmap out.
1223  **/
1224 static void
1225 lpfc_rrq_timeout(struct timer_list *t)
1226 {
1227 	struct lpfc_hba *phba;
1228 	unsigned long iflag;
1229 
1230 	phba = from_timer(phba, t, rrq_tmr);
1231 	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
1232 	if (!(phba->pport->load_flag & FC_UNLOADING))
1233 		phba->hba_flag |= HBA_RRQ_ACTIVE;
1234 	else
1235 		phba->hba_flag &= ~HBA_RRQ_ACTIVE;
1236 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
1237 
1238 	if (!(phba->pport->load_flag & FC_UNLOADING))
1239 		lpfc_worker_wake_up(phba);
1240 }
1241 
1242 /**
1243  * lpfc_hb_mbox_cmpl - The lpfc heart-beat mailbox command callback function
1244  * @phba: pointer to lpfc hba data structure.
1245  * @pmboxq: pointer to the driver internal queue element for mailbox command.
1246  *
1247  * This is the callback function to the lpfc heart-beat mailbox command.
1248  * If configured, the lpfc driver issues the heart-beat mailbox command to
1249  * the HBA every LPFC_HB_MBOX_INTERVAL (current 5) seconds. At the time the
1250  * heart-beat mailbox command is issued, the driver shall set up heart-beat
1251  * timeout timer to LPFC_HB_MBOX_TIMEOUT (current 30) seconds and marks
1252  * heart-beat outstanding state. Once the mailbox command comes back and
1253  * no error conditions detected, the heart-beat mailbox command timer is
1254  * reset to LPFC_HB_MBOX_INTERVAL seconds and the heart-beat outstanding
1255  * state is cleared for the next heart-beat. If the timer expired with the
1256  * heart-beat outstanding state set, the driver will put the HBA offline.
1257  **/
1258 static void
1259 lpfc_hb_mbox_cmpl(struct lpfc_hba * phba, LPFC_MBOXQ_t * pmboxq)
1260 {
1261 	unsigned long drvr_flag;
1262 
1263 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
1264 	phba->hba_flag &= ~(HBA_HBEAT_INP | HBA_HBEAT_TMO);
1265 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
1266 
1267 	/* Check and reset heart-beat timer if necessary */
1268 	mempool_free(pmboxq, phba->mbox_mem_pool);
1269 	if (!(phba->pport->fc_flag & FC_OFFLINE_MODE) &&
1270 		!(phba->link_state == LPFC_HBA_ERROR) &&
1271 		!(phba->pport->load_flag & FC_UNLOADING))
1272 		mod_timer(&phba->hb_tmofunc,
1273 			  jiffies +
1274 			  msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
1275 	return;
1276 }
1277 
1278 /*
1279  * lpfc_idle_stat_delay_work - idle_stat tracking
1280  *
1281  * This routine tracks per-cq idle_stat and determines polling decisions.
1282  *
1283  * Return codes:
1284  *   None
1285  **/
1286 static void
1287 lpfc_idle_stat_delay_work(struct work_struct *work)
1288 {
1289 	struct lpfc_hba *phba = container_of(to_delayed_work(work),
1290 					     struct lpfc_hba,
1291 					     idle_stat_delay_work);
1292 	struct lpfc_queue *cq;
1293 	struct lpfc_sli4_hdw_queue *hdwq;
1294 	struct lpfc_idle_stat *idle_stat;
1295 	u32 i, idle_percent;
1296 	u64 wall, wall_idle, diff_wall, diff_idle, busy_time;
1297 
1298 	if (phba->pport->load_flag & FC_UNLOADING)
1299 		return;
1300 
1301 	if (phba->link_state == LPFC_HBA_ERROR ||
1302 	    phba->pport->fc_flag & FC_OFFLINE_MODE ||
1303 	    phba->cmf_active_mode != LPFC_CFG_OFF)
1304 		goto requeue;
1305 
1306 	for_each_present_cpu(i) {
1307 		hdwq = &phba->sli4_hba.hdwq[phba->sli4_hba.cpu_map[i].hdwq];
1308 		cq = hdwq->io_cq;
1309 
1310 		/* Skip if we've already handled this cq's primary CPU */
1311 		if (cq->chann != i)
1312 			continue;
1313 
1314 		idle_stat = &phba->sli4_hba.idle_stat[i];
1315 
1316 		/* get_cpu_idle_time returns values as running counters. Thus,
1317 		 * to know the amount for this period, the prior counter values
1318 		 * need to be subtracted from the current counter values.
1319 		 * From there, the idle time stat can be calculated as a
1320 		 * percentage of 100 - the sum of the other consumption times.
1321 		 */
1322 		wall_idle = get_cpu_idle_time(i, &wall, 1);
1323 		diff_idle = wall_idle - idle_stat->prev_idle;
1324 		diff_wall = wall - idle_stat->prev_wall;
1325 
1326 		if (diff_wall <= diff_idle)
1327 			busy_time = 0;
1328 		else
1329 			busy_time = diff_wall - diff_idle;
1330 
1331 		idle_percent = div64_u64(100 * busy_time, diff_wall);
1332 		idle_percent = 100 - idle_percent;
1333 
1334 		if (idle_percent < 15)
1335 			cq->poll_mode = LPFC_QUEUE_WORK;
1336 		else
1337 			cq->poll_mode = LPFC_IRQ_POLL;
1338 
1339 		idle_stat->prev_idle = wall_idle;
1340 		idle_stat->prev_wall = wall;
1341 	}
1342 
1343 requeue:
1344 	schedule_delayed_work(&phba->idle_stat_delay_work,
1345 			      msecs_to_jiffies(LPFC_IDLE_STAT_DELAY));
1346 }
1347 
1348 static void
1349 lpfc_hb_eq_delay_work(struct work_struct *work)
1350 {
1351 	struct lpfc_hba *phba = container_of(to_delayed_work(work),
1352 					     struct lpfc_hba, eq_delay_work);
1353 	struct lpfc_eq_intr_info *eqi, *eqi_new;
1354 	struct lpfc_queue *eq, *eq_next;
1355 	unsigned char *ena_delay = NULL;
1356 	uint32_t usdelay;
1357 	int i;
1358 
1359 	if (!phba->cfg_auto_imax || phba->pport->load_flag & FC_UNLOADING)
1360 		return;
1361 
1362 	if (phba->link_state == LPFC_HBA_ERROR ||
1363 	    phba->pport->fc_flag & FC_OFFLINE_MODE)
1364 		goto requeue;
1365 
1366 	ena_delay = kcalloc(phba->sli4_hba.num_possible_cpu, sizeof(*ena_delay),
1367 			    GFP_KERNEL);
1368 	if (!ena_delay)
1369 		goto requeue;
1370 
1371 	for (i = 0; i < phba->cfg_irq_chann; i++) {
1372 		/* Get the EQ corresponding to the IRQ vector */
1373 		eq = phba->sli4_hba.hba_eq_hdl[i].eq;
1374 		if (!eq)
1375 			continue;
1376 		if (eq->q_mode || eq->q_flag & HBA_EQ_DELAY_CHK) {
1377 			eq->q_flag &= ~HBA_EQ_DELAY_CHK;
1378 			ena_delay[eq->last_cpu] = 1;
1379 		}
1380 	}
1381 
1382 	for_each_present_cpu(i) {
1383 		eqi = per_cpu_ptr(phba->sli4_hba.eq_info, i);
1384 		if (ena_delay[i]) {
1385 			usdelay = (eqi->icnt >> 10) * LPFC_EQ_DELAY_STEP;
1386 			if (usdelay > LPFC_MAX_AUTO_EQ_DELAY)
1387 				usdelay = LPFC_MAX_AUTO_EQ_DELAY;
1388 		} else {
1389 			usdelay = 0;
1390 		}
1391 
1392 		eqi->icnt = 0;
1393 
1394 		list_for_each_entry_safe(eq, eq_next, &eqi->list, cpu_list) {
1395 			if (unlikely(eq->last_cpu != i)) {
1396 				eqi_new = per_cpu_ptr(phba->sli4_hba.eq_info,
1397 						      eq->last_cpu);
1398 				list_move_tail(&eq->cpu_list, &eqi_new->list);
1399 				continue;
1400 			}
1401 			if (usdelay != eq->q_mode)
1402 				lpfc_modify_hba_eq_delay(phba, eq->hdwq, 1,
1403 							 usdelay);
1404 		}
1405 	}
1406 
1407 	kfree(ena_delay);
1408 
1409 requeue:
1410 	queue_delayed_work(phba->wq, &phba->eq_delay_work,
1411 			   msecs_to_jiffies(LPFC_EQ_DELAY_MSECS));
1412 }
1413 
1414 /**
1415  * lpfc_hb_mxp_handler - Multi-XRI pools handler to adjust XRI distribution
1416  * @phba: pointer to lpfc hba data structure.
1417  *
1418  * For each heartbeat, this routine does some heuristic methods to adjust
1419  * XRI distribution. The goal is to fully utilize free XRIs.
1420  **/
1421 static void lpfc_hb_mxp_handler(struct lpfc_hba *phba)
1422 {
1423 	u32 i;
1424 	u32 hwq_count;
1425 
1426 	hwq_count = phba->cfg_hdw_queue;
1427 	for (i = 0; i < hwq_count; i++) {
1428 		/* Adjust XRIs in private pool */
1429 		lpfc_adjust_pvt_pool_count(phba, i);
1430 
1431 		/* Adjust high watermark */
1432 		lpfc_adjust_high_watermark(phba, i);
1433 
1434 #ifdef LPFC_MXP_STAT
1435 		/* Snapshot pbl, pvt and busy count */
1436 		lpfc_snapshot_mxp(phba, i);
1437 #endif
1438 	}
1439 }
1440 
1441 /**
1442  * lpfc_issue_hb_mbox - Issues heart-beat mailbox command
1443  * @phba: pointer to lpfc hba data structure.
1444  *
1445  * If a HB mbox is not already in progrees, this routine will allocate
1446  * a LPFC_MBOXQ_t, populate it with a MBX_HEARTBEAT (0x31) command,
1447  * and issue it. The HBA_HBEAT_INP flag means the command is in progress.
1448  **/
1449 int
1450 lpfc_issue_hb_mbox(struct lpfc_hba *phba)
1451 {
1452 	LPFC_MBOXQ_t *pmboxq;
1453 	int retval;
1454 
1455 	/* Is a Heartbeat mbox already in progress */
1456 	if (phba->hba_flag & HBA_HBEAT_INP)
1457 		return 0;
1458 
1459 	pmboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
1460 	if (!pmboxq)
1461 		return -ENOMEM;
1462 
1463 	lpfc_heart_beat(phba, pmboxq);
1464 	pmboxq->mbox_cmpl = lpfc_hb_mbox_cmpl;
1465 	pmboxq->vport = phba->pport;
1466 	retval = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
1467 
1468 	if (retval != MBX_BUSY && retval != MBX_SUCCESS) {
1469 		mempool_free(pmboxq, phba->mbox_mem_pool);
1470 		return -ENXIO;
1471 	}
1472 	phba->hba_flag |= HBA_HBEAT_INP;
1473 
1474 	return 0;
1475 }
1476 
1477 /**
1478  * lpfc_issue_hb_tmo - Signals heartbeat timer to issue mbox command
1479  * @phba: pointer to lpfc hba data structure.
1480  *
1481  * The heartbeat timer (every 5 sec) will fire. If the HBA_HBEAT_TMO
1482  * flag is set, it will force a MBX_HEARTBEAT mbox command, regardless
1483  * of the value of lpfc_enable_hba_heartbeat.
1484  * If lpfc_enable_hba_heartbeat is set, the timeout routine will always
1485  * try to issue a MBX_HEARTBEAT mbox command.
1486  **/
1487 void
1488 lpfc_issue_hb_tmo(struct lpfc_hba *phba)
1489 {
1490 	if (phba->cfg_enable_hba_heartbeat)
1491 		return;
1492 	phba->hba_flag |= HBA_HBEAT_TMO;
1493 }
1494 
1495 /**
1496  * lpfc_hb_timeout_handler - The HBA-timer timeout handler
1497  * @phba: pointer to lpfc hba data structure.
1498  *
1499  * This is the actual HBA-timer timeout handler to be invoked by the worker
1500  * thread whenever the HBA timer fired and HBA-timeout event posted. This
1501  * handler performs any periodic operations needed for the device. If such
1502  * periodic event has already been attended to either in the interrupt handler
1503  * or by processing slow-ring or fast-ring events within the HBA-timer
1504  * timeout window (LPFC_HB_MBOX_INTERVAL), this handler just simply resets
1505  * the timer for the next timeout period. If lpfc heart-beat mailbox command
1506  * is configured and there is no heart-beat mailbox command outstanding, a
1507  * heart-beat mailbox is issued and timer set properly. Otherwise, if there
1508  * has been a heart-beat mailbox command outstanding, the HBA shall be put
1509  * to offline.
1510  **/
1511 void
1512 lpfc_hb_timeout_handler(struct lpfc_hba *phba)
1513 {
1514 	struct lpfc_vport **vports;
1515 	struct lpfc_dmabuf *buf_ptr;
1516 	int retval = 0;
1517 	int i, tmo;
1518 	struct lpfc_sli *psli = &phba->sli;
1519 	LIST_HEAD(completions);
1520 
1521 	if (phba->cfg_xri_rebalancing) {
1522 		/* Multi-XRI pools handler */
1523 		lpfc_hb_mxp_handler(phba);
1524 	}
1525 
1526 	vports = lpfc_create_vport_work_array(phba);
1527 	if (vports != NULL)
1528 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
1529 			lpfc_rcv_seq_check_edtov(vports[i]);
1530 			lpfc_fdmi_change_check(vports[i]);
1531 		}
1532 	lpfc_destroy_vport_work_array(phba, vports);
1533 
1534 	if ((phba->link_state == LPFC_HBA_ERROR) ||
1535 		(phba->pport->load_flag & FC_UNLOADING) ||
1536 		(phba->pport->fc_flag & FC_OFFLINE_MODE))
1537 		return;
1538 
1539 	if (phba->elsbuf_cnt &&
1540 		(phba->elsbuf_cnt == phba->elsbuf_prev_cnt)) {
1541 		spin_lock_irq(&phba->hbalock);
1542 		list_splice_init(&phba->elsbuf, &completions);
1543 		phba->elsbuf_cnt = 0;
1544 		phba->elsbuf_prev_cnt = 0;
1545 		spin_unlock_irq(&phba->hbalock);
1546 
1547 		while (!list_empty(&completions)) {
1548 			list_remove_head(&completions, buf_ptr,
1549 				struct lpfc_dmabuf, list);
1550 			lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
1551 			kfree(buf_ptr);
1552 		}
1553 	}
1554 	phba->elsbuf_prev_cnt = phba->elsbuf_cnt;
1555 
1556 	/* If there is no heart beat outstanding, issue a heartbeat command */
1557 	if (phba->cfg_enable_hba_heartbeat) {
1558 		/* If IOs are completing, no need to issue a MBX_HEARTBEAT */
1559 		spin_lock_irq(&phba->pport->work_port_lock);
1560 		if (time_after(phba->last_completion_time +
1561 				msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL),
1562 				jiffies)) {
1563 			spin_unlock_irq(&phba->pport->work_port_lock);
1564 			if (phba->hba_flag & HBA_HBEAT_INP)
1565 				tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1566 			else
1567 				tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1568 			goto out;
1569 		}
1570 		spin_unlock_irq(&phba->pport->work_port_lock);
1571 
1572 		/* Check if a MBX_HEARTBEAT is already in progress */
1573 		if (phba->hba_flag & HBA_HBEAT_INP) {
1574 			/*
1575 			 * If heart beat timeout called with HBA_HBEAT_INP set
1576 			 * we need to give the hb mailbox cmd a chance to
1577 			 * complete or TMO.
1578 			 */
1579 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
1580 				"0459 Adapter heartbeat still outstanding: "
1581 				"last compl time was %d ms.\n",
1582 				jiffies_to_msecs(jiffies
1583 					 - phba->last_completion_time));
1584 			tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1585 		} else {
1586 			if ((!(psli->sli_flag & LPFC_SLI_MBOX_ACTIVE)) &&
1587 				(list_empty(&psli->mboxq))) {
1588 
1589 				retval = lpfc_issue_hb_mbox(phba);
1590 				if (retval) {
1591 					tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1592 					goto out;
1593 				}
1594 				phba->skipped_hb = 0;
1595 			} else if (time_before_eq(phba->last_completion_time,
1596 					phba->skipped_hb)) {
1597 				lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
1598 					"2857 Last completion time not "
1599 					" updated in %d ms\n",
1600 					jiffies_to_msecs(jiffies
1601 						 - phba->last_completion_time));
1602 			} else
1603 				phba->skipped_hb = jiffies;
1604 
1605 			tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1606 			goto out;
1607 		}
1608 	} else {
1609 		/* Check to see if we want to force a MBX_HEARTBEAT */
1610 		if (phba->hba_flag & HBA_HBEAT_TMO) {
1611 			retval = lpfc_issue_hb_mbox(phba);
1612 			if (retval)
1613 				tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1614 			else
1615 				tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1616 			goto out;
1617 		}
1618 		tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1619 	}
1620 out:
1621 	mod_timer(&phba->hb_tmofunc, jiffies + msecs_to_jiffies(tmo));
1622 }
1623 
1624 /**
1625  * lpfc_offline_eratt - Bring lpfc offline on hardware error attention
1626  * @phba: pointer to lpfc hba data structure.
1627  *
1628  * This routine is called to bring the HBA offline when HBA hardware error
1629  * other than Port Error 6 has been detected.
1630  **/
1631 static void
1632 lpfc_offline_eratt(struct lpfc_hba *phba)
1633 {
1634 	struct lpfc_sli   *psli = &phba->sli;
1635 
1636 	spin_lock_irq(&phba->hbalock);
1637 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1638 	spin_unlock_irq(&phba->hbalock);
1639 	lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
1640 
1641 	lpfc_offline(phba);
1642 	lpfc_reset_barrier(phba);
1643 	spin_lock_irq(&phba->hbalock);
1644 	lpfc_sli_brdreset(phba);
1645 	spin_unlock_irq(&phba->hbalock);
1646 	lpfc_hba_down_post(phba);
1647 	lpfc_sli_brdready(phba, HS_MBRDY);
1648 	lpfc_unblock_mgmt_io(phba);
1649 	phba->link_state = LPFC_HBA_ERROR;
1650 	return;
1651 }
1652 
1653 /**
1654  * lpfc_sli4_offline_eratt - Bring lpfc offline on SLI4 hardware error attention
1655  * @phba: pointer to lpfc hba data structure.
1656  *
1657  * This routine is called to bring a SLI4 HBA offline when HBA hardware error
1658  * other than Port Error 6 has been detected.
1659  **/
1660 void
1661 lpfc_sli4_offline_eratt(struct lpfc_hba *phba)
1662 {
1663 	spin_lock_irq(&phba->hbalock);
1664 	if (phba->link_state == LPFC_HBA_ERROR &&
1665 		test_bit(HBA_PCI_ERR, &phba->bit_flags)) {
1666 		spin_unlock_irq(&phba->hbalock);
1667 		return;
1668 	}
1669 	phba->link_state = LPFC_HBA_ERROR;
1670 	spin_unlock_irq(&phba->hbalock);
1671 
1672 	lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
1673 	lpfc_sli_flush_io_rings(phba);
1674 	lpfc_offline(phba);
1675 	lpfc_hba_down_post(phba);
1676 	lpfc_unblock_mgmt_io(phba);
1677 }
1678 
1679 /**
1680  * lpfc_handle_deferred_eratt - The HBA hardware deferred error handler
1681  * @phba: pointer to lpfc hba data structure.
1682  *
1683  * This routine is invoked to handle the deferred HBA hardware error
1684  * conditions. This type of error is indicated by HBA by setting ER1
1685  * and another ER bit in the host status register. The driver will
1686  * wait until the ER1 bit clears before handling the error condition.
1687  **/
1688 static void
1689 lpfc_handle_deferred_eratt(struct lpfc_hba *phba)
1690 {
1691 	uint32_t old_host_status = phba->work_hs;
1692 	struct lpfc_sli *psli = &phba->sli;
1693 
1694 	/* If the pci channel is offline, ignore possible errors,
1695 	 * since we cannot communicate with the pci card anyway.
1696 	 */
1697 	if (pci_channel_offline(phba->pcidev)) {
1698 		spin_lock_irq(&phba->hbalock);
1699 		phba->hba_flag &= ~DEFER_ERATT;
1700 		spin_unlock_irq(&phba->hbalock);
1701 		return;
1702 	}
1703 
1704 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1705 			"0479 Deferred Adapter Hardware Error "
1706 			"Data: x%x x%x x%x\n",
1707 			phba->work_hs, phba->work_status[0],
1708 			phba->work_status[1]);
1709 
1710 	spin_lock_irq(&phba->hbalock);
1711 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1712 	spin_unlock_irq(&phba->hbalock);
1713 
1714 
1715 	/*
1716 	 * Firmware stops when it triggred erratt. That could cause the I/Os
1717 	 * dropped by the firmware. Error iocb (I/O) on txcmplq and let the
1718 	 * SCSI layer retry it after re-establishing link.
1719 	 */
1720 	lpfc_sli_abort_fcp_rings(phba);
1721 
1722 	/*
1723 	 * There was a firmware error. Take the hba offline and then
1724 	 * attempt to restart it.
1725 	 */
1726 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
1727 	lpfc_offline(phba);
1728 
1729 	/* Wait for the ER1 bit to clear.*/
1730 	while (phba->work_hs & HS_FFER1) {
1731 		msleep(100);
1732 		if (lpfc_readl(phba->HSregaddr, &phba->work_hs)) {
1733 			phba->work_hs = UNPLUG_ERR ;
1734 			break;
1735 		}
1736 		/* If driver is unloading let the worker thread continue */
1737 		if (phba->pport->load_flag & FC_UNLOADING) {
1738 			phba->work_hs = 0;
1739 			break;
1740 		}
1741 	}
1742 
1743 	/*
1744 	 * This is to ptrotect against a race condition in which
1745 	 * first write to the host attention register clear the
1746 	 * host status register.
1747 	 */
1748 	if ((!phba->work_hs) && (!(phba->pport->load_flag & FC_UNLOADING)))
1749 		phba->work_hs = old_host_status & ~HS_FFER1;
1750 
1751 	spin_lock_irq(&phba->hbalock);
1752 	phba->hba_flag &= ~DEFER_ERATT;
1753 	spin_unlock_irq(&phba->hbalock);
1754 	phba->work_status[0] = readl(phba->MBslimaddr + 0xa8);
1755 	phba->work_status[1] = readl(phba->MBslimaddr + 0xac);
1756 }
1757 
1758 static void
1759 lpfc_board_errevt_to_mgmt(struct lpfc_hba *phba)
1760 {
1761 	struct lpfc_board_event_header board_event;
1762 	struct Scsi_Host *shost;
1763 
1764 	board_event.event_type = FC_REG_BOARD_EVENT;
1765 	board_event.subcategory = LPFC_EVENT_PORTINTERR;
1766 	shost = lpfc_shost_from_vport(phba->pport);
1767 	fc_host_post_vendor_event(shost, fc_get_event_number(),
1768 				  sizeof(board_event),
1769 				  (char *) &board_event,
1770 				  LPFC_NL_VENDOR_ID);
1771 }
1772 
1773 /**
1774  * lpfc_handle_eratt_s3 - The SLI3 HBA hardware error handler
1775  * @phba: pointer to lpfc hba data structure.
1776  *
1777  * This routine is invoked to handle the following HBA hardware error
1778  * conditions:
1779  * 1 - HBA error attention interrupt
1780  * 2 - DMA ring index out of range
1781  * 3 - Mailbox command came back as unknown
1782  **/
1783 static void
1784 lpfc_handle_eratt_s3(struct lpfc_hba *phba)
1785 {
1786 	struct lpfc_vport *vport = phba->pport;
1787 	struct lpfc_sli   *psli = &phba->sli;
1788 	uint32_t event_data;
1789 	unsigned long temperature;
1790 	struct temp_event temp_event_data;
1791 	struct Scsi_Host  *shost;
1792 
1793 	/* If the pci channel is offline, ignore possible errors,
1794 	 * since we cannot communicate with the pci card anyway.
1795 	 */
1796 	if (pci_channel_offline(phba->pcidev)) {
1797 		spin_lock_irq(&phba->hbalock);
1798 		phba->hba_flag &= ~DEFER_ERATT;
1799 		spin_unlock_irq(&phba->hbalock);
1800 		return;
1801 	}
1802 
1803 	/* If resets are disabled then leave the HBA alone and return */
1804 	if (!phba->cfg_enable_hba_reset)
1805 		return;
1806 
1807 	/* Send an internal error event to mgmt application */
1808 	lpfc_board_errevt_to_mgmt(phba);
1809 
1810 	if (phba->hba_flag & DEFER_ERATT)
1811 		lpfc_handle_deferred_eratt(phba);
1812 
1813 	if ((phba->work_hs & HS_FFER6) || (phba->work_hs & HS_FFER8)) {
1814 		if (phba->work_hs & HS_FFER6)
1815 			/* Re-establishing Link */
1816 			lpfc_printf_log(phba, KERN_INFO, LOG_LINK_EVENT,
1817 					"1301 Re-establishing Link "
1818 					"Data: x%x x%x x%x\n",
1819 					phba->work_hs, phba->work_status[0],
1820 					phba->work_status[1]);
1821 		if (phba->work_hs & HS_FFER8)
1822 			/* Device Zeroization */
1823 			lpfc_printf_log(phba, KERN_INFO, LOG_LINK_EVENT,
1824 					"2861 Host Authentication device "
1825 					"zeroization Data:x%x x%x x%x\n",
1826 					phba->work_hs, phba->work_status[0],
1827 					phba->work_status[1]);
1828 
1829 		spin_lock_irq(&phba->hbalock);
1830 		psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1831 		spin_unlock_irq(&phba->hbalock);
1832 
1833 		/*
1834 		* Firmware stops when it triggled erratt with HS_FFER6.
1835 		* That could cause the I/Os dropped by the firmware.
1836 		* Error iocb (I/O) on txcmplq and let the SCSI layer
1837 		* retry it after re-establishing link.
1838 		*/
1839 		lpfc_sli_abort_fcp_rings(phba);
1840 
1841 		/*
1842 		 * There was a firmware error.  Take the hba offline and then
1843 		 * attempt to restart it.
1844 		 */
1845 		lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
1846 		lpfc_offline(phba);
1847 		lpfc_sli_brdrestart(phba);
1848 		if (lpfc_online(phba) == 0) {	/* Initialize the HBA */
1849 			lpfc_unblock_mgmt_io(phba);
1850 			return;
1851 		}
1852 		lpfc_unblock_mgmt_io(phba);
1853 	} else if (phba->work_hs & HS_CRIT_TEMP) {
1854 		temperature = readl(phba->MBslimaddr + TEMPERATURE_OFFSET);
1855 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
1856 		temp_event_data.event_code = LPFC_CRIT_TEMP;
1857 		temp_event_data.data = (uint32_t)temperature;
1858 
1859 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1860 				"0406 Adapter maximum temperature exceeded "
1861 				"(%ld), taking this port offline "
1862 				"Data: x%x x%x x%x\n",
1863 				temperature, phba->work_hs,
1864 				phba->work_status[0], phba->work_status[1]);
1865 
1866 		shost = lpfc_shost_from_vport(phba->pport);
1867 		fc_host_post_vendor_event(shost, fc_get_event_number(),
1868 					  sizeof(temp_event_data),
1869 					  (char *) &temp_event_data,
1870 					  SCSI_NL_VID_TYPE_PCI
1871 					  | PCI_VENDOR_ID_EMULEX);
1872 
1873 		spin_lock_irq(&phba->hbalock);
1874 		phba->over_temp_state = HBA_OVER_TEMP;
1875 		spin_unlock_irq(&phba->hbalock);
1876 		lpfc_offline_eratt(phba);
1877 
1878 	} else {
1879 		/* The if clause above forces this code path when the status
1880 		 * failure is a value other than FFER6. Do not call the offline
1881 		 * twice. This is the adapter hardware error path.
1882 		 */
1883 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1884 				"0457 Adapter Hardware Error "
1885 				"Data: x%x x%x x%x\n",
1886 				phba->work_hs,
1887 				phba->work_status[0], phba->work_status[1]);
1888 
1889 		event_data = FC_REG_DUMP_EVENT;
1890 		shost = lpfc_shost_from_vport(vport);
1891 		fc_host_post_vendor_event(shost, fc_get_event_number(),
1892 				sizeof(event_data), (char *) &event_data,
1893 				SCSI_NL_VID_TYPE_PCI | PCI_VENDOR_ID_EMULEX);
1894 
1895 		lpfc_offline_eratt(phba);
1896 	}
1897 	return;
1898 }
1899 
1900 /**
1901  * lpfc_sli4_port_sta_fn_reset - The SLI4 function reset due to port status reg
1902  * @phba: pointer to lpfc hba data structure.
1903  * @mbx_action: flag for mailbox shutdown action.
1904  * @en_rn_msg: send reset/port recovery message.
1905  * This routine is invoked to perform an SLI4 port PCI function reset in
1906  * response to port status register polling attention. It waits for port
1907  * status register (ERR, RDY, RN) bits before proceeding with function reset.
1908  * During this process, interrupt vectors are freed and later requested
1909  * for handling possible port resource change.
1910  **/
1911 static int
1912 lpfc_sli4_port_sta_fn_reset(struct lpfc_hba *phba, int mbx_action,
1913 			    bool en_rn_msg)
1914 {
1915 	int rc;
1916 	uint32_t intr_mode;
1917 	LPFC_MBOXQ_t *mboxq;
1918 
1919 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) >=
1920 	    LPFC_SLI_INTF_IF_TYPE_2) {
1921 		/*
1922 		 * On error status condition, driver need to wait for port
1923 		 * ready before performing reset.
1924 		 */
1925 		rc = lpfc_sli4_pdev_status_reg_wait(phba);
1926 		if (rc)
1927 			return rc;
1928 	}
1929 
1930 	/* need reset: attempt for port recovery */
1931 	if (en_rn_msg)
1932 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
1933 				"2887 Reset Needed: Attempting Port "
1934 				"Recovery...\n");
1935 
1936 	/* If we are no wait, the HBA has been reset and is not
1937 	 * functional, thus we should clear
1938 	 * (LPFC_SLI_ACTIVE | LPFC_SLI_MBOX_ACTIVE) flags.
1939 	 */
1940 	if (mbx_action == LPFC_MBX_NO_WAIT) {
1941 		spin_lock_irq(&phba->hbalock);
1942 		phba->sli.sli_flag &= ~LPFC_SLI_ACTIVE;
1943 		if (phba->sli.mbox_active) {
1944 			mboxq = phba->sli.mbox_active;
1945 			mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
1946 			__lpfc_mbox_cmpl_put(phba, mboxq);
1947 			phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
1948 			phba->sli.mbox_active = NULL;
1949 		}
1950 		spin_unlock_irq(&phba->hbalock);
1951 	}
1952 
1953 	lpfc_offline_prep(phba, mbx_action);
1954 	lpfc_sli_flush_io_rings(phba);
1955 	lpfc_offline(phba);
1956 	/* release interrupt for possible resource change */
1957 	lpfc_sli4_disable_intr(phba);
1958 	rc = lpfc_sli_brdrestart(phba);
1959 	if (rc) {
1960 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1961 				"6309 Failed to restart board\n");
1962 		return rc;
1963 	}
1964 	/* request and enable interrupt */
1965 	intr_mode = lpfc_sli4_enable_intr(phba, phba->intr_mode);
1966 	if (intr_mode == LPFC_INTR_ERROR) {
1967 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1968 				"3175 Failed to enable interrupt\n");
1969 		return -EIO;
1970 	}
1971 	phba->intr_mode = intr_mode;
1972 	rc = lpfc_online(phba);
1973 	if (rc == 0)
1974 		lpfc_unblock_mgmt_io(phba);
1975 
1976 	return rc;
1977 }
1978 
1979 /**
1980  * lpfc_handle_eratt_s4 - The SLI4 HBA hardware error handler
1981  * @phba: pointer to lpfc hba data structure.
1982  *
1983  * This routine is invoked to handle the SLI4 HBA hardware error attention
1984  * conditions.
1985  **/
1986 static void
1987 lpfc_handle_eratt_s4(struct lpfc_hba *phba)
1988 {
1989 	struct lpfc_vport *vport = phba->pport;
1990 	uint32_t event_data;
1991 	struct Scsi_Host *shost;
1992 	uint32_t if_type;
1993 	struct lpfc_register portstat_reg = {0};
1994 	uint32_t reg_err1, reg_err2;
1995 	uint32_t uerrlo_reg, uemasklo_reg;
1996 	uint32_t smphr_port_status = 0, pci_rd_rc1, pci_rd_rc2;
1997 	bool en_rn_msg = true;
1998 	struct temp_event temp_event_data;
1999 	struct lpfc_register portsmphr_reg;
2000 	int rc, i;
2001 
2002 	/* If the pci channel is offline, ignore possible errors, since
2003 	 * we cannot communicate with the pci card anyway.
2004 	 */
2005 	if (pci_channel_offline(phba->pcidev)) {
2006 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2007 				"3166 pci channel is offline\n");
2008 		lpfc_sli_flush_io_rings(phba);
2009 		return;
2010 	}
2011 
2012 	memset(&portsmphr_reg, 0, sizeof(portsmphr_reg));
2013 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
2014 	switch (if_type) {
2015 	case LPFC_SLI_INTF_IF_TYPE_0:
2016 		pci_rd_rc1 = lpfc_readl(
2017 				phba->sli4_hba.u.if_type0.UERRLOregaddr,
2018 				&uerrlo_reg);
2019 		pci_rd_rc2 = lpfc_readl(
2020 				phba->sli4_hba.u.if_type0.UEMASKLOregaddr,
2021 				&uemasklo_reg);
2022 		/* consider PCI bus read error as pci_channel_offline */
2023 		if (pci_rd_rc1 == -EIO && pci_rd_rc2 == -EIO)
2024 			return;
2025 		if (!(phba->hba_flag & HBA_RECOVERABLE_UE)) {
2026 			lpfc_sli4_offline_eratt(phba);
2027 			return;
2028 		}
2029 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2030 				"7623 Checking UE recoverable");
2031 
2032 		for (i = 0; i < phba->sli4_hba.ue_to_sr / 1000; i++) {
2033 			if (lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
2034 				       &portsmphr_reg.word0))
2035 				continue;
2036 
2037 			smphr_port_status = bf_get(lpfc_port_smphr_port_status,
2038 						   &portsmphr_reg);
2039 			if ((smphr_port_status & LPFC_PORT_SEM_MASK) ==
2040 			    LPFC_PORT_SEM_UE_RECOVERABLE)
2041 				break;
2042 			/*Sleep for 1Sec, before checking SEMAPHORE */
2043 			msleep(1000);
2044 		}
2045 
2046 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2047 				"4827 smphr_port_status x%x : Waited %dSec",
2048 				smphr_port_status, i);
2049 
2050 		/* Recoverable UE, reset the HBA device */
2051 		if ((smphr_port_status & LPFC_PORT_SEM_MASK) ==
2052 		    LPFC_PORT_SEM_UE_RECOVERABLE) {
2053 			for (i = 0; i < 20; i++) {
2054 				msleep(1000);
2055 				if (!lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
2056 				    &portsmphr_reg.word0) &&
2057 				    (LPFC_POST_STAGE_PORT_READY ==
2058 				     bf_get(lpfc_port_smphr_port_status,
2059 				     &portsmphr_reg))) {
2060 					rc = lpfc_sli4_port_sta_fn_reset(phba,
2061 						LPFC_MBX_NO_WAIT, en_rn_msg);
2062 					if (rc == 0)
2063 						return;
2064 					lpfc_printf_log(phba, KERN_ERR,
2065 						LOG_TRACE_EVENT,
2066 						"4215 Failed to recover UE");
2067 					break;
2068 				}
2069 			}
2070 		}
2071 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2072 				"7624 Firmware not ready: Failing UE recovery,"
2073 				" waited %dSec", i);
2074 		phba->link_state = LPFC_HBA_ERROR;
2075 		break;
2076 
2077 	case LPFC_SLI_INTF_IF_TYPE_2:
2078 	case LPFC_SLI_INTF_IF_TYPE_6:
2079 		pci_rd_rc1 = lpfc_readl(
2080 				phba->sli4_hba.u.if_type2.STATUSregaddr,
2081 				&portstat_reg.word0);
2082 		/* consider PCI bus read error as pci_channel_offline */
2083 		if (pci_rd_rc1 == -EIO) {
2084 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2085 				"3151 PCI bus read access failure: x%x\n",
2086 				readl(phba->sli4_hba.u.if_type2.STATUSregaddr));
2087 			lpfc_sli4_offline_eratt(phba);
2088 			return;
2089 		}
2090 		reg_err1 = readl(phba->sli4_hba.u.if_type2.ERR1regaddr);
2091 		reg_err2 = readl(phba->sli4_hba.u.if_type2.ERR2regaddr);
2092 		if (bf_get(lpfc_sliport_status_oti, &portstat_reg)) {
2093 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2094 					"2889 Port Overtemperature event, "
2095 					"taking port offline Data: x%x x%x\n",
2096 					reg_err1, reg_err2);
2097 
2098 			phba->sfp_alarm |= LPFC_TRANSGRESSION_HIGH_TEMPERATURE;
2099 			temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
2100 			temp_event_data.event_code = LPFC_CRIT_TEMP;
2101 			temp_event_data.data = 0xFFFFFFFF;
2102 
2103 			shost = lpfc_shost_from_vport(phba->pport);
2104 			fc_host_post_vendor_event(shost, fc_get_event_number(),
2105 						  sizeof(temp_event_data),
2106 						  (char *)&temp_event_data,
2107 						  SCSI_NL_VID_TYPE_PCI
2108 						  | PCI_VENDOR_ID_EMULEX);
2109 
2110 			spin_lock_irq(&phba->hbalock);
2111 			phba->over_temp_state = HBA_OVER_TEMP;
2112 			spin_unlock_irq(&phba->hbalock);
2113 			lpfc_sli4_offline_eratt(phba);
2114 			return;
2115 		}
2116 		if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2117 		    reg_err2 == SLIPORT_ERR2_REG_FW_RESTART) {
2118 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2119 					"3143 Port Down: Firmware Update "
2120 					"Detected\n");
2121 			en_rn_msg = false;
2122 		} else if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2123 			 reg_err2 == SLIPORT_ERR2_REG_FORCED_DUMP)
2124 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2125 					"3144 Port Down: Debug Dump\n");
2126 		else if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2127 			 reg_err2 == SLIPORT_ERR2_REG_FUNC_PROVISON)
2128 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2129 					"3145 Port Down: Provisioning\n");
2130 
2131 		/* If resets are disabled then leave the HBA alone and return */
2132 		if (!phba->cfg_enable_hba_reset)
2133 			return;
2134 
2135 		/* Check port status register for function reset */
2136 		rc = lpfc_sli4_port_sta_fn_reset(phba, LPFC_MBX_NO_WAIT,
2137 				en_rn_msg);
2138 		if (rc == 0) {
2139 			/* don't report event on forced debug dump */
2140 			if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2141 			    reg_err2 == SLIPORT_ERR2_REG_FORCED_DUMP)
2142 				return;
2143 			else
2144 				break;
2145 		}
2146 		/* fall through for not able to recover */
2147 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2148 				"3152 Unrecoverable error\n");
2149 		phba->link_state = LPFC_HBA_ERROR;
2150 		break;
2151 	case LPFC_SLI_INTF_IF_TYPE_1:
2152 	default:
2153 		break;
2154 	}
2155 	lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
2156 			"3123 Report dump event to upper layer\n");
2157 	/* Send an internal error event to mgmt application */
2158 	lpfc_board_errevt_to_mgmt(phba);
2159 
2160 	event_data = FC_REG_DUMP_EVENT;
2161 	shost = lpfc_shost_from_vport(vport);
2162 	fc_host_post_vendor_event(shost, fc_get_event_number(),
2163 				  sizeof(event_data), (char *) &event_data,
2164 				  SCSI_NL_VID_TYPE_PCI | PCI_VENDOR_ID_EMULEX);
2165 }
2166 
2167 /**
2168  * lpfc_handle_eratt - Wrapper func for handling hba error attention
2169  * @phba: pointer to lpfc HBA data structure.
2170  *
2171  * This routine wraps the actual SLI3 or SLI4 hba error attention handling
2172  * routine from the API jump table function pointer from the lpfc_hba struct.
2173  *
2174  * Return codes
2175  *   0 - success.
2176  *   Any other value - error.
2177  **/
2178 void
2179 lpfc_handle_eratt(struct lpfc_hba *phba)
2180 {
2181 	(*phba->lpfc_handle_eratt)(phba);
2182 }
2183 
2184 /**
2185  * lpfc_handle_latt - The HBA link event handler
2186  * @phba: pointer to lpfc hba data structure.
2187  *
2188  * This routine is invoked from the worker thread to handle a HBA host
2189  * attention link event. SLI3 only.
2190  **/
2191 void
2192 lpfc_handle_latt(struct lpfc_hba *phba)
2193 {
2194 	struct lpfc_vport *vport = phba->pport;
2195 	struct lpfc_sli   *psli = &phba->sli;
2196 	LPFC_MBOXQ_t *pmb;
2197 	volatile uint32_t control;
2198 	int rc = 0;
2199 
2200 	pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
2201 	if (!pmb) {
2202 		rc = 1;
2203 		goto lpfc_handle_latt_err_exit;
2204 	}
2205 
2206 	rc = lpfc_mbox_rsrc_prep(phba, pmb);
2207 	if (rc) {
2208 		rc = 2;
2209 		mempool_free(pmb, phba->mbox_mem_pool);
2210 		goto lpfc_handle_latt_err_exit;
2211 	}
2212 
2213 	/* Cleanup any outstanding ELS commands */
2214 	lpfc_els_flush_all_cmd(phba);
2215 	psli->slistat.link_event++;
2216 	lpfc_read_topology(phba, pmb, (struct lpfc_dmabuf *)pmb->ctx_buf);
2217 	pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
2218 	pmb->vport = vport;
2219 	/* Block ELS IOCBs until we have processed this mbox command */
2220 	phba->sli.sli3_ring[LPFC_ELS_RING].flag |= LPFC_STOP_IOCB_EVENT;
2221 	rc = lpfc_sli_issue_mbox (phba, pmb, MBX_NOWAIT);
2222 	if (rc == MBX_NOT_FINISHED) {
2223 		rc = 4;
2224 		goto lpfc_handle_latt_free_mbuf;
2225 	}
2226 
2227 	/* Clear Link Attention in HA REG */
2228 	spin_lock_irq(&phba->hbalock);
2229 	writel(HA_LATT, phba->HAregaddr);
2230 	readl(phba->HAregaddr); /* flush */
2231 	spin_unlock_irq(&phba->hbalock);
2232 
2233 	return;
2234 
2235 lpfc_handle_latt_free_mbuf:
2236 	phba->sli.sli3_ring[LPFC_ELS_RING].flag &= ~LPFC_STOP_IOCB_EVENT;
2237 	lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
2238 lpfc_handle_latt_err_exit:
2239 	/* Enable Link attention interrupts */
2240 	spin_lock_irq(&phba->hbalock);
2241 	psli->sli_flag |= LPFC_PROCESS_LA;
2242 	control = readl(phba->HCregaddr);
2243 	control |= HC_LAINT_ENA;
2244 	writel(control, phba->HCregaddr);
2245 	readl(phba->HCregaddr); /* flush */
2246 
2247 	/* Clear Link Attention in HA REG */
2248 	writel(HA_LATT, phba->HAregaddr);
2249 	readl(phba->HAregaddr); /* flush */
2250 	spin_unlock_irq(&phba->hbalock);
2251 	lpfc_linkdown(phba);
2252 	phba->link_state = LPFC_HBA_ERROR;
2253 
2254 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2255 			"0300 LATT: Cannot issue READ_LA: Data:%d\n", rc);
2256 
2257 	return;
2258 }
2259 
2260 static void
2261 lpfc_fill_vpd(struct lpfc_hba *phba, uint8_t *vpd, int length, int *pindex)
2262 {
2263 	int i, j;
2264 
2265 	while (length > 0) {
2266 		/* Look for Serial Number */
2267 		if ((vpd[*pindex] == 'S') && (vpd[*pindex + 1] == 'N')) {
2268 			*pindex += 2;
2269 			i = vpd[*pindex];
2270 			*pindex += 1;
2271 			j = 0;
2272 			length -= (3+i);
2273 			while (i--) {
2274 				phba->SerialNumber[j++] = vpd[(*pindex)++];
2275 				if (j == 31)
2276 					break;
2277 			}
2278 			phba->SerialNumber[j] = 0;
2279 			continue;
2280 		} else if ((vpd[*pindex] == 'V') && (vpd[*pindex + 1] == '1')) {
2281 			phba->vpd_flag |= VPD_MODEL_DESC;
2282 			*pindex += 2;
2283 			i = vpd[*pindex];
2284 			*pindex += 1;
2285 			j = 0;
2286 			length -= (3+i);
2287 			while (i--) {
2288 				phba->ModelDesc[j++] = vpd[(*pindex)++];
2289 				if (j == 255)
2290 					break;
2291 			}
2292 			phba->ModelDesc[j] = 0;
2293 			continue;
2294 		} else if ((vpd[*pindex] == 'V') && (vpd[*pindex + 1] == '2')) {
2295 			phba->vpd_flag |= VPD_MODEL_NAME;
2296 			*pindex += 2;
2297 			i = vpd[*pindex];
2298 			*pindex += 1;
2299 			j = 0;
2300 			length -= (3+i);
2301 			while (i--) {
2302 				phba->ModelName[j++] = vpd[(*pindex)++];
2303 				if (j == 79)
2304 					break;
2305 			}
2306 			phba->ModelName[j] = 0;
2307 			continue;
2308 		} else if ((vpd[*pindex] == 'V') && (vpd[*pindex + 1] == '3')) {
2309 			phba->vpd_flag |= VPD_PROGRAM_TYPE;
2310 			*pindex += 2;
2311 			i = vpd[*pindex];
2312 			*pindex += 1;
2313 			j = 0;
2314 			length -= (3+i);
2315 			while (i--) {
2316 				phba->ProgramType[j++] = vpd[(*pindex)++];
2317 				if (j == 255)
2318 					break;
2319 			}
2320 			phba->ProgramType[j] = 0;
2321 			continue;
2322 		} else if ((vpd[*pindex] == 'V') && (vpd[*pindex + 1] == '4')) {
2323 			phba->vpd_flag |= VPD_PORT;
2324 			*pindex += 2;
2325 			i = vpd[*pindex];
2326 			*pindex += 1;
2327 			j = 0;
2328 			length -= (3 + i);
2329 			while (i--) {
2330 				if ((phba->sli_rev == LPFC_SLI_REV4) &&
2331 				    (phba->sli4_hba.pport_name_sta ==
2332 				     LPFC_SLI4_PPNAME_GET)) {
2333 					j++;
2334 					(*pindex)++;
2335 				} else
2336 					phba->Port[j++] = vpd[(*pindex)++];
2337 				if (j == 19)
2338 					break;
2339 			}
2340 			if ((phba->sli_rev != LPFC_SLI_REV4) ||
2341 			    (phba->sli4_hba.pport_name_sta ==
2342 			     LPFC_SLI4_PPNAME_NON))
2343 				phba->Port[j] = 0;
2344 			continue;
2345 		} else {
2346 			*pindex += 2;
2347 			i = vpd[*pindex];
2348 			*pindex += 1;
2349 			*pindex += i;
2350 			length -= (3 + i);
2351 		}
2352 	}
2353 }
2354 
2355 /**
2356  * lpfc_parse_vpd - Parse VPD (Vital Product Data)
2357  * @phba: pointer to lpfc hba data structure.
2358  * @vpd: pointer to the vital product data.
2359  * @len: length of the vital product data in bytes.
2360  *
2361  * This routine parses the Vital Product Data (VPD). The VPD is treated as
2362  * an array of characters. In this routine, the ModelName, ProgramType, and
2363  * ModelDesc, etc. fields of the phba data structure will be populated.
2364  *
2365  * Return codes
2366  *   0 - pointer to the VPD passed in is NULL
2367  *   1 - success
2368  **/
2369 int
2370 lpfc_parse_vpd(struct lpfc_hba *phba, uint8_t *vpd, int len)
2371 {
2372 	uint8_t lenlo, lenhi;
2373 	int Length;
2374 	int i;
2375 	int finished = 0;
2376 	int index = 0;
2377 
2378 	if (!vpd)
2379 		return 0;
2380 
2381 	/* Vital Product */
2382 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
2383 			"0455 Vital Product Data: x%x x%x x%x x%x\n",
2384 			(uint32_t) vpd[0], (uint32_t) vpd[1], (uint32_t) vpd[2],
2385 			(uint32_t) vpd[3]);
2386 	while (!finished && (index < (len - 4))) {
2387 		switch (vpd[index]) {
2388 		case 0x82:
2389 		case 0x91:
2390 			index += 1;
2391 			lenlo = vpd[index];
2392 			index += 1;
2393 			lenhi = vpd[index];
2394 			index += 1;
2395 			i = ((((unsigned short)lenhi) << 8) + lenlo);
2396 			index += i;
2397 			break;
2398 		case 0x90:
2399 			index += 1;
2400 			lenlo = vpd[index];
2401 			index += 1;
2402 			lenhi = vpd[index];
2403 			index += 1;
2404 			Length = ((((unsigned short)lenhi) << 8) + lenlo);
2405 			if (Length > len - index)
2406 				Length = len - index;
2407 
2408 			lpfc_fill_vpd(phba, vpd, Length, &index);
2409 			finished = 0;
2410 			break;
2411 		case 0x78:
2412 			finished = 1;
2413 			break;
2414 		default:
2415 			index ++;
2416 			break;
2417 		}
2418 	}
2419 
2420 	return(1);
2421 }
2422 
2423 /**
2424  * lpfc_get_atto_model_desc - Retrieve ATTO HBA device model name and description
2425  * @phba: pointer to lpfc hba data structure.
2426  * @mdp: pointer to the data structure to hold the derived model name.
2427  * @descp: pointer to the data structure to hold the derived description.
2428  *
2429  * This routine retrieves HBA's description based on its registered PCI device
2430  * ID. The @descp passed into this function points to an array of 256 chars. It
2431  * shall be returned with the model name, maximum speed, and the host bus type.
2432  * The @mdp passed into this function points to an array of 80 chars. When the
2433  * function returns, the @mdp will be filled with the model name.
2434  **/
2435 static void
2436 lpfc_get_atto_model_desc(struct lpfc_hba *phba, uint8_t *mdp, uint8_t *descp)
2437 {
2438 	uint16_t sub_dev_id = phba->pcidev->subsystem_device;
2439 	char *model = "<Unknown>";
2440 	int tbolt = 0;
2441 
2442 	switch (sub_dev_id) {
2443 	case PCI_DEVICE_ID_CLRY_161E:
2444 		model = "161E";
2445 		break;
2446 	case PCI_DEVICE_ID_CLRY_162E:
2447 		model = "162E";
2448 		break;
2449 	case PCI_DEVICE_ID_CLRY_164E:
2450 		model = "164E";
2451 		break;
2452 	case PCI_DEVICE_ID_CLRY_161P:
2453 		model = "161P";
2454 		break;
2455 	case PCI_DEVICE_ID_CLRY_162P:
2456 		model = "162P";
2457 		break;
2458 	case PCI_DEVICE_ID_CLRY_164P:
2459 		model = "164P";
2460 		break;
2461 	case PCI_DEVICE_ID_CLRY_321E:
2462 		model = "321E";
2463 		break;
2464 	case PCI_DEVICE_ID_CLRY_322E:
2465 		model = "322E";
2466 		break;
2467 	case PCI_DEVICE_ID_CLRY_324E:
2468 		model = "324E";
2469 		break;
2470 	case PCI_DEVICE_ID_CLRY_321P:
2471 		model = "321P";
2472 		break;
2473 	case PCI_DEVICE_ID_CLRY_322P:
2474 		model = "322P";
2475 		break;
2476 	case PCI_DEVICE_ID_CLRY_324P:
2477 		model = "324P";
2478 		break;
2479 	case PCI_DEVICE_ID_TLFC_2XX2:
2480 		model = "2XX2";
2481 		tbolt = 1;
2482 		break;
2483 	case PCI_DEVICE_ID_TLFC_3162:
2484 		model = "3162";
2485 		tbolt = 1;
2486 		break;
2487 	case PCI_DEVICE_ID_TLFC_3322:
2488 		model = "3322";
2489 		tbolt = 1;
2490 		break;
2491 	default:
2492 		model = "Unknown";
2493 		break;
2494 	}
2495 
2496 	if (mdp && mdp[0] == '\0')
2497 		snprintf(mdp, 79, "%s", model);
2498 
2499 	if (descp && descp[0] == '\0')
2500 		snprintf(descp, 255,
2501 			 "ATTO %s%s, Fibre Channel Adapter Initiator, Port %s",
2502 			 (tbolt) ? "ThunderLink FC " : "Celerity FC-",
2503 			 model,
2504 			 phba->Port);
2505 }
2506 
2507 /**
2508  * lpfc_get_hba_model_desc - Retrieve HBA device model name and description
2509  * @phba: pointer to lpfc hba data structure.
2510  * @mdp: pointer to the data structure to hold the derived model name.
2511  * @descp: pointer to the data structure to hold the derived description.
2512  *
2513  * This routine retrieves HBA's description based on its registered PCI device
2514  * ID. The @descp passed into this function points to an array of 256 chars. It
2515  * shall be returned with the model name, maximum speed, and the host bus type.
2516  * The @mdp passed into this function points to an array of 80 chars. When the
2517  * function returns, the @mdp will be filled with the model name.
2518  **/
2519 static void
2520 lpfc_get_hba_model_desc(struct lpfc_hba *phba, uint8_t *mdp, uint8_t *descp)
2521 {
2522 	lpfc_vpd_t *vp;
2523 	uint16_t dev_id = phba->pcidev->device;
2524 	int max_speed;
2525 	int GE = 0;
2526 	int oneConnect = 0; /* default is not a oneConnect */
2527 	struct {
2528 		char *name;
2529 		char *bus;
2530 		char *function;
2531 	} m = {"<Unknown>", "", ""};
2532 
2533 	if (mdp && mdp[0] != '\0'
2534 		&& descp && descp[0] != '\0')
2535 		return;
2536 
2537 	if (phba->pcidev->vendor == PCI_VENDOR_ID_ATTO) {
2538 		lpfc_get_atto_model_desc(phba, mdp, descp);
2539 		return;
2540 	}
2541 
2542 	if (phba->lmt & LMT_64Gb)
2543 		max_speed = 64;
2544 	else if (phba->lmt & LMT_32Gb)
2545 		max_speed = 32;
2546 	else if (phba->lmt & LMT_16Gb)
2547 		max_speed = 16;
2548 	else if (phba->lmt & LMT_10Gb)
2549 		max_speed = 10;
2550 	else if (phba->lmt & LMT_8Gb)
2551 		max_speed = 8;
2552 	else if (phba->lmt & LMT_4Gb)
2553 		max_speed = 4;
2554 	else if (phba->lmt & LMT_2Gb)
2555 		max_speed = 2;
2556 	else if (phba->lmt & LMT_1Gb)
2557 		max_speed = 1;
2558 	else
2559 		max_speed = 0;
2560 
2561 	vp = &phba->vpd;
2562 
2563 	switch (dev_id) {
2564 	case PCI_DEVICE_ID_FIREFLY:
2565 		m = (typeof(m)){"LP6000", "PCI",
2566 				"Obsolete, Unsupported Fibre Channel Adapter"};
2567 		break;
2568 	case PCI_DEVICE_ID_SUPERFLY:
2569 		if (vp->rev.biuRev >= 1 && vp->rev.biuRev <= 3)
2570 			m = (typeof(m)){"LP7000", "PCI", ""};
2571 		else
2572 			m = (typeof(m)){"LP7000E", "PCI", ""};
2573 		m.function = "Obsolete, Unsupported Fibre Channel Adapter";
2574 		break;
2575 	case PCI_DEVICE_ID_DRAGONFLY:
2576 		m = (typeof(m)){"LP8000", "PCI",
2577 				"Obsolete, Unsupported Fibre Channel Adapter"};
2578 		break;
2579 	case PCI_DEVICE_ID_CENTAUR:
2580 		if (FC_JEDEC_ID(vp->rev.biuRev) == CENTAUR_2G_JEDEC_ID)
2581 			m = (typeof(m)){"LP9002", "PCI", ""};
2582 		else
2583 			m = (typeof(m)){"LP9000", "PCI", ""};
2584 		m.function = "Obsolete, Unsupported Fibre Channel Adapter";
2585 		break;
2586 	case PCI_DEVICE_ID_RFLY:
2587 		m = (typeof(m)){"LP952", "PCI",
2588 				"Obsolete, Unsupported Fibre Channel Adapter"};
2589 		break;
2590 	case PCI_DEVICE_ID_PEGASUS:
2591 		m = (typeof(m)){"LP9802", "PCI-X",
2592 				"Obsolete, Unsupported Fibre Channel Adapter"};
2593 		break;
2594 	case PCI_DEVICE_ID_THOR:
2595 		m = (typeof(m)){"LP10000", "PCI-X",
2596 				"Obsolete, Unsupported Fibre Channel Adapter"};
2597 		break;
2598 	case PCI_DEVICE_ID_VIPER:
2599 		m = (typeof(m)){"LPX1000",  "PCI-X",
2600 				"Obsolete, Unsupported Fibre Channel Adapter"};
2601 		break;
2602 	case PCI_DEVICE_ID_PFLY:
2603 		m = (typeof(m)){"LP982", "PCI-X",
2604 				"Obsolete, Unsupported Fibre Channel Adapter"};
2605 		break;
2606 	case PCI_DEVICE_ID_TFLY:
2607 		m = (typeof(m)){"LP1050", "PCI-X",
2608 				"Obsolete, Unsupported Fibre Channel Adapter"};
2609 		break;
2610 	case PCI_DEVICE_ID_HELIOS:
2611 		m = (typeof(m)){"LP11000", "PCI-X2",
2612 				"Obsolete, Unsupported Fibre Channel Adapter"};
2613 		break;
2614 	case PCI_DEVICE_ID_HELIOS_SCSP:
2615 		m = (typeof(m)){"LP11000-SP", "PCI-X2",
2616 				"Obsolete, Unsupported Fibre Channel Adapter"};
2617 		break;
2618 	case PCI_DEVICE_ID_HELIOS_DCSP:
2619 		m = (typeof(m)){"LP11002-SP",  "PCI-X2",
2620 				"Obsolete, Unsupported Fibre Channel Adapter"};
2621 		break;
2622 	case PCI_DEVICE_ID_NEPTUNE:
2623 		m = (typeof(m)){"LPe1000", "PCIe",
2624 				"Obsolete, Unsupported Fibre Channel Adapter"};
2625 		break;
2626 	case PCI_DEVICE_ID_NEPTUNE_SCSP:
2627 		m = (typeof(m)){"LPe1000-SP", "PCIe",
2628 				"Obsolete, Unsupported Fibre Channel Adapter"};
2629 		break;
2630 	case PCI_DEVICE_ID_NEPTUNE_DCSP:
2631 		m = (typeof(m)){"LPe1002-SP", "PCIe",
2632 				"Obsolete, Unsupported Fibre Channel Adapter"};
2633 		break;
2634 	case PCI_DEVICE_ID_BMID:
2635 		m = (typeof(m)){"LP1150", "PCI-X2", "Fibre Channel Adapter"};
2636 		break;
2637 	case PCI_DEVICE_ID_BSMB:
2638 		m = (typeof(m)){"LP111", "PCI-X2",
2639 				"Obsolete, Unsupported Fibre Channel Adapter"};
2640 		break;
2641 	case PCI_DEVICE_ID_ZEPHYR:
2642 		m = (typeof(m)){"LPe11000", "PCIe", "Fibre Channel Adapter"};
2643 		break;
2644 	case PCI_DEVICE_ID_ZEPHYR_SCSP:
2645 		m = (typeof(m)){"LPe11000", "PCIe", "Fibre Channel Adapter"};
2646 		break;
2647 	case PCI_DEVICE_ID_ZEPHYR_DCSP:
2648 		m = (typeof(m)){"LP2105", "PCIe", "FCoE Adapter"};
2649 		GE = 1;
2650 		break;
2651 	case PCI_DEVICE_ID_ZMID:
2652 		m = (typeof(m)){"LPe1150", "PCIe", "Fibre Channel Adapter"};
2653 		break;
2654 	case PCI_DEVICE_ID_ZSMB:
2655 		m = (typeof(m)){"LPe111", "PCIe", "Fibre Channel Adapter"};
2656 		break;
2657 	case PCI_DEVICE_ID_LP101:
2658 		m = (typeof(m)){"LP101", "PCI-X",
2659 				"Obsolete, Unsupported Fibre Channel Adapter"};
2660 		break;
2661 	case PCI_DEVICE_ID_LP10000S:
2662 		m = (typeof(m)){"LP10000-S", "PCI",
2663 				"Obsolete, Unsupported Fibre Channel Adapter"};
2664 		break;
2665 	case PCI_DEVICE_ID_LP11000S:
2666 		m = (typeof(m)){"LP11000-S", "PCI-X2",
2667 				"Obsolete, Unsupported Fibre Channel Adapter"};
2668 		break;
2669 	case PCI_DEVICE_ID_LPE11000S:
2670 		m = (typeof(m)){"LPe11000-S", "PCIe",
2671 				"Obsolete, Unsupported Fibre Channel Adapter"};
2672 		break;
2673 	case PCI_DEVICE_ID_SAT:
2674 		m = (typeof(m)){"LPe12000", "PCIe", "Fibre Channel Adapter"};
2675 		break;
2676 	case PCI_DEVICE_ID_SAT_MID:
2677 		m = (typeof(m)){"LPe1250", "PCIe", "Fibre Channel Adapter"};
2678 		break;
2679 	case PCI_DEVICE_ID_SAT_SMB:
2680 		m = (typeof(m)){"LPe121", "PCIe", "Fibre Channel Adapter"};
2681 		break;
2682 	case PCI_DEVICE_ID_SAT_DCSP:
2683 		m = (typeof(m)){"LPe12002-SP", "PCIe", "Fibre Channel Adapter"};
2684 		break;
2685 	case PCI_DEVICE_ID_SAT_SCSP:
2686 		m = (typeof(m)){"LPe12000-SP", "PCIe", "Fibre Channel Adapter"};
2687 		break;
2688 	case PCI_DEVICE_ID_SAT_S:
2689 		m = (typeof(m)){"LPe12000-S", "PCIe", "Fibre Channel Adapter"};
2690 		break;
2691 	case PCI_DEVICE_ID_PROTEUS_VF:
2692 		m = (typeof(m)){"LPev12000", "PCIe IOV",
2693 				"Obsolete, Unsupported Fibre Channel Adapter"};
2694 		break;
2695 	case PCI_DEVICE_ID_PROTEUS_PF:
2696 		m = (typeof(m)){"LPev12000", "PCIe IOV",
2697 				"Obsolete, Unsupported Fibre Channel Adapter"};
2698 		break;
2699 	case PCI_DEVICE_ID_PROTEUS_S:
2700 		m = (typeof(m)){"LPemv12002-S", "PCIe IOV",
2701 				"Obsolete, Unsupported Fibre Channel Adapter"};
2702 		break;
2703 	case PCI_DEVICE_ID_TIGERSHARK:
2704 		oneConnect = 1;
2705 		m = (typeof(m)){"OCe10100", "PCIe", "FCoE"};
2706 		break;
2707 	case PCI_DEVICE_ID_TOMCAT:
2708 		oneConnect = 1;
2709 		m = (typeof(m)){"OCe11100", "PCIe", "FCoE"};
2710 		break;
2711 	case PCI_DEVICE_ID_FALCON:
2712 		m = (typeof(m)){"LPSe12002-ML1-E", "PCIe",
2713 				"EmulexSecure Fibre"};
2714 		break;
2715 	case PCI_DEVICE_ID_BALIUS:
2716 		m = (typeof(m)){"LPVe12002", "PCIe Shared I/O",
2717 				"Obsolete, Unsupported Fibre Channel Adapter"};
2718 		break;
2719 	case PCI_DEVICE_ID_LANCER_FC:
2720 		m = (typeof(m)){"LPe16000", "PCIe", "Fibre Channel Adapter"};
2721 		break;
2722 	case PCI_DEVICE_ID_LANCER_FC_VF:
2723 		m = (typeof(m)){"LPe16000", "PCIe",
2724 				"Obsolete, Unsupported Fibre Channel Adapter"};
2725 		break;
2726 	case PCI_DEVICE_ID_LANCER_FCOE:
2727 		oneConnect = 1;
2728 		m = (typeof(m)){"OCe15100", "PCIe", "FCoE"};
2729 		break;
2730 	case PCI_DEVICE_ID_LANCER_FCOE_VF:
2731 		oneConnect = 1;
2732 		m = (typeof(m)){"OCe15100", "PCIe",
2733 				"Obsolete, Unsupported FCoE"};
2734 		break;
2735 	case PCI_DEVICE_ID_LANCER_G6_FC:
2736 		m = (typeof(m)){"LPe32000", "PCIe", "Fibre Channel Adapter"};
2737 		break;
2738 	case PCI_DEVICE_ID_LANCER_G7_FC:
2739 		m = (typeof(m)){"LPe36000", "PCIe", "Fibre Channel Adapter"};
2740 		break;
2741 	case PCI_DEVICE_ID_LANCER_G7P_FC:
2742 		m = (typeof(m)){"LPe38000", "PCIe", "Fibre Channel Adapter"};
2743 		break;
2744 	case PCI_DEVICE_ID_SKYHAWK:
2745 	case PCI_DEVICE_ID_SKYHAWK_VF:
2746 		oneConnect = 1;
2747 		m = (typeof(m)){"OCe14000", "PCIe", "FCoE"};
2748 		break;
2749 	default:
2750 		m = (typeof(m)){"Unknown", "", ""};
2751 		break;
2752 	}
2753 
2754 	if (mdp && mdp[0] == '\0')
2755 		snprintf(mdp, 79,"%s", m.name);
2756 	/*
2757 	 * oneConnect hba requires special processing, they are all initiators
2758 	 * and we put the port number on the end
2759 	 */
2760 	if (descp && descp[0] == '\0') {
2761 		if (oneConnect)
2762 			snprintf(descp, 255,
2763 				"Emulex OneConnect %s, %s Initiator %s",
2764 				m.name, m.function,
2765 				phba->Port);
2766 		else if (max_speed == 0)
2767 			snprintf(descp, 255,
2768 				"Emulex %s %s %s",
2769 				m.name, m.bus, m.function);
2770 		else
2771 			snprintf(descp, 255,
2772 				"Emulex %s %d%s %s %s",
2773 				m.name, max_speed, (GE) ? "GE" : "Gb",
2774 				m.bus, m.function);
2775 	}
2776 }
2777 
2778 /**
2779  * lpfc_sli3_post_buffer - Post IOCB(s) with DMA buffer descriptor(s) to a IOCB ring
2780  * @phba: pointer to lpfc hba data structure.
2781  * @pring: pointer to a IOCB ring.
2782  * @cnt: the number of IOCBs to be posted to the IOCB ring.
2783  *
2784  * This routine posts a given number of IOCBs with the associated DMA buffer
2785  * descriptors specified by the cnt argument to the given IOCB ring.
2786  *
2787  * Return codes
2788  *   The number of IOCBs NOT able to be posted to the IOCB ring.
2789  **/
2790 int
2791 lpfc_sli3_post_buffer(struct lpfc_hba *phba, struct lpfc_sli_ring *pring, int cnt)
2792 {
2793 	IOCB_t *icmd;
2794 	struct lpfc_iocbq *iocb;
2795 	struct lpfc_dmabuf *mp1, *mp2;
2796 
2797 	cnt += pring->missbufcnt;
2798 
2799 	/* While there are buffers to post */
2800 	while (cnt > 0) {
2801 		/* Allocate buffer for  command iocb */
2802 		iocb = lpfc_sli_get_iocbq(phba);
2803 		if (iocb == NULL) {
2804 			pring->missbufcnt = cnt;
2805 			return cnt;
2806 		}
2807 		icmd = &iocb->iocb;
2808 
2809 		/* 2 buffers can be posted per command */
2810 		/* Allocate buffer to post */
2811 		mp1 = kmalloc(sizeof (struct lpfc_dmabuf), GFP_KERNEL);
2812 		if (mp1)
2813 		    mp1->virt = lpfc_mbuf_alloc(phba, MEM_PRI, &mp1->phys);
2814 		if (!mp1 || !mp1->virt) {
2815 			kfree(mp1);
2816 			lpfc_sli_release_iocbq(phba, iocb);
2817 			pring->missbufcnt = cnt;
2818 			return cnt;
2819 		}
2820 
2821 		INIT_LIST_HEAD(&mp1->list);
2822 		/* Allocate buffer to post */
2823 		if (cnt > 1) {
2824 			mp2 = kmalloc(sizeof (struct lpfc_dmabuf), GFP_KERNEL);
2825 			if (mp2)
2826 				mp2->virt = lpfc_mbuf_alloc(phba, MEM_PRI,
2827 							    &mp2->phys);
2828 			if (!mp2 || !mp2->virt) {
2829 				kfree(mp2);
2830 				lpfc_mbuf_free(phba, mp1->virt, mp1->phys);
2831 				kfree(mp1);
2832 				lpfc_sli_release_iocbq(phba, iocb);
2833 				pring->missbufcnt = cnt;
2834 				return cnt;
2835 			}
2836 
2837 			INIT_LIST_HEAD(&mp2->list);
2838 		} else {
2839 			mp2 = NULL;
2840 		}
2841 
2842 		icmd->un.cont64[0].addrHigh = putPaddrHigh(mp1->phys);
2843 		icmd->un.cont64[0].addrLow = putPaddrLow(mp1->phys);
2844 		icmd->un.cont64[0].tus.f.bdeSize = FCELSSIZE;
2845 		icmd->ulpBdeCount = 1;
2846 		cnt--;
2847 		if (mp2) {
2848 			icmd->un.cont64[1].addrHigh = putPaddrHigh(mp2->phys);
2849 			icmd->un.cont64[1].addrLow = putPaddrLow(mp2->phys);
2850 			icmd->un.cont64[1].tus.f.bdeSize = FCELSSIZE;
2851 			cnt--;
2852 			icmd->ulpBdeCount = 2;
2853 		}
2854 
2855 		icmd->ulpCommand = CMD_QUE_RING_BUF64_CN;
2856 		icmd->ulpLe = 1;
2857 
2858 		if (lpfc_sli_issue_iocb(phba, pring->ringno, iocb, 0) ==
2859 		    IOCB_ERROR) {
2860 			lpfc_mbuf_free(phba, mp1->virt, mp1->phys);
2861 			kfree(mp1);
2862 			cnt++;
2863 			if (mp2) {
2864 				lpfc_mbuf_free(phba, mp2->virt, mp2->phys);
2865 				kfree(mp2);
2866 				cnt++;
2867 			}
2868 			lpfc_sli_release_iocbq(phba, iocb);
2869 			pring->missbufcnt = cnt;
2870 			return cnt;
2871 		}
2872 		lpfc_sli_ringpostbuf_put(phba, pring, mp1);
2873 		if (mp2)
2874 			lpfc_sli_ringpostbuf_put(phba, pring, mp2);
2875 	}
2876 	pring->missbufcnt = 0;
2877 	return 0;
2878 }
2879 
2880 /**
2881  * lpfc_post_rcv_buf - Post the initial receive IOCB buffers to ELS ring
2882  * @phba: pointer to lpfc hba data structure.
2883  *
2884  * This routine posts initial receive IOCB buffers to the ELS ring. The
2885  * current number of initial IOCB buffers specified by LPFC_BUF_RING0 is
2886  * set to 64 IOCBs. SLI3 only.
2887  *
2888  * Return codes
2889  *   0 - success (currently always success)
2890  **/
2891 static int
2892 lpfc_post_rcv_buf(struct lpfc_hba *phba)
2893 {
2894 	struct lpfc_sli *psli = &phba->sli;
2895 
2896 	/* Ring 0, ELS / CT buffers */
2897 	lpfc_sli3_post_buffer(phba, &psli->sli3_ring[LPFC_ELS_RING], LPFC_BUF_RING0);
2898 	/* Ring 2 - FCP no buffers needed */
2899 
2900 	return 0;
2901 }
2902 
2903 #define S(N,V) (((V)<<(N))|((V)>>(32-(N))))
2904 
2905 /**
2906  * lpfc_sha_init - Set up initial array of hash table entries
2907  * @HashResultPointer: pointer to an array as hash table.
2908  *
2909  * This routine sets up the initial values to the array of hash table entries
2910  * for the LC HBAs.
2911  **/
2912 static void
2913 lpfc_sha_init(uint32_t * HashResultPointer)
2914 {
2915 	HashResultPointer[0] = 0x67452301;
2916 	HashResultPointer[1] = 0xEFCDAB89;
2917 	HashResultPointer[2] = 0x98BADCFE;
2918 	HashResultPointer[3] = 0x10325476;
2919 	HashResultPointer[4] = 0xC3D2E1F0;
2920 }
2921 
2922 /**
2923  * lpfc_sha_iterate - Iterate initial hash table with the working hash table
2924  * @HashResultPointer: pointer to an initial/result hash table.
2925  * @HashWorkingPointer: pointer to an working hash table.
2926  *
2927  * This routine iterates an initial hash table pointed by @HashResultPointer
2928  * with the values from the working hash table pointeed by @HashWorkingPointer.
2929  * The results are putting back to the initial hash table, returned through
2930  * the @HashResultPointer as the result hash table.
2931  **/
2932 static void
2933 lpfc_sha_iterate(uint32_t * HashResultPointer, uint32_t * HashWorkingPointer)
2934 {
2935 	int t;
2936 	uint32_t TEMP;
2937 	uint32_t A, B, C, D, E;
2938 	t = 16;
2939 	do {
2940 		HashWorkingPointer[t] =
2941 		    S(1,
2942 		      HashWorkingPointer[t - 3] ^ HashWorkingPointer[t -
2943 								     8] ^
2944 		      HashWorkingPointer[t - 14] ^ HashWorkingPointer[t - 16]);
2945 	} while (++t <= 79);
2946 	t = 0;
2947 	A = HashResultPointer[0];
2948 	B = HashResultPointer[1];
2949 	C = HashResultPointer[2];
2950 	D = HashResultPointer[3];
2951 	E = HashResultPointer[4];
2952 
2953 	do {
2954 		if (t < 20) {
2955 			TEMP = ((B & C) | ((~B) & D)) + 0x5A827999;
2956 		} else if (t < 40) {
2957 			TEMP = (B ^ C ^ D) + 0x6ED9EBA1;
2958 		} else if (t < 60) {
2959 			TEMP = ((B & C) | (B & D) | (C & D)) + 0x8F1BBCDC;
2960 		} else {
2961 			TEMP = (B ^ C ^ D) + 0xCA62C1D6;
2962 		}
2963 		TEMP += S(5, A) + E + HashWorkingPointer[t];
2964 		E = D;
2965 		D = C;
2966 		C = S(30, B);
2967 		B = A;
2968 		A = TEMP;
2969 	} while (++t <= 79);
2970 
2971 	HashResultPointer[0] += A;
2972 	HashResultPointer[1] += B;
2973 	HashResultPointer[2] += C;
2974 	HashResultPointer[3] += D;
2975 	HashResultPointer[4] += E;
2976 
2977 }
2978 
2979 /**
2980  * lpfc_challenge_key - Create challenge key based on WWPN of the HBA
2981  * @RandomChallenge: pointer to the entry of host challenge random number array.
2982  * @HashWorking: pointer to the entry of the working hash array.
2983  *
2984  * This routine calculates the working hash array referred by @HashWorking
2985  * from the challenge random numbers associated with the host, referred by
2986  * @RandomChallenge. The result is put into the entry of the working hash
2987  * array and returned by reference through @HashWorking.
2988  **/
2989 static void
2990 lpfc_challenge_key(uint32_t * RandomChallenge, uint32_t * HashWorking)
2991 {
2992 	*HashWorking = (*RandomChallenge ^ *HashWorking);
2993 }
2994 
2995 /**
2996  * lpfc_hba_init - Perform special handling for LC HBA initialization
2997  * @phba: pointer to lpfc hba data structure.
2998  * @hbainit: pointer to an array of unsigned 32-bit integers.
2999  *
3000  * This routine performs the special handling for LC HBA initialization.
3001  **/
3002 void
3003 lpfc_hba_init(struct lpfc_hba *phba, uint32_t *hbainit)
3004 {
3005 	int t;
3006 	uint32_t *HashWorking;
3007 	uint32_t *pwwnn = (uint32_t *) phba->wwnn;
3008 
3009 	HashWorking = kcalloc(80, sizeof(uint32_t), GFP_KERNEL);
3010 	if (!HashWorking)
3011 		return;
3012 
3013 	HashWorking[0] = HashWorking[78] = *pwwnn++;
3014 	HashWorking[1] = HashWorking[79] = *pwwnn;
3015 
3016 	for (t = 0; t < 7; t++)
3017 		lpfc_challenge_key(phba->RandomData + t, HashWorking + t);
3018 
3019 	lpfc_sha_init(hbainit);
3020 	lpfc_sha_iterate(hbainit, HashWorking);
3021 	kfree(HashWorking);
3022 }
3023 
3024 /**
3025  * lpfc_cleanup - Performs vport cleanups before deleting a vport
3026  * @vport: pointer to a virtual N_Port data structure.
3027  *
3028  * This routine performs the necessary cleanups before deleting the @vport.
3029  * It invokes the discovery state machine to perform necessary state
3030  * transitions and to release the ndlps associated with the @vport. Note,
3031  * the physical port is treated as @vport 0.
3032  **/
3033 void
3034 lpfc_cleanup(struct lpfc_vport *vport)
3035 {
3036 	struct lpfc_hba   *phba = vport->phba;
3037 	struct lpfc_nodelist *ndlp, *next_ndlp;
3038 	int i = 0;
3039 
3040 	if (phba->link_state > LPFC_LINK_DOWN)
3041 		lpfc_port_link_failure(vport);
3042 
3043 	/* Clean up VMID resources */
3044 	if (lpfc_is_vmid_enabled(phba))
3045 		lpfc_vmid_vport_cleanup(vport);
3046 
3047 	list_for_each_entry_safe(ndlp, next_ndlp, &vport->fc_nodes, nlp_listp) {
3048 		if (vport->port_type != LPFC_PHYSICAL_PORT &&
3049 		    ndlp->nlp_DID == Fabric_DID) {
3050 			/* Just free up ndlp with Fabric_DID for vports */
3051 			lpfc_nlp_put(ndlp);
3052 			continue;
3053 		}
3054 
3055 		if (ndlp->nlp_DID == Fabric_Cntl_DID &&
3056 		    ndlp->nlp_state == NLP_STE_UNUSED_NODE) {
3057 			lpfc_nlp_put(ndlp);
3058 			continue;
3059 		}
3060 
3061 		/* Fabric Ports not in UNMAPPED state are cleaned up in the
3062 		 * DEVICE_RM event.
3063 		 */
3064 		if (ndlp->nlp_type & NLP_FABRIC &&
3065 		    ndlp->nlp_state == NLP_STE_UNMAPPED_NODE)
3066 			lpfc_disc_state_machine(vport, ndlp, NULL,
3067 					NLP_EVT_DEVICE_RECOVERY);
3068 
3069 		if (!(ndlp->fc4_xpt_flags & (NVME_XPT_REGD|SCSI_XPT_REGD)))
3070 			lpfc_disc_state_machine(vport, ndlp, NULL,
3071 					NLP_EVT_DEVICE_RM);
3072 	}
3073 
3074 	/* This is a special case flush to return all
3075 	 * IOs before entering this loop. There are
3076 	 * two points in the code where a flush is
3077 	 * avoided if the FC_UNLOADING flag is set.
3078 	 * one is in the multipool destroy,
3079 	 * (this prevents a crash) and the other is
3080 	 * in the nvme abort handler, ( also prevents
3081 	 * a crash). Both of these exceptions are
3082 	 * cases where the slot is still accessible.
3083 	 * The flush here is only when the pci slot
3084 	 * is offline.
3085 	 */
3086 	if (vport->load_flag & FC_UNLOADING &&
3087 	    pci_channel_offline(phba->pcidev))
3088 		lpfc_sli_flush_io_rings(vport->phba);
3089 
3090 	/* At this point, ALL ndlp's should be gone
3091 	 * because of the previous NLP_EVT_DEVICE_RM.
3092 	 * Lets wait for this to happen, if needed.
3093 	 */
3094 	while (!list_empty(&vport->fc_nodes)) {
3095 		if (i++ > 3000) {
3096 			lpfc_printf_vlog(vport, KERN_ERR,
3097 					 LOG_TRACE_EVENT,
3098 				"0233 Nodelist not empty\n");
3099 			list_for_each_entry_safe(ndlp, next_ndlp,
3100 						&vport->fc_nodes, nlp_listp) {
3101 				lpfc_printf_vlog(ndlp->vport, KERN_ERR,
3102 						 LOG_DISCOVERY,
3103 						 "0282 did:x%x ndlp:x%px "
3104 						 "refcnt:%d xflags x%x nflag x%x\n",
3105 						 ndlp->nlp_DID, (void *)ndlp,
3106 						 kref_read(&ndlp->kref),
3107 						 ndlp->fc4_xpt_flags,
3108 						 ndlp->nlp_flag);
3109 			}
3110 			break;
3111 		}
3112 
3113 		/* Wait for any activity on ndlps to settle */
3114 		msleep(10);
3115 	}
3116 	lpfc_cleanup_vports_rrqs(vport, NULL);
3117 }
3118 
3119 /**
3120  * lpfc_stop_vport_timers - Stop all the timers associated with a vport
3121  * @vport: pointer to a virtual N_Port data structure.
3122  *
3123  * This routine stops all the timers associated with a @vport. This function
3124  * is invoked before disabling or deleting a @vport. Note that the physical
3125  * port is treated as @vport 0.
3126  **/
3127 void
3128 lpfc_stop_vport_timers(struct lpfc_vport *vport)
3129 {
3130 	del_timer_sync(&vport->els_tmofunc);
3131 	del_timer_sync(&vport->delayed_disc_tmo);
3132 	lpfc_can_disctmo(vport);
3133 	return;
3134 }
3135 
3136 /**
3137  * __lpfc_sli4_stop_fcf_redisc_wait_timer - Stop FCF rediscovery wait timer
3138  * @phba: pointer to lpfc hba data structure.
3139  *
3140  * This routine stops the SLI4 FCF rediscover wait timer if it's on. The
3141  * caller of this routine should already hold the host lock.
3142  **/
3143 void
3144 __lpfc_sli4_stop_fcf_redisc_wait_timer(struct lpfc_hba *phba)
3145 {
3146 	/* Clear pending FCF rediscovery wait flag */
3147 	phba->fcf.fcf_flag &= ~FCF_REDISC_PEND;
3148 
3149 	/* Now, try to stop the timer */
3150 	del_timer(&phba->fcf.redisc_wait);
3151 }
3152 
3153 /**
3154  * lpfc_sli4_stop_fcf_redisc_wait_timer - Stop FCF rediscovery wait timer
3155  * @phba: pointer to lpfc hba data structure.
3156  *
3157  * This routine stops the SLI4 FCF rediscover wait timer if it's on. It
3158  * checks whether the FCF rediscovery wait timer is pending with the host
3159  * lock held before proceeding with disabling the timer and clearing the
3160  * wait timer pendig flag.
3161  **/
3162 void
3163 lpfc_sli4_stop_fcf_redisc_wait_timer(struct lpfc_hba *phba)
3164 {
3165 	spin_lock_irq(&phba->hbalock);
3166 	if (!(phba->fcf.fcf_flag & FCF_REDISC_PEND)) {
3167 		/* FCF rediscovery timer already fired or stopped */
3168 		spin_unlock_irq(&phba->hbalock);
3169 		return;
3170 	}
3171 	__lpfc_sli4_stop_fcf_redisc_wait_timer(phba);
3172 	/* Clear failover in progress flags */
3173 	phba->fcf.fcf_flag &= ~(FCF_DEAD_DISC | FCF_ACVL_DISC);
3174 	spin_unlock_irq(&phba->hbalock);
3175 }
3176 
3177 /**
3178  * lpfc_cmf_stop - Stop CMF processing
3179  * @phba: pointer to lpfc hba data structure.
3180  *
3181  * This is called when the link goes down or if CMF mode is turned OFF.
3182  * It is also called when going offline or unloaded just before the
3183  * congestion info buffer is unregistered.
3184  **/
3185 void
3186 lpfc_cmf_stop(struct lpfc_hba *phba)
3187 {
3188 	int cpu;
3189 	struct lpfc_cgn_stat *cgs;
3190 
3191 	/* We only do something if CMF is enabled */
3192 	if (!phba->sli4_hba.pc_sli4_params.cmf)
3193 		return;
3194 
3195 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
3196 			"6221 Stop CMF / Cancel Timer\n");
3197 
3198 	/* Cancel the CMF timer */
3199 	hrtimer_cancel(&phba->cmf_timer);
3200 
3201 	/* Zero CMF counters */
3202 	atomic_set(&phba->cmf_busy, 0);
3203 	for_each_present_cpu(cpu) {
3204 		cgs = per_cpu_ptr(phba->cmf_stat, cpu);
3205 		atomic64_set(&cgs->total_bytes, 0);
3206 		atomic64_set(&cgs->rcv_bytes, 0);
3207 		atomic_set(&cgs->rx_io_cnt, 0);
3208 		atomic64_set(&cgs->rx_latency, 0);
3209 	}
3210 	atomic_set(&phba->cmf_bw_wait, 0);
3211 
3212 	/* Resume any blocked IO - Queue unblock on workqueue */
3213 	queue_work(phba->wq, &phba->unblock_request_work);
3214 }
3215 
3216 static inline uint64_t
3217 lpfc_get_max_line_rate(struct lpfc_hba *phba)
3218 {
3219 	uint64_t rate = lpfc_sli_port_speed_get(phba);
3220 
3221 	return ((((unsigned long)rate) * 1024 * 1024) / 10);
3222 }
3223 
3224 void
3225 lpfc_cmf_signal_init(struct lpfc_hba *phba)
3226 {
3227 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
3228 			"6223 Signal CMF init\n");
3229 
3230 	/* Use the new fc_linkspeed to recalculate */
3231 	phba->cmf_interval_rate = LPFC_CMF_INTERVAL;
3232 	phba->cmf_max_line_rate = lpfc_get_max_line_rate(phba);
3233 	phba->cmf_link_byte_count = div_u64(phba->cmf_max_line_rate *
3234 					    phba->cmf_interval_rate, 1000);
3235 	phba->cmf_max_bytes_per_interval = phba->cmf_link_byte_count;
3236 
3237 	/* This is a signal to firmware to sync up CMF BW with link speed */
3238 	lpfc_issue_cmf_sync_wqe(phba, 0, 0);
3239 }
3240 
3241 /**
3242  * lpfc_cmf_start - Start CMF processing
3243  * @phba: pointer to lpfc hba data structure.
3244  *
3245  * This is called when the link comes up or if CMF mode is turned OFF
3246  * to Monitor or Managed.
3247  **/
3248 void
3249 lpfc_cmf_start(struct lpfc_hba *phba)
3250 {
3251 	struct lpfc_cgn_stat *cgs;
3252 	int cpu;
3253 
3254 	/* We only do something if CMF is enabled */
3255 	if (!phba->sli4_hba.pc_sli4_params.cmf ||
3256 	    phba->cmf_active_mode == LPFC_CFG_OFF)
3257 		return;
3258 
3259 	/* Reinitialize congestion buffer info */
3260 	lpfc_init_congestion_buf(phba);
3261 
3262 	atomic_set(&phba->cgn_fabric_warn_cnt, 0);
3263 	atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
3264 	atomic_set(&phba->cgn_sync_alarm_cnt, 0);
3265 	atomic_set(&phba->cgn_sync_warn_cnt, 0);
3266 
3267 	atomic_set(&phba->cmf_busy, 0);
3268 	for_each_present_cpu(cpu) {
3269 		cgs = per_cpu_ptr(phba->cmf_stat, cpu);
3270 		atomic64_set(&cgs->total_bytes, 0);
3271 		atomic64_set(&cgs->rcv_bytes, 0);
3272 		atomic_set(&cgs->rx_io_cnt, 0);
3273 		atomic64_set(&cgs->rx_latency, 0);
3274 	}
3275 	phba->cmf_latency.tv_sec = 0;
3276 	phba->cmf_latency.tv_nsec = 0;
3277 
3278 	lpfc_cmf_signal_init(phba);
3279 
3280 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
3281 			"6222 Start CMF / Timer\n");
3282 
3283 	phba->cmf_timer_cnt = 0;
3284 	hrtimer_start(&phba->cmf_timer,
3285 		      ktime_set(0, LPFC_CMF_INTERVAL * 1000000),
3286 		      HRTIMER_MODE_REL);
3287 	/* Setup for latency check in IO cmpl routines */
3288 	ktime_get_real_ts64(&phba->cmf_latency);
3289 
3290 	atomic_set(&phba->cmf_bw_wait, 0);
3291 	atomic_set(&phba->cmf_stop_io, 0);
3292 }
3293 
3294 /**
3295  * lpfc_stop_hba_timers - Stop all the timers associated with an HBA
3296  * @phba: pointer to lpfc hba data structure.
3297  *
3298  * This routine stops all the timers associated with a HBA. This function is
3299  * invoked before either putting a HBA offline or unloading the driver.
3300  **/
3301 void
3302 lpfc_stop_hba_timers(struct lpfc_hba *phba)
3303 {
3304 	if (phba->pport)
3305 		lpfc_stop_vport_timers(phba->pport);
3306 	cancel_delayed_work_sync(&phba->eq_delay_work);
3307 	cancel_delayed_work_sync(&phba->idle_stat_delay_work);
3308 	del_timer_sync(&phba->sli.mbox_tmo);
3309 	del_timer_sync(&phba->fabric_block_timer);
3310 	del_timer_sync(&phba->eratt_poll);
3311 	del_timer_sync(&phba->hb_tmofunc);
3312 	if (phba->sli_rev == LPFC_SLI_REV4) {
3313 		del_timer_sync(&phba->rrq_tmr);
3314 		phba->hba_flag &= ~HBA_RRQ_ACTIVE;
3315 	}
3316 	phba->hba_flag &= ~(HBA_HBEAT_INP | HBA_HBEAT_TMO);
3317 
3318 	switch (phba->pci_dev_grp) {
3319 	case LPFC_PCI_DEV_LP:
3320 		/* Stop any LightPulse device specific driver timers */
3321 		del_timer_sync(&phba->fcp_poll_timer);
3322 		break;
3323 	case LPFC_PCI_DEV_OC:
3324 		/* Stop any OneConnect device specific driver timers */
3325 		lpfc_sli4_stop_fcf_redisc_wait_timer(phba);
3326 		break;
3327 	default:
3328 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3329 				"0297 Invalid device group (x%x)\n",
3330 				phba->pci_dev_grp);
3331 		break;
3332 	}
3333 	return;
3334 }
3335 
3336 /**
3337  * lpfc_block_mgmt_io - Mark a HBA's management interface as blocked
3338  * @phba: pointer to lpfc hba data structure.
3339  * @mbx_action: flag for mailbox no wait action.
3340  *
3341  * This routine marks a HBA's management interface as blocked. Once the HBA's
3342  * management interface is marked as blocked, all the user space access to
3343  * the HBA, whether they are from sysfs interface or libdfc interface will
3344  * all be blocked. The HBA is set to block the management interface when the
3345  * driver prepares the HBA interface for online or offline.
3346  **/
3347 static void
3348 lpfc_block_mgmt_io(struct lpfc_hba *phba, int mbx_action)
3349 {
3350 	unsigned long iflag;
3351 	uint8_t actcmd = MBX_HEARTBEAT;
3352 	unsigned long timeout;
3353 
3354 	spin_lock_irqsave(&phba->hbalock, iflag);
3355 	phba->sli.sli_flag |= LPFC_BLOCK_MGMT_IO;
3356 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3357 	if (mbx_action == LPFC_MBX_NO_WAIT)
3358 		return;
3359 	timeout = msecs_to_jiffies(LPFC_MBOX_TMO * 1000) + jiffies;
3360 	spin_lock_irqsave(&phba->hbalock, iflag);
3361 	if (phba->sli.mbox_active) {
3362 		actcmd = phba->sli.mbox_active->u.mb.mbxCommand;
3363 		/* Determine how long we might wait for the active mailbox
3364 		 * command to be gracefully completed by firmware.
3365 		 */
3366 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
3367 				phba->sli.mbox_active) * 1000) + jiffies;
3368 	}
3369 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3370 
3371 	/* Wait for the outstnading mailbox command to complete */
3372 	while (phba->sli.mbox_active) {
3373 		/* Check active mailbox complete status every 2ms */
3374 		msleep(2);
3375 		if (time_after(jiffies, timeout)) {
3376 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3377 					"2813 Mgmt IO is Blocked %x "
3378 					"- mbox cmd %x still active\n",
3379 					phba->sli.sli_flag, actcmd);
3380 			break;
3381 		}
3382 	}
3383 }
3384 
3385 /**
3386  * lpfc_sli4_node_prep - Assign RPIs for active nodes.
3387  * @phba: pointer to lpfc hba data structure.
3388  *
3389  * Allocate RPIs for all active remote nodes. This is needed whenever
3390  * an SLI4 adapter is reset and the driver is not unloading. Its purpose
3391  * is to fixup the temporary rpi assignments.
3392  **/
3393 void
3394 lpfc_sli4_node_prep(struct lpfc_hba *phba)
3395 {
3396 	struct lpfc_nodelist  *ndlp, *next_ndlp;
3397 	struct lpfc_vport **vports;
3398 	int i, rpi;
3399 
3400 	if (phba->sli_rev != LPFC_SLI_REV4)
3401 		return;
3402 
3403 	vports = lpfc_create_vport_work_array(phba);
3404 	if (vports == NULL)
3405 		return;
3406 
3407 	for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3408 		if (vports[i]->load_flag & FC_UNLOADING)
3409 			continue;
3410 
3411 		list_for_each_entry_safe(ndlp, next_ndlp,
3412 					 &vports[i]->fc_nodes,
3413 					 nlp_listp) {
3414 			rpi = lpfc_sli4_alloc_rpi(phba);
3415 			if (rpi == LPFC_RPI_ALLOC_ERROR) {
3416 				/* TODO print log? */
3417 				continue;
3418 			}
3419 			ndlp->nlp_rpi = rpi;
3420 			lpfc_printf_vlog(ndlp->vport, KERN_INFO,
3421 					 LOG_NODE | LOG_DISCOVERY,
3422 					 "0009 Assign RPI x%x to ndlp x%px "
3423 					 "DID:x%06x flg:x%x\n",
3424 					 ndlp->nlp_rpi, ndlp, ndlp->nlp_DID,
3425 					 ndlp->nlp_flag);
3426 		}
3427 	}
3428 	lpfc_destroy_vport_work_array(phba, vports);
3429 }
3430 
3431 /**
3432  * lpfc_create_expedite_pool - create expedite pool
3433  * @phba: pointer to lpfc hba data structure.
3434  *
3435  * This routine moves a batch of XRIs from lpfc_io_buf_list_put of HWQ 0
3436  * to expedite pool. Mark them as expedite.
3437  **/
3438 static void lpfc_create_expedite_pool(struct lpfc_hba *phba)
3439 {
3440 	struct lpfc_sli4_hdw_queue *qp;
3441 	struct lpfc_io_buf *lpfc_ncmd;
3442 	struct lpfc_io_buf *lpfc_ncmd_next;
3443 	struct lpfc_epd_pool *epd_pool;
3444 	unsigned long iflag;
3445 
3446 	epd_pool = &phba->epd_pool;
3447 	qp = &phba->sli4_hba.hdwq[0];
3448 
3449 	spin_lock_init(&epd_pool->lock);
3450 	spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3451 	spin_lock(&epd_pool->lock);
3452 	INIT_LIST_HEAD(&epd_pool->list);
3453 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3454 				 &qp->lpfc_io_buf_list_put, list) {
3455 		list_move_tail(&lpfc_ncmd->list, &epd_pool->list);
3456 		lpfc_ncmd->expedite = true;
3457 		qp->put_io_bufs--;
3458 		epd_pool->count++;
3459 		if (epd_pool->count >= XRI_BATCH)
3460 			break;
3461 	}
3462 	spin_unlock(&epd_pool->lock);
3463 	spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3464 }
3465 
3466 /**
3467  * lpfc_destroy_expedite_pool - destroy expedite pool
3468  * @phba: pointer to lpfc hba data structure.
3469  *
3470  * This routine returns XRIs from expedite pool to lpfc_io_buf_list_put
3471  * of HWQ 0. Clear the mark.
3472  **/
3473 static void lpfc_destroy_expedite_pool(struct lpfc_hba *phba)
3474 {
3475 	struct lpfc_sli4_hdw_queue *qp;
3476 	struct lpfc_io_buf *lpfc_ncmd;
3477 	struct lpfc_io_buf *lpfc_ncmd_next;
3478 	struct lpfc_epd_pool *epd_pool;
3479 	unsigned long iflag;
3480 
3481 	epd_pool = &phba->epd_pool;
3482 	qp = &phba->sli4_hba.hdwq[0];
3483 
3484 	spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3485 	spin_lock(&epd_pool->lock);
3486 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3487 				 &epd_pool->list, list) {
3488 		list_move_tail(&lpfc_ncmd->list,
3489 			       &qp->lpfc_io_buf_list_put);
3490 		lpfc_ncmd->flags = false;
3491 		qp->put_io_bufs++;
3492 		epd_pool->count--;
3493 	}
3494 	spin_unlock(&epd_pool->lock);
3495 	spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3496 }
3497 
3498 /**
3499  * lpfc_create_multixri_pools - create multi-XRI pools
3500  * @phba: pointer to lpfc hba data structure.
3501  *
3502  * This routine initialize public, private per HWQ. Then, move XRIs from
3503  * lpfc_io_buf_list_put to public pool. High and low watermark are also
3504  * Initialized.
3505  **/
3506 void lpfc_create_multixri_pools(struct lpfc_hba *phba)
3507 {
3508 	u32 i, j;
3509 	u32 hwq_count;
3510 	u32 count_per_hwq;
3511 	struct lpfc_io_buf *lpfc_ncmd;
3512 	struct lpfc_io_buf *lpfc_ncmd_next;
3513 	unsigned long iflag;
3514 	struct lpfc_sli4_hdw_queue *qp;
3515 	struct lpfc_multixri_pool *multixri_pool;
3516 	struct lpfc_pbl_pool *pbl_pool;
3517 	struct lpfc_pvt_pool *pvt_pool;
3518 
3519 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3520 			"1234 num_hdw_queue=%d num_present_cpu=%d common_xri_cnt=%d\n",
3521 			phba->cfg_hdw_queue, phba->sli4_hba.num_present_cpu,
3522 			phba->sli4_hba.io_xri_cnt);
3523 
3524 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
3525 		lpfc_create_expedite_pool(phba);
3526 
3527 	hwq_count = phba->cfg_hdw_queue;
3528 	count_per_hwq = phba->sli4_hba.io_xri_cnt / hwq_count;
3529 
3530 	for (i = 0; i < hwq_count; i++) {
3531 		multixri_pool = kzalloc(sizeof(*multixri_pool), GFP_KERNEL);
3532 
3533 		if (!multixri_pool) {
3534 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3535 					"1238 Failed to allocate memory for "
3536 					"multixri_pool\n");
3537 
3538 			if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
3539 				lpfc_destroy_expedite_pool(phba);
3540 
3541 			j = 0;
3542 			while (j < i) {
3543 				qp = &phba->sli4_hba.hdwq[j];
3544 				kfree(qp->p_multixri_pool);
3545 				j++;
3546 			}
3547 			phba->cfg_xri_rebalancing = 0;
3548 			return;
3549 		}
3550 
3551 		qp = &phba->sli4_hba.hdwq[i];
3552 		qp->p_multixri_pool = multixri_pool;
3553 
3554 		multixri_pool->xri_limit = count_per_hwq;
3555 		multixri_pool->rrb_next_hwqid = i;
3556 
3557 		/* Deal with public free xri pool */
3558 		pbl_pool = &multixri_pool->pbl_pool;
3559 		spin_lock_init(&pbl_pool->lock);
3560 		spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3561 		spin_lock(&pbl_pool->lock);
3562 		INIT_LIST_HEAD(&pbl_pool->list);
3563 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3564 					 &qp->lpfc_io_buf_list_put, list) {
3565 			list_move_tail(&lpfc_ncmd->list, &pbl_pool->list);
3566 			qp->put_io_bufs--;
3567 			pbl_pool->count++;
3568 		}
3569 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3570 				"1235 Moved %d buffers from PUT list over to pbl_pool[%d]\n",
3571 				pbl_pool->count, i);
3572 		spin_unlock(&pbl_pool->lock);
3573 		spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3574 
3575 		/* Deal with private free xri pool */
3576 		pvt_pool = &multixri_pool->pvt_pool;
3577 		pvt_pool->high_watermark = multixri_pool->xri_limit / 2;
3578 		pvt_pool->low_watermark = XRI_BATCH;
3579 		spin_lock_init(&pvt_pool->lock);
3580 		spin_lock_irqsave(&pvt_pool->lock, iflag);
3581 		INIT_LIST_HEAD(&pvt_pool->list);
3582 		pvt_pool->count = 0;
3583 		spin_unlock_irqrestore(&pvt_pool->lock, iflag);
3584 	}
3585 }
3586 
3587 /**
3588  * lpfc_destroy_multixri_pools - destroy multi-XRI pools
3589  * @phba: pointer to lpfc hba data structure.
3590  *
3591  * This routine returns XRIs from public/private to lpfc_io_buf_list_put.
3592  **/
3593 static void lpfc_destroy_multixri_pools(struct lpfc_hba *phba)
3594 {
3595 	u32 i;
3596 	u32 hwq_count;
3597 	struct lpfc_io_buf *lpfc_ncmd;
3598 	struct lpfc_io_buf *lpfc_ncmd_next;
3599 	unsigned long iflag;
3600 	struct lpfc_sli4_hdw_queue *qp;
3601 	struct lpfc_multixri_pool *multixri_pool;
3602 	struct lpfc_pbl_pool *pbl_pool;
3603 	struct lpfc_pvt_pool *pvt_pool;
3604 
3605 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
3606 		lpfc_destroy_expedite_pool(phba);
3607 
3608 	if (!(phba->pport->load_flag & FC_UNLOADING))
3609 		lpfc_sli_flush_io_rings(phba);
3610 
3611 	hwq_count = phba->cfg_hdw_queue;
3612 
3613 	for (i = 0; i < hwq_count; i++) {
3614 		qp = &phba->sli4_hba.hdwq[i];
3615 		multixri_pool = qp->p_multixri_pool;
3616 		if (!multixri_pool)
3617 			continue;
3618 
3619 		qp->p_multixri_pool = NULL;
3620 
3621 		spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3622 
3623 		/* Deal with public free xri pool */
3624 		pbl_pool = &multixri_pool->pbl_pool;
3625 		spin_lock(&pbl_pool->lock);
3626 
3627 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3628 				"1236 Moving %d buffers from pbl_pool[%d] TO PUT list\n",
3629 				pbl_pool->count, i);
3630 
3631 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3632 					 &pbl_pool->list, list) {
3633 			list_move_tail(&lpfc_ncmd->list,
3634 				       &qp->lpfc_io_buf_list_put);
3635 			qp->put_io_bufs++;
3636 			pbl_pool->count--;
3637 		}
3638 
3639 		INIT_LIST_HEAD(&pbl_pool->list);
3640 		pbl_pool->count = 0;
3641 
3642 		spin_unlock(&pbl_pool->lock);
3643 
3644 		/* Deal with private free xri pool */
3645 		pvt_pool = &multixri_pool->pvt_pool;
3646 		spin_lock(&pvt_pool->lock);
3647 
3648 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3649 				"1237 Moving %d buffers from pvt_pool[%d] TO PUT list\n",
3650 				pvt_pool->count, i);
3651 
3652 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3653 					 &pvt_pool->list, list) {
3654 			list_move_tail(&lpfc_ncmd->list,
3655 				       &qp->lpfc_io_buf_list_put);
3656 			qp->put_io_bufs++;
3657 			pvt_pool->count--;
3658 		}
3659 
3660 		INIT_LIST_HEAD(&pvt_pool->list);
3661 		pvt_pool->count = 0;
3662 
3663 		spin_unlock(&pvt_pool->lock);
3664 		spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3665 
3666 		kfree(multixri_pool);
3667 	}
3668 }
3669 
3670 /**
3671  * lpfc_online - Initialize and bring a HBA online
3672  * @phba: pointer to lpfc hba data structure.
3673  *
3674  * This routine initializes the HBA and brings a HBA online. During this
3675  * process, the management interface is blocked to prevent user space access
3676  * to the HBA interfering with the driver initialization.
3677  *
3678  * Return codes
3679  *   0 - successful
3680  *   1 - failed
3681  **/
3682 int
3683 lpfc_online(struct lpfc_hba *phba)
3684 {
3685 	struct lpfc_vport *vport;
3686 	struct lpfc_vport **vports;
3687 	int i, error = 0;
3688 	bool vpis_cleared = false;
3689 
3690 	if (!phba)
3691 		return 0;
3692 	vport = phba->pport;
3693 
3694 	if (!(vport->fc_flag & FC_OFFLINE_MODE))
3695 		return 0;
3696 
3697 	lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
3698 			"0458 Bring Adapter online\n");
3699 
3700 	lpfc_block_mgmt_io(phba, LPFC_MBX_WAIT);
3701 
3702 	if (phba->sli_rev == LPFC_SLI_REV4) {
3703 		if (lpfc_sli4_hba_setup(phba)) { /* Initialize SLI4 HBA */
3704 			lpfc_unblock_mgmt_io(phba);
3705 			return 1;
3706 		}
3707 		spin_lock_irq(&phba->hbalock);
3708 		if (!phba->sli4_hba.max_cfg_param.vpi_used)
3709 			vpis_cleared = true;
3710 		spin_unlock_irq(&phba->hbalock);
3711 
3712 		/* Reestablish the local initiator port.
3713 		 * The offline process destroyed the previous lport.
3714 		 */
3715 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME &&
3716 				!phba->nvmet_support) {
3717 			error = lpfc_nvme_create_localport(phba->pport);
3718 			if (error)
3719 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3720 					"6132 NVME restore reg failed "
3721 					"on nvmei error x%x\n", error);
3722 		}
3723 	} else {
3724 		lpfc_sli_queue_init(phba);
3725 		if (lpfc_sli_hba_setup(phba)) {	/* Initialize SLI2/SLI3 HBA */
3726 			lpfc_unblock_mgmt_io(phba);
3727 			return 1;
3728 		}
3729 	}
3730 
3731 	vports = lpfc_create_vport_work_array(phba);
3732 	if (vports != NULL) {
3733 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3734 			struct Scsi_Host *shost;
3735 			shost = lpfc_shost_from_vport(vports[i]);
3736 			spin_lock_irq(shost->host_lock);
3737 			vports[i]->fc_flag &= ~FC_OFFLINE_MODE;
3738 			if (phba->sli3_options & LPFC_SLI3_NPIV_ENABLED)
3739 				vports[i]->fc_flag |= FC_VPORT_NEEDS_REG_VPI;
3740 			if (phba->sli_rev == LPFC_SLI_REV4) {
3741 				vports[i]->fc_flag |= FC_VPORT_NEEDS_INIT_VPI;
3742 				if ((vpis_cleared) &&
3743 				    (vports[i]->port_type !=
3744 					LPFC_PHYSICAL_PORT))
3745 					vports[i]->vpi = 0;
3746 			}
3747 			spin_unlock_irq(shost->host_lock);
3748 		}
3749 	}
3750 	lpfc_destroy_vport_work_array(phba, vports);
3751 
3752 	if (phba->cfg_xri_rebalancing)
3753 		lpfc_create_multixri_pools(phba);
3754 
3755 	lpfc_cpuhp_add(phba);
3756 
3757 	lpfc_unblock_mgmt_io(phba);
3758 	return 0;
3759 }
3760 
3761 /**
3762  * lpfc_unblock_mgmt_io - Mark a HBA's management interface to be not blocked
3763  * @phba: pointer to lpfc hba data structure.
3764  *
3765  * This routine marks a HBA's management interface as not blocked. Once the
3766  * HBA's management interface is marked as not blocked, all the user space
3767  * access to the HBA, whether they are from sysfs interface or libdfc
3768  * interface will be allowed. The HBA is set to block the management interface
3769  * when the driver prepares the HBA interface for online or offline and then
3770  * set to unblock the management interface afterwards.
3771  **/
3772 void
3773 lpfc_unblock_mgmt_io(struct lpfc_hba * phba)
3774 {
3775 	unsigned long iflag;
3776 
3777 	spin_lock_irqsave(&phba->hbalock, iflag);
3778 	phba->sli.sli_flag &= ~LPFC_BLOCK_MGMT_IO;
3779 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3780 }
3781 
3782 /**
3783  * lpfc_offline_prep - Prepare a HBA to be brought offline
3784  * @phba: pointer to lpfc hba data structure.
3785  * @mbx_action: flag for mailbox shutdown action.
3786  *
3787  * This routine is invoked to prepare a HBA to be brought offline. It performs
3788  * unregistration login to all the nodes on all vports and flushes the mailbox
3789  * queue to make it ready to be brought offline.
3790  **/
3791 void
3792 lpfc_offline_prep(struct lpfc_hba *phba, int mbx_action)
3793 {
3794 	struct lpfc_vport *vport = phba->pport;
3795 	struct lpfc_nodelist  *ndlp, *next_ndlp;
3796 	struct lpfc_vport **vports;
3797 	struct Scsi_Host *shost;
3798 	int i;
3799 	int offline;
3800 	bool hba_pci_err;
3801 
3802 	if (vport->fc_flag & FC_OFFLINE_MODE)
3803 		return;
3804 
3805 	lpfc_block_mgmt_io(phba, mbx_action);
3806 
3807 	lpfc_linkdown(phba);
3808 
3809 	offline =  pci_channel_offline(phba->pcidev);
3810 	hba_pci_err = test_bit(HBA_PCI_ERR, &phba->bit_flags);
3811 
3812 	/* Issue an unreg_login to all nodes on all vports */
3813 	vports = lpfc_create_vport_work_array(phba);
3814 	if (vports != NULL) {
3815 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3816 			if (vports[i]->load_flag & FC_UNLOADING)
3817 				continue;
3818 			shost = lpfc_shost_from_vport(vports[i]);
3819 			spin_lock_irq(shost->host_lock);
3820 			vports[i]->vpi_state &= ~LPFC_VPI_REGISTERED;
3821 			vports[i]->fc_flag |= FC_VPORT_NEEDS_REG_VPI;
3822 			vports[i]->fc_flag &= ~FC_VFI_REGISTERED;
3823 			spin_unlock_irq(shost->host_lock);
3824 
3825 			shost =	lpfc_shost_from_vport(vports[i]);
3826 			list_for_each_entry_safe(ndlp, next_ndlp,
3827 						 &vports[i]->fc_nodes,
3828 						 nlp_listp) {
3829 
3830 				spin_lock_irq(&ndlp->lock);
3831 				ndlp->nlp_flag &= ~NLP_NPR_ADISC;
3832 				spin_unlock_irq(&ndlp->lock);
3833 
3834 				if (offline || hba_pci_err) {
3835 					spin_lock_irq(&ndlp->lock);
3836 					ndlp->nlp_flag &= ~(NLP_UNREG_INP |
3837 							    NLP_RPI_REGISTERED);
3838 					spin_unlock_irq(&ndlp->lock);
3839 					if (phba->sli_rev == LPFC_SLI_REV4)
3840 						lpfc_sli_rpi_release(vports[i],
3841 								     ndlp);
3842 				} else {
3843 					lpfc_unreg_rpi(vports[i], ndlp);
3844 				}
3845 				/*
3846 				 * Whenever an SLI4 port goes offline, free the
3847 				 * RPI. Get a new RPI when the adapter port
3848 				 * comes back online.
3849 				 */
3850 				if (phba->sli_rev == LPFC_SLI_REV4) {
3851 					lpfc_printf_vlog(vports[i], KERN_INFO,
3852 						 LOG_NODE | LOG_DISCOVERY,
3853 						 "0011 Free RPI x%x on "
3854 						 "ndlp: x%px did x%x\n",
3855 						 ndlp->nlp_rpi, ndlp,
3856 						 ndlp->nlp_DID);
3857 					lpfc_sli4_free_rpi(phba, ndlp->nlp_rpi);
3858 					ndlp->nlp_rpi = LPFC_RPI_ALLOC_ERROR;
3859 				}
3860 
3861 				if (ndlp->nlp_type & NLP_FABRIC) {
3862 					lpfc_disc_state_machine(vports[i], ndlp,
3863 						NULL, NLP_EVT_DEVICE_RECOVERY);
3864 
3865 					/* Don't remove the node unless the node
3866 					 * has been unregistered with the
3867 					 * transport, and we're not in recovery
3868 					 * before dev_loss_tmo triggered.
3869 					 * Otherwise, let dev_loss take care of
3870 					 * the node.
3871 					 */
3872 					if (!(ndlp->save_flags &
3873 					      NLP_IN_RECOV_POST_DEV_LOSS) &&
3874 					    !(ndlp->fc4_xpt_flags &
3875 					      (NVME_XPT_REGD | SCSI_XPT_REGD)))
3876 						lpfc_disc_state_machine
3877 							(vports[i], ndlp,
3878 							 NULL,
3879 							 NLP_EVT_DEVICE_RM);
3880 				}
3881 			}
3882 		}
3883 	}
3884 	lpfc_destroy_vport_work_array(phba, vports);
3885 
3886 	lpfc_sli_mbox_sys_shutdown(phba, mbx_action);
3887 
3888 	if (phba->wq)
3889 		flush_workqueue(phba->wq);
3890 }
3891 
3892 /**
3893  * lpfc_offline - Bring a HBA offline
3894  * @phba: pointer to lpfc hba data structure.
3895  *
3896  * This routine actually brings a HBA offline. It stops all the timers
3897  * associated with the HBA, brings down the SLI layer, and eventually
3898  * marks the HBA as in offline state for the upper layer protocol.
3899  **/
3900 void
3901 lpfc_offline(struct lpfc_hba *phba)
3902 {
3903 	struct Scsi_Host  *shost;
3904 	struct lpfc_vport **vports;
3905 	int i;
3906 
3907 	if (phba->pport->fc_flag & FC_OFFLINE_MODE)
3908 		return;
3909 
3910 	/* stop port and all timers associated with this hba */
3911 	lpfc_stop_port(phba);
3912 
3913 	/* Tear down the local and target port registrations.  The
3914 	 * nvme transports need to cleanup.
3915 	 */
3916 	lpfc_nvmet_destroy_targetport(phba);
3917 	lpfc_nvme_destroy_localport(phba->pport);
3918 
3919 	vports = lpfc_create_vport_work_array(phba);
3920 	if (vports != NULL)
3921 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++)
3922 			lpfc_stop_vport_timers(vports[i]);
3923 	lpfc_destroy_vport_work_array(phba, vports);
3924 	lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
3925 			"0460 Bring Adapter offline\n");
3926 	/* Bring down the SLI Layer and cleanup.  The HBA is offline
3927 	   now.  */
3928 	lpfc_sli_hba_down(phba);
3929 	spin_lock_irq(&phba->hbalock);
3930 	phba->work_ha = 0;
3931 	spin_unlock_irq(&phba->hbalock);
3932 	vports = lpfc_create_vport_work_array(phba);
3933 	if (vports != NULL)
3934 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3935 			shost = lpfc_shost_from_vport(vports[i]);
3936 			spin_lock_irq(shost->host_lock);
3937 			vports[i]->work_port_events = 0;
3938 			vports[i]->fc_flag |= FC_OFFLINE_MODE;
3939 			spin_unlock_irq(shost->host_lock);
3940 		}
3941 	lpfc_destroy_vport_work_array(phba, vports);
3942 	/* If OFFLINE flag is clear (i.e. unloading), cpuhp removal is handled
3943 	 * in hba_unset
3944 	 */
3945 	if (phba->pport->fc_flag & FC_OFFLINE_MODE)
3946 		__lpfc_cpuhp_remove(phba);
3947 
3948 	if (phba->cfg_xri_rebalancing)
3949 		lpfc_destroy_multixri_pools(phba);
3950 }
3951 
3952 /**
3953  * lpfc_scsi_free - Free all the SCSI buffers and IOCBs from driver lists
3954  * @phba: pointer to lpfc hba data structure.
3955  *
3956  * This routine is to free all the SCSI buffers and IOCBs from the driver
3957  * list back to kernel. It is called from lpfc_pci_remove_one to free
3958  * the internal resources before the device is removed from the system.
3959  **/
3960 static void
3961 lpfc_scsi_free(struct lpfc_hba *phba)
3962 {
3963 	struct lpfc_io_buf *sb, *sb_next;
3964 
3965 	if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP))
3966 		return;
3967 
3968 	spin_lock_irq(&phba->hbalock);
3969 
3970 	/* Release all the lpfc_scsi_bufs maintained by this host. */
3971 
3972 	spin_lock(&phba->scsi_buf_list_put_lock);
3973 	list_for_each_entry_safe(sb, sb_next, &phba->lpfc_scsi_buf_list_put,
3974 				 list) {
3975 		list_del(&sb->list);
3976 		dma_pool_free(phba->lpfc_sg_dma_buf_pool, sb->data,
3977 			      sb->dma_handle);
3978 		kfree(sb);
3979 		phba->total_scsi_bufs--;
3980 	}
3981 	spin_unlock(&phba->scsi_buf_list_put_lock);
3982 
3983 	spin_lock(&phba->scsi_buf_list_get_lock);
3984 	list_for_each_entry_safe(sb, sb_next, &phba->lpfc_scsi_buf_list_get,
3985 				 list) {
3986 		list_del(&sb->list);
3987 		dma_pool_free(phba->lpfc_sg_dma_buf_pool, sb->data,
3988 			      sb->dma_handle);
3989 		kfree(sb);
3990 		phba->total_scsi_bufs--;
3991 	}
3992 	spin_unlock(&phba->scsi_buf_list_get_lock);
3993 	spin_unlock_irq(&phba->hbalock);
3994 }
3995 
3996 /**
3997  * lpfc_io_free - Free all the IO buffers and IOCBs from driver lists
3998  * @phba: pointer to lpfc hba data structure.
3999  *
4000  * This routine is to free all the IO buffers and IOCBs from the driver
4001  * list back to kernel. It is called from lpfc_pci_remove_one to free
4002  * the internal resources before the device is removed from the system.
4003  **/
4004 void
4005 lpfc_io_free(struct lpfc_hba *phba)
4006 {
4007 	struct lpfc_io_buf *lpfc_ncmd, *lpfc_ncmd_next;
4008 	struct lpfc_sli4_hdw_queue *qp;
4009 	int idx;
4010 
4011 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
4012 		qp = &phba->sli4_hba.hdwq[idx];
4013 		/* Release all the lpfc_nvme_bufs maintained by this host. */
4014 		spin_lock(&qp->io_buf_list_put_lock);
4015 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
4016 					 &qp->lpfc_io_buf_list_put,
4017 					 list) {
4018 			list_del(&lpfc_ncmd->list);
4019 			qp->put_io_bufs--;
4020 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4021 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4022 			if (phba->cfg_xpsgl && !phba->nvmet_support)
4023 				lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
4024 			lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
4025 			kfree(lpfc_ncmd);
4026 			qp->total_io_bufs--;
4027 		}
4028 		spin_unlock(&qp->io_buf_list_put_lock);
4029 
4030 		spin_lock(&qp->io_buf_list_get_lock);
4031 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
4032 					 &qp->lpfc_io_buf_list_get,
4033 					 list) {
4034 			list_del(&lpfc_ncmd->list);
4035 			qp->get_io_bufs--;
4036 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4037 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4038 			if (phba->cfg_xpsgl && !phba->nvmet_support)
4039 				lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
4040 			lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
4041 			kfree(lpfc_ncmd);
4042 			qp->total_io_bufs--;
4043 		}
4044 		spin_unlock(&qp->io_buf_list_get_lock);
4045 	}
4046 }
4047 
4048 /**
4049  * lpfc_sli4_els_sgl_update - update ELS xri-sgl sizing and mapping
4050  * @phba: pointer to lpfc hba data structure.
4051  *
4052  * This routine first calculates the sizes of the current els and allocated
4053  * scsi sgl lists, and then goes through all sgls to updates the physical
4054  * XRIs assigned due to port function reset. During port initialization, the
4055  * current els and allocated scsi sgl lists are 0s.
4056  *
4057  * Return codes
4058  *   0 - successful (for now, it always returns 0)
4059  **/
4060 int
4061 lpfc_sli4_els_sgl_update(struct lpfc_hba *phba)
4062 {
4063 	struct lpfc_sglq *sglq_entry = NULL, *sglq_entry_next = NULL;
4064 	uint16_t i, lxri, xri_cnt, els_xri_cnt;
4065 	LIST_HEAD(els_sgl_list);
4066 	int rc;
4067 
4068 	/*
4069 	 * update on pci function's els xri-sgl list
4070 	 */
4071 	els_xri_cnt = lpfc_sli4_get_els_iocb_cnt(phba);
4072 
4073 	if (els_xri_cnt > phba->sli4_hba.els_xri_cnt) {
4074 		/* els xri-sgl expanded */
4075 		xri_cnt = els_xri_cnt - phba->sli4_hba.els_xri_cnt;
4076 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4077 				"3157 ELS xri-sgl count increased from "
4078 				"%d to %d\n", phba->sli4_hba.els_xri_cnt,
4079 				els_xri_cnt);
4080 		/* allocate the additional els sgls */
4081 		for (i = 0; i < xri_cnt; i++) {
4082 			sglq_entry = kzalloc(sizeof(struct lpfc_sglq),
4083 					     GFP_KERNEL);
4084 			if (sglq_entry == NULL) {
4085 				lpfc_printf_log(phba, KERN_ERR,
4086 						LOG_TRACE_EVENT,
4087 						"2562 Failure to allocate an "
4088 						"ELS sgl entry:%d\n", i);
4089 				rc = -ENOMEM;
4090 				goto out_free_mem;
4091 			}
4092 			sglq_entry->buff_type = GEN_BUFF_TYPE;
4093 			sglq_entry->virt = lpfc_mbuf_alloc(phba, 0,
4094 							   &sglq_entry->phys);
4095 			if (sglq_entry->virt == NULL) {
4096 				kfree(sglq_entry);
4097 				lpfc_printf_log(phba, KERN_ERR,
4098 						LOG_TRACE_EVENT,
4099 						"2563 Failure to allocate an "
4100 						"ELS mbuf:%d\n", i);
4101 				rc = -ENOMEM;
4102 				goto out_free_mem;
4103 			}
4104 			sglq_entry->sgl = sglq_entry->virt;
4105 			memset(sglq_entry->sgl, 0, LPFC_BPL_SIZE);
4106 			sglq_entry->state = SGL_FREED;
4107 			list_add_tail(&sglq_entry->list, &els_sgl_list);
4108 		}
4109 		spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
4110 		list_splice_init(&els_sgl_list,
4111 				 &phba->sli4_hba.lpfc_els_sgl_list);
4112 		spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
4113 	} else if (els_xri_cnt < phba->sli4_hba.els_xri_cnt) {
4114 		/* els xri-sgl shrinked */
4115 		xri_cnt = phba->sli4_hba.els_xri_cnt - els_xri_cnt;
4116 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4117 				"3158 ELS xri-sgl count decreased from "
4118 				"%d to %d\n", phba->sli4_hba.els_xri_cnt,
4119 				els_xri_cnt);
4120 		spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
4121 		list_splice_init(&phba->sli4_hba.lpfc_els_sgl_list,
4122 				 &els_sgl_list);
4123 		/* release extra els sgls from list */
4124 		for (i = 0; i < xri_cnt; i++) {
4125 			list_remove_head(&els_sgl_list,
4126 					 sglq_entry, struct lpfc_sglq, list);
4127 			if (sglq_entry) {
4128 				__lpfc_mbuf_free(phba, sglq_entry->virt,
4129 						 sglq_entry->phys);
4130 				kfree(sglq_entry);
4131 			}
4132 		}
4133 		list_splice_init(&els_sgl_list,
4134 				 &phba->sli4_hba.lpfc_els_sgl_list);
4135 		spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
4136 	} else
4137 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4138 				"3163 ELS xri-sgl count unchanged: %d\n",
4139 				els_xri_cnt);
4140 	phba->sli4_hba.els_xri_cnt = els_xri_cnt;
4141 
4142 	/* update xris to els sgls on the list */
4143 	sglq_entry = NULL;
4144 	sglq_entry_next = NULL;
4145 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
4146 				 &phba->sli4_hba.lpfc_els_sgl_list, list) {
4147 		lxri = lpfc_sli4_next_xritag(phba);
4148 		if (lxri == NO_XRI) {
4149 			lpfc_printf_log(phba, KERN_ERR,
4150 					LOG_TRACE_EVENT,
4151 					"2400 Failed to allocate xri for "
4152 					"ELS sgl\n");
4153 			rc = -ENOMEM;
4154 			goto out_free_mem;
4155 		}
4156 		sglq_entry->sli4_lxritag = lxri;
4157 		sglq_entry->sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4158 	}
4159 	return 0;
4160 
4161 out_free_mem:
4162 	lpfc_free_els_sgl_list(phba);
4163 	return rc;
4164 }
4165 
4166 /**
4167  * lpfc_sli4_nvmet_sgl_update - update xri-sgl sizing and mapping
4168  * @phba: pointer to lpfc hba data structure.
4169  *
4170  * This routine first calculates the sizes of the current els and allocated
4171  * scsi sgl lists, and then goes through all sgls to updates the physical
4172  * XRIs assigned due to port function reset. During port initialization, the
4173  * current els and allocated scsi sgl lists are 0s.
4174  *
4175  * Return codes
4176  *   0 - successful (for now, it always returns 0)
4177  **/
4178 int
4179 lpfc_sli4_nvmet_sgl_update(struct lpfc_hba *phba)
4180 {
4181 	struct lpfc_sglq *sglq_entry = NULL, *sglq_entry_next = NULL;
4182 	uint16_t i, lxri, xri_cnt, els_xri_cnt;
4183 	uint16_t nvmet_xri_cnt;
4184 	LIST_HEAD(nvmet_sgl_list);
4185 	int rc;
4186 
4187 	/*
4188 	 * update on pci function's nvmet xri-sgl list
4189 	 */
4190 	els_xri_cnt = lpfc_sli4_get_els_iocb_cnt(phba);
4191 
4192 	/* For NVMET, ALL remaining XRIs are dedicated for IO processing */
4193 	nvmet_xri_cnt = phba->sli4_hba.max_cfg_param.max_xri - els_xri_cnt;
4194 	if (nvmet_xri_cnt > phba->sli4_hba.nvmet_xri_cnt) {
4195 		/* els xri-sgl expanded */
4196 		xri_cnt = nvmet_xri_cnt - phba->sli4_hba.nvmet_xri_cnt;
4197 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4198 				"6302 NVMET xri-sgl cnt grew from %d to %d\n",
4199 				phba->sli4_hba.nvmet_xri_cnt, nvmet_xri_cnt);
4200 		/* allocate the additional nvmet sgls */
4201 		for (i = 0; i < xri_cnt; i++) {
4202 			sglq_entry = kzalloc(sizeof(struct lpfc_sglq),
4203 					     GFP_KERNEL);
4204 			if (sglq_entry == NULL) {
4205 				lpfc_printf_log(phba, KERN_ERR,
4206 						LOG_TRACE_EVENT,
4207 						"6303 Failure to allocate an "
4208 						"NVMET sgl entry:%d\n", i);
4209 				rc = -ENOMEM;
4210 				goto out_free_mem;
4211 			}
4212 			sglq_entry->buff_type = NVMET_BUFF_TYPE;
4213 			sglq_entry->virt = lpfc_nvmet_buf_alloc(phba, 0,
4214 							   &sglq_entry->phys);
4215 			if (sglq_entry->virt == NULL) {
4216 				kfree(sglq_entry);
4217 				lpfc_printf_log(phba, KERN_ERR,
4218 						LOG_TRACE_EVENT,
4219 						"6304 Failure to allocate an "
4220 						"NVMET buf:%d\n", i);
4221 				rc = -ENOMEM;
4222 				goto out_free_mem;
4223 			}
4224 			sglq_entry->sgl = sglq_entry->virt;
4225 			memset(sglq_entry->sgl, 0,
4226 			       phba->cfg_sg_dma_buf_size);
4227 			sglq_entry->state = SGL_FREED;
4228 			list_add_tail(&sglq_entry->list, &nvmet_sgl_list);
4229 		}
4230 		spin_lock_irq(&phba->hbalock);
4231 		spin_lock(&phba->sli4_hba.sgl_list_lock);
4232 		list_splice_init(&nvmet_sgl_list,
4233 				 &phba->sli4_hba.lpfc_nvmet_sgl_list);
4234 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
4235 		spin_unlock_irq(&phba->hbalock);
4236 	} else if (nvmet_xri_cnt < phba->sli4_hba.nvmet_xri_cnt) {
4237 		/* nvmet xri-sgl shrunk */
4238 		xri_cnt = phba->sli4_hba.nvmet_xri_cnt - nvmet_xri_cnt;
4239 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4240 				"6305 NVMET xri-sgl count decreased from "
4241 				"%d to %d\n", phba->sli4_hba.nvmet_xri_cnt,
4242 				nvmet_xri_cnt);
4243 		spin_lock_irq(&phba->hbalock);
4244 		spin_lock(&phba->sli4_hba.sgl_list_lock);
4245 		list_splice_init(&phba->sli4_hba.lpfc_nvmet_sgl_list,
4246 				 &nvmet_sgl_list);
4247 		/* release extra nvmet sgls from list */
4248 		for (i = 0; i < xri_cnt; i++) {
4249 			list_remove_head(&nvmet_sgl_list,
4250 					 sglq_entry, struct lpfc_sglq, list);
4251 			if (sglq_entry) {
4252 				lpfc_nvmet_buf_free(phba, sglq_entry->virt,
4253 						    sglq_entry->phys);
4254 				kfree(sglq_entry);
4255 			}
4256 		}
4257 		list_splice_init(&nvmet_sgl_list,
4258 				 &phba->sli4_hba.lpfc_nvmet_sgl_list);
4259 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
4260 		spin_unlock_irq(&phba->hbalock);
4261 	} else
4262 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4263 				"6306 NVMET xri-sgl count unchanged: %d\n",
4264 				nvmet_xri_cnt);
4265 	phba->sli4_hba.nvmet_xri_cnt = nvmet_xri_cnt;
4266 
4267 	/* update xris to nvmet sgls on the list */
4268 	sglq_entry = NULL;
4269 	sglq_entry_next = NULL;
4270 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
4271 				 &phba->sli4_hba.lpfc_nvmet_sgl_list, list) {
4272 		lxri = lpfc_sli4_next_xritag(phba);
4273 		if (lxri == NO_XRI) {
4274 			lpfc_printf_log(phba, KERN_ERR,
4275 					LOG_TRACE_EVENT,
4276 					"6307 Failed to allocate xri for "
4277 					"NVMET sgl\n");
4278 			rc = -ENOMEM;
4279 			goto out_free_mem;
4280 		}
4281 		sglq_entry->sli4_lxritag = lxri;
4282 		sglq_entry->sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4283 	}
4284 	return 0;
4285 
4286 out_free_mem:
4287 	lpfc_free_nvmet_sgl_list(phba);
4288 	return rc;
4289 }
4290 
4291 int
4292 lpfc_io_buf_flush(struct lpfc_hba *phba, struct list_head *cbuf)
4293 {
4294 	LIST_HEAD(blist);
4295 	struct lpfc_sli4_hdw_queue *qp;
4296 	struct lpfc_io_buf *lpfc_cmd;
4297 	struct lpfc_io_buf *iobufp, *prev_iobufp;
4298 	int idx, cnt, xri, inserted;
4299 
4300 	cnt = 0;
4301 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
4302 		qp = &phba->sli4_hba.hdwq[idx];
4303 		spin_lock_irq(&qp->io_buf_list_get_lock);
4304 		spin_lock(&qp->io_buf_list_put_lock);
4305 
4306 		/* Take everything off the get and put lists */
4307 		list_splice_init(&qp->lpfc_io_buf_list_get, &blist);
4308 		list_splice(&qp->lpfc_io_buf_list_put, &blist);
4309 		INIT_LIST_HEAD(&qp->lpfc_io_buf_list_get);
4310 		INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
4311 		cnt += qp->get_io_bufs + qp->put_io_bufs;
4312 		qp->get_io_bufs = 0;
4313 		qp->put_io_bufs = 0;
4314 		qp->total_io_bufs = 0;
4315 		spin_unlock(&qp->io_buf_list_put_lock);
4316 		spin_unlock_irq(&qp->io_buf_list_get_lock);
4317 	}
4318 
4319 	/*
4320 	 * Take IO buffers off blist and put on cbuf sorted by XRI.
4321 	 * This is because POST_SGL takes a sequential range of XRIs
4322 	 * to post to the firmware.
4323 	 */
4324 	for (idx = 0; idx < cnt; idx++) {
4325 		list_remove_head(&blist, lpfc_cmd, struct lpfc_io_buf, list);
4326 		if (!lpfc_cmd)
4327 			return cnt;
4328 		if (idx == 0) {
4329 			list_add_tail(&lpfc_cmd->list, cbuf);
4330 			continue;
4331 		}
4332 		xri = lpfc_cmd->cur_iocbq.sli4_xritag;
4333 		inserted = 0;
4334 		prev_iobufp = NULL;
4335 		list_for_each_entry(iobufp, cbuf, list) {
4336 			if (xri < iobufp->cur_iocbq.sli4_xritag) {
4337 				if (prev_iobufp)
4338 					list_add(&lpfc_cmd->list,
4339 						 &prev_iobufp->list);
4340 				else
4341 					list_add(&lpfc_cmd->list, cbuf);
4342 				inserted = 1;
4343 				break;
4344 			}
4345 			prev_iobufp = iobufp;
4346 		}
4347 		if (!inserted)
4348 			list_add_tail(&lpfc_cmd->list, cbuf);
4349 	}
4350 	return cnt;
4351 }
4352 
4353 int
4354 lpfc_io_buf_replenish(struct lpfc_hba *phba, struct list_head *cbuf)
4355 {
4356 	struct lpfc_sli4_hdw_queue *qp;
4357 	struct lpfc_io_buf *lpfc_cmd;
4358 	int idx, cnt;
4359 
4360 	qp = phba->sli4_hba.hdwq;
4361 	cnt = 0;
4362 	while (!list_empty(cbuf)) {
4363 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
4364 			list_remove_head(cbuf, lpfc_cmd,
4365 					 struct lpfc_io_buf, list);
4366 			if (!lpfc_cmd)
4367 				return cnt;
4368 			cnt++;
4369 			qp = &phba->sli4_hba.hdwq[idx];
4370 			lpfc_cmd->hdwq_no = idx;
4371 			lpfc_cmd->hdwq = qp;
4372 			lpfc_cmd->cur_iocbq.cmd_cmpl = NULL;
4373 			spin_lock(&qp->io_buf_list_put_lock);
4374 			list_add_tail(&lpfc_cmd->list,
4375 				      &qp->lpfc_io_buf_list_put);
4376 			qp->put_io_bufs++;
4377 			qp->total_io_bufs++;
4378 			spin_unlock(&qp->io_buf_list_put_lock);
4379 		}
4380 	}
4381 	return cnt;
4382 }
4383 
4384 /**
4385  * lpfc_sli4_io_sgl_update - update xri-sgl sizing and mapping
4386  * @phba: pointer to lpfc hba data structure.
4387  *
4388  * This routine first calculates the sizes of the current els and allocated
4389  * scsi sgl lists, and then goes through all sgls to updates the physical
4390  * XRIs assigned due to port function reset. During port initialization, the
4391  * current els and allocated scsi sgl lists are 0s.
4392  *
4393  * Return codes
4394  *   0 - successful (for now, it always returns 0)
4395  **/
4396 int
4397 lpfc_sli4_io_sgl_update(struct lpfc_hba *phba)
4398 {
4399 	struct lpfc_io_buf *lpfc_ncmd = NULL, *lpfc_ncmd_next = NULL;
4400 	uint16_t i, lxri, els_xri_cnt;
4401 	uint16_t io_xri_cnt, io_xri_max;
4402 	LIST_HEAD(io_sgl_list);
4403 	int rc, cnt;
4404 
4405 	/*
4406 	 * update on pci function's allocated nvme xri-sgl list
4407 	 */
4408 
4409 	/* maximum number of xris available for nvme buffers */
4410 	els_xri_cnt = lpfc_sli4_get_els_iocb_cnt(phba);
4411 	io_xri_max = phba->sli4_hba.max_cfg_param.max_xri - els_xri_cnt;
4412 	phba->sli4_hba.io_xri_max = io_xri_max;
4413 
4414 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4415 			"6074 Current allocated XRI sgl count:%d, "
4416 			"maximum XRI count:%d els_xri_cnt:%d\n\n",
4417 			phba->sli4_hba.io_xri_cnt,
4418 			phba->sli4_hba.io_xri_max,
4419 			els_xri_cnt);
4420 
4421 	cnt = lpfc_io_buf_flush(phba, &io_sgl_list);
4422 
4423 	if (phba->sli4_hba.io_xri_cnt > phba->sli4_hba.io_xri_max) {
4424 		/* max nvme xri shrunk below the allocated nvme buffers */
4425 		io_xri_cnt = phba->sli4_hba.io_xri_cnt -
4426 					phba->sli4_hba.io_xri_max;
4427 		/* release the extra allocated nvme buffers */
4428 		for (i = 0; i < io_xri_cnt; i++) {
4429 			list_remove_head(&io_sgl_list, lpfc_ncmd,
4430 					 struct lpfc_io_buf, list);
4431 			if (lpfc_ncmd) {
4432 				dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4433 					      lpfc_ncmd->data,
4434 					      lpfc_ncmd->dma_handle);
4435 				kfree(lpfc_ncmd);
4436 			}
4437 		}
4438 		phba->sli4_hba.io_xri_cnt -= io_xri_cnt;
4439 	}
4440 
4441 	/* update xris associated to remaining allocated nvme buffers */
4442 	lpfc_ncmd = NULL;
4443 	lpfc_ncmd_next = NULL;
4444 	phba->sli4_hba.io_xri_cnt = cnt;
4445 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
4446 				 &io_sgl_list, list) {
4447 		lxri = lpfc_sli4_next_xritag(phba);
4448 		if (lxri == NO_XRI) {
4449 			lpfc_printf_log(phba, KERN_ERR,
4450 					LOG_TRACE_EVENT,
4451 					"6075 Failed to allocate xri for "
4452 					"nvme buffer\n");
4453 			rc = -ENOMEM;
4454 			goto out_free_mem;
4455 		}
4456 		lpfc_ncmd->cur_iocbq.sli4_lxritag = lxri;
4457 		lpfc_ncmd->cur_iocbq.sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4458 	}
4459 	cnt = lpfc_io_buf_replenish(phba, &io_sgl_list);
4460 	return 0;
4461 
4462 out_free_mem:
4463 	lpfc_io_free(phba);
4464 	return rc;
4465 }
4466 
4467 /**
4468  * lpfc_new_io_buf - IO buffer allocator for HBA with SLI4 IF spec
4469  * @phba: Pointer to lpfc hba data structure.
4470  * @num_to_alloc: The requested number of buffers to allocate.
4471  *
4472  * This routine allocates nvme buffers for device with SLI-4 interface spec,
4473  * the nvme buffer contains all the necessary information needed to initiate
4474  * an I/O. After allocating up to @num_to_allocate IO buffers and put
4475  * them on a list, it post them to the port by using SGL block post.
4476  *
4477  * Return codes:
4478  *   int - number of IO buffers that were allocated and posted.
4479  *   0 = failure, less than num_to_alloc is a partial failure.
4480  **/
4481 int
4482 lpfc_new_io_buf(struct lpfc_hba *phba, int num_to_alloc)
4483 {
4484 	struct lpfc_io_buf *lpfc_ncmd;
4485 	struct lpfc_iocbq *pwqeq;
4486 	uint16_t iotag, lxri = 0;
4487 	int bcnt, num_posted;
4488 	LIST_HEAD(prep_nblist);
4489 	LIST_HEAD(post_nblist);
4490 	LIST_HEAD(nvme_nblist);
4491 
4492 	phba->sli4_hba.io_xri_cnt = 0;
4493 	for (bcnt = 0; bcnt < num_to_alloc; bcnt++) {
4494 		lpfc_ncmd = kzalloc(sizeof(*lpfc_ncmd), GFP_KERNEL);
4495 		if (!lpfc_ncmd)
4496 			break;
4497 		/*
4498 		 * Get memory from the pci pool to map the virt space to
4499 		 * pci bus space for an I/O. The DMA buffer includes the
4500 		 * number of SGE's necessary to support the sg_tablesize.
4501 		 */
4502 		lpfc_ncmd->data = dma_pool_zalloc(phba->lpfc_sg_dma_buf_pool,
4503 						  GFP_KERNEL,
4504 						  &lpfc_ncmd->dma_handle);
4505 		if (!lpfc_ncmd->data) {
4506 			kfree(lpfc_ncmd);
4507 			break;
4508 		}
4509 
4510 		if (phba->cfg_xpsgl && !phba->nvmet_support) {
4511 			INIT_LIST_HEAD(&lpfc_ncmd->dma_sgl_xtra_list);
4512 		} else {
4513 			/*
4514 			 * 4K Page alignment is CRITICAL to BlockGuard, double
4515 			 * check to be sure.
4516 			 */
4517 			if ((phba->sli3_options & LPFC_SLI3_BG_ENABLED) &&
4518 			    (((unsigned long)(lpfc_ncmd->data) &
4519 			    (unsigned long)(SLI4_PAGE_SIZE - 1)) != 0)) {
4520 				lpfc_printf_log(phba, KERN_ERR,
4521 						LOG_TRACE_EVENT,
4522 						"3369 Memory alignment err: "
4523 						"addr=%lx\n",
4524 						(unsigned long)lpfc_ncmd->data);
4525 				dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4526 					      lpfc_ncmd->data,
4527 					      lpfc_ncmd->dma_handle);
4528 				kfree(lpfc_ncmd);
4529 				break;
4530 			}
4531 		}
4532 
4533 		INIT_LIST_HEAD(&lpfc_ncmd->dma_cmd_rsp_list);
4534 
4535 		lxri = lpfc_sli4_next_xritag(phba);
4536 		if (lxri == NO_XRI) {
4537 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4538 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4539 			kfree(lpfc_ncmd);
4540 			break;
4541 		}
4542 		pwqeq = &lpfc_ncmd->cur_iocbq;
4543 
4544 		/* Allocate iotag for lpfc_ncmd->cur_iocbq. */
4545 		iotag = lpfc_sli_next_iotag(phba, pwqeq);
4546 		if (iotag == 0) {
4547 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4548 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4549 			kfree(lpfc_ncmd);
4550 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4551 					"6121 Failed to allocate IOTAG for"
4552 					" XRI:0x%x\n", lxri);
4553 			lpfc_sli4_free_xri(phba, lxri);
4554 			break;
4555 		}
4556 		pwqeq->sli4_lxritag = lxri;
4557 		pwqeq->sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4558 
4559 		/* Initialize local short-hand pointers. */
4560 		lpfc_ncmd->dma_sgl = lpfc_ncmd->data;
4561 		lpfc_ncmd->dma_phys_sgl = lpfc_ncmd->dma_handle;
4562 		lpfc_ncmd->cur_iocbq.io_buf = lpfc_ncmd;
4563 		spin_lock_init(&lpfc_ncmd->buf_lock);
4564 
4565 		/* add the nvme buffer to a post list */
4566 		list_add_tail(&lpfc_ncmd->list, &post_nblist);
4567 		phba->sli4_hba.io_xri_cnt++;
4568 	}
4569 	lpfc_printf_log(phba, KERN_INFO, LOG_NVME,
4570 			"6114 Allocate %d out of %d requested new NVME "
4571 			"buffers of size x%zu bytes\n", bcnt, num_to_alloc,
4572 			sizeof(*lpfc_ncmd));
4573 
4574 
4575 	/* post the list of nvme buffer sgls to port if available */
4576 	if (!list_empty(&post_nblist))
4577 		num_posted = lpfc_sli4_post_io_sgl_list(
4578 				phba, &post_nblist, bcnt);
4579 	else
4580 		num_posted = 0;
4581 
4582 	return num_posted;
4583 }
4584 
4585 static uint64_t
4586 lpfc_get_wwpn(struct lpfc_hba *phba)
4587 {
4588 	uint64_t wwn;
4589 	int rc;
4590 	LPFC_MBOXQ_t *mboxq;
4591 	MAILBOX_t *mb;
4592 
4593 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
4594 						GFP_KERNEL);
4595 	if (!mboxq)
4596 		return (uint64_t)-1;
4597 
4598 	/* First get WWN of HBA instance */
4599 	lpfc_read_nv(phba, mboxq);
4600 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
4601 	if (rc != MBX_SUCCESS) {
4602 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4603 				"6019 Mailbox failed , mbxCmd x%x "
4604 				"READ_NV, mbxStatus x%x\n",
4605 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
4606 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
4607 		mempool_free(mboxq, phba->mbox_mem_pool);
4608 		return (uint64_t) -1;
4609 	}
4610 	mb = &mboxq->u.mb;
4611 	memcpy(&wwn, (char *)mb->un.varRDnvp.portname, sizeof(uint64_t));
4612 	/* wwn is WWPN of HBA instance */
4613 	mempool_free(mboxq, phba->mbox_mem_pool);
4614 	if (phba->sli_rev == LPFC_SLI_REV4)
4615 		return be64_to_cpu(wwn);
4616 	else
4617 		return rol64(wwn, 32);
4618 }
4619 
4620 static unsigned short lpfc_get_sg_tablesize(struct lpfc_hba *phba)
4621 {
4622 	if (phba->sli_rev == LPFC_SLI_REV4)
4623 		if (phba->cfg_xpsgl && !phba->nvmet_support)
4624 			return LPFC_MAX_SG_TABLESIZE;
4625 		else
4626 			return phba->cfg_scsi_seg_cnt;
4627 	else
4628 		return phba->cfg_sg_seg_cnt;
4629 }
4630 
4631 /**
4632  * lpfc_vmid_res_alloc - Allocates resources for VMID
4633  * @phba: pointer to lpfc hba data structure.
4634  * @vport: pointer to vport data structure
4635  *
4636  * This routine allocated the resources needed for the VMID.
4637  *
4638  * Return codes
4639  *	0 on Success
4640  *	Non-0 on Failure
4641  */
4642 static int
4643 lpfc_vmid_res_alloc(struct lpfc_hba *phba, struct lpfc_vport *vport)
4644 {
4645 	/* VMID feature is supported only on SLI4 */
4646 	if (phba->sli_rev == LPFC_SLI_REV3) {
4647 		phba->cfg_vmid_app_header = 0;
4648 		phba->cfg_vmid_priority_tagging = 0;
4649 	}
4650 
4651 	if (lpfc_is_vmid_enabled(phba)) {
4652 		vport->vmid =
4653 		    kcalloc(phba->cfg_max_vmid, sizeof(struct lpfc_vmid),
4654 			    GFP_KERNEL);
4655 		if (!vport->vmid)
4656 			return -ENOMEM;
4657 
4658 		rwlock_init(&vport->vmid_lock);
4659 
4660 		/* Set the VMID parameters for the vport */
4661 		vport->vmid_priority_tagging = phba->cfg_vmid_priority_tagging;
4662 		vport->vmid_inactivity_timeout =
4663 		    phba->cfg_vmid_inactivity_timeout;
4664 		vport->max_vmid = phba->cfg_max_vmid;
4665 		vport->cur_vmid_cnt = 0;
4666 
4667 		vport->vmid_priority_range = bitmap_zalloc
4668 			(LPFC_VMID_MAX_PRIORITY_RANGE, GFP_KERNEL);
4669 
4670 		if (!vport->vmid_priority_range) {
4671 			kfree(vport->vmid);
4672 			return -ENOMEM;
4673 		}
4674 
4675 		hash_init(vport->hash_table);
4676 	}
4677 	return 0;
4678 }
4679 
4680 /**
4681  * lpfc_create_port - Create an FC port
4682  * @phba: pointer to lpfc hba data structure.
4683  * @instance: a unique integer ID to this FC port.
4684  * @dev: pointer to the device data structure.
4685  *
4686  * This routine creates a FC port for the upper layer protocol. The FC port
4687  * can be created on top of either a physical port or a virtual port provided
4688  * by the HBA. This routine also allocates a SCSI host data structure (shost)
4689  * and associates the FC port created before adding the shost into the SCSI
4690  * layer.
4691  *
4692  * Return codes
4693  *   @vport - pointer to the virtual N_Port data structure.
4694  *   NULL - port create failed.
4695  **/
4696 struct lpfc_vport *
4697 lpfc_create_port(struct lpfc_hba *phba, int instance, struct device *dev)
4698 {
4699 	struct lpfc_vport *vport;
4700 	struct Scsi_Host  *shost = NULL;
4701 	struct scsi_host_template *template;
4702 	int error = 0;
4703 	int i;
4704 	uint64_t wwn;
4705 	bool use_no_reset_hba = false;
4706 	int rc;
4707 
4708 	if (lpfc_no_hba_reset_cnt) {
4709 		if (phba->sli_rev < LPFC_SLI_REV4 &&
4710 		    dev == &phba->pcidev->dev) {
4711 			/* Reset the port first */
4712 			lpfc_sli_brdrestart(phba);
4713 			rc = lpfc_sli_chipset_init(phba);
4714 			if (rc)
4715 				return NULL;
4716 		}
4717 		wwn = lpfc_get_wwpn(phba);
4718 	}
4719 
4720 	for (i = 0; i < lpfc_no_hba_reset_cnt; i++) {
4721 		if (wwn == lpfc_no_hba_reset[i]) {
4722 			lpfc_printf_log(phba, KERN_ERR,
4723 					LOG_TRACE_EVENT,
4724 					"6020 Setting use_no_reset port=%llx\n",
4725 					wwn);
4726 			use_no_reset_hba = true;
4727 			break;
4728 		}
4729 	}
4730 
4731 	/* Seed template for SCSI host registration */
4732 	if (dev == &phba->pcidev->dev) {
4733 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP) {
4734 			/* Seed physical port template */
4735 			template = &lpfc_template;
4736 
4737 			if (use_no_reset_hba)
4738 				/* template is for a no reset SCSI Host */
4739 				template->eh_host_reset_handler = NULL;
4740 
4741 			/* Seed updated value of sg_tablesize */
4742 			template->sg_tablesize = lpfc_get_sg_tablesize(phba);
4743 		} else {
4744 			/* NVMET is for physical port only */
4745 			template = &lpfc_template_nvme;
4746 		}
4747 	} else {
4748 		/* Seed vport template */
4749 		template = &lpfc_vport_template;
4750 
4751 		/* Seed updated value of sg_tablesize */
4752 		template->sg_tablesize = lpfc_get_sg_tablesize(phba);
4753 	}
4754 
4755 	shost = scsi_host_alloc(template, sizeof(struct lpfc_vport));
4756 	if (!shost)
4757 		goto out;
4758 
4759 	vport = (struct lpfc_vport *) shost->hostdata;
4760 	vport->phba = phba;
4761 	vport->load_flag |= FC_LOADING;
4762 	vport->fc_flag |= FC_VPORT_NEEDS_REG_VPI;
4763 	vport->fc_rscn_flush = 0;
4764 	lpfc_get_vport_cfgparam(vport);
4765 
4766 	/* Adjust value in vport */
4767 	vport->cfg_enable_fc4_type = phba->cfg_enable_fc4_type;
4768 
4769 	shost->unique_id = instance;
4770 	shost->max_id = LPFC_MAX_TARGET;
4771 	shost->max_lun = vport->cfg_max_luns;
4772 	shost->this_id = -1;
4773 	shost->max_cmd_len = 16;
4774 
4775 	if (phba->sli_rev == LPFC_SLI_REV4) {
4776 		if (!phba->cfg_fcp_mq_threshold ||
4777 		    phba->cfg_fcp_mq_threshold > phba->cfg_hdw_queue)
4778 			phba->cfg_fcp_mq_threshold = phba->cfg_hdw_queue;
4779 
4780 		shost->nr_hw_queues = min_t(int, 2 * num_possible_nodes(),
4781 					    phba->cfg_fcp_mq_threshold);
4782 
4783 		shost->dma_boundary =
4784 			phba->sli4_hba.pc_sli4_params.sge_supp_len-1;
4785 	} else
4786 		/* SLI-3 has a limited number of hardware queues (3),
4787 		 * thus there is only one for FCP processing.
4788 		 */
4789 		shost->nr_hw_queues = 1;
4790 
4791 	/*
4792 	 * Set initial can_queue value since 0 is no longer supported and
4793 	 * scsi_add_host will fail. This will be adjusted later based on the
4794 	 * max xri value determined in hba setup.
4795 	 */
4796 	shost->can_queue = phba->cfg_hba_queue_depth - 10;
4797 	if (dev != &phba->pcidev->dev) {
4798 		shost->transportt = lpfc_vport_transport_template;
4799 		vport->port_type = LPFC_NPIV_PORT;
4800 	} else {
4801 		shost->transportt = lpfc_transport_template;
4802 		vport->port_type = LPFC_PHYSICAL_PORT;
4803 	}
4804 
4805 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP,
4806 			"9081 CreatePort TMPLATE type %x TBLsize %d "
4807 			"SEGcnt %d/%d\n",
4808 			vport->port_type, shost->sg_tablesize,
4809 			phba->cfg_scsi_seg_cnt, phba->cfg_sg_seg_cnt);
4810 
4811 	/* Allocate the resources for VMID */
4812 	rc = lpfc_vmid_res_alloc(phba, vport);
4813 
4814 	if (rc)
4815 		goto out;
4816 
4817 	/* Initialize all internally managed lists. */
4818 	INIT_LIST_HEAD(&vport->fc_nodes);
4819 	INIT_LIST_HEAD(&vport->rcv_buffer_list);
4820 	spin_lock_init(&vport->work_port_lock);
4821 
4822 	timer_setup(&vport->fc_disctmo, lpfc_disc_timeout, 0);
4823 
4824 	timer_setup(&vport->els_tmofunc, lpfc_els_timeout, 0);
4825 
4826 	timer_setup(&vport->delayed_disc_tmo, lpfc_delayed_disc_tmo, 0);
4827 
4828 	if (phba->sli3_options & LPFC_SLI3_BG_ENABLED)
4829 		lpfc_setup_bg(phba, shost);
4830 
4831 	error = scsi_add_host_with_dma(shost, dev, &phba->pcidev->dev);
4832 	if (error)
4833 		goto out_put_shost;
4834 
4835 	spin_lock_irq(&phba->port_list_lock);
4836 	list_add_tail(&vport->listentry, &phba->port_list);
4837 	spin_unlock_irq(&phba->port_list_lock);
4838 	return vport;
4839 
4840 out_put_shost:
4841 	kfree(vport->vmid);
4842 	bitmap_free(vport->vmid_priority_range);
4843 	scsi_host_put(shost);
4844 out:
4845 	return NULL;
4846 }
4847 
4848 /**
4849  * destroy_port -  destroy an FC port
4850  * @vport: pointer to an lpfc virtual N_Port data structure.
4851  *
4852  * This routine destroys a FC port from the upper layer protocol. All the
4853  * resources associated with the port are released.
4854  **/
4855 void
4856 destroy_port(struct lpfc_vport *vport)
4857 {
4858 	struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
4859 	struct lpfc_hba  *phba = vport->phba;
4860 
4861 	lpfc_debugfs_terminate(vport);
4862 	fc_remove_host(shost);
4863 	scsi_remove_host(shost);
4864 
4865 	spin_lock_irq(&phba->port_list_lock);
4866 	list_del_init(&vport->listentry);
4867 	spin_unlock_irq(&phba->port_list_lock);
4868 
4869 	lpfc_cleanup(vport);
4870 	return;
4871 }
4872 
4873 /**
4874  * lpfc_get_instance - Get a unique integer ID
4875  *
4876  * This routine allocates a unique integer ID from lpfc_hba_index pool. It
4877  * uses the kernel idr facility to perform the task.
4878  *
4879  * Return codes:
4880  *   instance - a unique integer ID allocated as the new instance.
4881  *   -1 - lpfc get instance failed.
4882  **/
4883 int
4884 lpfc_get_instance(void)
4885 {
4886 	int ret;
4887 
4888 	ret = idr_alloc(&lpfc_hba_index, NULL, 0, 0, GFP_KERNEL);
4889 	return ret < 0 ? -1 : ret;
4890 }
4891 
4892 /**
4893  * lpfc_scan_finished - method for SCSI layer to detect whether scan is done
4894  * @shost: pointer to SCSI host data structure.
4895  * @time: elapsed time of the scan in jiffies.
4896  *
4897  * This routine is called by the SCSI layer with a SCSI host to determine
4898  * whether the scan host is finished.
4899  *
4900  * Note: there is no scan_start function as adapter initialization will have
4901  * asynchronously kicked off the link initialization.
4902  *
4903  * Return codes
4904  *   0 - SCSI host scan is not over yet.
4905  *   1 - SCSI host scan is over.
4906  **/
4907 int lpfc_scan_finished(struct Scsi_Host *shost, unsigned long time)
4908 {
4909 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
4910 	struct lpfc_hba   *phba = vport->phba;
4911 	int stat = 0;
4912 
4913 	spin_lock_irq(shost->host_lock);
4914 
4915 	if (vport->load_flag & FC_UNLOADING) {
4916 		stat = 1;
4917 		goto finished;
4918 	}
4919 	if (time >= msecs_to_jiffies(30 * 1000)) {
4920 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4921 				"0461 Scanning longer than 30 "
4922 				"seconds.  Continuing initialization\n");
4923 		stat = 1;
4924 		goto finished;
4925 	}
4926 	if (time >= msecs_to_jiffies(15 * 1000) &&
4927 	    phba->link_state <= LPFC_LINK_DOWN) {
4928 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4929 				"0465 Link down longer than 15 "
4930 				"seconds.  Continuing initialization\n");
4931 		stat = 1;
4932 		goto finished;
4933 	}
4934 
4935 	if (vport->port_state != LPFC_VPORT_READY)
4936 		goto finished;
4937 	if (vport->num_disc_nodes || vport->fc_prli_sent)
4938 		goto finished;
4939 	if (vport->fc_map_cnt == 0 && time < msecs_to_jiffies(2 * 1000))
4940 		goto finished;
4941 	if ((phba->sli.sli_flag & LPFC_SLI_MBOX_ACTIVE) != 0)
4942 		goto finished;
4943 
4944 	stat = 1;
4945 
4946 finished:
4947 	spin_unlock_irq(shost->host_lock);
4948 	return stat;
4949 }
4950 
4951 static void lpfc_host_supported_speeds_set(struct Scsi_Host *shost)
4952 {
4953 	struct lpfc_vport *vport = (struct lpfc_vport *)shost->hostdata;
4954 	struct lpfc_hba   *phba = vport->phba;
4955 
4956 	fc_host_supported_speeds(shost) = 0;
4957 	/*
4958 	 * Avoid reporting supported link speed for FCoE as it can't be
4959 	 * controlled via FCoE.
4960 	 */
4961 	if (phba->hba_flag & HBA_FCOE_MODE)
4962 		return;
4963 
4964 	if (phba->lmt & LMT_256Gb)
4965 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_256GBIT;
4966 	if (phba->lmt & LMT_128Gb)
4967 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_128GBIT;
4968 	if (phba->lmt & LMT_64Gb)
4969 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_64GBIT;
4970 	if (phba->lmt & LMT_32Gb)
4971 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_32GBIT;
4972 	if (phba->lmt & LMT_16Gb)
4973 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_16GBIT;
4974 	if (phba->lmt & LMT_10Gb)
4975 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_10GBIT;
4976 	if (phba->lmt & LMT_8Gb)
4977 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_8GBIT;
4978 	if (phba->lmt & LMT_4Gb)
4979 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_4GBIT;
4980 	if (phba->lmt & LMT_2Gb)
4981 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_2GBIT;
4982 	if (phba->lmt & LMT_1Gb)
4983 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_1GBIT;
4984 }
4985 
4986 /**
4987  * lpfc_host_attrib_init - Initialize SCSI host attributes on a FC port
4988  * @shost: pointer to SCSI host data structure.
4989  *
4990  * This routine initializes a given SCSI host attributes on a FC port. The
4991  * SCSI host can be either on top of a physical port or a virtual port.
4992  **/
4993 void lpfc_host_attrib_init(struct Scsi_Host *shost)
4994 {
4995 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
4996 	struct lpfc_hba   *phba = vport->phba;
4997 	/*
4998 	 * Set fixed host attributes.  Must done after lpfc_sli_hba_setup().
4999 	 */
5000 
5001 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
5002 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
5003 	fc_host_supported_classes(shost) = FC_COS_CLASS3;
5004 
5005 	memset(fc_host_supported_fc4s(shost), 0,
5006 	       sizeof(fc_host_supported_fc4s(shost)));
5007 	fc_host_supported_fc4s(shost)[2] = 1;
5008 	fc_host_supported_fc4s(shost)[7] = 1;
5009 
5010 	lpfc_vport_symbolic_node_name(vport, fc_host_symbolic_name(shost),
5011 				 sizeof fc_host_symbolic_name(shost));
5012 
5013 	lpfc_host_supported_speeds_set(shost);
5014 
5015 	fc_host_maxframe_size(shost) =
5016 		(((uint32_t) vport->fc_sparam.cmn.bbRcvSizeMsb & 0x0F) << 8) |
5017 		(uint32_t) vport->fc_sparam.cmn.bbRcvSizeLsb;
5018 
5019 	fc_host_dev_loss_tmo(shost) = vport->cfg_devloss_tmo;
5020 
5021 	/* This value is also unchanging */
5022 	memset(fc_host_active_fc4s(shost), 0,
5023 	       sizeof(fc_host_active_fc4s(shost)));
5024 	fc_host_active_fc4s(shost)[2] = 1;
5025 	fc_host_active_fc4s(shost)[7] = 1;
5026 
5027 	fc_host_max_npiv_vports(shost) = phba->max_vpi;
5028 	spin_lock_irq(shost->host_lock);
5029 	vport->load_flag &= ~FC_LOADING;
5030 	spin_unlock_irq(shost->host_lock);
5031 }
5032 
5033 /**
5034  * lpfc_stop_port_s3 - Stop SLI3 device port
5035  * @phba: pointer to lpfc hba data structure.
5036  *
5037  * This routine is invoked to stop an SLI3 device port, it stops the device
5038  * from generating interrupts and stops the device driver's timers for the
5039  * device.
5040  **/
5041 static void
5042 lpfc_stop_port_s3(struct lpfc_hba *phba)
5043 {
5044 	/* Clear all interrupt enable conditions */
5045 	writel(0, phba->HCregaddr);
5046 	readl(phba->HCregaddr); /* flush */
5047 	/* Clear all pending interrupts */
5048 	writel(0xffffffff, phba->HAregaddr);
5049 	readl(phba->HAregaddr); /* flush */
5050 
5051 	/* Reset some HBA SLI setup states */
5052 	lpfc_stop_hba_timers(phba);
5053 	phba->pport->work_port_events = 0;
5054 }
5055 
5056 /**
5057  * lpfc_stop_port_s4 - Stop SLI4 device port
5058  * @phba: pointer to lpfc hba data structure.
5059  *
5060  * This routine is invoked to stop an SLI4 device port, it stops the device
5061  * from generating interrupts and stops the device driver's timers for the
5062  * device.
5063  **/
5064 static void
5065 lpfc_stop_port_s4(struct lpfc_hba *phba)
5066 {
5067 	/* Reset some HBA SLI4 setup states */
5068 	lpfc_stop_hba_timers(phba);
5069 	if (phba->pport)
5070 		phba->pport->work_port_events = 0;
5071 	phba->sli4_hba.intr_enable = 0;
5072 }
5073 
5074 /**
5075  * lpfc_stop_port - Wrapper function for stopping hba port
5076  * @phba: Pointer to HBA context object.
5077  *
5078  * This routine wraps the actual SLI3 or SLI4 hba stop port routine from
5079  * the API jump table function pointer from the lpfc_hba struct.
5080  **/
5081 void
5082 lpfc_stop_port(struct lpfc_hba *phba)
5083 {
5084 	phba->lpfc_stop_port(phba);
5085 
5086 	if (phba->wq)
5087 		flush_workqueue(phba->wq);
5088 }
5089 
5090 /**
5091  * lpfc_fcf_redisc_wait_start_timer - Start fcf rediscover wait timer
5092  * @phba: Pointer to hba for which this call is being executed.
5093  *
5094  * This routine starts the timer waiting for the FCF rediscovery to complete.
5095  **/
5096 void
5097 lpfc_fcf_redisc_wait_start_timer(struct lpfc_hba *phba)
5098 {
5099 	unsigned long fcf_redisc_wait_tmo =
5100 		(jiffies + msecs_to_jiffies(LPFC_FCF_REDISCOVER_WAIT_TMO));
5101 	/* Start fcf rediscovery wait period timer */
5102 	mod_timer(&phba->fcf.redisc_wait, fcf_redisc_wait_tmo);
5103 	spin_lock_irq(&phba->hbalock);
5104 	/* Allow action to new fcf asynchronous event */
5105 	phba->fcf.fcf_flag &= ~(FCF_AVAILABLE | FCF_SCAN_DONE);
5106 	/* Mark the FCF rediscovery pending state */
5107 	phba->fcf.fcf_flag |= FCF_REDISC_PEND;
5108 	spin_unlock_irq(&phba->hbalock);
5109 }
5110 
5111 /**
5112  * lpfc_sli4_fcf_redisc_wait_tmo - FCF table rediscover wait timeout
5113  * @t: Timer context used to obtain the pointer to lpfc hba data structure.
5114  *
5115  * This routine is invoked when waiting for FCF table rediscover has been
5116  * timed out. If new FCF record(s) has (have) been discovered during the
5117  * wait period, a new FCF event shall be added to the FCOE async event
5118  * list, and then worker thread shall be waked up for processing from the
5119  * worker thread context.
5120  **/
5121 static void
5122 lpfc_sli4_fcf_redisc_wait_tmo(struct timer_list *t)
5123 {
5124 	struct lpfc_hba *phba = from_timer(phba, t, fcf.redisc_wait);
5125 
5126 	/* Don't send FCF rediscovery event if timer cancelled */
5127 	spin_lock_irq(&phba->hbalock);
5128 	if (!(phba->fcf.fcf_flag & FCF_REDISC_PEND)) {
5129 		spin_unlock_irq(&phba->hbalock);
5130 		return;
5131 	}
5132 	/* Clear FCF rediscovery timer pending flag */
5133 	phba->fcf.fcf_flag &= ~FCF_REDISC_PEND;
5134 	/* FCF rediscovery event to worker thread */
5135 	phba->fcf.fcf_flag |= FCF_REDISC_EVT;
5136 	spin_unlock_irq(&phba->hbalock);
5137 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
5138 			"2776 FCF rediscover quiescent timer expired\n");
5139 	/* wake up worker thread */
5140 	lpfc_worker_wake_up(phba);
5141 }
5142 
5143 /**
5144  * lpfc_vmid_poll - VMID timeout detection
5145  * @t: Timer context used to obtain the pointer to lpfc hba data structure.
5146  *
5147  * This routine is invoked when there is no I/O on by a VM for the specified
5148  * amount of time. When this situation is detected, the VMID has to be
5149  * deregistered from the switch and all the local resources freed. The VMID
5150  * will be reassigned to the VM once the I/O begins.
5151  **/
5152 static void
5153 lpfc_vmid_poll(struct timer_list *t)
5154 {
5155 	struct lpfc_hba *phba = from_timer(phba, t, inactive_vmid_poll);
5156 	u32 wake_up = 0;
5157 
5158 	/* check if there is a need to issue QFPA */
5159 	if (phba->pport->vmid_priority_tagging) {
5160 		wake_up = 1;
5161 		phba->pport->work_port_events |= WORKER_CHECK_VMID_ISSUE_QFPA;
5162 	}
5163 
5164 	/* Is the vmid inactivity timer enabled */
5165 	if (phba->pport->vmid_inactivity_timeout ||
5166 	    phba->pport->load_flag & FC_DEREGISTER_ALL_APP_ID) {
5167 		wake_up = 1;
5168 		phba->pport->work_port_events |= WORKER_CHECK_INACTIVE_VMID;
5169 	}
5170 
5171 	if (wake_up)
5172 		lpfc_worker_wake_up(phba);
5173 
5174 	/* restart the timer for the next iteration */
5175 	mod_timer(&phba->inactive_vmid_poll, jiffies + msecs_to_jiffies(1000 *
5176 							LPFC_VMID_TIMER));
5177 }
5178 
5179 /**
5180  * lpfc_sli4_parse_latt_fault - Parse sli4 link-attention link fault code
5181  * @phba: pointer to lpfc hba data structure.
5182  * @acqe_link: pointer to the async link completion queue entry.
5183  *
5184  * This routine is to parse the SLI4 link-attention link fault code.
5185  **/
5186 static void
5187 lpfc_sli4_parse_latt_fault(struct lpfc_hba *phba,
5188 			   struct lpfc_acqe_link *acqe_link)
5189 {
5190 	switch (bf_get(lpfc_acqe_link_fault, acqe_link)) {
5191 	case LPFC_ASYNC_LINK_FAULT_NONE:
5192 	case LPFC_ASYNC_LINK_FAULT_LOCAL:
5193 	case LPFC_ASYNC_LINK_FAULT_REMOTE:
5194 	case LPFC_ASYNC_LINK_FAULT_LR_LRR:
5195 		break;
5196 	default:
5197 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5198 				"0398 Unknown link fault code: x%x\n",
5199 				bf_get(lpfc_acqe_link_fault, acqe_link));
5200 		break;
5201 	}
5202 }
5203 
5204 /**
5205  * lpfc_sli4_parse_latt_type - Parse sli4 link attention type
5206  * @phba: pointer to lpfc hba data structure.
5207  * @acqe_link: pointer to the async link completion queue entry.
5208  *
5209  * This routine is to parse the SLI4 link attention type and translate it
5210  * into the base driver's link attention type coding.
5211  *
5212  * Return: Link attention type in terms of base driver's coding.
5213  **/
5214 static uint8_t
5215 lpfc_sli4_parse_latt_type(struct lpfc_hba *phba,
5216 			  struct lpfc_acqe_link *acqe_link)
5217 {
5218 	uint8_t att_type;
5219 
5220 	switch (bf_get(lpfc_acqe_link_status, acqe_link)) {
5221 	case LPFC_ASYNC_LINK_STATUS_DOWN:
5222 	case LPFC_ASYNC_LINK_STATUS_LOGICAL_DOWN:
5223 		att_type = LPFC_ATT_LINK_DOWN;
5224 		break;
5225 	case LPFC_ASYNC_LINK_STATUS_UP:
5226 		/* Ignore physical link up events - wait for logical link up */
5227 		att_type = LPFC_ATT_RESERVED;
5228 		break;
5229 	case LPFC_ASYNC_LINK_STATUS_LOGICAL_UP:
5230 		att_type = LPFC_ATT_LINK_UP;
5231 		break;
5232 	default:
5233 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5234 				"0399 Invalid link attention type: x%x\n",
5235 				bf_get(lpfc_acqe_link_status, acqe_link));
5236 		att_type = LPFC_ATT_RESERVED;
5237 		break;
5238 	}
5239 	return att_type;
5240 }
5241 
5242 /**
5243  * lpfc_sli_port_speed_get - Get sli3 link speed code to link speed
5244  * @phba: pointer to lpfc hba data structure.
5245  *
5246  * This routine is to get an SLI3 FC port's link speed in Mbps.
5247  *
5248  * Return: link speed in terms of Mbps.
5249  **/
5250 uint32_t
5251 lpfc_sli_port_speed_get(struct lpfc_hba *phba)
5252 {
5253 	uint32_t link_speed;
5254 
5255 	if (!lpfc_is_link_up(phba))
5256 		return 0;
5257 
5258 	if (phba->sli_rev <= LPFC_SLI_REV3) {
5259 		switch (phba->fc_linkspeed) {
5260 		case LPFC_LINK_SPEED_1GHZ:
5261 			link_speed = 1000;
5262 			break;
5263 		case LPFC_LINK_SPEED_2GHZ:
5264 			link_speed = 2000;
5265 			break;
5266 		case LPFC_LINK_SPEED_4GHZ:
5267 			link_speed = 4000;
5268 			break;
5269 		case LPFC_LINK_SPEED_8GHZ:
5270 			link_speed = 8000;
5271 			break;
5272 		case LPFC_LINK_SPEED_10GHZ:
5273 			link_speed = 10000;
5274 			break;
5275 		case LPFC_LINK_SPEED_16GHZ:
5276 			link_speed = 16000;
5277 			break;
5278 		default:
5279 			link_speed = 0;
5280 		}
5281 	} else {
5282 		if (phba->sli4_hba.link_state.logical_speed)
5283 			link_speed =
5284 			      phba->sli4_hba.link_state.logical_speed;
5285 		else
5286 			link_speed = phba->sli4_hba.link_state.speed;
5287 	}
5288 	return link_speed;
5289 }
5290 
5291 /**
5292  * lpfc_sli4_port_speed_parse - Parse async evt link speed code to link speed
5293  * @phba: pointer to lpfc hba data structure.
5294  * @evt_code: asynchronous event code.
5295  * @speed_code: asynchronous event link speed code.
5296  *
5297  * This routine is to parse the giving SLI4 async event link speed code into
5298  * value of Mbps for the link speed.
5299  *
5300  * Return: link speed in terms of Mbps.
5301  **/
5302 static uint32_t
5303 lpfc_sli4_port_speed_parse(struct lpfc_hba *phba, uint32_t evt_code,
5304 			   uint8_t speed_code)
5305 {
5306 	uint32_t port_speed;
5307 
5308 	switch (evt_code) {
5309 	case LPFC_TRAILER_CODE_LINK:
5310 		switch (speed_code) {
5311 		case LPFC_ASYNC_LINK_SPEED_ZERO:
5312 			port_speed = 0;
5313 			break;
5314 		case LPFC_ASYNC_LINK_SPEED_10MBPS:
5315 			port_speed = 10;
5316 			break;
5317 		case LPFC_ASYNC_LINK_SPEED_100MBPS:
5318 			port_speed = 100;
5319 			break;
5320 		case LPFC_ASYNC_LINK_SPEED_1GBPS:
5321 			port_speed = 1000;
5322 			break;
5323 		case LPFC_ASYNC_LINK_SPEED_10GBPS:
5324 			port_speed = 10000;
5325 			break;
5326 		case LPFC_ASYNC_LINK_SPEED_20GBPS:
5327 			port_speed = 20000;
5328 			break;
5329 		case LPFC_ASYNC_LINK_SPEED_25GBPS:
5330 			port_speed = 25000;
5331 			break;
5332 		case LPFC_ASYNC_LINK_SPEED_40GBPS:
5333 			port_speed = 40000;
5334 			break;
5335 		case LPFC_ASYNC_LINK_SPEED_100GBPS:
5336 			port_speed = 100000;
5337 			break;
5338 		default:
5339 			port_speed = 0;
5340 		}
5341 		break;
5342 	case LPFC_TRAILER_CODE_FC:
5343 		switch (speed_code) {
5344 		case LPFC_FC_LA_SPEED_UNKNOWN:
5345 			port_speed = 0;
5346 			break;
5347 		case LPFC_FC_LA_SPEED_1G:
5348 			port_speed = 1000;
5349 			break;
5350 		case LPFC_FC_LA_SPEED_2G:
5351 			port_speed = 2000;
5352 			break;
5353 		case LPFC_FC_LA_SPEED_4G:
5354 			port_speed = 4000;
5355 			break;
5356 		case LPFC_FC_LA_SPEED_8G:
5357 			port_speed = 8000;
5358 			break;
5359 		case LPFC_FC_LA_SPEED_10G:
5360 			port_speed = 10000;
5361 			break;
5362 		case LPFC_FC_LA_SPEED_16G:
5363 			port_speed = 16000;
5364 			break;
5365 		case LPFC_FC_LA_SPEED_32G:
5366 			port_speed = 32000;
5367 			break;
5368 		case LPFC_FC_LA_SPEED_64G:
5369 			port_speed = 64000;
5370 			break;
5371 		case LPFC_FC_LA_SPEED_128G:
5372 			port_speed = 128000;
5373 			break;
5374 		case LPFC_FC_LA_SPEED_256G:
5375 			port_speed = 256000;
5376 			break;
5377 		default:
5378 			port_speed = 0;
5379 		}
5380 		break;
5381 	default:
5382 		port_speed = 0;
5383 	}
5384 	return port_speed;
5385 }
5386 
5387 /**
5388  * lpfc_sli4_async_link_evt - Process the asynchronous FCoE link event
5389  * @phba: pointer to lpfc hba data structure.
5390  * @acqe_link: pointer to the async link completion queue entry.
5391  *
5392  * This routine is to handle the SLI4 asynchronous FCoE link event.
5393  **/
5394 static void
5395 lpfc_sli4_async_link_evt(struct lpfc_hba *phba,
5396 			 struct lpfc_acqe_link *acqe_link)
5397 {
5398 	LPFC_MBOXQ_t *pmb;
5399 	MAILBOX_t *mb;
5400 	struct lpfc_mbx_read_top *la;
5401 	uint8_t att_type;
5402 	int rc;
5403 
5404 	att_type = lpfc_sli4_parse_latt_type(phba, acqe_link);
5405 	if (att_type != LPFC_ATT_LINK_DOWN && att_type != LPFC_ATT_LINK_UP)
5406 		return;
5407 	phba->fcoe_eventtag = acqe_link->event_tag;
5408 	pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5409 	if (!pmb) {
5410 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5411 				"0395 The mboxq allocation failed\n");
5412 		return;
5413 	}
5414 
5415 	rc = lpfc_mbox_rsrc_prep(phba, pmb);
5416 	if (rc) {
5417 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5418 				"0396 mailbox allocation failed\n");
5419 		goto out_free_pmb;
5420 	}
5421 
5422 	/* Cleanup any outstanding ELS commands */
5423 	lpfc_els_flush_all_cmd(phba);
5424 
5425 	/* Block ELS IOCBs until we have done process link event */
5426 	phba->sli4_hba.els_wq->pring->flag |= LPFC_STOP_IOCB_EVENT;
5427 
5428 	/* Update link event statistics */
5429 	phba->sli.slistat.link_event++;
5430 
5431 	/* Create lpfc_handle_latt mailbox command from link ACQE */
5432 	lpfc_read_topology(phba, pmb, (struct lpfc_dmabuf *)pmb->ctx_buf);
5433 	pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
5434 	pmb->vport = phba->pport;
5435 
5436 	/* Keep the link status for extra SLI4 state machine reference */
5437 	phba->sli4_hba.link_state.speed =
5438 			lpfc_sli4_port_speed_parse(phba, LPFC_TRAILER_CODE_LINK,
5439 				bf_get(lpfc_acqe_link_speed, acqe_link));
5440 	phba->sli4_hba.link_state.duplex =
5441 				bf_get(lpfc_acqe_link_duplex, acqe_link);
5442 	phba->sli4_hba.link_state.status =
5443 				bf_get(lpfc_acqe_link_status, acqe_link);
5444 	phba->sli4_hba.link_state.type =
5445 				bf_get(lpfc_acqe_link_type, acqe_link);
5446 	phba->sli4_hba.link_state.number =
5447 				bf_get(lpfc_acqe_link_number, acqe_link);
5448 	phba->sli4_hba.link_state.fault =
5449 				bf_get(lpfc_acqe_link_fault, acqe_link);
5450 	phba->sli4_hba.link_state.logical_speed =
5451 			bf_get(lpfc_acqe_logical_link_speed, acqe_link) * 10;
5452 
5453 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5454 			"2900 Async FC/FCoE Link event - Speed:%dGBit "
5455 			"duplex:x%x LA Type:x%x Port Type:%d Port Number:%d "
5456 			"Logical speed:%dMbps Fault:%d\n",
5457 			phba->sli4_hba.link_state.speed,
5458 			phba->sli4_hba.link_state.topology,
5459 			phba->sli4_hba.link_state.status,
5460 			phba->sli4_hba.link_state.type,
5461 			phba->sli4_hba.link_state.number,
5462 			phba->sli4_hba.link_state.logical_speed,
5463 			phba->sli4_hba.link_state.fault);
5464 	/*
5465 	 * For FC Mode: issue the READ_TOPOLOGY mailbox command to fetch
5466 	 * topology info. Note: Optional for non FC-AL ports.
5467 	 */
5468 	if (!(phba->hba_flag & HBA_FCOE_MODE)) {
5469 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
5470 		if (rc == MBX_NOT_FINISHED)
5471 			goto out_free_pmb;
5472 		return;
5473 	}
5474 	/*
5475 	 * For FCoE Mode: fill in all the topology information we need and call
5476 	 * the READ_TOPOLOGY completion routine to continue without actually
5477 	 * sending the READ_TOPOLOGY mailbox command to the port.
5478 	 */
5479 	/* Initialize completion status */
5480 	mb = &pmb->u.mb;
5481 	mb->mbxStatus = MBX_SUCCESS;
5482 
5483 	/* Parse port fault information field */
5484 	lpfc_sli4_parse_latt_fault(phba, acqe_link);
5485 
5486 	/* Parse and translate link attention fields */
5487 	la = (struct lpfc_mbx_read_top *) &pmb->u.mb.un.varReadTop;
5488 	la->eventTag = acqe_link->event_tag;
5489 	bf_set(lpfc_mbx_read_top_att_type, la, att_type);
5490 	bf_set(lpfc_mbx_read_top_link_spd, la,
5491 	       (bf_get(lpfc_acqe_link_speed, acqe_link)));
5492 
5493 	/* Fake the the following irrelvant fields */
5494 	bf_set(lpfc_mbx_read_top_topology, la, LPFC_TOPOLOGY_PT_PT);
5495 	bf_set(lpfc_mbx_read_top_alpa_granted, la, 0);
5496 	bf_set(lpfc_mbx_read_top_il, la, 0);
5497 	bf_set(lpfc_mbx_read_top_pb, la, 0);
5498 	bf_set(lpfc_mbx_read_top_fa, la, 0);
5499 	bf_set(lpfc_mbx_read_top_mm, la, 0);
5500 
5501 	/* Invoke the lpfc_handle_latt mailbox command callback function */
5502 	lpfc_mbx_cmpl_read_topology(phba, pmb);
5503 
5504 	return;
5505 
5506 out_free_pmb:
5507 	lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
5508 }
5509 
5510 /**
5511  * lpfc_async_link_speed_to_read_top - Parse async evt link speed code to read
5512  * topology.
5513  * @phba: pointer to lpfc hba data structure.
5514  * @speed_code: asynchronous event link speed code.
5515  *
5516  * This routine is to parse the giving SLI4 async event link speed code into
5517  * value of Read topology link speed.
5518  *
5519  * Return: link speed in terms of Read topology.
5520  **/
5521 static uint8_t
5522 lpfc_async_link_speed_to_read_top(struct lpfc_hba *phba, uint8_t speed_code)
5523 {
5524 	uint8_t port_speed;
5525 
5526 	switch (speed_code) {
5527 	case LPFC_FC_LA_SPEED_1G:
5528 		port_speed = LPFC_LINK_SPEED_1GHZ;
5529 		break;
5530 	case LPFC_FC_LA_SPEED_2G:
5531 		port_speed = LPFC_LINK_SPEED_2GHZ;
5532 		break;
5533 	case LPFC_FC_LA_SPEED_4G:
5534 		port_speed = LPFC_LINK_SPEED_4GHZ;
5535 		break;
5536 	case LPFC_FC_LA_SPEED_8G:
5537 		port_speed = LPFC_LINK_SPEED_8GHZ;
5538 		break;
5539 	case LPFC_FC_LA_SPEED_16G:
5540 		port_speed = LPFC_LINK_SPEED_16GHZ;
5541 		break;
5542 	case LPFC_FC_LA_SPEED_32G:
5543 		port_speed = LPFC_LINK_SPEED_32GHZ;
5544 		break;
5545 	case LPFC_FC_LA_SPEED_64G:
5546 		port_speed = LPFC_LINK_SPEED_64GHZ;
5547 		break;
5548 	case LPFC_FC_LA_SPEED_128G:
5549 		port_speed = LPFC_LINK_SPEED_128GHZ;
5550 		break;
5551 	case LPFC_FC_LA_SPEED_256G:
5552 		port_speed = LPFC_LINK_SPEED_256GHZ;
5553 		break;
5554 	default:
5555 		port_speed = 0;
5556 		break;
5557 	}
5558 
5559 	return port_speed;
5560 }
5561 
5562 void
5563 lpfc_cgn_dump_rxmonitor(struct lpfc_hba *phba)
5564 {
5565 	if (!phba->rx_monitor) {
5566 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5567 				"4411 Rx Monitor Info is empty.\n");
5568 	} else {
5569 		lpfc_rx_monitor_report(phba, phba->rx_monitor, NULL, 0,
5570 				       LPFC_MAX_RXMONITOR_DUMP);
5571 	}
5572 }
5573 
5574 /**
5575  * lpfc_cgn_update_stat - Save data into congestion stats buffer
5576  * @phba: pointer to lpfc hba data structure.
5577  * @dtag: FPIN descriptor received
5578  *
5579  * Increment the FPIN received counter/time when it happens.
5580  */
5581 void
5582 lpfc_cgn_update_stat(struct lpfc_hba *phba, uint32_t dtag)
5583 {
5584 	struct lpfc_cgn_info *cp;
5585 	struct tm broken;
5586 	struct timespec64 cur_time;
5587 	u32 cnt;
5588 	u32 value;
5589 
5590 	/* Make sure we have a congestion info buffer */
5591 	if (!phba->cgn_i)
5592 		return;
5593 	cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
5594 	ktime_get_real_ts64(&cur_time);
5595 	time64_to_tm(cur_time.tv_sec, 0, &broken);
5596 
5597 	/* Update congestion statistics */
5598 	switch (dtag) {
5599 	case ELS_DTAG_LNK_INTEGRITY:
5600 		cnt = le32_to_cpu(cp->link_integ_notification);
5601 		cnt++;
5602 		cp->link_integ_notification = cpu_to_le32(cnt);
5603 
5604 		cp->cgn_stat_lnk_month = broken.tm_mon + 1;
5605 		cp->cgn_stat_lnk_day = broken.tm_mday;
5606 		cp->cgn_stat_lnk_year = broken.tm_year - 100;
5607 		cp->cgn_stat_lnk_hour = broken.tm_hour;
5608 		cp->cgn_stat_lnk_min = broken.tm_min;
5609 		cp->cgn_stat_lnk_sec = broken.tm_sec;
5610 		break;
5611 	case ELS_DTAG_DELIVERY:
5612 		cnt = le32_to_cpu(cp->delivery_notification);
5613 		cnt++;
5614 		cp->delivery_notification = cpu_to_le32(cnt);
5615 
5616 		cp->cgn_stat_del_month = broken.tm_mon + 1;
5617 		cp->cgn_stat_del_day = broken.tm_mday;
5618 		cp->cgn_stat_del_year = broken.tm_year - 100;
5619 		cp->cgn_stat_del_hour = broken.tm_hour;
5620 		cp->cgn_stat_del_min = broken.tm_min;
5621 		cp->cgn_stat_del_sec = broken.tm_sec;
5622 		break;
5623 	case ELS_DTAG_PEER_CONGEST:
5624 		cnt = le32_to_cpu(cp->cgn_peer_notification);
5625 		cnt++;
5626 		cp->cgn_peer_notification = cpu_to_le32(cnt);
5627 
5628 		cp->cgn_stat_peer_month = broken.tm_mon + 1;
5629 		cp->cgn_stat_peer_day = broken.tm_mday;
5630 		cp->cgn_stat_peer_year = broken.tm_year - 100;
5631 		cp->cgn_stat_peer_hour = broken.tm_hour;
5632 		cp->cgn_stat_peer_min = broken.tm_min;
5633 		cp->cgn_stat_peer_sec = broken.tm_sec;
5634 		break;
5635 	case ELS_DTAG_CONGESTION:
5636 		cnt = le32_to_cpu(cp->cgn_notification);
5637 		cnt++;
5638 		cp->cgn_notification = cpu_to_le32(cnt);
5639 
5640 		cp->cgn_stat_cgn_month = broken.tm_mon + 1;
5641 		cp->cgn_stat_cgn_day = broken.tm_mday;
5642 		cp->cgn_stat_cgn_year = broken.tm_year - 100;
5643 		cp->cgn_stat_cgn_hour = broken.tm_hour;
5644 		cp->cgn_stat_cgn_min = broken.tm_min;
5645 		cp->cgn_stat_cgn_sec = broken.tm_sec;
5646 	}
5647 	if (phba->cgn_fpin_frequency &&
5648 	    phba->cgn_fpin_frequency != LPFC_FPIN_INIT_FREQ) {
5649 		value = LPFC_CGN_TIMER_TO_MIN / phba->cgn_fpin_frequency;
5650 		cp->cgn_stat_npm = value;
5651 	}
5652 	value = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ,
5653 				    LPFC_CGN_CRC32_SEED);
5654 	cp->cgn_info_crc = cpu_to_le32(value);
5655 }
5656 
5657 /**
5658  * lpfc_cgn_save_evt_cnt - Save data into registered congestion buffer
5659  * @phba: pointer to lpfc hba data structure.
5660  *
5661  * Save the congestion event data every minute.
5662  * On the hour collapse all the minute data into hour data. Every day
5663  * collapse all the hour data into daily data. Separate driver
5664  * and fabrc congestion event counters that will be saved out
5665  * to the registered congestion buffer every minute.
5666  */
5667 static void
5668 lpfc_cgn_save_evt_cnt(struct lpfc_hba *phba)
5669 {
5670 	struct lpfc_cgn_info *cp;
5671 	struct tm broken;
5672 	struct timespec64 cur_time;
5673 	uint32_t i, index;
5674 	uint16_t value, mvalue;
5675 	uint64_t bps;
5676 	uint32_t mbps;
5677 	uint32_t dvalue, wvalue, lvalue, avalue;
5678 	uint64_t latsum;
5679 	__le16 *ptr;
5680 	__le32 *lptr;
5681 	__le16 *mptr;
5682 
5683 	/* Make sure we have a congestion info buffer */
5684 	if (!phba->cgn_i)
5685 		return;
5686 	cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
5687 
5688 	if (time_before(jiffies, phba->cgn_evt_timestamp))
5689 		return;
5690 	phba->cgn_evt_timestamp = jiffies +
5691 			msecs_to_jiffies(LPFC_CGN_TIMER_TO_MIN);
5692 	phba->cgn_evt_minute++;
5693 
5694 	/* We should get to this point in the routine on 1 minute intervals */
5695 
5696 	ktime_get_real_ts64(&cur_time);
5697 	time64_to_tm(cur_time.tv_sec, 0, &broken);
5698 
5699 	if (phba->cgn_fpin_frequency &&
5700 	    phba->cgn_fpin_frequency != LPFC_FPIN_INIT_FREQ) {
5701 		value = LPFC_CGN_TIMER_TO_MIN / phba->cgn_fpin_frequency;
5702 		cp->cgn_stat_npm = value;
5703 	}
5704 
5705 	/* Read and clear the latency counters for this minute */
5706 	lvalue = atomic_read(&phba->cgn_latency_evt_cnt);
5707 	latsum = atomic64_read(&phba->cgn_latency_evt);
5708 	atomic_set(&phba->cgn_latency_evt_cnt, 0);
5709 	atomic64_set(&phba->cgn_latency_evt, 0);
5710 
5711 	/* We need to store MB/sec bandwidth in the congestion information.
5712 	 * block_cnt is count of 512 byte blocks for the entire minute,
5713 	 * bps will get bytes per sec before finally converting to MB/sec.
5714 	 */
5715 	bps = div_u64(phba->rx_block_cnt, LPFC_SEC_MIN) * 512;
5716 	phba->rx_block_cnt = 0;
5717 	mvalue = bps / (1024 * 1024); /* convert to MB/sec */
5718 
5719 	/* Every minute */
5720 	/* cgn parameters */
5721 	cp->cgn_info_mode = phba->cgn_p.cgn_param_mode;
5722 	cp->cgn_info_level0 = phba->cgn_p.cgn_param_level0;
5723 	cp->cgn_info_level1 = phba->cgn_p.cgn_param_level1;
5724 	cp->cgn_info_level2 = phba->cgn_p.cgn_param_level2;
5725 
5726 	/* Fill in default LUN qdepth */
5727 	value = (uint16_t)(phba->pport->cfg_lun_queue_depth);
5728 	cp->cgn_lunq = cpu_to_le16(value);
5729 
5730 	/* Record congestion buffer info - every minute
5731 	 * cgn_driver_evt_cnt (Driver events)
5732 	 * cgn_fabric_warn_cnt (Congestion Warnings)
5733 	 * cgn_latency_evt_cnt / cgn_latency_evt (IO Latency)
5734 	 * cgn_fabric_alarm_cnt (Congestion Alarms)
5735 	 */
5736 	index = ++cp->cgn_index_minute;
5737 	if (cp->cgn_index_minute == LPFC_MIN_HOUR) {
5738 		cp->cgn_index_minute = 0;
5739 		index = 0;
5740 	}
5741 
5742 	/* Get the number of driver events in this sample and reset counter */
5743 	dvalue = atomic_read(&phba->cgn_driver_evt_cnt);
5744 	atomic_set(&phba->cgn_driver_evt_cnt, 0);
5745 
5746 	/* Get the number of warning events - FPIN and Signal for this minute */
5747 	wvalue = 0;
5748 	if ((phba->cgn_reg_fpin & LPFC_CGN_FPIN_WARN) ||
5749 	    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY ||
5750 	    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM)
5751 		wvalue = atomic_read(&phba->cgn_fabric_warn_cnt);
5752 	atomic_set(&phba->cgn_fabric_warn_cnt, 0);
5753 
5754 	/* Get the number of alarm events - FPIN and Signal for this minute */
5755 	avalue = 0;
5756 	if ((phba->cgn_reg_fpin & LPFC_CGN_FPIN_ALARM) ||
5757 	    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM)
5758 		avalue = atomic_read(&phba->cgn_fabric_alarm_cnt);
5759 	atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
5760 
5761 	/* Collect the driver, warning, alarm and latency counts for this
5762 	 * minute into the driver congestion buffer.
5763 	 */
5764 	ptr = &cp->cgn_drvr_min[index];
5765 	value = (uint16_t)dvalue;
5766 	*ptr = cpu_to_le16(value);
5767 
5768 	ptr = &cp->cgn_warn_min[index];
5769 	value = (uint16_t)wvalue;
5770 	*ptr = cpu_to_le16(value);
5771 
5772 	ptr = &cp->cgn_alarm_min[index];
5773 	value = (uint16_t)avalue;
5774 	*ptr = cpu_to_le16(value);
5775 
5776 	lptr = &cp->cgn_latency_min[index];
5777 	if (lvalue) {
5778 		lvalue = (uint32_t)div_u64(latsum, lvalue);
5779 		*lptr = cpu_to_le32(lvalue);
5780 	} else {
5781 		*lptr = 0;
5782 	}
5783 
5784 	/* Collect the bandwidth value into the driver's congesion buffer. */
5785 	mptr = &cp->cgn_bw_min[index];
5786 	*mptr = cpu_to_le16(mvalue);
5787 
5788 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5789 			"2418 Congestion Info - minute (%d): %d %d %d %d %d\n",
5790 			index, dvalue, wvalue, *lptr, mvalue, avalue);
5791 
5792 	/* Every hour */
5793 	if ((phba->cgn_evt_minute % LPFC_MIN_HOUR) == 0) {
5794 		/* Record congestion buffer info - every hour
5795 		 * Collapse all minutes into an hour
5796 		 */
5797 		index = ++cp->cgn_index_hour;
5798 		if (cp->cgn_index_hour == LPFC_HOUR_DAY) {
5799 			cp->cgn_index_hour = 0;
5800 			index = 0;
5801 		}
5802 
5803 		dvalue = 0;
5804 		wvalue = 0;
5805 		lvalue = 0;
5806 		avalue = 0;
5807 		mvalue = 0;
5808 		mbps = 0;
5809 		for (i = 0; i < LPFC_MIN_HOUR; i++) {
5810 			dvalue += le16_to_cpu(cp->cgn_drvr_min[i]);
5811 			wvalue += le16_to_cpu(cp->cgn_warn_min[i]);
5812 			lvalue += le32_to_cpu(cp->cgn_latency_min[i]);
5813 			mbps += le16_to_cpu(cp->cgn_bw_min[i]);
5814 			avalue += le16_to_cpu(cp->cgn_alarm_min[i]);
5815 		}
5816 		if (lvalue)		/* Avg of latency averages */
5817 			lvalue /= LPFC_MIN_HOUR;
5818 		if (mbps)		/* Avg of Bandwidth averages */
5819 			mvalue = mbps / LPFC_MIN_HOUR;
5820 
5821 		lptr = &cp->cgn_drvr_hr[index];
5822 		*lptr = cpu_to_le32(dvalue);
5823 		lptr = &cp->cgn_warn_hr[index];
5824 		*lptr = cpu_to_le32(wvalue);
5825 		lptr = &cp->cgn_latency_hr[index];
5826 		*lptr = cpu_to_le32(lvalue);
5827 		mptr = &cp->cgn_bw_hr[index];
5828 		*mptr = cpu_to_le16(mvalue);
5829 		lptr = &cp->cgn_alarm_hr[index];
5830 		*lptr = cpu_to_le32(avalue);
5831 
5832 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5833 				"2419 Congestion Info - hour "
5834 				"(%d): %d %d %d %d %d\n",
5835 				index, dvalue, wvalue, lvalue, mvalue, avalue);
5836 	}
5837 
5838 	/* Every day */
5839 	if ((phba->cgn_evt_minute % LPFC_MIN_DAY) == 0) {
5840 		/* Record congestion buffer info - every hour
5841 		 * Collapse all hours into a day. Rotate days
5842 		 * after LPFC_MAX_CGN_DAYS.
5843 		 */
5844 		index = ++cp->cgn_index_day;
5845 		if (cp->cgn_index_day == LPFC_MAX_CGN_DAYS) {
5846 			cp->cgn_index_day = 0;
5847 			index = 0;
5848 		}
5849 
5850 		/* Anytime we overwrite daily index 0, after we wrap,
5851 		 * we will be overwriting the oldest day, so we must
5852 		 * update the congestion data start time for that day.
5853 		 * That start time should have previously been saved after
5854 		 * we wrote the last days worth of data.
5855 		 */
5856 		if ((phba->hba_flag & HBA_CGN_DAY_WRAP) && index == 0) {
5857 			time64_to_tm(phba->cgn_daily_ts.tv_sec, 0, &broken);
5858 
5859 			cp->cgn_info_month = broken.tm_mon + 1;
5860 			cp->cgn_info_day = broken.tm_mday;
5861 			cp->cgn_info_year = broken.tm_year - 100;
5862 			cp->cgn_info_hour = broken.tm_hour;
5863 			cp->cgn_info_minute = broken.tm_min;
5864 			cp->cgn_info_second = broken.tm_sec;
5865 
5866 			lpfc_printf_log
5867 				(phba, KERN_INFO, LOG_CGN_MGMT,
5868 				"2646 CGNInfo idx0 Start Time: "
5869 				"%d/%d/%d %d:%d:%d\n",
5870 				cp->cgn_info_day, cp->cgn_info_month,
5871 				cp->cgn_info_year, cp->cgn_info_hour,
5872 				cp->cgn_info_minute, cp->cgn_info_second);
5873 		}
5874 
5875 		dvalue = 0;
5876 		wvalue = 0;
5877 		lvalue = 0;
5878 		mvalue = 0;
5879 		mbps = 0;
5880 		avalue = 0;
5881 		for (i = 0; i < LPFC_HOUR_DAY; i++) {
5882 			dvalue += le32_to_cpu(cp->cgn_drvr_hr[i]);
5883 			wvalue += le32_to_cpu(cp->cgn_warn_hr[i]);
5884 			lvalue += le32_to_cpu(cp->cgn_latency_hr[i]);
5885 			mbps += le16_to_cpu(cp->cgn_bw_hr[i]);
5886 			avalue += le32_to_cpu(cp->cgn_alarm_hr[i]);
5887 		}
5888 		if (lvalue)		/* Avg of latency averages */
5889 			lvalue /= LPFC_HOUR_DAY;
5890 		if (mbps)		/* Avg of Bandwidth averages */
5891 			mvalue = mbps / LPFC_HOUR_DAY;
5892 
5893 		lptr = &cp->cgn_drvr_day[index];
5894 		*lptr = cpu_to_le32(dvalue);
5895 		lptr = &cp->cgn_warn_day[index];
5896 		*lptr = cpu_to_le32(wvalue);
5897 		lptr = &cp->cgn_latency_day[index];
5898 		*lptr = cpu_to_le32(lvalue);
5899 		mptr = &cp->cgn_bw_day[index];
5900 		*mptr = cpu_to_le16(mvalue);
5901 		lptr = &cp->cgn_alarm_day[index];
5902 		*lptr = cpu_to_le32(avalue);
5903 
5904 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5905 				"2420 Congestion Info - daily (%d): "
5906 				"%d %d %d %d %d\n",
5907 				index, dvalue, wvalue, lvalue, mvalue, avalue);
5908 
5909 		/* We just wrote LPFC_MAX_CGN_DAYS of data,
5910 		 * so we are wrapped on any data after this.
5911 		 * Save this as the start time for the next day.
5912 		 */
5913 		if (index == (LPFC_MAX_CGN_DAYS - 1)) {
5914 			phba->hba_flag |= HBA_CGN_DAY_WRAP;
5915 			ktime_get_real_ts64(&phba->cgn_daily_ts);
5916 		}
5917 	}
5918 
5919 	/* Use the frequency found in the last rcv'ed FPIN */
5920 	value = phba->cgn_fpin_frequency;
5921 	cp->cgn_warn_freq = cpu_to_le16(value);
5922 	cp->cgn_alarm_freq = cpu_to_le16(value);
5923 
5924 	lvalue = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ,
5925 				     LPFC_CGN_CRC32_SEED);
5926 	cp->cgn_info_crc = cpu_to_le32(lvalue);
5927 }
5928 
5929 /**
5930  * lpfc_calc_cmf_latency - latency from start of rxate timer interval
5931  * @phba: The Hba for which this call is being executed.
5932  *
5933  * The routine calculates the latency from the beginning of the CMF timer
5934  * interval to the current point in time. It is called from IO completion
5935  * when we exceed our Bandwidth limitation for the time interval.
5936  */
5937 uint32_t
5938 lpfc_calc_cmf_latency(struct lpfc_hba *phba)
5939 {
5940 	struct timespec64 cmpl_time;
5941 	uint32_t msec = 0;
5942 
5943 	ktime_get_real_ts64(&cmpl_time);
5944 
5945 	/* This routine works on a ms granularity so sec and usec are
5946 	 * converted accordingly.
5947 	 */
5948 	if (cmpl_time.tv_sec == phba->cmf_latency.tv_sec) {
5949 		msec = (cmpl_time.tv_nsec - phba->cmf_latency.tv_nsec) /
5950 			NSEC_PER_MSEC;
5951 	} else {
5952 		if (cmpl_time.tv_nsec >= phba->cmf_latency.tv_nsec) {
5953 			msec = (cmpl_time.tv_sec -
5954 				phba->cmf_latency.tv_sec) * MSEC_PER_SEC;
5955 			msec += ((cmpl_time.tv_nsec -
5956 				  phba->cmf_latency.tv_nsec) / NSEC_PER_MSEC);
5957 		} else {
5958 			msec = (cmpl_time.tv_sec - phba->cmf_latency.tv_sec -
5959 				1) * MSEC_PER_SEC;
5960 			msec += (((NSEC_PER_SEC - phba->cmf_latency.tv_nsec) +
5961 				 cmpl_time.tv_nsec) / NSEC_PER_MSEC);
5962 		}
5963 	}
5964 	return msec;
5965 }
5966 
5967 /**
5968  * lpfc_cmf_timer -  This is the timer function for one congestion
5969  * rate interval.
5970  * @timer: Pointer to the high resolution timer that expired
5971  */
5972 static enum hrtimer_restart
5973 lpfc_cmf_timer(struct hrtimer *timer)
5974 {
5975 	struct lpfc_hba *phba = container_of(timer, struct lpfc_hba,
5976 					     cmf_timer);
5977 	struct rx_info_entry entry;
5978 	uint32_t io_cnt;
5979 	uint32_t busy, max_read;
5980 	uint64_t total, rcv, lat, mbpi, extra, cnt;
5981 	int timer_interval = LPFC_CMF_INTERVAL;
5982 	uint32_t ms;
5983 	struct lpfc_cgn_stat *cgs;
5984 	int cpu;
5985 
5986 	/* Only restart the timer if congestion mgmt is on */
5987 	if (phba->cmf_active_mode == LPFC_CFG_OFF ||
5988 	    !phba->cmf_latency.tv_sec) {
5989 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5990 				"6224 CMF timer exit: %d %lld\n",
5991 				phba->cmf_active_mode,
5992 				(uint64_t)phba->cmf_latency.tv_sec);
5993 		return HRTIMER_NORESTART;
5994 	}
5995 
5996 	/* If pport is not ready yet, just exit and wait for
5997 	 * the next timer cycle to hit.
5998 	 */
5999 	if (!phba->pport)
6000 		goto skip;
6001 
6002 	/* Do not block SCSI IO while in the timer routine since
6003 	 * total_bytes will be cleared
6004 	 */
6005 	atomic_set(&phba->cmf_stop_io, 1);
6006 
6007 	/* First we need to calculate the actual ms between
6008 	 * the last timer interrupt and this one. We ask for
6009 	 * LPFC_CMF_INTERVAL, however the actual time may
6010 	 * vary depending on system overhead.
6011 	 */
6012 	ms = lpfc_calc_cmf_latency(phba);
6013 
6014 
6015 	/* Immediately after we calculate the time since the last
6016 	 * timer interrupt, set the start time for the next
6017 	 * interrupt
6018 	 */
6019 	ktime_get_real_ts64(&phba->cmf_latency);
6020 
6021 	phba->cmf_link_byte_count =
6022 		div_u64(phba->cmf_max_line_rate * LPFC_CMF_INTERVAL, 1000);
6023 
6024 	/* Collect all the stats from the prior timer interval */
6025 	total = 0;
6026 	io_cnt = 0;
6027 	lat = 0;
6028 	rcv = 0;
6029 	for_each_present_cpu(cpu) {
6030 		cgs = per_cpu_ptr(phba->cmf_stat, cpu);
6031 		total += atomic64_xchg(&cgs->total_bytes, 0);
6032 		io_cnt += atomic_xchg(&cgs->rx_io_cnt, 0);
6033 		lat += atomic64_xchg(&cgs->rx_latency, 0);
6034 		rcv += atomic64_xchg(&cgs->rcv_bytes, 0);
6035 	}
6036 
6037 	/* Before we issue another CMF_SYNC_WQE, retrieve the BW
6038 	 * returned from the last CMF_SYNC_WQE issued, from
6039 	 * cmf_last_sync_bw. This will be the target BW for
6040 	 * this next timer interval.
6041 	 */
6042 	if (phba->cmf_active_mode == LPFC_CFG_MANAGED &&
6043 	    phba->link_state != LPFC_LINK_DOWN &&
6044 	    phba->hba_flag & HBA_SETUP) {
6045 		mbpi = phba->cmf_last_sync_bw;
6046 		phba->cmf_last_sync_bw = 0;
6047 		extra = 0;
6048 
6049 		/* Calculate any extra bytes needed to account for the
6050 		 * timer accuracy. If we are less than LPFC_CMF_INTERVAL
6051 		 * calculate the adjustment needed for total to reflect
6052 		 * a full LPFC_CMF_INTERVAL.
6053 		 */
6054 		if (ms && ms < LPFC_CMF_INTERVAL) {
6055 			cnt = div_u64(total, ms); /* bytes per ms */
6056 			cnt *= LPFC_CMF_INTERVAL; /* what total should be */
6057 
6058 			/* If the timeout is scheduled to be shorter,
6059 			 * this value may skew the data, so cap it at mbpi.
6060 			 */
6061 			if ((phba->hba_flag & HBA_SHORT_CMF) && cnt > mbpi)
6062 				cnt = mbpi;
6063 
6064 			extra = cnt - total;
6065 		}
6066 		lpfc_issue_cmf_sync_wqe(phba, LPFC_CMF_INTERVAL, total + extra);
6067 	} else {
6068 		/* For Monitor mode or link down we want mbpi
6069 		 * to be the full link speed
6070 		 */
6071 		mbpi = phba->cmf_link_byte_count;
6072 		extra = 0;
6073 	}
6074 	phba->cmf_timer_cnt++;
6075 
6076 	if (io_cnt) {
6077 		/* Update congestion info buffer latency in us */
6078 		atomic_add(io_cnt, &phba->cgn_latency_evt_cnt);
6079 		atomic64_add(lat, &phba->cgn_latency_evt);
6080 	}
6081 	busy = atomic_xchg(&phba->cmf_busy, 0);
6082 	max_read = atomic_xchg(&phba->rx_max_read_cnt, 0);
6083 
6084 	/* Calculate MBPI for the next timer interval */
6085 	if (mbpi) {
6086 		if (mbpi > phba->cmf_link_byte_count ||
6087 		    phba->cmf_active_mode == LPFC_CFG_MONITOR)
6088 			mbpi = phba->cmf_link_byte_count;
6089 
6090 		/* Change max_bytes_per_interval to what the prior
6091 		 * CMF_SYNC_WQE cmpl indicated.
6092 		 */
6093 		if (mbpi != phba->cmf_max_bytes_per_interval)
6094 			phba->cmf_max_bytes_per_interval = mbpi;
6095 	}
6096 
6097 	/* Save rxmonitor information for debug */
6098 	if (phba->rx_monitor) {
6099 		entry.total_bytes = total;
6100 		entry.cmf_bytes = total + extra;
6101 		entry.rcv_bytes = rcv;
6102 		entry.cmf_busy = busy;
6103 		entry.cmf_info = phba->cmf_active_info;
6104 		if (io_cnt) {
6105 			entry.avg_io_latency = div_u64(lat, io_cnt);
6106 			entry.avg_io_size = div_u64(rcv, io_cnt);
6107 		} else {
6108 			entry.avg_io_latency = 0;
6109 			entry.avg_io_size = 0;
6110 		}
6111 		entry.max_read_cnt = max_read;
6112 		entry.io_cnt = io_cnt;
6113 		entry.max_bytes_per_interval = mbpi;
6114 		if (phba->cmf_active_mode == LPFC_CFG_MANAGED)
6115 			entry.timer_utilization = phba->cmf_last_ts;
6116 		else
6117 			entry.timer_utilization = ms;
6118 		entry.timer_interval = ms;
6119 		phba->cmf_last_ts = 0;
6120 
6121 		lpfc_rx_monitor_record(phba->rx_monitor, &entry);
6122 	}
6123 
6124 	if (phba->cmf_active_mode == LPFC_CFG_MONITOR) {
6125 		/* If Monitor mode, check if we are oversubscribed
6126 		 * against the full line rate.
6127 		 */
6128 		if (mbpi && total > mbpi)
6129 			atomic_inc(&phba->cgn_driver_evt_cnt);
6130 	}
6131 	phba->rx_block_cnt += div_u64(rcv, 512);  /* save 512 byte block cnt */
6132 
6133 	/* Each minute save Fabric and Driver congestion information */
6134 	lpfc_cgn_save_evt_cnt(phba);
6135 
6136 	phba->hba_flag &= ~HBA_SHORT_CMF;
6137 
6138 	/* Since we need to call lpfc_cgn_save_evt_cnt every minute, on the
6139 	 * minute, adjust our next timer interval, if needed, to ensure a
6140 	 * 1 minute granularity when we get the next timer interrupt.
6141 	 */
6142 	if (time_after(jiffies + msecs_to_jiffies(LPFC_CMF_INTERVAL),
6143 		       phba->cgn_evt_timestamp)) {
6144 		timer_interval = jiffies_to_msecs(phba->cgn_evt_timestamp -
6145 						  jiffies);
6146 		if (timer_interval <= 0)
6147 			timer_interval = LPFC_CMF_INTERVAL;
6148 		else
6149 			phba->hba_flag |= HBA_SHORT_CMF;
6150 
6151 		/* If we adjust timer_interval, max_bytes_per_interval
6152 		 * needs to be adjusted as well.
6153 		 */
6154 		phba->cmf_link_byte_count = div_u64(phba->cmf_max_line_rate *
6155 						    timer_interval, 1000);
6156 		if (phba->cmf_active_mode == LPFC_CFG_MONITOR)
6157 			phba->cmf_max_bytes_per_interval =
6158 				phba->cmf_link_byte_count;
6159 	}
6160 
6161 	/* Since total_bytes has already been zero'ed, its okay to unblock
6162 	 * after max_bytes_per_interval is setup.
6163 	 */
6164 	if (atomic_xchg(&phba->cmf_bw_wait, 0))
6165 		queue_work(phba->wq, &phba->unblock_request_work);
6166 
6167 	/* SCSI IO is now unblocked */
6168 	atomic_set(&phba->cmf_stop_io, 0);
6169 
6170 skip:
6171 	hrtimer_forward_now(timer,
6172 			    ktime_set(0, timer_interval * NSEC_PER_MSEC));
6173 	return HRTIMER_RESTART;
6174 }
6175 
6176 #define trunk_link_status(__idx)\
6177 	bf_get(lpfc_acqe_fc_la_trunk_config_port##__idx, acqe_fc) ?\
6178 	       ((phba->trunk_link.link##__idx.state == LPFC_LINK_UP) ?\
6179 		"Link up" : "Link down") : "NA"
6180 /* Did port __idx reported an error */
6181 #define trunk_port_fault(__idx)\
6182 	bf_get(lpfc_acqe_fc_la_trunk_config_port##__idx, acqe_fc) ?\
6183 	       (port_fault & (1 << __idx) ? "YES" : "NO") : "NA"
6184 
6185 static void
6186 lpfc_update_trunk_link_status(struct lpfc_hba *phba,
6187 			      struct lpfc_acqe_fc_la *acqe_fc)
6188 {
6189 	uint8_t port_fault = bf_get(lpfc_acqe_fc_la_trunk_linkmask, acqe_fc);
6190 	uint8_t err = bf_get(lpfc_acqe_fc_la_trunk_fault, acqe_fc);
6191 	u8 cnt = 0;
6192 
6193 	phba->sli4_hba.link_state.speed =
6194 		lpfc_sli4_port_speed_parse(phba, LPFC_TRAILER_CODE_FC,
6195 				bf_get(lpfc_acqe_fc_la_speed, acqe_fc));
6196 
6197 	phba->sli4_hba.link_state.logical_speed =
6198 				bf_get(lpfc_acqe_fc_la_llink_spd, acqe_fc) * 10;
6199 	/* We got FC link speed, convert to fc_linkspeed (READ_TOPOLOGY) */
6200 	phba->fc_linkspeed =
6201 		 lpfc_async_link_speed_to_read_top(
6202 				phba,
6203 				bf_get(lpfc_acqe_fc_la_speed, acqe_fc));
6204 
6205 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port0, acqe_fc)) {
6206 		phba->trunk_link.link0.state =
6207 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port0, acqe_fc)
6208 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
6209 		phba->trunk_link.link0.fault = port_fault & 0x1 ? err : 0;
6210 		cnt++;
6211 	}
6212 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port1, acqe_fc)) {
6213 		phba->trunk_link.link1.state =
6214 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port1, acqe_fc)
6215 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
6216 		phba->trunk_link.link1.fault = port_fault & 0x2 ? err : 0;
6217 		cnt++;
6218 	}
6219 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port2, acqe_fc)) {
6220 		phba->trunk_link.link2.state =
6221 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port2, acqe_fc)
6222 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
6223 		phba->trunk_link.link2.fault = port_fault & 0x4 ? err : 0;
6224 		cnt++;
6225 	}
6226 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port3, acqe_fc)) {
6227 		phba->trunk_link.link3.state =
6228 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port3, acqe_fc)
6229 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
6230 		phba->trunk_link.link3.fault = port_fault & 0x8 ? err : 0;
6231 		cnt++;
6232 	}
6233 
6234 	if (cnt)
6235 		phba->trunk_link.phy_lnk_speed =
6236 			phba->sli4_hba.link_state.logical_speed / (cnt * 1000);
6237 	else
6238 		phba->trunk_link.phy_lnk_speed = LPFC_LINK_SPEED_UNKNOWN;
6239 
6240 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6241 			"2910 Async FC Trunking Event - Speed:%d\n"
6242 			"\tLogical speed:%d "
6243 			"port0: %s port1: %s port2: %s port3: %s\n",
6244 			phba->sli4_hba.link_state.speed,
6245 			phba->sli4_hba.link_state.logical_speed,
6246 			trunk_link_status(0), trunk_link_status(1),
6247 			trunk_link_status(2), trunk_link_status(3));
6248 
6249 	if (phba->cmf_active_mode != LPFC_CFG_OFF)
6250 		lpfc_cmf_signal_init(phba);
6251 
6252 	if (port_fault)
6253 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6254 				"3202 trunk error:0x%x (%s) seen on port0:%s "
6255 				/*
6256 				 * SLI-4: We have only 0xA error codes
6257 				 * defined as of now. print an appropriate
6258 				 * message in case driver needs to be updated.
6259 				 */
6260 				"port1:%s port2:%s port3:%s\n", err, err > 0xA ?
6261 				"UNDEFINED. update driver." : trunk_errmsg[err],
6262 				trunk_port_fault(0), trunk_port_fault(1),
6263 				trunk_port_fault(2), trunk_port_fault(3));
6264 }
6265 
6266 
6267 /**
6268  * lpfc_sli4_async_fc_evt - Process the asynchronous FC link event
6269  * @phba: pointer to lpfc hba data structure.
6270  * @acqe_fc: pointer to the async fc completion queue entry.
6271  *
6272  * This routine is to handle the SLI4 asynchronous FC event. It will simply log
6273  * that the event was received and then issue a read_topology mailbox command so
6274  * that the rest of the driver will treat it the same as SLI3.
6275  **/
6276 static void
6277 lpfc_sli4_async_fc_evt(struct lpfc_hba *phba, struct lpfc_acqe_fc_la *acqe_fc)
6278 {
6279 	LPFC_MBOXQ_t *pmb;
6280 	MAILBOX_t *mb;
6281 	struct lpfc_mbx_read_top *la;
6282 	int rc;
6283 
6284 	if (bf_get(lpfc_trailer_type, acqe_fc) !=
6285 	    LPFC_FC_LA_EVENT_TYPE_FC_LINK) {
6286 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6287 				"2895 Non FC link Event detected.(%d)\n",
6288 				bf_get(lpfc_trailer_type, acqe_fc));
6289 		return;
6290 	}
6291 
6292 	if (bf_get(lpfc_acqe_fc_la_att_type, acqe_fc) ==
6293 	    LPFC_FC_LA_TYPE_TRUNKING_EVENT) {
6294 		lpfc_update_trunk_link_status(phba, acqe_fc);
6295 		return;
6296 	}
6297 
6298 	/* Keep the link status for extra SLI4 state machine reference */
6299 	phba->sli4_hba.link_state.speed =
6300 			lpfc_sli4_port_speed_parse(phba, LPFC_TRAILER_CODE_FC,
6301 				bf_get(lpfc_acqe_fc_la_speed, acqe_fc));
6302 	phba->sli4_hba.link_state.duplex = LPFC_ASYNC_LINK_DUPLEX_FULL;
6303 	phba->sli4_hba.link_state.topology =
6304 				bf_get(lpfc_acqe_fc_la_topology, acqe_fc);
6305 	phba->sli4_hba.link_state.status =
6306 				bf_get(lpfc_acqe_fc_la_att_type, acqe_fc);
6307 	phba->sli4_hba.link_state.type =
6308 				bf_get(lpfc_acqe_fc_la_port_type, acqe_fc);
6309 	phba->sli4_hba.link_state.number =
6310 				bf_get(lpfc_acqe_fc_la_port_number, acqe_fc);
6311 	phba->sli4_hba.link_state.fault =
6312 				bf_get(lpfc_acqe_link_fault, acqe_fc);
6313 
6314 	if (bf_get(lpfc_acqe_fc_la_att_type, acqe_fc) ==
6315 	    LPFC_FC_LA_TYPE_LINK_DOWN)
6316 		phba->sli4_hba.link_state.logical_speed = 0;
6317 	else if (!phba->sli4_hba.conf_trunk)
6318 		phba->sli4_hba.link_state.logical_speed =
6319 				bf_get(lpfc_acqe_fc_la_llink_spd, acqe_fc) * 10;
6320 
6321 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6322 			"2896 Async FC event - Speed:%dGBaud Topology:x%x "
6323 			"LA Type:x%x Port Type:%d Port Number:%d Logical speed:"
6324 			"%dMbps Fault:%d\n",
6325 			phba->sli4_hba.link_state.speed,
6326 			phba->sli4_hba.link_state.topology,
6327 			phba->sli4_hba.link_state.status,
6328 			phba->sli4_hba.link_state.type,
6329 			phba->sli4_hba.link_state.number,
6330 			phba->sli4_hba.link_state.logical_speed,
6331 			phba->sli4_hba.link_state.fault);
6332 	pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6333 	if (!pmb) {
6334 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6335 				"2897 The mboxq allocation failed\n");
6336 		return;
6337 	}
6338 	rc = lpfc_mbox_rsrc_prep(phba, pmb);
6339 	if (rc) {
6340 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6341 				"2898 The mboxq prep failed\n");
6342 		goto out_free_pmb;
6343 	}
6344 
6345 	/* Cleanup any outstanding ELS commands */
6346 	lpfc_els_flush_all_cmd(phba);
6347 
6348 	/* Block ELS IOCBs until we have done process link event */
6349 	phba->sli4_hba.els_wq->pring->flag |= LPFC_STOP_IOCB_EVENT;
6350 
6351 	/* Update link event statistics */
6352 	phba->sli.slistat.link_event++;
6353 
6354 	/* Create lpfc_handle_latt mailbox command from link ACQE */
6355 	lpfc_read_topology(phba, pmb, (struct lpfc_dmabuf *)pmb->ctx_buf);
6356 	pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
6357 	pmb->vport = phba->pport;
6358 
6359 	if (phba->sli4_hba.link_state.status != LPFC_FC_LA_TYPE_LINK_UP) {
6360 		phba->link_flag &= ~(LS_MDS_LINK_DOWN | LS_MDS_LOOPBACK);
6361 
6362 		switch (phba->sli4_hba.link_state.status) {
6363 		case LPFC_FC_LA_TYPE_MDS_LINK_DOWN:
6364 			phba->link_flag |= LS_MDS_LINK_DOWN;
6365 			break;
6366 		case LPFC_FC_LA_TYPE_MDS_LOOPBACK:
6367 			phba->link_flag |= LS_MDS_LOOPBACK;
6368 			break;
6369 		default:
6370 			break;
6371 		}
6372 
6373 		/* Initialize completion status */
6374 		mb = &pmb->u.mb;
6375 		mb->mbxStatus = MBX_SUCCESS;
6376 
6377 		/* Parse port fault information field */
6378 		lpfc_sli4_parse_latt_fault(phba, (void *)acqe_fc);
6379 
6380 		/* Parse and translate link attention fields */
6381 		la = (struct lpfc_mbx_read_top *)&pmb->u.mb.un.varReadTop;
6382 		la->eventTag = acqe_fc->event_tag;
6383 
6384 		if (phba->sli4_hba.link_state.status ==
6385 		    LPFC_FC_LA_TYPE_UNEXP_WWPN) {
6386 			bf_set(lpfc_mbx_read_top_att_type, la,
6387 			       LPFC_FC_LA_TYPE_UNEXP_WWPN);
6388 		} else {
6389 			bf_set(lpfc_mbx_read_top_att_type, la,
6390 			       LPFC_FC_LA_TYPE_LINK_DOWN);
6391 		}
6392 		/* Invoke the mailbox command callback function */
6393 		lpfc_mbx_cmpl_read_topology(phba, pmb);
6394 
6395 		return;
6396 	}
6397 
6398 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
6399 	if (rc == MBX_NOT_FINISHED)
6400 		goto out_free_pmb;
6401 	return;
6402 
6403 out_free_pmb:
6404 	lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
6405 }
6406 
6407 /**
6408  * lpfc_sli4_async_sli_evt - Process the asynchronous SLI link event
6409  * @phba: pointer to lpfc hba data structure.
6410  * @acqe_sli: pointer to the async SLI completion queue entry.
6411  *
6412  * This routine is to handle the SLI4 asynchronous SLI events.
6413  **/
6414 static void
6415 lpfc_sli4_async_sli_evt(struct lpfc_hba *phba, struct lpfc_acqe_sli *acqe_sli)
6416 {
6417 	char port_name;
6418 	char message[128];
6419 	uint8_t status;
6420 	uint8_t evt_type;
6421 	uint8_t operational = 0;
6422 	struct temp_event temp_event_data;
6423 	struct lpfc_acqe_misconfigured_event *misconfigured;
6424 	struct lpfc_acqe_cgn_signal *cgn_signal;
6425 	struct Scsi_Host  *shost;
6426 	struct lpfc_vport **vports;
6427 	int rc, i, cnt;
6428 
6429 	evt_type = bf_get(lpfc_trailer_type, acqe_sli);
6430 
6431 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6432 			"2901 Async SLI event - Type:%d, Event Data: x%08x "
6433 			"x%08x x%08x x%08x\n", evt_type,
6434 			acqe_sli->event_data1, acqe_sli->event_data2,
6435 			acqe_sli->event_data3, acqe_sli->trailer);
6436 
6437 	port_name = phba->Port[0];
6438 	if (port_name == 0x00)
6439 		port_name = '?'; /* get port name is empty */
6440 
6441 	switch (evt_type) {
6442 	case LPFC_SLI_EVENT_TYPE_OVER_TEMP:
6443 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
6444 		temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
6445 		temp_event_data.data = (uint32_t)acqe_sli->event_data1;
6446 
6447 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6448 				"3190 Over Temperature:%d Celsius- Port Name %c\n",
6449 				acqe_sli->event_data1, port_name);
6450 
6451 		phba->sfp_warning |= LPFC_TRANSGRESSION_HIGH_TEMPERATURE;
6452 		shost = lpfc_shost_from_vport(phba->pport);
6453 		fc_host_post_vendor_event(shost, fc_get_event_number(),
6454 					  sizeof(temp_event_data),
6455 					  (char *)&temp_event_data,
6456 					  SCSI_NL_VID_TYPE_PCI
6457 					  | PCI_VENDOR_ID_EMULEX);
6458 		break;
6459 	case LPFC_SLI_EVENT_TYPE_NORM_TEMP:
6460 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
6461 		temp_event_data.event_code = LPFC_NORMAL_TEMP;
6462 		temp_event_data.data = (uint32_t)acqe_sli->event_data1;
6463 
6464 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI | LOG_LDS_EVENT,
6465 				"3191 Normal Temperature:%d Celsius - Port Name %c\n",
6466 				acqe_sli->event_data1, port_name);
6467 
6468 		shost = lpfc_shost_from_vport(phba->pport);
6469 		fc_host_post_vendor_event(shost, fc_get_event_number(),
6470 					  sizeof(temp_event_data),
6471 					  (char *)&temp_event_data,
6472 					  SCSI_NL_VID_TYPE_PCI
6473 					  | PCI_VENDOR_ID_EMULEX);
6474 		break;
6475 	case LPFC_SLI_EVENT_TYPE_MISCONFIGURED:
6476 		misconfigured = (struct lpfc_acqe_misconfigured_event *)
6477 					&acqe_sli->event_data1;
6478 
6479 		/* fetch the status for this port */
6480 		switch (phba->sli4_hba.lnk_info.lnk_no) {
6481 		case LPFC_LINK_NUMBER_0:
6482 			status = bf_get(lpfc_sli_misconfigured_port0_state,
6483 					&misconfigured->theEvent);
6484 			operational = bf_get(lpfc_sli_misconfigured_port0_op,
6485 					&misconfigured->theEvent);
6486 			break;
6487 		case LPFC_LINK_NUMBER_1:
6488 			status = bf_get(lpfc_sli_misconfigured_port1_state,
6489 					&misconfigured->theEvent);
6490 			operational = bf_get(lpfc_sli_misconfigured_port1_op,
6491 					&misconfigured->theEvent);
6492 			break;
6493 		case LPFC_LINK_NUMBER_2:
6494 			status = bf_get(lpfc_sli_misconfigured_port2_state,
6495 					&misconfigured->theEvent);
6496 			operational = bf_get(lpfc_sli_misconfigured_port2_op,
6497 					&misconfigured->theEvent);
6498 			break;
6499 		case LPFC_LINK_NUMBER_3:
6500 			status = bf_get(lpfc_sli_misconfigured_port3_state,
6501 					&misconfigured->theEvent);
6502 			operational = bf_get(lpfc_sli_misconfigured_port3_op,
6503 					&misconfigured->theEvent);
6504 			break;
6505 		default:
6506 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6507 					"3296 "
6508 					"LPFC_SLI_EVENT_TYPE_MISCONFIGURED "
6509 					"event: Invalid link %d",
6510 					phba->sli4_hba.lnk_info.lnk_no);
6511 			return;
6512 		}
6513 
6514 		/* Skip if optic state unchanged */
6515 		if (phba->sli4_hba.lnk_info.optic_state == status)
6516 			return;
6517 
6518 		switch (status) {
6519 		case LPFC_SLI_EVENT_STATUS_VALID:
6520 			sprintf(message, "Physical Link is functional");
6521 			break;
6522 		case LPFC_SLI_EVENT_STATUS_NOT_PRESENT:
6523 			sprintf(message, "Optics faulted/incorrectly "
6524 				"installed/not installed - Reseat optics, "
6525 				"if issue not resolved, replace.");
6526 			break;
6527 		case LPFC_SLI_EVENT_STATUS_WRONG_TYPE:
6528 			sprintf(message,
6529 				"Optics of two types installed - Remove one "
6530 				"optic or install matching pair of optics.");
6531 			break;
6532 		case LPFC_SLI_EVENT_STATUS_UNSUPPORTED:
6533 			sprintf(message, "Incompatible optics - Replace with "
6534 				"compatible optics for card to function.");
6535 			break;
6536 		case LPFC_SLI_EVENT_STATUS_UNQUALIFIED:
6537 			sprintf(message, "Unqualified optics - Replace with "
6538 				"Avago optics for Warranty and Technical "
6539 				"Support - Link is%s operational",
6540 				(operational) ? " not" : "");
6541 			break;
6542 		case LPFC_SLI_EVENT_STATUS_UNCERTIFIED:
6543 			sprintf(message, "Uncertified optics - Replace with "
6544 				"Avago-certified optics to enable link "
6545 				"operation - Link is%s operational",
6546 				(operational) ? " not" : "");
6547 			break;
6548 		default:
6549 			/* firmware is reporting a status we don't know about */
6550 			sprintf(message, "Unknown event status x%02x", status);
6551 			break;
6552 		}
6553 
6554 		/* Issue READ_CONFIG mbox command to refresh supported speeds */
6555 		rc = lpfc_sli4_read_config(phba);
6556 		if (rc) {
6557 			phba->lmt = 0;
6558 			lpfc_printf_log(phba, KERN_ERR,
6559 					LOG_TRACE_EVENT,
6560 					"3194 Unable to retrieve supported "
6561 					"speeds, rc = 0x%x\n", rc);
6562 		}
6563 		rc = lpfc_sli4_refresh_params(phba);
6564 		if (rc) {
6565 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6566 					"3174 Unable to update pls support, "
6567 					"rc x%x\n", rc);
6568 		}
6569 		vports = lpfc_create_vport_work_array(phba);
6570 		if (vports != NULL) {
6571 			for (i = 0; i <= phba->max_vports && vports[i] != NULL;
6572 					i++) {
6573 				shost = lpfc_shost_from_vport(vports[i]);
6574 				lpfc_host_supported_speeds_set(shost);
6575 			}
6576 		}
6577 		lpfc_destroy_vport_work_array(phba, vports);
6578 
6579 		phba->sli4_hba.lnk_info.optic_state = status;
6580 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6581 				"3176 Port Name %c %s\n", port_name, message);
6582 		break;
6583 	case LPFC_SLI_EVENT_TYPE_REMOTE_DPORT:
6584 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6585 				"3192 Remote DPort Test Initiated - "
6586 				"Event Data1:x%08x Event Data2: x%08x\n",
6587 				acqe_sli->event_data1, acqe_sli->event_data2);
6588 		break;
6589 	case LPFC_SLI_EVENT_TYPE_PORT_PARAMS_CHG:
6590 		/* Call FW to obtain active parms */
6591 		lpfc_sli4_cgn_parm_chg_evt(phba);
6592 		break;
6593 	case LPFC_SLI_EVENT_TYPE_MISCONF_FAWWN:
6594 		/* Misconfigured WWN. Reports that the SLI Port is configured
6595 		 * to use FA-WWN, but the attached device doesn’t support it.
6596 		 * Event Data1 - N.A, Event Data2 - N.A
6597 		 * This event only happens on the physical port.
6598 		 */
6599 		lpfc_log_msg(phba, KERN_WARNING, LOG_SLI | LOG_DISCOVERY,
6600 			     "2699 Misconfigured FA-PWWN - Attached device "
6601 			     "does not support FA-PWWN\n");
6602 		phba->sli4_hba.fawwpn_flag &= ~LPFC_FAWWPN_FABRIC;
6603 		memset(phba->pport->fc_portname.u.wwn, 0,
6604 		       sizeof(struct lpfc_name));
6605 		break;
6606 	case LPFC_SLI_EVENT_TYPE_EEPROM_FAILURE:
6607 		/* EEPROM failure. No driver action is required */
6608 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6609 			     "2518 EEPROM failure - "
6610 			     "Event Data1: x%08x Event Data2: x%08x\n",
6611 			     acqe_sli->event_data1, acqe_sli->event_data2);
6612 		break;
6613 	case LPFC_SLI_EVENT_TYPE_CGN_SIGNAL:
6614 		if (phba->cmf_active_mode == LPFC_CFG_OFF)
6615 			break;
6616 		cgn_signal = (struct lpfc_acqe_cgn_signal *)
6617 					&acqe_sli->event_data1;
6618 		phba->cgn_acqe_cnt++;
6619 
6620 		cnt = bf_get(lpfc_warn_acqe, cgn_signal);
6621 		atomic64_add(cnt, &phba->cgn_acqe_stat.warn);
6622 		atomic64_add(cgn_signal->alarm_cnt, &phba->cgn_acqe_stat.alarm);
6623 
6624 		/* no threshold for CMF, even 1 signal will trigger an event */
6625 
6626 		/* Alarm overrides warning, so check that first */
6627 		if (cgn_signal->alarm_cnt) {
6628 			if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
6629 				/* Keep track of alarm cnt for CMF_SYNC_WQE */
6630 				atomic_add(cgn_signal->alarm_cnt,
6631 					   &phba->cgn_sync_alarm_cnt);
6632 			}
6633 		} else if (cnt) {
6634 			/* signal action needs to be taken */
6635 			if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY ||
6636 			    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
6637 				/* Keep track of warning cnt for CMF_SYNC_WQE */
6638 				atomic_add(cnt, &phba->cgn_sync_warn_cnt);
6639 			}
6640 		}
6641 		break;
6642 	case LPFC_SLI_EVENT_TYPE_RD_SIGNAL:
6643 		/* May be accompanied by a temperature event */
6644 		lpfc_printf_log(phba, KERN_INFO,
6645 				LOG_SLI | LOG_LINK_EVENT | LOG_LDS_EVENT,
6646 				"2902 Remote Degrade Signaling: x%08x x%08x "
6647 				"x%08x\n",
6648 				acqe_sli->event_data1, acqe_sli->event_data2,
6649 				acqe_sli->event_data3);
6650 		break;
6651 	default:
6652 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6653 				"3193 Unrecognized SLI event, type: 0x%x",
6654 				evt_type);
6655 		break;
6656 	}
6657 }
6658 
6659 /**
6660  * lpfc_sli4_perform_vport_cvl - Perform clear virtual link on a vport
6661  * @vport: pointer to vport data structure.
6662  *
6663  * This routine is to perform Clear Virtual Link (CVL) on a vport in
6664  * response to a CVL event.
6665  *
6666  * Return the pointer to the ndlp with the vport if successful, otherwise
6667  * return NULL.
6668  **/
6669 static struct lpfc_nodelist *
6670 lpfc_sli4_perform_vport_cvl(struct lpfc_vport *vport)
6671 {
6672 	struct lpfc_nodelist *ndlp;
6673 	struct Scsi_Host *shost;
6674 	struct lpfc_hba *phba;
6675 
6676 	if (!vport)
6677 		return NULL;
6678 	phba = vport->phba;
6679 	if (!phba)
6680 		return NULL;
6681 	ndlp = lpfc_findnode_did(vport, Fabric_DID);
6682 	if (!ndlp) {
6683 		/* Cannot find existing Fabric ndlp, so allocate a new one */
6684 		ndlp = lpfc_nlp_init(vport, Fabric_DID);
6685 		if (!ndlp)
6686 			return NULL;
6687 		/* Set the node type */
6688 		ndlp->nlp_type |= NLP_FABRIC;
6689 		/* Put ndlp onto node list */
6690 		lpfc_enqueue_node(vport, ndlp);
6691 	}
6692 	if ((phba->pport->port_state < LPFC_FLOGI) &&
6693 		(phba->pport->port_state != LPFC_VPORT_FAILED))
6694 		return NULL;
6695 	/* If virtual link is not yet instantiated ignore CVL */
6696 	if ((vport != phba->pport) && (vport->port_state < LPFC_FDISC)
6697 		&& (vport->port_state != LPFC_VPORT_FAILED))
6698 		return NULL;
6699 	shost = lpfc_shost_from_vport(vport);
6700 	if (!shost)
6701 		return NULL;
6702 	lpfc_linkdown_port(vport);
6703 	lpfc_cleanup_pending_mbox(vport);
6704 	spin_lock_irq(shost->host_lock);
6705 	vport->fc_flag |= FC_VPORT_CVL_RCVD;
6706 	spin_unlock_irq(shost->host_lock);
6707 
6708 	return ndlp;
6709 }
6710 
6711 /**
6712  * lpfc_sli4_perform_all_vport_cvl - Perform clear virtual link on all vports
6713  * @phba: pointer to lpfc hba data structure.
6714  *
6715  * This routine is to perform Clear Virtual Link (CVL) on all vports in
6716  * response to a FCF dead event.
6717  **/
6718 static void
6719 lpfc_sli4_perform_all_vport_cvl(struct lpfc_hba *phba)
6720 {
6721 	struct lpfc_vport **vports;
6722 	int i;
6723 
6724 	vports = lpfc_create_vport_work_array(phba);
6725 	if (vports)
6726 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++)
6727 			lpfc_sli4_perform_vport_cvl(vports[i]);
6728 	lpfc_destroy_vport_work_array(phba, vports);
6729 }
6730 
6731 /**
6732  * lpfc_sli4_async_fip_evt - Process the asynchronous FCoE FIP event
6733  * @phba: pointer to lpfc hba data structure.
6734  * @acqe_fip: pointer to the async fcoe completion queue entry.
6735  *
6736  * This routine is to handle the SLI4 asynchronous fcoe event.
6737  **/
6738 static void
6739 lpfc_sli4_async_fip_evt(struct lpfc_hba *phba,
6740 			struct lpfc_acqe_fip *acqe_fip)
6741 {
6742 	uint8_t event_type = bf_get(lpfc_trailer_type, acqe_fip);
6743 	int rc;
6744 	struct lpfc_vport *vport;
6745 	struct lpfc_nodelist *ndlp;
6746 	int active_vlink_present;
6747 	struct lpfc_vport **vports;
6748 	int i;
6749 
6750 	phba->fc_eventTag = acqe_fip->event_tag;
6751 	phba->fcoe_eventtag = acqe_fip->event_tag;
6752 	switch (event_type) {
6753 	case LPFC_FIP_EVENT_TYPE_NEW_FCF:
6754 	case LPFC_FIP_EVENT_TYPE_FCF_PARAM_MOD:
6755 		if (event_type == LPFC_FIP_EVENT_TYPE_NEW_FCF)
6756 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6757 					"2546 New FCF event, evt_tag:x%x, "
6758 					"index:x%x\n",
6759 					acqe_fip->event_tag,
6760 					acqe_fip->index);
6761 		else
6762 			lpfc_printf_log(phba, KERN_WARNING, LOG_FIP |
6763 					LOG_DISCOVERY,
6764 					"2788 FCF param modified event, "
6765 					"evt_tag:x%x, index:x%x\n",
6766 					acqe_fip->event_tag,
6767 					acqe_fip->index);
6768 		if (phba->fcf.fcf_flag & FCF_DISCOVERY) {
6769 			/*
6770 			 * During period of FCF discovery, read the FCF
6771 			 * table record indexed by the event to update
6772 			 * FCF roundrobin failover eligible FCF bmask.
6773 			 */
6774 			lpfc_printf_log(phba, KERN_INFO, LOG_FIP |
6775 					LOG_DISCOVERY,
6776 					"2779 Read FCF (x%x) for updating "
6777 					"roundrobin FCF failover bmask\n",
6778 					acqe_fip->index);
6779 			rc = lpfc_sli4_read_fcf_rec(phba, acqe_fip->index);
6780 		}
6781 
6782 		/* If the FCF discovery is in progress, do nothing. */
6783 		spin_lock_irq(&phba->hbalock);
6784 		if (phba->hba_flag & FCF_TS_INPROG) {
6785 			spin_unlock_irq(&phba->hbalock);
6786 			break;
6787 		}
6788 		/* If fast FCF failover rescan event is pending, do nothing */
6789 		if (phba->fcf.fcf_flag & (FCF_REDISC_EVT | FCF_REDISC_PEND)) {
6790 			spin_unlock_irq(&phba->hbalock);
6791 			break;
6792 		}
6793 
6794 		/* If the FCF has been in discovered state, do nothing. */
6795 		if (phba->fcf.fcf_flag & FCF_SCAN_DONE) {
6796 			spin_unlock_irq(&phba->hbalock);
6797 			break;
6798 		}
6799 		spin_unlock_irq(&phba->hbalock);
6800 
6801 		/* Otherwise, scan the entire FCF table and re-discover SAN */
6802 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
6803 				"2770 Start FCF table scan per async FCF "
6804 				"event, evt_tag:x%x, index:x%x\n",
6805 				acqe_fip->event_tag, acqe_fip->index);
6806 		rc = lpfc_sli4_fcf_scan_read_fcf_rec(phba,
6807 						     LPFC_FCOE_FCF_GET_FIRST);
6808 		if (rc)
6809 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6810 					"2547 Issue FCF scan read FCF mailbox "
6811 					"command failed (x%x)\n", rc);
6812 		break;
6813 
6814 	case LPFC_FIP_EVENT_TYPE_FCF_TABLE_FULL:
6815 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6816 				"2548 FCF Table full count 0x%x tag 0x%x\n",
6817 				bf_get(lpfc_acqe_fip_fcf_count, acqe_fip),
6818 				acqe_fip->event_tag);
6819 		break;
6820 
6821 	case LPFC_FIP_EVENT_TYPE_FCF_DEAD:
6822 		phba->fcoe_cvl_eventtag = acqe_fip->event_tag;
6823 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6824 				"2549 FCF (x%x) disconnected from network, "
6825 				 "tag:x%x\n", acqe_fip->index,
6826 				 acqe_fip->event_tag);
6827 		/*
6828 		 * If we are in the middle of FCF failover process, clear
6829 		 * the corresponding FCF bit in the roundrobin bitmap.
6830 		 */
6831 		spin_lock_irq(&phba->hbalock);
6832 		if ((phba->fcf.fcf_flag & FCF_DISCOVERY) &&
6833 		    (phba->fcf.current_rec.fcf_indx != acqe_fip->index)) {
6834 			spin_unlock_irq(&phba->hbalock);
6835 			/* Update FLOGI FCF failover eligible FCF bmask */
6836 			lpfc_sli4_fcf_rr_index_clear(phba, acqe_fip->index);
6837 			break;
6838 		}
6839 		spin_unlock_irq(&phba->hbalock);
6840 
6841 		/* If the event is not for currently used fcf do nothing */
6842 		if (phba->fcf.current_rec.fcf_indx != acqe_fip->index)
6843 			break;
6844 
6845 		/*
6846 		 * Otherwise, request the port to rediscover the entire FCF
6847 		 * table for a fast recovery from case that the current FCF
6848 		 * is no longer valid as we are not in the middle of FCF
6849 		 * failover process already.
6850 		 */
6851 		spin_lock_irq(&phba->hbalock);
6852 		/* Mark the fast failover process in progress */
6853 		phba->fcf.fcf_flag |= FCF_DEAD_DISC;
6854 		spin_unlock_irq(&phba->hbalock);
6855 
6856 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
6857 				"2771 Start FCF fast failover process due to "
6858 				"FCF DEAD event: evt_tag:x%x, fcf_index:x%x "
6859 				"\n", acqe_fip->event_tag, acqe_fip->index);
6860 		rc = lpfc_sli4_redisc_fcf_table(phba);
6861 		if (rc) {
6862 			lpfc_printf_log(phba, KERN_ERR, LOG_FIP |
6863 					LOG_TRACE_EVENT,
6864 					"2772 Issue FCF rediscover mailbox "
6865 					"command failed, fail through to FCF "
6866 					"dead event\n");
6867 			spin_lock_irq(&phba->hbalock);
6868 			phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
6869 			spin_unlock_irq(&phba->hbalock);
6870 			/*
6871 			 * Last resort will fail over by treating this
6872 			 * as a link down to FCF registration.
6873 			 */
6874 			lpfc_sli4_fcf_dead_failthrough(phba);
6875 		} else {
6876 			/* Reset FCF roundrobin bmask for new discovery */
6877 			lpfc_sli4_clear_fcf_rr_bmask(phba);
6878 			/*
6879 			 * Handling fast FCF failover to a DEAD FCF event is
6880 			 * considered equalivant to receiving CVL to all vports.
6881 			 */
6882 			lpfc_sli4_perform_all_vport_cvl(phba);
6883 		}
6884 		break;
6885 	case LPFC_FIP_EVENT_TYPE_CVL:
6886 		phba->fcoe_cvl_eventtag = acqe_fip->event_tag;
6887 		lpfc_printf_log(phba, KERN_ERR,
6888 				LOG_TRACE_EVENT,
6889 			"2718 Clear Virtual Link Received for VPI 0x%x"
6890 			" tag 0x%x\n", acqe_fip->index, acqe_fip->event_tag);
6891 
6892 		vport = lpfc_find_vport_by_vpid(phba,
6893 						acqe_fip->index);
6894 		ndlp = lpfc_sli4_perform_vport_cvl(vport);
6895 		if (!ndlp)
6896 			break;
6897 		active_vlink_present = 0;
6898 
6899 		vports = lpfc_create_vport_work_array(phba);
6900 		if (vports) {
6901 			for (i = 0; i <= phba->max_vports && vports[i] != NULL;
6902 					i++) {
6903 				if ((!(vports[i]->fc_flag &
6904 					FC_VPORT_CVL_RCVD)) &&
6905 					(vports[i]->port_state > LPFC_FDISC)) {
6906 					active_vlink_present = 1;
6907 					break;
6908 				}
6909 			}
6910 			lpfc_destroy_vport_work_array(phba, vports);
6911 		}
6912 
6913 		/*
6914 		 * Don't re-instantiate if vport is marked for deletion.
6915 		 * If we are here first then vport_delete is going to wait
6916 		 * for discovery to complete.
6917 		 */
6918 		if (!(vport->load_flag & FC_UNLOADING) &&
6919 					active_vlink_present) {
6920 			/*
6921 			 * If there are other active VLinks present,
6922 			 * re-instantiate the Vlink using FDISC.
6923 			 */
6924 			mod_timer(&ndlp->nlp_delayfunc,
6925 				  jiffies + msecs_to_jiffies(1000));
6926 			spin_lock_irq(&ndlp->lock);
6927 			ndlp->nlp_flag |= NLP_DELAY_TMO;
6928 			spin_unlock_irq(&ndlp->lock);
6929 			ndlp->nlp_last_elscmd = ELS_CMD_FDISC;
6930 			vport->port_state = LPFC_FDISC;
6931 		} else {
6932 			/*
6933 			 * Otherwise, we request port to rediscover
6934 			 * the entire FCF table for a fast recovery
6935 			 * from possible case that the current FCF
6936 			 * is no longer valid if we are not already
6937 			 * in the FCF failover process.
6938 			 */
6939 			spin_lock_irq(&phba->hbalock);
6940 			if (phba->fcf.fcf_flag & FCF_DISCOVERY) {
6941 				spin_unlock_irq(&phba->hbalock);
6942 				break;
6943 			}
6944 			/* Mark the fast failover process in progress */
6945 			phba->fcf.fcf_flag |= FCF_ACVL_DISC;
6946 			spin_unlock_irq(&phba->hbalock);
6947 			lpfc_printf_log(phba, KERN_INFO, LOG_FIP |
6948 					LOG_DISCOVERY,
6949 					"2773 Start FCF failover per CVL, "
6950 					"evt_tag:x%x\n", acqe_fip->event_tag);
6951 			rc = lpfc_sli4_redisc_fcf_table(phba);
6952 			if (rc) {
6953 				lpfc_printf_log(phba, KERN_ERR, LOG_FIP |
6954 						LOG_TRACE_EVENT,
6955 						"2774 Issue FCF rediscover "
6956 						"mailbox command failed, "
6957 						"through to CVL event\n");
6958 				spin_lock_irq(&phba->hbalock);
6959 				phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
6960 				spin_unlock_irq(&phba->hbalock);
6961 				/*
6962 				 * Last resort will be re-try on the
6963 				 * the current registered FCF entry.
6964 				 */
6965 				lpfc_retry_pport_discovery(phba);
6966 			} else
6967 				/*
6968 				 * Reset FCF roundrobin bmask for new
6969 				 * discovery.
6970 				 */
6971 				lpfc_sli4_clear_fcf_rr_bmask(phba);
6972 		}
6973 		break;
6974 	default:
6975 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6976 				"0288 Unknown FCoE event type 0x%x event tag "
6977 				"0x%x\n", event_type, acqe_fip->event_tag);
6978 		break;
6979 	}
6980 }
6981 
6982 /**
6983  * lpfc_sli4_async_dcbx_evt - Process the asynchronous dcbx event
6984  * @phba: pointer to lpfc hba data structure.
6985  * @acqe_dcbx: pointer to the async dcbx completion queue entry.
6986  *
6987  * This routine is to handle the SLI4 asynchronous dcbx event.
6988  **/
6989 static void
6990 lpfc_sli4_async_dcbx_evt(struct lpfc_hba *phba,
6991 			 struct lpfc_acqe_dcbx *acqe_dcbx)
6992 {
6993 	phba->fc_eventTag = acqe_dcbx->event_tag;
6994 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6995 			"0290 The SLI4 DCBX asynchronous event is not "
6996 			"handled yet\n");
6997 }
6998 
6999 /**
7000  * lpfc_sli4_async_grp5_evt - Process the asynchronous group5 event
7001  * @phba: pointer to lpfc hba data structure.
7002  * @acqe_grp5: pointer to the async grp5 completion queue entry.
7003  *
7004  * This routine is to handle the SLI4 asynchronous grp5 event. A grp5 event
7005  * is an asynchronous notified of a logical link speed change.  The Port
7006  * reports the logical link speed in units of 10Mbps.
7007  **/
7008 static void
7009 lpfc_sli4_async_grp5_evt(struct lpfc_hba *phba,
7010 			 struct lpfc_acqe_grp5 *acqe_grp5)
7011 {
7012 	uint16_t prev_ll_spd;
7013 
7014 	phba->fc_eventTag = acqe_grp5->event_tag;
7015 	phba->fcoe_eventtag = acqe_grp5->event_tag;
7016 	prev_ll_spd = phba->sli4_hba.link_state.logical_speed;
7017 	phba->sli4_hba.link_state.logical_speed =
7018 		(bf_get(lpfc_acqe_grp5_llink_spd, acqe_grp5)) * 10;
7019 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
7020 			"2789 GRP5 Async Event: Updating logical link speed "
7021 			"from %dMbps to %dMbps\n", prev_ll_spd,
7022 			phba->sli4_hba.link_state.logical_speed);
7023 }
7024 
7025 /**
7026  * lpfc_sli4_async_cmstat_evt - Process the asynchronous cmstat event
7027  * @phba: pointer to lpfc hba data structure.
7028  *
7029  * This routine is to handle the SLI4 asynchronous cmstat event. A cmstat event
7030  * is an asynchronous notification of a request to reset CM stats.
7031  **/
7032 static void
7033 lpfc_sli4_async_cmstat_evt(struct lpfc_hba *phba)
7034 {
7035 	if (!phba->cgn_i)
7036 		return;
7037 	lpfc_init_congestion_stat(phba);
7038 }
7039 
7040 /**
7041  * lpfc_cgn_params_val - Validate FW congestion parameters.
7042  * @phba: pointer to lpfc hba data structure.
7043  * @p_cfg_param: pointer to FW provided congestion parameters.
7044  *
7045  * This routine validates the congestion parameters passed
7046  * by the FW to the driver via an ACQE event.
7047  **/
7048 static void
7049 lpfc_cgn_params_val(struct lpfc_hba *phba, struct lpfc_cgn_param *p_cfg_param)
7050 {
7051 	spin_lock_irq(&phba->hbalock);
7052 
7053 	if (!lpfc_rangecheck(p_cfg_param->cgn_param_mode, LPFC_CFG_OFF,
7054 			     LPFC_CFG_MONITOR)) {
7055 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT,
7056 				"6225 CMF mode param out of range: %d\n",
7057 				 p_cfg_param->cgn_param_mode);
7058 		p_cfg_param->cgn_param_mode = LPFC_CFG_OFF;
7059 	}
7060 
7061 	spin_unlock_irq(&phba->hbalock);
7062 }
7063 
7064 static const char * const lpfc_cmf_mode_to_str[] = {
7065 	"OFF",
7066 	"MANAGED",
7067 	"MONITOR",
7068 };
7069 
7070 /**
7071  * lpfc_cgn_params_parse - Process a FW cong parm change event
7072  * @phba: pointer to lpfc hba data structure.
7073  * @p_cgn_param: pointer to a data buffer with the FW cong params.
7074  * @len: the size of pdata in bytes.
7075  *
7076  * This routine validates the congestion management buffer signature
7077  * from the FW, validates the contents and makes corrections for
7078  * valid, in-range values.  If the signature magic is correct and
7079  * after parameter validation, the contents are copied to the driver's
7080  * @phba structure. If the magic is incorrect, an error message is
7081  * logged.
7082  **/
7083 static void
7084 lpfc_cgn_params_parse(struct lpfc_hba *phba,
7085 		      struct lpfc_cgn_param *p_cgn_param, uint32_t len)
7086 {
7087 	struct lpfc_cgn_info *cp;
7088 	uint32_t crc, oldmode;
7089 	char acr_string[4] = {0};
7090 
7091 	/* Make sure the FW has encoded the correct magic number to
7092 	 * validate the congestion parameter in FW memory.
7093 	 */
7094 	if (p_cgn_param->cgn_param_magic == LPFC_CFG_PARAM_MAGIC_NUM) {
7095 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT | LOG_INIT,
7096 				"4668 FW cgn parm buffer data: "
7097 				"magic 0x%x version %d mode %d "
7098 				"level0 %d level1 %d "
7099 				"level2 %d byte13 %d "
7100 				"byte14 %d byte15 %d "
7101 				"byte11 %d byte12 %d activeMode %d\n",
7102 				p_cgn_param->cgn_param_magic,
7103 				p_cgn_param->cgn_param_version,
7104 				p_cgn_param->cgn_param_mode,
7105 				p_cgn_param->cgn_param_level0,
7106 				p_cgn_param->cgn_param_level1,
7107 				p_cgn_param->cgn_param_level2,
7108 				p_cgn_param->byte13,
7109 				p_cgn_param->byte14,
7110 				p_cgn_param->byte15,
7111 				p_cgn_param->byte11,
7112 				p_cgn_param->byte12,
7113 				phba->cmf_active_mode);
7114 
7115 		oldmode = phba->cmf_active_mode;
7116 
7117 		/* Any parameters out of range are corrected to defaults
7118 		 * by this routine.  No need to fail.
7119 		 */
7120 		lpfc_cgn_params_val(phba, p_cgn_param);
7121 
7122 		/* Parameters are verified, move them into driver storage */
7123 		spin_lock_irq(&phba->hbalock);
7124 		memcpy(&phba->cgn_p, p_cgn_param,
7125 		       sizeof(struct lpfc_cgn_param));
7126 
7127 		/* Update parameters in congestion info buffer now */
7128 		if (phba->cgn_i) {
7129 			cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
7130 			cp->cgn_info_mode = phba->cgn_p.cgn_param_mode;
7131 			cp->cgn_info_level0 = phba->cgn_p.cgn_param_level0;
7132 			cp->cgn_info_level1 = phba->cgn_p.cgn_param_level1;
7133 			cp->cgn_info_level2 = phba->cgn_p.cgn_param_level2;
7134 			crc = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ,
7135 						  LPFC_CGN_CRC32_SEED);
7136 			cp->cgn_info_crc = cpu_to_le32(crc);
7137 		}
7138 		spin_unlock_irq(&phba->hbalock);
7139 
7140 		phba->cmf_active_mode = phba->cgn_p.cgn_param_mode;
7141 
7142 		switch (oldmode) {
7143 		case LPFC_CFG_OFF:
7144 			if (phba->cgn_p.cgn_param_mode != LPFC_CFG_OFF) {
7145 				/* Turning CMF on */
7146 				lpfc_cmf_start(phba);
7147 
7148 				if (phba->link_state >= LPFC_LINK_UP) {
7149 					phba->cgn_reg_fpin =
7150 						phba->cgn_init_reg_fpin;
7151 					phba->cgn_reg_signal =
7152 						phba->cgn_init_reg_signal;
7153 					lpfc_issue_els_edc(phba->pport, 0);
7154 				}
7155 			}
7156 			break;
7157 		case LPFC_CFG_MANAGED:
7158 			switch (phba->cgn_p.cgn_param_mode) {
7159 			case LPFC_CFG_OFF:
7160 				/* Turning CMF off */
7161 				lpfc_cmf_stop(phba);
7162 				if (phba->link_state >= LPFC_LINK_UP)
7163 					lpfc_issue_els_edc(phba->pport, 0);
7164 				break;
7165 			case LPFC_CFG_MONITOR:
7166 				phba->cmf_max_bytes_per_interval =
7167 					phba->cmf_link_byte_count;
7168 
7169 				/* Resume blocked IO - unblock on workqueue */
7170 				queue_work(phba->wq,
7171 					   &phba->unblock_request_work);
7172 				break;
7173 			}
7174 			break;
7175 		case LPFC_CFG_MONITOR:
7176 			switch (phba->cgn_p.cgn_param_mode) {
7177 			case LPFC_CFG_OFF:
7178 				/* Turning CMF off */
7179 				lpfc_cmf_stop(phba);
7180 				if (phba->link_state >= LPFC_LINK_UP)
7181 					lpfc_issue_els_edc(phba->pport, 0);
7182 				break;
7183 			case LPFC_CFG_MANAGED:
7184 				lpfc_cmf_signal_init(phba);
7185 				break;
7186 			}
7187 			break;
7188 		}
7189 		if (oldmode != LPFC_CFG_OFF ||
7190 		    oldmode != phba->cgn_p.cgn_param_mode) {
7191 			if (phba->cgn_p.cgn_param_mode == LPFC_CFG_MANAGED)
7192 				scnprintf(acr_string, sizeof(acr_string), "%u",
7193 					  phba->cgn_p.cgn_param_level0);
7194 			else
7195 				scnprintf(acr_string, sizeof(acr_string), "NA");
7196 
7197 			dev_info(&phba->pcidev->dev, "%d: "
7198 				 "4663 CMF: Mode %s acr %s\n",
7199 				 phba->brd_no,
7200 				 lpfc_cmf_mode_to_str
7201 				 [phba->cgn_p.cgn_param_mode],
7202 				 acr_string);
7203 		}
7204 	} else {
7205 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7206 				"4669 FW cgn parm buf wrong magic 0x%x "
7207 				"version %d\n", p_cgn_param->cgn_param_magic,
7208 				p_cgn_param->cgn_param_version);
7209 	}
7210 }
7211 
7212 /**
7213  * lpfc_sli4_cgn_params_read - Read and Validate FW congestion parameters.
7214  * @phba: pointer to lpfc hba data structure.
7215  *
7216  * This routine issues a read_object mailbox command to
7217  * get the congestion management parameters from the FW
7218  * parses it and updates the driver maintained values.
7219  *
7220  * Returns
7221  *  0     if the object was empty
7222  *  -Eval if an error was encountered
7223  *  Count if bytes were read from object
7224  **/
7225 int
7226 lpfc_sli4_cgn_params_read(struct lpfc_hba *phba)
7227 {
7228 	int ret = 0;
7229 	struct lpfc_cgn_param *p_cgn_param = NULL;
7230 	u32 *pdata = NULL;
7231 	u32 len = 0;
7232 
7233 	/* Find out if the FW has a new set of congestion parameters. */
7234 	len = sizeof(struct lpfc_cgn_param);
7235 	pdata = kzalloc(len, GFP_KERNEL);
7236 	ret = lpfc_read_object(phba, (char *)LPFC_PORT_CFG_NAME,
7237 			       pdata, len);
7238 
7239 	/* 0 means no data.  A negative means error.  A positive means
7240 	 * bytes were copied.
7241 	 */
7242 	if (!ret) {
7243 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7244 				"4670 CGN RD OBJ returns no data\n");
7245 		goto rd_obj_err;
7246 	} else if (ret < 0) {
7247 		/* Some error.  Just exit and return it to the caller.*/
7248 		goto rd_obj_err;
7249 	}
7250 
7251 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT | LOG_INIT,
7252 			"6234 READ CGN PARAMS Successful %d\n", len);
7253 
7254 	/* Parse data pointer over len and update the phba congestion
7255 	 * parameters with values passed back.  The receive rate values
7256 	 * may have been altered in FW, but take no action here.
7257 	 */
7258 	p_cgn_param = (struct lpfc_cgn_param *)pdata;
7259 	lpfc_cgn_params_parse(phba, p_cgn_param, len);
7260 
7261  rd_obj_err:
7262 	kfree(pdata);
7263 	return ret;
7264 }
7265 
7266 /**
7267  * lpfc_sli4_cgn_parm_chg_evt - Process a FW congestion param change event
7268  * @phba: pointer to lpfc hba data structure.
7269  *
7270  * The FW generated Async ACQE SLI event calls this routine when
7271  * the event type is an SLI Internal Port Event and the Event Code
7272  * indicates a change to the FW maintained congestion parameters.
7273  *
7274  * This routine executes a Read_Object mailbox call to obtain the
7275  * current congestion parameters maintained in FW and corrects
7276  * the driver's active congestion parameters.
7277  *
7278  * The acqe event is not passed because there is no further data
7279  * required.
7280  *
7281  * Returns nonzero error if event processing encountered an error.
7282  * Zero otherwise for success.
7283  **/
7284 static int
7285 lpfc_sli4_cgn_parm_chg_evt(struct lpfc_hba *phba)
7286 {
7287 	int ret = 0;
7288 
7289 	if (!phba->sli4_hba.pc_sli4_params.cmf) {
7290 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7291 				"4664 Cgn Evt when E2E off. Drop event\n");
7292 		return -EACCES;
7293 	}
7294 
7295 	/* If the event is claiming an empty object, it's ok.  A write
7296 	 * could have cleared it.  Only error is a negative return
7297 	 * status.
7298 	 */
7299 	ret = lpfc_sli4_cgn_params_read(phba);
7300 	if (ret < 0) {
7301 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7302 				"4667 Error reading Cgn Params (%d)\n",
7303 				ret);
7304 	} else if (!ret) {
7305 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7306 				"4673 CGN Event empty object.\n");
7307 	}
7308 	return ret;
7309 }
7310 
7311 /**
7312  * lpfc_sli4_async_event_proc - Process all the pending asynchronous event
7313  * @phba: pointer to lpfc hba data structure.
7314  *
7315  * This routine is invoked by the worker thread to process all the pending
7316  * SLI4 asynchronous events.
7317  **/
7318 void lpfc_sli4_async_event_proc(struct lpfc_hba *phba)
7319 {
7320 	struct lpfc_cq_event *cq_event;
7321 	unsigned long iflags;
7322 
7323 	/* First, declare the async event has been handled */
7324 	spin_lock_irqsave(&phba->hbalock, iflags);
7325 	phba->hba_flag &= ~ASYNC_EVENT;
7326 	spin_unlock_irqrestore(&phba->hbalock, iflags);
7327 
7328 	/* Now, handle all the async events */
7329 	spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
7330 	while (!list_empty(&phba->sli4_hba.sp_asynce_work_queue)) {
7331 		list_remove_head(&phba->sli4_hba.sp_asynce_work_queue,
7332 				 cq_event, struct lpfc_cq_event, list);
7333 		spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock,
7334 				       iflags);
7335 
7336 		/* Process the asynchronous event */
7337 		switch (bf_get(lpfc_trailer_code, &cq_event->cqe.mcqe_cmpl)) {
7338 		case LPFC_TRAILER_CODE_LINK:
7339 			lpfc_sli4_async_link_evt(phba,
7340 						 &cq_event->cqe.acqe_link);
7341 			break;
7342 		case LPFC_TRAILER_CODE_FCOE:
7343 			lpfc_sli4_async_fip_evt(phba, &cq_event->cqe.acqe_fip);
7344 			break;
7345 		case LPFC_TRAILER_CODE_DCBX:
7346 			lpfc_sli4_async_dcbx_evt(phba,
7347 						 &cq_event->cqe.acqe_dcbx);
7348 			break;
7349 		case LPFC_TRAILER_CODE_GRP5:
7350 			lpfc_sli4_async_grp5_evt(phba,
7351 						 &cq_event->cqe.acqe_grp5);
7352 			break;
7353 		case LPFC_TRAILER_CODE_FC:
7354 			lpfc_sli4_async_fc_evt(phba, &cq_event->cqe.acqe_fc);
7355 			break;
7356 		case LPFC_TRAILER_CODE_SLI:
7357 			lpfc_sli4_async_sli_evt(phba, &cq_event->cqe.acqe_sli);
7358 			break;
7359 		case LPFC_TRAILER_CODE_CMSTAT:
7360 			lpfc_sli4_async_cmstat_evt(phba);
7361 			break;
7362 		default:
7363 			lpfc_printf_log(phba, KERN_ERR,
7364 					LOG_TRACE_EVENT,
7365 					"1804 Invalid asynchronous event code: "
7366 					"x%x\n", bf_get(lpfc_trailer_code,
7367 					&cq_event->cqe.mcqe_cmpl));
7368 			break;
7369 		}
7370 
7371 		/* Free the completion event processed to the free pool */
7372 		lpfc_sli4_cq_event_release(phba, cq_event);
7373 		spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
7374 	}
7375 	spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock, iflags);
7376 }
7377 
7378 /**
7379  * lpfc_sli4_fcf_redisc_event_proc - Process fcf table rediscovery event
7380  * @phba: pointer to lpfc hba data structure.
7381  *
7382  * This routine is invoked by the worker thread to process FCF table
7383  * rediscovery pending completion event.
7384  **/
7385 void lpfc_sli4_fcf_redisc_event_proc(struct lpfc_hba *phba)
7386 {
7387 	int rc;
7388 
7389 	spin_lock_irq(&phba->hbalock);
7390 	/* Clear FCF rediscovery timeout event */
7391 	phba->fcf.fcf_flag &= ~FCF_REDISC_EVT;
7392 	/* Clear driver fast failover FCF record flag */
7393 	phba->fcf.failover_rec.flag = 0;
7394 	/* Set state for FCF fast failover */
7395 	phba->fcf.fcf_flag |= FCF_REDISC_FOV;
7396 	spin_unlock_irq(&phba->hbalock);
7397 
7398 	/* Scan FCF table from the first entry to re-discover SAN */
7399 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
7400 			"2777 Start post-quiescent FCF table scan\n");
7401 	rc = lpfc_sli4_fcf_scan_read_fcf_rec(phba, LPFC_FCOE_FCF_GET_FIRST);
7402 	if (rc)
7403 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7404 				"2747 Issue FCF scan read FCF mailbox "
7405 				"command failed 0x%x\n", rc);
7406 }
7407 
7408 /**
7409  * lpfc_api_table_setup - Set up per hba pci-device group func api jump table
7410  * @phba: pointer to lpfc hba data structure.
7411  * @dev_grp: The HBA PCI-Device group number.
7412  *
7413  * This routine is invoked to set up the per HBA PCI-Device group function
7414  * API jump table entries.
7415  *
7416  * Return: 0 if success, otherwise -ENODEV
7417  **/
7418 int
7419 lpfc_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
7420 {
7421 	int rc;
7422 
7423 	/* Set up lpfc PCI-device group */
7424 	phba->pci_dev_grp = dev_grp;
7425 
7426 	/* The LPFC_PCI_DEV_OC uses SLI4 */
7427 	if (dev_grp == LPFC_PCI_DEV_OC)
7428 		phba->sli_rev = LPFC_SLI_REV4;
7429 
7430 	/* Set up device INIT API function jump table */
7431 	rc = lpfc_init_api_table_setup(phba, dev_grp);
7432 	if (rc)
7433 		return -ENODEV;
7434 	/* Set up SCSI API function jump table */
7435 	rc = lpfc_scsi_api_table_setup(phba, dev_grp);
7436 	if (rc)
7437 		return -ENODEV;
7438 	/* Set up SLI API function jump table */
7439 	rc = lpfc_sli_api_table_setup(phba, dev_grp);
7440 	if (rc)
7441 		return -ENODEV;
7442 	/* Set up MBOX API function jump table */
7443 	rc = lpfc_mbox_api_table_setup(phba, dev_grp);
7444 	if (rc)
7445 		return -ENODEV;
7446 
7447 	return 0;
7448 }
7449 
7450 /**
7451  * lpfc_log_intr_mode - Log the active interrupt mode
7452  * @phba: pointer to lpfc hba data structure.
7453  * @intr_mode: active interrupt mode adopted.
7454  *
7455  * This routine it invoked to log the currently used active interrupt mode
7456  * to the device.
7457  **/
7458 static void lpfc_log_intr_mode(struct lpfc_hba *phba, uint32_t intr_mode)
7459 {
7460 	switch (intr_mode) {
7461 	case 0:
7462 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7463 				"0470 Enable INTx interrupt mode.\n");
7464 		break;
7465 	case 1:
7466 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7467 				"0481 Enabled MSI interrupt mode.\n");
7468 		break;
7469 	case 2:
7470 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7471 				"0480 Enabled MSI-X interrupt mode.\n");
7472 		break;
7473 	default:
7474 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7475 				"0482 Illegal interrupt mode.\n");
7476 		break;
7477 	}
7478 	return;
7479 }
7480 
7481 /**
7482  * lpfc_enable_pci_dev - Enable a generic PCI device.
7483  * @phba: pointer to lpfc hba data structure.
7484  *
7485  * This routine is invoked to enable the PCI device that is common to all
7486  * PCI devices.
7487  *
7488  * Return codes
7489  * 	0 - successful
7490  * 	other values - error
7491  **/
7492 static int
7493 lpfc_enable_pci_dev(struct lpfc_hba *phba)
7494 {
7495 	struct pci_dev *pdev;
7496 
7497 	/* Obtain PCI device reference */
7498 	if (!phba->pcidev)
7499 		goto out_error;
7500 	else
7501 		pdev = phba->pcidev;
7502 	/* Enable PCI device */
7503 	if (pci_enable_device_mem(pdev))
7504 		goto out_error;
7505 	/* Request PCI resource for the device */
7506 	if (pci_request_mem_regions(pdev, LPFC_DRIVER_NAME))
7507 		goto out_disable_device;
7508 	/* Set up device as PCI master and save state for EEH */
7509 	pci_set_master(pdev);
7510 	pci_try_set_mwi(pdev);
7511 	pci_save_state(pdev);
7512 
7513 	/* PCIe EEH recovery on powerpc platforms needs fundamental reset */
7514 	if (pci_is_pcie(pdev))
7515 		pdev->needs_freset = 1;
7516 
7517 	return 0;
7518 
7519 out_disable_device:
7520 	pci_disable_device(pdev);
7521 out_error:
7522 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7523 			"1401 Failed to enable pci device\n");
7524 	return -ENODEV;
7525 }
7526 
7527 /**
7528  * lpfc_disable_pci_dev - Disable a generic PCI device.
7529  * @phba: pointer to lpfc hba data structure.
7530  *
7531  * This routine is invoked to disable the PCI device that is common to all
7532  * PCI devices.
7533  **/
7534 static void
7535 lpfc_disable_pci_dev(struct lpfc_hba *phba)
7536 {
7537 	struct pci_dev *pdev;
7538 
7539 	/* Obtain PCI device reference */
7540 	if (!phba->pcidev)
7541 		return;
7542 	else
7543 		pdev = phba->pcidev;
7544 	/* Release PCI resource and disable PCI device */
7545 	pci_release_mem_regions(pdev);
7546 	pci_disable_device(pdev);
7547 
7548 	return;
7549 }
7550 
7551 /**
7552  * lpfc_reset_hba - Reset a hba
7553  * @phba: pointer to lpfc hba data structure.
7554  *
7555  * This routine is invoked to reset a hba device. It brings the HBA
7556  * offline, performs a board restart, and then brings the board back
7557  * online. The lpfc_offline calls lpfc_sli_hba_down which will clean up
7558  * on outstanding mailbox commands.
7559  **/
7560 void
7561 lpfc_reset_hba(struct lpfc_hba *phba)
7562 {
7563 	/* If resets are disabled then set error state and return. */
7564 	if (!phba->cfg_enable_hba_reset) {
7565 		phba->link_state = LPFC_HBA_ERROR;
7566 		return;
7567 	}
7568 
7569 	/* If not LPFC_SLI_ACTIVE, force all IO to be flushed */
7570 	if (phba->sli.sli_flag & LPFC_SLI_ACTIVE) {
7571 		lpfc_offline_prep(phba, LPFC_MBX_WAIT);
7572 	} else {
7573 		lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
7574 		lpfc_sli_flush_io_rings(phba);
7575 	}
7576 	lpfc_offline(phba);
7577 	lpfc_sli_brdrestart(phba);
7578 	lpfc_online(phba);
7579 	lpfc_unblock_mgmt_io(phba);
7580 }
7581 
7582 /**
7583  * lpfc_sli_sriov_nr_virtfn_get - Get the number of sr-iov virtual functions
7584  * @phba: pointer to lpfc hba data structure.
7585  *
7586  * This function enables the PCI SR-IOV virtual functions to a physical
7587  * function. It invokes the PCI SR-IOV api with the @nr_vfn provided to
7588  * enable the number of virtual functions to the physical function. As
7589  * not all devices support SR-IOV, the return code from the pci_enable_sriov()
7590  * API call does not considered as an error condition for most of the device.
7591  **/
7592 uint16_t
7593 lpfc_sli_sriov_nr_virtfn_get(struct lpfc_hba *phba)
7594 {
7595 	struct pci_dev *pdev = phba->pcidev;
7596 	uint16_t nr_virtfn;
7597 	int pos;
7598 
7599 	pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_SRIOV);
7600 	if (pos == 0)
7601 		return 0;
7602 
7603 	pci_read_config_word(pdev, pos + PCI_SRIOV_TOTAL_VF, &nr_virtfn);
7604 	return nr_virtfn;
7605 }
7606 
7607 /**
7608  * lpfc_sli_probe_sriov_nr_virtfn - Enable a number of sr-iov virtual functions
7609  * @phba: pointer to lpfc hba data structure.
7610  * @nr_vfn: number of virtual functions to be enabled.
7611  *
7612  * This function enables the PCI SR-IOV virtual functions to a physical
7613  * function. It invokes the PCI SR-IOV api with the @nr_vfn provided to
7614  * enable the number of virtual functions to the physical function. As
7615  * not all devices support SR-IOV, the return code from the pci_enable_sriov()
7616  * API call does not considered as an error condition for most of the device.
7617  **/
7618 int
7619 lpfc_sli_probe_sriov_nr_virtfn(struct lpfc_hba *phba, int nr_vfn)
7620 {
7621 	struct pci_dev *pdev = phba->pcidev;
7622 	uint16_t max_nr_vfn;
7623 	int rc;
7624 
7625 	max_nr_vfn = lpfc_sli_sriov_nr_virtfn_get(phba);
7626 	if (nr_vfn > max_nr_vfn) {
7627 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7628 				"3057 Requested vfs (%d) greater than "
7629 				"supported vfs (%d)", nr_vfn, max_nr_vfn);
7630 		return -EINVAL;
7631 	}
7632 
7633 	rc = pci_enable_sriov(pdev, nr_vfn);
7634 	if (rc) {
7635 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7636 				"2806 Failed to enable sriov on this device "
7637 				"with vfn number nr_vf:%d, rc:%d\n",
7638 				nr_vfn, rc);
7639 	} else
7640 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7641 				"2807 Successful enable sriov on this device "
7642 				"with vfn number nr_vf:%d\n", nr_vfn);
7643 	return rc;
7644 }
7645 
7646 static void
7647 lpfc_unblock_requests_work(struct work_struct *work)
7648 {
7649 	struct lpfc_hba *phba = container_of(work, struct lpfc_hba,
7650 					     unblock_request_work);
7651 
7652 	lpfc_unblock_requests(phba);
7653 }
7654 
7655 /**
7656  * lpfc_setup_driver_resource_phase1 - Phase1 etup driver internal resources.
7657  * @phba: pointer to lpfc hba data structure.
7658  *
7659  * This routine is invoked to set up the driver internal resources before the
7660  * device specific resource setup to support the HBA device it attached to.
7661  *
7662  * Return codes
7663  *	0 - successful
7664  *	other values - error
7665  **/
7666 static int
7667 lpfc_setup_driver_resource_phase1(struct lpfc_hba *phba)
7668 {
7669 	struct lpfc_sli *psli = &phba->sli;
7670 
7671 	/*
7672 	 * Driver resources common to all SLI revisions
7673 	 */
7674 	atomic_set(&phba->fast_event_count, 0);
7675 	atomic_set(&phba->dbg_log_idx, 0);
7676 	atomic_set(&phba->dbg_log_cnt, 0);
7677 	atomic_set(&phba->dbg_log_dmping, 0);
7678 	spin_lock_init(&phba->hbalock);
7679 
7680 	/* Initialize port_list spinlock */
7681 	spin_lock_init(&phba->port_list_lock);
7682 	INIT_LIST_HEAD(&phba->port_list);
7683 
7684 	INIT_LIST_HEAD(&phba->work_list);
7685 
7686 	/* Initialize the wait queue head for the kernel thread */
7687 	init_waitqueue_head(&phba->work_waitq);
7688 
7689 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7690 			"1403 Protocols supported %s %s %s\n",
7691 			((phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP) ?
7692 				"SCSI" : " "),
7693 			((phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) ?
7694 				"NVME" : " "),
7695 			(phba->nvmet_support ? "NVMET" : " "));
7696 
7697 	/* Initialize the IO buffer list used by driver for SLI3 SCSI */
7698 	spin_lock_init(&phba->scsi_buf_list_get_lock);
7699 	INIT_LIST_HEAD(&phba->lpfc_scsi_buf_list_get);
7700 	spin_lock_init(&phba->scsi_buf_list_put_lock);
7701 	INIT_LIST_HEAD(&phba->lpfc_scsi_buf_list_put);
7702 
7703 	/* Initialize the fabric iocb list */
7704 	INIT_LIST_HEAD(&phba->fabric_iocb_list);
7705 
7706 	/* Initialize list to save ELS buffers */
7707 	INIT_LIST_HEAD(&phba->elsbuf);
7708 
7709 	/* Initialize FCF connection rec list */
7710 	INIT_LIST_HEAD(&phba->fcf_conn_rec_list);
7711 
7712 	/* Initialize OAS configuration list */
7713 	spin_lock_init(&phba->devicelock);
7714 	INIT_LIST_HEAD(&phba->luns);
7715 
7716 	/* MBOX heartbeat timer */
7717 	timer_setup(&psli->mbox_tmo, lpfc_mbox_timeout, 0);
7718 	/* Fabric block timer */
7719 	timer_setup(&phba->fabric_block_timer, lpfc_fabric_block_timeout, 0);
7720 	/* EA polling mode timer */
7721 	timer_setup(&phba->eratt_poll, lpfc_poll_eratt, 0);
7722 	/* Heartbeat timer */
7723 	timer_setup(&phba->hb_tmofunc, lpfc_hb_timeout, 0);
7724 
7725 	INIT_DELAYED_WORK(&phba->eq_delay_work, lpfc_hb_eq_delay_work);
7726 
7727 	INIT_DELAYED_WORK(&phba->idle_stat_delay_work,
7728 			  lpfc_idle_stat_delay_work);
7729 	INIT_WORK(&phba->unblock_request_work, lpfc_unblock_requests_work);
7730 	return 0;
7731 }
7732 
7733 /**
7734  * lpfc_sli_driver_resource_setup - Setup driver internal resources for SLI3 dev
7735  * @phba: pointer to lpfc hba data structure.
7736  *
7737  * This routine is invoked to set up the driver internal resources specific to
7738  * support the SLI-3 HBA device it attached to.
7739  *
7740  * Return codes
7741  * 0 - successful
7742  * other values - error
7743  **/
7744 static int
7745 lpfc_sli_driver_resource_setup(struct lpfc_hba *phba)
7746 {
7747 	int rc, entry_sz;
7748 
7749 	/*
7750 	 * Initialize timers used by driver
7751 	 */
7752 
7753 	/* FCP polling mode timer */
7754 	timer_setup(&phba->fcp_poll_timer, lpfc_poll_timeout, 0);
7755 
7756 	/* Host attention work mask setup */
7757 	phba->work_ha_mask = (HA_ERATT | HA_MBATT | HA_LATT);
7758 	phba->work_ha_mask |= (HA_RXMASK << (LPFC_ELS_RING * 4));
7759 
7760 	/* Get all the module params for configuring this host */
7761 	lpfc_get_cfgparam(phba);
7762 	/* Set up phase-1 common device driver resources */
7763 
7764 	rc = lpfc_setup_driver_resource_phase1(phba);
7765 	if (rc)
7766 		return -ENODEV;
7767 
7768 	if (!phba->sli.sli3_ring)
7769 		phba->sli.sli3_ring = kcalloc(LPFC_SLI3_MAX_RING,
7770 					      sizeof(struct lpfc_sli_ring),
7771 					      GFP_KERNEL);
7772 	if (!phba->sli.sli3_ring)
7773 		return -ENOMEM;
7774 
7775 	/*
7776 	 * Since lpfc_sg_seg_cnt is module parameter, the sg_dma_buf_size
7777 	 * used to create the sg_dma_buf_pool must be dynamically calculated.
7778 	 */
7779 
7780 	if (phba->sli_rev == LPFC_SLI_REV4)
7781 		entry_sz = sizeof(struct sli4_sge);
7782 	else
7783 		entry_sz = sizeof(struct ulp_bde64);
7784 
7785 	/* There are going to be 2 reserved BDEs: 1 FCP cmnd + 1 FCP rsp */
7786 	if (phba->cfg_enable_bg) {
7787 		/*
7788 		 * The scsi_buf for a T10-DIF I/O will hold the FCP cmnd,
7789 		 * the FCP rsp, and a BDE for each. Sice we have no control
7790 		 * over how many protection data segments the SCSI Layer
7791 		 * will hand us (ie: there could be one for every block
7792 		 * in the IO), we just allocate enough BDEs to accomidate
7793 		 * our max amount and we need to limit lpfc_sg_seg_cnt to
7794 		 * minimize the risk of running out.
7795 		 */
7796 		phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd) +
7797 			sizeof(struct fcp_rsp) +
7798 			(LPFC_MAX_SG_SEG_CNT * entry_sz);
7799 
7800 		if (phba->cfg_sg_seg_cnt > LPFC_MAX_SG_SEG_CNT_DIF)
7801 			phba->cfg_sg_seg_cnt = LPFC_MAX_SG_SEG_CNT_DIF;
7802 
7803 		/* Total BDEs in BPL for scsi_sg_list and scsi_sg_prot_list */
7804 		phba->cfg_total_seg_cnt = LPFC_MAX_SG_SEG_CNT;
7805 	} else {
7806 		/*
7807 		 * The scsi_buf for a regular I/O will hold the FCP cmnd,
7808 		 * the FCP rsp, a BDE for each, and a BDE for up to
7809 		 * cfg_sg_seg_cnt data segments.
7810 		 */
7811 		phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd) +
7812 			sizeof(struct fcp_rsp) +
7813 			((phba->cfg_sg_seg_cnt + 2) * entry_sz);
7814 
7815 		/* Total BDEs in BPL for scsi_sg_list */
7816 		phba->cfg_total_seg_cnt = phba->cfg_sg_seg_cnt + 2;
7817 	}
7818 
7819 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP,
7820 			"9088 INIT sg_tablesize:%d dmabuf_size:%d total_bde:%d\n",
7821 			phba->cfg_sg_seg_cnt, phba->cfg_sg_dma_buf_size,
7822 			phba->cfg_total_seg_cnt);
7823 
7824 	phba->max_vpi = LPFC_MAX_VPI;
7825 	/* This will be set to correct value after config_port mbox */
7826 	phba->max_vports = 0;
7827 
7828 	/*
7829 	 * Initialize the SLI Layer to run with lpfc HBAs.
7830 	 */
7831 	lpfc_sli_setup(phba);
7832 	lpfc_sli_queue_init(phba);
7833 
7834 	/* Allocate device driver memory */
7835 	if (lpfc_mem_alloc(phba, BPL_ALIGN_SZ))
7836 		return -ENOMEM;
7837 
7838 	phba->lpfc_sg_dma_buf_pool =
7839 		dma_pool_create("lpfc_sg_dma_buf_pool",
7840 				&phba->pcidev->dev, phba->cfg_sg_dma_buf_size,
7841 				BPL_ALIGN_SZ, 0);
7842 
7843 	if (!phba->lpfc_sg_dma_buf_pool)
7844 		goto fail_free_mem;
7845 
7846 	phba->lpfc_cmd_rsp_buf_pool =
7847 			dma_pool_create("lpfc_cmd_rsp_buf_pool",
7848 					&phba->pcidev->dev,
7849 					sizeof(struct fcp_cmnd) +
7850 					sizeof(struct fcp_rsp),
7851 					BPL_ALIGN_SZ, 0);
7852 
7853 	if (!phba->lpfc_cmd_rsp_buf_pool)
7854 		goto fail_free_dma_buf_pool;
7855 
7856 	/*
7857 	 * Enable sr-iov virtual functions if supported and configured
7858 	 * through the module parameter.
7859 	 */
7860 	if (phba->cfg_sriov_nr_virtfn > 0) {
7861 		rc = lpfc_sli_probe_sriov_nr_virtfn(phba,
7862 						 phba->cfg_sriov_nr_virtfn);
7863 		if (rc) {
7864 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7865 					"2808 Requested number of SR-IOV "
7866 					"virtual functions (%d) is not "
7867 					"supported\n",
7868 					phba->cfg_sriov_nr_virtfn);
7869 			phba->cfg_sriov_nr_virtfn = 0;
7870 		}
7871 	}
7872 
7873 	return 0;
7874 
7875 fail_free_dma_buf_pool:
7876 	dma_pool_destroy(phba->lpfc_sg_dma_buf_pool);
7877 	phba->lpfc_sg_dma_buf_pool = NULL;
7878 fail_free_mem:
7879 	lpfc_mem_free(phba);
7880 	return -ENOMEM;
7881 }
7882 
7883 /**
7884  * lpfc_sli_driver_resource_unset - Unset drvr internal resources for SLI3 dev
7885  * @phba: pointer to lpfc hba data structure.
7886  *
7887  * This routine is invoked to unset the driver internal resources set up
7888  * specific for supporting the SLI-3 HBA device it attached to.
7889  **/
7890 static void
7891 lpfc_sli_driver_resource_unset(struct lpfc_hba *phba)
7892 {
7893 	/* Free device driver memory allocated */
7894 	lpfc_mem_free_all(phba);
7895 
7896 	return;
7897 }
7898 
7899 /**
7900  * lpfc_sli4_driver_resource_setup - Setup drvr internal resources for SLI4 dev
7901  * @phba: pointer to lpfc hba data structure.
7902  *
7903  * This routine is invoked to set up the driver internal resources specific to
7904  * support the SLI-4 HBA device it attached to.
7905  *
7906  * Return codes
7907  * 	0 - successful
7908  * 	other values - error
7909  **/
7910 static int
7911 lpfc_sli4_driver_resource_setup(struct lpfc_hba *phba)
7912 {
7913 	LPFC_MBOXQ_t *mboxq;
7914 	MAILBOX_t *mb;
7915 	int rc, i, max_buf_size;
7916 	int longs;
7917 	int extra;
7918 	uint64_t wwn;
7919 	u32 if_type;
7920 	u32 if_fam;
7921 
7922 	phba->sli4_hba.num_present_cpu = lpfc_present_cpu;
7923 	phba->sli4_hba.num_possible_cpu = cpumask_last(cpu_possible_mask) + 1;
7924 	phba->sli4_hba.curr_disp_cpu = 0;
7925 
7926 	/* Get all the module params for configuring this host */
7927 	lpfc_get_cfgparam(phba);
7928 
7929 	/* Set up phase-1 common device driver resources */
7930 	rc = lpfc_setup_driver_resource_phase1(phba);
7931 	if (rc)
7932 		return -ENODEV;
7933 
7934 	/* Before proceed, wait for POST done and device ready */
7935 	rc = lpfc_sli4_post_status_check(phba);
7936 	if (rc)
7937 		return -ENODEV;
7938 
7939 	/* Allocate all driver workqueues here */
7940 
7941 	/* The lpfc_wq workqueue for deferred irq use */
7942 	phba->wq = alloc_workqueue("lpfc_wq", WQ_MEM_RECLAIM, 0);
7943 	if (!phba->wq)
7944 		return -ENOMEM;
7945 
7946 	/*
7947 	 * Initialize timers used by driver
7948 	 */
7949 
7950 	timer_setup(&phba->rrq_tmr, lpfc_rrq_timeout, 0);
7951 
7952 	/* FCF rediscover timer */
7953 	timer_setup(&phba->fcf.redisc_wait, lpfc_sli4_fcf_redisc_wait_tmo, 0);
7954 
7955 	/* CMF congestion timer */
7956 	hrtimer_init(&phba->cmf_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
7957 	phba->cmf_timer.function = lpfc_cmf_timer;
7958 
7959 	/*
7960 	 * Control structure for handling external multi-buffer mailbox
7961 	 * command pass-through.
7962 	 */
7963 	memset((uint8_t *)&phba->mbox_ext_buf_ctx, 0,
7964 		sizeof(struct lpfc_mbox_ext_buf_ctx));
7965 	INIT_LIST_HEAD(&phba->mbox_ext_buf_ctx.ext_dmabuf_list);
7966 
7967 	phba->max_vpi = LPFC_MAX_VPI;
7968 
7969 	/* This will be set to correct value after the read_config mbox */
7970 	phba->max_vports = 0;
7971 
7972 	/* Program the default value of vlan_id and fc_map */
7973 	phba->valid_vlan = 0;
7974 	phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
7975 	phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
7976 	phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
7977 
7978 	/*
7979 	 * For SLI4, instead of using ring 0 (LPFC_FCP_RING) for FCP commands
7980 	 * we will associate a new ring, for each EQ/CQ/WQ tuple.
7981 	 * The WQ create will allocate the ring.
7982 	 */
7983 
7984 	/* Initialize buffer queue management fields */
7985 	INIT_LIST_HEAD(&phba->hbqs[LPFC_ELS_HBQ].hbq_buffer_list);
7986 	phba->hbqs[LPFC_ELS_HBQ].hbq_alloc_buffer = lpfc_sli4_rb_alloc;
7987 	phba->hbqs[LPFC_ELS_HBQ].hbq_free_buffer = lpfc_sli4_rb_free;
7988 
7989 	/* for VMID idle timeout if VMID is enabled */
7990 	if (lpfc_is_vmid_enabled(phba))
7991 		timer_setup(&phba->inactive_vmid_poll, lpfc_vmid_poll, 0);
7992 
7993 	/*
7994 	 * Initialize the SLI Layer to run with lpfc SLI4 HBAs.
7995 	 */
7996 	/* Initialize the Abort buffer list used by driver */
7997 	spin_lock_init(&phba->sli4_hba.abts_io_buf_list_lock);
7998 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_io_buf_list);
7999 
8000 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
8001 		/* Initialize the Abort nvme buffer list used by driver */
8002 		spin_lock_init(&phba->sli4_hba.abts_nvmet_buf_list_lock);
8003 		INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
8004 		INIT_LIST_HEAD(&phba->sli4_hba.lpfc_nvmet_io_wait_list);
8005 		spin_lock_init(&phba->sli4_hba.t_active_list_lock);
8006 		INIT_LIST_HEAD(&phba->sli4_hba.t_active_ctx_list);
8007 	}
8008 
8009 	/* This abort list used by worker thread */
8010 	spin_lock_init(&phba->sli4_hba.sgl_list_lock);
8011 	spin_lock_init(&phba->sli4_hba.nvmet_io_wait_lock);
8012 	spin_lock_init(&phba->sli4_hba.asynce_list_lock);
8013 	spin_lock_init(&phba->sli4_hba.els_xri_abrt_list_lock);
8014 
8015 	/*
8016 	 * Initialize driver internal slow-path work queues
8017 	 */
8018 
8019 	/* Driver internel slow-path CQ Event pool */
8020 	INIT_LIST_HEAD(&phba->sli4_hba.sp_cqe_event_pool);
8021 	/* Response IOCB work queue list */
8022 	INIT_LIST_HEAD(&phba->sli4_hba.sp_queue_event);
8023 	/* Asynchronous event CQ Event work queue list */
8024 	INIT_LIST_HEAD(&phba->sli4_hba.sp_asynce_work_queue);
8025 	/* Slow-path XRI aborted CQ Event work queue list */
8026 	INIT_LIST_HEAD(&phba->sli4_hba.sp_els_xri_aborted_work_queue);
8027 	/* Receive queue CQ Event work queue list */
8028 	INIT_LIST_HEAD(&phba->sli4_hba.sp_unsol_work_queue);
8029 
8030 	/* Initialize extent block lists. */
8031 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_rpi_blk_list);
8032 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_xri_blk_list);
8033 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_vfi_blk_list);
8034 	INIT_LIST_HEAD(&phba->lpfc_vpi_blk_list);
8035 
8036 	/* Initialize mboxq lists. If the early init routines fail
8037 	 * these lists need to be correctly initialized.
8038 	 */
8039 	INIT_LIST_HEAD(&phba->sli.mboxq);
8040 	INIT_LIST_HEAD(&phba->sli.mboxq_cmpl);
8041 
8042 	/* initialize optic_state to 0xFF */
8043 	phba->sli4_hba.lnk_info.optic_state = 0xff;
8044 
8045 	/* Allocate device driver memory */
8046 	rc = lpfc_mem_alloc(phba, SGL_ALIGN_SZ);
8047 	if (rc)
8048 		goto out_destroy_workqueue;
8049 
8050 	/* IF Type 2 ports get initialized now. */
8051 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) >=
8052 	    LPFC_SLI_INTF_IF_TYPE_2) {
8053 		rc = lpfc_pci_function_reset(phba);
8054 		if (unlikely(rc)) {
8055 			rc = -ENODEV;
8056 			goto out_free_mem;
8057 		}
8058 		phba->temp_sensor_support = 1;
8059 	}
8060 
8061 	/* Create the bootstrap mailbox command */
8062 	rc = lpfc_create_bootstrap_mbox(phba);
8063 	if (unlikely(rc))
8064 		goto out_free_mem;
8065 
8066 	/* Set up the host's endian order with the device. */
8067 	rc = lpfc_setup_endian_order(phba);
8068 	if (unlikely(rc))
8069 		goto out_free_bsmbx;
8070 
8071 	/* Set up the hba's configuration parameters. */
8072 	rc = lpfc_sli4_read_config(phba);
8073 	if (unlikely(rc))
8074 		goto out_free_bsmbx;
8075 
8076 	if (phba->sli4_hba.fawwpn_flag & LPFC_FAWWPN_CONFIG) {
8077 		/* Right now the link is down, if FA-PWWN is configured the
8078 		 * firmware will try FLOGI before the driver gets a link up.
8079 		 * If it fails, the driver should get a MISCONFIGURED async
8080 		 * event which will clear this flag. The only notification
8081 		 * the driver gets is if it fails, if it succeeds there is no
8082 		 * notification given. Assume success.
8083 		 */
8084 		phba->sli4_hba.fawwpn_flag |= LPFC_FAWWPN_FABRIC;
8085 	}
8086 
8087 	rc = lpfc_mem_alloc_active_rrq_pool_s4(phba);
8088 	if (unlikely(rc))
8089 		goto out_free_bsmbx;
8090 
8091 	/* IF Type 0 ports get initialized now. */
8092 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
8093 	    LPFC_SLI_INTF_IF_TYPE_0) {
8094 		rc = lpfc_pci_function_reset(phba);
8095 		if (unlikely(rc))
8096 			goto out_free_bsmbx;
8097 	}
8098 
8099 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
8100 						       GFP_KERNEL);
8101 	if (!mboxq) {
8102 		rc = -ENOMEM;
8103 		goto out_free_bsmbx;
8104 	}
8105 
8106 	/* Check for NVMET being configured */
8107 	phba->nvmet_support = 0;
8108 	if (lpfc_enable_nvmet_cnt) {
8109 
8110 		/* First get WWN of HBA instance */
8111 		lpfc_read_nv(phba, mboxq);
8112 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8113 		if (rc != MBX_SUCCESS) {
8114 			lpfc_printf_log(phba, KERN_ERR,
8115 					LOG_TRACE_EVENT,
8116 					"6016 Mailbox failed , mbxCmd x%x "
8117 					"READ_NV, mbxStatus x%x\n",
8118 					bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8119 					bf_get(lpfc_mqe_status, &mboxq->u.mqe));
8120 			mempool_free(mboxq, phba->mbox_mem_pool);
8121 			rc = -EIO;
8122 			goto out_free_bsmbx;
8123 		}
8124 		mb = &mboxq->u.mb;
8125 		memcpy(&wwn, (char *)mb->un.varRDnvp.nodename,
8126 		       sizeof(uint64_t));
8127 		wwn = cpu_to_be64(wwn);
8128 		phba->sli4_hba.wwnn.u.name = wwn;
8129 		memcpy(&wwn, (char *)mb->un.varRDnvp.portname,
8130 		       sizeof(uint64_t));
8131 		/* wwn is WWPN of HBA instance */
8132 		wwn = cpu_to_be64(wwn);
8133 		phba->sli4_hba.wwpn.u.name = wwn;
8134 
8135 		/* Check to see if it matches any module parameter */
8136 		for (i = 0; i < lpfc_enable_nvmet_cnt; i++) {
8137 			if (wwn == lpfc_enable_nvmet[i]) {
8138 #if (IS_ENABLED(CONFIG_NVME_TARGET_FC))
8139 				if (lpfc_nvmet_mem_alloc(phba))
8140 					break;
8141 
8142 				phba->nvmet_support = 1; /* a match */
8143 
8144 				lpfc_printf_log(phba, KERN_ERR,
8145 						LOG_TRACE_EVENT,
8146 						"6017 NVME Target %016llx\n",
8147 						wwn);
8148 #else
8149 				lpfc_printf_log(phba, KERN_ERR,
8150 						LOG_TRACE_EVENT,
8151 						"6021 Can't enable NVME Target."
8152 						" NVME_TARGET_FC infrastructure"
8153 						" is not in kernel\n");
8154 #endif
8155 				/* Not supported for NVMET */
8156 				phba->cfg_xri_rebalancing = 0;
8157 				if (phba->irq_chann_mode == NHT_MODE) {
8158 					phba->cfg_irq_chann =
8159 						phba->sli4_hba.num_present_cpu;
8160 					phba->cfg_hdw_queue =
8161 						phba->sli4_hba.num_present_cpu;
8162 					phba->irq_chann_mode = NORMAL_MODE;
8163 				}
8164 				break;
8165 			}
8166 		}
8167 	}
8168 
8169 	lpfc_nvme_mod_param_dep(phba);
8170 
8171 	/*
8172 	 * Get sli4 parameters that override parameters from Port capabilities.
8173 	 * If this call fails, it isn't critical unless the SLI4 parameters come
8174 	 * back in conflict.
8175 	 */
8176 	rc = lpfc_get_sli4_parameters(phba, mboxq);
8177 	if (rc) {
8178 		if_type = bf_get(lpfc_sli_intf_if_type,
8179 				 &phba->sli4_hba.sli_intf);
8180 		if_fam = bf_get(lpfc_sli_intf_sli_family,
8181 				&phba->sli4_hba.sli_intf);
8182 		if (phba->sli4_hba.extents_in_use &&
8183 		    phba->sli4_hba.rpi_hdrs_in_use) {
8184 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8185 					"2999 Unsupported SLI4 Parameters "
8186 					"Extents and RPI headers enabled.\n");
8187 			if (if_type == LPFC_SLI_INTF_IF_TYPE_0 &&
8188 			    if_fam ==  LPFC_SLI_INTF_FAMILY_BE2) {
8189 				mempool_free(mboxq, phba->mbox_mem_pool);
8190 				rc = -EIO;
8191 				goto out_free_bsmbx;
8192 			}
8193 		}
8194 		if (!(if_type == LPFC_SLI_INTF_IF_TYPE_0 &&
8195 		      if_fam == LPFC_SLI_INTF_FAMILY_BE2)) {
8196 			mempool_free(mboxq, phba->mbox_mem_pool);
8197 			rc = -EIO;
8198 			goto out_free_bsmbx;
8199 		}
8200 	}
8201 
8202 	/*
8203 	 * 1 for cmd, 1 for rsp, NVME adds an extra one
8204 	 * for boundary conditions in its max_sgl_segment template.
8205 	 */
8206 	extra = 2;
8207 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
8208 		extra++;
8209 
8210 	/*
8211 	 * It doesn't matter what family our adapter is in, we are
8212 	 * limited to 2 Pages, 512 SGEs, for our SGL.
8213 	 * There are going to be 2 reserved SGEs: 1 FCP cmnd + 1 FCP rsp
8214 	 */
8215 	max_buf_size = (2 * SLI4_PAGE_SIZE);
8216 
8217 	/*
8218 	 * Since lpfc_sg_seg_cnt is module param, the sg_dma_buf_size
8219 	 * used to create the sg_dma_buf_pool must be calculated.
8220 	 */
8221 	if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
8222 		/* Both cfg_enable_bg and cfg_external_dif code paths */
8223 
8224 		/*
8225 		 * The scsi_buf for a T10-DIF I/O holds the FCP cmnd,
8226 		 * the FCP rsp, and a SGE. Sice we have no control
8227 		 * over how many protection segments the SCSI Layer
8228 		 * will hand us (ie: there could be one for every block
8229 		 * in the IO), just allocate enough SGEs to accomidate
8230 		 * our max amount and we need to limit lpfc_sg_seg_cnt
8231 		 * to minimize the risk of running out.
8232 		 */
8233 		phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd) +
8234 				sizeof(struct fcp_rsp) + max_buf_size;
8235 
8236 		/* Total SGEs for scsi_sg_list and scsi_sg_prot_list */
8237 		phba->cfg_total_seg_cnt = LPFC_MAX_SGL_SEG_CNT;
8238 
8239 		/*
8240 		 * If supporting DIF, reduce the seg count for scsi to
8241 		 * allow room for the DIF sges.
8242 		 */
8243 		if (phba->cfg_enable_bg &&
8244 		    phba->cfg_sg_seg_cnt > LPFC_MAX_BG_SLI4_SEG_CNT_DIF)
8245 			phba->cfg_scsi_seg_cnt = LPFC_MAX_BG_SLI4_SEG_CNT_DIF;
8246 		else
8247 			phba->cfg_scsi_seg_cnt = phba->cfg_sg_seg_cnt;
8248 
8249 	} else {
8250 		/*
8251 		 * The scsi_buf for a regular I/O holds the FCP cmnd,
8252 		 * the FCP rsp, a SGE for each, and a SGE for up to
8253 		 * cfg_sg_seg_cnt data segments.
8254 		 */
8255 		phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd) +
8256 				sizeof(struct fcp_rsp) +
8257 				((phba->cfg_sg_seg_cnt + extra) *
8258 				sizeof(struct sli4_sge));
8259 
8260 		/* Total SGEs for scsi_sg_list */
8261 		phba->cfg_total_seg_cnt = phba->cfg_sg_seg_cnt + extra;
8262 		phba->cfg_scsi_seg_cnt = phba->cfg_sg_seg_cnt;
8263 
8264 		/*
8265 		 * NOTE: if (phba->cfg_sg_seg_cnt + extra) <= 256 we only
8266 		 * need to post 1 page for the SGL.
8267 		 */
8268 	}
8269 
8270 	if (phba->cfg_xpsgl && !phba->nvmet_support)
8271 		phba->cfg_sg_dma_buf_size = LPFC_DEFAULT_XPSGL_SIZE;
8272 	else if (phba->cfg_sg_dma_buf_size  <= LPFC_MIN_SG_SLI4_BUF_SZ)
8273 		phba->cfg_sg_dma_buf_size = LPFC_MIN_SG_SLI4_BUF_SZ;
8274 	else
8275 		phba->cfg_sg_dma_buf_size =
8276 				SLI4_PAGE_ALIGN(phba->cfg_sg_dma_buf_size);
8277 
8278 	phba->border_sge_num = phba->cfg_sg_dma_buf_size /
8279 			       sizeof(struct sli4_sge);
8280 
8281 	/* Limit to LPFC_MAX_NVME_SEG_CNT for NVME. */
8282 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
8283 		if (phba->cfg_sg_seg_cnt > LPFC_MAX_NVME_SEG_CNT) {
8284 			lpfc_printf_log(phba, KERN_INFO, LOG_NVME | LOG_INIT,
8285 					"6300 Reducing NVME sg segment "
8286 					"cnt to %d\n",
8287 					LPFC_MAX_NVME_SEG_CNT);
8288 			phba->cfg_nvme_seg_cnt = LPFC_MAX_NVME_SEG_CNT;
8289 		} else
8290 			phba->cfg_nvme_seg_cnt = phba->cfg_sg_seg_cnt;
8291 	}
8292 
8293 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP,
8294 			"9087 sg_seg_cnt:%d dmabuf_size:%d "
8295 			"total:%d scsi:%d nvme:%d\n",
8296 			phba->cfg_sg_seg_cnt, phba->cfg_sg_dma_buf_size,
8297 			phba->cfg_total_seg_cnt,  phba->cfg_scsi_seg_cnt,
8298 			phba->cfg_nvme_seg_cnt);
8299 
8300 	if (phba->cfg_sg_dma_buf_size < SLI4_PAGE_SIZE)
8301 		i = phba->cfg_sg_dma_buf_size;
8302 	else
8303 		i = SLI4_PAGE_SIZE;
8304 
8305 	phba->lpfc_sg_dma_buf_pool =
8306 			dma_pool_create("lpfc_sg_dma_buf_pool",
8307 					&phba->pcidev->dev,
8308 					phba->cfg_sg_dma_buf_size,
8309 					i, 0);
8310 	if (!phba->lpfc_sg_dma_buf_pool) {
8311 		rc = -ENOMEM;
8312 		goto out_free_bsmbx;
8313 	}
8314 
8315 	phba->lpfc_cmd_rsp_buf_pool =
8316 			dma_pool_create("lpfc_cmd_rsp_buf_pool",
8317 					&phba->pcidev->dev,
8318 					sizeof(struct fcp_cmnd) +
8319 					sizeof(struct fcp_rsp),
8320 					i, 0);
8321 	if (!phba->lpfc_cmd_rsp_buf_pool) {
8322 		rc = -ENOMEM;
8323 		goto out_free_sg_dma_buf;
8324 	}
8325 
8326 	mempool_free(mboxq, phba->mbox_mem_pool);
8327 
8328 	/* Verify OAS is supported */
8329 	lpfc_sli4_oas_verify(phba);
8330 
8331 	/* Verify RAS support on adapter */
8332 	lpfc_sli4_ras_init(phba);
8333 
8334 	/* Verify all the SLI4 queues */
8335 	rc = lpfc_sli4_queue_verify(phba);
8336 	if (rc)
8337 		goto out_free_cmd_rsp_buf;
8338 
8339 	/* Create driver internal CQE event pool */
8340 	rc = lpfc_sli4_cq_event_pool_create(phba);
8341 	if (rc)
8342 		goto out_free_cmd_rsp_buf;
8343 
8344 	/* Initialize sgl lists per host */
8345 	lpfc_init_sgl_list(phba);
8346 
8347 	/* Allocate and initialize active sgl array */
8348 	rc = lpfc_init_active_sgl_array(phba);
8349 	if (rc) {
8350 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8351 				"1430 Failed to initialize sgl list.\n");
8352 		goto out_destroy_cq_event_pool;
8353 	}
8354 	rc = lpfc_sli4_init_rpi_hdrs(phba);
8355 	if (rc) {
8356 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8357 				"1432 Failed to initialize rpi headers.\n");
8358 		goto out_free_active_sgl;
8359 	}
8360 
8361 	/* Allocate eligible FCF bmask memory for FCF roundrobin failover */
8362 	longs = (LPFC_SLI4_FCF_TBL_INDX_MAX + BITS_PER_LONG - 1)/BITS_PER_LONG;
8363 	phba->fcf.fcf_rr_bmask = kcalloc(longs, sizeof(unsigned long),
8364 					 GFP_KERNEL);
8365 	if (!phba->fcf.fcf_rr_bmask) {
8366 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8367 				"2759 Failed allocate memory for FCF round "
8368 				"robin failover bmask\n");
8369 		rc = -ENOMEM;
8370 		goto out_remove_rpi_hdrs;
8371 	}
8372 
8373 	phba->sli4_hba.hba_eq_hdl = kcalloc(phba->cfg_irq_chann,
8374 					    sizeof(struct lpfc_hba_eq_hdl),
8375 					    GFP_KERNEL);
8376 	if (!phba->sli4_hba.hba_eq_hdl) {
8377 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8378 				"2572 Failed allocate memory for "
8379 				"fast-path per-EQ handle array\n");
8380 		rc = -ENOMEM;
8381 		goto out_free_fcf_rr_bmask;
8382 	}
8383 
8384 	phba->sli4_hba.cpu_map = kcalloc(phba->sli4_hba.num_possible_cpu,
8385 					sizeof(struct lpfc_vector_map_info),
8386 					GFP_KERNEL);
8387 	if (!phba->sli4_hba.cpu_map) {
8388 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8389 				"3327 Failed allocate memory for msi-x "
8390 				"interrupt vector mapping\n");
8391 		rc = -ENOMEM;
8392 		goto out_free_hba_eq_hdl;
8393 	}
8394 
8395 	phba->sli4_hba.eq_info = alloc_percpu(struct lpfc_eq_intr_info);
8396 	if (!phba->sli4_hba.eq_info) {
8397 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8398 				"3321 Failed allocation for per_cpu stats\n");
8399 		rc = -ENOMEM;
8400 		goto out_free_hba_cpu_map;
8401 	}
8402 
8403 	phba->sli4_hba.idle_stat = kcalloc(phba->sli4_hba.num_possible_cpu,
8404 					   sizeof(*phba->sli4_hba.idle_stat),
8405 					   GFP_KERNEL);
8406 	if (!phba->sli4_hba.idle_stat) {
8407 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8408 				"3390 Failed allocation for idle_stat\n");
8409 		rc = -ENOMEM;
8410 		goto out_free_hba_eq_info;
8411 	}
8412 
8413 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
8414 	phba->sli4_hba.c_stat = alloc_percpu(struct lpfc_hdwq_stat);
8415 	if (!phba->sli4_hba.c_stat) {
8416 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8417 				"3332 Failed allocating per cpu hdwq stats\n");
8418 		rc = -ENOMEM;
8419 		goto out_free_hba_idle_stat;
8420 	}
8421 #endif
8422 
8423 	phba->cmf_stat = alloc_percpu(struct lpfc_cgn_stat);
8424 	if (!phba->cmf_stat) {
8425 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8426 				"3331 Failed allocating per cpu cgn stats\n");
8427 		rc = -ENOMEM;
8428 		goto out_free_hba_hdwq_info;
8429 	}
8430 
8431 	/*
8432 	 * Enable sr-iov virtual functions if supported and configured
8433 	 * through the module parameter.
8434 	 */
8435 	if (phba->cfg_sriov_nr_virtfn > 0) {
8436 		rc = lpfc_sli_probe_sriov_nr_virtfn(phba,
8437 						 phba->cfg_sriov_nr_virtfn);
8438 		if (rc) {
8439 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
8440 					"3020 Requested number of SR-IOV "
8441 					"virtual functions (%d) is not "
8442 					"supported\n",
8443 					phba->cfg_sriov_nr_virtfn);
8444 			phba->cfg_sriov_nr_virtfn = 0;
8445 		}
8446 	}
8447 
8448 	return 0;
8449 
8450 out_free_hba_hdwq_info:
8451 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
8452 	free_percpu(phba->sli4_hba.c_stat);
8453 out_free_hba_idle_stat:
8454 #endif
8455 	kfree(phba->sli4_hba.idle_stat);
8456 out_free_hba_eq_info:
8457 	free_percpu(phba->sli4_hba.eq_info);
8458 out_free_hba_cpu_map:
8459 	kfree(phba->sli4_hba.cpu_map);
8460 out_free_hba_eq_hdl:
8461 	kfree(phba->sli4_hba.hba_eq_hdl);
8462 out_free_fcf_rr_bmask:
8463 	kfree(phba->fcf.fcf_rr_bmask);
8464 out_remove_rpi_hdrs:
8465 	lpfc_sli4_remove_rpi_hdrs(phba);
8466 out_free_active_sgl:
8467 	lpfc_free_active_sgl(phba);
8468 out_destroy_cq_event_pool:
8469 	lpfc_sli4_cq_event_pool_destroy(phba);
8470 out_free_cmd_rsp_buf:
8471 	dma_pool_destroy(phba->lpfc_cmd_rsp_buf_pool);
8472 	phba->lpfc_cmd_rsp_buf_pool = NULL;
8473 out_free_sg_dma_buf:
8474 	dma_pool_destroy(phba->lpfc_sg_dma_buf_pool);
8475 	phba->lpfc_sg_dma_buf_pool = NULL;
8476 out_free_bsmbx:
8477 	lpfc_destroy_bootstrap_mbox(phba);
8478 out_free_mem:
8479 	lpfc_mem_free(phba);
8480 out_destroy_workqueue:
8481 	destroy_workqueue(phba->wq);
8482 	phba->wq = NULL;
8483 	return rc;
8484 }
8485 
8486 /**
8487  * lpfc_sli4_driver_resource_unset - Unset drvr internal resources for SLI4 dev
8488  * @phba: pointer to lpfc hba data structure.
8489  *
8490  * This routine is invoked to unset the driver internal resources set up
8491  * specific for supporting the SLI-4 HBA device it attached to.
8492  **/
8493 static void
8494 lpfc_sli4_driver_resource_unset(struct lpfc_hba *phba)
8495 {
8496 	struct lpfc_fcf_conn_entry *conn_entry, *next_conn_entry;
8497 
8498 	free_percpu(phba->sli4_hba.eq_info);
8499 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
8500 	free_percpu(phba->sli4_hba.c_stat);
8501 #endif
8502 	free_percpu(phba->cmf_stat);
8503 	kfree(phba->sli4_hba.idle_stat);
8504 
8505 	/* Free memory allocated for msi-x interrupt vector to CPU mapping */
8506 	kfree(phba->sli4_hba.cpu_map);
8507 	phba->sli4_hba.num_possible_cpu = 0;
8508 	phba->sli4_hba.num_present_cpu = 0;
8509 	phba->sli4_hba.curr_disp_cpu = 0;
8510 	cpumask_clear(&phba->sli4_hba.irq_aff_mask);
8511 
8512 	/* Free memory allocated for fast-path work queue handles */
8513 	kfree(phba->sli4_hba.hba_eq_hdl);
8514 
8515 	/* Free the allocated rpi headers. */
8516 	lpfc_sli4_remove_rpi_hdrs(phba);
8517 	lpfc_sli4_remove_rpis(phba);
8518 
8519 	/* Free eligible FCF index bmask */
8520 	kfree(phba->fcf.fcf_rr_bmask);
8521 
8522 	/* Free the ELS sgl list */
8523 	lpfc_free_active_sgl(phba);
8524 	lpfc_free_els_sgl_list(phba);
8525 	lpfc_free_nvmet_sgl_list(phba);
8526 
8527 	/* Free the completion queue EQ event pool */
8528 	lpfc_sli4_cq_event_release_all(phba);
8529 	lpfc_sli4_cq_event_pool_destroy(phba);
8530 
8531 	/* Release resource identifiers. */
8532 	lpfc_sli4_dealloc_resource_identifiers(phba);
8533 
8534 	/* Free the bsmbx region. */
8535 	lpfc_destroy_bootstrap_mbox(phba);
8536 
8537 	/* Free the SLI Layer memory with SLI4 HBAs */
8538 	lpfc_mem_free_all(phba);
8539 
8540 	/* Free the current connect table */
8541 	list_for_each_entry_safe(conn_entry, next_conn_entry,
8542 		&phba->fcf_conn_rec_list, list) {
8543 		list_del_init(&conn_entry->list);
8544 		kfree(conn_entry);
8545 	}
8546 
8547 	return;
8548 }
8549 
8550 /**
8551  * lpfc_init_api_table_setup - Set up init api function jump table
8552  * @phba: The hba struct for which this call is being executed.
8553  * @dev_grp: The HBA PCI-Device group number.
8554  *
8555  * This routine sets up the device INIT interface API function jump table
8556  * in @phba struct.
8557  *
8558  * Returns: 0 - success, -ENODEV - failure.
8559  **/
8560 int
8561 lpfc_init_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
8562 {
8563 	phba->lpfc_hba_init_link = lpfc_hba_init_link;
8564 	phba->lpfc_hba_down_link = lpfc_hba_down_link;
8565 	phba->lpfc_selective_reset = lpfc_selective_reset;
8566 	switch (dev_grp) {
8567 	case LPFC_PCI_DEV_LP:
8568 		phba->lpfc_hba_down_post = lpfc_hba_down_post_s3;
8569 		phba->lpfc_handle_eratt = lpfc_handle_eratt_s3;
8570 		phba->lpfc_stop_port = lpfc_stop_port_s3;
8571 		break;
8572 	case LPFC_PCI_DEV_OC:
8573 		phba->lpfc_hba_down_post = lpfc_hba_down_post_s4;
8574 		phba->lpfc_handle_eratt = lpfc_handle_eratt_s4;
8575 		phba->lpfc_stop_port = lpfc_stop_port_s4;
8576 		break;
8577 	default:
8578 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8579 				"1431 Invalid HBA PCI-device group: 0x%x\n",
8580 				dev_grp);
8581 		return -ENODEV;
8582 	}
8583 	return 0;
8584 }
8585 
8586 /**
8587  * lpfc_setup_driver_resource_phase2 - Phase2 setup driver internal resources.
8588  * @phba: pointer to lpfc hba data structure.
8589  *
8590  * This routine is invoked to set up the driver internal resources after the
8591  * device specific resource setup to support the HBA device it attached to.
8592  *
8593  * Return codes
8594  * 	0 - successful
8595  * 	other values - error
8596  **/
8597 static int
8598 lpfc_setup_driver_resource_phase2(struct lpfc_hba *phba)
8599 {
8600 	int error;
8601 
8602 	/* Startup the kernel thread for this host adapter. */
8603 	phba->worker_thread = kthread_run(lpfc_do_work, phba,
8604 					  "lpfc_worker_%d", phba->brd_no);
8605 	if (IS_ERR(phba->worker_thread)) {
8606 		error = PTR_ERR(phba->worker_thread);
8607 		return error;
8608 	}
8609 
8610 	return 0;
8611 }
8612 
8613 /**
8614  * lpfc_unset_driver_resource_phase2 - Phase2 unset driver internal resources.
8615  * @phba: pointer to lpfc hba data structure.
8616  *
8617  * This routine is invoked to unset the driver internal resources set up after
8618  * the device specific resource setup for supporting the HBA device it
8619  * attached to.
8620  **/
8621 static void
8622 lpfc_unset_driver_resource_phase2(struct lpfc_hba *phba)
8623 {
8624 	if (phba->wq) {
8625 		destroy_workqueue(phba->wq);
8626 		phba->wq = NULL;
8627 	}
8628 
8629 	/* Stop kernel worker thread */
8630 	if (phba->worker_thread)
8631 		kthread_stop(phba->worker_thread);
8632 }
8633 
8634 /**
8635  * lpfc_free_iocb_list - Free iocb list.
8636  * @phba: pointer to lpfc hba data structure.
8637  *
8638  * This routine is invoked to free the driver's IOCB list and memory.
8639  **/
8640 void
8641 lpfc_free_iocb_list(struct lpfc_hba *phba)
8642 {
8643 	struct lpfc_iocbq *iocbq_entry = NULL, *iocbq_next = NULL;
8644 
8645 	spin_lock_irq(&phba->hbalock);
8646 	list_for_each_entry_safe(iocbq_entry, iocbq_next,
8647 				 &phba->lpfc_iocb_list, list) {
8648 		list_del(&iocbq_entry->list);
8649 		kfree(iocbq_entry);
8650 		phba->total_iocbq_bufs--;
8651 	}
8652 	spin_unlock_irq(&phba->hbalock);
8653 
8654 	return;
8655 }
8656 
8657 /**
8658  * lpfc_init_iocb_list - Allocate and initialize iocb list.
8659  * @phba: pointer to lpfc hba data structure.
8660  * @iocb_count: number of requested iocbs
8661  *
8662  * This routine is invoked to allocate and initizlize the driver's IOCB
8663  * list and set up the IOCB tag array accordingly.
8664  *
8665  * Return codes
8666  *	0 - successful
8667  *	other values - error
8668  **/
8669 int
8670 lpfc_init_iocb_list(struct lpfc_hba *phba, int iocb_count)
8671 {
8672 	struct lpfc_iocbq *iocbq_entry = NULL;
8673 	uint16_t iotag;
8674 	int i;
8675 
8676 	/* Initialize and populate the iocb list per host.  */
8677 	INIT_LIST_HEAD(&phba->lpfc_iocb_list);
8678 	for (i = 0; i < iocb_count; i++) {
8679 		iocbq_entry = kzalloc(sizeof(struct lpfc_iocbq), GFP_KERNEL);
8680 		if (iocbq_entry == NULL) {
8681 			printk(KERN_ERR "%s: only allocated %d iocbs of "
8682 				"expected %d count. Unloading driver.\n",
8683 				__func__, i, iocb_count);
8684 			goto out_free_iocbq;
8685 		}
8686 
8687 		iotag = lpfc_sli_next_iotag(phba, iocbq_entry);
8688 		if (iotag == 0) {
8689 			kfree(iocbq_entry);
8690 			printk(KERN_ERR "%s: failed to allocate IOTAG. "
8691 				"Unloading driver.\n", __func__);
8692 			goto out_free_iocbq;
8693 		}
8694 		iocbq_entry->sli4_lxritag = NO_XRI;
8695 		iocbq_entry->sli4_xritag = NO_XRI;
8696 
8697 		spin_lock_irq(&phba->hbalock);
8698 		list_add(&iocbq_entry->list, &phba->lpfc_iocb_list);
8699 		phba->total_iocbq_bufs++;
8700 		spin_unlock_irq(&phba->hbalock);
8701 	}
8702 
8703 	return 0;
8704 
8705 out_free_iocbq:
8706 	lpfc_free_iocb_list(phba);
8707 
8708 	return -ENOMEM;
8709 }
8710 
8711 /**
8712  * lpfc_free_sgl_list - Free a given sgl list.
8713  * @phba: pointer to lpfc hba data structure.
8714  * @sglq_list: pointer to the head of sgl list.
8715  *
8716  * This routine is invoked to free a give sgl list and memory.
8717  **/
8718 void
8719 lpfc_free_sgl_list(struct lpfc_hba *phba, struct list_head *sglq_list)
8720 {
8721 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
8722 
8723 	list_for_each_entry_safe(sglq_entry, sglq_next, sglq_list, list) {
8724 		list_del(&sglq_entry->list);
8725 		lpfc_mbuf_free(phba, sglq_entry->virt, sglq_entry->phys);
8726 		kfree(sglq_entry);
8727 	}
8728 }
8729 
8730 /**
8731  * lpfc_free_els_sgl_list - Free els sgl list.
8732  * @phba: pointer to lpfc hba data structure.
8733  *
8734  * This routine is invoked to free the driver's els sgl list and memory.
8735  **/
8736 static void
8737 lpfc_free_els_sgl_list(struct lpfc_hba *phba)
8738 {
8739 	LIST_HEAD(sglq_list);
8740 
8741 	/* Retrieve all els sgls from driver list */
8742 	spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
8743 	list_splice_init(&phba->sli4_hba.lpfc_els_sgl_list, &sglq_list);
8744 	spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
8745 
8746 	/* Now free the sgl list */
8747 	lpfc_free_sgl_list(phba, &sglq_list);
8748 }
8749 
8750 /**
8751  * lpfc_free_nvmet_sgl_list - Free nvmet sgl list.
8752  * @phba: pointer to lpfc hba data structure.
8753  *
8754  * This routine is invoked to free the driver's nvmet sgl list and memory.
8755  **/
8756 static void
8757 lpfc_free_nvmet_sgl_list(struct lpfc_hba *phba)
8758 {
8759 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
8760 	LIST_HEAD(sglq_list);
8761 
8762 	/* Retrieve all nvmet sgls from driver list */
8763 	spin_lock_irq(&phba->hbalock);
8764 	spin_lock(&phba->sli4_hba.sgl_list_lock);
8765 	list_splice_init(&phba->sli4_hba.lpfc_nvmet_sgl_list, &sglq_list);
8766 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
8767 	spin_unlock_irq(&phba->hbalock);
8768 
8769 	/* Now free the sgl list */
8770 	list_for_each_entry_safe(sglq_entry, sglq_next, &sglq_list, list) {
8771 		list_del(&sglq_entry->list);
8772 		lpfc_nvmet_buf_free(phba, sglq_entry->virt, sglq_entry->phys);
8773 		kfree(sglq_entry);
8774 	}
8775 
8776 	/* Update the nvmet_xri_cnt to reflect no current sgls.
8777 	 * The next initialization cycle sets the count and allocates
8778 	 * the sgls over again.
8779 	 */
8780 	phba->sli4_hba.nvmet_xri_cnt = 0;
8781 }
8782 
8783 /**
8784  * lpfc_init_active_sgl_array - Allocate the buf to track active ELS XRIs.
8785  * @phba: pointer to lpfc hba data structure.
8786  *
8787  * This routine is invoked to allocate the driver's active sgl memory.
8788  * This array will hold the sglq_entry's for active IOs.
8789  **/
8790 static int
8791 lpfc_init_active_sgl_array(struct lpfc_hba *phba)
8792 {
8793 	int size;
8794 	size = sizeof(struct lpfc_sglq *);
8795 	size *= phba->sli4_hba.max_cfg_param.max_xri;
8796 
8797 	phba->sli4_hba.lpfc_sglq_active_list =
8798 		kzalloc(size, GFP_KERNEL);
8799 	if (!phba->sli4_hba.lpfc_sglq_active_list)
8800 		return -ENOMEM;
8801 	return 0;
8802 }
8803 
8804 /**
8805  * lpfc_free_active_sgl - Free the buf that tracks active ELS XRIs.
8806  * @phba: pointer to lpfc hba data structure.
8807  *
8808  * This routine is invoked to walk through the array of active sglq entries
8809  * and free all of the resources.
8810  * This is just a place holder for now.
8811  **/
8812 static void
8813 lpfc_free_active_sgl(struct lpfc_hba *phba)
8814 {
8815 	kfree(phba->sli4_hba.lpfc_sglq_active_list);
8816 }
8817 
8818 /**
8819  * lpfc_init_sgl_list - Allocate and initialize sgl list.
8820  * @phba: pointer to lpfc hba data structure.
8821  *
8822  * This routine is invoked to allocate and initizlize the driver's sgl
8823  * list and set up the sgl xritag tag array accordingly.
8824  *
8825  **/
8826 static void
8827 lpfc_init_sgl_list(struct lpfc_hba *phba)
8828 {
8829 	/* Initialize and populate the sglq list per host/VF. */
8830 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_els_sgl_list);
8831 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_els_sgl_list);
8832 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_nvmet_sgl_list);
8833 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
8834 
8835 	/* els xri-sgl book keeping */
8836 	phba->sli4_hba.els_xri_cnt = 0;
8837 
8838 	/* nvme xri-buffer book keeping */
8839 	phba->sli4_hba.io_xri_cnt = 0;
8840 }
8841 
8842 /**
8843  * lpfc_sli4_init_rpi_hdrs - Post the rpi header memory region to the port
8844  * @phba: pointer to lpfc hba data structure.
8845  *
8846  * This routine is invoked to post rpi header templates to the
8847  * port for those SLI4 ports that do not support extents.  This routine
8848  * posts a PAGE_SIZE memory region to the port to hold up to
8849  * PAGE_SIZE modulo 64 rpi context headers.  This is an initialization routine
8850  * and should be called only when interrupts are disabled.
8851  *
8852  * Return codes
8853  * 	0 - successful
8854  *	-ERROR - otherwise.
8855  **/
8856 int
8857 lpfc_sli4_init_rpi_hdrs(struct lpfc_hba *phba)
8858 {
8859 	int rc = 0;
8860 	struct lpfc_rpi_hdr *rpi_hdr;
8861 
8862 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_rpi_hdr_list);
8863 	if (!phba->sli4_hba.rpi_hdrs_in_use)
8864 		return rc;
8865 	if (phba->sli4_hba.extents_in_use)
8866 		return -EIO;
8867 
8868 	rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
8869 	if (!rpi_hdr) {
8870 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8871 				"0391 Error during rpi post operation\n");
8872 		lpfc_sli4_remove_rpis(phba);
8873 		rc = -ENODEV;
8874 	}
8875 
8876 	return rc;
8877 }
8878 
8879 /**
8880  * lpfc_sli4_create_rpi_hdr - Allocate an rpi header memory region
8881  * @phba: pointer to lpfc hba data structure.
8882  *
8883  * This routine is invoked to allocate a single 4KB memory region to
8884  * support rpis and stores them in the phba.  This single region
8885  * provides support for up to 64 rpis.  The region is used globally
8886  * by the device.
8887  *
8888  * Returns:
8889  *   A valid rpi hdr on success.
8890  *   A NULL pointer on any failure.
8891  **/
8892 struct lpfc_rpi_hdr *
8893 lpfc_sli4_create_rpi_hdr(struct lpfc_hba *phba)
8894 {
8895 	uint16_t rpi_limit, curr_rpi_range;
8896 	struct lpfc_dmabuf *dmabuf;
8897 	struct lpfc_rpi_hdr *rpi_hdr;
8898 
8899 	/*
8900 	 * If the SLI4 port supports extents, posting the rpi header isn't
8901 	 * required.  Set the expected maximum count and let the actual value
8902 	 * get set when extents are fully allocated.
8903 	 */
8904 	if (!phba->sli4_hba.rpi_hdrs_in_use)
8905 		return NULL;
8906 	if (phba->sli4_hba.extents_in_use)
8907 		return NULL;
8908 
8909 	/* The limit on the logical index is just the max_rpi count. */
8910 	rpi_limit = phba->sli4_hba.max_cfg_param.max_rpi;
8911 
8912 	spin_lock_irq(&phba->hbalock);
8913 	/*
8914 	 * Establish the starting RPI in this header block.  The starting
8915 	 * rpi is normalized to a zero base because the physical rpi is
8916 	 * port based.
8917 	 */
8918 	curr_rpi_range = phba->sli4_hba.next_rpi;
8919 	spin_unlock_irq(&phba->hbalock);
8920 
8921 	/* Reached full RPI range */
8922 	if (curr_rpi_range == rpi_limit)
8923 		return NULL;
8924 
8925 	/*
8926 	 * First allocate the protocol header region for the port.  The
8927 	 * port expects a 4KB DMA-mapped memory region that is 4K aligned.
8928 	 */
8929 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
8930 	if (!dmabuf)
8931 		return NULL;
8932 
8933 	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
8934 					  LPFC_HDR_TEMPLATE_SIZE,
8935 					  &dmabuf->phys, GFP_KERNEL);
8936 	if (!dmabuf->virt) {
8937 		rpi_hdr = NULL;
8938 		goto err_free_dmabuf;
8939 	}
8940 
8941 	if (!IS_ALIGNED(dmabuf->phys, LPFC_HDR_TEMPLATE_SIZE)) {
8942 		rpi_hdr = NULL;
8943 		goto err_free_coherent;
8944 	}
8945 
8946 	/* Save the rpi header data for cleanup later. */
8947 	rpi_hdr = kzalloc(sizeof(struct lpfc_rpi_hdr), GFP_KERNEL);
8948 	if (!rpi_hdr)
8949 		goto err_free_coherent;
8950 
8951 	rpi_hdr->dmabuf = dmabuf;
8952 	rpi_hdr->len = LPFC_HDR_TEMPLATE_SIZE;
8953 	rpi_hdr->page_count = 1;
8954 	spin_lock_irq(&phba->hbalock);
8955 
8956 	/* The rpi_hdr stores the logical index only. */
8957 	rpi_hdr->start_rpi = curr_rpi_range;
8958 	rpi_hdr->next_rpi = phba->sli4_hba.next_rpi + LPFC_RPI_HDR_COUNT;
8959 	list_add_tail(&rpi_hdr->list, &phba->sli4_hba.lpfc_rpi_hdr_list);
8960 
8961 	spin_unlock_irq(&phba->hbalock);
8962 	return rpi_hdr;
8963 
8964  err_free_coherent:
8965 	dma_free_coherent(&phba->pcidev->dev, LPFC_HDR_TEMPLATE_SIZE,
8966 			  dmabuf->virt, dmabuf->phys);
8967  err_free_dmabuf:
8968 	kfree(dmabuf);
8969 	return NULL;
8970 }
8971 
8972 /**
8973  * lpfc_sli4_remove_rpi_hdrs - Remove all rpi header memory regions
8974  * @phba: pointer to lpfc hba data structure.
8975  *
8976  * This routine is invoked to remove all memory resources allocated
8977  * to support rpis for SLI4 ports not supporting extents. This routine
8978  * presumes the caller has released all rpis consumed by fabric or port
8979  * logins and is prepared to have the header pages removed.
8980  **/
8981 void
8982 lpfc_sli4_remove_rpi_hdrs(struct lpfc_hba *phba)
8983 {
8984 	struct lpfc_rpi_hdr *rpi_hdr, *next_rpi_hdr;
8985 
8986 	if (!phba->sli4_hba.rpi_hdrs_in_use)
8987 		goto exit;
8988 
8989 	list_for_each_entry_safe(rpi_hdr, next_rpi_hdr,
8990 				 &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
8991 		list_del(&rpi_hdr->list);
8992 		dma_free_coherent(&phba->pcidev->dev, rpi_hdr->len,
8993 				  rpi_hdr->dmabuf->virt, rpi_hdr->dmabuf->phys);
8994 		kfree(rpi_hdr->dmabuf);
8995 		kfree(rpi_hdr);
8996 	}
8997  exit:
8998 	/* There are no rpis available to the port now. */
8999 	phba->sli4_hba.next_rpi = 0;
9000 }
9001 
9002 /**
9003  * lpfc_hba_alloc - Allocate driver hba data structure for a device.
9004  * @pdev: pointer to pci device data structure.
9005  *
9006  * This routine is invoked to allocate the driver hba data structure for an
9007  * HBA device. If the allocation is successful, the phba reference to the
9008  * PCI device data structure is set.
9009  *
9010  * Return codes
9011  *      pointer to @phba - successful
9012  *      NULL - error
9013  **/
9014 static struct lpfc_hba *
9015 lpfc_hba_alloc(struct pci_dev *pdev)
9016 {
9017 	struct lpfc_hba *phba;
9018 
9019 	/* Allocate memory for HBA structure */
9020 	phba = kzalloc(sizeof(struct lpfc_hba), GFP_KERNEL);
9021 	if (!phba) {
9022 		dev_err(&pdev->dev, "failed to allocate hba struct\n");
9023 		return NULL;
9024 	}
9025 
9026 	/* Set reference to PCI device in HBA structure */
9027 	phba->pcidev = pdev;
9028 
9029 	/* Assign an unused board number */
9030 	phba->brd_no = lpfc_get_instance();
9031 	if (phba->brd_no < 0) {
9032 		kfree(phba);
9033 		return NULL;
9034 	}
9035 	phba->eratt_poll_interval = LPFC_ERATT_POLL_INTERVAL;
9036 
9037 	spin_lock_init(&phba->ct_ev_lock);
9038 	INIT_LIST_HEAD(&phba->ct_ev_waiters);
9039 
9040 	return phba;
9041 }
9042 
9043 /**
9044  * lpfc_hba_free - Free driver hba data structure with a device.
9045  * @phba: pointer to lpfc hba data structure.
9046  *
9047  * This routine is invoked to free the driver hba data structure with an
9048  * HBA device.
9049  **/
9050 static void
9051 lpfc_hba_free(struct lpfc_hba *phba)
9052 {
9053 	if (phba->sli_rev == LPFC_SLI_REV4)
9054 		kfree(phba->sli4_hba.hdwq);
9055 
9056 	/* Release the driver assigned board number */
9057 	idr_remove(&lpfc_hba_index, phba->brd_no);
9058 
9059 	/* Free memory allocated with sli3 rings */
9060 	kfree(phba->sli.sli3_ring);
9061 	phba->sli.sli3_ring = NULL;
9062 
9063 	kfree(phba);
9064 	return;
9065 }
9066 
9067 /**
9068  * lpfc_setup_fdmi_mask - Setup initial FDMI mask for HBA and Port attributes
9069  * @vport: pointer to lpfc vport data structure.
9070  *
9071  * This routine is will setup initial FDMI attribute masks for
9072  * FDMI2 or SmartSAN depending on module parameters. The driver will attempt
9073  * to get these attributes first before falling back, the attribute
9074  * fallback hierarchy is SmartSAN -> FDMI2 -> FMDI1
9075  **/
9076 void
9077 lpfc_setup_fdmi_mask(struct lpfc_vport *vport)
9078 {
9079 	struct lpfc_hba *phba = vport->phba;
9080 
9081 	vport->load_flag |= FC_ALLOW_FDMI;
9082 	if (phba->cfg_enable_SmartSAN ||
9083 	    phba->cfg_fdmi_on == LPFC_FDMI_SUPPORT) {
9084 		/* Setup appropriate attribute masks */
9085 		vport->fdmi_hba_mask = LPFC_FDMI2_HBA_ATTR;
9086 		if (phba->cfg_enable_SmartSAN)
9087 			vport->fdmi_port_mask = LPFC_FDMI2_SMART_ATTR;
9088 		else
9089 			vport->fdmi_port_mask = LPFC_FDMI2_PORT_ATTR;
9090 	}
9091 
9092 	lpfc_printf_log(phba, KERN_INFO, LOG_DISCOVERY,
9093 			"6077 Setup FDMI mask: hba x%x port x%x\n",
9094 			vport->fdmi_hba_mask, vport->fdmi_port_mask);
9095 }
9096 
9097 /**
9098  * lpfc_create_shost - Create hba physical port with associated scsi host.
9099  * @phba: pointer to lpfc hba data structure.
9100  *
9101  * This routine is invoked to create HBA physical port and associate a SCSI
9102  * host with it.
9103  *
9104  * Return codes
9105  *      0 - successful
9106  *      other values - error
9107  **/
9108 static int
9109 lpfc_create_shost(struct lpfc_hba *phba)
9110 {
9111 	struct lpfc_vport *vport;
9112 	struct Scsi_Host  *shost;
9113 
9114 	/* Initialize HBA FC structure */
9115 	phba->fc_edtov = FF_DEF_EDTOV;
9116 	phba->fc_ratov = FF_DEF_RATOV;
9117 	phba->fc_altov = FF_DEF_ALTOV;
9118 	phba->fc_arbtov = FF_DEF_ARBTOV;
9119 
9120 	atomic_set(&phba->sdev_cnt, 0);
9121 	vport = lpfc_create_port(phba, phba->brd_no, &phba->pcidev->dev);
9122 	if (!vport)
9123 		return -ENODEV;
9124 
9125 	shost = lpfc_shost_from_vport(vport);
9126 	phba->pport = vport;
9127 
9128 	if (phba->nvmet_support) {
9129 		/* Only 1 vport (pport) will support NVME target */
9130 		phba->targetport = NULL;
9131 		phba->cfg_enable_fc4_type = LPFC_ENABLE_NVME;
9132 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_NVME_DISC,
9133 				"6076 NVME Target Found\n");
9134 	}
9135 
9136 	lpfc_debugfs_initialize(vport);
9137 	/* Put reference to SCSI host to driver's device private data */
9138 	pci_set_drvdata(phba->pcidev, shost);
9139 
9140 	lpfc_setup_fdmi_mask(vport);
9141 
9142 	/*
9143 	 * At this point we are fully registered with PSA. In addition,
9144 	 * any initial discovery should be completed.
9145 	 */
9146 	return 0;
9147 }
9148 
9149 /**
9150  * lpfc_destroy_shost - Destroy hba physical port with associated scsi host.
9151  * @phba: pointer to lpfc hba data structure.
9152  *
9153  * This routine is invoked to destroy HBA physical port and the associated
9154  * SCSI host.
9155  **/
9156 static void
9157 lpfc_destroy_shost(struct lpfc_hba *phba)
9158 {
9159 	struct lpfc_vport *vport = phba->pport;
9160 
9161 	/* Destroy physical port that associated with the SCSI host */
9162 	destroy_port(vport);
9163 
9164 	return;
9165 }
9166 
9167 /**
9168  * lpfc_setup_bg - Setup Block guard structures and debug areas.
9169  * @phba: pointer to lpfc hba data structure.
9170  * @shost: the shost to be used to detect Block guard settings.
9171  *
9172  * This routine sets up the local Block guard protocol settings for @shost.
9173  * This routine also allocates memory for debugging bg buffers.
9174  **/
9175 static void
9176 lpfc_setup_bg(struct lpfc_hba *phba, struct Scsi_Host *shost)
9177 {
9178 	uint32_t old_mask;
9179 	uint32_t old_guard;
9180 
9181 	if (phba->cfg_prot_mask && phba->cfg_prot_guard) {
9182 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9183 				"1478 Registering BlockGuard with the "
9184 				"SCSI layer\n");
9185 
9186 		old_mask = phba->cfg_prot_mask;
9187 		old_guard = phba->cfg_prot_guard;
9188 
9189 		/* Only allow supported values */
9190 		phba->cfg_prot_mask &= (SHOST_DIF_TYPE1_PROTECTION |
9191 			SHOST_DIX_TYPE0_PROTECTION |
9192 			SHOST_DIX_TYPE1_PROTECTION);
9193 		phba->cfg_prot_guard &= (SHOST_DIX_GUARD_IP |
9194 					 SHOST_DIX_GUARD_CRC);
9195 
9196 		/* DIF Type 1 protection for profiles AST1/C1 is end to end */
9197 		if (phba->cfg_prot_mask == SHOST_DIX_TYPE1_PROTECTION)
9198 			phba->cfg_prot_mask |= SHOST_DIF_TYPE1_PROTECTION;
9199 
9200 		if (phba->cfg_prot_mask && phba->cfg_prot_guard) {
9201 			if ((old_mask != phba->cfg_prot_mask) ||
9202 				(old_guard != phba->cfg_prot_guard))
9203 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9204 					"1475 Registering BlockGuard with the "
9205 					"SCSI layer: mask %d  guard %d\n",
9206 					phba->cfg_prot_mask,
9207 					phba->cfg_prot_guard);
9208 
9209 			scsi_host_set_prot(shost, phba->cfg_prot_mask);
9210 			scsi_host_set_guard(shost, phba->cfg_prot_guard);
9211 		} else
9212 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9213 				"1479 Not Registering BlockGuard with the SCSI "
9214 				"layer, Bad protection parameters: %d %d\n",
9215 				old_mask, old_guard);
9216 	}
9217 }
9218 
9219 /**
9220  * lpfc_post_init_setup - Perform necessary device post initialization setup.
9221  * @phba: pointer to lpfc hba data structure.
9222  *
9223  * This routine is invoked to perform all the necessary post initialization
9224  * setup for the device.
9225  **/
9226 static void
9227 lpfc_post_init_setup(struct lpfc_hba *phba)
9228 {
9229 	struct Scsi_Host  *shost;
9230 	struct lpfc_adapter_event_header adapter_event;
9231 
9232 	/* Get the default values for Model Name and Description */
9233 	lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
9234 
9235 	/*
9236 	 * hba setup may have changed the hba_queue_depth so we need to
9237 	 * adjust the value of can_queue.
9238 	 */
9239 	shost = pci_get_drvdata(phba->pcidev);
9240 	shost->can_queue = phba->cfg_hba_queue_depth - 10;
9241 
9242 	lpfc_host_attrib_init(shost);
9243 
9244 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
9245 		spin_lock_irq(shost->host_lock);
9246 		lpfc_poll_start_timer(phba);
9247 		spin_unlock_irq(shost->host_lock);
9248 	}
9249 
9250 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9251 			"0428 Perform SCSI scan\n");
9252 	/* Send board arrival event to upper layer */
9253 	adapter_event.event_type = FC_REG_ADAPTER_EVENT;
9254 	adapter_event.subcategory = LPFC_EVENT_ARRIVAL;
9255 	fc_host_post_vendor_event(shost, fc_get_event_number(),
9256 				  sizeof(adapter_event),
9257 				  (char *) &adapter_event,
9258 				  LPFC_NL_VENDOR_ID);
9259 	return;
9260 }
9261 
9262 /**
9263  * lpfc_sli_pci_mem_setup - Setup SLI3 HBA PCI memory space.
9264  * @phba: pointer to lpfc hba data structure.
9265  *
9266  * This routine is invoked to set up the PCI device memory space for device
9267  * with SLI-3 interface spec.
9268  *
9269  * Return codes
9270  * 	0 - successful
9271  * 	other values - error
9272  **/
9273 static int
9274 lpfc_sli_pci_mem_setup(struct lpfc_hba *phba)
9275 {
9276 	struct pci_dev *pdev = phba->pcidev;
9277 	unsigned long bar0map_len, bar2map_len;
9278 	int i, hbq_count;
9279 	void *ptr;
9280 	int error;
9281 
9282 	if (!pdev)
9283 		return -ENODEV;
9284 
9285 	/* Set the device DMA mask size */
9286 	error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
9287 	if (error)
9288 		error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32));
9289 	if (error)
9290 		return error;
9291 	error = -ENODEV;
9292 
9293 	/* Get the bus address of Bar0 and Bar2 and the number of bytes
9294 	 * required by each mapping.
9295 	 */
9296 	phba->pci_bar0_map = pci_resource_start(pdev, 0);
9297 	bar0map_len = pci_resource_len(pdev, 0);
9298 
9299 	phba->pci_bar2_map = pci_resource_start(pdev, 2);
9300 	bar2map_len = pci_resource_len(pdev, 2);
9301 
9302 	/* Map HBA SLIM to a kernel virtual address. */
9303 	phba->slim_memmap_p = ioremap(phba->pci_bar0_map, bar0map_len);
9304 	if (!phba->slim_memmap_p) {
9305 		dev_printk(KERN_ERR, &pdev->dev,
9306 			   "ioremap failed for SLIM memory.\n");
9307 		goto out;
9308 	}
9309 
9310 	/* Map HBA Control Registers to a kernel virtual address. */
9311 	phba->ctrl_regs_memmap_p = ioremap(phba->pci_bar2_map, bar2map_len);
9312 	if (!phba->ctrl_regs_memmap_p) {
9313 		dev_printk(KERN_ERR, &pdev->dev,
9314 			   "ioremap failed for HBA control registers.\n");
9315 		goto out_iounmap_slim;
9316 	}
9317 
9318 	/* Allocate memory for SLI-2 structures */
9319 	phba->slim2p.virt = dma_alloc_coherent(&pdev->dev, SLI2_SLIM_SIZE,
9320 					       &phba->slim2p.phys, GFP_KERNEL);
9321 	if (!phba->slim2p.virt)
9322 		goto out_iounmap;
9323 
9324 	phba->mbox = phba->slim2p.virt + offsetof(struct lpfc_sli2_slim, mbx);
9325 	phba->mbox_ext = (phba->slim2p.virt +
9326 		offsetof(struct lpfc_sli2_slim, mbx_ext_words));
9327 	phba->pcb = (phba->slim2p.virt + offsetof(struct lpfc_sli2_slim, pcb));
9328 	phba->IOCBs = (phba->slim2p.virt +
9329 		       offsetof(struct lpfc_sli2_slim, IOCBs));
9330 
9331 	phba->hbqslimp.virt = dma_alloc_coherent(&pdev->dev,
9332 						 lpfc_sli_hbq_size(),
9333 						 &phba->hbqslimp.phys,
9334 						 GFP_KERNEL);
9335 	if (!phba->hbqslimp.virt)
9336 		goto out_free_slim;
9337 
9338 	hbq_count = lpfc_sli_hbq_count();
9339 	ptr = phba->hbqslimp.virt;
9340 	for (i = 0; i < hbq_count; ++i) {
9341 		phba->hbqs[i].hbq_virt = ptr;
9342 		INIT_LIST_HEAD(&phba->hbqs[i].hbq_buffer_list);
9343 		ptr += (lpfc_hbq_defs[i]->entry_count *
9344 			sizeof(struct lpfc_hbq_entry));
9345 	}
9346 	phba->hbqs[LPFC_ELS_HBQ].hbq_alloc_buffer = lpfc_els_hbq_alloc;
9347 	phba->hbqs[LPFC_ELS_HBQ].hbq_free_buffer = lpfc_els_hbq_free;
9348 
9349 	memset(phba->hbqslimp.virt, 0, lpfc_sli_hbq_size());
9350 
9351 	phba->MBslimaddr = phba->slim_memmap_p;
9352 	phba->HAregaddr = phba->ctrl_regs_memmap_p + HA_REG_OFFSET;
9353 	phba->CAregaddr = phba->ctrl_regs_memmap_p + CA_REG_OFFSET;
9354 	phba->HSregaddr = phba->ctrl_regs_memmap_p + HS_REG_OFFSET;
9355 	phba->HCregaddr = phba->ctrl_regs_memmap_p + HC_REG_OFFSET;
9356 
9357 	return 0;
9358 
9359 out_free_slim:
9360 	dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
9361 			  phba->slim2p.virt, phba->slim2p.phys);
9362 out_iounmap:
9363 	iounmap(phba->ctrl_regs_memmap_p);
9364 out_iounmap_slim:
9365 	iounmap(phba->slim_memmap_p);
9366 out:
9367 	return error;
9368 }
9369 
9370 /**
9371  * lpfc_sli_pci_mem_unset - Unset SLI3 HBA PCI memory space.
9372  * @phba: pointer to lpfc hba data structure.
9373  *
9374  * This routine is invoked to unset the PCI device memory space for device
9375  * with SLI-3 interface spec.
9376  **/
9377 static void
9378 lpfc_sli_pci_mem_unset(struct lpfc_hba *phba)
9379 {
9380 	struct pci_dev *pdev;
9381 
9382 	/* Obtain PCI device reference */
9383 	if (!phba->pcidev)
9384 		return;
9385 	else
9386 		pdev = phba->pcidev;
9387 
9388 	/* Free coherent DMA memory allocated */
9389 	dma_free_coherent(&pdev->dev, lpfc_sli_hbq_size(),
9390 			  phba->hbqslimp.virt, phba->hbqslimp.phys);
9391 	dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
9392 			  phba->slim2p.virt, phba->slim2p.phys);
9393 
9394 	/* I/O memory unmap */
9395 	iounmap(phba->ctrl_regs_memmap_p);
9396 	iounmap(phba->slim_memmap_p);
9397 
9398 	return;
9399 }
9400 
9401 /**
9402  * lpfc_sli4_post_status_check - Wait for SLI4 POST done and check status
9403  * @phba: pointer to lpfc hba data structure.
9404  *
9405  * This routine is invoked to wait for SLI4 device Power On Self Test (POST)
9406  * done and check status.
9407  *
9408  * Return 0 if successful, otherwise -ENODEV.
9409  **/
9410 int
9411 lpfc_sli4_post_status_check(struct lpfc_hba *phba)
9412 {
9413 	struct lpfc_register portsmphr_reg, uerrlo_reg, uerrhi_reg;
9414 	struct lpfc_register reg_data;
9415 	int i, port_error = 0;
9416 	uint32_t if_type;
9417 
9418 	memset(&portsmphr_reg, 0, sizeof(portsmphr_reg));
9419 	memset(&reg_data, 0, sizeof(reg_data));
9420 	if (!phba->sli4_hba.PSMPHRregaddr)
9421 		return -ENODEV;
9422 
9423 	/* Wait up to 30 seconds for the SLI Port POST done and ready */
9424 	for (i = 0; i < 3000; i++) {
9425 		if (lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
9426 			&portsmphr_reg.word0) ||
9427 			(bf_get(lpfc_port_smphr_perr, &portsmphr_reg))) {
9428 			/* Port has a fatal POST error, break out */
9429 			port_error = -ENODEV;
9430 			break;
9431 		}
9432 		if (LPFC_POST_STAGE_PORT_READY ==
9433 		    bf_get(lpfc_port_smphr_port_status, &portsmphr_reg))
9434 			break;
9435 		msleep(10);
9436 	}
9437 
9438 	/*
9439 	 * If there was a port error during POST, then don't proceed with
9440 	 * other register reads as the data may not be valid.  Just exit.
9441 	 */
9442 	if (port_error) {
9443 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9444 			"1408 Port Failed POST - portsmphr=0x%x, "
9445 			"perr=x%x, sfi=x%x, nip=x%x, ipc=x%x, scr1=x%x, "
9446 			"scr2=x%x, hscratch=x%x, pstatus=x%x\n",
9447 			portsmphr_reg.word0,
9448 			bf_get(lpfc_port_smphr_perr, &portsmphr_reg),
9449 			bf_get(lpfc_port_smphr_sfi, &portsmphr_reg),
9450 			bf_get(lpfc_port_smphr_nip, &portsmphr_reg),
9451 			bf_get(lpfc_port_smphr_ipc, &portsmphr_reg),
9452 			bf_get(lpfc_port_smphr_scr1, &portsmphr_reg),
9453 			bf_get(lpfc_port_smphr_scr2, &portsmphr_reg),
9454 			bf_get(lpfc_port_smphr_host_scratch, &portsmphr_reg),
9455 			bf_get(lpfc_port_smphr_port_status, &portsmphr_reg));
9456 	} else {
9457 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9458 				"2534 Device Info: SLIFamily=0x%x, "
9459 				"SLIRev=0x%x, IFType=0x%x, SLIHint_1=0x%x, "
9460 				"SLIHint_2=0x%x, FT=0x%x\n",
9461 				bf_get(lpfc_sli_intf_sli_family,
9462 				       &phba->sli4_hba.sli_intf),
9463 				bf_get(lpfc_sli_intf_slirev,
9464 				       &phba->sli4_hba.sli_intf),
9465 				bf_get(lpfc_sli_intf_if_type,
9466 				       &phba->sli4_hba.sli_intf),
9467 				bf_get(lpfc_sli_intf_sli_hint1,
9468 				       &phba->sli4_hba.sli_intf),
9469 				bf_get(lpfc_sli_intf_sli_hint2,
9470 				       &phba->sli4_hba.sli_intf),
9471 				bf_get(lpfc_sli_intf_func_type,
9472 				       &phba->sli4_hba.sli_intf));
9473 		/*
9474 		 * Check for other Port errors during the initialization
9475 		 * process.  Fail the load if the port did not come up
9476 		 * correctly.
9477 		 */
9478 		if_type = bf_get(lpfc_sli_intf_if_type,
9479 				 &phba->sli4_hba.sli_intf);
9480 		switch (if_type) {
9481 		case LPFC_SLI_INTF_IF_TYPE_0:
9482 			phba->sli4_hba.ue_mask_lo =
9483 			      readl(phba->sli4_hba.u.if_type0.UEMASKLOregaddr);
9484 			phba->sli4_hba.ue_mask_hi =
9485 			      readl(phba->sli4_hba.u.if_type0.UEMASKHIregaddr);
9486 			uerrlo_reg.word0 =
9487 			      readl(phba->sli4_hba.u.if_type0.UERRLOregaddr);
9488 			uerrhi_reg.word0 =
9489 				readl(phba->sli4_hba.u.if_type0.UERRHIregaddr);
9490 			if ((~phba->sli4_hba.ue_mask_lo & uerrlo_reg.word0) ||
9491 			    (~phba->sli4_hba.ue_mask_hi & uerrhi_reg.word0)) {
9492 				lpfc_printf_log(phba, KERN_ERR,
9493 						LOG_TRACE_EVENT,
9494 						"1422 Unrecoverable Error "
9495 						"Detected during POST "
9496 						"uerr_lo_reg=0x%x, "
9497 						"uerr_hi_reg=0x%x, "
9498 						"ue_mask_lo_reg=0x%x, "
9499 						"ue_mask_hi_reg=0x%x\n",
9500 						uerrlo_reg.word0,
9501 						uerrhi_reg.word0,
9502 						phba->sli4_hba.ue_mask_lo,
9503 						phba->sli4_hba.ue_mask_hi);
9504 				port_error = -ENODEV;
9505 			}
9506 			break;
9507 		case LPFC_SLI_INTF_IF_TYPE_2:
9508 		case LPFC_SLI_INTF_IF_TYPE_6:
9509 			/* Final checks.  The port status should be clean. */
9510 			if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
9511 				&reg_data.word0) ||
9512 				(bf_get(lpfc_sliport_status_err, &reg_data) &&
9513 				 !bf_get(lpfc_sliport_status_rn, &reg_data))) {
9514 				phba->work_status[0] =
9515 					readl(phba->sli4_hba.u.if_type2.
9516 					      ERR1regaddr);
9517 				phba->work_status[1] =
9518 					readl(phba->sli4_hba.u.if_type2.
9519 					      ERR2regaddr);
9520 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9521 					"2888 Unrecoverable port error "
9522 					"following POST: port status reg "
9523 					"0x%x, port_smphr reg 0x%x, "
9524 					"error 1=0x%x, error 2=0x%x\n",
9525 					reg_data.word0,
9526 					portsmphr_reg.word0,
9527 					phba->work_status[0],
9528 					phba->work_status[1]);
9529 				port_error = -ENODEV;
9530 				break;
9531 			}
9532 
9533 			if (lpfc_pldv_detect &&
9534 			    bf_get(lpfc_sli_intf_sli_family,
9535 				   &phba->sli4_hba.sli_intf) ==
9536 					LPFC_SLI_INTF_FAMILY_G6)
9537 				pci_write_config_byte(phba->pcidev,
9538 						      LPFC_SLI_INTF, CFG_PLD);
9539 			break;
9540 		case LPFC_SLI_INTF_IF_TYPE_1:
9541 		default:
9542 			break;
9543 		}
9544 	}
9545 	return port_error;
9546 }
9547 
9548 /**
9549  * lpfc_sli4_bar0_register_memmap - Set up SLI4 BAR0 register memory map.
9550  * @phba: pointer to lpfc hba data structure.
9551  * @if_type:  The SLI4 interface type getting configured.
9552  *
9553  * This routine is invoked to set up SLI4 BAR0 PCI config space register
9554  * memory map.
9555  **/
9556 static void
9557 lpfc_sli4_bar0_register_memmap(struct lpfc_hba *phba, uint32_t if_type)
9558 {
9559 	switch (if_type) {
9560 	case LPFC_SLI_INTF_IF_TYPE_0:
9561 		phba->sli4_hba.u.if_type0.UERRLOregaddr =
9562 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UERR_STATUS_LO;
9563 		phba->sli4_hba.u.if_type0.UERRHIregaddr =
9564 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UERR_STATUS_HI;
9565 		phba->sli4_hba.u.if_type0.UEMASKLOregaddr =
9566 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UE_MASK_LO;
9567 		phba->sli4_hba.u.if_type0.UEMASKHIregaddr =
9568 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UE_MASK_HI;
9569 		phba->sli4_hba.SLIINTFregaddr =
9570 			phba->sli4_hba.conf_regs_memmap_p + LPFC_SLI_INTF;
9571 		break;
9572 	case LPFC_SLI_INTF_IF_TYPE_2:
9573 		phba->sli4_hba.u.if_type2.EQDregaddr =
9574 			phba->sli4_hba.conf_regs_memmap_p +
9575 						LPFC_CTL_PORT_EQ_DELAY_OFFSET;
9576 		phba->sli4_hba.u.if_type2.ERR1regaddr =
9577 			phba->sli4_hba.conf_regs_memmap_p +
9578 						LPFC_CTL_PORT_ER1_OFFSET;
9579 		phba->sli4_hba.u.if_type2.ERR2regaddr =
9580 			phba->sli4_hba.conf_regs_memmap_p +
9581 						LPFC_CTL_PORT_ER2_OFFSET;
9582 		phba->sli4_hba.u.if_type2.CTRLregaddr =
9583 			phba->sli4_hba.conf_regs_memmap_p +
9584 						LPFC_CTL_PORT_CTL_OFFSET;
9585 		phba->sli4_hba.u.if_type2.STATUSregaddr =
9586 			phba->sli4_hba.conf_regs_memmap_p +
9587 						LPFC_CTL_PORT_STA_OFFSET;
9588 		phba->sli4_hba.SLIINTFregaddr =
9589 			phba->sli4_hba.conf_regs_memmap_p + LPFC_SLI_INTF;
9590 		phba->sli4_hba.PSMPHRregaddr =
9591 			phba->sli4_hba.conf_regs_memmap_p +
9592 						LPFC_CTL_PORT_SEM_OFFSET;
9593 		phba->sli4_hba.RQDBregaddr =
9594 			phba->sli4_hba.conf_regs_memmap_p +
9595 						LPFC_ULP0_RQ_DOORBELL;
9596 		phba->sli4_hba.WQDBregaddr =
9597 			phba->sli4_hba.conf_regs_memmap_p +
9598 						LPFC_ULP0_WQ_DOORBELL;
9599 		phba->sli4_hba.CQDBregaddr =
9600 			phba->sli4_hba.conf_regs_memmap_p + LPFC_EQCQ_DOORBELL;
9601 		phba->sli4_hba.EQDBregaddr = phba->sli4_hba.CQDBregaddr;
9602 		phba->sli4_hba.MQDBregaddr =
9603 			phba->sli4_hba.conf_regs_memmap_p + LPFC_MQ_DOORBELL;
9604 		phba->sli4_hba.BMBXregaddr =
9605 			phba->sli4_hba.conf_regs_memmap_p + LPFC_BMBX;
9606 		break;
9607 	case LPFC_SLI_INTF_IF_TYPE_6:
9608 		phba->sli4_hba.u.if_type2.EQDregaddr =
9609 			phba->sli4_hba.conf_regs_memmap_p +
9610 						LPFC_CTL_PORT_EQ_DELAY_OFFSET;
9611 		phba->sli4_hba.u.if_type2.ERR1regaddr =
9612 			phba->sli4_hba.conf_regs_memmap_p +
9613 						LPFC_CTL_PORT_ER1_OFFSET;
9614 		phba->sli4_hba.u.if_type2.ERR2regaddr =
9615 			phba->sli4_hba.conf_regs_memmap_p +
9616 						LPFC_CTL_PORT_ER2_OFFSET;
9617 		phba->sli4_hba.u.if_type2.CTRLregaddr =
9618 			phba->sli4_hba.conf_regs_memmap_p +
9619 						LPFC_CTL_PORT_CTL_OFFSET;
9620 		phba->sli4_hba.u.if_type2.STATUSregaddr =
9621 			phba->sli4_hba.conf_regs_memmap_p +
9622 						LPFC_CTL_PORT_STA_OFFSET;
9623 		phba->sli4_hba.PSMPHRregaddr =
9624 			phba->sli4_hba.conf_regs_memmap_p +
9625 						LPFC_CTL_PORT_SEM_OFFSET;
9626 		phba->sli4_hba.BMBXregaddr =
9627 			phba->sli4_hba.conf_regs_memmap_p + LPFC_BMBX;
9628 		break;
9629 	case LPFC_SLI_INTF_IF_TYPE_1:
9630 	default:
9631 		dev_printk(KERN_ERR, &phba->pcidev->dev,
9632 			   "FATAL - unsupported SLI4 interface type - %d\n",
9633 			   if_type);
9634 		break;
9635 	}
9636 }
9637 
9638 /**
9639  * lpfc_sli4_bar1_register_memmap - Set up SLI4 BAR1 register memory map.
9640  * @phba: pointer to lpfc hba data structure.
9641  * @if_type: sli if type to operate on.
9642  *
9643  * This routine is invoked to set up SLI4 BAR1 register memory map.
9644  **/
9645 static void
9646 lpfc_sli4_bar1_register_memmap(struct lpfc_hba *phba, uint32_t if_type)
9647 {
9648 	switch (if_type) {
9649 	case LPFC_SLI_INTF_IF_TYPE_0:
9650 		phba->sli4_hba.PSMPHRregaddr =
9651 			phba->sli4_hba.ctrl_regs_memmap_p +
9652 			LPFC_SLIPORT_IF0_SMPHR;
9653 		phba->sli4_hba.ISRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
9654 			LPFC_HST_ISR0;
9655 		phba->sli4_hba.IMRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
9656 			LPFC_HST_IMR0;
9657 		phba->sli4_hba.ISCRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
9658 			LPFC_HST_ISCR0;
9659 		break;
9660 	case LPFC_SLI_INTF_IF_TYPE_6:
9661 		phba->sli4_hba.RQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9662 			LPFC_IF6_RQ_DOORBELL;
9663 		phba->sli4_hba.WQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9664 			LPFC_IF6_WQ_DOORBELL;
9665 		phba->sli4_hba.CQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9666 			LPFC_IF6_CQ_DOORBELL;
9667 		phba->sli4_hba.EQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9668 			LPFC_IF6_EQ_DOORBELL;
9669 		phba->sli4_hba.MQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9670 			LPFC_IF6_MQ_DOORBELL;
9671 		break;
9672 	case LPFC_SLI_INTF_IF_TYPE_2:
9673 	case LPFC_SLI_INTF_IF_TYPE_1:
9674 	default:
9675 		dev_err(&phba->pcidev->dev,
9676 			   "FATAL - unsupported SLI4 interface type - %d\n",
9677 			   if_type);
9678 		break;
9679 	}
9680 }
9681 
9682 /**
9683  * lpfc_sli4_bar2_register_memmap - Set up SLI4 BAR2 register memory map.
9684  * @phba: pointer to lpfc hba data structure.
9685  * @vf: virtual function number
9686  *
9687  * This routine is invoked to set up SLI4 BAR2 doorbell register memory map
9688  * based on the given viftual function number, @vf.
9689  *
9690  * Return 0 if successful, otherwise -ENODEV.
9691  **/
9692 static int
9693 lpfc_sli4_bar2_register_memmap(struct lpfc_hba *phba, uint32_t vf)
9694 {
9695 	if (vf > LPFC_VIR_FUNC_MAX)
9696 		return -ENODEV;
9697 
9698 	phba->sli4_hba.RQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9699 				vf * LPFC_VFR_PAGE_SIZE +
9700 					LPFC_ULP0_RQ_DOORBELL);
9701 	phba->sli4_hba.WQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9702 				vf * LPFC_VFR_PAGE_SIZE +
9703 					LPFC_ULP0_WQ_DOORBELL);
9704 	phba->sli4_hba.CQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9705 				vf * LPFC_VFR_PAGE_SIZE +
9706 					LPFC_EQCQ_DOORBELL);
9707 	phba->sli4_hba.EQDBregaddr = phba->sli4_hba.CQDBregaddr;
9708 	phba->sli4_hba.MQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9709 				vf * LPFC_VFR_PAGE_SIZE + LPFC_MQ_DOORBELL);
9710 	phba->sli4_hba.BMBXregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9711 				vf * LPFC_VFR_PAGE_SIZE + LPFC_BMBX);
9712 	return 0;
9713 }
9714 
9715 /**
9716  * lpfc_create_bootstrap_mbox - Create the bootstrap mailbox
9717  * @phba: pointer to lpfc hba data structure.
9718  *
9719  * This routine is invoked to create the bootstrap mailbox
9720  * region consistent with the SLI-4 interface spec.  This
9721  * routine allocates all memory necessary to communicate
9722  * mailbox commands to the port and sets up all alignment
9723  * needs.  No locks are expected to be held when calling
9724  * this routine.
9725  *
9726  * Return codes
9727  * 	0 - successful
9728  * 	-ENOMEM - could not allocated memory.
9729  **/
9730 static int
9731 lpfc_create_bootstrap_mbox(struct lpfc_hba *phba)
9732 {
9733 	uint32_t bmbx_size;
9734 	struct lpfc_dmabuf *dmabuf;
9735 	struct dma_address *dma_address;
9736 	uint32_t pa_addr;
9737 	uint64_t phys_addr;
9738 
9739 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
9740 	if (!dmabuf)
9741 		return -ENOMEM;
9742 
9743 	/*
9744 	 * The bootstrap mailbox region is comprised of 2 parts
9745 	 * plus an alignment restriction of 16 bytes.
9746 	 */
9747 	bmbx_size = sizeof(struct lpfc_bmbx_create) + (LPFC_ALIGN_16_BYTE - 1);
9748 	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev, bmbx_size,
9749 					  &dmabuf->phys, GFP_KERNEL);
9750 	if (!dmabuf->virt) {
9751 		kfree(dmabuf);
9752 		return -ENOMEM;
9753 	}
9754 
9755 	/*
9756 	 * Initialize the bootstrap mailbox pointers now so that the register
9757 	 * operations are simple later.  The mailbox dma address is required
9758 	 * to be 16-byte aligned.  Also align the virtual memory as each
9759 	 * maibox is copied into the bmbx mailbox region before issuing the
9760 	 * command to the port.
9761 	 */
9762 	phba->sli4_hba.bmbx.dmabuf = dmabuf;
9763 	phba->sli4_hba.bmbx.bmbx_size = bmbx_size;
9764 
9765 	phba->sli4_hba.bmbx.avirt = PTR_ALIGN(dmabuf->virt,
9766 					      LPFC_ALIGN_16_BYTE);
9767 	phba->sli4_hba.bmbx.aphys = ALIGN(dmabuf->phys,
9768 					      LPFC_ALIGN_16_BYTE);
9769 
9770 	/*
9771 	 * Set the high and low physical addresses now.  The SLI4 alignment
9772 	 * requirement is 16 bytes and the mailbox is posted to the port
9773 	 * as two 30-bit addresses.  The other data is a bit marking whether
9774 	 * the 30-bit address is the high or low address.
9775 	 * Upcast bmbx aphys to 64bits so shift instruction compiles
9776 	 * clean on 32 bit machines.
9777 	 */
9778 	dma_address = &phba->sli4_hba.bmbx.dma_address;
9779 	phys_addr = (uint64_t)phba->sli4_hba.bmbx.aphys;
9780 	pa_addr = (uint32_t) ((phys_addr >> 34) & 0x3fffffff);
9781 	dma_address->addr_hi = (uint32_t) ((pa_addr << 2) |
9782 					   LPFC_BMBX_BIT1_ADDR_HI);
9783 
9784 	pa_addr = (uint32_t) ((phba->sli4_hba.bmbx.aphys >> 4) & 0x3fffffff);
9785 	dma_address->addr_lo = (uint32_t) ((pa_addr << 2) |
9786 					   LPFC_BMBX_BIT1_ADDR_LO);
9787 	return 0;
9788 }
9789 
9790 /**
9791  * lpfc_destroy_bootstrap_mbox - Destroy all bootstrap mailbox resources
9792  * @phba: pointer to lpfc hba data structure.
9793  *
9794  * This routine is invoked to teardown the bootstrap mailbox
9795  * region and release all host resources. This routine requires
9796  * the caller to ensure all mailbox commands recovered, no
9797  * additional mailbox comands are sent, and interrupts are disabled
9798  * before calling this routine.
9799  *
9800  **/
9801 static void
9802 lpfc_destroy_bootstrap_mbox(struct lpfc_hba *phba)
9803 {
9804 	dma_free_coherent(&phba->pcidev->dev,
9805 			  phba->sli4_hba.bmbx.bmbx_size,
9806 			  phba->sli4_hba.bmbx.dmabuf->virt,
9807 			  phba->sli4_hba.bmbx.dmabuf->phys);
9808 
9809 	kfree(phba->sli4_hba.bmbx.dmabuf);
9810 	memset(&phba->sli4_hba.bmbx, 0, sizeof(struct lpfc_bmbx));
9811 }
9812 
9813 static const char * const lpfc_topo_to_str[] = {
9814 	"Loop then P2P",
9815 	"Loopback",
9816 	"P2P Only",
9817 	"Unsupported",
9818 	"Loop Only",
9819 	"Unsupported",
9820 	"P2P then Loop",
9821 };
9822 
9823 #define	LINK_FLAGS_DEF	0x0
9824 #define	LINK_FLAGS_P2P	0x1
9825 #define	LINK_FLAGS_LOOP	0x2
9826 /**
9827  * lpfc_map_topology - Map the topology read from READ_CONFIG
9828  * @phba: pointer to lpfc hba data structure.
9829  * @rd_config: pointer to read config data
9830  *
9831  * This routine is invoked to map the topology values as read
9832  * from the read config mailbox command. If the persistent
9833  * topology feature is supported, the firmware will provide the
9834  * saved topology information to be used in INIT_LINK
9835  **/
9836 static void
9837 lpfc_map_topology(struct lpfc_hba *phba, struct lpfc_mbx_read_config *rd_config)
9838 {
9839 	u8 ptv, tf, pt;
9840 
9841 	ptv = bf_get(lpfc_mbx_rd_conf_ptv, rd_config);
9842 	tf = bf_get(lpfc_mbx_rd_conf_tf, rd_config);
9843 	pt = bf_get(lpfc_mbx_rd_conf_pt, rd_config);
9844 
9845 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9846 			"2027 Read Config Data : ptv:0x%x, tf:0x%x pt:0x%x",
9847 			 ptv, tf, pt);
9848 	if (!ptv) {
9849 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9850 				"2019 FW does not support persistent topology "
9851 				"Using driver parameter defined value [%s]",
9852 				lpfc_topo_to_str[phba->cfg_topology]);
9853 		return;
9854 	}
9855 	/* FW supports persistent topology - override module parameter value */
9856 	phba->hba_flag |= HBA_PERSISTENT_TOPO;
9857 
9858 	/* if ASIC_GEN_NUM >= 0xC) */
9859 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
9860 		    LPFC_SLI_INTF_IF_TYPE_6) ||
9861 	    (bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf) ==
9862 		    LPFC_SLI_INTF_FAMILY_G6)) {
9863 		if (!tf) {
9864 			phba->cfg_topology = ((pt == LINK_FLAGS_LOOP)
9865 					? FLAGS_TOPOLOGY_MODE_LOOP
9866 					: FLAGS_TOPOLOGY_MODE_PT_PT);
9867 		} else {
9868 			phba->hba_flag &= ~HBA_PERSISTENT_TOPO;
9869 		}
9870 	} else { /* G5 */
9871 		if (tf) {
9872 			/* If topology failover set - pt is '0' or '1' */
9873 			phba->cfg_topology = (pt ? FLAGS_TOPOLOGY_MODE_PT_LOOP :
9874 					      FLAGS_TOPOLOGY_MODE_LOOP_PT);
9875 		} else {
9876 			phba->cfg_topology = ((pt == LINK_FLAGS_P2P)
9877 					? FLAGS_TOPOLOGY_MODE_PT_PT
9878 					: FLAGS_TOPOLOGY_MODE_LOOP);
9879 		}
9880 	}
9881 	if (phba->hba_flag & HBA_PERSISTENT_TOPO) {
9882 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9883 				"2020 Using persistent topology value [%s]",
9884 				lpfc_topo_to_str[phba->cfg_topology]);
9885 	} else {
9886 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9887 				"2021 Invalid topology values from FW "
9888 				"Using driver parameter defined value [%s]",
9889 				lpfc_topo_to_str[phba->cfg_topology]);
9890 	}
9891 }
9892 
9893 /**
9894  * lpfc_sli4_read_config - Get the config parameters.
9895  * @phba: pointer to lpfc hba data structure.
9896  *
9897  * This routine is invoked to read the configuration parameters from the HBA.
9898  * The configuration parameters are used to set the base and maximum values
9899  * for RPI's XRI's VPI's VFI's and FCFIs. These values also affect the resource
9900  * allocation for the port.
9901  *
9902  * Return codes
9903  * 	0 - successful
9904  * 	-ENOMEM - No available memory
9905  *      -EIO - The mailbox failed to complete successfully.
9906  **/
9907 int
9908 lpfc_sli4_read_config(struct lpfc_hba *phba)
9909 {
9910 	LPFC_MBOXQ_t *pmb;
9911 	struct lpfc_mbx_read_config *rd_config;
9912 	union  lpfc_sli4_cfg_shdr *shdr;
9913 	uint32_t shdr_status, shdr_add_status;
9914 	struct lpfc_mbx_get_func_cfg *get_func_cfg;
9915 	struct lpfc_rsrc_desc_fcfcoe *desc;
9916 	char *pdesc_0;
9917 	uint16_t forced_link_speed;
9918 	uint32_t if_type, qmin, fawwpn;
9919 	int length, i, rc = 0, rc2;
9920 
9921 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
9922 	if (!pmb) {
9923 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9924 				"2011 Unable to allocate memory for issuing "
9925 				"SLI_CONFIG_SPECIAL mailbox command\n");
9926 		return -ENOMEM;
9927 	}
9928 
9929 	lpfc_read_config(phba, pmb);
9930 
9931 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
9932 	if (rc != MBX_SUCCESS) {
9933 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9934 				"2012 Mailbox failed , mbxCmd x%x "
9935 				"READ_CONFIG, mbxStatus x%x\n",
9936 				bf_get(lpfc_mqe_command, &pmb->u.mqe),
9937 				bf_get(lpfc_mqe_status, &pmb->u.mqe));
9938 		rc = -EIO;
9939 	} else {
9940 		rd_config = &pmb->u.mqe.un.rd_config;
9941 		if (bf_get(lpfc_mbx_rd_conf_lnk_ldv, rd_config)) {
9942 			phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL;
9943 			phba->sli4_hba.lnk_info.lnk_tp =
9944 				bf_get(lpfc_mbx_rd_conf_lnk_type, rd_config);
9945 			phba->sli4_hba.lnk_info.lnk_no =
9946 				bf_get(lpfc_mbx_rd_conf_lnk_numb, rd_config);
9947 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9948 					"3081 lnk_type:%d, lnk_numb:%d\n",
9949 					phba->sli4_hba.lnk_info.lnk_tp,
9950 					phba->sli4_hba.lnk_info.lnk_no);
9951 		} else
9952 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9953 					"3082 Mailbox (x%x) returned ldv:x0\n",
9954 					bf_get(lpfc_mqe_command, &pmb->u.mqe));
9955 		if (bf_get(lpfc_mbx_rd_conf_bbscn_def, rd_config)) {
9956 			phba->bbcredit_support = 1;
9957 			phba->sli4_hba.bbscn_params.word0 = rd_config->word8;
9958 		}
9959 
9960 		fawwpn = bf_get(lpfc_mbx_rd_conf_fawwpn, rd_config);
9961 
9962 		if (fawwpn) {
9963 			lpfc_printf_log(phba, KERN_INFO,
9964 					LOG_INIT | LOG_DISCOVERY,
9965 					"2702 READ_CONFIG: FA-PWWN is "
9966 					"configured on\n");
9967 			phba->sli4_hba.fawwpn_flag |= LPFC_FAWWPN_CONFIG;
9968 		} else {
9969 			/* Clear FW configured flag, preserve driver flag */
9970 			phba->sli4_hba.fawwpn_flag &= ~LPFC_FAWWPN_CONFIG;
9971 		}
9972 
9973 		phba->sli4_hba.conf_trunk =
9974 			bf_get(lpfc_mbx_rd_conf_trunk, rd_config);
9975 		phba->sli4_hba.extents_in_use =
9976 			bf_get(lpfc_mbx_rd_conf_extnts_inuse, rd_config);
9977 
9978 		phba->sli4_hba.max_cfg_param.max_xri =
9979 			bf_get(lpfc_mbx_rd_conf_xri_count, rd_config);
9980 		/* Reduce resource usage in kdump environment */
9981 		if (is_kdump_kernel() &&
9982 		    phba->sli4_hba.max_cfg_param.max_xri > 512)
9983 			phba->sli4_hba.max_cfg_param.max_xri = 512;
9984 		phba->sli4_hba.max_cfg_param.xri_base =
9985 			bf_get(lpfc_mbx_rd_conf_xri_base, rd_config);
9986 		phba->sli4_hba.max_cfg_param.max_vpi =
9987 			bf_get(lpfc_mbx_rd_conf_vpi_count, rd_config);
9988 		/* Limit the max we support */
9989 		if (phba->sli4_hba.max_cfg_param.max_vpi > LPFC_MAX_VPORTS)
9990 			phba->sli4_hba.max_cfg_param.max_vpi = LPFC_MAX_VPORTS;
9991 		phba->sli4_hba.max_cfg_param.vpi_base =
9992 			bf_get(lpfc_mbx_rd_conf_vpi_base, rd_config);
9993 		phba->sli4_hba.max_cfg_param.max_rpi =
9994 			bf_get(lpfc_mbx_rd_conf_rpi_count, rd_config);
9995 		phba->sli4_hba.max_cfg_param.rpi_base =
9996 			bf_get(lpfc_mbx_rd_conf_rpi_base, rd_config);
9997 		phba->sli4_hba.max_cfg_param.max_vfi =
9998 			bf_get(lpfc_mbx_rd_conf_vfi_count, rd_config);
9999 		phba->sli4_hba.max_cfg_param.vfi_base =
10000 			bf_get(lpfc_mbx_rd_conf_vfi_base, rd_config);
10001 		phba->sli4_hba.max_cfg_param.max_fcfi =
10002 			bf_get(lpfc_mbx_rd_conf_fcfi_count, rd_config);
10003 		phba->sli4_hba.max_cfg_param.max_eq =
10004 			bf_get(lpfc_mbx_rd_conf_eq_count, rd_config);
10005 		phba->sli4_hba.max_cfg_param.max_rq =
10006 			bf_get(lpfc_mbx_rd_conf_rq_count, rd_config);
10007 		phba->sli4_hba.max_cfg_param.max_wq =
10008 			bf_get(lpfc_mbx_rd_conf_wq_count, rd_config);
10009 		phba->sli4_hba.max_cfg_param.max_cq =
10010 			bf_get(lpfc_mbx_rd_conf_cq_count, rd_config);
10011 		phba->lmt = bf_get(lpfc_mbx_rd_conf_lmt, rd_config);
10012 		phba->sli4_hba.next_xri = phba->sli4_hba.max_cfg_param.xri_base;
10013 		phba->vpi_base = phba->sli4_hba.max_cfg_param.vpi_base;
10014 		phba->vfi_base = phba->sli4_hba.max_cfg_param.vfi_base;
10015 		phba->max_vpi = (phba->sli4_hba.max_cfg_param.max_vpi > 0) ?
10016 				(phba->sli4_hba.max_cfg_param.max_vpi - 1) : 0;
10017 		phba->max_vports = phba->max_vpi;
10018 
10019 		/* Next decide on FPIN or Signal E2E CGN support
10020 		 * For congestion alarms and warnings valid combination are:
10021 		 * 1. FPIN alarms / FPIN warnings
10022 		 * 2. Signal alarms / Signal warnings
10023 		 * 3. FPIN alarms / Signal warnings
10024 		 * 4. Signal alarms / FPIN warnings
10025 		 *
10026 		 * Initialize the adapter frequency to 100 mSecs
10027 		 */
10028 		phba->cgn_reg_fpin = LPFC_CGN_FPIN_BOTH;
10029 		phba->cgn_reg_signal = EDC_CG_SIG_NOTSUPPORTED;
10030 		phba->cgn_sig_freq = lpfc_fabric_cgn_frequency;
10031 
10032 		if (lpfc_use_cgn_signal) {
10033 			if (bf_get(lpfc_mbx_rd_conf_wcs, rd_config)) {
10034 				phba->cgn_reg_signal = EDC_CG_SIG_WARN_ONLY;
10035 				phba->cgn_reg_fpin &= ~LPFC_CGN_FPIN_WARN;
10036 			}
10037 			if (bf_get(lpfc_mbx_rd_conf_acs, rd_config)) {
10038 				/* MUST support both alarm and warning
10039 				 * because EDC does not support alarm alone.
10040 				 */
10041 				if (phba->cgn_reg_signal !=
10042 				    EDC_CG_SIG_WARN_ONLY) {
10043 					/* Must support both or none */
10044 					phba->cgn_reg_fpin = LPFC_CGN_FPIN_BOTH;
10045 					phba->cgn_reg_signal =
10046 						EDC_CG_SIG_NOTSUPPORTED;
10047 				} else {
10048 					phba->cgn_reg_signal =
10049 						EDC_CG_SIG_WARN_ALARM;
10050 					phba->cgn_reg_fpin =
10051 						LPFC_CGN_FPIN_NONE;
10052 				}
10053 			}
10054 		}
10055 
10056 		/* Set the congestion initial signal and fpin values. */
10057 		phba->cgn_init_reg_fpin = phba->cgn_reg_fpin;
10058 		phba->cgn_init_reg_signal = phba->cgn_reg_signal;
10059 
10060 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
10061 				"6446 READ_CONFIG reg_sig x%x reg_fpin:x%x\n",
10062 				phba->cgn_reg_signal, phba->cgn_reg_fpin);
10063 
10064 		lpfc_map_topology(phba, rd_config);
10065 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10066 				"2003 cfg params Extents? %d "
10067 				"XRI(B:%d M:%d), "
10068 				"VPI(B:%d M:%d) "
10069 				"VFI(B:%d M:%d) "
10070 				"RPI(B:%d M:%d) "
10071 				"FCFI:%d EQ:%d CQ:%d WQ:%d RQ:%d lmt:x%x\n",
10072 				phba->sli4_hba.extents_in_use,
10073 				phba->sli4_hba.max_cfg_param.xri_base,
10074 				phba->sli4_hba.max_cfg_param.max_xri,
10075 				phba->sli4_hba.max_cfg_param.vpi_base,
10076 				phba->sli4_hba.max_cfg_param.max_vpi,
10077 				phba->sli4_hba.max_cfg_param.vfi_base,
10078 				phba->sli4_hba.max_cfg_param.max_vfi,
10079 				phba->sli4_hba.max_cfg_param.rpi_base,
10080 				phba->sli4_hba.max_cfg_param.max_rpi,
10081 				phba->sli4_hba.max_cfg_param.max_fcfi,
10082 				phba->sli4_hba.max_cfg_param.max_eq,
10083 				phba->sli4_hba.max_cfg_param.max_cq,
10084 				phba->sli4_hba.max_cfg_param.max_wq,
10085 				phba->sli4_hba.max_cfg_param.max_rq,
10086 				phba->lmt);
10087 
10088 		/*
10089 		 * Calculate queue resources based on how
10090 		 * many WQ/CQ/EQs are available.
10091 		 */
10092 		qmin = phba->sli4_hba.max_cfg_param.max_wq;
10093 		if (phba->sli4_hba.max_cfg_param.max_cq < qmin)
10094 			qmin = phba->sli4_hba.max_cfg_param.max_cq;
10095 		if (phba->sli4_hba.max_cfg_param.max_eq < qmin)
10096 			qmin = phba->sli4_hba.max_cfg_param.max_eq;
10097 		/*
10098 		 * Whats left after this can go toward NVME / FCP.
10099 		 * The minus 4 accounts for ELS, NVME LS, MBOX
10100 		 * plus one extra. When configured for
10101 		 * NVMET, FCP io channel WQs are not created.
10102 		 */
10103 		qmin -= 4;
10104 
10105 		/* Check to see if there is enough for NVME */
10106 		if ((phba->cfg_irq_chann > qmin) ||
10107 		    (phba->cfg_hdw_queue > qmin)) {
10108 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10109 					"2005 Reducing Queues - "
10110 					"FW resource limitation: "
10111 					"WQ %d CQ %d EQ %d: min %d: "
10112 					"IRQ %d HDWQ %d\n",
10113 					phba->sli4_hba.max_cfg_param.max_wq,
10114 					phba->sli4_hba.max_cfg_param.max_cq,
10115 					phba->sli4_hba.max_cfg_param.max_eq,
10116 					qmin, phba->cfg_irq_chann,
10117 					phba->cfg_hdw_queue);
10118 
10119 			if (phba->cfg_irq_chann > qmin)
10120 				phba->cfg_irq_chann = qmin;
10121 			if (phba->cfg_hdw_queue > qmin)
10122 				phba->cfg_hdw_queue = qmin;
10123 		}
10124 	}
10125 
10126 	if (rc)
10127 		goto read_cfg_out;
10128 
10129 	/* Update link speed if forced link speed is supported */
10130 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
10131 	if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
10132 		forced_link_speed =
10133 			bf_get(lpfc_mbx_rd_conf_link_speed, rd_config);
10134 		if (forced_link_speed) {
10135 			phba->hba_flag |= HBA_FORCED_LINK_SPEED;
10136 
10137 			switch (forced_link_speed) {
10138 			case LINK_SPEED_1G:
10139 				phba->cfg_link_speed =
10140 					LPFC_USER_LINK_SPEED_1G;
10141 				break;
10142 			case LINK_SPEED_2G:
10143 				phba->cfg_link_speed =
10144 					LPFC_USER_LINK_SPEED_2G;
10145 				break;
10146 			case LINK_SPEED_4G:
10147 				phba->cfg_link_speed =
10148 					LPFC_USER_LINK_SPEED_4G;
10149 				break;
10150 			case LINK_SPEED_8G:
10151 				phba->cfg_link_speed =
10152 					LPFC_USER_LINK_SPEED_8G;
10153 				break;
10154 			case LINK_SPEED_10G:
10155 				phba->cfg_link_speed =
10156 					LPFC_USER_LINK_SPEED_10G;
10157 				break;
10158 			case LINK_SPEED_16G:
10159 				phba->cfg_link_speed =
10160 					LPFC_USER_LINK_SPEED_16G;
10161 				break;
10162 			case LINK_SPEED_32G:
10163 				phba->cfg_link_speed =
10164 					LPFC_USER_LINK_SPEED_32G;
10165 				break;
10166 			case LINK_SPEED_64G:
10167 				phba->cfg_link_speed =
10168 					LPFC_USER_LINK_SPEED_64G;
10169 				break;
10170 			case 0xffff:
10171 				phba->cfg_link_speed =
10172 					LPFC_USER_LINK_SPEED_AUTO;
10173 				break;
10174 			default:
10175 				lpfc_printf_log(phba, KERN_ERR,
10176 						LOG_TRACE_EVENT,
10177 						"0047 Unrecognized link "
10178 						"speed : %d\n",
10179 						forced_link_speed);
10180 				phba->cfg_link_speed =
10181 					LPFC_USER_LINK_SPEED_AUTO;
10182 			}
10183 		}
10184 	}
10185 
10186 	/* Reset the DFT_HBA_Q_DEPTH to the max xri  */
10187 	length = phba->sli4_hba.max_cfg_param.max_xri -
10188 			lpfc_sli4_get_els_iocb_cnt(phba);
10189 	if (phba->cfg_hba_queue_depth > length) {
10190 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
10191 				"3361 HBA queue depth changed from %d to %d\n",
10192 				phba->cfg_hba_queue_depth, length);
10193 		phba->cfg_hba_queue_depth = length;
10194 	}
10195 
10196 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) <
10197 	    LPFC_SLI_INTF_IF_TYPE_2)
10198 		goto read_cfg_out;
10199 
10200 	/* get the pf# and vf# for SLI4 if_type 2 port */
10201 	length = (sizeof(struct lpfc_mbx_get_func_cfg) -
10202 		  sizeof(struct lpfc_sli4_cfg_mhdr));
10203 	lpfc_sli4_config(phba, pmb, LPFC_MBOX_SUBSYSTEM_COMMON,
10204 			 LPFC_MBOX_OPCODE_GET_FUNCTION_CONFIG,
10205 			 length, LPFC_SLI4_MBX_EMBED);
10206 
10207 	rc2 = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
10208 	shdr = (union lpfc_sli4_cfg_shdr *)
10209 				&pmb->u.mqe.un.sli4_config.header.cfg_shdr;
10210 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
10211 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
10212 	if (rc2 || shdr_status || shdr_add_status) {
10213 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10214 				"3026 Mailbox failed , mbxCmd x%x "
10215 				"GET_FUNCTION_CONFIG, mbxStatus x%x\n",
10216 				bf_get(lpfc_mqe_command, &pmb->u.mqe),
10217 				bf_get(lpfc_mqe_status, &pmb->u.mqe));
10218 		goto read_cfg_out;
10219 	}
10220 
10221 	/* search for fc_fcoe resrouce descriptor */
10222 	get_func_cfg = &pmb->u.mqe.un.get_func_cfg;
10223 
10224 	pdesc_0 = (char *)&get_func_cfg->func_cfg.desc[0];
10225 	desc = (struct lpfc_rsrc_desc_fcfcoe *)pdesc_0;
10226 	length = bf_get(lpfc_rsrc_desc_fcfcoe_length, desc);
10227 	if (length == LPFC_RSRC_DESC_TYPE_FCFCOE_V0_RSVD)
10228 		length = LPFC_RSRC_DESC_TYPE_FCFCOE_V0_LENGTH;
10229 	else if (length != LPFC_RSRC_DESC_TYPE_FCFCOE_V1_LENGTH)
10230 		goto read_cfg_out;
10231 
10232 	for (i = 0; i < LPFC_RSRC_DESC_MAX_NUM; i++) {
10233 		desc = (struct lpfc_rsrc_desc_fcfcoe *)(pdesc_0 + length * i);
10234 		if (LPFC_RSRC_DESC_TYPE_FCFCOE ==
10235 		    bf_get(lpfc_rsrc_desc_fcfcoe_type, desc)) {
10236 			phba->sli4_hba.iov.pf_number =
10237 				bf_get(lpfc_rsrc_desc_fcfcoe_pfnum, desc);
10238 			phba->sli4_hba.iov.vf_number =
10239 				bf_get(lpfc_rsrc_desc_fcfcoe_vfnum, desc);
10240 			break;
10241 		}
10242 	}
10243 
10244 	if (i < LPFC_RSRC_DESC_MAX_NUM)
10245 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10246 				"3027 GET_FUNCTION_CONFIG: pf_number:%d, "
10247 				"vf_number:%d\n", phba->sli4_hba.iov.pf_number,
10248 				phba->sli4_hba.iov.vf_number);
10249 	else
10250 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10251 				"3028 GET_FUNCTION_CONFIG: failed to find "
10252 				"Resource Descriptor:x%x\n",
10253 				LPFC_RSRC_DESC_TYPE_FCFCOE);
10254 
10255 read_cfg_out:
10256 	mempool_free(pmb, phba->mbox_mem_pool);
10257 	return rc;
10258 }
10259 
10260 /**
10261  * lpfc_setup_endian_order - Write endian order to an SLI4 if_type 0 port.
10262  * @phba: pointer to lpfc hba data structure.
10263  *
10264  * This routine is invoked to setup the port-side endian order when
10265  * the port if_type is 0.  This routine has no function for other
10266  * if_types.
10267  *
10268  * Return codes
10269  * 	0 - successful
10270  * 	-ENOMEM - No available memory
10271  *      -EIO - The mailbox failed to complete successfully.
10272  **/
10273 static int
10274 lpfc_setup_endian_order(struct lpfc_hba *phba)
10275 {
10276 	LPFC_MBOXQ_t *mboxq;
10277 	uint32_t if_type, rc = 0;
10278 	uint32_t endian_mb_data[2] = {HOST_ENDIAN_LOW_WORD0,
10279 				      HOST_ENDIAN_HIGH_WORD1};
10280 
10281 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
10282 	switch (if_type) {
10283 	case LPFC_SLI_INTF_IF_TYPE_0:
10284 		mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
10285 						       GFP_KERNEL);
10286 		if (!mboxq) {
10287 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10288 					"0492 Unable to allocate memory for "
10289 					"issuing SLI_CONFIG_SPECIAL mailbox "
10290 					"command\n");
10291 			return -ENOMEM;
10292 		}
10293 
10294 		/*
10295 		 * The SLI4_CONFIG_SPECIAL mailbox command requires the first
10296 		 * two words to contain special data values and no other data.
10297 		 */
10298 		memset(mboxq, 0, sizeof(LPFC_MBOXQ_t));
10299 		memcpy(&mboxq->u.mqe, &endian_mb_data, sizeof(endian_mb_data));
10300 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
10301 		if (rc != MBX_SUCCESS) {
10302 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10303 					"0493 SLI_CONFIG_SPECIAL mailbox "
10304 					"failed with status x%x\n",
10305 					rc);
10306 			rc = -EIO;
10307 		}
10308 		mempool_free(mboxq, phba->mbox_mem_pool);
10309 		break;
10310 	case LPFC_SLI_INTF_IF_TYPE_6:
10311 	case LPFC_SLI_INTF_IF_TYPE_2:
10312 	case LPFC_SLI_INTF_IF_TYPE_1:
10313 	default:
10314 		break;
10315 	}
10316 	return rc;
10317 }
10318 
10319 /**
10320  * lpfc_sli4_queue_verify - Verify and update EQ counts
10321  * @phba: pointer to lpfc hba data structure.
10322  *
10323  * This routine is invoked to check the user settable queue counts for EQs.
10324  * After this routine is called the counts will be set to valid values that
10325  * adhere to the constraints of the system's interrupt vectors and the port's
10326  * queue resources.
10327  *
10328  * Return codes
10329  *      0 - successful
10330  *      -ENOMEM - No available memory
10331  **/
10332 static int
10333 lpfc_sli4_queue_verify(struct lpfc_hba *phba)
10334 {
10335 	/*
10336 	 * Sanity check for configured queue parameters against the run-time
10337 	 * device parameters
10338 	 */
10339 
10340 	if (phba->nvmet_support) {
10341 		if (phba->cfg_hdw_queue < phba->cfg_nvmet_mrq)
10342 			phba->cfg_nvmet_mrq = phba->cfg_hdw_queue;
10343 		if (phba->cfg_nvmet_mrq > LPFC_NVMET_MRQ_MAX)
10344 			phba->cfg_nvmet_mrq = LPFC_NVMET_MRQ_MAX;
10345 	}
10346 
10347 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10348 			"2574 IO channels: hdwQ %d IRQ %d MRQ: %d\n",
10349 			phba->cfg_hdw_queue, phba->cfg_irq_chann,
10350 			phba->cfg_nvmet_mrq);
10351 
10352 	/* Get EQ depth from module parameter, fake the default for now */
10353 	phba->sli4_hba.eq_esize = LPFC_EQE_SIZE_4B;
10354 	phba->sli4_hba.eq_ecount = LPFC_EQE_DEF_COUNT;
10355 
10356 	/* Get CQ depth from module parameter, fake the default for now */
10357 	phba->sli4_hba.cq_esize = LPFC_CQE_SIZE;
10358 	phba->sli4_hba.cq_ecount = LPFC_CQE_DEF_COUNT;
10359 	return 0;
10360 }
10361 
10362 static int
10363 lpfc_alloc_io_wq_cq(struct lpfc_hba *phba, int idx)
10364 {
10365 	struct lpfc_queue *qdesc;
10366 	u32 wqesize;
10367 	int cpu;
10368 
10369 	cpu = lpfc_find_cpu_handle(phba, idx, LPFC_FIND_BY_HDWQ);
10370 	/* Create Fast Path IO CQs */
10371 	if (phba->enab_exp_wqcq_pages)
10372 		/* Increase the CQ size when WQEs contain an embedded cdb */
10373 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_EXPANDED_PAGE_SIZE,
10374 					      phba->sli4_hba.cq_esize,
10375 					      LPFC_CQE_EXP_COUNT, cpu);
10376 
10377 	else
10378 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10379 					      phba->sli4_hba.cq_esize,
10380 					      phba->sli4_hba.cq_ecount, cpu);
10381 	if (!qdesc) {
10382 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10383 				"0499 Failed allocate fast-path IO CQ (%d)\n",
10384 				idx);
10385 		return 1;
10386 	}
10387 	qdesc->qe_valid = 1;
10388 	qdesc->hdwq = idx;
10389 	qdesc->chann = cpu;
10390 	phba->sli4_hba.hdwq[idx].io_cq = qdesc;
10391 
10392 	/* Create Fast Path IO WQs */
10393 	if (phba->enab_exp_wqcq_pages) {
10394 		/* Increase the WQ size when WQEs contain an embedded cdb */
10395 		wqesize = (phba->fcp_embed_io) ?
10396 			LPFC_WQE128_SIZE : phba->sli4_hba.wq_esize;
10397 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_EXPANDED_PAGE_SIZE,
10398 					      wqesize,
10399 					      LPFC_WQE_EXP_COUNT, cpu);
10400 	} else
10401 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10402 					      phba->sli4_hba.wq_esize,
10403 					      phba->sli4_hba.wq_ecount, cpu);
10404 
10405 	if (!qdesc) {
10406 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10407 				"0503 Failed allocate fast-path IO WQ (%d)\n",
10408 				idx);
10409 		return 1;
10410 	}
10411 	qdesc->hdwq = idx;
10412 	qdesc->chann = cpu;
10413 	phba->sli4_hba.hdwq[idx].io_wq = qdesc;
10414 	list_add_tail(&qdesc->wq_list, &phba->sli4_hba.lpfc_wq_list);
10415 	return 0;
10416 }
10417 
10418 /**
10419  * lpfc_sli4_queue_create - Create all the SLI4 queues
10420  * @phba: pointer to lpfc hba data structure.
10421  *
10422  * This routine is invoked to allocate all the SLI4 queues for the FCoE HBA
10423  * operation. For each SLI4 queue type, the parameters such as queue entry
10424  * count (queue depth) shall be taken from the module parameter. For now,
10425  * we just use some constant number as place holder.
10426  *
10427  * Return codes
10428  *      0 - successful
10429  *      -ENOMEM - No availble memory
10430  *      -EIO - The mailbox failed to complete successfully.
10431  **/
10432 int
10433 lpfc_sli4_queue_create(struct lpfc_hba *phba)
10434 {
10435 	struct lpfc_queue *qdesc;
10436 	int idx, cpu, eqcpu;
10437 	struct lpfc_sli4_hdw_queue *qp;
10438 	struct lpfc_vector_map_info *cpup;
10439 	struct lpfc_vector_map_info *eqcpup;
10440 	struct lpfc_eq_intr_info *eqi;
10441 
10442 	/*
10443 	 * Create HBA Record arrays.
10444 	 * Both NVME and FCP will share that same vectors / EQs
10445 	 */
10446 	phba->sli4_hba.mq_esize = LPFC_MQE_SIZE;
10447 	phba->sli4_hba.mq_ecount = LPFC_MQE_DEF_COUNT;
10448 	phba->sli4_hba.wq_esize = LPFC_WQE_SIZE;
10449 	phba->sli4_hba.wq_ecount = LPFC_WQE_DEF_COUNT;
10450 	phba->sli4_hba.rq_esize = LPFC_RQE_SIZE;
10451 	phba->sli4_hba.rq_ecount = LPFC_RQE_DEF_COUNT;
10452 	phba->sli4_hba.eq_esize = LPFC_EQE_SIZE_4B;
10453 	phba->sli4_hba.eq_ecount = LPFC_EQE_DEF_COUNT;
10454 	phba->sli4_hba.cq_esize = LPFC_CQE_SIZE;
10455 	phba->sli4_hba.cq_ecount = LPFC_CQE_DEF_COUNT;
10456 
10457 	if (!phba->sli4_hba.hdwq) {
10458 		phba->sli4_hba.hdwq = kcalloc(
10459 			phba->cfg_hdw_queue, sizeof(struct lpfc_sli4_hdw_queue),
10460 			GFP_KERNEL);
10461 		if (!phba->sli4_hba.hdwq) {
10462 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10463 					"6427 Failed allocate memory for "
10464 					"fast-path Hardware Queue array\n");
10465 			goto out_error;
10466 		}
10467 		/* Prepare hardware queues to take IO buffers */
10468 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10469 			qp = &phba->sli4_hba.hdwq[idx];
10470 			spin_lock_init(&qp->io_buf_list_get_lock);
10471 			spin_lock_init(&qp->io_buf_list_put_lock);
10472 			INIT_LIST_HEAD(&qp->lpfc_io_buf_list_get);
10473 			INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
10474 			qp->get_io_bufs = 0;
10475 			qp->put_io_bufs = 0;
10476 			qp->total_io_bufs = 0;
10477 			spin_lock_init(&qp->abts_io_buf_list_lock);
10478 			INIT_LIST_HEAD(&qp->lpfc_abts_io_buf_list);
10479 			qp->abts_scsi_io_bufs = 0;
10480 			qp->abts_nvme_io_bufs = 0;
10481 			INIT_LIST_HEAD(&qp->sgl_list);
10482 			INIT_LIST_HEAD(&qp->cmd_rsp_buf_list);
10483 			spin_lock_init(&qp->hdwq_lock);
10484 		}
10485 	}
10486 
10487 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
10488 		if (phba->nvmet_support) {
10489 			phba->sli4_hba.nvmet_cqset = kcalloc(
10490 					phba->cfg_nvmet_mrq,
10491 					sizeof(struct lpfc_queue *),
10492 					GFP_KERNEL);
10493 			if (!phba->sli4_hba.nvmet_cqset) {
10494 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10495 					"3121 Fail allocate memory for "
10496 					"fast-path CQ set array\n");
10497 				goto out_error;
10498 			}
10499 			phba->sli4_hba.nvmet_mrq_hdr = kcalloc(
10500 					phba->cfg_nvmet_mrq,
10501 					sizeof(struct lpfc_queue *),
10502 					GFP_KERNEL);
10503 			if (!phba->sli4_hba.nvmet_mrq_hdr) {
10504 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10505 					"3122 Fail allocate memory for "
10506 					"fast-path RQ set hdr array\n");
10507 				goto out_error;
10508 			}
10509 			phba->sli4_hba.nvmet_mrq_data = kcalloc(
10510 					phba->cfg_nvmet_mrq,
10511 					sizeof(struct lpfc_queue *),
10512 					GFP_KERNEL);
10513 			if (!phba->sli4_hba.nvmet_mrq_data) {
10514 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10515 					"3124 Fail allocate memory for "
10516 					"fast-path RQ set data array\n");
10517 				goto out_error;
10518 			}
10519 		}
10520 	}
10521 
10522 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_wq_list);
10523 
10524 	/* Create HBA Event Queues (EQs) */
10525 	for_each_present_cpu(cpu) {
10526 		/* We only want to create 1 EQ per vector, even though
10527 		 * multiple CPUs might be using that vector. so only
10528 		 * selects the CPUs that are LPFC_CPU_FIRST_IRQ.
10529 		 */
10530 		cpup = &phba->sli4_hba.cpu_map[cpu];
10531 		if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
10532 			continue;
10533 
10534 		/* Get a ptr to the Hardware Queue associated with this CPU */
10535 		qp = &phba->sli4_hba.hdwq[cpup->hdwq];
10536 
10537 		/* Allocate an EQ */
10538 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10539 					      phba->sli4_hba.eq_esize,
10540 					      phba->sli4_hba.eq_ecount, cpu);
10541 		if (!qdesc) {
10542 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10543 					"0497 Failed allocate EQ (%d)\n",
10544 					cpup->hdwq);
10545 			goto out_error;
10546 		}
10547 		qdesc->qe_valid = 1;
10548 		qdesc->hdwq = cpup->hdwq;
10549 		qdesc->chann = cpu; /* First CPU this EQ is affinitized to */
10550 		qdesc->last_cpu = qdesc->chann;
10551 
10552 		/* Save the allocated EQ in the Hardware Queue */
10553 		qp->hba_eq = qdesc;
10554 
10555 		eqi = per_cpu_ptr(phba->sli4_hba.eq_info, qdesc->last_cpu);
10556 		list_add(&qdesc->cpu_list, &eqi->list);
10557 	}
10558 
10559 	/* Now we need to populate the other Hardware Queues, that share
10560 	 * an IRQ vector, with the associated EQ ptr.
10561 	 */
10562 	for_each_present_cpu(cpu) {
10563 		cpup = &phba->sli4_hba.cpu_map[cpu];
10564 
10565 		/* Check for EQ already allocated in previous loop */
10566 		if (cpup->flag & LPFC_CPU_FIRST_IRQ)
10567 			continue;
10568 
10569 		/* Check for multiple CPUs per hdwq */
10570 		qp = &phba->sli4_hba.hdwq[cpup->hdwq];
10571 		if (qp->hba_eq)
10572 			continue;
10573 
10574 		/* We need to share an EQ for this hdwq */
10575 		eqcpu = lpfc_find_cpu_handle(phba, cpup->eq, LPFC_FIND_BY_EQ);
10576 		eqcpup = &phba->sli4_hba.cpu_map[eqcpu];
10577 		qp->hba_eq = phba->sli4_hba.hdwq[eqcpup->hdwq].hba_eq;
10578 	}
10579 
10580 	/* Allocate IO Path SLI4 CQ/WQs */
10581 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10582 		if (lpfc_alloc_io_wq_cq(phba, idx))
10583 			goto out_error;
10584 	}
10585 
10586 	if (phba->nvmet_support) {
10587 		for (idx = 0; idx < phba->cfg_nvmet_mrq; idx++) {
10588 			cpu = lpfc_find_cpu_handle(phba, idx,
10589 						   LPFC_FIND_BY_HDWQ);
10590 			qdesc = lpfc_sli4_queue_alloc(phba,
10591 						      LPFC_DEFAULT_PAGE_SIZE,
10592 						      phba->sli4_hba.cq_esize,
10593 						      phba->sli4_hba.cq_ecount,
10594 						      cpu);
10595 			if (!qdesc) {
10596 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10597 						"3142 Failed allocate NVME "
10598 						"CQ Set (%d)\n", idx);
10599 				goto out_error;
10600 			}
10601 			qdesc->qe_valid = 1;
10602 			qdesc->hdwq = idx;
10603 			qdesc->chann = cpu;
10604 			phba->sli4_hba.nvmet_cqset[idx] = qdesc;
10605 		}
10606 	}
10607 
10608 	/*
10609 	 * Create Slow Path Completion Queues (CQs)
10610 	 */
10611 
10612 	cpu = lpfc_find_cpu_handle(phba, 0, LPFC_FIND_BY_EQ);
10613 	/* Create slow-path Mailbox Command Complete Queue */
10614 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10615 				      phba->sli4_hba.cq_esize,
10616 				      phba->sli4_hba.cq_ecount, cpu);
10617 	if (!qdesc) {
10618 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10619 				"0500 Failed allocate slow-path mailbox CQ\n");
10620 		goto out_error;
10621 	}
10622 	qdesc->qe_valid = 1;
10623 	phba->sli4_hba.mbx_cq = qdesc;
10624 
10625 	/* Create slow-path ELS Complete Queue */
10626 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10627 				      phba->sli4_hba.cq_esize,
10628 				      phba->sli4_hba.cq_ecount, cpu);
10629 	if (!qdesc) {
10630 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10631 				"0501 Failed allocate slow-path ELS CQ\n");
10632 		goto out_error;
10633 	}
10634 	qdesc->qe_valid = 1;
10635 	qdesc->chann = cpu;
10636 	phba->sli4_hba.els_cq = qdesc;
10637 
10638 
10639 	/*
10640 	 * Create Slow Path Work Queues (WQs)
10641 	 */
10642 
10643 	/* Create Mailbox Command Queue */
10644 
10645 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10646 				      phba->sli4_hba.mq_esize,
10647 				      phba->sli4_hba.mq_ecount, cpu);
10648 	if (!qdesc) {
10649 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10650 				"0505 Failed allocate slow-path MQ\n");
10651 		goto out_error;
10652 	}
10653 	qdesc->chann = cpu;
10654 	phba->sli4_hba.mbx_wq = qdesc;
10655 
10656 	/*
10657 	 * Create ELS Work Queues
10658 	 */
10659 
10660 	/* Create slow-path ELS Work Queue */
10661 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10662 				      phba->sli4_hba.wq_esize,
10663 				      phba->sli4_hba.wq_ecount, cpu);
10664 	if (!qdesc) {
10665 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10666 				"0504 Failed allocate slow-path ELS WQ\n");
10667 		goto out_error;
10668 	}
10669 	qdesc->chann = cpu;
10670 	phba->sli4_hba.els_wq = qdesc;
10671 	list_add_tail(&qdesc->wq_list, &phba->sli4_hba.lpfc_wq_list);
10672 
10673 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
10674 		/* Create NVME LS Complete Queue */
10675 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10676 					      phba->sli4_hba.cq_esize,
10677 					      phba->sli4_hba.cq_ecount, cpu);
10678 		if (!qdesc) {
10679 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10680 					"6079 Failed allocate NVME LS CQ\n");
10681 			goto out_error;
10682 		}
10683 		qdesc->chann = cpu;
10684 		qdesc->qe_valid = 1;
10685 		phba->sli4_hba.nvmels_cq = qdesc;
10686 
10687 		/* Create NVME LS Work Queue */
10688 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10689 					      phba->sli4_hba.wq_esize,
10690 					      phba->sli4_hba.wq_ecount, cpu);
10691 		if (!qdesc) {
10692 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10693 					"6080 Failed allocate NVME LS WQ\n");
10694 			goto out_error;
10695 		}
10696 		qdesc->chann = cpu;
10697 		phba->sli4_hba.nvmels_wq = qdesc;
10698 		list_add_tail(&qdesc->wq_list, &phba->sli4_hba.lpfc_wq_list);
10699 	}
10700 
10701 	/*
10702 	 * Create Receive Queue (RQ)
10703 	 */
10704 
10705 	/* Create Receive Queue for header */
10706 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10707 				      phba->sli4_hba.rq_esize,
10708 				      phba->sli4_hba.rq_ecount, cpu);
10709 	if (!qdesc) {
10710 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10711 				"0506 Failed allocate receive HRQ\n");
10712 		goto out_error;
10713 	}
10714 	phba->sli4_hba.hdr_rq = qdesc;
10715 
10716 	/* Create Receive Queue for data */
10717 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10718 				      phba->sli4_hba.rq_esize,
10719 				      phba->sli4_hba.rq_ecount, cpu);
10720 	if (!qdesc) {
10721 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10722 				"0507 Failed allocate receive DRQ\n");
10723 		goto out_error;
10724 	}
10725 	phba->sli4_hba.dat_rq = qdesc;
10726 
10727 	if ((phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) &&
10728 	    phba->nvmet_support) {
10729 		for (idx = 0; idx < phba->cfg_nvmet_mrq; idx++) {
10730 			cpu = lpfc_find_cpu_handle(phba, idx,
10731 						   LPFC_FIND_BY_HDWQ);
10732 			/* Create NVMET Receive Queue for header */
10733 			qdesc = lpfc_sli4_queue_alloc(phba,
10734 						      LPFC_DEFAULT_PAGE_SIZE,
10735 						      phba->sli4_hba.rq_esize,
10736 						      LPFC_NVMET_RQE_DEF_COUNT,
10737 						      cpu);
10738 			if (!qdesc) {
10739 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10740 						"3146 Failed allocate "
10741 						"receive HRQ\n");
10742 				goto out_error;
10743 			}
10744 			qdesc->hdwq = idx;
10745 			phba->sli4_hba.nvmet_mrq_hdr[idx] = qdesc;
10746 
10747 			/* Only needed for header of RQ pair */
10748 			qdesc->rqbp = kzalloc_node(sizeof(*qdesc->rqbp),
10749 						   GFP_KERNEL,
10750 						   cpu_to_node(cpu));
10751 			if (qdesc->rqbp == NULL) {
10752 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10753 						"6131 Failed allocate "
10754 						"Header RQBP\n");
10755 				goto out_error;
10756 			}
10757 
10758 			/* Put list in known state in case driver load fails. */
10759 			INIT_LIST_HEAD(&qdesc->rqbp->rqb_buffer_list);
10760 
10761 			/* Create NVMET Receive Queue for data */
10762 			qdesc = lpfc_sli4_queue_alloc(phba,
10763 						      LPFC_DEFAULT_PAGE_SIZE,
10764 						      phba->sli4_hba.rq_esize,
10765 						      LPFC_NVMET_RQE_DEF_COUNT,
10766 						      cpu);
10767 			if (!qdesc) {
10768 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10769 						"3156 Failed allocate "
10770 						"receive DRQ\n");
10771 				goto out_error;
10772 			}
10773 			qdesc->hdwq = idx;
10774 			phba->sli4_hba.nvmet_mrq_data[idx] = qdesc;
10775 		}
10776 	}
10777 
10778 	/* Clear NVME stats */
10779 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
10780 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10781 			memset(&phba->sli4_hba.hdwq[idx].nvme_cstat, 0,
10782 			       sizeof(phba->sli4_hba.hdwq[idx].nvme_cstat));
10783 		}
10784 	}
10785 
10786 	/* Clear SCSI stats */
10787 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP) {
10788 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10789 			memset(&phba->sli4_hba.hdwq[idx].scsi_cstat, 0,
10790 			       sizeof(phba->sli4_hba.hdwq[idx].scsi_cstat));
10791 		}
10792 	}
10793 
10794 	return 0;
10795 
10796 out_error:
10797 	lpfc_sli4_queue_destroy(phba);
10798 	return -ENOMEM;
10799 }
10800 
10801 static inline void
10802 __lpfc_sli4_release_queue(struct lpfc_queue **qp)
10803 {
10804 	if (*qp != NULL) {
10805 		lpfc_sli4_queue_free(*qp);
10806 		*qp = NULL;
10807 	}
10808 }
10809 
10810 static inline void
10811 lpfc_sli4_release_queues(struct lpfc_queue ***qs, int max)
10812 {
10813 	int idx;
10814 
10815 	if (*qs == NULL)
10816 		return;
10817 
10818 	for (idx = 0; idx < max; idx++)
10819 		__lpfc_sli4_release_queue(&(*qs)[idx]);
10820 
10821 	kfree(*qs);
10822 	*qs = NULL;
10823 }
10824 
10825 static inline void
10826 lpfc_sli4_release_hdwq(struct lpfc_hba *phba)
10827 {
10828 	struct lpfc_sli4_hdw_queue *hdwq;
10829 	struct lpfc_queue *eq;
10830 	uint32_t idx;
10831 
10832 	hdwq = phba->sli4_hba.hdwq;
10833 
10834 	/* Loop thru all Hardware Queues */
10835 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10836 		/* Free the CQ/WQ corresponding to the Hardware Queue */
10837 		lpfc_sli4_queue_free(hdwq[idx].io_cq);
10838 		lpfc_sli4_queue_free(hdwq[idx].io_wq);
10839 		hdwq[idx].hba_eq = NULL;
10840 		hdwq[idx].io_cq = NULL;
10841 		hdwq[idx].io_wq = NULL;
10842 		if (phba->cfg_xpsgl && !phba->nvmet_support)
10843 			lpfc_free_sgl_per_hdwq(phba, &hdwq[idx]);
10844 		lpfc_free_cmd_rsp_buf_per_hdwq(phba, &hdwq[idx]);
10845 	}
10846 	/* Loop thru all IRQ vectors */
10847 	for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
10848 		/* Free the EQ corresponding to the IRQ vector */
10849 		eq = phba->sli4_hba.hba_eq_hdl[idx].eq;
10850 		lpfc_sli4_queue_free(eq);
10851 		phba->sli4_hba.hba_eq_hdl[idx].eq = NULL;
10852 	}
10853 }
10854 
10855 /**
10856  * lpfc_sli4_queue_destroy - Destroy all the SLI4 queues
10857  * @phba: pointer to lpfc hba data structure.
10858  *
10859  * This routine is invoked to release all the SLI4 queues with the FCoE HBA
10860  * operation.
10861  *
10862  * Return codes
10863  *      0 - successful
10864  *      -ENOMEM - No available memory
10865  *      -EIO - The mailbox failed to complete successfully.
10866  **/
10867 void
10868 lpfc_sli4_queue_destroy(struct lpfc_hba *phba)
10869 {
10870 	/*
10871 	 * Set FREE_INIT before beginning to free the queues.
10872 	 * Wait until the users of queues to acknowledge to
10873 	 * release queues by clearing FREE_WAIT.
10874 	 */
10875 	spin_lock_irq(&phba->hbalock);
10876 	phba->sli.sli_flag |= LPFC_QUEUE_FREE_INIT;
10877 	while (phba->sli.sli_flag & LPFC_QUEUE_FREE_WAIT) {
10878 		spin_unlock_irq(&phba->hbalock);
10879 		msleep(20);
10880 		spin_lock_irq(&phba->hbalock);
10881 	}
10882 	spin_unlock_irq(&phba->hbalock);
10883 
10884 	lpfc_sli4_cleanup_poll_list(phba);
10885 
10886 	/* Release HBA eqs */
10887 	if (phba->sli4_hba.hdwq)
10888 		lpfc_sli4_release_hdwq(phba);
10889 
10890 	if (phba->nvmet_support) {
10891 		lpfc_sli4_release_queues(&phba->sli4_hba.nvmet_cqset,
10892 					 phba->cfg_nvmet_mrq);
10893 
10894 		lpfc_sli4_release_queues(&phba->sli4_hba.nvmet_mrq_hdr,
10895 					 phba->cfg_nvmet_mrq);
10896 		lpfc_sli4_release_queues(&phba->sli4_hba.nvmet_mrq_data,
10897 					 phba->cfg_nvmet_mrq);
10898 	}
10899 
10900 	/* Release mailbox command work queue */
10901 	__lpfc_sli4_release_queue(&phba->sli4_hba.mbx_wq);
10902 
10903 	/* Release ELS work queue */
10904 	__lpfc_sli4_release_queue(&phba->sli4_hba.els_wq);
10905 
10906 	/* Release ELS work queue */
10907 	__lpfc_sli4_release_queue(&phba->sli4_hba.nvmels_wq);
10908 
10909 	/* Release unsolicited receive queue */
10910 	__lpfc_sli4_release_queue(&phba->sli4_hba.hdr_rq);
10911 	__lpfc_sli4_release_queue(&phba->sli4_hba.dat_rq);
10912 
10913 	/* Release ELS complete queue */
10914 	__lpfc_sli4_release_queue(&phba->sli4_hba.els_cq);
10915 
10916 	/* Release NVME LS complete queue */
10917 	__lpfc_sli4_release_queue(&phba->sli4_hba.nvmels_cq);
10918 
10919 	/* Release mailbox command complete queue */
10920 	__lpfc_sli4_release_queue(&phba->sli4_hba.mbx_cq);
10921 
10922 	/* Everything on this list has been freed */
10923 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_wq_list);
10924 
10925 	/* Done with freeing the queues */
10926 	spin_lock_irq(&phba->hbalock);
10927 	phba->sli.sli_flag &= ~LPFC_QUEUE_FREE_INIT;
10928 	spin_unlock_irq(&phba->hbalock);
10929 }
10930 
10931 int
10932 lpfc_free_rq_buffer(struct lpfc_hba *phba, struct lpfc_queue *rq)
10933 {
10934 	struct lpfc_rqb *rqbp;
10935 	struct lpfc_dmabuf *h_buf;
10936 	struct rqb_dmabuf *rqb_buffer;
10937 
10938 	rqbp = rq->rqbp;
10939 	while (!list_empty(&rqbp->rqb_buffer_list)) {
10940 		list_remove_head(&rqbp->rqb_buffer_list, h_buf,
10941 				 struct lpfc_dmabuf, list);
10942 
10943 		rqb_buffer = container_of(h_buf, struct rqb_dmabuf, hbuf);
10944 		(rqbp->rqb_free_buffer)(phba, rqb_buffer);
10945 		rqbp->buffer_count--;
10946 	}
10947 	return 1;
10948 }
10949 
10950 static int
10951 lpfc_create_wq_cq(struct lpfc_hba *phba, struct lpfc_queue *eq,
10952 	struct lpfc_queue *cq, struct lpfc_queue *wq, uint16_t *cq_map,
10953 	int qidx, uint32_t qtype)
10954 {
10955 	struct lpfc_sli_ring *pring;
10956 	int rc;
10957 
10958 	if (!eq || !cq || !wq) {
10959 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10960 			"6085 Fast-path %s (%d) not allocated\n",
10961 			((eq) ? ((cq) ? "WQ" : "CQ") : "EQ"), qidx);
10962 		return -ENOMEM;
10963 	}
10964 
10965 	/* create the Cq first */
10966 	rc = lpfc_cq_create(phba, cq, eq,
10967 			(qtype == LPFC_MBOX) ? LPFC_MCQ : LPFC_WCQ, qtype);
10968 	if (rc) {
10969 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10970 				"6086 Failed setup of CQ (%d), rc = 0x%x\n",
10971 				qidx, (uint32_t)rc);
10972 		return rc;
10973 	}
10974 
10975 	if (qtype != LPFC_MBOX) {
10976 		/* Setup cq_map for fast lookup */
10977 		if (cq_map)
10978 			*cq_map = cq->queue_id;
10979 
10980 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
10981 			"6087 CQ setup: cq[%d]-id=%d, parent eq[%d]-id=%d\n",
10982 			qidx, cq->queue_id, qidx, eq->queue_id);
10983 
10984 		/* create the wq */
10985 		rc = lpfc_wq_create(phba, wq, cq, qtype);
10986 		if (rc) {
10987 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10988 				"4618 Fail setup fastpath WQ (%d), rc = 0x%x\n",
10989 				qidx, (uint32_t)rc);
10990 			/* no need to tear down cq - caller will do so */
10991 			return rc;
10992 		}
10993 
10994 		/* Bind this CQ/WQ to the NVME ring */
10995 		pring = wq->pring;
10996 		pring->sli.sli4.wqp = (void *)wq;
10997 		cq->pring = pring;
10998 
10999 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11000 			"2593 WQ setup: wq[%d]-id=%d assoc=%d, cq[%d]-id=%d\n",
11001 			qidx, wq->queue_id, wq->assoc_qid, qidx, cq->queue_id);
11002 	} else {
11003 		rc = lpfc_mq_create(phba, wq, cq, LPFC_MBOX);
11004 		if (rc) {
11005 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11006 					"0539 Failed setup of slow-path MQ: "
11007 					"rc = 0x%x\n", rc);
11008 			/* no need to tear down cq - caller will do so */
11009 			return rc;
11010 		}
11011 
11012 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11013 			"2589 MBX MQ setup: wq-id=%d, parent cq-id=%d\n",
11014 			phba->sli4_hba.mbx_wq->queue_id,
11015 			phba->sli4_hba.mbx_cq->queue_id);
11016 	}
11017 
11018 	return 0;
11019 }
11020 
11021 /**
11022  * lpfc_setup_cq_lookup - Setup the CQ lookup table
11023  * @phba: pointer to lpfc hba data structure.
11024  *
11025  * This routine will populate the cq_lookup table by all
11026  * available CQ queue_id's.
11027  **/
11028 static void
11029 lpfc_setup_cq_lookup(struct lpfc_hba *phba)
11030 {
11031 	struct lpfc_queue *eq, *childq;
11032 	int qidx;
11033 
11034 	memset(phba->sli4_hba.cq_lookup, 0,
11035 	       (sizeof(struct lpfc_queue *) * (phba->sli4_hba.cq_max + 1)));
11036 	/* Loop thru all IRQ vectors */
11037 	for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
11038 		/* Get the EQ corresponding to the IRQ vector */
11039 		eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
11040 		if (!eq)
11041 			continue;
11042 		/* Loop through all CQs associated with that EQ */
11043 		list_for_each_entry(childq, &eq->child_list, list) {
11044 			if (childq->queue_id > phba->sli4_hba.cq_max)
11045 				continue;
11046 			if (childq->subtype == LPFC_IO)
11047 				phba->sli4_hba.cq_lookup[childq->queue_id] =
11048 					childq;
11049 		}
11050 	}
11051 }
11052 
11053 /**
11054  * lpfc_sli4_queue_setup - Set up all the SLI4 queues
11055  * @phba: pointer to lpfc hba data structure.
11056  *
11057  * This routine is invoked to set up all the SLI4 queues for the FCoE HBA
11058  * operation.
11059  *
11060  * Return codes
11061  *      0 - successful
11062  *      -ENOMEM - No available memory
11063  *      -EIO - The mailbox failed to complete successfully.
11064  **/
11065 int
11066 lpfc_sli4_queue_setup(struct lpfc_hba *phba)
11067 {
11068 	uint32_t shdr_status, shdr_add_status;
11069 	union lpfc_sli4_cfg_shdr *shdr;
11070 	struct lpfc_vector_map_info *cpup;
11071 	struct lpfc_sli4_hdw_queue *qp;
11072 	LPFC_MBOXQ_t *mboxq;
11073 	int qidx, cpu;
11074 	uint32_t length, usdelay;
11075 	int rc = -ENOMEM;
11076 
11077 	/* Check for dual-ULP support */
11078 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
11079 	if (!mboxq) {
11080 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11081 				"3249 Unable to allocate memory for "
11082 				"QUERY_FW_CFG mailbox command\n");
11083 		return -ENOMEM;
11084 	}
11085 	length = (sizeof(struct lpfc_mbx_query_fw_config) -
11086 		  sizeof(struct lpfc_sli4_cfg_mhdr));
11087 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
11088 			 LPFC_MBOX_OPCODE_QUERY_FW_CFG,
11089 			 length, LPFC_SLI4_MBX_EMBED);
11090 
11091 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
11092 
11093 	shdr = (union lpfc_sli4_cfg_shdr *)
11094 			&mboxq->u.mqe.un.sli4_config.header.cfg_shdr;
11095 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
11096 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
11097 	if (shdr_status || shdr_add_status || rc) {
11098 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11099 				"3250 QUERY_FW_CFG mailbox failed with status "
11100 				"x%x add_status x%x, mbx status x%x\n",
11101 				shdr_status, shdr_add_status, rc);
11102 		mempool_free(mboxq, phba->mbox_mem_pool);
11103 		rc = -ENXIO;
11104 		goto out_error;
11105 	}
11106 
11107 	phba->sli4_hba.fw_func_mode =
11108 			mboxq->u.mqe.un.query_fw_cfg.rsp.function_mode;
11109 	phba->sli4_hba.ulp0_mode = mboxq->u.mqe.un.query_fw_cfg.rsp.ulp0_mode;
11110 	phba->sli4_hba.ulp1_mode = mboxq->u.mqe.un.query_fw_cfg.rsp.ulp1_mode;
11111 	phba->sli4_hba.physical_port =
11112 			mboxq->u.mqe.un.query_fw_cfg.rsp.physical_port;
11113 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11114 			"3251 QUERY_FW_CFG: func_mode:x%x, ulp0_mode:x%x, "
11115 			"ulp1_mode:x%x\n", phba->sli4_hba.fw_func_mode,
11116 			phba->sli4_hba.ulp0_mode, phba->sli4_hba.ulp1_mode);
11117 
11118 	mempool_free(mboxq, phba->mbox_mem_pool);
11119 
11120 	/*
11121 	 * Set up HBA Event Queues (EQs)
11122 	 */
11123 	qp = phba->sli4_hba.hdwq;
11124 
11125 	/* Set up HBA event queue */
11126 	if (!qp) {
11127 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11128 				"3147 Fast-path EQs not allocated\n");
11129 		rc = -ENOMEM;
11130 		goto out_error;
11131 	}
11132 
11133 	/* Loop thru all IRQ vectors */
11134 	for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
11135 		/* Create HBA Event Queues (EQs) in order */
11136 		for_each_present_cpu(cpu) {
11137 			cpup = &phba->sli4_hba.cpu_map[cpu];
11138 
11139 			/* Look for the CPU thats using that vector with
11140 			 * LPFC_CPU_FIRST_IRQ set.
11141 			 */
11142 			if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
11143 				continue;
11144 			if (qidx != cpup->eq)
11145 				continue;
11146 
11147 			/* Create an EQ for that vector */
11148 			rc = lpfc_eq_create(phba, qp[cpup->hdwq].hba_eq,
11149 					    phba->cfg_fcp_imax);
11150 			if (rc) {
11151 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11152 						"0523 Failed setup of fast-path"
11153 						" EQ (%d), rc = 0x%x\n",
11154 						cpup->eq, (uint32_t)rc);
11155 				goto out_destroy;
11156 			}
11157 
11158 			/* Save the EQ for that vector in the hba_eq_hdl */
11159 			phba->sli4_hba.hba_eq_hdl[cpup->eq].eq =
11160 				qp[cpup->hdwq].hba_eq;
11161 
11162 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11163 					"2584 HBA EQ setup: queue[%d]-id=%d\n",
11164 					cpup->eq,
11165 					qp[cpup->hdwq].hba_eq->queue_id);
11166 		}
11167 	}
11168 
11169 	/* Loop thru all Hardware Queues */
11170 	for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
11171 		cpu = lpfc_find_cpu_handle(phba, qidx, LPFC_FIND_BY_HDWQ);
11172 		cpup = &phba->sli4_hba.cpu_map[cpu];
11173 
11174 		/* Create the CQ/WQ corresponding to the Hardware Queue */
11175 		rc = lpfc_create_wq_cq(phba,
11176 				       phba->sli4_hba.hdwq[cpup->hdwq].hba_eq,
11177 				       qp[qidx].io_cq,
11178 				       qp[qidx].io_wq,
11179 				       &phba->sli4_hba.hdwq[qidx].io_cq_map,
11180 				       qidx,
11181 				       LPFC_IO);
11182 		if (rc) {
11183 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11184 					"0535 Failed to setup fastpath "
11185 					"IO WQ/CQ (%d), rc = 0x%x\n",
11186 					qidx, (uint32_t)rc);
11187 			goto out_destroy;
11188 		}
11189 	}
11190 
11191 	/*
11192 	 * Set up Slow Path Complete Queues (CQs)
11193 	 */
11194 
11195 	/* Set up slow-path MBOX CQ/MQ */
11196 
11197 	if (!phba->sli4_hba.mbx_cq || !phba->sli4_hba.mbx_wq) {
11198 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11199 				"0528 %s not allocated\n",
11200 				phba->sli4_hba.mbx_cq ?
11201 				"Mailbox WQ" : "Mailbox CQ");
11202 		rc = -ENOMEM;
11203 		goto out_destroy;
11204 	}
11205 
11206 	rc = lpfc_create_wq_cq(phba, qp[0].hba_eq,
11207 			       phba->sli4_hba.mbx_cq,
11208 			       phba->sli4_hba.mbx_wq,
11209 			       NULL, 0, LPFC_MBOX);
11210 	if (rc) {
11211 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11212 			"0529 Failed setup of mailbox WQ/CQ: rc = 0x%x\n",
11213 			(uint32_t)rc);
11214 		goto out_destroy;
11215 	}
11216 	if (phba->nvmet_support) {
11217 		if (!phba->sli4_hba.nvmet_cqset) {
11218 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11219 					"3165 Fast-path NVME CQ Set "
11220 					"array not allocated\n");
11221 			rc = -ENOMEM;
11222 			goto out_destroy;
11223 		}
11224 		if (phba->cfg_nvmet_mrq > 1) {
11225 			rc = lpfc_cq_create_set(phba,
11226 					phba->sli4_hba.nvmet_cqset,
11227 					qp,
11228 					LPFC_WCQ, LPFC_NVMET);
11229 			if (rc) {
11230 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11231 						"3164 Failed setup of NVME CQ "
11232 						"Set, rc = 0x%x\n",
11233 						(uint32_t)rc);
11234 				goto out_destroy;
11235 			}
11236 		} else {
11237 			/* Set up NVMET Receive Complete Queue */
11238 			rc = lpfc_cq_create(phba, phba->sli4_hba.nvmet_cqset[0],
11239 					    qp[0].hba_eq,
11240 					    LPFC_WCQ, LPFC_NVMET);
11241 			if (rc) {
11242 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11243 						"6089 Failed setup NVMET CQ: "
11244 						"rc = 0x%x\n", (uint32_t)rc);
11245 				goto out_destroy;
11246 			}
11247 			phba->sli4_hba.nvmet_cqset[0]->chann = 0;
11248 
11249 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11250 					"6090 NVMET CQ setup: cq-id=%d, "
11251 					"parent eq-id=%d\n",
11252 					phba->sli4_hba.nvmet_cqset[0]->queue_id,
11253 					qp[0].hba_eq->queue_id);
11254 		}
11255 	}
11256 
11257 	/* Set up slow-path ELS WQ/CQ */
11258 	if (!phba->sli4_hba.els_cq || !phba->sli4_hba.els_wq) {
11259 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11260 				"0530 ELS %s not allocated\n",
11261 				phba->sli4_hba.els_cq ? "WQ" : "CQ");
11262 		rc = -ENOMEM;
11263 		goto out_destroy;
11264 	}
11265 	rc = lpfc_create_wq_cq(phba, qp[0].hba_eq,
11266 			       phba->sli4_hba.els_cq,
11267 			       phba->sli4_hba.els_wq,
11268 			       NULL, 0, LPFC_ELS);
11269 	if (rc) {
11270 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11271 				"0525 Failed setup of ELS WQ/CQ: rc = 0x%x\n",
11272 				(uint32_t)rc);
11273 		goto out_destroy;
11274 	}
11275 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11276 			"2590 ELS WQ setup: wq-id=%d, parent cq-id=%d\n",
11277 			phba->sli4_hba.els_wq->queue_id,
11278 			phba->sli4_hba.els_cq->queue_id);
11279 
11280 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
11281 		/* Set up NVME LS Complete Queue */
11282 		if (!phba->sli4_hba.nvmels_cq || !phba->sli4_hba.nvmels_wq) {
11283 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11284 					"6091 LS %s not allocated\n",
11285 					phba->sli4_hba.nvmels_cq ? "WQ" : "CQ");
11286 			rc = -ENOMEM;
11287 			goto out_destroy;
11288 		}
11289 		rc = lpfc_create_wq_cq(phba, qp[0].hba_eq,
11290 				       phba->sli4_hba.nvmels_cq,
11291 				       phba->sli4_hba.nvmels_wq,
11292 				       NULL, 0, LPFC_NVME_LS);
11293 		if (rc) {
11294 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11295 					"0526 Failed setup of NVVME LS WQ/CQ: "
11296 					"rc = 0x%x\n", (uint32_t)rc);
11297 			goto out_destroy;
11298 		}
11299 
11300 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11301 				"6096 ELS WQ setup: wq-id=%d, "
11302 				"parent cq-id=%d\n",
11303 				phba->sli4_hba.nvmels_wq->queue_id,
11304 				phba->sli4_hba.nvmels_cq->queue_id);
11305 	}
11306 
11307 	/*
11308 	 * Create NVMET Receive Queue (RQ)
11309 	 */
11310 	if (phba->nvmet_support) {
11311 		if ((!phba->sli4_hba.nvmet_cqset) ||
11312 		    (!phba->sli4_hba.nvmet_mrq_hdr) ||
11313 		    (!phba->sli4_hba.nvmet_mrq_data)) {
11314 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11315 					"6130 MRQ CQ Queues not "
11316 					"allocated\n");
11317 			rc = -ENOMEM;
11318 			goto out_destroy;
11319 		}
11320 		if (phba->cfg_nvmet_mrq > 1) {
11321 			rc = lpfc_mrq_create(phba,
11322 					     phba->sli4_hba.nvmet_mrq_hdr,
11323 					     phba->sli4_hba.nvmet_mrq_data,
11324 					     phba->sli4_hba.nvmet_cqset,
11325 					     LPFC_NVMET);
11326 			if (rc) {
11327 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11328 						"6098 Failed setup of NVMET "
11329 						"MRQ: rc = 0x%x\n",
11330 						(uint32_t)rc);
11331 				goto out_destroy;
11332 			}
11333 
11334 		} else {
11335 			rc = lpfc_rq_create(phba,
11336 					    phba->sli4_hba.nvmet_mrq_hdr[0],
11337 					    phba->sli4_hba.nvmet_mrq_data[0],
11338 					    phba->sli4_hba.nvmet_cqset[0],
11339 					    LPFC_NVMET);
11340 			if (rc) {
11341 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11342 						"6057 Failed setup of NVMET "
11343 						"Receive Queue: rc = 0x%x\n",
11344 						(uint32_t)rc);
11345 				goto out_destroy;
11346 			}
11347 
11348 			lpfc_printf_log(
11349 				phba, KERN_INFO, LOG_INIT,
11350 				"6099 NVMET RQ setup: hdr-rq-id=%d, "
11351 				"dat-rq-id=%d parent cq-id=%d\n",
11352 				phba->sli4_hba.nvmet_mrq_hdr[0]->queue_id,
11353 				phba->sli4_hba.nvmet_mrq_data[0]->queue_id,
11354 				phba->sli4_hba.nvmet_cqset[0]->queue_id);
11355 
11356 		}
11357 	}
11358 
11359 	if (!phba->sli4_hba.hdr_rq || !phba->sli4_hba.dat_rq) {
11360 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11361 				"0540 Receive Queue not allocated\n");
11362 		rc = -ENOMEM;
11363 		goto out_destroy;
11364 	}
11365 
11366 	rc = lpfc_rq_create(phba, phba->sli4_hba.hdr_rq, phba->sli4_hba.dat_rq,
11367 			    phba->sli4_hba.els_cq, LPFC_USOL);
11368 	if (rc) {
11369 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11370 				"0541 Failed setup of Receive Queue: "
11371 				"rc = 0x%x\n", (uint32_t)rc);
11372 		goto out_destroy;
11373 	}
11374 
11375 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11376 			"2592 USL RQ setup: hdr-rq-id=%d, dat-rq-id=%d "
11377 			"parent cq-id=%d\n",
11378 			phba->sli4_hba.hdr_rq->queue_id,
11379 			phba->sli4_hba.dat_rq->queue_id,
11380 			phba->sli4_hba.els_cq->queue_id);
11381 
11382 	if (phba->cfg_fcp_imax)
11383 		usdelay = LPFC_SEC_TO_USEC / phba->cfg_fcp_imax;
11384 	else
11385 		usdelay = 0;
11386 
11387 	for (qidx = 0; qidx < phba->cfg_irq_chann;
11388 	     qidx += LPFC_MAX_EQ_DELAY_EQID_CNT)
11389 		lpfc_modify_hba_eq_delay(phba, qidx, LPFC_MAX_EQ_DELAY_EQID_CNT,
11390 					 usdelay);
11391 
11392 	if (phba->sli4_hba.cq_max) {
11393 		kfree(phba->sli4_hba.cq_lookup);
11394 		phba->sli4_hba.cq_lookup = kcalloc((phba->sli4_hba.cq_max + 1),
11395 			sizeof(struct lpfc_queue *), GFP_KERNEL);
11396 		if (!phba->sli4_hba.cq_lookup) {
11397 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11398 					"0549 Failed setup of CQ Lookup table: "
11399 					"size 0x%x\n", phba->sli4_hba.cq_max);
11400 			rc = -ENOMEM;
11401 			goto out_destroy;
11402 		}
11403 		lpfc_setup_cq_lookup(phba);
11404 	}
11405 	return 0;
11406 
11407 out_destroy:
11408 	lpfc_sli4_queue_unset(phba);
11409 out_error:
11410 	return rc;
11411 }
11412 
11413 /**
11414  * lpfc_sli4_queue_unset - Unset all the SLI4 queues
11415  * @phba: pointer to lpfc hba data structure.
11416  *
11417  * This routine is invoked to unset all the SLI4 queues with the FCoE HBA
11418  * operation.
11419  *
11420  * Return codes
11421  *      0 - successful
11422  *      -ENOMEM - No available memory
11423  *      -EIO - The mailbox failed to complete successfully.
11424  **/
11425 void
11426 lpfc_sli4_queue_unset(struct lpfc_hba *phba)
11427 {
11428 	struct lpfc_sli4_hdw_queue *qp;
11429 	struct lpfc_queue *eq;
11430 	int qidx;
11431 
11432 	/* Unset mailbox command work queue */
11433 	if (phba->sli4_hba.mbx_wq)
11434 		lpfc_mq_destroy(phba, phba->sli4_hba.mbx_wq);
11435 
11436 	/* Unset NVME LS work queue */
11437 	if (phba->sli4_hba.nvmels_wq)
11438 		lpfc_wq_destroy(phba, phba->sli4_hba.nvmels_wq);
11439 
11440 	/* Unset ELS work queue */
11441 	if (phba->sli4_hba.els_wq)
11442 		lpfc_wq_destroy(phba, phba->sli4_hba.els_wq);
11443 
11444 	/* Unset unsolicited receive queue */
11445 	if (phba->sli4_hba.hdr_rq)
11446 		lpfc_rq_destroy(phba, phba->sli4_hba.hdr_rq,
11447 				phba->sli4_hba.dat_rq);
11448 
11449 	/* Unset mailbox command complete queue */
11450 	if (phba->sli4_hba.mbx_cq)
11451 		lpfc_cq_destroy(phba, phba->sli4_hba.mbx_cq);
11452 
11453 	/* Unset ELS complete queue */
11454 	if (phba->sli4_hba.els_cq)
11455 		lpfc_cq_destroy(phba, phba->sli4_hba.els_cq);
11456 
11457 	/* Unset NVME LS complete queue */
11458 	if (phba->sli4_hba.nvmels_cq)
11459 		lpfc_cq_destroy(phba, phba->sli4_hba.nvmels_cq);
11460 
11461 	if (phba->nvmet_support) {
11462 		/* Unset NVMET MRQ queue */
11463 		if (phba->sli4_hba.nvmet_mrq_hdr) {
11464 			for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++)
11465 				lpfc_rq_destroy(
11466 					phba,
11467 					phba->sli4_hba.nvmet_mrq_hdr[qidx],
11468 					phba->sli4_hba.nvmet_mrq_data[qidx]);
11469 		}
11470 
11471 		/* Unset NVMET CQ Set complete queue */
11472 		if (phba->sli4_hba.nvmet_cqset) {
11473 			for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++)
11474 				lpfc_cq_destroy(
11475 					phba, phba->sli4_hba.nvmet_cqset[qidx]);
11476 		}
11477 	}
11478 
11479 	/* Unset fast-path SLI4 queues */
11480 	if (phba->sli4_hba.hdwq) {
11481 		/* Loop thru all Hardware Queues */
11482 		for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
11483 			/* Destroy the CQ/WQ corresponding to Hardware Queue */
11484 			qp = &phba->sli4_hba.hdwq[qidx];
11485 			lpfc_wq_destroy(phba, qp->io_wq);
11486 			lpfc_cq_destroy(phba, qp->io_cq);
11487 		}
11488 		/* Loop thru all IRQ vectors */
11489 		for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
11490 			/* Destroy the EQ corresponding to the IRQ vector */
11491 			eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
11492 			lpfc_eq_destroy(phba, eq);
11493 		}
11494 	}
11495 
11496 	kfree(phba->sli4_hba.cq_lookup);
11497 	phba->sli4_hba.cq_lookup = NULL;
11498 	phba->sli4_hba.cq_max = 0;
11499 }
11500 
11501 /**
11502  * lpfc_sli4_cq_event_pool_create - Create completion-queue event free pool
11503  * @phba: pointer to lpfc hba data structure.
11504  *
11505  * This routine is invoked to allocate and set up a pool of completion queue
11506  * events. The body of the completion queue event is a completion queue entry
11507  * CQE. For now, this pool is used for the interrupt service routine to queue
11508  * the following HBA completion queue events for the worker thread to process:
11509  *   - Mailbox asynchronous events
11510  *   - Receive queue completion unsolicited events
11511  * Later, this can be used for all the slow-path events.
11512  *
11513  * Return codes
11514  *      0 - successful
11515  *      -ENOMEM - No available memory
11516  **/
11517 static int
11518 lpfc_sli4_cq_event_pool_create(struct lpfc_hba *phba)
11519 {
11520 	struct lpfc_cq_event *cq_event;
11521 	int i;
11522 
11523 	for (i = 0; i < (4 * phba->sli4_hba.cq_ecount); i++) {
11524 		cq_event = kmalloc(sizeof(struct lpfc_cq_event), GFP_KERNEL);
11525 		if (!cq_event)
11526 			goto out_pool_create_fail;
11527 		list_add_tail(&cq_event->list,
11528 			      &phba->sli4_hba.sp_cqe_event_pool);
11529 	}
11530 	return 0;
11531 
11532 out_pool_create_fail:
11533 	lpfc_sli4_cq_event_pool_destroy(phba);
11534 	return -ENOMEM;
11535 }
11536 
11537 /**
11538  * lpfc_sli4_cq_event_pool_destroy - Free completion-queue event free pool
11539  * @phba: pointer to lpfc hba data structure.
11540  *
11541  * This routine is invoked to free the pool of completion queue events at
11542  * driver unload time. Note that, it is the responsibility of the driver
11543  * cleanup routine to free all the outstanding completion-queue events
11544  * allocated from this pool back into the pool before invoking this routine
11545  * to destroy the pool.
11546  **/
11547 static void
11548 lpfc_sli4_cq_event_pool_destroy(struct lpfc_hba *phba)
11549 {
11550 	struct lpfc_cq_event *cq_event, *next_cq_event;
11551 
11552 	list_for_each_entry_safe(cq_event, next_cq_event,
11553 				 &phba->sli4_hba.sp_cqe_event_pool, list) {
11554 		list_del(&cq_event->list);
11555 		kfree(cq_event);
11556 	}
11557 }
11558 
11559 /**
11560  * __lpfc_sli4_cq_event_alloc - Allocate a completion-queue event from free pool
11561  * @phba: pointer to lpfc hba data structure.
11562  *
11563  * This routine is the lock free version of the API invoked to allocate a
11564  * completion-queue event from the free pool.
11565  *
11566  * Return: Pointer to the newly allocated completion-queue event if successful
11567  *         NULL otherwise.
11568  **/
11569 struct lpfc_cq_event *
11570 __lpfc_sli4_cq_event_alloc(struct lpfc_hba *phba)
11571 {
11572 	struct lpfc_cq_event *cq_event = NULL;
11573 
11574 	list_remove_head(&phba->sli4_hba.sp_cqe_event_pool, cq_event,
11575 			 struct lpfc_cq_event, list);
11576 	return cq_event;
11577 }
11578 
11579 /**
11580  * lpfc_sli4_cq_event_alloc - Allocate a completion-queue event from free pool
11581  * @phba: pointer to lpfc hba data structure.
11582  *
11583  * This routine is the lock version of the API invoked to allocate a
11584  * completion-queue event from the free pool.
11585  *
11586  * Return: Pointer to the newly allocated completion-queue event if successful
11587  *         NULL otherwise.
11588  **/
11589 struct lpfc_cq_event *
11590 lpfc_sli4_cq_event_alloc(struct lpfc_hba *phba)
11591 {
11592 	struct lpfc_cq_event *cq_event;
11593 	unsigned long iflags;
11594 
11595 	spin_lock_irqsave(&phba->hbalock, iflags);
11596 	cq_event = __lpfc_sli4_cq_event_alloc(phba);
11597 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11598 	return cq_event;
11599 }
11600 
11601 /**
11602  * __lpfc_sli4_cq_event_release - Release a completion-queue event to free pool
11603  * @phba: pointer to lpfc hba data structure.
11604  * @cq_event: pointer to the completion queue event to be freed.
11605  *
11606  * This routine is the lock free version of the API invoked to release a
11607  * completion-queue event back into the free pool.
11608  **/
11609 void
11610 __lpfc_sli4_cq_event_release(struct lpfc_hba *phba,
11611 			     struct lpfc_cq_event *cq_event)
11612 {
11613 	list_add_tail(&cq_event->list, &phba->sli4_hba.sp_cqe_event_pool);
11614 }
11615 
11616 /**
11617  * lpfc_sli4_cq_event_release - Release a completion-queue event to free pool
11618  * @phba: pointer to lpfc hba data structure.
11619  * @cq_event: pointer to the completion queue event to be freed.
11620  *
11621  * This routine is the lock version of the API invoked to release a
11622  * completion-queue event back into the free pool.
11623  **/
11624 void
11625 lpfc_sli4_cq_event_release(struct lpfc_hba *phba,
11626 			   struct lpfc_cq_event *cq_event)
11627 {
11628 	unsigned long iflags;
11629 	spin_lock_irqsave(&phba->hbalock, iflags);
11630 	__lpfc_sli4_cq_event_release(phba, cq_event);
11631 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11632 }
11633 
11634 /**
11635  * lpfc_sli4_cq_event_release_all - Release all cq events to the free pool
11636  * @phba: pointer to lpfc hba data structure.
11637  *
11638  * This routine is to free all the pending completion-queue events to the
11639  * back into the free pool for device reset.
11640  **/
11641 static void
11642 lpfc_sli4_cq_event_release_all(struct lpfc_hba *phba)
11643 {
11644 	LIST_HEAD(cq_event_list);
11645 	struct lpfc_cq_event *cq_event;
11646 	unsigned long iflags;
11647 
11648 	/* Retrieve all the pending WCQEs from pending WCQE lists */
11649 
11650 	/* Pending ELS XRI abort events */
11651 	spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
11652 	list_splice_init(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
11653 			 &cq_event_list);
11654 	spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
11655 
11656 	/* Pending asynnc events */
11657 	spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
11658 	list_splice_init(&phba->sli4_hba.sp_asynce_work_queue,
11659 			 &cq_event_list);
11660 	spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock, iflags);
11661 
11662 	while (!list_empty(&cq_event_list)) {
11663 		list_remove_head(&cq_event_list, cq_event,
11664 				 struct lpfc_cq_event, list);
11665 		lpfc_sli4_cq_event_release(phba, cq_event);
11666 	}
11667 }
11668 
11669 /**
11670  * lpfc_pci_function_reset - Reset pci function.
11671  * @phba: pointer to lpfc hba data structure.
11672  *
11673  * This routine is invoked to request a PCI function reset. It will destroys
11674  * all resources assigned to the PCI function which originates this request.
11675  *
11676  * Return codes
11677  *      0 - successful
11678  *      -ENOMEM - No available memory
11679  *      -EIO - The mailbox failed to complete successfully.
11680  **/
11681 int
11682 lpfc_pci_function_reset(struct lpfc_hba *phba)
11683 {
11684 	LPFC_MBOXQ_t *mboxq;
11685 	uint32_t rc = 0, if_type;
11686 	uint32_t shdr_status, shdr_add_status;
11687 	uint32_t rdy_chk;
11688 	uint32_t port_reset = 0;
11689 	union lpfc_sli4_cfg_shdr *shdr;
11690 	struct lpfc_register reg_data;
11691 	uint16_t devid;
11692 
11693 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
11694 	switch (if_type) {
11695 	case LPFC_SLI_INTF_IF_TYPE_0:
11696 		mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
11697 						       GFP_KERNEL);
11698 		if (!mboxq) {
11699 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11700 					"0494 Unable to allocate memory for "
11701 					"issuing SLI_FUNCTION_RESET mailbox "
11702 					"command\n");
11703 			return -ENOMEM;
11704 		}
11705 
11706 		/* Setup PCI function reset mailbox-ioctl command */
11707 		lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
11708 				 LPFC_MBOX_OPCODE_FUNCTION_RESET, 0,
11709 				 LPFC_SLI4_MBX_EMBED);
11710 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
11711 		shdr = (union lpfc_sli4_cfg_shdr *)
11712 			&mboxq->u.mqe.un.sli4_config.header.cfg_shdr;
11713 		shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
11714 		shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
11715 					 &shdr->response);
11716 		mempool_free(mboxq, phba->mbox_mem_pool);
11717 		if (shdr_status || shdr_add_status || rc) {
11718 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11719 					"0495 SLI_FUNCTION_RESET mailbox "
11720 					"failed with status x%x add_status x%x,"
11721 					" mbx status x%x\n",
11722 					shdr_status, shdr_add_status, rc);
11723 			rc = -ENXIO;
11724 		}
11725 		break;
11726 	case LPFC_SLI_INTF_IF_TYPE_2:
11727 	case LPFC_SLI_INTF_IF_TYPE_6:
11728 wait:
11729 		/*
11730 		 * Poll the Port Status Register and wait for RDY for
11731 		 * up to 30 seconds. If the port doesn't respond, treat
11732 		 * it as an error.
11733 		 */
11734 		for (rdy_chk = 0; rdy_chk < 1500; rdy_chk++) {
11735 			if (lpfc_readl(phba->sli4_hba.u.if_type2.
11736 				STATUSregaddr, &reg_data.word0)) {
11737 				rc = -ENODEV;
11738 				goto out;
11739 			}
11740 			if (bf_get(lpfc_sliport_status_rdy, &reg_data))
11741 				break;
11742 			msleep(20);
11743 		}
11744 
11745 		if (!bf_get(lpfc_sliport_status_rdy, &reg_data)) {
11746 			phba->work_status[0] = readl(
11747 				phba->sli4_hba.u.if_type2.ERR1regaddr);
11748 			phba->work_status[1] = readl(
11749 				phba->sli4_hba.u.if_type2.ERR2regaddr);
11750 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11751 					"2890 Port not ready, port status reg "
11752 					"0x%x error 1=0x%x, error 2=0x%x\n",
11753 					reg_data.word0,
11754 					phba->work_status[0],
11755 					phba->work_status[1]);
11756 			rc = -ENODEV;
11757 			goto out;
11758 		}
11759 
11760 		if (bf_get(lpfc_sliport_status_pldv, &reg_data))
11761 			lpfc_pldv_detect = true;
11762 
11763 		if (!port_reset) {
11764 			/*
11765 			 * Reset the port now
11766 			 */
11767 			reg_data.word0 = 0;
11768 			bf_set(lpfc_sliport_ctrl_end, &reg_data,
11769 			       LPFC_SLIPORT_LITTLE_ENDIAN);
11770 			bf_set(lpfc_sliport_ctrl_ip, &reg_data,
11771 			       LPFC_SLIPORT_INIT_PORT);
11772 			writel(reg_data.word0, phba->sli4_hba.u.if_type2.
11773 			       CTRLregaddr);
11774 			/* flush */
11775 			pci_read_config_word(phba->pcidev,
11776 					     PCI_DEVICE_ID, &devid);
11777 
11778 			port_reset = 1;
11779 			msleep(20);
11780 			goto wait;
11781 		} else if (bf_get(lpfc_sliport_status_rn, &reg_data)) {
11782 			rc = -ENODEV;
11783 			goto out;
11784 		}
11785 		break;
11786 
11787 	case LPFC_SLI_INTF_IF_TYPE_1:
11788 	default:
11789 		break;
11790 	}
11791 
11792 out:
11793 	/* Catch the not-ready port failure after a port reset. */
11794 	if (rc) {
11795 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11796 				"3317 HBA not functional: IP Reset Failed "
11797 				"try: echo fw_reset > board_mode\n");
11798 		rc = -ENODEV;
11799 	}
11800 
11801 	return rc;
11802 }
11803 
11804 /**
11805  * lpfc_sli4_pci_mem_setup - Setup SLI4 HBA PCI memory space.
11806  * @phba: pointer to lpfc hba data structure.
11807  *
11808  * This routine is invoked to set up the PCI device memory space for device
11809  * with SLI-4 interface spec.
11810  *
11811  * Return codes
11812  * 	0 - successful
11813  * 	other values - error
11814  **/
11815 static int
11816 lpfc_sli4_pci_mem_setup(struct lpfc_hba *phba)
11817 {
11818 	struct pci_dev *pdev = phba->pcidev;
11819 	unsigned long bar0map_len, bar1map_len, bar2map_len;
11820 	int error;
11821 	uint32_t if_type;
11822 
11823 	if (!pdev)
11824 		return -ENODEV;
11825 
11826 	/* Set the device DMA mask size */
11827 	error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
11828 	if (error)
11829 		error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32));
11830 	if (error)
11831 		return error;
11832 
11833 	/*
11834 	 * The BARs and register set definitions and offset locations are
11835 	 * dependent on the if_type.
11836 	 */
11837 	if (pci_read_config_dword(pdev, LPFC_SLI_INTF,
11838 				  &phba->sli4_hba.sli_intf.word0)) {
11839 		return -ENODEV;
11840 	}
11841 
11842 	/* There is no SLI3 failback for SLI4 devices. */
11843 	if (bf_get(lpfc_sli_intf_valid, &phba->sli4_hba.sli_intf) !=
11844 	    LPFC_SLI_INTF_VALID) {
11845 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11846 				"2894 SLI_INTF reg contents invalid "
11847 				"sli_intf reg 0x%x\n",
11848 				phba->sli4_hba.sli_intf.word0);
11849 		return -ENODEV;
11850 	}
11851 
11852 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
11853 	/*
11854 	 * Get the bus address of SLI4 device Bar regions and the
11855 	 * number of bytes required by each mapping. The mapping of the
11856 	 * particular PCI BARs regions is dependent on the type of
11857 	 * SLI4 device.
11858 	 */
11859 	if (pci_resource_start(pdev, PCI_64BIT_BAR0)) {
11860 		phba->pci_bar0_map = pci_resource_start(pdev, PCI_64BIT_BAR0);
11861 		bar0map_len = pci_resource_len(pdev, PCI_64BIT_BAR0);
11862 
11863 		/*
11864 		 * Map SLI4 PCI Config Space Register base to a kernel virtual
11865 		 * addr
11866 		 */
11867 		phba->sli4_hba.conf_regs_memmap_p =
11868 			ioremap(phba->pci_bar0_map, bar0map_len);
11869 		if (!phba->sli4_hba.conf_regs_memmap_p) {
11870 			dev_printk(KERN_ERR, &pdev->dev,
11871 				   "ioremap failed for SLI4 PCI config "
11872 				   "registers.\n");
11873 			return -ENODEV;
11874 		}
11875 		phba->pci_bar0_memmap_p = phba->sli4_hba.conf_regs_memmap_p;
11876 		/* Set up BAR0 PCI config space register memory map */
11877 		lpfc_sli4_bar0_register_memmap(phba, if_type);
11878 	} else {
11879 		phba->pci_bar0_map = pci_resource_start(pdev, 1);
11880 		bar0map_len = pci_resource_len(pdev, 1);
11881 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
11882 			dev_printk(KERN_ERR, &pdev->dev,
11883 			   "FATAL - No BAR0 mapping for SLI4, if_type 2\n");
11884 			return -ENODEV;
11885 		}
11886 		phba->sli4_hba.conf_regs_memmap_p =
11887 				ioremap(phba->pci_bar0_map, bar0map_len);
11888 		if (!phba->sli4_hba.conf_regs_memmap_p) {
11889 			dev_printk(KERN_ERR, &pdev->dev,
11890 				"ioremap failed for SLI4 PCI config "
11891 				"registers.\n");
11892 			return -ENODEV;
11893 		}
11894 		lpfc_sli4_bar0_register_memmap(phba, if_type);
11895 	}
11896 
11897 	if (if_type == LPFC_SLI_INTF_IF_TYPE_0) {
11898 		if (pci_resource_start(pdev, PCI_64BIT_BAR2)) {
11899 			/*
11900 			 * Map SLI4 if type 0 HBA Control Register base to a
11901 			 * kernel virtual address and setup the registers.
11902 			 */
11903 			phba->pci_bar1_map = pci_resource_start(pdev,
11904 								PCI_64BIT_BAR2);
11905 			bar1map_len = pci_resource_len(pdev, PCI_64BIT_BAR2);
11906 			phba->sli4_hba.ctrl_regs_memmap_p =
11907 					ioremap(phba->pci_bar1_map,
11908 						bar1map_len);
11909 			if (!phba->sli4_hba.ctrl_regs_memmap_p) {
11910 				dev_err(&pdev->dev,
11911 					   "ioremap failed for SLI4 HBA "
11912 					    "control registers.\n");
11913 				error = -ENOMEM;
11914 				goto out_iounmap_conf;
11915 			}
11916 			phba->pci_bar2_memmap_p =
11917 					 phba->sli4_hba.ctrl_regs_memmap_p;
11918 			lpfc_sli4_bar1_register_memmap(phba, if_type);
11919 		} else {
11920 			error = -ENOMEM;
11921 			goto out_iounmap_conf;
11922 		}
11923 	}
11924 
11925 	if ((if_type == LPFC_SLI_INTF_IF_TYPE_6) &&
11926 	    (pci_resource_start(pdev, PCI_64BIT_BAR2))) {
11927 		/*
11928 		 * Map SLI4 if type 6 HBA Doorbell Register base to a kernel
11929 		 * virtual address and setup the registers.
11930 		 */
11931 		phba->pci_bar1_map = pci_resource_start(pdev, PCI_64BIT_BAR2);
11932 		bar1map_len = pci_resource_len(pdev, PCI_64BIT_BAR2);
11933 		phba->sli4_hba.drbl_regs_memmap_p =
11934 				ioremap(phba->pci_bar1_map, bar1map_len);
11935 		if (!phba->sli4_hba.drbl_regs_memmap_p) {
11936 			dev_err(&pdev->dev,
11937 			   "ioremap failed for SLI4 HBA doorbell registers.\n");
11938 			error = -ENOMEM;
11939 			goto out_iounmap_conf;
11940 		}
11941 		phba->pci_bar2_memmap_p = phba->sli4_hba.drbl_regs_memmap_p;
11942 		lpfc_sli4_bar1_register_memmap(phba, if_type);
11943 	}
11944 
11945 	if (if_type == LPFC_SLI_INTF_IF_TYPE_0) {
11946 		if (pci_resource_start(pdev, PCI_64BIT_BAR4)) {
11947 			/*
11948 			 * Map SLI4 if type 0 HBA Doorbell Register base to
11949 			 * a kernel virtual address and setup the registers.
11950 			 */
11951 			phba->pci_bar2_map = pci_resource_start(pdev,
11952 								PCI_64BIT_BAR4);
11953 			bar2map_len = pci_resource_len(pdev, PCI_64BIT_BAR4);
11954 			phba->sli4_hba.drbl_regs_memmap_p =
11955 					ioremap(phba->pci_bar2_map,
11956 						bar2map_len);
11957 			if (!phba->sli4_hba.drbl_regs_memmap_p) {
11958 				dev_err(&pdev->dev,
11959 					   "ioremap failed for SLI4 HBA"
11960 					   " doorbell registers.\n");
11961 				error = -ENOMEM;
11962 				goto out_iounmap_ctrl;
11963 			}
11964 			phba->pci_bar4_memmap_p =
11965 					phba->sli4_hba.drbl_regs_memmap_p;
11966 			error = lpfc_sli4_bar2_register_memmap(phba, LPFC_VF0);
11967 			if (error)
11968 				goto out_iounmap_all;
11969 		} else {
11970 			error = -ENOMEM;
11971 			goto out_iounmap_all;
11972 		}
11973 	}
11974 
11975 	if (if_type == LPFC_SLI_INTF_IF_TYPE_6 &&
11976 	    pci_resource_start(pdev, PCI_64BIT_BAR4)) {
11977 		/*
11978 		 * Map SLI4 if type 6 HBA DPP Register base to a kernel
11979 		 * virtual address and setup the registers.
11980 		 */
11981 		phba->pci_bar2_map = pci_resource_start(pdev, PCI_64BIT_BAR4);
11982 		bar2map_len = pci_resource_len(pdev, PCI_64BIT_BAR4);
11983 		phba->sli4_hba.dpp_regs_memmap_p =
11984 				ioremap(phba->pci_bar2_map, bar2map_len);
11985 		if (!phba->sli4_hba.dpp_regs_memmap_p) {
11986 			dev_err(&pdev->dev,
11987 			   "ioremap failed for SLI4 HBA dpp registers.\n");
11988 			error = -ENOMEM;
11989 			goto out_iounmap_ctrl;
11990 		}
11991 		phba->pci_bar4_memmap_p = phba->sli4_hba.dpp_regs_memmap_p;
11992 	}
11993 
11994 	/* Set up the EQ/CQ register handeling functions now */
11995 	switch (if_type) {
11996 	case LPFC_SLI_INTF_IF_TYPE_0:
11997 	case LPFC_SLI_INTF_IF_TYPE_2:
11998 		phba->sli4_hba.sli4_eq_clr_intr = lpfc_sli4_eq_clr_intr;
11999 		phba->sli4_hba.sli4_write_eq_db = lpfc_sli4_write_eq_db;
12000 		phba->sli4_hba.sli4_write_cq_db = lpfc_sli4_write_cq_db;
12001 		break;
12002 	case LPFC_SLI_INTF_IF_TYPE_6:
12003 		phba->sli4_hba.sli4_eq_clr_intr = lpfc_sli4_if6_eq_clr_intr;
12004 		phba->sli4_hba.sli4_write_eq_db = lpfc_sli4_if6_write_eq_db;
12005 		phba->sli4_hba.sli4_write_cq_db = lpfc_sli4_if6_write_cq_db;
12006 		break;
12007 	default:
12008 		break;
12009 	}
12010 
12011 	return 0;
12012 
12013 out_iounmap_all:
12014 	iounmap(phba->sli4_hba.drbl_regs_memmap_p);
12015 out_iounmap_ctrl:
12016 	iounmap(phba->sli4_hba.ctrl_regs_memmap_p);
12017 out_iounmap_conf:
12018 	iounmap(phba->sli4_hba.conf_regs_memmap_p);
12019 
12020 	return error;
12021 }
12022 
12023 /**
12024  * lpfc_sli4_pci_mem_unset - Unset SLI4 HBA PCI memory space.
12025  * @phba: pointer to lpfc hba data structure.
12026  *
12027  * This routine is invoked to unset the PCI device memory space for device
12028  * with SLI-4 interface spec.
12029  **/
12030 static void
12031 lpfc_sli4_pci_mem_unset(struct lpfc_hba *phba)
12032 {
12033 	uint32_t if_type;
12034 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
12035 
12036 	switch (if_type) {
12037 	case LPFC_SLI_INTF_IF_TYPE_0:
12038 		iounmap(phba->sli4_hba.drbl_regs_memmap_p);
12039 		iounmap(phba->sli4_hba.ctrl_regs_memmap_p);
12040 		iounmap(phba->sli4_hba.conf_regs_memmap_p);
12041 		break;
12042 	case LPFC_SLI_INTF_IF_TYPE_2:
12043 		iounmap(phba->sli4_hba.conf_regs_memmap_p);
12044 		break;
12045 	case LPFC_SLI_INTF_IF_TYPE_6:
12046 		iounmap(phba->sli4_hba.drbl_regs_memmap_p);
12047 		iounmap(phba->sli4_hba.conf_regs_memmap_p);
12048 		if (phba->sli4_hba.dpp_regs_memmap_p)
12049 			iounmap(phba->sli4_hba.dpp_regs_memmap_p);
12050 		break;
12051 	case LPFC_SLI_INTF_IF_TYPE_1:
12052 	default:
12053 		dev_printk(KERN_ERR, &phba->pcidev->dev,
12054 			   "FATAL - unsupported SLI4 interface type - %d\n",
12055 			   if_type);
12056 		break;
12057 	}
12058 }
12059 
12060 /**
12061  * lpfc_sli_enable_msix - Enable MSI-X interrupt mode on SLI-3 device
12062  * @phba: pointer to lpfc hba data structure.
12063  *
12064  * This routine is invoked to enable the MSI-X interrupt vectors to device
12065  * with SLI-3 interface specs.
12066  *
12067  * Return codes
12068  *   0 - successful
12069  *   other values - error
12070  **/
12071 static int
12072 lpfc_sli_enable_msix(struct lpfc_hba *phba)
12073 {
12074 	int rc;
12075 	LPFC_MBOXQ_t *pmb;
12076 
12077 	/* Set up MSI-X multi-message vectors */
12078 	rc = pci_alloc_irq_vectors(phba->pcidev,
12079 			LPFC_MSIX_VECTORS, LPFC_MSIX_VECTORS, PCI_IRQ_MSIX);
12080 	if (rc < 0) {
12081 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12082 				"0420 PCI enable MSI-X failed (%d)\n", rc);
12083 		goto vec_fail_out;
12084 	}
12085 
12086 	/*
12087 	 * Assign MSI-X vectors to interrupt handlers
12088 	 */
12089 
12090 	/* vector-0 is associated to slow-path handler */
12091 	rc = request_irq(pci_irq_vector(phba->pcidev, 0),
12092 			 &lpfc_sli_sp_intr_handler, 0,
12093 			 LPFC_SP_DRIVER_HANDLER_NAME, phba);
12094 	if (rc) {
12095 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
12096 				"0421 MSI-X slow-path request_irq failed "
12097 				"(%d)\n", rc);
12098 		goto msi_fail_out;
12099 	}
12100 
12101 	/* vector-1 is associated to fast-path handler */
12102 	rc = request_irq(pci_irq_vector(phba->pcidev, 1),
12103 			 &lpfc_sli_fp_intr_handler, 0,
12104 			 LPFC_FP_DRIVER_HANDLER_NAME, phba);
12105 
12106 	if (rc) {
12107 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
12108 				"0429 MSI-X fast-path request_irq failed "
12109 				"(%d)\n", rc);
12110 		goto irq_fail_out;
12111 	}
12112 
12113 	/*
12114 	 * Configure HBA MSI-X attention conditions to messages
12115 	 */
12116 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
12117 
12118 	if (!pmb) {
12119 		rc = -ENOMEM;
12120 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12121 				"0474 Unable to allocate memory for issuing "
12122 				"MBOX_CONFIG_MSI command\n");
12123 		goto mem_fail_out;
12124 	}
12125 	rc = lpfc_config_msi(phba, pmb);
12126 	if (rc)
12127 		goto mbx_fail_out;
12128 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
12129 	if (rc != MBX_SUCCESS) {
12130 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX,
12131 				"0351 Config MSI mailbox command failed, "
12132 				"mbxCmd x%x, mbxStatus x%x\n",
12133 				pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus);
12134 		goto mbx_fail_out;
12135 	}
12136 
12137 	/* Free memory allocated for mailbox command */
12138 	mempool_free(pmb, phba->mbox_mem_pool);
12139 	return rc;
12140 
12141 mbx_fail_out:
12142 	/* Free memory allocated for mailbox command */
12143 	mempool_free(pmb, phba->mbox_mem_pool);
12144 
12145 mem_fail_out:
12146 	/* free the irq already requested */
12147 	free_irq(pci_irq_vector(phba->pcidev, 1), phba);
12148 
12149 irq_fail_out:
12150 	/* free the irq already requested */
12151 	free_irq(pci_irq_vector(phba->pcidev, 0), phba);
12152 
12153 msi_fail_out:
12154 	/* Unconfigure MSI-X capability structure */
12155 	pci_free_irq_vectors(phba->pcidev);
12156 
12157 vec_fail_out:
12158 	return rc;
12159 }
12160 
12161 /**
12162  * lpfc_sli_enable_msi - Enable MSI interrupt mode on SLI-3 device.
12163  * @phba: pointer to lpfc hba data structure.
12164  *
12165  * This routine is invoked to enable the MSI interrupt mode to device with
12166  * SLI-3 interface spec. The kernel function pci_enable_msi() is called to
12167  * enable the MSI vector. The device driver is responsible for calling the
12168  * request_irq() to register MSI vector with a interrupt the handler, which
12169  * is done in this function.
12170  *
12171  * Return codes
12172  * 	0 - successful
12173  * 	other values - error
12174  */
12175 static int
12176 lpfc_sli_enable_msi(struct lpfc_hba *phba)
12177 {
12178 	int rc;
12179 
12180 	rc = pci_enable_msi(phba->pcidev);
12181 	if (!rc)
12182 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12183 				"0012 PCI enable MSI mode success.\n");
12184 	else {
12185 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12186 				"0471 PCI enable MSI mode failed (%d)\n", rc);
12187 		return rc;
12188 	}
12189 
12190 	rc = request_irq(phba->pcidev->irq, lpfc_sli_intr_handler,
12191 			 0, LPFC_DRIVER_NAME, phba);
12192 	if (rc) {
12193 		pci_disable_msi(phba->pcidev);
12194 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
12195 				"0478 MSI request_irq failed (%d)\n", rc);
12196 	}
12197 	return rc;
12198 }
12199 
12200 /**
12201  * lpfc_sli_enable_intr - Enable device interrupt to SLI-3 device.
12202  * @phba: pointer to lpfc hba data structure.
12203  * @cfg_mode: Interrupt configuration mode (INTx, MSI or MSI-X).
12204  *
12205  * This routine is invoked to enable device interrupt and associate driver's
12206  * interrupt handler(s) to interrupt vector(s) to device with SLI-3 interface
12207  * spec. Depends on the interrupt mode configured to the driver, the driver
12208  * will try to fallback from the configured interrupt mode to an interrupt
12209  * mode which is supported by the platform, kernel, and device in the order
12210  * of:
12211  * MSI-X -> MSI -> IRQ.
12212  *
12213  * Return codes
12214  *   0 - successful
12215  *   other values - error
12216  **/
12217 static uint32_t
12218 lpfc_sli_enable_intr(struct lpfc_hba *phba, uint32_t cfg_mode)
12219 {
12220 	uint32_t intr_mode = LPFC_INTR_ERROR;
12221 	int retval;
12222 
12223 	/* Need to issue conf_port mbox cmd before conf_msi mbox cmd */
12224 	retval = lpfc_sli_config_port(phba, LPFC_SLI_REV3);
12225 	if (retval)
12226 		return intr_mode;
12227 	phba->hba_flag &= ~HBA_NEEDS_CFG_PORT;
12228 
12229 	if (cfg_mode == 2) {
12230 		/* Now, try to enable MSI-X interrupt mode */
12231 		retval = lpfc_sli_enable_msix(phba);
12232 		if (!retval) {
12233 			/* Indicate initialization to MSI-X mode */
12234 			phba->intr_type = MSIX;
12235 			intr_mode = 2;
12236 		}
12237 	}
12238 
12239 	/* Fallback to MSI if MSI-X initialization failed */
12240 	if (cfg_mode >= 1 && phba->intr_type == NONE) {
12241 		retval = lpfc_sli_enable_msi(phba);
12242 		if (!retval) {
12243 			/* Indicate initialization to MSI mode */
12244 			phba->intr_type = MSI;
12245 			intr_mode = 1;
12246 		}
12247 	}
12248 
12249 	/* Fallback to INTx if both MSI-X/MSI initalization failed */
12250 	if (phba->intr_type == NONE) {
12251 		retval = request_irq(phba->pcidev->irq, lpfc_sli_intr_handler,
12252 				     IRQF_SHARED, LPFC_DRIVER_NAME, phba);
12253 		if (!retval) {
12254 			/* Indicate initialization to INTx mode */
12255 			phba->intr_type = INTx;
12256 			intr_mode = 0;
12257 		}
12258 	}
12259 	return intr_mode;
12260 }
12261 
12262 /**
12263  * lpfc_sli_disable_intr - Disable device interrupt to SLI-3 device.
12264  * @phba: pointer to lpfc hba data structure.
12265  *
12266  * This routine is invoked to disable device interrupt and disassociate the
12267  * driver's interrupt handler(s) from interrupt vector(s) to device with
12268  * SLI-3 interface spec. Depending on the interrupt mode, the driver will
12269  * release the interrupt vector(s) for the message signaled interrupt.
12270  **/
12271 static void
12272 lpfc_sli_disable_intr(struct lpfc_hba *phba)
12273 {
12274 	int nr_irqs, i;
12275 
12276 	if (phba->intr_type == MSIX)
12277 		nr_irqs = LPFC_MSIX_VECTORS;
12278 	else
12279 		nr_irqs = 1;
12280 
12281 	for (i = 0; i < nr_irqs; i++)
12282 		free_irq(pci_irq_vector(phba->pcidev, i), phba);
12283 	pci_free_irq_vectors(phba->pcidev);
12284 
12285 	/* Reset interrupt management states */
12286 	phba->intr_type = NONE;
12287 	phba->sli.slistat.sli_intr = 0;
12288 }
12289 
12290 /**
12291  * lpfc_find_cpu_handle - Find the CPU that corresponds to the specified Queue
12292  * @phba: pointer to lpfc hba data structure.
12293  * @id: EQ vector index or Hardware Queue index
12294  * @match: LPFC_FIND_BY_EQ = match by EQ
12295  *         LPFC_FIND_BY_HDWQ = match by Hardware Queue
12296  * Return the CPU that matches the selection criteria
12297  */
12298 static uint16_t
12299 lpfc_find_cpu_handle(struct lpfc_hba *phba, uint16_t id, int match)
12300 {
12301 	struct lpfc_vector_map_info *cpup;
12302 	int cpu;
12303 
12304 	/* Loop through all CPUs */
12305 	for_each_present_cpu(cpu) {
12306 		cpup = &phba->sli4_hba.cpu_map[cpu];
12307 
12308 		/* If we are matching by EQ, there may be multiple CPUs using
12309 		 * using the same vector, so select the one with
12310 		 * LPFC_CPU_FIRST_IRQ set.
12311 		 */
12312 		if ((match == LPFC_FIND_BY_EQ) &&
12313 		    (cpup->flag & LPFC_CPU_FIRST_IRQ) &&
12314 		    (cpup->eq == id))
12315 			return cpu;
12316 
12317 		/* If matching by HDWQ, select the first CPU that matches */
12318 		if ((match == LPFC_FIND_BY_HDWQ) && (cpup->hdwq == id))
12319 			return cpu;
12320 	}
12321 	return 0;
12322 }
12323 
12324 #ifdef CONFIG_X86
12325 /**
12326  * lpfc_find_hyper - Determine if the CPU map entry is hyper-threaded
12327  * @phba: pointer to lpfc hba data structure.
12328  * @cpu: CPU map index
12329  * @phys_id: CPU package physical id
12330  * @core_id: CPU core id
12331  */
12332 static int
12333 lpfc_find_hyper(struct lpfc_hba *phba, int cpu,
12334 		uint16_t phys_id, uint16_t core_id)
12335 {
12336 	struct lpfc_vector_map_info *cpup;
12337 	int idx;
12338 
12339 	for_each_present_cpu(idx) {
12340 		cpup = &phba->sli4_hba.cpu_map[idx];
12341 		/* Does the cpup match the one we are looking for */
12342 		if ((cpup->phys_id == phys_id) &&
12343 		    (cpup->core_id == core_id) &&
12344 		    (cpu != idx))
12345 			return 1;
12346 	}
12347 	return 0;
12348 }
12349 #endif
12350 
12351 /*
12352  * lpfc_assign_eq_map_info - Assigns eq for vector_map structure
12353  * @phba: pointer to lpfc hba data structure.
12354  * @eqidx: index for eq and irq vector
12355  * @flag: flags to set for vector_map structure
12356  * @cpu: cpu used to index vector_map structure
12357  *
12358  * The routine assigns eq info into vector_map structure
12359  */
12360 static inline void
12361 lpfc_assign_eq_map_info(struct lpfc_hba *phba, uint16_t eqidx, uint16_t flag,
12362 			unsigned int cpu)
12363 {
12364 	struct lpfc_vector_map_info *cpup = &phba->sli4_hba.cpu_map[cpu];
12365 	struct lpfc_hba_eq_hdl *eqhdl = lpfc_get_eq_hdl(eqidx);
12366 
12367 	cpup->eq = eqidx;
12368 	cpup->flag |= flag;
12369 
12370 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12371 			"3336 Set Affinity: CPU %d irq %d eq %d flag x%x\n",
12372 			cpu, eqhdl->irq, cpup->eq, cpup->flag);
12373 }
12374 
12375 /**
12376  * lpfc_cpu_map_array_init - Initialize cpu_map structure
12377  * @phba: pointer to lpfc hba data structure.
12378  *
12379  * The routine initializes the cpu_map array structure
12380  */
12381 static void
12382 lpfc_cpu_map_array_init(struct lpfc_hba *phba)
12383 {
12384 	struct lpfc_vector_map_info *cpup;
12385 	struct lpfc_eq_intr_info *eqi;
12386 	int cpu;
12387 
12388 	for_each_possible_cpu(cpu) {
12389 		cpup = &phba->sli4_hba.cpu_map[cpu];
12390 		cpup->phys_id = LPFC_VECTOR_MAP_EMPTY;
12391 		cpup->core_id = LPFC_VECTOR_MAP_EMPTY;
12392 		cpup->hdwq = LPFC_VECTOR_MAP_EMPTY;
12393 		cpup->eq = LPFC_VECTOR_MAP_EMPTY;
12394 		cpup->flag = 0;
12395 		eqi = per_cpu_ptr(phba->sli4_hba.eq_info, cpu);
12396 		INIT_LIST_HEAD(&eqi->list);
12397 		eqi->icnt = 0;
12398 	}
12399 }
12400 
12401 /**
12402  * lpfc_hba_eq_hdl_array_init - Initialize hba_eq_hdl structure
12403  * @phba: pointer to lpfc hba data structure.
12404  *
12405  * The routine initializes the hba_eq_hdl array structure
12406  */
12407 static void
12408 lpfc_hba_eq_hdl_array_init(struct lpfc_hba *phba)
12409 {
12410 	struct lpfc_hba_eq_hdl *eqhdl;
12411 	int i;
12412 
12413 	for (i = 0; i < phba->cfg_irq_chann; i++) {
12414 		eqhdl = lpfc_get_eq_hdl(i);
12415 		eqhdl->irq = LPFC_IRQ_EMPTY;
12416 		eqhdl->phba = phba;
12417 	}
12418 }
12419 
12420 /**
12421  * lpfc_cpu_affinity_check - Check vector CPU affinity mappings
12422  * @phba: pointer to lpfc hba data structure.
12423  * @vectors: number of msix vectors allocated.
12424  *
12425  * The routine will figure out the CPU affinity assignment for every
12426  * MSI-X vector allocated for the HBA.
12427  * In addition, the CPU to IO channel mapping will be calculated
12428  * and the phba->sli4_hba.cpu_map array will reflect this.
12429  */
12430 static void
12431 lpfc_cpu_affinity_check(struct lpfc_hba *phba, int vectors)
12432 {
12433 	int i, cpu, idx, next_idx, new_cpu, start_cpu, first_cpu;
12434 	int max_phys_id, min_phys_id;
12435 	int max_core_id, min_core_id;
12436 	struct lpfc_vector_map_info *cpup;
12437 	struct lpfc_vector_map_info *new_cpup;
12438 #ifdef CONFIG_X86
12439 	struct cpuinfo_x86 *cpuinfo;
12440 #endif
12441 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
12442 	struct lpfc_hdwq_stat *c_stat;
12443 #endif
12444 
12445 	max_phys_id = 0;
12446 	min_phys_id = LPFC_VECTOR_MAP_EMPTY;
12447 	max_core_id = 0;
12448 	min_core_id = LPFC_VECTOR_MAP_EMPTY;
12449 
12450 	/* Update CPU map with physical id and core id of each CPU */
12451 	for_each_present_cpu(cpu) {
12452 		cpup = &phba->sli4_hba.cpu_map[cpu];
12453 #ifdef CONFIG_X86
12454 		cpuinfo = &cpu_data(cpu);
12455 		cpup->phys_id = cpuinfo->phys_proc_id;
12456 		cpup->core_id = cpuinfo->cpu_core_id;
12457 		if (lpfc_find_hyper(phba, cpu, cpup->phys_id, cpup->core_id))
12458 			cpup->flag |= LPFC_CPU_MAP_HYPER;
12459 #else
12460 		/* No distinction between CPUs for other platforms */
12461 		cpup->phys_id = 0;
12462 		cpup->core_id = cpu;
12463 #endif
12464 
12465 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12466 				"3328 CPU %d physid %d coreid %d flag x%x\n",
12467 				cpu, cpup->phys_id, cpup->core_id, cpup->flag);
12468 
12469 		if (cpup->phys_id > max_phys_id)
12470 			max_phys_id = cpup->phys_id;
12471 		if (cpup->phys_id < min_phys_id)
12472 			min_phys_id = cpup->phys_id;
12473 
12474 		if (cpup->core_id > max_core_id)
12475 			max_core_id = cpup->core_id;
12476 		if (cpup->core_id < min_core_id)
12477 			min_core_id = cpup->core_id;
12478 	}
12479 
12480 	/* After looking at each irq vector assigned to this pcidev, its
12481 	 * possible to see that not ALL CPUs have been accounted for.
12482 	 * Next we will set any unassigned (unaffinitized) cpu map
12483 	 * entries to a IRQ on the same phys_id.
12484 	 */
12485 	first_cpu = cpumask_first(cpu_present_mask);
12486 	start_cpu = first_cpu;
12487 
12488 	for_each_present_cpu(cpu) {
12489 		cpup = &phba->sli4_hba.cpu_map[cpu];
12490 
12491 		/* Is this CPU entry unassigned */
12492 		if (cpup->eq == LPFC_VECTOR_MAP_EMPTY) {
12493 			/* Mark CPU as IRQ not assigned by the kernel */
12494 			cpup->flag |= LPFC_CPU_MAP_UNASSIGN;
12495 
12496 			/* If so, find a new_cpup thats on the the SAME
12497 			 * phys_id as cpup. start_cpu will start where we
12498 			 * left off so all unassigned entries don't get assgined
12499 			 * the IRQ of the first entry.
12500 			 */
12501 			new_cpu = start_cpu;
12502 			for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12503 				new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12504 				if (!(new_cpup->flag & LPFC_CPU_MAP_UNASSIGN) &&
12505 				    (new_cpup->eq != LPFC_VECTOR_MAP_EMPTY) &&
12506 				    (new_cpup->phys_id == cpup->phys_id))
12507 					goto found_same;
12508 				new_cpu = cpumask_next(
12509 					new_cpu, cpu_present_mask);
12510 				if (new_cpu == nr_cpumask_bits)
12511 					new_cpu = first_cpu;
12512 			}
12513 			/* At this point, we leave the CPU as unassigned */
12514 			continue;
12515 found_same:
12516 			/* We found a matching phys_id, so copy the IRQ info */
12517 			cpup->eq = new_cpup->eq;
12518 
12519 			/* Bump start_cpu to the next slot to minmize the
12520 			 * chance of having multiple unassigned CPU entries
12521 			 * selecting the same IRQ.
12522 			 */
12523 			start_cpu = cpumask_next(new_cpu, cpu_present_mask);
12524 			if (start_cpu == nr_cpumask_bits)
12525 				start_cpu = first_cpu;
12526 
12527 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12528 					"3337 Set Affinity: CPU %d "
12529 					"eq %d from peer cpu %d same "
12530 					"phys_id (%d)\n",
12531 					cpu, cpup->eq, new_cpu,
12532 					cpup->phys_id);
12533 		}
12534 	}
12535 
12536 	/* Set any unassigned cpu map entries to a IRQ on any phys_id */
12537 	start_cpu = first_cpu;
12538 
12539 	for_each_present_cpu(cpu) {
12540 		cpup = &phba->sli4_hba.cpu_map[cpu];
12541 
12542 		/* Is this entry unassigned */
12543 		if (cpup->eq == LPFC_VECTOR_MAP_EMPTY) {
12544 			/* Mark it as IRQ not assigned by the kernel */
12545 			cpup->flag |= LPFC_CPU_MAP_UNASSIGN;
12546 
12547 			/* If so, find a new_cpup thats on ANY phys_id
12548 			 * as the cpup. start_cpu will start where we
12549 			 * left off so all unassigned entries don't get
12550 			 * assigned the IRQ of the first entry.
12551 			 */
12552 			new_cpu = start_cpu;
12553 			for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12554 				new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12555 				if (!(new_cpup->flag & LPFC_CPU_MAP_UNASSIGN) &&
12556 				    (new_cpup->eq != LPFC_VECTOR_MAP_EMPTY))
12557 					goto found_any;
12558 				new_cpu = cpumask_next(
12559 					new_cpu, cpu_present_mask);
12560 				if (new_cpu == nr_cpumask_bits)
12561 					new_cpu = first_cpu;
12562 			}
12563 			/* We should never leave an entry unassigned */
12564 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12565 					"3339 Set Affinity: CPU %d "
12566 					"eq %d UNASSIGNED\n",
12567 					cpup->hdwq, cpup->eq);
12568 			continue;
12569 found_any:
12570 			/* We found an available entry, copy the IRQ info */
12571 			cpup->eq = new_cpup->eq;
12572 
12573 			/* Bump start_cpu to the next slot to minmize the
12574 			 * chance of having multiple unassigned CPU entries
12575 			 * selecting the same IRQ.
12576 			 */
12577 			start_cpu = cpumask_next(new_cpu, cpu_present_mask);
12578 			if (start_cpu == nr_cpumask_bits)
12579 				start_cpu = first_cpu;
12580 
12581 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12582 					"3338 Set Affinity: CPU %d "
12583 					"eq %d from peer cpu %d (%d/%d)\n",
12584 					cpu, cpup->eq, new_cpu,
12585 					new_cpup->phys_id, new_cpup->core_id);
12586 		}
12587 	}
12588 
12589 	/* Assign hdwq indices that are unique across all cpus in the map
12590 	 * that are also FIRST_CPUs.
12591 	 */
12592 	idx = 0;
12593 	for_each_present_cpu(cpu) {
12594 		cpup = &phba->sli4_hba.cpu_map[cpu];
12595 
12596 		/* Only FIRST IRQs get a hdwq index assignment. */
12597 		if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
12598 			continue;
12599 
12600 		/* 1 to 1, the first LPFC_CPU_FIRST_IRQ cpus to a unique hdwq */
12601 		cpup->hdwq = idx;
12602 		idx++;
12603 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12604 				"3333 Set Affinity: CPU %d (phys %d core %d): "
12605 				"hdwq %d eq %d flg x%x\n",
12606 				cpu, cpup->phys_id, cpup->core_id,
12607 				cpup->hdwq, cpup->eq, cpup->flag);
12608 	}
12609 	/* Associate a hdwq with each cpu_map entry
12610 	 * This will be 1 to 1 - hdwq to cpu, unless there are less
12611 	 * hardware queues then CPUs. For that case we will just round-robin
12612 	 * the available hardware queues as they get assigned to CPUs.
12613 	 * The next_idx is the idx from the FIRST_CPU loop above to account
12614 	 * for irq_chann < hdwq.  The idx is used for round-robin assignments
12615 	 * and needs to start at 0.
12616 	 */
12617 	next_idx = idx;
12618 	start_cpu = 0;
12619 	idx = 0;
12620 	for_each_present_cpu(cpu) {
12621 		cpup = &phba->sli4_hba.cpu_map[cpu];
12622 
12623 		/* FIRST cpus are already mapped. */
12624 		if (cpup->flag & LPFC_CPU_FIRST_IRQ)
12625 			continue;
12626 
12627 		/* If the cfg_irq_chann < cfg_hdw_queue, set the hdwq
12628 		 * of the unassigned cpus to the next idx so that all
12629 		 * hdw queues are fully utilized.
12630 		 */
12631 		if (next_idx < phba->cfg_hdw_queue) {
12632 			cpup->hdwq = next_idx;
12633 			next_idx++;
12634 			continue;
12635 		}
12636 
12637 		/* Not a First CPU and all hdw_queues are used.  Reuse a
12638 		 * Hardware Queue for another CPU, so be smart about it
12639 		 * and pick one that has its IRQ/EQ mapped to the same phys_id
12640 		 * (CPU package) and core_id.
12641 		 */
12642 		new_cpu = start_cpu;
12643 		for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12644 			new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12645 			if (new_cpup->hdwq != LPFC_VECTOR_MAP_EMPTY &&
12646 			    new_cpup->phys_id == cpup->phys_id &&
12647 			    new_cpup->core_id == cpup->core_id) {
12648 				goto found_hdwq;
12649 			}
12650 			new_cpu = cpumask_next(new_cpu, cpu_present_mask);
12651 			if (new_cpu == nr_cpumask_bits)
12652 				new_cpu = first_cpu;
12653 		}
12654 
12655 		/* If we can't match both phys_id and core_id,
12656 		 * settle for just a phys_id match.
12657 		 */
12658 		new_cpu = start_cpu;
12659 		for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12660 			new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12661 			if (new_cpup->hdwq != LPFC_VECTOR_MAP_EMPTY &&
12662 			    new_cpup->phys_id == cpup->phys_id)
12663 				goto found_hdwq;
12664 
12665 			new_cpu = cpumask_next(new_cpu, cpu_present_mask);
12666 			if (new_cpu == nr_cpumask_bits)
12667 				new_cpu = first_cpu;
12668 		}
12669 
12670 		/* Otherwise just round robin on cfg_hdw_queue */
12671 		cpup->hdwq = idx % phba->cfg_hdw_queue;
12672 		idx++;
12673 		goto logit;
12674  found_hdwq:
12675 		/* We found an available entry, copy the IRQ info */
12676 		start_cpu = cpumask_next(new_cpu, cpu_present_mask);
12677 		if (start_cpu == nr_cpumask_bits)
12678 			start_cpu = first_cpu;
12679 		cpup->hdwq = new_cpup->hdwq;
12680  logit:
12681 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12682 				"3335 Set Affinity: CPU %d (phys %d core %d): "
12683 				"hdwq %d eq %d flg x%x\n",
12684 				cpu, cpup->phys_id, cpup->core_id,
12685 				cpup->hdwq, cpup->eq, cpup->flag);
12686 	}
12687 
12688 	/*
12689 	 * Initialize the cpu_map slots for not-present cpus in case
12690 	 * a cpu is hot-added. Perform a simple hdwq round robin assignment.
12691 	 */
12692 	idx = 0;
12693 	for_each_possible_cpu(cpu) {
12694 		cpup = &phba->sli4_hba.cpu_map[cpu];
12695 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
12696 		c_stat = per_cpu_ptr(phba->sli4_hba.c_stat, cpu);
12697 		c_stat->hdwq_no = cpup->hdwq;
12698 #endif
12699 		if (cpup->hdwq != LPFC_VECTOR_MAP_EMPTY)
12700 			continue;
12701 
12702 		cpup->hdwq = idx++ % phba->cfg_hdw_queue;
12703 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
12704 		c_stat->hdwq_no = cpup->hdwq;
12705 #endif
12706 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12707 				"3340 Set Affinity: not present "
12708 				"CPU %d hdwq %d\n",
12709 				cpu, cpup->hdwq);
12710 	}
12711 
12712 	/* The cpu_map array will be used later during initialization
12713 	 * when EQ / CQ / WQs are allocated and configured.
12714 	 */
12715 	return;
12716 }
12717 
12718 /**
12719  * lpfc_cpuhp_get_eq
12720  *
12721  * @phba:   pointer to lpfc hba data structure.
12722  * @cpu:    cpu going offline
12723  * @eqlist: eq list to append to
12724  */
12725 static int
12726 lpfc_cpuhp_get_eq(struct lpfc_hba *phba, unsigned int cpu,
12727 		  struct list_head *eqlist)
12728 {
12729 	const struct cpumask *maskp;
12730 	struct lpfc_queue *eq;
12731 	struct cpumask *tmp;
12732 	u16 idx;
12733 
12734 	tmp = kzalloc(cpumask_size(), GFP_KERNEL);
12735 	if (!tmp)
12736 		return -ENOMEM;
12737 
12738 	for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
12739 		maskp = pci_irq_get_affinity(phba->pcidev, idx);
12740 		if (!maskp)
12741 			continue;
12742 		/*
12743 		 * if irq is not affinitized to the cpu going
12744 		 * then we don't need to poll the eq attached
12745 		 * to it.
12746 		 */
12747 		if (!cpumask_and(tmp, maskp, cpumask_of(cpu)))
12748 			continue;
12749 		/* get the cpus that are online and are affini-
12750 		 * tized to this irq vector.  If the count is
12751 		 * more than 1 then cpuhp is not going to shut-
12752 		 * down this vector.  Since this cpu has not
12753 		 * gone offline yet, we need >1.
12754 		 */
12755 		cpumask_and(tmp, maskp, cpu_online_mask);
12756 		if (cpumask_weight(tmp) > 1)
12757 			continue;
12758 
12759 		/* Now that we have an irq to shutdown, get the eq
12760 		 * mapped to this irq.  Note: multiple hdwq's in
12761 		 * the software can share an eq, but eventually
12762 		 * only eq will be mapped to this vector
12763 		 */
12764 		eq = phba->sli4_hba.hba_eq_hdl[idx].eq;
12765 		list_add(&eq->_poll_list, eqlist);
12766 	}
12767 	kfree(tmp);
12768 	return 0;
12769 }
12770 
12771 static void __lpfc_cpuhp_remove(struct lpfc_hba *phba)
12772 {
12773 	if (phba->sli_rev != LPFC_SLI_REV4)
12774 		return;
12775 
12776 	cpuhp_state_remove_instance_nocalls(lpfc_cpuhp_state,
12777 					    &phba->cpuhp);
12778 	/*
12779 	 * unregistering the instance doesn't stop the polling
12780 	 * timer. Wait for the poll timer to retire.
12781 	 */
12782 	synchronize_rcu();
12783 	del_timer_sync(&phba->cpuhp_poll_timer);
12784 }
12785 
12786 static void lpfc_cpuhp_remove(struct lpfc_hba *phba)
12787 {
12788 	if (phba->pport && (phba->pport->fc_flag & FC_OFFLINE_MODE))
12789 		return;
12790 
12791 	__lpfc_cpuhp_remove(phba);
12792 }
12793 
12794 static void lpfc_cpuhp_add(struct lpfc_hba *phba)
12795 {
12796 	if (phba->sli_rev != LPFC_SLI_REV4)
12797 		return;
12798 
12799 	rcu_read_lock();
12800 
12801 	if (!list_empty(&phba->poll_list))
12802 		mod_timer(&phba->cpuhp_poll_timer,
12803 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
12804 
12805 	rcu_read_unlock();
12806 
12807 	cpuhp_state_add_instance_nocalls(lpfc_cpuhp_state,
12808 					 &phba->cpuhp);
12809 }
12810 
12811 static int __lpfc_cpuhp_checks(struct lpfc_hba *phba, int *retval)
12812 {
12813 	if (phba->pport->load_flag & FC_UNLOADING) {
12814 		*retval = -EAGAIN;
12815 		return true;
12816 	}
12817 
12818 	if (phba->sli_rev != LPFC_SLI_REV4) {
12819 		*retval = 0;
12820 		return true;
12821 	}
12822 
12823 	/* proceed with the hotplug */
12824 	return false;
12825 }
12826 
12827 /**
12828  * lpfc_irq_set_aff - set IRQ affinity
12829  * @eqhdl: EQ handle
12830  * @cpu: cpu to set affinity
12831  *
12832  **/
12833 static inline void
12834 lpfc_irq_set_aff(struct lpfc_hba_eq_hdl *eqhdl, unsigned int cpu)
12835 {
12836 	cpumask_clear(&eqhdl->aff_mask);
12837 	cpumask_set_cpu(cpu, &eqhdl->aff_mask);
12838 	irq_set_status_flags(eqhdl->irq, IRQ_NO_BALANCING);
12839 	irq_set_affinity(eqhdl->irq, &eqhdl->aff_mask);
12840 }
12841 
12842 /**
12843  * lpfc_irq_clear_aff - clear IRQ affinity
12844  * @eqhdl: EQ handle
12845  *
12846  **/
12847 static inline void
12848 lpfc_irq_clear_aff(struct lpfc_hba_eq_hdl *eqhdl)
12849 {
12850 	cpumask_clear(&eqhdl->aff_mask);
12851 	irq_clear_status_flags(eqhdl->irq, IRQ_NO_BALANCING);
12852 }
12853 
12854 /**
12855  * lpfc_irq_rebalance - rebalances IRQ affinity according to cpuhp event
12856  * @phba: pointer to HBA context object.
12857  * @cpu: cpu going offline/online
12858  * @offline: true, cpu is going offline. false, cpu is coming online.
12859  *
12860  * If cpu is going offline, we'll try our best effort to find the next
12861  * online cpu on the phba's original_mask and migrate all offlining IRQ
12862  * affinities.
12863  *
12864  * If cpu is coming online, reaffinitize the IRQ back to the onlining cpu.
12865  *
12866  * Note: Call only if NUMA or NHT mode is enabled, otherwise rely on
12867  *	 PCI_IRQ_AFFINITY to auto-manage IRQ affinity.
12868  *
12869  **/
12870 static void
12871 lpfc_irq_rebalance(struct lpfc_hba *phba, unsigned int cpu, bool offline)
12872 {
12873 	struct lpfc_vector_map_info *cpup;
12874 	struct cpumask *aff_mask;
12875 	unsigned int cpu_select, cpu_next, idx;
12876 	const struct cpumask *orig_mask;
12877 
12878 	if (phba->irq_chann_mode == NORMAL_MODE)
12879 		return;
12880 
12881 	orig_mask = &phba->sli4_hba.irq_aff_mask;
12882 
12883 	if (!cpumask_test_cpu(cpu, orig_mask))
12884 		return;
12885 
12886 	cpup = &phba->sli4_hba.cpu_map[cpu];
12887 
12888 	if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
12889 		return;
12890 
12891 	if (offline) {
12892 		/* Find next online CPU on original mask */
12893 		cpu_next = cpumask_next_wrap(cpu, orig_mask, cpu, true);
12894 		cpu_select = lpfc_next_online_cpu(orig_mask, cpu_next);
12895 
12896 		/* Found a valid CPU */
12897 		if ((cpu_select < nr_cpu_ids) && (cpu_select != cpu)) {
12898 			/* Go through each eqhdl and ensure offlining
12899 			 * cpu aff_mask is migrated
12900 			 */
12901 			for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
12902 				aff_mask = lpfc_get_aff_mask(idx);
12903 
12904 				/* Migrate affinity */
12905 				if (cpumask_test_cpu(cpu, aff_mask))
12906 					lpfc_irq_set_aff(lpfc_get_eq_hdl(idx),
12907 							 cpu_select);
12908 			}
12909 		} else {
12910 			/* Rely on irqbalance if no online CPUs left on NUMA */
12911 			for (idx = 0; idx < phba->cfg_irq_chann; idx++)
12912 				lpfc_irq_clear_aff(lpfc_get_eq_hdl(idx));
12913 		}
12914 	} else {
12915 		/* Migrate affinity back to this CPU */
12916 		lpfc_irq_set_aff(lpfc_get_eq_hdl(cpup->eq), cpu);
12917 	}
12918 }
12919 
12920 static int lpfc_cpu_offline(unsigned int cpu, struct hlist_node *node)
12921 {
12922 	struct lpfc_hba *phba = hlist_entry_safe(node, struct lpfc_hba, cpuhp);
12923 	struct lpfc_queue *eq, *next;
12924 	LIST_HEAD(eqlist);
12925 	int retval;
12926 
12927 	if (!phba) {
12928 		WARN_ONCE(!phba, "cpu: %u. phba:NULL", raw_smp_processor_id());
12929 		return 0;
12930 	}
12931 
12932 	if (__lpfc_cpuhp_checks(phba, &retval))
12933 		return retval;
12934 
12935 	lpfc_irq_rebalance(phba, cpu, true);
12936 
12937 	retval = lpfc_cpuhp_get_eq(phba, cpu, &eqlist);
12938 	if (retval)
12939 		return retval;
12940 
12941 	/* start polling on these eq's */
12942 	list_for_each_entry_safe(eq, next, &eqlist, _poll_list) {
12943 		list_del_init(&eq->_poll_list);
12944 		lpfc_sli4_start_polling(eq);
12945 	}
12946 
12947 	return 0;
12948 }
12949 
12950 static int lpfc_cpu_online(unsigned int cpu, struct hlist_node *node)
12951 {
12952 	struct lpfc_hba *phba = hlist_entry_safe(node, struct lpfc_hba, cpuhp);
12953 	struct lpfc_queue *eq, *next;
12954 	unsigned int n;
12955 	int retval;
12956 
12957 	if (!phba) {
12958 		WARN_ONCE(!phba, "cpu: %u. phba:NULL", raw_smp_processor_id());
12959 		return 0;
12960 	}
12961 
12962 	if (__lpfc_cpuhp_checks(phba, &retval))
12963 		return retval;
12964 
12965 	lpfc_irq_rebalance(phba, cpu, false);
12966 
12967 	list_for_each_entry_safe(eq, next, &phba->poll_list, _poll_list) {
12968 		n = lpfc_find_cpu_handle(phba, eq->hdwq, LPFC_FIND_BY_HDWQ);
12969 		if (n == cpu)
12970 			lpfc_sli4_stop_polling(eq);
12971 	}
12972 
12973 	return 0;
12974 }
12975 
12976 /**
12977  * lpfc_sli4_enable_msix - Enable MSI-X interrupt mode to SLI-4 device
12978  * @phba: pointer to lpfc hba data structure.
12979  *
12980  * This routine is invoked to enable the MSI-X interrupt vectors to device
12981  * with SLI-4 interface spec.  It also allocates MSI-X vectors and maps them
12982  * to cpus on the system.
12983  *
12984  * When cfg_irq_numa is enabled, the adapter will only allocate vectors for
12985  * the number of cpus on the same numa node as this adapter.  The vectors are
12986  * allocated without requesting OS affinity mapping.  A vector will be
12987  * allocated and assigned to each online and offline cpu.  If the cpu is
12988  * online, then affinity will be set to that cpu.  If the cpu is offline, then
12989  * affinity will be set to the nearest peer cpu within the numa node that is
12990  * online.  If there are no online cpus within the numa node, affinity is not
12991  * assigned and the OS may do as it pleases. Note: cpu vector affinity mapping
12992  * is consistent with the way cpu online/offline is handled when cfg_irq_numa is
12993  * configured.
12994  *
12995  * If numa mode is not enabled and there is more than 1 vector allocated, then
12996  * the driver relies on the managed irq interface where the OS assigns vector to
12997  * cpu affinity.  The driver will then use that affinity mapping to setup its
12998  * cpu mapping table.
12999  *
13000  * Return codes
13001  * 0 - successful
13002  * other values - error
13003  **/
13004 static int
13005 lpfc_sli4_enable_msix(struct lpfc_hba *phba)
13006 {
13007 	int vectors, rc, index;
13008 	char *name;
13009 	const struct cpumask *aff_mask = NULL;
13010 	unsigned int cpu = 0, cpu_cnt = 0, cpu_select = nr_cpu_ids;
13011 	struct lpfc_vector_map_info *cpup;
13012 	struct lpfc_hba_eq_hdl *eqhdl;
13013 	const struct cpumask *maskp;
13014 	unsigned int flags = PCI_IRQ_MSIX;
13015 
13016 	/* Set up MSI-X multi-message vectors */
13017 	vectors = phba->cfg_irq_chann;
13018 
13019 	if (phba->irq_chann_mode != NORMAL_MODE)
13020 		aff_mask = &phba->sli4_hba.irq_aff_mask;
13021 
13022 	if (aff_mask) {
13023 		cpu_cnt = cpumask_weight(aff_mask);
13024 		vectors = min(phba->cfg_irq_chann, cpu_cnt);
13025 
13026 		/* cpu: iterates over aff_mask including offline or online
13027 		 * cpu_select: iterates over online aff_mask to set affinity
13028 		 */
13029 		cpu = cpumask_first(aff_mask);
13030 		cpu_select = lpfc_next_online_cpu(aff_mask, cpu);
13031 	} else {
13032 		flags |= PCI_IRQ_AFFINITY;
13033 	}
13034 
13035 	rc = pci_alloc_irq_vectors(phba->pcidev, 1, vectors, flags);
13036 	if (rc < 0) {
13037 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13038 				"0484 PCI enable MSI-X failed (%d)\n", rc);
13039 		goto vec_fail_out;
13040 	}
13041 	vectors = rc;
13042 
13043 	/* Assign MSI-X vectors to interrupt handlers */
13044 	for (index = 0; index < vectors; index++) {
13045 		eqhdl = lpfc_get_eq_hdl(index);
13046 		name = eqhdl->handler_name;
13047 		memset(name, 0, LPFC_SLI4_HANDLER_NAME_SZ);
13048 		snprintf(name, LPFC_SLI4_HANDLER_NAME_SZ,
13049 			 LPFC_DRIVER_HANDLER_NAME"%d", index);
13050 
13051 		eqhdl->idx = index;
13052 		rc = pci_irq_vector(phba->pcidev, index);
13053 		if (rc < 0) {
13054 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13055 					"0489 MSI-X fast-path (%d) "
13056 					"pci_irq_vec failed (%d)\n", index, rc);
13057 			goto cfg_fail_out;
13058 		}
13059 		eqhdl->irq = rc;
13060 
13061 		rc = request_irq(eqhdl->irq, &lpfc_sli4_hba_intr_handler, 0,
13062 				 name, eqhdl);
13063 		if (rc) {
13064 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13065 					"0486 MSI-X fast-path (%d) "
13066 					"request_irq failed (%d)\n", index, rc);
13067 			goto cfg_fail_out;
13068 		}
13069 
13070 		if (aff_mask) {
13071 			/* If found a neighboring online cpu, set affinity */
13072 			if (cpu_select < nr_cpu_ids)
13073 				lpfc_irq_set_aff(eqhdl, cpu_select);
13074 
13075 			/* Assign EQ to cpu_map */
13076 			lpfc_assign_eq_map_info(phba, index,
13077 						LPFC_CPU_FIRST_IRQ,
13078 						cpu);
13079 
13080 			/* Iterate to next offline or online cpu in aff_mask */
13081 			cpu = cpumask_next(cpu, aff_mask);
13082 
13083 			/* Find next online cpu in aff_mask to set affinity */
13084 			cpu_select = lpfc_next_online_cpu(aff_mask, cpu);
13085 		} else if (vectors == 1) {
13086 			cpu = cpumask_first(cpu_present_mask);
13087 			lpfc_assign_eq_map_info(phba, index, LPFC_CPU_FIRST_IRQ,
13088 						cpu);
13089 		} else {
13090 			maskp = pci_irq_get_affinity(phba->pcidev, index);
13091 
13092 			/* Loop through all CPUs associated with vector index */
13093 			for_each_cpu_and(cpu, maskp, cpu_present_mask) {
13094 				cpup = &phba->sli4_hba.cpu_map[cpu];
13095 
13096 				/* If this is the first CPU thats assigned to
13097 				 * this vector, set LPFC_CPU_FIRST_IRQ.
13098 				 *
13099 				 * With certain platforms its possible that irq
13100 				 * vectors are affinitized to all the cpu's.
13101 				 * This can result in each cpu_map.eq to be set
13102 				 * to the last vector, resulting in overwrite
13103 				 * of all the previous cpu_map.eq.  Ensure that
13104 				 * each vector receives a place in cpu_map.
13105 				 * Later call to lpfc_cpu_affinity_check will
13106 				 * ensure we are nicely balanced out.
13107 				 */
13108 				if (cpup->eq != LPFC_VECTOR_MAP_EMPTY)
13109 					continue;
13110 				lpfc_assign_eq_map_info(phba, index,
13111 							LPFC_CPU_FIRST_IRQ,
13112 							cpu);
13113 				break;
13114 			}
13115 		}
13116 	}
13117 
13118 	if (vectors != phba->cfg_irq_chann) {
13119 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13120 				"3238 Reducing IO channels to match number of "
13121 				"MSI-X vectors, requested %d got %d\n",
13122 				phba->cfg_irq_chann, vectors);
13123 		if (phba->cfg_irq_chann > vectors)
13124 			phba->cfg_irq_chann = vectors;
13125 	}
13126 
13127 	return rc;
13128 
13129 cfg_fail_out:
13130 	/* free the irq already requested */
13131 	for (--index; index >= 0; index--) {
13132 		eqhdl = lpfc_get_eq_hdl(index);
13133 		lpfc_irq_clear_aff(eqhdl);
13134 		free_irq(eqhdl->irq, eqhdl);
13135 	}
13136 
13137 	/* Unconfigure MSI-X capability structure */
13138 	pci_free_irq_vectors(phba->pcidev);
13139 
13140 vec_fail_out:
13141 	return rc;
13142 }
13143 
13144 /**
13145  * lpfc_sli4_enable_msi - Enable MSI interrupt mode to SLI-4 device
13146  * @phba: pointer to lpfc hba data structure.
13147  *
13148  * This routine is invoked to enable the MSI interrupt mode to device with
13149  * SLI-4 interface spec. The kernel function pci_alloc_irq_vectors() is
13150  * called to enable the MSI vector. The device driver is responsible for
13151  * calling the request_irq() to register MSI vector with a interrupt the
13152  * handler, which is done in this function.
13153  *
13154  * Return codes
13155  * 	0 - successful
13156  * 	other values - error
13157  **/
13158 static int
13159 lpfc_sli4_enable_msi(struct lpfc_hba *phba)
13160 {
13161 	int rc, index;
13162 	unsigned int cpu;
13163 	struct lpfc_hba_eq_hdl *eqhdl;
13164 
13165 	rc = pci_alloc_irq_vectors(phba->pcidev, 1, 1,
13166 				   PCI_IRQ_MSI | PCI_IRQ_AFFINITY);
13167 	if (rc > 0)
13168 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13169 				"0487 PCI enable MSI mode success.\n");
13170 	else {
13171 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13172 				"0488 PCI enable MSI mode failed (%d)\n", rc);
13173 		return rc ? rc : -1;
13174 	}
13175 
13176 	rc = request_irq(phba->pcidev->irq, lpfc_sli4_intr_handler,
13177 			 0, LPFC_DRIVER_NAME, phba);
13178 	if (rc) {
13179 		pci_free_irq_vectors(phba->pcidev);
13180 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13181 				"0490 MSI request_irq failed (%d)\n", rc);
13182 		return rc;
13183 	}
13184 
13185 	eqhdl = lpfc_get_eq_hdl(0);
13186 	rc = pci_irq_vector(phba->pcidev, 0);
13187 	if (rc < 0) {
13188 		pci_free_irq_vectors(phba->pcidev);
13189 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13190 				"0496 MSI pci_irq_vec failed (%d)\n", rc);
13191 		return rc;
13192 	}
13193 	eqhdl->irq = rc;
13194 
13195 	cpu = cpumask_first(cpu_present_mask);
13196 	lpfc_assign_eq_map_info(phba, 0, LPFC_CPU_FIRST_IRQ, cpu);
13197 
13198 	for (index = 0; index < phba->cfg_irq_chann; index++) {
13199 		eqhdl = lpfc_get_eq_hdl(index);
13200 		eqhdl->idx = index;
13201 	}
13202 
13203 	return 0;
13204 }
13205 
13206 /**
13207  * lpfc_sli4_enable_intr - Enable device interrupt to SLI-4 device
13208  * @phba: pointer to lpfc hba data structure.
13209  * @cfg_mode: Interrupt configuration mode (INTx, MSI or MSI-X).
13210  *
13211  * This routine is invoked to enable device interrupt and associate driver's
13212  * interrupt handler(s) to interrupt vector(s) to device with SLI-4
13213  * interface spec. Depends on the interrupt mode configured to the driver,
13214  * the driver will try to fallback from the configured interrupt mode to an
13215  * interrupt mode which is supported by the platform, kernel, and device in
13216  * the order of:
13217  * MSI-X -> MSI -> IRQ.
13218  *
13219  * Return codes
13220  *	Interrupt mode (2, 1, 0) - successful
13221  *	LPFC_INTR_ERROR - error
13222  **/
13223 static uint32_t
13224 lpfc_sli4_enable_intr(struct lpfc_hba *phba, uint32_t cfg_mode)
13225 {
13226 	uint32_t intr_mode = LPFC_INTR_ERROR;
13227 	int retval, idx;
13228 
13229 	if (cfg_mode == 2) {
13230 		/* Preparation before conf_msi mbox cmd */
13231 		retval = 0;
13232 		if (!retval) {
13233 			/* Now, try to enable MSI-X interrupt mode */
13234 			retval = lpfc_sli4_enable_msix(phba);
13235 			if (!retval) {
13236 				/* Indicate initialization to MSI-X mode */
13237 				phba->intr_type = MSIX;
13238 				intr_mode = 2;
13239 			}
13240 		}
13241 	}
13242 
13243 	/* Fallback to MSI if MSI-X initialization failed */
13244 	if (cfg_mode >= 1 && phba->intr_type == NONE) {
13245 		retval = lpfc_sli4_enable_msi(phba);
13246 		if (!retval) {
13247 			/* Indicate initialization to MSI mode */
13248 			phba->intr_type = MSI;
13249 			intr_mode = 1;
13250 		}
13251 	}
13252 
13253 	/* Fallback to INTx if both MSI-X/MSI initalization failed */
13254 	if (phba->intr_type == NONE) {
13255 		retval = request_irq(phba->pcidev->irq, lpfc_sli4_intr_handler,
13256 				     IRQF_SHARED, LPFC_DRIVER_NAME, phba);
13257 		if (!retval) {
13258 			struct lpfc_hba_eq_hdl *eqhdl;
13259 			unsigned int cpu;
13260 
13261 			/* Indicate initialization to INTx mode */
13262 			phba->intr_type = INTx;
13263 			intr_mode = 0;
13264 
13265 			eqhdl = lpfc_get_eq_hdl(0);
13266 			retval = pci_irq_vector(phba->pcidev, 0);
13267 			if (retval < 0) {
13268 				lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13269 					"0502 INTR pci_irq_vec failed (%d)\n",
13270 					 retval);
13271 				return LPFC_INTR_ERROR;
13272 			}
13273 			eqhdl->irq = retval;
13274 
13275 			cpu = cpumask_first(cpu_present_mask);
13276 			lpfc_assign_eq_map_info(phba, 0, LPFC_CPU_FIRST_IRQ,
13277 						cpu);
13278 			for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
13279 				eqhdl = lpfc_get_eq_hdl(idx);
13280 				eqhdl->idx = idx;
13281 			}
13282 		}
13283 	}
13284 	return intr_mode;
13285 }
13286 
13287 /**
13288  * lpfc_sli4_disable_intr - Disable device interrupt to SLI-4 device
13289  * @phba: pointer to lpfc hba data structure.
13290  *
13291  * This routine is invoked to disable device interrupt and disassociate
13292  * the driver's interrupt handler(s) from interrupt vector(s) to device
13293  * with SLI-4 interface spec. Depending on the interrupt mode, the driver
13294  * will release the interrupt vector(s) for the message signaled interrupt.
13295  **/
13296 static void
13297 lpfc_sli4_disable_intr(struct lpfc_hba *phba)
13298 {
13299 	/* Disable the currently initialized interrupt mode */
13300 	if (phba->intr_type == MSIX) {
13301 		int index;
13302 		struct lpfc_hba_eq_hdl *eqhdl;
13303 
13304 		/* Free up MSI-X multi-message vectors */
13305 		for (index = 0; index < phba->cfg_irq_chann; index++) {
13306 			eqhdl = lpfc_get_eq_hdl(index);
13307 			lpfc_irq_clear_aff(eqhdl);
13308 			free_irq(eqhdl->irq, eqhdl);
13309 		}
13310 	} else {
13311 		free_irq(phba->pcidev->irq, phba);
13312 	}
13313 
13314 	pci_free_irq_vectors(phba->pcidev);
13315 
13316 	/* Reset interrupt management states */
13317 	phba->intr_type = NONE;
13318 	phba->sli.slistat.sli_intr = 0;
13319 }
13320 
13321 /**
13322  * lpfc_unset_hba - Unset SLI3 hba device initialization
13323  * @phba: pointer to lpfc hba data structure.
13324  *
13325  * This routine is invoked to unset the HBA device initialization steps to
13326  * a device with SLI-3 interface spec.
13327  **/
13328 static void
13329 lpfc_unset_hba(struct lpfc_hba *phba)
13330 {
13331 	struct lpfc_vport *vport = phba->pport;
13332 	struct Scsi_Host  *shost = lpfc_shost_from_vport(vport);
13333 
13334 	spin_lock_irq(shost->host_lock);
13335 	vport->load_flag |= FC_UNLOADING;
13336 	spin_unlock_irq(shost->host_lock);
13337 
13338 	kfree(phba->vpi_bmask);
13339 	kfree(phba->vpi_ids);
13340 
13341 	lpfc_stop_hba_timers(phba);
13342 
13343 	phba->pport->work_port_events = 0;
13344 
13345 	lpfc_sli_hba_down(phba);
13346 
13347 	lpfc_sli_brdrestart(phba);
13348 
13349 	lpfc_sli_disable_intr(phba);
13350 
13351 	return;
13352 }
13353 
13354 /**
13355  * lpfc_sli4_xri_exchange_busy_wait - Wait for device XRI exchange busy
13356  * @phba: Pointer to HBA context object.
13357  *
13358  * This function is called in the SLI4 code path to wait for completion
13359  * of device's XRIs exchange busy. It will check the XRI exchange busy
13360  * on outstanding FCP and ELS I/Os every 10ms for up to 10 seconds; after
13361  * that, it will check the XRI exchange busy on outstanding FCP and ELS
13362  * I/Os every 30 seconds, log error message, and wait forever. Only when
13363  * all XRI exchange busy complete, the driver unload shall proceed with
13364  * invoking the function reset ioctl mailbox command to the CNA and the
13365  * the rest of the driver unload resource release.
13366  **/
13367 static void
13368 lpfc_sli4_xri_exchange_busy_wait(struct lpfc_hba *phba)
13369 {
13370 	struct lpfc_sli4_hdw_queue *qp;
13371 	int idx, ccnt;
13372 	int wait_time = 0;
13373 	int io_xri_cmpl = 1;
13374 	int nvmet_xri_cmpl = 1;
13375 	int els_xri_cmpl = list_empty(&phba->sli4_hba.lpfc_abts_els_sgl_list);
13376 
13377 	/* Driver just aborted IOs during the hba_unset process.  Pause
13378 	 * here to give the HBA time to complete the IO and get entries
13379 	 * into the abts lists.
13380 	 */
13381 	msleep(LPFC_XRI_EXCH_BUSY_WAIT_T1 * 5);
13382 
13383 	/* Wait for NVME pending IO to flush back to transport. */
13384 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
13385 		lpfc_nvme_wait_for_io_drain(phba);
13386 
13387 	ccnt = 0;
13388 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
13389 		qp = &phba->sli4_hba.hdwq[idx];
13390 		io_xri_cmpl = list_empty(&qp->lpfc_abts_io_buf_list);
13391 		if (!io_xri_cmpl) /* if list is NOT empty */
13392 			ccnt++;
13393 	}
13394 	if (ccnt)
13395 		io_xri_cmpl = 0;
13396 
13397 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13398 		nvmet_xri_cmpl =
13399 			list_empty(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
13400 	}
13401 
13402 	while (!els_xri_cmpl || !io_xri_cmpl || !nvmet_xri_cmpl) {
13403 		if (wait_time > LPFC_XRI_EXCH_BUSY_WAIT_TMO) {
13404 			if (!nvmet_xri_cmpl)
13405 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13406 						"6424 NVMET XRI exchange busy "
13407 						"wait time: %d seconds.\n",
13408 						wait_time/1000);
13409 			if (!io_xri_cmpl)
13410 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13411 						"6100 IO XRI exchange busy "
13412 						"wait time: %d seconds.\n",
13413 						wait_time/1000);
13414 			if (!els_xri_cmpl)
13415 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13416 						"2878 ELS XRI exchange busy "
13417 						"wait time: %d seconds.\n",
13418 						wait_time/1000);
13419 			msleep(LPFC_XRI_EXCH_BUSY_WAIT_T2);
13420 			wait_time += LPFC_XRI_EXCH_BUSY_WAIT_T2;
13421 		} else {
13422 			msleep(LPFC_XRI_EXCH_BUSY_WAIT_T1);
13423 			wait_time += LPFC_XRI_EXCH_BUSY_WAIT_T1;
13424 		}
13425 
13426 		ccnt = 0;
13427 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
13428 			qp = &phba->sli4_hba.hdwq[idx];
13429 			io_xri_cmpl = list_empty(
13430 			    &qp->lpfc_abts_io_buf_list);
13431 			if (!io_xri_cmpl) /* if list is NOT empty */
13432 				ccnt++;
13433 		}
13434 		if (ccnt)
13435 			io_xri_cmpl = 0;
13436 
13437 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13438 			nvmet_xri_cmpl = list_empty(
13439 				&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
13440 		}
13441 		els_xri_cmpl =
13442 			list_empty(&phba->sli4_hba.lpfc_abts_els_sgl_list);
13443 
13444 	}
13445 }
13446 
13447 /**
13448  * lpfc_sli4_hba_unset - Unset the fcoe hba
13449  * @phba: Pointer to HBA context object.
13450  *
13451  * This function is called in the SLI4 code path to reset the HBA's FCoE
13452  * function. The caller is not required to hold any lock. This routine
13453  * issues PCI function reset mailbox command to reset the FCoE function.
13454  * At the end of the function, it calls lpfc_hba_down_post function to
13455  * free any pending commands.
13456  **/
13457 static void
13458 lpfc_sli4_hba_unset(struct lpfc_hba *phba)
13459 {
13460 	int wait_cnt = 0;
13461 	LPFC_MBOXQ_t *mboxq;
13462 	struct pci_dev *pdev = phba->pcidev;
13463 
13464 	lpfc_stop_hba_timers(phba);
13465 	hrtimer_cancel(&phba->cmf_timer);
13466 
13467 	if (phba->pport)
13468 		phba->sli4_hba.intr_enable = 0;
13469 
13470 	/*
13471 	 * Gracefully wait out the potential current outstanding asynchronous
13472 	 * mailbox command.
13473 	 */
13474 
13475 	/* First, block any pending async mailbox command from posted */
13476 	spin_lock_irq(&phba->hbalock);
13477 	phba->sli.sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
13478 	spin_unlock_irq(&phba->hbalock);
13479 	/* Now, trying to wait it out if we can */
13480 	while (phba->sli.sli_flag & LPFC_SLI_MBOX_ACTIVE) {
13481 		msleep(10);
13482 		if (++wait_cnt > LPFC_ACTIVE_MBOX_WAIT_CNT)
13483 			break;
13484 	}
13485 	/* Forcefully release the outstanding mailbox command if timed out */
13486 	if (phba->sli.sli_flag & LPFC_SLI_MBOX_ACTIVE) {
13487 		spin_lock_irq(&phba->hbalock);
13488 		mboxq = phba->sli.mbox_active;
13489 		mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
13490 		__lpfc_mbox_cmpl_put(phba, mboxq);
13491 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
13492 		phba->sli.mbox_active = NULL;
13493 		spin_unlock_irq(&phba->hbalock);
13494 	}
13495 
13496 	/* Abort all iocbs associated with the hba */
13497 	lpfc_sli_hba_iocb_abort(phba);
13498 
13499 	if (!pci_channel_offline(phba->pcidev))
13500 		/* Wait for completion of device XRI exchange busy */
13501 		lpfc_sli4_xri_exchange_busy_wait(phba);
13502 
13503 	/* per-phba callback de-registration for hotplug event */
13504 	if (phba->pport)
13505 		lpfc_cpuhp_remove(phba);
13506 
13507 	/* Disable PCI subsystem interrupt */
13508 	lpfc_sli4_disable_intr(phba);
13509 
13510 	/* Disable SR-IOV if enabled */
13511 	if (phba->cfg_sriov_nr_virtfn)
13512 		pci_disable_sriov(pdev);
13513 
13514 	/* Stop kthread signal shall trigger work_done one more time */
13515 	kthread_stop(phba->worker_thread);
13516 
13517 	/* Disable FW logging to host memory */
13518 	lpfc_ras_stop_fwlog(phba);
13519 
13520 	/* Reset SLI4 HBA FCoE function */
13521 	lpfc_pci_function_reset(phba);
13522 
13523 	/* release all queue allocated resources. */
13524 	lpfc_sli4_queue_destroy(phba);
13525 
13526 	/* Free RAS DMA memory */
13527 	if (phba->ras_fwlog.ras_enabled)
13528 		lpfc_sli4_ras_dma_free(phba);
13529 
13530 	/* Stop the SLI4 device port */
13531 	if (phba->pport)
13532 		phba->pport->work_port_events = 0;
13533 }
13534 
13535 static uint32_t
13536 lpfc_cgn_crc32(uint32_t crc, u8 byte)
13537 {
13538 	uint32_t msb = 0;
13539 	uint32_t bit;
13540 
13541 	for (bit = 0; bit < 8; bit++) {
13542 		msb = (crc >> 31) & 1;
13543 		crc <<= 1;
13544 
13545 		if (msb ^ (byte & 1)) {
13546 			crc ^= LPFC_CGN_CRC32_MAGIC_NUMBER;
13547 			crc |= 1;
13548 		}
13549 		byte >>= 1;
13550 	}
13551 	return crc;
13552 }
13553 
13554 static uint32_t
13555 lpfc_cgn_reverse_bits(uint32_t wd)
13556 {
13557 	uint32_t result = 0;
13558 	uint32_t i;
13559 
13560 	for (i = 0; i < 32; i++) {
13561 		result <<= 1;
13562 		result |= (1 & (wd >> i));
13563 	}
13564 	return result;
13565 }
13566 
13567 /*
13568  * The routine corresponds with the algorithm the HBA firmware
13569  * uses to validate the data integrity.
13570  */
13571 uint32_t
13572 lpfc_cgn_calc_crc32(void *ptr, uint32_t byteLen, uint32_t crc)
13573 {
13574 	uint32_t  i;
13575 	uint32_t result;
13576 	uint8_t  *data = (uint8_t *)ptr;
13577 
13578 	for (i = 0; i < byteLen; ++i)
13579 		crc = lpfc_cgn_crc32(crc, data[i]);
13580 
13581 	result = ~lpfc_cgn_reverse_bits(crc);
13582 	return result;
13583 }
13584 
13585 void
13586 lpfc_init_congestion_buf(struct lpfc_hba *phba)
13587 {
13588 	struct lpfc_cgn_info *cp;
13589 	struct timespec64 cmpl_time;
13590 	struct tm broken;
13591 	uint16_t size;
13592 	uint32_t crc;
13593 
13594 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
13595 			"6235 INIT Congestion Buffer %p\n", phba->cgn_i);
13596 
13597 	if (!phba->cgn_i)
13598 		return;
13599 	cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
13600 
13601 	atomic_set(&phba->cgn_fabric_warn_cnt, 0);
13602 	atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
13603 	atomic_set(&phba->cgn_sync_alarm_cnt, 0);
13604 	atomic_set(&phba->cgn_sync_warn_cnt, 0);
13605 
13606 	atomic_set(&phba->cgn_driver_evt_cnt, 0);
13607 	atomic_set(&phba->cgn_latency_evt_cnt, 0);
13608 	atomic64_set(&phba->cgn_latency_evt, 0);
13609 	phba->cgn_evt_minute = 0;
13610 	phba->hba_flag &= ~HBA_CGN_DAY_WRAP;
13611 
13612 	memset(cp, 0xff, offsetof(struct lpfc_cgn_info, cgn_stat));
13613 	cp->cgn_info_size = cpu_to_le16(LPFC_CGN_INFO_SZ);
13614 	cp->cgn_info_version = LPFC_CGN_INFO_V3;
13615 
13616 	/* cgn parameters */
13617 	cp->cgn_info_mode = phba->cgn_p.cgn_param_mode;
13618 	cp->cgn_info_level0 = phba->cgn_p.cgn_param_level0;
13619 	cp->cgn_info_level1 = phba->cgn_p.cgn_param_level1;
13620 	cp->cgn_info_level2 = phba->cgn_p.cgn_param_level2;
13621 
13622 	ktime_get_real_ts64(&cmpl_time);
13623 	time64_to_tm(cmpl_time.tv_sec, 0, &broken);
13624 
13625 	cp->cgn_info_month = broken.tm_mon + 1;
13626 	cp->cgn_info_day = broken.tm_mday;
13627 	cp->cgn_info_year = broken.tm_year - 100; /* relative to 2000 */
13628 	cp->cgn_info_hour = broken.tm_hour;
13629 	cp->cgn_info_minute = broken.tm_min;
13630 	cp->cgn_info_second = broken.tm_sec;
13631 
13632 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT | LOG_INIT,
13633 			"2643 CGNInfo Init: Start Time "
13634 			"%d/%d/%d %d:%d:%d\n",
13635 			cp->cgn_info_day, cp->cgn_info_month,
13636 			cp->cgn_info_year, cp->cgn_info_hour,
13637 			cp->cgn_info_minute, cp->cgn_info_second);
13638 
13639 	/* Fill in default LUN qdepth */
13640 	if (phba->pport) {
13641 		size = (uint16_t)(phba->pport->cfg_lun_queue_depth);
13642 		cp->cgn_lunq = cpu_to_le16(size);
13643 	}
13644 
13645 	/* last used Index initialized to 0xff already */
13646 
13647 	cp->cgn_warn_freq = cpu_to_le16(LPFC_FPIN_INIT_FREQ);
13648 	cp->cgn_alarm_freq = cpu_to_le16(LPFC_FPIN_INIT_FREQ);
13649 	crc = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ, LPFC_CGN_CRC32_SEED);
13650 	cp->cgn_info_crc = cpu_to_le32(crc);
13651 
13652 	phba->cgn_evt_timestamp = jiffies +
13653 		msecs_to_jiffies(LPFC_CGN_TIMER_TO_MIN);
13654 }
13655 
13656 void
13657 lpfc_init_congestion_stat(struct lpfc_hba *phba)
13658 {
13659 	struct lpfc_cgn_info *cp;
13660 	struct timespec64 cmpl_time;
13661 	struct tm broken;
13662 	uint32_t crc;
13663 
13664 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
13665 			"6236 INIT Congestion Stat %p\n", phba->cgn_i);
13666 
13667 	if (!phba->cgn_i)
13668 		return;
13669 
13670 	cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
13671 	memset(&cp->cgn_stat, 0, sizeof(cp->cgn_stat));
13672 
13673 	ktime_get_real_ts64(&cmpl_time);
13674 	time64_to_tm(cmpl_time.tv_sec, 0, &broken);
13675 
13676 	cp->cgn_stat_month = broken.tm_mon + 1;
13677 	cp->cgn_stat_day = broken.tm_mday;
13678 	cp->cgn_stat_year = broken.tm_year - 100; /* relative to 2000 */
13679 	cp->cgn_stat_hour = broken.tm_hour;
13680 	cp->cgn_stat_minute = broken.tm_min;
13681 
13682 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT | LOG_INIT,
13683 			"2647 CGNstat Init: Start Time "
13684 			"%d/%d/%d %d:%d\n",
13685 			cp->cgn_stat_day, cp->cgn_stat_month,
13686 			cp->cgn_stat_year, cp->cgn_stat_hour,
13687 			cp->cgn_stat_minute);
13688 
13689 	crc = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ, LPFC_CGN_CRC32_SEED);
13690 	cp->cgn_info_crc = cpu_to_le32(crc);
13691 }
13692 
13693 /**
13694  * __lpfc_reg_congestion_buf - register congestion info buffer with HBA
13695  * @phba: Pointer to hba context object.
13696  * @reg: flag to determine register or unregister.
13697  */
13698 static int
13699 __lpfc_reg_congestion_buf(struct lpfc_hba *phba, int reg)
13700 {
13701 	struct lpfc_mbx_reg_congestion_buf *reg_congestion_buf;
13702 	union  lpfc_sli4_cfg_shdr *shdr;
13703 	uint32_t shdr_status, shdr_add_status;
13704 	LPFC_MBOXQ_t *mboxq;
13705 	int length, rc;
13706 
13707 	if (!phba->cgn_i)
13708 		return -ENXIO;
13709 
13710 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
13711 	if (!mboxq) {
13712 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX,
13713 				"2641 REG_CONGESTION_BUF mbox allocation fail: "
13714 				"HBA state x%x reg %d\n",
13715 				phba->pport->port_state, reg);
13716 		return -ENOMEM;
13717 	}
13718 
13719 	length = (sizeof(struct lpfc_mbx_reg_congestion_buf) -
13720 		sizeof(struct lpfc_sli4_cfg_mhdr));
13721 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
13722 			 LPFC_MBOX_OPCODE_REG_CONGESTION_BUF, length,
13723 			 LPFC_SLI4_MBX_EMBED);
13724 	reg_congestion_buf = &mboxq->u.mqe.un.reg_congestion_buf;
13725 	bf_set(lpfc_mbx_reg_cgn_buf_type, reg_congestion_buf, 1);
13726 	if (reg > 0)
13727 		bf_set(lpfc_mbx_reg_cgn_buf_cnt, reg_congestion_buf, 1);
13728 	else
13729 		bf_set(lpfc_mbx_reg_cgn_buf_cnt, reg_congestion_buf, 0);
13730 	reg_congestion_buf->length = sizeof(struct lpfc_cgn_info);
13731 	reg_congestion_buf->addr_lo =
13732 		putPaddrLow(phba->cgn_i->phys);
13733 	reg_congestion_buf->addr_hi =
13734 		putPaddrHigh(phba->cgn_i->phys);
13735 
13736 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
13737 	shdr = (union lpfc_sli4_cfg_shdr *)
13738 		&mboxq->u.mqe.un.sli4_config.header.cfg_shdr;
13739 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13740 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
13741 				 &shdr->response);
13742 	mempool_free(mboxq, phba->mbox_mem_pool);
13743 	if (shdr_status || shdr_add_status || rc) {
13744 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13745 				"2642 REG_CONGESTION_BUF mailbox "
13746 				"failed with status x%x add_status x%x,"
13747 				" mbx status x%x reg %d\n",
13748 				shdr_status, shdr_add_status, rc, reg);
13749 		return -ENXIO;
13750 	}
13751 	return 0;
13752 }
13753 
13754 int
13755 lpfc_unreg_congestion_buf(struct lpfc_hba *phba)
13756 {
13757 	lpfc_cmf_stop(phba);
13758 	return __lpfc_reg_congestion_buf(phba, 0);
13759 }
13760 
13761 int
13762 lpfc_reg_congestion_buf(struct lpfc_hba *phba)
13763 {
13764 	return __lpfc_reg_congestion_buf(phba, 1);
13765 }
13766 
13767 /**
13768  * lpfc_get_sli4_parameters - Get the SLI4 Config PARAMETERS.
13769  * @phba: Pointer to HBA context object.
13770  * @mboxq: Pointer to the mailboxq memory for the mailbox command response.
13771  *
13772  * This function is called in the SLI4 code path to read the port's
13773  * sli4 capabilities.
13774  *
13775  * This function may be be called from any context that can block-wait
13776  * for the completion.  The expectation is that this routine is called
13777  * typically from probe_one or from the online routine.
13778  **/
13779 int
13780 lpfc_get_sli4_parameters(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
13781 {
13782 	int rc;
13783 	struct lpfc_mqe *mqe = &mboxq->u.mqe;
13784 	struct lpfc_pc_sli4_params *sli4_params;
13785 	uint32_t mbox_tmo;
13786 	int length;
13787 	bool exp_wqcq_pages = true;
13788 	struct lpfc_sli4_parameters *mbx_sli4_parameters;
13789 
13790 	/*
13791 	 * By default, the driver assumes the SLI4 port requires RPI
13792 	 * header postings.  The SLI4_PARAM response will correct this
13793 	 * assumption.
13794 	 */
13795 	phba->sli4_hba.rpi_hdrs_in_use = 1;
13796 
13797 	/* Read the port's SLI4 Config Parameters */
13798 	length = (sizeof(struct lpfc_mbx_get_sli4_parameters) -
13799 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13800 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
13801 			 LPFC_MBOX_OPCODE_GET_SLI4_PARAMETERS,
13802 			 length, LPFC_SLI4_MBX_EMBED);
13803 	if (!phba->sli4_hba.intr_enable)
13804 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
13805 	else {
13806 		mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
13807 		rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
13808 	}
13809 	if (unlikely(rc))
13810 		return rc;
13811 	sli4_params = &phba->sli4_hba.pc_sli4_params;
13812 	mbx_sli4_parameters = &mqe->un.get_sli4_parameters.sli4_parameters;
13813 	sli4_params->if_type = bf_get(cfg_if_type, mbx_sli4_parameters);
13814 	sli4_params->sli_rev = bf_get(cfg_sli_rev, mbx_sli4_parameters);
13815 	sli4_params->sli_family = bf_get(cfg_sli_family, mbx_sli4_parameters);
13816 	sli4_params->featurelevel_1 = bf_get(cfg_sli_hint_1,
13817 					     mbx_sli4_parameters);
13818 	sli4_params->featurelevel_2 = bf_get(cfg_sli_hint_2,
13819 					     mbx_sli4_parameters);
13820 	if (bf_get(cfg_phwq, mbx_sli4_parameters))
13821 		phba->sli3_options |= LPFC_SLI4_PHWQ_ENABLED;
13822 	else
13823 		phba->sli3_options &= ~LPFC_SLI4_PHWQ_ENABLED;
13824 	sli4_params->sge_supp_len = mbx_sli4_parameters->sge_supp_len;
13825 	sli4_params->loopbk_scope = bf_get(cfg_loopbk_scope,
13826 					   mbx_sli4_parameters);
13827 	sli4_params->oas_supported = bf_get(cfg_oas, mbx_sli4_parameters);
13828 	sli4_params->cqv = bf_get(cfg_cqv, mbx_sli4_parameters);
13829 	sli4_params->mqv = bf_get(cfg_mqv, mbx_sli4_parameters);
13830 	sli4_params->wqv = bf_get(cfg_wqv, mbx_sli4_parameters);
13831 	sli4_params->rqv = bf_get(cfg_rqv, mbx_sli4_parameters);
13832 	sli4_params->eqav = bf_get(cfg_eqav, mbx_sli4_parameters);
13833 	sli4_params->cqav = bf_get(cfg_cqav, mbx_sli4_parameters);
13834 	sli4_params->wqsize = bf_get(cfg_wqsize, mbx_sli4_parameters);
13835 	sli4_params->bv1s = bf_get(cfg_bv1s, mbx_sli4_parameters);
13836 	sli4_params->pls = bf_get(cfg_pvl, mbx_sli4_parameters);
13837 	sli4_params->sgl_pages_max = bf_get(cfg_sgl_page_cnt,
13838 					    mbx_sli4_parameters);
13839 	sli4_params->wqpcnt = bf_get(cfg_wqpcnt, mbx_sli4_parameters);
13840 	sli4_params->sgl_pp_align = bf_get(cfg_sgl_pp_align,
13841 					   mbx_sli4_parameters);
13842 	phba->sli4_hba.extents_in_use = bf_get(cfg_ext, mbx_sli4_parameters);
13843 	phba->sli4_hba.rpi_hdrs_in_use = bf_get(cfg_hdrr, mbx_sli4_parameters);
13844 
13845 	/* Check for Extended Pre-Registered SGL support */
13846 	phba->cfg_xpsgl = bf_get(cfg_xpsgl, mbx_sli4_parameters);
13847 
13848 	/* Check for firmware nvme support */
13849 	rc = (bf_get(cfg_nvme, mbx_sli4_parameters) &&
13850 		     bf_get(cfg_xib, mbx_sli4_parameters));
13851 
13852 	if (rc) {
13853 		/* Save this to indicate the Firmware supports NVME */
13854 		sli4_params->nvme = 1;
13855 
13856 		/* Firmware NVME support, check driver FC4 NVME support */
13857 		if (phba->cfg_enable_fc4_type == LPFC_ENABLE_FCP) {
13858 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_NVME,
13859 					"6133 Disabling NVME support: "
13860 					"FC4 type not supported: x%x\n",
13861 					phba->cfg_enable_fc4_type);
13862 			goto fcponly;
13863 		}
13864 	} else {
13865 		/* No firmware NVME support, check driver FC4 NVME support */
13866 		sli4_params->nvme = 0;
13867 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13868 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_NVME,
13869 					"6101 Disabling NVME support: Not "
13870 					"supported by firmware (%d %d) x%x\n",
13871 					bf_get(cfg_nvme, mbx_sli4_parameters),
13872 					bf_get(cfg_xib, mbx_sli4_parameters),
13873 					phba->cfg_enable_fc4_type);
13874 fcponly:
13875 			phba->nvmet_support = 0;
13876 			phba->cfg_nvmet_mrq = 0;
13877 			phba->cfg_nvme_seg_cnt = 0;
13878 
13879 			/* If no FC4 type support, move to just SCSI support */
13880 			if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP))
13881 				return -ENODEV;
13882 			phba->cfg_enable_fc4_type = LPFC_ENABLE_FCP;
13883 		}
13884 	}
13885 
13886 	/* If the NVME FC4 type is enabled, scale the sg_seg_cnt to
13887 	 * accommodate 512K and 1M IOs in a single nvme buf.
13888 	 */
13889 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
13890 		phba->cfg_sg_seg_cnt = LPFC_MAX_NVME_SEG_CNT;
13891 
13892 	/* Enable embedded Payload BDE if support is indicated */
13893 	if (bf_get(cfg_pbde, mbx_sli4_parameters))
13894 		phba->cfg_enable_pbde = 1;
13895 	else
13896 		phba->cfg_enable_pbde = 0;
13897 
13898 	/*
13899 	 * To support Suppress Response feature we must satisfy 3 conditions.
13900 	 * lpfc_suppress_rsp module parameter must be set (default).
13901 	 * In SLI4-Parameters Descriptor:
13902 	 * Extended Inline Buffers (XIB) must be supported.
13903 	 * Suppress Response IU Not Supported (SRIUNS) must NOT be supported
13904 	 * (double negative).
13905 	 */
13906 	if (phba->cfg_suppress_rsp && bf_get(cfg_xib, mbx_sli4_parameters) &&
13907 	    !(bf_get(cfg_nosr, mbx_sli4_parameters)))
13908 		phba->sli.sli_flag |= LPFC_SLI_SUPPRESS_RSP;
13909 	else
13910 		phba->cfg_suppress_rsp = 0;
13911 
13912 	if (bf_get(cfg_eqdr, mbx_sli4_parameters))
13913 		phba->sli.sli_flag |= LPFC_SLI_USE_EQDR;
13914 
13915 	/* Make sure that sge_supp_len can be handled by the driver */
13916 	if (sli4_params->sge_supp_len > LPFC_MAX_SGE_SIZE)
13917 		sli4_params->sge_supp_len = LPFC_MAX_SGE_SIZE;
13918 
13919 	/*
13920 	 * Check whether the adapter supports an embedded copy of the
13921 	 * FCP CMD IU within the WQE for FCP_Ixxx commands. In order
13922 	 * to use this option, 128-byte WQEs must be used.
13923 	 */
13924 	if (bf_get(cfg_ext_embed_cb, mbx_sli4_parameters))
13925 		phba->fcp_embed_io = 1;
13926 	else
13927 		phba->fcp_embed_io = 0;
13928 
13929 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_NVME,
13930 			"6422 XIB %d PBDE %d: FCP %d NVME %d %d %d\n",
13931 			bf_get(cfg_xib, mbx_sli4_parameters),
13932 			phba->cfg_enable_pbde,
13933 			phba->fcp_embed_io, sli4_params->nvme,
13934 			phba->cfg_nvme_embed_cmd, phba->cfg_suppress_rsp);
13935 
13936 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
13937 	    LPFC_SLI_INTF_IF_TYPE_2) &&
13938 	    (bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf) ==
13939 		 LPFC_SLI_INTF_FAMILY_LNCR_A0))
13940 		exp_wqcq_pages = false;
13941 
13942 	if ((bf_get(cfg_cqpsize, mbx_sli4_parameters) & LPFC_CQ_16K_PAGE_SZ) &&
13943 	    (bf_get(cfg_wqpsize, mbx_sli4_parameters) & LPFC_WQ_16K_PAGE_SZ) &&
13944 	    exp_wqcq_pages &&
13945 	    (sli4_params->wqsize & LPFC_WQ_SZ128_SUPPORT))
13946 		phba->enab_exp_wqcq_pages = 1;
13947 	else
13948 		phba->enab_exp_wqcq_pages = 0;
13949 	/*
13950 	 * Check if the SLI port supports MDS Diagnostics
13951 	 */
13952 	if (bf_get(cfg_mds_diags, mbx_sli4_parameters))
13953 		phba->mds_diags_support = 1;
13954 	else
13955 		phba->mds_diags_support = 0;
13956 
13957 	/*
13958 	 * Check if the SLI port supports NSLER
13959 	 */
13960 	if (bf_get(cfg_nsler, mbx_sli4_parameters))
13961 		phba->nsler = 1;
13962 	else
13963 		phba->nsler = 0;
13964 
13965 	return 0;
13966 }
13967 
13968 /**
13969  * lpfc_pci_probe_one_s3 - PCI probe func to reg SLI-3 device to PCI subsystem.
13970  * @pdev: pointer to PCI device
13971  * @pid: pointer to PCI device identifier
13972  *
13973  * This routine is to be called to attach a device with SLI-3 interface spec
13974  * to the PCI subsystem. When an Emulex HBA with SLI-3 interface spec is
13975  * presented on PCI bus, the kernel PCI subsystem looks at PCI device-specific
13976  * information of the device and driver to see if the driver state that it can
13977  * support this kind of device. If the match is successful, the driver core
13978  * invokes this routine. If this routine determines it can claim the HBA, it
13979  * does all the initialization that it needs to do to handle the HBA properly.
13980  *
13981  * Return code
13982  * 	0 - driver can claim the device
13983  * 	negative value - driver can not claim the device
13984  **/
13985 static int
13986 lpfc_pci_probe_one_s3(struct pci_dev *pdev, const struct pci_device_id *pid)
13987 {
13988 	struct lpfc_hba   *phba;
13989 	struct lpfc_vport *vport = NULL;
13990 	struct Scsi_Host  *shost = NULL;
13991 	int error;
13992 	uint32_t cfg_mode, intr_mode;
13993 
13994 	/* Allocate memory for HBA structure */
13995 	phba = lpfc_hba_alloc(pdev);
13996 	if (!phba)
13997 		return -ENOMEM;
13998 
13999 	/* Perform generic PCI device enabling operation */
14000 	error = lpfc_enable_pci_dev(phba);
14001 	if (error)
14002 		goto out_free_phba;
14003 
14004 	/* Set up SLI API function jump table for PCI-device group-0 HBAs */
14005 	error = lpfc_api_table_setup(phba, LPFC_PCI_DEV_LP);
14006 	if (error)
14007 		goto out_disable_pci_dev;
14008 
14009 	/* Set up SLI-3 specific device PCI memory space */
14010 	error = lpfc_sli_pci_mem_setup(phba);
14011 	if (error) {
14012 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14013 				"1402 Failed to set up pci memory space.\n");
14014 		goto out_disable_pci_dev;
14015 	}
14016 
14017 	/* Set up SLI-3 specific device driver resources */
14018 	error = lpfc_sli_driver_resource_setup(phba);
14019 	if (error) {
14020 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14021 				"1404 Failed to set up driver resource.\n");
14022 		goto out_unset_pci_mem_s3;
14023 	}
14024 
14025 	/* Initialize and populate the iocb list per host */
14026 
14027 	error = lpfc_init_iocb_list(phba, LPFC_IOCB_LIST_CNT);
14028 	if (error) {
14029 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14030 				"1405 Failed to initialize iocb list.\n");
14031 		goto out_unset_driver_resource_s3;
14032 	}
14033 
14034 	/* Set up common device driver resources */
14035 	error = lpfc_setup_driver_resource_phase2(phba);
14036 	if (error) {
14037 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14038 				"1406 Failed to set up driver resource.\n");
14039 		goto out_free_iocb_list;
14040 	}
14041 
14042 	/* Get the default values for Model Name and Description */
14043 	lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
14044 
14045 	/* Create SCSI host to the physical port */
14046 	error = lpfc_create_shost(phba);
14047 	if (error) {
14048 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14049 				"1407 Failed to create scsi host.\n");
14050 		goto out_unset_driver_resource;
14051 	}
14052 
14053 	/* Configure sysfs attributes */
14054 	vport = phba->pport;
14055 	error = lpfc_alloc_sysfs_attr(vport);
14056 	if (error) {
14057 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14058 				"1476 Failed to allocate sysfs attr\n");
14059 		goto out_destroy_shost;
14060 	}
14061 
14062 	shost = lpfc_shost_from_vport(vport); /* save shost for error cleanup */
14063 	/* Now, trying to enable interrupt and bring up the device */
14064 	cfg_mode = phba->cfg_use_msi;
14065 	while (true) {
14066 		/* Put device to a known state before enabling interrupt */
14067 		lpfc_stop_port(phba);
14068 		/* Configure and enable interrupt */
14069 		intr_mode = lpfc_sli_enable_intr(phba, cfg_mode);
14070 		if (intr_mode == LPFC_INTR_ERROR) {
14071 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14072 					"0431 Failed to enable interrupt.\n");
14073 			error = -ENODEV;
14074 			goto out_free_sysfs_attr;
14075 		}
14076 		/* SLI-3 HBA setup */
14077 		if (lpfc_sli_hba_setup(phba)) {
14078 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14079 					"1477 Failed to set up hba\n");
14080 			error = -ENODEV;
14081 			goto out_remove_device;
14082 		}
14083 
14084 		/* Wait 50ms for the interrupts of previous mailbox commands */
14085 		msleep(50);
14086 		/* Check active interrupts on message signaled interrupts */
14087 		if (intr_mode == 0 ||
14088 		    phba->sli.slistat.sli_intr > LPFC_MSIX_VECTORS) {
14089 			/* Log the current active interrupt mode */
14090 			phba->intr_mode = intr_mode;
14091 			lpfc_log_intr_mode(phba, intr_mode);
14092 			break;
14093 		} else {
14094 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
14095 					"0447 Configure interrupt mode (%d) "
14096 					"failed active interrupt test.\n",
14097 					intr_mode);
14098 			/* Disable the current interrupt mode */
14099 			lpfc_sli_disable_intr(phba);
14100 			/* Try next level of interrupt mode */
14101 			cfg_mode = --intr_mode;
14102 		}
14103 	}
14104 
14105 	/* Perform post initialization setup */
14106 	lpfc_post_init_setup(phba);
14107 
14108 	/* Check if there are static vports to be created. */
14109 	lpfc_create_static_vport(phba);
14110 
14111 	return 0;
14112 
14113 out_remove_device:
14114 	lpfc_unset_hba(phba);
14115 out_free_sysfs_attr:
14116 	lpfc_free_sysfs_attr(vport);
14117 out_destroy_shost:
14118 	lpfc_destroy_shost(phba);
14119 out_unset_driver_resource:
14120 	lpfc_unset_driver_resource_phase2(phba);
14121 out_free_iocb_list:
14122 	lpfc_free_iocb_list(phba);
14123 out_unset_driver_resource_s3:
14124 	lpfc_sli_driver_resource_unset(phba);
14125 out_unset_pci_mem_s3:
14126 	lpfc_sli_pci_mem_unset(phba);
14127 out_disable_pci_dev:
14128 	lpfc_disable_pci_dev(phba);
14129 	if (shost)
14130 		scsi_host_put(shost);
14131 out_free_phba:
14132 	lpfc_hba_free(phba);
14133 	return error;
14134 }
14135 
14136 /**
14137  * lpfc_pci_remove_one_s3 - PCI func to unreg SLI-3 device from PCI subsystem.
14138  * @pdev: pointer to PCI device
14139  *
14140  * This routine is to be called to disattach a device with SLI-3 interface
14141  * spec from PCI subsystem. When an Emulex HBA with SLI-3 interface spec is
14142  * removed from PCI bus, it performs all the necessary cleanup for the HBA
14143  * device to be removed from the PCI subsystem properly.
14144  **/
14145 static void
14146 lpfc_pci_remove_one_s3(struct pci_dev *pdev)
14147 {
14148 	struct Scsi_Host  *shost = pci_get_drvdata(pdev);
14149 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
14150 	struct lpfc_vport **vports;
14151 	struct lpfc_hba   *phba = vport->phba;
14152 	int i;
14153 
14154 	spin_lock_irq(&phba->hbalock);
14155 	vport->load_flag |= FC_UNLOADING;
14156 	spin_unlock_irq(&phba->hbalock);
14157 
14158 	lpfc_free_sysfs_attr(vport);
14159 
14160 	/* Release all the vports against this physical port */
14161 	vports = lpfc_create_vport_work_array(phba);
14162 	if (vports != NULL)
14163 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
14164 			if (vports[i]->port_type == LPFC_PHYSICAL_PORT)
14165 				continue;
14166 			fc_vport_terminate(vports[i]->fc_vport);
14167 		}
14168 	lpfc_destroy_vport_work_array(phba, vports);
14169 
14170 	/* Remove FC host with the physical port */
14171 	fc_remove_host(shost);
14172 	scsi_remove_host(shost);
14173 
14174 	/* Clean up all nodes, mailboxes and IOs. */
14175 	lpfc_cleanup(vport);
14176 
14177 	/*
14178 	 * Bring down the SLI Layer. This step disable all interrupts,
14179 	 * clears the rings, discards all mailbox commands, and resets
14180 	 * the HBA.
14181 	 */
14182 
14183 	/* HBA interrupt will be disabled after this call */
14184 	lpfc_sli_hba_down(phba);
14185 	/* Stop kthread signal shall trigger work_done one more time */
14186 	kthread_stop(phba->worker_thread);
14187 	/* Final cleanup of txcmplq and reset the HBA */
14188 	lpfc_sli_brdrestart(phba);
14189 
14190 	kfree(phba->vpi_bmask);
14191 	kfree(phba->vpi_ids);
14192 
14193 	lpfc_stop_hba_timers(phba);
14194 	spin_lock_irq(&phba->port_list_lock);
14195 	list_del_init(&vport->listentry);
14196 	spin_unlock_irq(&phba->port_list_lock);
14197 
14198 	lpfc_debugfs_terminate(vport);
14199 
14200 	/* Disable SR-IOV if enabled */
14201 	if (phba->cfg_sriov_nr_virtfn)
14202 		pci_disable_sriov(pdev);
14203 
14204 	/* Disable interrupt */
14205 	lpfc_sli_disable_intr(phba);
14206 
14207 	scsi_host_put(shost);
14208 
14209 	/*
14210 	 * Call scsi_free before mem_free since scsi bufs are released to their
14211 	 * corresponding pools here.
14212 	 */
14213 	lpfc_scsi_free(phba);
14214 	lpfc_free_iocb_list(phba);
14215 
14216 	lpfc_mem_free_all(phba);
14217 
14218 	dma_free_coherent(&pdev->dev, lpfc_sli_hbq_size(),
14219 			  phba->hbqslimp.virt, phba->hbqslimp.phys);
14220 
14221 	/* Free resources associated with SLI2 interface */
14222 	dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
14223 			  phba->slim2p.virt, phba->slim2p.phys);
14224 
14225 	/* unmap adapter SLIM and Control Registers */
14226 	iounmap(phba->ctrl_regs_memmap_p);
14227 	iounmap(phba->slim_memmap_p);
14228 
14229 	lpfc_hba_free(phba);
14230 
14231 	pci_release_mem_regions(pdev);
14232 	pci_disable_device(pdev);
14233 }
14234 
14235 /**
14236  * lpfc_pci_suspend_one_s3 - PCI func to suspend SLI-3 device for power mgmnt
14237  * @dev_d: pointer to device
14238  *
14239  * This routine is to be called from the kernel's PCI subsystem to support
14240  * system Power Management (PM) to device with SLI-3 interface spec. When
14241  * PM invokes this method, it quiesces the device by stopping the driver's
14242  * worker thread for the device, turning off device's interrupt and DMA,
14243  * and bring the device offline. Note that as the driver implements the
14244  * minimum PM requirements to a power-aware driver's PM support for the
14245  * suspend/resume -- all the possible PM messages (SUSPEND, HIBERNATE, FREEZE)
14246  * to the suspend() method call will be treated as SUSPEND and the driver will
14247  * fully reinitialize its device during resume() method call, the driver will
14248  * set device to PCI_D3hot state in PCI config space instead of setting it
14249  * according to the @msg provided by the PM.
14250  *
14251  * Return code
14252  * 	0 - driver suspended the device
14253  * 	Error otherwise
14254  **/
14255 static int __maybe_unused
14256 lpfc_pci_suspend_one_s3(struct device *dev_d)
14257 {
14258 	struct Scsi_Host *shost = dev_get_drvdata(dev_d);
14259 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14260 
14261 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
14262 			"0473 PCI device Power Management suspend.\n");
14263 
14264 	/* Bring down the device */
14265 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
14266 	lpfc_offline(phba);
14267 	kthread_stop(phba->worker_thread);
14268 
14269 	/* Disable interrupt from device */
14270 	lpfc_sli_disable_intr(phba);
14271 
14272 	return 0;
14273 }
14274 
14275 /**
14276  * lpfc_pci_resume_one_s3 - PCI func to resume SLI-3 device for power mgmnt
14277  * @dev_d: pointer to device
14278  *
14279  * This routine is to be called from the kernel's PCI subsystem to support
14280  * system Power Management (PM) to device with SLI-3 interface spec. When PM
14281  * invokes this method, it restores the device's PCI config space state and
14282  * fully reinitializes the device and brings it online. Note that as the
14283  * driver implements the minimum PM requirements to a power-aware driver's
14284  * PM for suspend/resume -- all the possible PM messages (SUSPEND, HIBERNATE,
14285  * FREEZE) to the suspend() method call will be treated as SUSPEND and the
14286  * driver will fully reinitialize its device during resume() method call,
14287  * the device will be set to PCI_D0 directly in PCI config space before
14288  * restoring the state.
14289  *
14290  * Return code
14291  * 	0 - driver suspended the device
14292  * 	Error otherwise
14293  **/
14294 static int __maybe_unused
14295 lpfc_pci_resume_one_s3(struct device *dev_d)
14296 {
14297 	struct Scsi_Host *shost = dev_get_drvdata(dev_d);
14298 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14299 	uint32_t intr_mode;
14300 	int error;
14301 
14302 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
14303 			"0452 PCI device Power Management resume.\n");
14304 
14305 	/* Startup the kernel thread for this host adapter. */
14306 	phba->worker_thread = kthread_run(lpfc_do_work, phba,
14307 					"lpfc_worker_%d", phba->brd_no);
14308 	if (IS_ERR(phba->worker_thread)) {
14309 		error = PTR_ERR(phba->worker_thread);
14310 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14311 				"0434 PM resume failed to start worker "
14312 				"thread: error=x%x.\n", error);
14313 		return error;
14314 	}
14315 
14316 	/* Init cpu_map array */
14317 	lpfc_cpu_map_array_init(phba);
14318 	/* Init hba_eq_hdl array */
14319 	lpfc_hba_eq_hdl_array_init(phba);
14320 	/* Configure and enable interrupt */
14321 	intr_mode = lpfc_sli_enable_intr(phba, phba->intr_mode);
14322 	if (intr_mode == LPFC_INTR_ERROR) {
14323 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14324 				"0430 PM resume Failed to enable interrupt\n");
14325 		return -EIO;
14326 	} else
14327 		phba->intr_mode = intr_mode;
14328 
14329 	/* Restart HBA and bring it online */
14330 	lpfc_sli_brdrestart(phba);
14331 	lpfc_online(phba);
14332 
14333 	/* Log the current active interrupt mode */
14334 	lpfc_log_intr_mode(phba, phba->intr_mode);
14335 
14336 	return 0;
14337 }
14338 
14339 /**
14340  * lpfc_sli_prep_dev_for_recover - Prepare SLI3 device for pci slot recover
14341  * @phba: pointer to lpfc hba data structure.
14342  *
14343  * This routine is called to prepare the SLI3 device for PCI slot recover. It
14344  * aborts all the outstanding SCSI I/Os to the pci device.
14345  **/
14346 static void
14347 lpfc_sli_prep_dev_for_recover(struct lpfc_hba *phba)
14348 {
14349 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14350 			"2723 PCI channel I/O abort preparing for recovery\n");
14351 
14352 	/*
14353 	 * There may be errored I/Os through HBA, abort all I/Os on txcmplq
14354 	 * and let the SCSI mid-layer to retry them to recover.
14355 	 */
14356 	lpfc_sli_abort_fcp_rings(phba);
14357 }
14358 
14359 /**
14360  * lpfc_sli_prep_dev_for_reset - Prepare SLI3 device for pci slot reset
14361  * @phba: pointer to lpfc hba data structure.
14362  *
14363  * This routine is called to prepare the SLI3 device for PCI slot reset. It
14364  * disables the device interrupt and pci device, and aborts the internal FCP
14365  * pending I/Os.
14366  **/
14367 static void
14368 lpfc_sli_prep_dev_for_reset(struct lpfc_hba *phba)
14369 {
14370 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14371 			"2710 PCI channel disable preparing for reset\n");
14372 
14373 	/* Block any management I/Os to the device */
14374 	lpfc_block_mgmt_io(phba, LPFC_MBX_WAIT);
14375 
14376 	/* Block all SCSI devices' I/Os on the host */
14377 	lpfc_scsi_dev_block(phba);
14378 
14379 	/* Flush all driver's outstanding SCSI I/Os as we are to reset */
14380 	lpfc_sli_flush_io_rings(phba);
14381 
14382 	/* stop all timers */
14383 	lpfc_stop_hba_timers(phba);
14384 
14385 	/* Disable interrupt and pci device */
14386 	lpfc_sli_disable_intr(phba);
14387 	pci_disable_device(phba->pcidev);
14388 }
14389 
14390 /**
14391  * lpfc_sli_prep_dev_for_perm_failure - Prepare SLI3 dev for pci slot disable
14392  * @phba: pointer to lpfc hba data structure.
14393  *
14394  * This routine is called to prepare the SLI3 device for PCI slot permanently
14395  * disabling. It blocks the SCSI transport layer traffic and flushes the FCP
14396  * pending I/Os.
14397  **/
14398 static void
14399 lpfc_sli_prep_dev_for_perm_failure(struct lpfc_hba *phba)
14400 {
14401 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14402 			"2711 PCI channel permanent disable for failure\n");
14403 	/* Block all SCSI devices' I/Os on the host */
14404 	lpfc_scsi_dev_block(phba);
14405 	lpfc_sli4_prep_dev_for_reset(phba);
14406 
14407 	/* stop all timers */
14408 	lpfc_stop_hba_timers(phba);
14409 
14410 	/* Clean up all driver's outstanding SCSI I/Os */
14411 	lpfc_sli_flush_io_rings(phba);
14412 }
14413 
14414 /**
14415  * lpfc_io_error_detected_s3 - Method for handling SLI-3 device PCI I/O error
14416  * @pdev: pointer to PCI device.
14417  * @state: the current PCI connection state.
14418  *
14419  * This routine is called from the PCI subsystem for I/O error handling to
14420  * device with SLI-3 interface spec. This function is called by the PCI
14421  * subsystem after a PCI bus error affecting this device has been detected.
14422  * When this function is invoked, it will need to stop all the I/Os and
14423  * interrupt(s) to the device. Once that is done, it will return
14424  * PCI_ERS_RESULT_NEED_RESET for the PCI subsystem to perform proper recovery
14425  * as desired.
14426  *
14427  * Return codes
14428  * 	PCI_ERS_RESULT_CAN_RECOVER - can be recovered with reset_link
14429  * 	PCI_ERS_RESULT_NEED_RESET - need to reset before recovery
14430  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
14431  **/
14432 static pci_ers_result_t
14433 lpfc_io_error_detected_s3(struct pci_dev *pdev, pci_channel_state_t state)
14434 {
14435 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
14436 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14437 
14438 	switch (state) {
14439 	case pci_channel_io_normal:
14440 		/* Non-fatal error, prepare for recovery */
14441 		lpfc_sli_prep_dev_for_recover(phba);
14442 		return PCI_ERS_RESULT_CAN_RECOVER;
14443 	case pci_channel_io_frozen:
14444 		/* Fatal error, prepare for slot reset */
14445 		lpfc_sli_prep_dev_for_reset(phba);
14446 		return PCI_ERS_RESULT_NEED_RESET;
14447 	case pci_channel_io_perm_failure:
14448 		/* Permanent failure, prepare for device down */
14449 		lpfc_sli_prep_dev_for_perm_failure(phba);
14450 		return PCI_ERS_RESULT_DISCONNECT;
14451 	default:
14452 		/* Unknown state, prepare and request slot reset */
14453 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14454 				"0472 Unknown PCI error state: x%x\n", state);
14455 		lpfc_sli_prep_dev_for_reset(phba);
14456 		return PCI_ERS_RESULT_NEED_RESET;
14457 	}
14458 }
14459 
14460 /**
14461  * lpfc_io_slot_reset_s3 - Method for restarting PCI SLI-3 device from scratch.
14462  * @pdev: pointer to PCI device.
14463  *
14464  * This routine is called from the PCI subsystem for error handling to
14465  * device with SLI-3 interface spec. This is called after PCI bus has been
14466  * reset to restart the PCI card from scratch, as if from a cold-boot.
14467  * During the PCI subsystem error recovery, after driver returns
14468  * PCI_ERS_RESULT_NEED_RESET, the PCI subsystem will perform proper error
14469  * recovery and then call this routine before calling the .resume method
14470  * to recover the device. This function will initialize the HBA device,
14471  * enable the interrupt, but it will just put the HBA to offline state
14472  * without passing any I/O traffic.
14473  *
14474  * Return codes
14475  * 	PCI_ERS_RESULT_RECOVERED - the device has been recovered
14476  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
14477  */
14478 static pci_ers_result_t
14479 lpfc_io_slot_reset_s3(struct pci_dev *pdev)
14480 {
14481 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
14482 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14483 	struct lpfc_sli *psli = &phba->sli;
14484 	uint32_t intr_mode;
14485 
14486 	dev_printk(KERN_INFO, &pdev->dev, "recovering from a slot reset.\n");
14487 	if (pci_enable_device_mem(pdev)) {
14488 		printk(KERN_ERR "lpfc: Cannot re-enable "
14489 			"PCI device after reset.\n");
14490 		return PCI_ERS_RESULT_DISCONNECT;
14491 	}
14492 
14493 	pci_restore_state(pdev);
14494 
14495 	/*
14496 	 * As the new kernel behavior of pci_restore_state() API call clears
14497 	 * device saved_state flag, need to save the restored state again.
14498 	 */
14499 	pci_save_state(pdev);
14500 
14501 	if (pdev->is_busmaster)
14502 		pci_set_master(pdev);
14503 
14504 	spin_lock_irq(&phba->hbalock);
14505 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
14506 	spin_unlock_irq(&phba->hbalock);
14507 
14508 	/* Configure and enable interrupt */
14509 	intr_mode = lpfc_sli_enable_intr(phba, phba->intr_mode);
14510 	if (intr_mode == LPFC_INTR_ERROR) {
14511 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14512 				"0427 Cannot re-enable interrupt after "
14513 				"slot reset.\n");
14514 		return PCI_ERS_RESULT_DISCONNECT;
14515 	} else
14516 		phba->intr_mode = intr_mode;
14517 
14518 	/* Take device offline, it will perform cleanup */
14519 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
14520 	lpfc_offline(phba);
14521 	lpfc_sli_brdrestart(phba);
14522 
14523 	/* Log the current active interrupt mode */
14524 	lpfc_log_intr_mode(phba, phba->intr_mode);
14525 
14526 	return PCI_ERS_RESULT_RECOVERED;
14527 }
14528 
14529 /**
14530  * lpfc_io_resume_s3 - Method for resuming PCI I/O operation on SLI-3 device.
14531  * @pdev: pointer to PCI device
14532  *
14533  * This routine is called from the PCI subsystem for error handling to device
14534  * with SLI-3 interface spec. It is called when kernel error recovery tells
14535  * the lpfc driver that it is ok to resume normal PCI operation after PCI bus
14536  * error recovery. After this call, traffic can start to flow from this device
14537  * again.
14538  */
14539 static void
14540 lpfc_io_resume_s3(struct pci_dev *pdev)
14541 {
14542 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
14543 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14544 
14545 	/* Bring device online, it will be no-op for non-fatal error resume */
14546 	lpfc_online(phba);
14547 }
14548 
14549 /**
14550  * lpfc_sli4_get_els_iocb_cnt - Calculate the # of ELS IOCBs to reserve
14551  * @phba: pointer to lpfc hba data structure.
14552  *
14553  * returns the number of ELS/CT IOCBs to reserve
14554  **/
14555 int
14556 lpfc_sli4_get_els_iocb_cnt(struct lpfc_hba *phba)
14557 {
14558 	int max_xri = phba->sli4_hba.max_cfg_param.max_xri;
14559 
14560 	if (phba->sli_rev == LPFC_SLI_REV4) {
14561 		if (max_xri <= 100)
14562 			return 10;
14563 		else if (max_xri <= 256)
14564 			return 25;
14565 		else if (max_xri <= 512)
14566 			return 50;
14567 		else if (max_xri <= 1024)
14568 			return 100;
14569 		else if (max_xri <= 1536)
14570 			return 150;
14571 		else if (max_xri <= 2048)
14572 			return 200;
14573 		else
14574 			return 250;
14575 	} else
14576 		return 0;
14577 }
14578 
14579 /**
14580  * lpfc_sli4_get_iocb_cnt - Calculate the # of total IOCBs to reserve
14581  * @phba: pointer to lpfc hba data structure.
14582  *
14583  * returns the number of ELS/CT + NVMET IOCBs to reserve
14584  **/
14585 int
14586 lpfc_sli4_get_iocb_cnt(struct lpfc_hba *phba)
14587 {
14588 	int max_xri = lpfc_sli4_get_els_iocb_cnt(phba);
14589 
14590 	if (phba->nvmet_support)
14591 		max_xri += LPFC_NVMET_BUF_POST;
14592 	return max_xri;
14593 }
14594 
14595 
14596 static int
14597 lpfc_log_write_firmware_error(struct lpfc_hba *phba, uint32_t offset,
14598 	uint32_t magic_number, uint32_t ftype, uint32_t fid, uint32_t fsize,
14599 	const struct firmware *fw)
14600 {
14601 	int rc;
14602 	u8 sli_family;
14603 
14604 	sli_family = bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf);
14605 	/* Three cases:  (1) FW was not supported on the detected adapter.
14606 	 * (2) FW update has been locked out administratively.
14607 	 * (3) Some other error during FW update.
14608 	 * In each case, an unmaskable message is written to the console
14609 	 * for admin diagnosis.
14610 	 */
14611 	if (offset == ADD_STATUS_FW_NOT_SUPPORTED ||
14612 	    (sli_family == LPFC_SLI_INTF_FAMILY_G6 &&
14613 	     magic_number != MAGIC_NUMBER_G6) ||
14614 	    (sli_family == LPFC_SLI_INTF_FAMILY_G7 &&
14615 	     magic_number != MAGIC_NUMBER_G7) ||
14616 	    (sli_family == LPFC_SLI_INTF_FAMILY_G7P &&
14617 	     magic_number != MAGIC_NUMBER_G7P)) {
14618 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14619 				"3030 This firmware version is not supported on"
14620 				" this HBA model. Device:%x Magic:%x Type:%x "
14621 				"ID:%x Size %d %zd\n",
14622 				phba->pcidev->device, magic_number, ftype, fid,
14623 				fsize, fw->size);
14624 		rc = -EINVAL;
14625 	} else if (offset == ADD_STATUS_FW_DOWNLOAD_HW_DISABLED) {
14626 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14627 				"3021 Firmware downloads have been prohibited "
14628 				"by a system configuration setting on "
14629 				"Device:%x Magic:%x Type:%x ID:%x Size %d "
14630 				"%zd\n",
14631 				phba->pcidev->device, magic_number, ftype, fid,
14632 				fsize, fw->size);
14633 		rc = -EACCES;
14634 	} else {
14635 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14636 				"3022 FW Download failed. Add Status x%x "
14637 				"Device:%x Magic:%x Type:%x ID:%x Size %d "
14638 				"%zd\n",
14639 				offset, phba->pcidev->device, magic_number,
14640 				ftype, fid, fsize, fw->size);
14641 		rc = -EIO;
14642 	}
14643 	return rc;
14644 }
14645 
14646 /**
14647  * lpfc_write_firmware - attempt to write a firmware image to the port
14648  * @fw: pointer to firmware image returned from request_firmware.
14649  * @context: pointer to firmware image returned from request_firmware.
14650  *
14651  **/
14652 static void
14653 lpfc_write_firmware(const struct firmware *fw, void *context)
14654 {
14655 	struct lpfc_hba *phba = (struct lpfc_hba *)context;
14656 	char fwrev[FW_REV_STR_SIZE];
14657 	struct lpfc_grp_hdr *image;
14658 	struct list_head dma_buffer_list;
14659 	int i, rc = 0;
14660 	struct lpfc_dmabuf *dmabuf, *next;
14661 	uint32_t offset = 0, temp_offset = 0;
14662 	uint32_t magic_number, ftype, fid, fsize;
14663 
14664 	/* It can be null in no-wait mode, sanity check */
14665 	if (!fw) {
14666 		rc = -ENXIO;
14667 		goto out;
14668 	}
14669 	image = (struct lpfc_grp_hdr *)fw->data;
14670 
14671 	magic_number = be32_to_cpu(image->magic_number);
14672 	ftype = bf_get_be32(lpfc_grp_hdr_file_type, image);
14673 	fid = bf_get_be32(lpfc_grp_hdr_id, image);
14674 	fsize = be32_to_cpu(image->size);
14675 
14676 	INIT_LIST_HEAD(&dma_buffer_list);
14677 	lpfc_decode_firmware_rev(phba, fwrev, 1);
14678 	if (strncmp(fwrev, image->revision, strnlen(image->revision, 16))) {
14679 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14680 				"3023 Updating Firmware, Current Version:%s "
14681 				"New Version:%s\n",
14682 				fwrev, image->revision);
14683 		for (i = 0; i < LPFC_MBX_WR_CONFIG_MAX_BDE; i++) {
14684 			dmabuf = kzalloc(sizeof(struct lpfc_dmabuf),
14685 					 GFP_KERNEL);
14686 			if (!dmabuf) {
14687 				rc = -ENOMEM;
14688 				goto release_out;
14689 			}
14690 			dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
14691 							  SLI4_PAGE_SIZE,
14692 							  &dmabuf->phys,
14693 							  GFP_KERNEL);
14694 			if (!dmabuf->virt) {
14695 				kfree(dmabuf);
14696 				rc = -ENOMEM;
14697 				goto release_out;
14698 			}
14699 			list_add_tail(&dmabuf->list, &dma_buffer_list);
14700 		}
14701 		while (offset < fw->size) {
14702 			temp_offset = offset;
14703 			list_for_each_entry(dmabuf, &dma_buffer_list, list) {
14704 				if (temp_offset + SLI4_PAGE_SIZE > fw->size) {
14705 					memcpy(dmabuf->virt,
14706 					       fw->data + temp_offset,
14707 					       fw->size - temp_offset);
14708 					temp_offset = fw->size;
14709 					break;
14710 				}
14711 				memcpy(dmabuf->virt, fw->data + temp_offset,
14712 				       SLI4_PAGE_SIZE);
14713 				temp_offset += SLI4_PAGE_SIZE;
14714 			}
14715 			rc = lpfc_wr_object(phba, &dma_buffer_list,
14716 				    (fw->size - offset), &offset);
14717 			if (rc) {
14718 				rc = lpfc_log_write_firmware_error(phba, offset,
14719 								   magic_number,
14720 								   ftype,
14721 								   fid,
14722 								   fsize,
14723 								   fw);
14724 				goto release_out;
14725 			}
14726 		}
14727 		rc = offset;
14728 	} else
14729 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14730 				"3029 Skipped Firmware update, Current "
14731 				"Version:%s New Version:%s\n",
14732 				fwrev, image->revision);
14733 
14734 release_out:
14735 	list_for_each_entry_safe(dmabuf, next, &dma_buffer_list, list) {
14736 		list_del(&dmabuf->list);
14737 		dma_free_coherent(&phba->pcidev->dev, SLI4_PAGE_SIZE,
14738 				  dmabuf->virt, dmabuf->phys);
14739 		kfree(dmabuf);
14740 	}
14741 	release_firmware(fw);
14742 out:
14743 	if (rc < 0)
14744 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14745 				"3062 Firmware update error, status %d.\n", rc);
14746 	else
14747 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14748 				"3024 Firmware update success: size %d.\n", rc);
14749 }
14750 
14751 /**
14752  * lpfc_sli4_request_firmware_update - Request linux generic firmware upgrade
14753  * @phba: pointer to lpfc hba data structure.
14754  * @fw_upgrade: which firmware to update.
14755  *
14756  * This routine is called to perform Linux generic firmware upgrade on device
14757  * that supports such feature.
14758  **/
14759 int
14760 lpfc_sli4_request_firmware_update(struct lpfc_hba *phba, uint8_t fw_upgrade)
14761 {
14762 	uint8_t file_name[ELX_MODEL_NAME_SIZE];
14763 	int ret;
14764 	const struct firmware *fw;
14765 
14766 	/* Only supported on SLI4 interface type 2 for now */
14767 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) <
14768 	    LPFC_SLI_INTF_IF_TYPE_2)
14769 		return -EPERM;
14770 
14771 	snprintf(file_name, ELX_MODEL_NAME_SIZE, "%s.grp", phba->ModelName);
14772 
14773 	if (fw_upgrade == INT_FW_UPGRADE) {
14774 		ret = request_firmware_nowait(THIS_MODULE, FW_ACTION_UEVENT,
14775 					file_name, &phba->pcidev->dev,
14776 					GFP_KERNEL, (void *)phba,
14777 					lpfc_write_firmware);
14778 	} else if (fw_upgrade == RUN_FW_UPGRADE) {
14779 		ret = request_firmware(&fw, file_name, &phba->pcidev->dev);
14780 		if (!ret)
14781 			lpfc_write_firmware(fw, (void *)phba);
14782 	} else {
14783 		ret = -EINVAL;
14784 	}
14785 
14786 	return ret;
14787 }
14788 
14789 /**
14790  * lpfc_pci_probe_one_s4 - PCI probe func to reg SLI-4 device to PCI subsys
14791  * @pdev: pointer to PCI device
14792  * @pid: pointer to PCI device identifier
14793  *
14794  * This routine is called from the kernel's PCI subsystem to device with
14795  * SLI-4 interface spec. When an Emulex HBA with SLI-4 interface spec is
14796  * presented on PCI bus, the kernel PCI subsystem looks at PCI device-specific
14797  * information of the device and driver to see if the driver state that it
14798  * can support this kind of device. If the match is successful, the driver
14799  * core invokes this routine. If this routine determines it can claim the HBA,
14800  * it does all the initialization that it needs to do to handle the HBA
14801  * properly.
14802  *
14803  * Return code
14804  * 	0 - driver can claim the device
14805  * 	negative value - driver can not claim the device
14806  **/
14807 static int
14808 lpfc_pci_probe_one_s4(struct pci_dev *pdev, const struct pci_device_id *pid)
14809 {
14810 	struct lpfc_hba   *phba;
14811 	struct lpfc_vport *vport = NULL;
14812 	struct Scsi_Host  *shost = NULL;
14813 	int error;
14814 	uint32_t cfg_mode, intr_mode;
14815 
14816 	/* Allocate memory for HBA structure */
14817 	phba = lpfc_hba_alloc(pdev);
14818 	if (!phba)
14819 		return -ENOMEM;
14820 
14821 	INIT_LIST_HEAD(&phba->poll_list);
14822 
14823 	/* Perform generic PCI device enabling operation */
14824 	error = lpfc_enable_pci_dev(phba);
14825 	if (error)
14826 		goto out_free_phba;
14827 
14828 	/* Set up SLI API function jump table for PCI-device group-1 HBAs */
14829 	error = lpfc_api_table_setup(phba, LPFC_PCI_DEV_OC);
14830 	if (error)
14831 		goto out_disable_pci_dev;
14832 
14833 	/* Set up SLI-4 specific device PCI memory space */
14834 	error = lpfc_sli4_pci_mem_setup(phba);
14835 	if (error) {
14836 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14837 				"1410 Failed to set up pci memory space.\n");
14838 		goto out_disable_pci_dev;
14839 	}
14840 
14841 	/* Set up SLI-4 Specific device driver resources */
14842 	error = lpfc_sli4_driver_resource_setup(phba);
14843 	if (error) {
14844 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14845 				"1412 Failed to set up driver resource.\n");
14846 		goto out_unset_pci_mem_s4;
14847 	}
14848 
14849 	INIT_LIST_HEAD(&phba->active_rrq_list);
14850 	INIT_LIST_HEAD(&phba->fcf.fcf_pri_list);
14851 
14852 	/* Set up common device driver resources */
14853 	error = lpfc_setup_driver_resource_phase2(phba);
14854 	if (error) {
14855 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14856 				"1414 Failed to set up driver resource.\n");
14857 		goto out_unset_driver_resource_s4;
14858 	}
14859 
14860 	/* Get the default values for Model Name and Description */
14861 	lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
14862 
14863 	/* Now, trying to enable interrupt and bring up the device */
14864 	cfg_mode = phba->cfg_use_msi;
14865 
14866 	/* Put device to a known state before enabling interrupt */
14867 	phba->pport = NULL;
14868 	lpfc_stop_port(phba);
14869 
14870 	/* Init cpu_map array */
14871 	lpfc_cpu_map_array_init(phba);
14872 
14873 	/* Init hba_eq_hdl array */
14874 	lpfc_hba_eq_hdl_array_init(phba);
14875 
14876 	/* Configure and enable interrupt */
14877 	intr_mode = lpfc_sli4_enable_intr(phba, cfg_mode);
14878 	if (intr_mode == LPFC_INTR_ERROR) {
14879 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14880 				"0426 Failed to enable interrupt.\n");
14881 		error = -ENODEV;
14882 		goto out_unset_driver_resource;
14883 	}
14884 	/* Default to single EQ for non-MSI-X */
14885 	if (phba->intr_type != MSIX) {
14886 		phba->cfg_irq_chann = 1;
14887 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
14888 			if (phba->nvmet_support)
14889 				phba->cfg_nvmet_mrq = 1;
14890 		}
14891 	}
14892 	lpfc_cpu_affinity_check(phba, phba->cfg_irq_chann);
14893 
14894 	/* Create SCSI host to the physical port */
14895 	error = lpfc_create_shost(phba);
14896 	if (error) {
14897 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14898 				"1415 Failed to create scsi host.\n");
14899 		goto out_disable_intr;
14900 	}
14901 	vport = phba->pport;
14902 	shost = lpfc_shost_from_vport(vport); /* save shost for error cleanup */
14903 
14904 	/* Configure sysfs attributes */
14905 	error = lpfc_alloc_sysfs_attr(vport);
14906 	if (error) {
14907 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14908 				"1416 Failed to allocate sysfs attr\n");
14909 		goto out_destroy_shost;
14910 	}
14911 
14912 	/* Set up SLI-4 HBA */
14913 	if (lpfc_sli4_hba_setup(phba)) {
14914 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14915 				"1421 Failed to set up hba\n");
14916 		error = -ENODEV;
14917 		goto out_free_sysfs_attr;
14918 	}
14919 
14920 	/* Log the current active interrupt mode */
14921 	phba->intr_mode = intr_mode;
14922 	lpfc_log_intr_mode(phba, intr_mode);
14923 
14924 	/* Perform post initialization setup */
14925 	lpfc_post_init_setup(phba);
14926 
14927 	/* NVME support in FW earlier in the driver load corrects the
14928 	 * FC4 type making a check for nvme_support unnecessary.
14929 	 */
14930 	if (phba->nvmet_support == 0) {
14931 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
14932 			/* Create NVME binding with nvme_fc_transport. This
14933 			 * ensures the vport is initialized.  If the localport
14934 			 * create fails, it should not unload the driver to
14935 			 * support field issues.
14936 			 */
14937 			error = lpfc_nvme_create_localport(vport);
14938 			if (error) {
14939 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14940 						"6004 NVME registration "
14941 						"failed, error x%x\n",
14942 						error);
14943 			}
14944 		}
14945 	}
14946 
14947 	/* check for firmware upgrade or downgrade */
14948 	if (phba->cfg_request_firmware_upgrade)
14949 		lpfc_sli4_request_firmware_update(phba, INT_FW_UPGRADE);
14950 
14951 	/* Check if there are static vports to be created. */
14952 	lpfc_create_static_vport(phba);
14953 
14954 	timer_setup(&phba->cpuhp_poll_timer, lpfc_sli4_poll_hbtimer, 0);
14955 	cpuhp_state_add_instance_nocalls(lpfc_cpuhp_state, &phba->cpuhp);
14956 
14957 	return 0;
14958 
14959 out_free_sysfs_attr:
14960 	lpfc_free_sysfs_attr(vport);
14961 out_destroy_shost:
14962 	lpfc_destroy_shost(phba);
14963 out_disable_intr:
14964 	lpfc_sli4_disable_intr(phba);
14965 out_unset_driver_resource:
14966 	lpfc_unset_driver_resource_phase2(phba);
14967 out_unset_driver_resource_s4:
14968 	lpfc_sli4_driver_resource_unset(phba);
14969 out_unset_pci_mem_s4:
14970 	lpfc_sli4_pci_mem_unset(phba);
14971 out_disable_pci_dev:
14972 	lpfc_disable_pci_dev(phba);
14973 	if (shost)
14974 		scsi_host_put(shost);
14975 out_free_phba:
14976 	lpfc_hba_free(phba);
14977 	return error;
14978 }
14979 
14980 /**
14981  * lpfc_pci_remove_one_s4 - PCI func to unreg SLI-4 device from PCI subsystem
14982  * @pdev: pointer to PCI device
14983  *
14984  * This routine is called from the kernel's PCI subsystem to device with
14985  * SLI-4 interface spec. When an Emulex HBA with SLI-4 interface spec is
14986  * removed from PCI bus, it performs all the necessary cleanup for the HBA
14987  * device to be removed from the PCI subsystem properly.
14988  **/
14989 static void
14990 lpfc_pci_remove_one_s4(struct pci_dev *pdev)
14991 {
14992 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
14993 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
14994 	struct lpfc_vport **vports;
14995 	struct lpfc_hba *phba = vport->phba;
14996 	int i;
14997 
14998 	/* Mark the device unloading flag */
14999 	spin_lock_irq(&phba->hbalock);
15000 	vport->load_flag |= FC_UNLOADING;
15001 	spin_unlock_irq(&phba->hbalock);
15002 	if (phba->cgn_i)
15003 		lpfc_unreg_congestion_buf(phba);
15004 
15005 	lpfc_free_sysfs_attr(vport);
15006 
15007 	/* Release all the vports against this physical port */
15008 	vports = lpfc_create_vport_work_array(phba);
15009 	if (vports != NULL)
15010 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
15011 			if (vports[i]->port_type == LPFC_PHYSICAL_PORT)
15012 				continue;
15013 			fc_vport_terminate(vports[i]->fc_vport);
15014 		}
15015 	lpfc_destroy_vport_work_array(phba, vports);
15016 
15017 	/* Remove FC host with the physical port */
15018 	fc_remove_host(shost);
15019 	scsi_remove_host(shost);
15020 
15021 	/* Perform ndlp cleanup on the physical port.  The nvme and nvmet
15022 	 * localports are destroyed after to cleanup all transport memory.
15023 	 */
15024 	lpfc_cleanup(vport);
15025 	lpfc_nvmet_destroy_targetport(phba);
15026 	lpfc_nvme_destroy_localport(vport);
15027 
15028 	/* De-allocate multi-XRI pools */
15029 	if (phba->cfg_xri_rebalancing)
15030 		lpfc_destroy_multixri_pools(phba);
15031 
15032 	/*
15033 	 * Bring down the SLI Layer. This step disables all interrupts,
15034 	 * clears the rings, discards all mailbox commands, and resets
15035 	 * the HBA FCoE function.
15036 	 */
15037 	lpfc_debugfs_terminate(vport);
15038 
15039 	lpfc_stop_hba_timers(phba);
15040 	spin_lock_irq(&phba->port_list_lock);
15041 	list_del_init(&vport->listentry);
15042 	spin_unlock_irq(&phba->port_list_lock);
15043 
15044 	/* Perform scsi free before driver resource_unset since scsi
15045 	 * buffers are released to their corresponding pools here.
15046 	 */
15047 	lpfc_io_free(phba);
15048 	lpfc_free_iocb_list(phba);
15049 	lpfc_sli4_hba_unset(phba);
15050 
15051 	lpfc_unset_driver_resource_phase2(phba);
15052 	lpfc_sli4_driver_resource_unset(phba);
15053 
15054 	/* Unmap adapter Control and Doorbell registers */
15055 	lpfc_sli4_pci_mem_unset(phba);
15056 
15057 	/* Release PCI resources and disable device's PCI function */
15058 	scsi_host_put(shost);
15059 	lpfc_disable_pci_dev(phba);
15060 
15061 	/* Finally, free the driver's device data structure */
15062 	lpfc_hba_free(phba);
15063 
15064 	return;
15065 }
15066 
15067 /**
15068  * lpfc_pci_suspend_one_s4 - PCI func to suspend SLI-4 device for power mgmnt
15069  * @dev_d: pointer to device
15070  *
15071  * This routine is called from the kernel's PCI subsystem to support system
15072  * Power Management (PM) to device with SLI-4 interface spec. When PM invokes
15073  * this method, it quiesces the device by stopping the driver's worker
15074  * thread for the device, turning off device's interrupt and DMA, and bring
15075  * the device offline. Note that as the driver implements the minimum PM
15076  * requirements to a power-aware driver's PM support for suspend/resume -- all
15077  * the possible PM messages (SUSPEND, HIBERNATE, FREEZE) to the suspend()
15078  * method call will be treated as SUSPEND and the driver will fully
15079  * reinitialize its device during resume() method call, the driver will set
15080  * device to PCI_D3hot state in PCI config space instead of setting it
15081  * according to the @msg provided by the PM.
15082  *
15083  * Return code
15084  * 	0 - driver suspended the device
15085  * 	Error otherwise
15086  **/
15087 static int __maybe_unused
15088 lpfc_pci_suspend_one_s4(struct device *dev_d)
15089 {
15090 	struct Scsi_Host *shost = dev_get_drvdata(dev_d);
15091 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15092 
15093 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
15094 			"2843 PCI device Power Management suspend.\n");
15095 
15096 	/* Bring down the device */
15097 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
15098 	lpfc_offline(phba);
15099 	kthread_stop(phba->worker_thread);
15100 
15101 	/* Disable interrupt from device */
15102 	lpfc_sli4_disable_intr(phba);
15103 	lpfc_sli4_queue_destroy(phba);
15104 
15105 	return 0;
15106 }
15107 
15108 /**
15109  * lpfc_pci_resume_one_s4 - PCI func to resume SLI-4 device for power mgmnt
15110  * @dev_d: pointer to device
15111  *
15112  * This routine is called from the kernel's PCI subsystem to support system
15113  * Power Management (PM) to device with SLI-4 interface spac. When PM invokes
15114  * this method, it restores the device's PCI config space state and fully
15115  * reinitializes the device and brings it online. Note that as the driver
15116  * implements the minimum PM requirements to a power-aware driver's PM for
15117  * suspend/resume -- all the possible PM messages (SUSPEND, HIBERNATE, FREEZE)
15118  * to the suspend() method call will be treated as SUSPEND and the driver
15119  * will fully reinitialize its device during resume() method call, the device
15120  * will be set to PCI_D0 directly in PCI config space before restoring the
15121  * state.
15122  *
15123  * Return code
15124  * 	0 - driver suspended the device
15125  * 	Error otherwise
15126  **/
15127 static int __maybe_unused
15128 lpfc_pci_resume_one_s4(struct device *dev_d)
15129 {
15130 	struct Scsi_Host *shost = dev_get_drvdata(dev_d);
15131 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15132 	uint32_t intr_mode;
15133 	int error;
15134 
15135 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
15136 			"0292 PCI device Power Management resume.\n");
15137 
15138 	 /* Startup the kernel thread for this host adapter. */
15139 	phba->worker_thread = kthread_run(lpfc_do_work, phba,
15140 					"lpfc_worker_%d", phba->brd_no);
15141 	if (IS_ERR(phba->worker_thread)) {
15142 		error = PTR_ERR(phba->worker_thread);
15143 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15144 				"0293 PM resume failed to start worker "
15145 				"thread: error=x%x.\n", error);
15146 		return error;
15147 	}
15148 
15149 	/* Configure and enable interrupt */
15150 	intr_mode = lpfc_sli4_enable_intr(phba, phba->intr_mode);
15151 	if (intr_mode == LPFC_INTR_ERROR) {
15152 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15153 				"0294 PM resume Failed to enable interrupt\n");
15154 		return -EIO;
15155 	} else
15156 		phba->intr_mode = intr_mode;
15157 
15158 	/* Restart HBA and bring it online */
15159 	lpfc_sli_brdrestart(phba);
15160 	lpfc_online(phba);
15161 
15162 	/* Log the current active interrupt mode */
15163 	lpfc_log_intr_mode(phba, phba->intr_mode);
15164 
15165 	return 0;
15166 }
15167 
15168 /**
15169  * lpfc_sli4_prep_dev_for_recover - Prepare SLI4 device for pci slot recover
15170  * @phba: pointer to lpfc hba data structure.
15171  *
15172  * This routine is called to prepare the SLI4 device for PCI slot recover. It
15173  * aborts all the outstanding SCSI I/Os to the pci device.
15174  **/
15175 static void
15176 lpfc_sli4_prep_dev_for_recover(struct lpfc_hba *phba)
15177 {
15178 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15179 			"2828 PCI channel I/O abort preparing for recovery\n");
15180 	/*
15181 	 * There may be errored I/Os through HBA, abort all I/Os on txcmplq
15182 	 * and let the SCSI mid-layer to retry them to recover.
15183 	 */
15184 	lpfc_sli_abort_fcp_rings(phba);
15185 }
15186 
15187 /**
15188  * lpfc_sli4_prep_dev_for_reset - Prepare SLI4 device for pci slot reset
15189  * @phba: pointer to lpfc hba data structure.
15190  *
15191  * This routine is called to prepare the SLI4 device for PCI slot reset. It
15192  * disables the device interrupt and pci device, and aborts the internal FCP
15193  * pending I/Os.
15194  **/
15195 static void
15196 lpfc_sli4_prep_dev_for_reset(struct lpfc_hba *phba)
15197 {
15198 	int offline =  pci_channel_offline(phba->pcidev);
15199 
15200 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15201 			"2826 PCI channel disable preparing for reset offline"
15202 			" %d\n", offline);
15203 
15204 	/* Block any management I/Os to the device */
15205 	lpfc_block_mgmt_io(phba, LPFC_MBX_NO_WAIT);
15206 
15207 
15208 	/* HBA_PCI_ERR was set in io_error_detect */
15209 	lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
15210 	/* Flush all driver's outstanding I/Os as we are to reset */
15211 	lpfc_sli_flush_io_rings(phba);
15212 	lpfc_offline(phba);
15213 
15214 	/* stop all timers */
15215 	lpfc_stop_hba_timers(phba);
15216 
15217 	lpfc_sli4_queue_destroy(phba);
15218 	/* Disable interrupt and pci device */
15219 	lpfc_sli4_disable_intr(phba);
15220 	pci_disable_device(phba->pcidev);
15221 }
15222 
15223 /**
15224  * lpfc_sli4_prep_dev_for_perm_failure - Prepare SLI4 dev for pci slot disable
15225  * @phba: pointer to lpfc hba data structure.
15226  *
15227  * This routine is called to prepare the SLI4 device for PCI slot permanently
15228  * disabling. It blocks the SCSI transport layer traffic and flushes the FCP
15229  * pending I/Os.
15230  **/
15231 static void
15232 lpfc_sli4_prep_dev_for_perm_failure(struct lpfc_hba *phba)
15233 {
15234 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15235 			"2827 PCI channel permanent disable for failure\n");
15236 
15237 	/* Block all SCSI devices' I/Os on the host */
15238 	lpfc_scsi_dev_block(phba);
15239 
15240 	/* stop all timers */
15241 	lpfc_stop_hba_timers(phba);
15242 
15243 	/* Clean up all driver's outstanding I/Os */
15244 	lpfc_sli_flush_io_rings(phba);
15245 }
15246 
15247 /**
15248  * lpfc_io_error_detected_s4 - Method for handling PCI I/O error to SLI-4 device
15249  * @pdev: pointer to PCI device.
15250  * @state: the current PCI connection state.
15251  *
15252  * This routine is called from the PCI subsystem for error handling to device
15253  * with SLI-4 interface spec. This function is called by the PCI subsystem
15254  * after a PCI bus error affecting this device has been detected. When this
15255  * function is invoked, it will need to stop all the I/Os and interrupt(s)
15256  * to the device. Once that is done, it will return PCI_ERS_RESULT_NEED_RESET
15257  * for the PCI subsystem to perform proper recovery as desired.
15258  *
15259  * Return codes
15260  * 	PCI_ERS_RESULT_NEED_RESET - need to reset before recovery
15261  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15262  **/
15263 static pci_ers_result_t
15264 lpfc_io_error_detected_s4(struct pci_dev *pdev, pci_channel_state_t state)
15265 {
15266 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15267 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15268 	bool hba_pci_err;
15269 
15270 	switch (state) {
15271 	case pci_channel_io_normal:
15272 		/* Non-fatal error, prepare for recovery */
15273 		lpfc_sli4_prep_dev_for_recover(phba);
15274 		return PCI_ERS_RESULT_CAN_RECOVER;
15275 	case pci_channel_io_frozen:
15276 		hba_pci_err = test_and_set_bit(HBA_PCI_ERR, &phba->bit_flags);
15277 		/* Fatal error, prepare for slot reset */
15278 		if (!hba_pci_err)
15279 			lpfc_sli4_prep_dev_for_reset(phba);
15280 		else
15281 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15282 					"2832  Already handling PCI error "
15283 					"state: x%x\n", state);
15284 		return PCI_ERS_RESULT_NEED_RESET;
15285 	case pci_channel_io_perm_failure:
15286 		set_bit(HBA_PCI_ERR, &phba->bit_flags);
15287 		/* Permanent failure, prepare for device down */
15288 		lpfc_sli4_prep_dev_for_perm_failure(phba);
15289 		return PCI_ERS_RESULT_DISCONNECT;
15290 	default:
15291 		hba_pci_err = test_and_set_bit(HBA_PCI_ERR, &phba->bit_flags);
15292 		if (!hba_pci_err)
15293 			lpfc_sli4_prep_dev_for_reset(phba);
15294 		/* Unknown state, prepare and request slot reset */
15295 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15296 				"2825 Unknown PCI error state: x%x\n", state);
15297 		lpfc_sli4_prep_dev_for_reset(phba);
15298 		return PCI_ERS_RESULT_NEED_RESET;
15299 	}
15300 }
15301 
15302 /**
15303  * lpfc_io_slot_reset_s4 - Method for restart PCI SLI-4 device from scratch
15304  * @pdev: pointer to PCI device.
15305  *
15306  * This routine is called from the PCI subsystem for error handling to device
15307  * with SLI-4 interface spec. It is called after PCI bus has been reset to
15308  * restart the PCI card from scratch, as if from a cold-boot. During the
15309  * PCI subsystem error recovery, after the driver returns
15310  * PCI_ERS_RESULT_NEED_RESET, the PCI subsystem will perform proper error
15311  * recovery and then call this routine before calling the .resume method to
15312  * recover the device. This function will initialize the HBA device, enable
15313  * the interrupt, but it will just put the HBA to offline state without
15314  * passing any I/O traffic.
15315  *
15316  * Return codes
15317  * 	PCI_ERS_RESULT_RECOVERED - the device has been recovered
15318  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15319  */
15320 static pci_ers_result_t
15321 lpfc_io_slot_reset_s4(struct pci_dev *pdev)
15322 {
15323 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15324 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15325 	struct lpfc_sli *psli = &phba->sli;
15326 	uint32_t intr_mode;
15327 	bool hba_pci_err;
15328 
15329 	dev_printk(KERN_INFO, &pdev->dev, "recovering from a slot reset.\n");
15330 	if (pci_enable_device_mem(pdev)) {
15331 		printk(KERN_ERR "lpfc: Cannot re-enable "
15332 		       "PCI device after reset.\n");
15333 		return PCI_ERS_RESULT_DISCONNECT;
15334 	}
15335 
15336 	pci_restore_state(pdev);
15337 
15338 	hba_pci_err = test_and_clear_bit(HBA_PCI_ERR, &phba->bit_flags);
15339 	if (!hba_pci_err)
15340 		dev_info(&pdev->dev,
15341 			 "hba_pci_err was not set, recovering slot reset.\n");
15342 	/*
15343 	 * As the new kernel behavior of pci_restore_state() API call clears
15344 	 * device saved_state flag, need to save the restored state again.
15345 	 */
15346 	pci_save_state(pdev);
15347 
15348 	if (pdev->is_busmaster)
15349 		pci_set_master(pdev);
15350 
15351 	spin_lock_irq(&phba->hbalock);
15352 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
15353 	spin_unlock_irq(&phba->hbalock);
15354 
15355 	/* Init cpu_map array */
15356 	lpfc_cpu_map_array_init(phba);
15357 	/* Configure and enable interrupt */
15358 	intr_mode = lpfc_sli4_enable_intr(phba, phba->intr_mode);
15359 	if (intr_mode == LPFC_INTR_ERROR) {
15360 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15361 				"2824 Cannot re-enable interrupt after "
15362 				"slot reset.\n");
15363 		return PCI_ERS_RESULT_DISCONNECT;
15364 	} else
15365 		phba->intr_mode = intr_mode;
15366 	lpfc_cpu_affinity_check(phba, phba->cfg_irq_chann);
15367 
15368 	/* Log the current active interrupt mode */
15369 	lpfc_log_intr_mode(phba, phba->intr_mode);
15370 
15371 	return PCI_ERS_RESULT_RECOVERED;
15372 }
15373 
15374 /**
15375  * lpfc_io_resume_s4 - Method for resuming PCI I/O operation to SLI-4 device
15376  * @pdev: pointer to PCI device
15377  *
15378  * This routine is called from the PCI subsystem for error handling to device
15379  * with SLI-4 interface spec. It is called when kernel error recovery tells
15380  * the lpfc driver that it is ok to resume normal PCI operation after PCI bus
15381  * error recovery. After this call, traffic can start to flow from this device
15382  * again.
15383  **/
15384 static void
15385 lpfc_io_resume_s4(struct pci_dev *pdev)
15386 {
15387 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15388 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15389 
15390 	/*
15391 	 * In case of slot reset, as function reset is performed through
15392 	 * mailbox command which needs DMA to be enabled, this operation
15393 	 * has to be moved to the io resume phase. Taking device offline
15394 	 * will perform the necessary cleanup.
15395 	 */
15396 	if (!(phba->sli.sli_flag & LPFC_SLI_ACTIVE)) {
15397 		/* Perform device reset */
15398 		lpfc_sli_brdrestart(phba);
15399 		/* Bring the device back online */
15400 		lpfc_online(phba);
15401 	}
15402 }
15403 
15404 /**
15405  * lpfc_pci_probe_one - lpfc PCI probe func to reg dev to PCI subsystem
15406  * @pdev: pointer to PCI device
15407  * @pid: pointer to PCI device identifier
15408  *
15409  * This routine is to be registered to the kernel's PCI subsystem. When an
15410  * Emulex HBA device is presented on PCI bus, the kernel PCI subsystem looks
15411  * at PCI device-specific information of the device and driver to see if the
15412  * driver state that it can support this kind of device. If the match is
15413  * successful, the driver core invokes this routine. This routine dispatches
15414  * the action to the proper SLI-3 or SLI-4 device probing routine, which will
15415  * do all the initialization that it needs to do to handle the HBA device
15416  * properly.
15417  *
15418  * Return code
15419  * 	0 - driver can claim the device
15420  * 	negative value - driver can not claim the device
15421  **/
15422 static int
15423 lpfc_pci_probe_one(struct pci_dev *pdev, const struct pci_device_id *pid)
15424 {
15425 	int rc;
15426 	struct lpfc_sli_intf intf;
15427 
15428 	if (pci_read_config_dword(pdev, LPFC_SLI_INTF, &intf.word0))
15429 		return -ENODEV;
15430 
15431 	if ((bf_get(lpfc_sli_intf_valid, &intf) == LPFC_SLI_INTF_VALID) &&
15432 	    (bf_get(lpfc_sli_intf_slirev, &intf) == LPFC_SLI_INTF_REV_SLI4))
15433 		rc = lpfc_pci_probe_one_s4(pdev, pid);
15434 	else
15435 		rc = lpfc_pci_probe_one_s3(pdev, pid);
15436 
15437 	return rc;
15438 }
15439 
15440 /**
15441  * lpfc_pci_remove_one - lpfc PCI func to unreg dev from PCI subsystem
15442  * @pdev: pointer to PCI device
15443  *
15444  * This routine is to be registered to the kernel's PCI subsystem. When an
15445  * Emulex HBA is removed from PCI bus, the driver core invokes this routine.
15446  * This routine dispatches the action to the proper SLI-3 or SLI-4 device
15447  * remove routine, which will perform all the necessary cleanup for the
15448  * device to be removed from the PCI subsystem properly.
15449  **/
15450 static void
15451 lpfc_pci_remove_one(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 	switch (phba->pci_dev_grp) {
15457 	case LPFC_PCI_DEV_LP:
15458 		lpfc_pci_remove_one_s3(pdev);
15459 		break;
15460 	case LPFC_PCI_DEV_OC:
15461 		lpfc_pci_remove_one_s4(pdev);
15462 		break;
15463 	default:
15464 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15465 				"1424 Invalid PCI device group: 0x%x\n",
15466 				phba->pci_dev_grp);
15467 		break;
15468 	}
15469 	return;
15470 }
15471 
15472 /**
15473  * lpfc_pci_suspend_one - lpfc PCI func to suspend dev for power management
15474  * @dev: pointer to device
15475  *
15476  * This routine is to be registered to the kernel's PCI subsystem to support
15477  * system Power Management (PM). When PM invokes this method, it dispatches
15478  * the action to the proper SLI-3 or SLI-4 device suspend routine, which will
15479  * suspend the device.
15480  *
15481  * Return code
15482  * 	0 - driver suspended the device
15483  * 	Error otherwise
15484  **/
15485 static int __maybe_unused
15486 lpfc_pci_suspend_one(struct device *dev)
15487 {
15488 	struct Scsi_Host *shost = dev_get_drvdata(dev);
15489 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15490 	int rc = -ENODEV;
15491 
15492 	switch (phba->pci_dev_grp) {
15493 	case LPFC_PCI_DEV_LP:
15494 		rc = lpfc_pci_suspend_one_s3(dev);
15495 		break;
15496 	case LPFC_PCI_DEV_OC:
15497 		rc = lpfc_pci_suspend_one_s4(dev);
15498 		break;
15499 	default:
15500 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15501 				"1425 Invalid PCI device group: 0x%x\n",
15502 				phba->pci_dev_grp);
15503 		break;
15504 	}
15505 	return rc;
15506 }
15507 
15508 /**
15509  * lpfc_pci_resume_one - lpfc PCI func to resume dev for power management
15510  * @dev: pointer to device
15511  *
15512  * This routine is to be registered to the kernel's PCI subsystem to support
15513  * system Power Management (PM). When PM invokes this method, it dispatches
15514  * the action to the proper SLI-3 or SLI-4 device resume routine, which will
15515  * resume the device.
15516  *
15517  * Return code
15518  * 	0 - driver suspended the device
15519  * 	Error otherwise
15520  **/
15521 static int __maybe_unused
15522 lpfc_pci_resume_one(struct device *dev)
15523 {
15524 	struct Scsi_Host *shost = dev_get_drvdata(dev);
15525 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15526 	int rc = -ENODEV;
15527 
15528 	switch (phba->pci_dev_grp) {
15529 	case LPFC_PCI_DEV_LP:
15530 		rc = lpfc_pci_resume_one_s3(dev);
15531 		break;
15532 	case LPFC_PCI_DEV_OC:
15533 		rc = lpfc_pci_resume_one_s4(dev);
15534 		break;
15535 	default:
15536 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15537 				"1426 Invalid PCI device group: 0x%x\n",
15538 				phba->pci_dev_grp);
15539 		break;
15540 	}
15541 	return rc;
15542 }
15543 
15544 /**
15545  * lpfc_io_error_detected - lpfc method for handling PCI I/O error
15546  * @pdev: pointer to PCI device.
15547  * @state: the current PCI connection state.
15548  *
15549  * This routine is registered to the PCI subsystem for error handling. This
15550  * function is called by the PCI subsystem after a PCI bus error affecting
15551  * this device has been detected. When this routine is invoked, it dispatches
15552  * the action to the proper SLI-3 or SLI-4 device error detected handling
15553  * routine, which will perform the proper error detected operation.
15554  *
15555  * Return codes
15556  * 	PCI_ERS_RESULT_NEED_RESET - need to reset before recovery
15557  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15558  **/
15559 static pci_ers_result_t
15560 lpfc_io_error_detected(struct pci_dev *pdev, pci_channel_state_t state)
15561 {
15562 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15563 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15564 	pci_ers_result_t rc = PCI_ERS_RESULT_DISCONNECT;
15565 
15566 	if (phba->link_state == LPFC_HBA_ERROR &&
15567 	    phba->hba_flag & HBA_IOQ_FLUSH)
15568 		return PCI_ERS_RESULT_NEED_RESET;
15569 
15570 	switch (phba->pci_dev_grp) {
15571 	case LPFC_PCI_DEV_LP:
15572 		rc = lpfc_io_error_detected_s3(pdev, state);
15573 		break;
15574 	case LPFC_PCI_DEV_OC:
15575 		rc = lpfc_io_error_detected_s4(pdev, state);
15576 		break;
15577 	default:
15578 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15579 				"1427 Invalid PCI device group: 0x%x\n",
15580 				phba->pci_dev_grp);
15581 		break;
15582 	}
15583 	return rc;
15584 }
15585 
15586 /**
15587  * lpfc_io_slot_reset - lpfc method for restart PCI dev from scratch
15588  * @pdev: pointer to PCI device.
15589  *
15590  * This routine is registered to the PCI subsystem for error handling. This
15591  * function is called after PCI bus has been reset to restart the PCI card
15592  * from scratch, as if from a cold-boot. When this routine is invoked, it
15593  * dispatches the action to the proper SLI-3 or SLI-4 device reset handling
15594  * routine, which will perform the proper device reset.
15595  *
15596  * Return codes
15597  * 	PCI_ERS_RESULT_RECOVERED - the device has been recovered
15598  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15599  **/
15600 static pci_ers_result_t
15601 lpfc_io_slot_reset(struct pci_dev *pdev)
15602 {
15603 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15604 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15605 	pci_ers_result_t rc = PCI_ERS_RESULT_DISCONNECT;
15606 
15607 	switch (phba->pci_dev_grp) {
15608 	case LPFC_PCI_DEV_LP:
15609 		rc = lpfc_io_slot_reset_s3(pdev);
15610 		break;
15611 	case LPFC_PCI_DEV_OC:
15612 		rc = lpfc_io_slot_reset_s4(pdev);
15613 		break;
15614 	default:
15615 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15616 				"1428 Invalid PCI device group: 0x%x\n",
15617 				phba->pci_dev_grp);
15618 		break;
15619 	}
15620 	return rc;
15621 }
15622 
15623 /**
15624  * lpfc_io_resume - lpfc method for resuming PCI I/O operation
15625  * @pdev: pointer to PCI device
15626  *
15627  * This routine is registered to the PCI subsystem for error handling. It
15628  * is called when kernel error recovery tells the lpfc driver that it is
15629  * OK to resume normal PCI operation after PCI bus error recovery. When
15630  * this routine is invoked, it dispatches the action to the proper SLI-3
15631  * or SLI-4 device io_resume routine, which will resume the device operation.
15632  **/
15633 static void
15634 lpfc_io_resume(struct pci_dev *pdev)
15635 {
15636 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15637 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15638 
15639 	switch (phba->pci_dev_grp) {
15640 	case LPFC_PCI_DEV_LP:
15641 		lpfc_io_resume_s3(pdev);
15642 		break;
15643 	case LPFC_PCI_DEV_OC:
15644 		lpfc_io_resume_s4(pdev);
15645 		break;
15646 	default:
15647 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15648 				"1429 Invalid PCI device group: 0x%x\n",
15649 				phba->pci_dev_grp);
15650 		break;
15651 	}
15652 	return;
15653 }
15654 
15655 /**
15656  * lpfc_sli4_oas_verify - Verify OAS is supported by this adapter
15657  * @phba: pointer to lpfc hba data structure.
15658  *
15659  * This routine checks to see if OAS is supported for this adapter. If
15660  * supported, the configure Flash Optimized Fabric flag is set.  Otherwise,
15661  * the enable oas flag is cleared and the pool created for OAS device data
15662  * is destroyed.
15663  *
15664  **/
15665 static void
15666 lpfc_sli4_oas_verify(struct lpfc_hba *phba)
15667 {
15668 
15669 	if (!phba->cfg_EnableXLane)
15670 		return;
15671 
15672 	if (phba->sli4_hba.pc_sli4_params.oas_supported) {
15673 		phba->cfg_fof = 1;
15674 	} else {
15675 		phba->cfg_fof = 0;
15676 		mempool_destroy(phba->device_data_mem_pool);
15677 		phba->device_data_mem_pool = NULL;
15678 	}
15679 
15680 	return;
15681 }
15682 
15683 /**
15684  * lpfc_sli4_ras_init - Verify RAS-FW log is supported by this adapter
15685  * @phba: pointer to lpfc hba data structure.
15686  *
15687  * This routine checks to see if RAS is supported by the adapter. Check the
15688  * function through which RAS support enablement is to be done.
15689  **/
15690 void
15691 lpfc_sli4_ras_init(struct lpfc_hba *phba)
15692 {
15693 	/* if ASIC_GEN_NUM >= 0xC) */
15694 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
15695 		    LPFC_SLI_INTF_IF_TYPE_6) ||
15696 	    (bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf) ==
15697 		    LPFC_SLI_INTF_FAMILY_G6)) {
15698 		phba->ras_fwlog.ras_hwsupport = true;
15699 		if (phba->cfg_ras_fwlog_func == PCI_FUNC(phba->pcidev->devfn) &&
15700 		    phba->cfg_ras_fwlog_buffsize)
15701 			phba->ras_fwlog.ras_enabled = true;
15702 		else
15703 			phba->ras_fwlog.ras_enabled = false;
15704 	} else {
15705 		phba->ras_fwlog.ras_hwsupport = false;
15706 	}
15707 }
15708 
15709 
15710 MODULE_DEVICE_TABLE(pci, lpfc_id_table);
15711 
15712 static const struct pci_error_handlers lpfc_err_handler = {
15713 	.error_detected = lpfc_io_error_detected,
15714 	.slot_reset = lpfc_io_slot_reset,
15715 	.resume = lpfc_io_resume,
15716 };
15717 
15718 static SIMPLE_DEV_PM_OPS(lpfc_pci_pm_ops_one,
15719 			 lpfc_pci_suspend_one,
15720 			 lpfc_pci_resume_one);
15721 
15722 static struct pci_driver lpfc_driver = {
15723 	.name		= LPFC_DRIVER_NAME,
15724 	.id_table	= lpfc_id_table,
15725 	.probe		= lpfc_pci_probe_one,
15726 	.remove		= lpfc_pci_remove_one,
15727 	.shutdown	= lpfc_pci_remove_one,
15728 	.driver.pm	= &lpfc_pci_pm_ops_one,
15729 	.err_handler    = &lpfc_err_handler,
15730 };
15731 
15732 static const struct file_operations lpfc_mgmt_fop = {
15733 	.owner = THIS_MODULE,
15734 };
15735 
15736 static struct miscdevice lpfc_mgmt_dev = {
15737 	.minor = MISC_DYNAMIC_MINOR,
15738 	.name = "lpfcmgmt",
15739 	.fops = &lpfc_mgmt_fop,
15740 };
15741 
15742 /**
15743  * lpfc_init - lpfc module initialization routine
15744  *
15745  * This routine is to be invoked when the lpfc module is loaded into the
15746  * kernel. The special kernel macro module_init() is used to indicate the
15747  * role of this routine to the kernel as lpfc module entry point.
15748  *
15749  * Return codes
15750  *   0 - successful
15751  *   -ENOMEM - FC attach transport failed
15752  *   all others - failed
15753  */
15754 static int __init
15755 lpfc_init(void)
15756 {
15757 	int error = 0;
15758 
15759 	pr_info(LPFC_MODULE_DESC "\n");
15760 	pr_info(LPFC_COPYRIGHT "\n");
15761 
15762 	error = misc_register(&lpfc_mgmt_dev);
15763 	if (error)
15764 		printk(KERN_ERR "Could not register lpfcmgmt device, "
15765 			"misc_register returned with status %d", error);
15766 
15767 	error = -ENOMEM;
15768 	lpfc_transport_functions.vport_create = lpfc_vport_create;
15769 	lpfc_transport_functions.vport_delete = lpfc_vport_delete;
15770 	lpfc_transport_template =
15771 				fc_attach_transport(&lpfc_transport_functions);
15772 	if (lpfc_transport_template == NULL)
15773 		goto unregister;
15774 	lpfc_vport_transport_template =
15775 		fc_attach_transport(&lpfc_vport_transport_functions);
15776 	if (lpfc_vport_transport_template == NULL) {
15777 		fc_release_transport(lpfc_transport_template);
15778 		goto unregister;
15779 	}
15780 	lpfc_wqe_cmd_template();
15781 	lpfc_nvmet_cmd_template();
15782 
15783 	/* Initialize in case vector mapping is needed */
15784 	lpfc_present_cpu = num_present_cpus();
15785 
15786 	lpfc_pldv_detect = false;
15787 
15788 	error = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN,
15789 					"lpfc/sli4:online",
15790 					lpfc_cpu_online, lpfc_cpu_offline);
15791 	if (error < 0)
15792 		goto cpuhp_failure;
15793 	lpfc_cpuhp_state = error;
15794 
15795 	error = pci_register_driver(&lpfc_driver);
15796 	if (error)
15797 		goto unwind;
15798 
15799 	return error;
15800 
15801 unwind:
15802 	cpuhp_remove_multi_state(lpfc_cpuhp_state);
15803 cpuhp_failure:
15804 	fc_release_transport(lpfc_transport_template);
15805 	fc_release_transport(lpfc_vport_transport_template);
15806 unregister:
15807 	misc_deregister(&lpfc_mgmt_dev);
15808 
15809 	return error;
15810 }
15811 
15812 void lpfc_dmp_dbg(struct lpfc_hba *phba)
15813 {
15814 	unsigned int start_idx;
15815 	unsigned int dbg_cnt;
15816 	unsigned int temp_idx;
15817 	int i;
15818 	int j = 0;
15819 	unsigned long rem_nsec;
15820 
15821 	if (atomic_cmpxchg(&phba->dbg_log_dmping, 0, 1) != 0)
15822 		return;
15823 
15824 	start_idx = (unsigned int)atomic_read(&phba->dbg_log_idx) % DBG_LOG_SZ;
15825 	dbg_cnt = (unsigned int)atomic_read(&phba->dbg_log_cnt);
15826 	if (!dbg_cnt)
15827 		goto out;
15828 	temp_idx = start_idx;
15829 	if (dbg_cnt >= DBG_LOG_SZ) {
15830 		dbg_cnt = DBG_LOG_SZ;
15831 		temp_idx -= 1;
15832 	} else {
15833 		if ((start_idx + dbg_cnt) > (DBG_LOG_SZ - 1)) {
15834 			temp_idx = (start_idx + dbg_cnt) % DBG_LOG_SZ;
15835 		} else {
15836 			if (start_idx < dbg_cnt)
15837 				start_idx = DBG_LOG_SZ - (dbg_cnt - start_idx);
15838 			else
15839 				start_idx -= dbg_cnt;
15840 		}
15841 	}
15842 	dev_info(&phba->pcidev->dev, "start %d end %d cnt %d\n",
15843 		 start_idx, temp_idx, dbg_cnt);
15844 
15845 	for (i = 0; i < dbg_cnt; i++) {
15846 		if ((start_idx + i) < DBG_LOG_SZ)
15847 			temp_idx = (start_idx + i) % DBG_LOG_SZ;
15848 		else
15849 			temp_idx = j++;
15850 		rem_nsec = do_div(phba->dbg_log[temp_idx].t_ns, NSEC_PER_SEC);
15851 		dev_info(&phba->pcidev->dev, "%d: [%5lu.%06lu] %s",
15852 			 temp_idx,
15853 			 (unsigned long)phba->dbg_log[temp_idx].t_ns,
15854 			 rem_nsec / 1000,
15855 			 phba->dbg_log[temp_idx].log);
15856 	}
15857 out:
15858 	atomic_set(&phba->dbg_log_cnt, 0);
15859 	atomic_set(&phba->dbg_log_dmping, 0);
15860 }
15861 
15862 __printf(2, 3)
15863 void lpfc_dbg_print(struct lpfc_hba *phba, const char *fmt, ...)
15864 {
15865 	unsigned int idx;
15866 	va_list args;
15867 	int dbg_dmping = atomic_read(&phba->dbg_log_dmping);
15868 	struct va_format vaf;
15869 
15870 
15871 	va_start(args, fmt);
15872 	if (unlikely(dbg_dmping)) {
15873 		vaf.fmt = fmt;
15874 		vaf.va = &args;
15875 		dev_info(&phba->pcidev->dev, "%pV", &vaf);
15876 		va_end(args);
15877 		return;
15878 	}
15879 	idx = (unsigned int)atomic_fetch_add(1, &phba->dbg_log_idx) %
15880 		DBG_LOG_SZ;
15881 
15882 	atomic_inc(&phba->dbg_log_cnt);
15883 
15884 	vscnprintf(phba->dbg_log[idx].log,
15885 		   sizeof(phba->dbg_log[idx].log), fmt, args);
15886 	va_end(args);
15887 
15888 	phba->dbg_log[idx].t_ns = local_clock();
15889 }
15890 
15891 /**
15892  * lpfc_exit - lpfc module removal routine
15893  *
15894  * This routine is invoked when the lpfc module is removed from the kernel.
15895  * The special kernel macro module_exit() is used to indicate the role of
15896  * this routine to the kernel as lpfc module exit point.
15897  */
15898 static void __exit
15899 lpfc_exit(void)
15900 {
15901 	misc_deregister(&lpfc_mgmt_dev);
15902 	pci_unregister_driver(&lpfc_driver);
15903 	cpuhp_remove_multi_state(lpfc_cpuhp_state);
15904 	fc_release_transport(lpfc_transport_template);
15905 	fc_release_transport(lpfc_vport_transport_template);
15906 	idr_destroy(&lpfc_hba_index);
15907 }
15908 
15909 module_init(lpfc_init);
15910 module_exit(lpfc_exit);
15911 MODULE_LICENSE("GPL");
15912 MODULE_DESCRIPTION(LPFC_MODULE_DESC);
15913 MODULE_AUTHOR("Broadcom");
15914 MODULE_VERSION("0:" LPFC_DRIVER_VERSION);
15915