xref: /linux/drivers/scsi/lpfc/lpfc_init.c (revision 7f71507851fc7764b36a3221839607d3a45c2025)
1 /*******************************************************************
2  * This file is part of the Emulex Linux Device Driver for         *
3  * Fibre Channel Host Bus Adapters.                                *
4  * Copyright (C) 2017-2024 Broadcom. All Rights Reserved. The term *
5  * “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.  *
6  * Copyright (C) 2004-2016 Emulex.  All rights reserved.           *
7  * EMULEX and SLI are trademarks of Emulex.                        *
8  * www.broadcom.com                                                *
9  * Portions Copyright (C) 2004-2005 Christoph Hellwig              *
10  *                                                                 *
11  * This program is free software; you can redistribute it and/or   *
12  * modify it under the terms of version 2 of the GNU General       *
13  * Public License as published by the Free Software Foundation.    *
14  * This program is distributed in the hope that it will be useful. *
15  * ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND          *
16  * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,  *
17  * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE      *
18  * DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD *
19  * TO BE LEGALLY INVALID.  See the GNU General Public License for  *
20  * more details, a copy of which can be found in the file COPYING  *
21  * included with this package.                                     *
22  *******************************************************************/
23 
24 #include <linux/blkdev.h>
25 #include <linux/delay.h>
26 #include <linux/dma-mapping.h>
27 #include <linux/idr.h>
28 #include <linux/interrupt.h>
29 #include <linux/module.h>
30 #include <linux/kthread.h>
31 #include <linux/pci.h>
32 #include <linux/spinlock.h>
33 #include <linux/sched/clock.h>
34 #include <linux/ctype.h>
35 #include <linux/slab.h>
36 #include <linux/firmware.h>
37 #include <linux/miscdevice.h>
38 #include <linux/percpu.h>
39 #include <linux/irq.h>
40 #include <linux/bitops.h>
41 #include <linux/crash_dump.h>
42 #include <linux/cpu.h>
43 #include <linux/cpuhotplug.h>
44 
45 #include <scsi/scsi.h>
46 #include <scsi/scsi_device.h>
47 #include <scsi/scsi_host.h>
48 #include <scsi/scsi_transport_fc.h>
49 #include <scsi/scsi_tcq.h>
50 #include <scsi/fc/fc_fs.h>
51 
52 #include "lpfc_hw4.h"
53 #include "lpfc_hw.h"
54 #include "lpfc_sli.h"
55 #include "lpfc_sli4.h"
56 #include "lpfc_nl.h"
57 #include "lpfc_disc.h"
58 #include "lpfc.h"
59 #include "lpfc_scsi.h"
60 #include "lpfc_nvme.h"
61 #include "lpfc_logmsg.h"
62 #include "lpfc_crtn.h"
63 #include "lpfc_vport.h"
64 #include "lpfc_version.h"
65 #include "lpfc_ids.h"
66 
67 static enum cpuhp_state lpfc_cpuhp_state;
68 /* Used when mapping IRQ vectors in a driver centric manner */
69 static uint32_t lpfc_present_cpu;
70 static bool lpfc_pldv_detect;
71 
72 static void __lpfc_cpuhp_remove(struct lpfc_hba *phba);
73 static void lpfc_cpuhp_remove(struct lpfc_hba *phba);
74 static void lpfc_cpuhp_add(struct lpfc_hba *phba);
75 static void lpfc_get_hba_model_desc(struct lpfc_hba *, uint8_t *, uint8_t *);
76 static int lpfc_post_rcv_buf(struct lpfc_hba *);
77 static int lpfc_sli4_queue_verify(struct lpfc_hba *);
78 static int lpfc_create_bootstrap_mbox(struct lpfc_hba *);
79 static int lpfc_setup_endian_order(struct lpfc_hba *);
80 static void lpfc_destroy_bootstrap_mbox(struct lpfc_hba *);
81 static void lpfc_free_els_sgl_list(struct lpfc_hba *);
82 static void lpfc_free_nvmet_sgl_list(struct lpfc_hba *);
83 static void lpfc_init_sgl_list(struct lpfc_hba *);
84 static int lpfc_init_active_sgl_array(struct lpfc_hba *);
85 static void lpfc_free_active_sgl(struct lpfc_hba *);
86 static int lpfc_hba_down_post_s3(struct lpfc_hba *phba);
87 static int lpfc_hba_down_post_s4(struct lpfc_hba *phba);
88 static int lpfc_sli4_cq_event_pool_create(struct lpfc_hba *);
89 static void lpfc_sli4_cq_event_pool_destroy(struct lpfc_hba *);
90 static void lpfc_sli4_cq_event_release_all(struct lpfc_hba *);
91 static void lpfc_sli4_disable_intr(struct lpfc_hba *);
92 static uint32_t lpfc_sli4_enable_intr(struct lpfc_hba *, uint32_t);
93 static void lpfc_sli4_oas_verify(struct lpfc_hba *phba);
94 static uint16_t lpfc_find_cpu_handle(struct lpfc_hba *, uint16_t, int);
95 static void lpfc_setup_bg(struct lpfc_hba *, struct Scsi_Host *);
96 static int lpfc_sli4_cgn_parm_chg_evt(struct lpfc_hba *);
97 static void lpfc_sli4_async_cmstat_evt(struct lpfc_hba *phba);
98 static void lpfc_sli4_prep_dev_for_reset(struct lpfc_hba *phba);
99 
100 static struct scsi_transport_template *lpfc_transport_template = NULL;
101 static struct scsi_transport_template *lpfc_vport_transport_template = NULL;
102 static DEFINE_IDR(lpfc_hba_index);
103 #define LPFC_NVMET_BUF_POST 254
104 static int lpfc_vmid_res_alloc(struct lpfc_hba *phba, struct lpfc_vport *vport);
105 static void lpfc_cgn_update_tstamp(struct lpfc_hba *phba, struct lpfc_cgn_ts *ts);
106 
107 /**
108  * lpfc_config_port_prep - Perform lpfc initialization prior to config port
109  * @phba: pointer to lpfc hba data structure.
110  *
111  * This routine will do LPFC initialization prior to issuing the CONFIG_PORT
112  * mailbox command. It retrieves the revision information from the HBA and
113  * collects the Vital Product Data (VPD) about the HBA for preparing the
114  * configuration of the HBA.
115  *
116  * Return codes:
117  *   0 - success.
118  *   -ERESTART - requests the SLI layer to reset the HBA and try again.
119  *   Any other value - indicates an error.
120  **/
121 int
122 lpfc_config_port_prep(struct lpfc_hba *phba)
123 {
124 	lpfc_vpd_t *vp = &phba->vpd;
125 	int i = 0, rc;
126 	LPFC_MBOXQ_t *pmb;
127 	MAILBOX_t *mb;
128 	char *lpfc_vpd_data = NULL;
129 	uint16_t offset = 0;
130 	static char licensed[56] =
131 		    "key unlock for use with gnu public licensed code only\0";
132 	static int init_key = 1;
133 
134 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
135 	if (!pmb) {
136 		phba->link_state = LPFC_HBA_ERROR;
137 		return -ENOMEM;
138 	}
139 
140 	mb = &pmb->u.mb;
141 	phba->link_state = LPFC_INIT_MBX_CMDS;
142 
143 	if (lpfc_is_LC_HBA(phba->pcidev->device)) {
144 		if (init_key) {
145 			uint32_t *ptext = (uint32_t *) licensed;
146 
147 			for (i = 0; i < 56; i += sizeof (uint32_t), ptext++)
148 				*ptext = cpu_to_be32(*ptext);
149 			init_key = 0;
150 		}
151 
152 		lpfc_read_nv(phba, pmb);
153 		memset((char*)mb->un.varRDnvp.rsvd3, 0,
154 			sizeof (mb->un.varRDnvp.rsvd3));
155 		memcpy((char*)mb->un.varRDnvp.rsvd3, licensed,
156 			 sizeof (licensed));
157 
158 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
159 
160 		if (rc != MBX_SUCCESS) {
161 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
162 					"0324 Config Port initialization "
163 					"error, mbxCmd x%x READ_NVPARM, "
164 					"mbxStatus x%x\n",
165 					mb->mbxCommand, mb->mbxStatus);
166 			mempool_free(pmb, phba->mbox_mem_pool);
167 			return -ERESTART;
168 		}
169 		memcpy(phba->wwnn, (char *)mb->un.varRDnvp.nodename,
170 		       sizeof(phba->wwnn));
171 		memcpy(phba->wwpn, (char *)mb->un.varRDnvp.portname,
172 		       sizeof(phba->wwpn));
173 	}
174 
175 	/*
176 	 * Clear all option bits except LPFC_SLI3_BG_ENABLED,
177 	 * which was already set in lpfc_get_cfgparam()
178 	 */
179 	phba->sli3_options &= (uint32_t)LPFC_SLI3_BG_ENABLED;
180 
181 	/* Setup and issue mailbox READ REV command */
182 	lpfc_read_rev(phba, pmb);
183 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
184 	if (rc != MBX_SUCCESS) {
185 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
186 				"0439 Adapter failed to init, mbxCmd x%x "
187 				"READ_REV, mbxStatus x%x\n",
188 				mb->mbxCommand, mb->mbxStatus);
189 		mempool_free( pmb, phba->mbox_mem_pool);
190 		return -ERESTART;
191 	}
192 
193 
194 	/*
195 	 * The value of rr must be 1 since the driver set the cv field to 1.
196 	 * This setting requires the FW to set all revision fields.
197 	 */
198 	if (mb->un.varRdRev.rr == 0) {
199 		vp->rev.rBit = 0;
200 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
201 				"0440 Adapter failed to init, READ_REV has "
202 				"missing revision information.\n");
203 		mempool_free(pmb, phba->mbox_mem_pool);
204 		return -ERESTART;
205 	}
206 
207 	if (phba->sli_rev == 3 && !mb->un.varRdRev.v3rsp) {
208 		mempool_free(pmb, phba->mbox_mem_pool);
209 		return -EINVAL;
210 	}
211 
212 	/* Save information as VPD data */
213 	vp->rev.rBit = 1;
214 	memcpy(&vp->sli3Feat, &mb->un.varRdRev.sli3Feat, sizeof(uint32_t));
215 	vp->rev.sli1FwRev = mb->un.varRdRev.sli1FwRev;
216 	memcpy(vp->rev.sli1FwName, (char*) mb->un.varRdRev.sli1FwName, 16);
217 	vp->rev.sli2FwRev = mb->un.varRdRev.sli2FwRev;
218 	memcpy(vp->rev.sli2FwName, (char *) mb->un.varRdRev.sli2FwName, 16);
219 	vp->rev.biuRev = mb->un.varRdRev.biuRev;
220 	vp->rev.smRev = mb->un.varRdRev.smRev;
221 	vp->rev.smFwRev = mb->un.varRdRev.un.smFwRev;
222 	vp->rev.endecRev = mb->un.varRdRev.endecRev;
223 	vp->rev.fcphHigh = mb->un.varRdRev.fcphHigh;
224 	vp->rev.fcphLow = mb->un.varRdRev.fcphLow;
225 	vp->rev.feaLevelHigh = mb->un.varRdRev.feaLevelHigh;
226 	vp->rev.feaLevelLow = mb->un.varRdRev.feaLevelLow;
227 	vp->rev.postKernRev = mb->un.varRdRev.postKernRev;
228 	vp->rev.opFwRev = mb->un.varRdRev.opFwRev;
229 
230 	/* If the sli feature level is less then 9, we must
231 	 * tear down all RPIs and VPIs on link down if NPIV
232 	 * is enabled.
233 	 */
234 	if (vp->rev.feaLevelHigh < 9)
235 		phba->sli3_options |= LPFC_SLI3_VPORT_TEARDOWN;
236 
237 	if (lpfc_is_LC_HBA(phba->pcidev->device))
238 		memcpy(phba->RandomData, (char *)&mb->un.varWords[24],
239 						sizeof (phba->RandomData));
240 
241 	/* Get adapter VPD information */
242 	lpfc_vpd_data = kmalloc(DMP_VPD_SIZE, GFP_KERNEL);
243 	if (!lpfc_vpd_data)
244 		goto out_free_mbox;
245 	do {
246 		lpfc_dump_mem(phba, pmb, offset, DMP_REGION_VPD);
247 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
248 
249 		if (rc != MBX_SUCCESS) {
250 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
251 					"0441 VPD not present on adapter, "
252 					"mbxCmd x%x DUMP VPD, mbxStatus x%x\n",
253 					mb->mbxCommand, mb->mbxStatus);
254 			mb->un.varDmp.word_cnt = 0;
255 		}
256 		/* dump mem may return a zero when finished or we got a
257 		 * mailbox error, either way we are done.
258 		 */
259 		if (mb->un.varDmp.word_cnt == 0)
260 			break;
261 
262 		if (mb->un.varDmp.word_cnt > DMP_VPD_SIZE - offset)
263 			mb->un.varDmp.word_cnt = DMP_VPD_SIZE - offset;
264 		lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
265 				      lpfc_vpd_data + offset,
266 				      mb->un.varDmp.word_cnt);
267 		offset += mb->un.varDmp.word_cnt;
268 	} while (mb->un.varDmp.word_cnt && offset < DMP_VPD_SIZE);
269 
270 	lpfc_parse_vpd(phba, lpfc_vpd_data, offset);
271 
272 	kfree(lpfc_vpd_data);
273 out_free_mbox:
274 	mempool_free(pmb, phba->mbox_mem_pool);
275 	return 0;
276 }
277 
278 /**
279  * lpfc_config_async_cmpl - Completion handler for config async event mbox cmd
280  * @phba: pointer to lpfc hba data structure.
281  * @pmboxq: pointer to the driver internal queue element for mailbox command.
282  *
283  * This is the completion handler for driver's configuring asynchronous event
284  * mailbox command to the device. If the mailbox command returns successfully,
285  * it will set internal async event support flag to 1; otherwise, it will
286  * set internal async event support flag to 0.
287  **/
288 static void
289 lpfc_config_async_cmpl(struct lpfc_hba * phba, LPFC_MBOXQ_t * pmboxq)
290 {
291 	if (pmboxq->u.mb.mbxStatus == MBX_SUCCESS)
292 		phba->temp_sensor_support = 1;
293 	else
294 		phba->temp_sensor_support = 0;
295 	mempool_free(pmboxq, phba->mbox_mem_pool);
296 	return;
297 }
298 
299 /**
300  * lpfc_dump_wakeup_param_cmpl - dump memory mailbox command completion handler
301  * @phba: pointer to lpfc hba data structure.
302  * @pmboxq: pointer to the driver internal queue element for mailbox command.
303  *
304  * This is the completion handler for dump mailbox command for getting
305  * wake up parameters. When this command complete, the response contain
306  * Option rom version of the HBA. This function translate the version number
307  * into a human readable string and store it in OptionROMVersion.
308  **/
309 static void
310 lpfc_dump_wakeup_param_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
311 {
312 	struct prog_id *prg;
313 	uint32_t prog_id_word;
314 	char dist = ' ';
315 	/* character array used for decoding dist type. */
316 	char dist_char[] = "nabx";
317 
318 	if (pmboxq->u.mb.mbxStatus != MBX_SUCCESS) {
319 		mempool_free(pmboxq, phba->mbox_mem_pool);
320 		return;
321 	}
322 
323 	prg = (struct prog_id *) &prog_id_word;
324 
325 	/* word 7 contain option rom version */
326 	prog_id_word = pmboxq->u.mb.un.varWords[7];
327 
328 	/* Decode the Option rom version word to a readable string */
329 	dist = dist_char[prg->dist];
330 
331 	if ((prg->dist == 3) && (prg->num == 0))
332 		snprintf(phba->OptionROMVersion, 32, "%d.%d%d",
333 			prg->ver, prg->rev, prg->lev);
334 	else
335 		snprintf(phba->OptionROMVersion, 32, "%d.%d%d%c%d",
336 			prg->ver, prg->rev, prg->lev,
337 			dist, prg->num);
338 	mempool_free(pmboxq, phba->mbox_mem_pool);
339 	return;
340 }
341 
342 /**
343  * lpfc_update_vport_wwn - Updates the fc_nodename, fc_portname,
344  * @vport: pointer to lpfc vport data structure.
345  *
346  *
347  * Return codes
348  *   None.
349  **/
350 void
351 lpfc_update_vport_wwn(struct lpfc_vport *vport)
352 {
353 	struct lpfc_hba *phba = vport->phba;
354 
355 	/*
356 	 * If the name is empty or there exists a soft name
357 	 * then copy the service params name, otherwise use the fc name
358 	 */
359 	if (vport->fc_nodename.u.wwn[0] == 0)
360 		memcpy(&vport->fc_nodename, &vport->fc_sparam.nodeName,
361 			sizeof(struct lpfc_name));
362 	else
363 		memcpy(&vport->fc_sparam.nodeName, &vport->fc_nodename,
364 			sizeof(struct lpfc_name));
365 
366 	/*
367 	 * If the port name has changed, then set the Param changes flag
368 	 * to unreg the login
369 	 */
370 	if (vport->fc_portname.u.wwn[0] != 0 &&
371 		memcmp(&vport->fc_portname, &vport->fc_sparam.portName,
372 		       sizeof(struct lpfc_name))) {
373 		vport->vport_flag |= FAWWPN_PARAM_CHG;
374 
375 		if (phba->sli_rev == LPFC_SLI_REV4 &&
376 		    vport->port_type == LPFC_PHYSICAL_PORT &&
377 		    phba->sli4_hba.fawwpn_flag & LPFC_FAWWPN_FABRIC) {
378 			if (!(phba->sli4_hba.fawwpn_flag & LPFC_FAWWPN_CONFIG))
379 				phba->sli4_hba.fawwpn_flag &=
380 						~LPFC_FAWWPN_FABRIC;
381 			lpfc_printf_log(phba, KERN_INFO,
382 					LOG_SLI | LOG_DISCOVERY | LOG_ELS,
383 					"2701 FA-PWWN change WWPN from %llx to "
384 					"%llx: vflag x%x fawwpn_flag x%x\n",
385 					wwn_to_u64(vport->fc_portname.u.wwn),
386 					wwn_to_u64
387 					   (vport->fc_sparam.portName.u.wwn),
388 					vport->vport_flag,
389 					phba->sli4_hba.fawwpn_flag);
390 			memcpy(&vport->fc_portname, &vport->fc_sparam.portName,
391 			       sizeof(struct lpfc_name));
392 		}
393 	}
394 
395 	if (vport->fc_portname.u.wwn[0] == 0)
396 		memcpy(&vport->fc_portname, &vport->fc_sparam.portName,
397 		       sizeof(struct lpfc_name));
398 	else
399 		memcpy(&vport->fc_sparam.portName, &vport->fc_portname,
400 		       sizeof(struct lpfc_name));
401 }
402 
403 /**
404  * lpfc_config_port_post - Perform lpfc initialization after config port
405  * @phba: pointer to lpfc hba data structure.
406  *
407  * This routine will do LPFC initialization after the CONFIG_PORT mailbox
408  * command call. It performs all internal resource and state setups on the
409  * port: post IOCB buffers, enable appropriate host interrupt attentions,
410  * ELS ring timers, etc.
411  *
412  * Return codes
413  *   0 - success.
414  *   Any other value - error.
415  **/
416 int
417 lpfc_config_port_post(struct lpfc_hba *phba)
418 {
419 	struct lpfc_vport *vport = phba->pport;
420 	struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
421 	LPFC_MBOXQ_t *pmb;
422 	MAILBOX_t *mb;
423 	struct lpfc_dmabuf *mp;
424 	struct lpfc_sli *psli = &phba->sli;
425 	uint32_t status, timeout;
426 	int i, j;
427 	int rc;
428 
429 	spin_lock_irq(&phba->hbalock);
430 	/*
431 	 * If the Config port completed correctly the HBA is not
432 	 * over heated any more.
433 	 */
434 	if (phba->over_temp_state == HBA_OVER_TEMP)
435 		phba->over_temp_state = HBA_NORMAL_TEMP;
436 	spin_unlock_irq(&phba->hbalock);
437 
438 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
439 	if (!pmb) {
440 		phba->link_state = LPFC_HBA_ERROR;
441 		return -ENOMEM;
442 	}
443 	mb = &pmb->u.mb;
444 
445 	/* Get login parameters for NID.  */
446 	rc = lpfc_read_sparam(phba, pmb, 0);
447 	if (rc) {
448 		mempool_free(pmb, phba->mbox_mem_pool);
449 		return -ENOMEM;
450 	}
451 
452 	pmb->vport = vport;
453 	if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
454 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
455 				"0448 Adapter failed init, mbxCmd x%x "
456 				"READ_SPARM mbxStatus x%x\n",
457 				mb->mbxCommand, mb->mbxStatus);
458 		phba->link_state = LPFC_HBA_ERROR;
459 		lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
460 		return -EIO;
461 	}
462 
463 	mp = pmb->ctx_buf;
464 
465 	/* This dmabuf was allocated by lpfc_read_sparam. The dmabuf is no
466 	 * longer needed.  Prevent unintended ctx_buf access as the mbox is
467 	 * reused.
468 	 */
469 	memcpy(&vport->fc_sparam, mp->virt, sizeof (struct serv_parm));
470 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
471 	kfree(mp);
472 	pmb->ctx_buf = NULL;
473 	lpfc_update_vport_wwn(vport);
474 
475 	/* Update the fc_host data structures with new wwn. */
476 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
477 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
478 	fc_host_max_npiv_vports(shost) = phba->max_vpi;
479 
480 	/* If no serial number in VPD data, use low 6 bytes of WWNN */
481 	/* This should be consolidated into parse_vpd ? - mr */
482 	if (phba->SerialNumber[0] == 0) {
483 		uint8_t *outptr;
484 
485 		outptr = &vport->fc_nodename.u.s.IEEE[0];
486 		for (i = 0; i < 12; i++) {
487 			status = *outptr++;
488 			j = ((status & 0xf0) >> 4);
489 			if (j <= 9)
490 				phba->SerialNumber[i] =
491 				    (char)((uint8_t) 0x30 + (uint8_t) j);
492 			else
493 				phba->SerialNumber[i] =
494 				    (char)((uint8_t) 0x61 + (uint8_t) (j - 10));
495 			i++;
496 			j = (status & 0xf);
497 			if (j <= 9)
498 				phba->SerialNumber[i] =
499 				    (char)((uint8_t) 0x30 + (uint8_t) j);
500 			else
501 				phba->SerialNumber[i] =
502 				    (char)((uint8_t) 0x61 + (uint8_t) (j - 10));
503 		}
504 	}
505 
506 	lpfc_read_config(phba, pmb);
507 	pmb->vport = vport;
508 	if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
509 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
510 				"0453 Adapter failed to init, mbxCmd x%x "
511 				"READ_CONFIG, mbxStatus x%x\n",
512 				mb->mbxCommand, mb->mbxStatus);
513 		phba->link_state = LPFC_HBA_ERROR;
514 		mempool_free( pmb, phba->mbox_mem_pool);
515 		return -EIO;
516 	}
517 
518 	/* Check if the port is disabled */
519 	lpfc_sli_read_link_ste(phba);
520 
521 	/* Reset the DFT_HBA_Q_DEPTH to the max xri  */
522 	if (phba->cfg_hba_queue_depth > mb->un.varRdConfig.max_xri) {
523 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
524 				"3359 HBA queue depth changed from %d to %d\n",
525 				phba->cfg_hba_queue_depth,
526 				mb->un.varRdConfig.max_xri);
527 		phba->cfg_hba_queue_depth = mb->un.varRdConfig.max_xri;
528 	}
529 
530 	phba->lmt = mb->un.varRdConfig.lmt;
531 
532 	/* Get the default values for Model Name and Description */
533 	lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
534 
535 	phba->link_state = LPFC_LINK_DOWN;
536 
537 	/* Only process IOCBs on ELS ring till hba_state is READY */
538 	if (psli->sli3_ring[LPFC_EXTRA_RING].sli.sli3.cmdringaddr)
539 		psli->sli3_ring[LPFC_EXTRA_RING].flag |= LPFC_STOP_IOCB_EVENT;
540 	if (psli->sli3_ring[LPFC_FCP_RING].sli.sli3.cmdringaddr)
541 		psli->sli3_ring[LPFC_FCP_RING].flag |= LPFC_STOP_IOCB_EVENT;
542 
543 	/* Post receive buffers for desired rings */
544 	if (phba->sli_rev != 3)
545 		lpfc_post_rcv_buf(phba);
546 
547 	/*
548 	 * Configure HBA MSI-X attention conditions to messages if MSI-X mode
549 	 */
550 	if (phba->intr_type == MSIX) {
551 		rc = lpfc_config_msi(phba, pmb);
552 		if (rc) {
553 			mempool_free(pmb, phba->mbox_mem_pool);
554 			return -EIO;
555 		}
556 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
557 		if (rc != MBX_SUCCESS) {
558 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
559 					"0352 Config MSI mailbox command "
560 					"failed, mbxCmd x%x, mbxStatus x%x\n",
561 					pmb->u.mb.mbxCommand,
562 					pmb->u.mb.mbxStatus);
563 			mempool_free(pmb, phba->mbox_mem_pool);
564 			return -EIO;
565 		}
566 	}
567 
568 	spin_lock_irq(&phba->hbalock);
569 	/* Initialize ERATT handling flag */
570 	clear_bit(HBA_ERATT_HANDLED, &phba->hba_flag);
571 
572 	/* Enable appropriate host interrupts */
573 	if (lpfc_readl(phba->HCregaddr, &status)) {
574 		spin_unlock_irq(&phba->hbalock);
575 		return -EIO;
576 	}
577 	status |= HC_MBINT_ENA | HC_ERINT_ENA | HC_LAINT_ENA;
578 	if (psli->num_rings > 0)
579 		status |= HC_R0INT_ENA;
580 	if (psli->num_rings > 1)
581 		status |= HC_R1INT_ENA;
582 	if (psli->num_rings > 2)
583 		status |= HC_R2INT_ENA;
584 	if (psli->num_rings > 3)
585 		status |= HC_R3INT_ENA;
586 
587 	if ((phba->cfg_poll & ENABLE_FCP_RING_POLLING) &&
588 	    (phba->cfg_poll & DISABLE_FCP_RING_INT))
589 		status &= ~(HC_R0INT_ENA);
590 
591 	writel(status, phba->HCregaddr);
592 	readl(phba->HCregaddr); /* flush */
593 	spin_unlock_irq(&phba->hbalock);
594 
595 	/* Set up ring-0 (ELS) timer */
596 	timeout = phba->fc_ratov * 2;
597 	mod_timer(&vport->els_tmofunc,
598 		  jiffies + msecs_to_jiffies(1000 * timeout));
599 	/* Set up heart beat (HB) timer */
600 	mod_timer(&phba->hb_tmofunc,
601 		  jiffies + msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
602 	clear_bit(HBA_HBEAT_INP, &phba->hba_flag);
603 	clear_bit(HBA_HBEAT_TMO, &phba->hba_flag);
604 	phba->last_completion_time = jiffies;
605 	/* Set up error attention (ERATT) polling timer */
606 	mod_timer(&phba->eratt_poll,
607 		  jiffies + msecs_to_jiffies(1000 * phba->eratt_poll_interval));
608 
609 	if (test_bit(LINK_DISABLED, &phba->hba_flag)) {
610 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
611 				"2598 Adapter Link is disabled.\n");
612 		lpfc_down_link(phba, pmb);
613 		pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
614 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
615 		if ((rc != MBX_SUCCESS) && (rc != MBX_BUSY)) {
616 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
617 					"2599 Adapter failed to issue DOWN_LINK"
618 					" mbox command rc 0x%x\n", rc);
619 
620 			mempool_free(pmb, phba->mbox_mem_pool);
621 			return -EIO;
622 		}
623 	} else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
624 		mempool_free(pmb, phba->mbox_mem_pool);
625 		rc = phba->lpfc_hba_init_link(phba, MBX_NOWAIT);
626 		if (rc)
627 			return rc;
628 	}
629 	/* MBOX buffer will be freed in mbox compl */
630 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
631 	if (!pmb) {
632 		phba->link_state = LPFC_HBA_ERROR;
633 		return -ENOMEM;
634 	}
635 
636 	lpfc_config_async(phba, pmb, LPFC_ELS_RING);
637 	pmb->mbox_cmpl = lpfc_config_async_cmpl;
638 	pmb->vport = phba->pport;
639 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
640 
641 	if ((rc != MBX_BUSY) && (rc != MBX_SUCCESS)) {
642 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
643 				"0456 Adapter failed to issue "
644 				"ASYNCEVT_ENABLE mbox status x%x\n",
645 				rc);
646 		mempool_free(pmb, phba->mbox_mem_pool);
647 	}
648 
649 	/* Get Option rom version */
650 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
651 	if (!pmb) {
652 		phba->link_state = LPFC_HBA_ERROR;
653 		return -ENOMEM;
654 	}
655 
656 	lpfc_dump_wakeup_param(phba, pmb);
657 	pmb->mbox_cmpl = lpfc_dump_wakeup_param_cmpl;
658 	pmb->vport = phba->pport;
659 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
660 
661 	if ((rc != MBX_BUSY) && (rc != MBX_SUCCESS)) {
662 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
663 				"0435 Adapter failed "
664 				"to get Option ROM version status x%x\n", rc);
665 		mempool_free(pmb, phba->mbox_mem_pool);
666 	}
667 
668 	return 0;
669 }
670 
671 /**
672  * lpfc_sli4_refresh_params - update driver copy of params.
673  * @phba: Pointer to HBA context object.
674  *
675  * This is called to refresh driver copy of dynamic fields from the
676  * common_get_sli4_parameters descriptor.
677  **/
678 int
679 lpfc_sli4_refresh_params(struct lpfc_hba *phba)
680 {
681 	LPFC_MBOXQ_t *mboxq;
682 	struct lpfc_mqe *mqe;
683 	struct lpfc_sli4_parameters *mbx_sli4_parameters;
684 	int length, rc;
685 
686 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
687 	if (!mboxq)
688 		return -ENOMEM;
689 
690 	mqe = &mboxq->u.mqe;
691 	/* Read the port's SLI4 Config Parameters */
692 	length = (sizeof(struct lpfc_mbx_get_sli4_parameters) -
693 		  sizeof(struct lpfc_sli4_cfg_mhdr));
694 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
695 			 LPFC_MBOX_OPCODE_GET_SLI4_PARAMETERS,
696 			 length, LPFC_SLI4_MBX_EMBED);
697 
698 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
699 	if (unlikely(rc)) {
700 		mempool_free(mboxq, phba->mbox_mem_pool);
701 		return rc;
702 	}
703 	mbx_sli4_parameters = &mqe->un.get_sli4_parameters.sli4_parameters;
704 	phba->sli4_hba.pc_sli4_params.mi_cap =
705 		bf_get(cfg_mi_ver, mbx_sli4_parameters);
706 
707 	/* Are we forcing MI off via module parameter? */
708 	if (phba->cfg_enable_mi)
709 		phba->sli4_hba.pc_sli4_params.mi_ver =
710 			bf_get(cfg_mi_ver, mbx_sli4_parameters);
711 	else
712 		phba->sli4_hba.pc_sli4_params.mi_ver = 0;
713 
714 	phba->sli4_hba.pc_sli4_params.cmf =
715 			bf_get(cfg_cmf, mbx_sli4_parameters);
716 	phba->sli4_hba.pc_sli4_params.pls =
717 			bf_get(cfg_pvl, mbx_sli4_parameters);
718 
719 	mempool_free(mboxq, phba->mbox_mem_pool);
720 	return rc;
721 }
722 
723 /**
724  * lpfc_hba_init_link - Initialize the FC link
725  * @phba: pointer to lpfc hba data structure.
726  * @flag: mailbox command issue mode - either MBX_POLL or MBX_NOWAIT
727  *
728  * This routine will issue the INIT_LINK mailbox command call.
729  * It is available to other drivers through the lpfc_hba data
730  * structure for use as a delayed link up mechanism with the
731  * module parameter lpfc_suppress_link_up.
732  *
733  * Return code
734  *		0 - success
735  *		Any other value - error
736  **/
737 static int
738 lpfc_hba_init_link(struct lpfc_hba *phba, uint32_t flag)
739 {
740 	return lpfc_hba_init_link_fc_topology(phba, phba->cfg_topology, flag);
741 }
742 
743 /**
744  * lpfc_hba_init_link_fc_topology - Initialize FC link with desired topology
745  * @phba: pointer to lpfc hba data structure.
746  * @fc_topology: desired fc topology.
747  * @flag: mailbox command issue mode - either MBX_POLL or MBX_NOWAIT
748  *
749  * This routine will issue the INIT_LINK mailbox command call.
750  * It is available to other drivers through the lpfc_hba data
751  * structure for use as a delayed link up mechanism with the
752  * module parameter lpfc_suppress_link_up.
753  *
754  * Return code
755  *              0 - success
756  *              Any other value - error
757  **/
758 int
759 lpfc_hba_init_link_fc_topology(struct lpfc_hba *phba, uint32_t fc_topology,
760 			       uint32_t flag)
761 {
762 	struct lpfc_vport *vport = phba->pport;
763 	LPFC_MBOXQ_t *pmb;
764 	MAILBOX_t *mb;
765 	int rc;
766 
767 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
768 	if (!pmb) {
769 		phba->link_state = LPFC_HBA_ERROR;
770 		return -ENOMEM;
771 	}
772 	mb = &pmb->u.mb;
773 	pmb->vport = vport;
774 
775 	if ((phba->cfg_link_speed > LPFC_USER_LINK_SPEED_MAX) ||
776 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_1G) &&
777 	     !(phba->lmt & LMT_1Gb)) ||
778 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_2G) &&
779 	     !(phba->lmt & LMT_2Gb)) ||
780 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_4G) &&
781 	     !(phba->lmt & LMT_4Gb)) ||
782 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_8G) &&
783 	     !(phba->lmt & LMT_8Gb)) ||
784 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_10G) &&
785 	     !(phba->lmt & LMT_10Gb)) ||
786 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_16G) &&
787 	     !(phba->lmt & LMT_16Gb)) ||
788 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_32G) &&
789 	     !(phba->lmt & LMT_32Gb)) ||
790 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_64G) &&
791 	     !(phba->lmt & LMT_64Gb))) {
792 		/* Reset link speed to auto */
793 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
794 				"1302 Invalid speed for this board:%d "
795 				"Reset link speed to auto.\n",
796 				phba->cfg_link_speed);
797 			phba->cfg_link_speed = LPFC_USER_LINK_SPEED_AUTO;
798 	}
799 	lpfc_init_link(phba, pmb, fc_topology, phba->cfg_link_speed);
800 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
801 	if (phba->sli_rev < LPFC_SLI_REV4)
802 		lpfc_set_loopback_flag(phba);
803 	rc = lpfc_sli_issue_mbox(phba, pmb, flag);
804 	if ((rc != MBX_BUSY) && (rc != MBX_SUCCESS)) {
805 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
806 				"0498 Adapter failed to init, mbxCmd x%x "
807 				"INIT_LINK, mbxStatus x%x\n",
808 				mb->mbxCommand, mb->mbxStatus);
809 		if (phba->sli_rev <= LPFC_SLI_REV3) {
810 			/* Clear all interrupt enable conditions */
811 			writel(0, phba->HCregaddr);
812 			readl(phba->HCregaddr); /* flush */
813 			/* Clear all pending interrupts */
814 			writel(0xffffffff, phba->HAregaddr);
815 			readl(phba->HAregaddr); /* flush */
816 		}
817 		phba->link_state = LPFC_HBA_ERROR;
818 		if (rc != MBX_BUSY || flag == MBX_POLL)
819 			mempool_free(pmb, phba->mbox_mem_pool);
820 		return -EIO;
821 	}
822 	phba->cfg_suppress_link_up = LPFC_INITIALIZE_LINK;
823 	if (flag == MBX_POLL)
824 		mempool_free(pmb, phba->mbox_mem_pool);
825 
826 	return 0;
827 }
828 
829 /**
830  * lpfc_hba_down_link - this routine downs the FC link
831  * @phba: pointer to lpfc hba data structure.
832  * @flag: mailbox command issue mode - either MBX_POLL or MBX_NOWAIT
833  *
834  * This routine will issue the DOWN_LINK mailbox command call.
835  * It is available to other drivers through the lpfc_hba data
836  * structure for use to stop the link.
837  *
838  * Return code
839  *		0 - success
840  *		Any other value - error
841  **/
842 static int
843 lpfc_hba_down_link(struct lpfc_hba *phba, uint32_t flag)
844 {
845 	LPFC_MBOXQ_t *pmb;
846 	int rc;
847 
848 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
849 	if (!pmb) {
850 		phba->link_state = LPFC_HBA_ERROR;
851 		return -ENOMEM;
852 	}
853 
854 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
855 			"0491 Adapter Link is disabled.\n");
856 	lpfc_down_link(phba, pmb);
857 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
858 	rc = lpfc_sli_issue_mbox(phba, pmb, flag);
859 	if ((rc != MBX_SUCCESS) && (rc != MBX_BUSY)) {
860 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
861 				"2522 Adapter failed to issue DOWN_LINK"
862 				" mbox command rc 0x%x\n", rc);
863 
864 		mempool_free(pmb, phba->mbox_mem_pool);
865 		return -EIO;
866 	}
867 	if (flag == MBX_POLL)
868 		mempool_free(pmb, phba->mbox_mem_pool);
869 
870 	return 0;
871 }
872 
873 /**
874  * lpfc_hba_down_prep - Perform lpfc uninitialization prior to HBA reset
875  * @phba: pointer to lpfc HBA data structure.
876  *
877  * This routine will do LPFC uninitialization before the HBA is reset when
878  * bringing down the SLI Layer.
879  *
880  * Return codes
881  *   0 - success.
882  *   Any other value - error.
883  **/
884 int
885 lpfc_hba_down_prep(struct lpfc_hba *phba)
886 {
887 	struct lpfc_vport **vports;
888 	int i;
889 
890 	if (phba->sli_rev <= LPFC_SLI_REV3) {
891 		/* Disable interrupts */
892 		writel(0, phba->HCregaddr);
893 		readl(phba->HCregaddr); /* flush */
894 	}
895 
896 	if (test_bit(FC_UNLOADING, &phba->pport->load_flag))
897 		lpfc_cleanup_discovery_resources(phba->pport);
898 	else {
899 		vports = lpfc_create_vport_work_array(phba);
900 		if (vports != NULL)
901 			for (i = 0; i <= phba->max_vports &&
902 				vports[i] != NULL; i++)
903 				lpfc_cleanup_discovery_resources(vports[i]);
904 		lpfc_destroy_vport_work_array(phba, vports);
905 	}
906 	return 0;
907 }
908 
909 /**
910  * lpfc_sli4_free_sp_events - Cleanup sp_queue_events to free
911  * rspiocb which got deferred
912  *
913  * @phba: pointer to lpfc HBA data structure.
914  *
915  * This routine will cleanup completed slow path events after HBA is reset
916  * when bringing down the SLI Layer.
917  *
918  *
919  * Return codes
920  *   void.
921  **/
922 static void
923 lpfc_sli4_free_sp_events(struct lpfc_hba *phba)
924 {
925 	struct lpfc_iocbq *rspiocbq;
926 	struct hbq_dmabuf *dmabuf;
927 	struct lpfc_cq_event *cq_event;
928 
929 	clear_bit(HBA_SP_QUEUE_EVT, &phba->hba_flag);
930 
931 	while (!list_empty(&phba->sli4_hba.sp_queue_event)) {
932 		/* Get the response iocb from the head of work queue */
933 		spin_lock_irq(&phba->hbalock);
934 		list_remove_head(&phba->sli4_hba.sp_queue_event,
935 				 cq_event, struct lpfc_cq_event, list);
936 		spin_unlock_irq(&phba->hbalock);
937 
938 		switch (bf_get(lpfc_wcqe_c_code, &cq_event->cqe.wcqe_cmpl)) {
939 		case CQE_CODE_COMPL_WQE:
940 			rspiocbq = container_of(cq_event, struct lpfc_iocbq,
941 						 cq_event);
942 			lpfc_sli_release_iocbq(phba, rspiocbq);
943 			break;
944 		case CQE_CODE_RECEIVE:
945 		case CQE_CODE_RECEIVE_V1:
946 			dmabuf = container_of(cq_event, struct hbq_dmabuf,
947 					      cq_event);
948 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
949 		}
950 	}
951 }
952 
953 /**
954  * lpfc_hba_free_post_buf - Perform lpfc uninitialization after HBA reset
955  * @phba: pointer to lpfc HBA data structure.
956  *
957  * This routine will cleanup posted ELS buffers after the HBA is reset
958  * when bringing down the SLI Layer.
959  *
960  *
961  * Return codes
962  *   void.
963  **/
964 static void
965 lpfc_hba_free_post_buf(struct lpfc_hba *phba)
966 {
967 	struct lpfc_sli *psli = &phba->sli;
968 	struct lpfc_sli_ring *pring;
969 	struct lpfc_dmabuf *mp, *next_mp;
970 	LIST_HEAD(buflist);
971 	int count;
972 
973 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)
974 		lpfc_sli_hbqbuf_free_all(phba);
975 	else {
976 		/* Cleanup preposted buffers on the ELS ring */
977 		pring = &psli->sli3_ring[LPFC_ELS_RING];
978 		spin_lock_irq(&phba->hbalock);
979 		list_splice_init(&pring->postbufq, &buflist);
980 		spin_unlock_irq(&phba->hbalock);
981 
982 		count = 0;
983 		list_for_each_entry_safe(mp, next_mp, &buflist, list) {
984 			list_del(&mp->list);
985 			count++;
986 			lpfc_mbuf_free(phba, mp->virt, mp->phys);
987 			kfree(mp);
988 		}
989 
990 		spin_lock_irq(&phba->hbalock);
991 		pring->postbufq_cnt -= count;
992 		spin_unlock_irq(&phba->hbalock);
993 	}
994 }
995 
996 /**
997  * lpfc_hba_clean_txcmplq - Perform lpfc uninitialization after HBA reset
998  * @phba: pointer to lpfc HBA data structure.
999  *
1000  * This routine will cleanup the txcmplq after the HBA is reset when bringing
1001  * down the SLI Layer.
1002  *
1003  * Return codes
1004  *   void
1005  **/
1006 static void
1007 lpfc_hba_clean_txcmplq(struct lpfc_hba *phba)
1008 {
1009 	struct lpfc_sli *psli = &phba->sli;
1010 	struct lpfc_queue *qp = NULL;
1011 	struct lpfc_sli_ring *pring;
1012 	LIST_HEAD(completions);
1013 	int i;
1014 	struct lpfc_iocbq *piocb, *next_iocb;
1015 
1016 	if (phba->sli_rev != LPFC_SLI_REV4) {
1017 		for (i = 0; i < psli->num_rings; i++) {
1018 			pring = &psli->sli3_ring[i];
1019 			spin_lock_irq(&phba->hbalock);
1020 			/* At this point in time the HBA is either reset or DOA
1021 			 * Nothing should be on txcmplq as it will
1022 			 * NEVER complete.
1023 			 */
1024 			list_splice_init(&pring->txcmplq, &completions);
1025 			pring->txcmplq_cnt = 0;
1026 			spin_unlock_irq(&phba->hbalock);
1027 
1028 			lpfc_sli_abort_iocb_ring(phba, pring);
1029 		}
1030 		/* Cancel all the IOCBs from the completions list */
1031 		lpfc_sli_cancel_iocbs(phba, &completions,
1032 				      IOSTAT_LOCAL_REJECT, IOERR_SLI_ABORTED);
1033 		return;
1034 	}
1035 	list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
1036 		pring = qp->pring;
1037 		if (!pring)
1038 			continue;
1039 		spin_lock_irq(&pring->ring_lock);
1040 		list_for_each_entry_safe(piocb, next_iocb,
1041 					 &pring->txcmplq, list)
1042 			piocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
1043 		list_splice_init(&pring->txcmplq, &completions);
1044 		pring->txcmplq_cnt = 0;
1045 		spin_unlock_irq(&pring->ring_lock);
1046 		lpfc_sli_abort_iocb_ring(phba, pring);
1047 	}
1048 	/* Cancel all the IOCBs from the completions list */
1049 	lpfc_sli_cancel_iocbs(phba, &completions,
1050 			      IOSTAT_LOCAL_REJECT, IOERR_SLI_ABORTED);
1051 }
1052 
1053 /**
1054  * lpfc_hba_down_post_s3 - Perform lpfc uninitialization after HBA reset
1055  * @phba: pointer to lpfc HBA data structure.
1056  *
1057  * This routine will do uninitialization after the HBA is reset when bring
1058  * down the SLI Layer.
1059  *
1060  * Return codes
1061  *   0 - success.
1062  *   Any other value - error.
1063  **/
1064 static int
1065 lpfc_hba_down_post_s3(struct lpfc_hba *phba)
1066 {
1067 	lpfc_hba_free_post_buf(phba);
1068 	lpfc_hba_clean_txcmplq(phba);
1069 	return 0;
1070 }
1071 
1072 /**
1073  * lpfc_hba_down_post_s4 - Perform lpfc uninitialization after HBA reset
1074  * @phba: pointer to lpfc HBA data structure.
1075  *
1076  * This routine will do uninitialization after the HBA is reset when bring
1077  * down the SLI Layer.
1078  *
1079  * Return codes
1080  *   0 - success.
1081  *   Any other value - error.
1082  **/
1083 static int
1084 lpfc_hba_down_post_s4(struct lpfc_hba *phba)
1085 {
1086 	struct lpfc_io_buf *psb, *psb_next;
1087 	struct lpfc_async_xchg_ctx *ctxp, *ctxp_next;
1088 	struct lpfc_sli4_hdw_queue *qp;
1089 	LIST_HEAD(aborts);
1090 	LIST_HEAD(nvme_aborts);
1091 	LIST_HEAD(nvmet_aborts);
1092 	struct lpfc_sglq *sglq_entry = NULL;
1093 	int cnt, idx;
1094 
1095 
1096 	lpfc_sli_hbqbuf_free_all(phba);
1097 	lpfc_hba_clean_txcmplq(phba);
1098 
1099 	/* At this point in time the HBA is either reset or DOA. Either
1100 	 * way, nothing should be on lpfc_abts_els_sgl_list, it needs to be
1101 	 * on the lpfc_els_sgl_list so that it can either be freed if the
1102 	 * driver is unloading or reposted if the driver is restarting
1103 	 * the port.
1104 	 */
1105 
1106 	/* sgl_list_lock required because worker thread uses this
1107 	 * list.
1108 	 */
1109 	spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
1110 	list_for_each_entry(sglq_entry,
1111 		&phba->sli4_hba.lpfc_abts_els_sgl_list, list)
1112 		sglq_entry->state = SGL_FREED;
1113 
1114 	list_splice_init(&phba->sli4_hba.lpfc_abts_els_sgl_list,
1115 			&phba->sli4_hba.lpfc_els_sgl_list);
1116 
1117 
1118 	spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
1119 
1120 	/* abts_xxxx_buf_list_lock required because worker thread uses this
1121 	 * list.
1122 	 */
1123 	spin_lock_irq(&phba->hbalock);
1124 	cnt = 0;
1125 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
1126 		qp = &phba->sli4_hba.hdwq[idx];
1127 
1128 		spin_lock(&qp->abts_io_buf_list_lock);
1129 		list_splice_init(&qp->lpfc_abts_io_buf_list,
1130 				 &aborts);
1131 
1132 		list_for_each_entry_safe(psb, psb_next, &aborts, list) {
1133 			psb->pCmd = NULL;
1134 			psb->status = IOSTAT_SUCCESS;
1135 			cnt++;
1136 		}
1137 		spin_lock(&qp->io_buf_list_put_lock);
1138 		list_splice_init(&aborts, &qp->lpfc_io_buf_list_put);
1139 		qp->put_io_bufs += qp->abts_scsi_io_bufs;
1140 		qp->put_io_bufs += qp->abts_nvme_io_bufs;
1141 		qp->abts_scsi_io_bufs = 0;
1142 		qp->abts_nvme_io_bufs = 0;
1143 		spin_unlock(&qp->io_buf_list_put_lock);
1144 		spin_unlock(&qp->abts_io_buf_list_lock);
1145 	}
1146 	spin_unlock_irq(&phba->hbalock);
1147 
1148 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
1149 		spin_lock_irq(&phba->sli4_hba.abts_nvmet_buf_list_lock);
1150 		list_splice_init(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list,
1151 				 &nvmet_aborts);
1152 		spin_unlock_irq(&phba->sli4_hba.abts_nvmet_buf_list_lock);
1153 		list_for_each_entry_safe(ctxp, ctxp_next, &nvmet_aborts, list) {
1154 			ctxp->flag &= ~(LPFC_NVME_XBUSY | LPFC_NVME_ABORT_OP);
1155 			lpfc_nvmet_ctxbuf_post(phba, ctxp->ctxbuf);
1156 		}
1157 	}
1158 
1159 	lpfc_sli4_free_sp_events(phba);
1160 	return cnt;
1161 }
1162 
1163 /**
1164  * lpfc_hba_down_post - Wrapper func for hba down post routine
1165  * @phba: pointer to lpfc HBA data structure.
1166  *
1167  * This routine wraps the actual SLI3 or SLI4 routine for performing
1168  * uninitialization after the HBA is reset when bring down the SLI Layer.
1169  *
1170  * Return codes
1171  *   0 - success.
1172  *   Any other value - error.
1173  **/
1174 int
1175 lpfc_hba_down_post(struct lpfc_hba *phba)
1176 {
1177 	return (*phba->lpfc_hba_down_post)(phba);
1178 }
1179 
1180 /**
1181  * lpfc_hb_timeout - The HBA-timer timeout handler
1182  * @t: timer context used to obtain the pointer to lpfc hba data structure.
1183  *
1184  * This is the HBA-timer timeout handler registered to the lpfc driver. When
1185  * this timer fires, a HBA timeout event shall be posted to the lpfc driver
1186  * work-port-events bitmap and the worker thread is notified. This timeout
1187  * event will be used by the worker thread to invoke the actual timeout
1188  * handler routine, lpfc_hb_timeout_handler. Any periodical operations will
1189  * be performed in the timeout handler and the HBA timeout event bit shall
1190  * be cleared by the worker thread after it has taken the event bitmap out.
1191  **/
1192 static void
1193 lpfc_hb_timeout(struct timer_list *t)
1194 {
1195 	struct lpfc_hba *phba;
1196 	uint32_t tmo_posted;
1197 	unsigned long iflag;
1198 
1199 	phba = from_timer(phba, t, hb_tmofunc);
1200 
1201 	/* Check for heart beat timeout conditions */
1202 	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
1203 	tmo_posted = phba->pport->work_port_events & WORKER_HB_TMO;
1204 	if (!tmo_posted)
1205 		phba->pport->work_port_events |= WORKER_HB_TMO;
1206 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
1207 
1208 	/* Tell the worker thread there is work to do */
1209 	if (!tmo_posted)
1210 		lpfc_worker_wake_up(phba);
1211 	return;
1212 }
1213 
1214 /**
1215  * lpfc_rrq_timeout - The RRQ-timer timeout handler
1216  * @t: timer context used to obtain the pointer to lpfc hba data structure.
1217  *
1218  * This is the RRQ-timer timeout handler registered to the lpfc driver. When
1219  * this timer fires, a RRQ timeout event shall be posted to the lpfc driver
1220  * work-port-events bitmap and the worker thread is notified. This timeout
1221  * event will be used by the worker thread to invoke the actual timeout
1222  * handler routine, lpfc_rrq_handler. Any periodical operations will
1223  * be performed in the timeout handler and the RRQ timeout event bit shall
1224  * be cleared by the worker thread after it has taken the event bitmap out.
1225  **/
1226 static void
1227 lpfc_rrq_timeout(struct timer_list *t)
1228 {
1229 	struct lpfc_hba *phba;
1230 
1231 	phba = from_timer(phba, t, rrq_tmr);
1232 	if (test_bit(FC_UNLOADING, &phba->pport->load_flag)) {
1233 		clear_bit(HBA_RRQ_ACTIVE, &phba->hba_flag);
1234 		return;
1235 	}
1236 
1237 	set_bit(HBA_RRQ_ACTIVE, &phba->hba_flag);
1238 	lpfc_worker_wake_up(phba);
1239 }
1240 
1241 /**
1242  * lpfc_hb_mbox_cmpl - The lpfc heart-beat mailbox command callback function
1243  * @phba: pointer to lpfc hba data structure.
1244  * @pmboxq: pointer to the driver internal queue element for mailbox command.
1245  *
1246  * This is the callback function to the lpfc heart-beat mailbox command.
1247  * If configured, the lpfc driver issues the heart-beat mailbox command to
1248  * the HBA every LPFC_HB_MBOX_INTERVAL (current 5) seconds. At the time the
1249  * heart-beat mailbox command is issued, the driver shall set up heart-beat
1250  * timeout timer to LPFC_HB_MBOX_TIMEOUT (current 30) seconds and marks
1251  * heart-beat outstanding state. Once the mailbox command comes back and
1252  * no error conditions detected, the heart-beat mailbox command timer is
1253  * reset to LPFC_HB_MBOX_INTERVAL seconds and the heart-beat outstanding
1254  * state is cleared for the next heart-beat. If the timer expired with the
1255  * heart-beat outstanding state set, the driver will put the HBA offline.
1256  **/
1257 static void
1258 lpfc_hb_mbox_cmpl(struct lpfc_hba * phba, LPFC_MBOXQ_t * pmboxq)
1259 {
1260 	clear_bit(HBA_HBEAT_INP, &phba->hba_flag);
1261 	clear_bit(HBA_HBEAT_TMO, &phba->hba_flag);
1262 
1263 	/* Check and reset heart-beat timer if necessary */
1264 	mempool_free(pmboxq, phba->mbox_mem_pool);
1265 	if (!test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag) &&
1266 	    !(phba->link_state == LPFC_HBA_ERROR) &&
1267 	    !test_bit(FC_UNLOADING, &phba->pport->load_flag))
1268 		mod_timer(&phba->hb_tmofunc,
1269 			  jiffies +
1270 			  msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
1271 	return;
1272 }
1273 
1274 /*
1275  * lpfc_idle_stat_delay_work - idle_stat tracking
1276  *
1277  * This routine tracks per-eq idle_stat and determines polling decisions.
1278  *
1279  * Return codes:
1280  *   None
1281  **/
1282 static void
1283 lpfc_idle_stat_delay_work(struct work_struct *work)
1284 {
1285 	struct lpfc_hba *phba = container_of(to_delayed_work(work),
1286 					     struct lpfc_hba,
1287 					     idle_stat_delay_work);
1288 	struct lpfc_queue *eq;
1289 	struct lpfc_sli4_hdw_queue *hdwq;
1290 	struct lpfc_idle_stat *idle_stat;
1291 	u32 i, idle_percent;
1292 	u64 wall, wall_idle, diff_wall, diff_idle, busy_time;
1293 
1294 	if (test_bit(FC_UNLOADING, &phba->pport->load_flag))
1295 		return;
1296 
1297 	if (phba->link_state == LPFC_HBA_ERROR ||
1298 	    test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag) ||
1299 	    phba->cmf_active_mode != LPFC_CFG_OFF)
1300 		goto requeue;
1301 
1302 	for_each_present_cpu(i) {
1303 		hdwq = &phba->sli4_hba.hdwq[phba->sli4_hba.cpu_map[i].hdwq];
1304 		eq = hdwq->hba_eq;
1305 
1306 		/* Skip if we've already handled this eq's primary CPU */
1307 		if (eq->chann != i)
1308 			continue;
1309 
1310 		idle_stat = &phba->sli4_hba.idle_stat[i];
1311 
1312 		/* get_cpu_idle_time returns values as running counters. Thus,
1313 		 * to know the amount for this period, the prior counter values
1314 		 * need to be subtracted from the current counter values.
1315 		 * From there, the idle time stat can be calculated as a
1316 		 * percentage of 100 - the sum of the other consumption times.
1317 		 */
1318 		wall_idle = get_cpu_idle_time(i, &wall, 1);
1319 		diff_idle = wall_idle - idle_stat->prev_idle;
1320 		diff_wall = wall - idle_stat->prev_wall;
1321 
1322 		if (diff_wall <= diff_idle)
1323 			busy_time = 0;
1324 		else
1325 			busy_time = diff_wall - diff_idle;
1326 
1327 		idle_percent = div64_u64(100 * busy_time, diff_wall);
1328 		idle_percent = 100 - idle_percent;
1329 
1330 		if (idle_percent < 15)
1331 			eq->poll_mode = LPFC_QUEUE_WORK;
1332 		else
1333 			eq->poll_mode = LPFC_THREADED_IRQ;
1334 
1335 		idle_stat->prev_idle = wall_idle;
1336 		idle_stat->prev_wall = wall;
1337 	}
1338 
1339 requeue:
1340 	schedule_delayed_work(&phba->idle_stat_delay_work,
1341 			      msecs_to_jiffies(LPFC_IDLE_STAT_DELAY));
1342 }
1343 
1344 static void
1345 lpfc_hb_eq_delay_work(struct work_struct *work)
1346 {
1347 	struct lpfc_hba *phba = container_of(to_delayed_work(work),
1348 					     struct lpfc_hba, eq_delay_work);
1349 	struct lpfc_eq_intr_info *eqi, *eqi_new;
1350 	struct lpfc_queue *eq, *eq_next;
1351 	unsigned char *ena_delay = NULL;
1352 	uint32_t usdelay;
1353 	int i;
1354 
1355 	if (!phba->cfg_auto_imax ||
1356 	    test_bit(FC_UNLOADING, &phba->pport->load_flag))
1357 		return;
1358 
1359 	if (phba->link_state == LPFC_HBA_ERROR ||
1360 	    test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag))
1361 		goto requeue;
1362 
1363 	ena_delay = kcalloc(phba->sli4_hba.num_possible_cpu, sizeof(*ena_delay),
1364 			    GFP_KERNEL);
1365 	if (!ena_delay)
1366 		goto requeue;
1367 
1368 	for (i = 0; i < phba->cfg_irq_chann; i++) {
1369 		/* Get the EQ corresponding to the IRQ vector */
1370 		eq = phba->sli4_hba.hba_eq_hdl[i].eq;
1371 		if (!eq)
1372 			continue;
1373 		if (eq->q_mode || eq->q_flag & HBA_EQ_DELAY_CHK) {
1374 			eq->q_flag &= ~HBA_EQ_DELAY_CHK;
1375 			ena_delay[eq->last_cpu] = 1;
1376 		}
1377 	}
1378 
1379 	for_each_present_cpu(i) {
1380 		eqi = per_cpu_ptr(phba->sli4_hba.eq_info, i);
1381 		if (ena_delay[i]) {
1382 			usdelay = (eqi->icnt >> 10) * LPFC_EQ_DELAY_STEP;
1383 			if (usdelay > LPFC_MAX_AUTO_EQ_DELAY)
1384 				usdelay = LPFC_MAX_AUTO_EQ_DELAY;
1385 		} else {
1386 			usdelay = 0;
1387 		}
1388 
1389 		eqi->icnt = 0;
1390 
1391 		list_for_each_entry_safe(eq, eq_next, &eqi->list, cpu_list) {
1392 			if (unlikely(eq->last_cpu != i)) {
1393 				eqi_new = per_cpu_ptr(phba->sli4_hba.eq_info,
1394 						      eq->last_cpu);
1395 				list_move_tail(&eq->cpu_list, &eqi_new->list);
1396 				continue;
1397 			}
1398 			if (usdelay != eq->q_mode)
1399 				lpfc_modify_hba_eq_delay(phba, eq->hdwq, 1,
1400 							 usdelay);
1401 		}
1402 	}
1403 
1404 	kfree(ena_delay);
1405 
1406 requeue:
1407 	queue_delayed_work(phba->wq, &phba->eq_delay_work,
1408 			   msecs_to_jiffies(LPFC_EQ_DELAY_MSECS));
1409 }
1410 
1411 /**
1412  * lpfc_hb_mxp_handler - Multi-XRI pools handler to adjust XRI distribution
1413  * @phba: pointer to lpfc hba data structure.
1414  *
1415  * For each heartbeat, this routine does some heuristic methods to adjust
1416  * XRI distribution. The goal is to fully utilize free XRIs.
1417  **/
1418 static void lpfc_hb_mxp_handler(struct lpfc_hba *phba)
1419 {
1420 	u32 i;
1421 	u32 hwq_count;
1422 
1423 	hwq_count = phba->cfg_hdw_queue;
1424 	for (i = 0; i < hwq_count; i++) {
1425 		/* Adjust XRIs in private pool */
1426 		lpfc_adjust_pvt_pool_count(phba, i);
1427 
1428 		/* Adjust high watermark */
1429 		lpfc_adjust_high_watermark(phba, i);
1430 
1431 #ifdef LPFC_MXP_STAT
1432 		/* Snapshot pbl, pvt and busy count */
1433 		lpfc_snapshot_mxp(phba, i);
1434 #endif
1435 	}
1436 }
1437 
1438 /**
1439  * lpfc_issue_hb_mbox - Issues heart-beat mailbox command
1440  * @phba: pointer to lpfc hba data structure.
1441  *
1442  * If a HB mbox is not already in progrees, this routine will allocate
1443  * a LPFC_MBOXQ_t, populate it with a MBX_HEARTBEAT (0x31) command,
1444  * and issue it. The HBA_HBEAT_INP flag means the command is in progress.
1445  **/
1446 int
1447 lpfc_issue_hb_mbox(struct lpfc_hba *phba)
1448 {
1449 	LPFC_MBOXQ_t *pmboxq;
1450 	int retval;
1451 
1452 	/* Is a Heartbeat mbox already in progress */
1453 	if (test_bit(HBA_HBEAT_INP, &phba->hba_flag))
1454 		return 0;
1455 
1456 	pmboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
1457 	if (!pmboxq)
1458 		return -ENOMEM;
1459 
1460 	lpfc_heart_beat(phba, pmboxq);
1461 	pmboxq->mbox_cmpl = lpfc_hb_mbox_cmpl;
1462 	pmboxq->vport = phba->pport;
1463 	retval = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
1464 
1465 	if (retval != MBX_BUSY && retval != MBX_SUCCESS) {
1466 		mempool_free(pmboxq, phba->mbox_mem_pool);
1467 		return -ENXIO;
1468 	}
1469 	set_bit(HBA_HBEAT_INP, &phba->hba_flag);
1470 
1471 	return 0;
1472 }
1473 
1474 /**
1475  * lpfc_issue_hb_tmo - Signals heartbeat timer to issue mbox command
1476  * @phba: pointer to lpfc hba data structure.
1477  *
1478  * The heartbeat timer (every 5 sec) will fire. If the HBA_HBEAT_TMO
1479  * flag is set, it will force a MBX_HEARTBEAT mbox command, regardless
1480  * of the value of lpfc_enable_hba_heartbeat.
1481  * If lpfc_enable_hba_heartbeat is set, the timeout routine will always
1482  * try to issue a MBX_HEARTBEAT mbox command.
1483  **/
1484 void
1485 lpfc_issue_hb_tmo(struct lpfc_hba *phba)
1486 {
1487 	if (phba->cfg_enable_hba_heartbeat)
1488 		return;
1489 	set_bit(HBA_HBEAT_TMO, &phba->hba_flag);
1490 }
1491 
1492 /**
1493  * lpfc_hb_timeout_handler - The HBA-timer timeout handler
1494  * @phba: pointer to lpfc hba data structure.
1495  *
1496  * This is the actual HBA-timer timeout handler to be invoked by the worker
1497  * thread whenever the HBA timer fired and HBA-timeout event posted. This
1498  * handler performs any periodic operations needed for the device. If such
1499  * periodic event has already been attended to either in the interrupt handler
1500  * or by processing slow-ring or fast-ring events within the HBA-timer
1501  * timeout window (LPFC_HB_MBOX_INTERVAL), this handler just simply resets
1502  * the timer for the next timeout period. If lpfc heart-beat mailbox command
1503  * is configured and there is no heart-beat mailbox command outstanding, a
1504  * heart-beat mailbox is issued and timer set properly. Otherwise, if there
1505  * has been a heart-beat mailbox command outstanding, the HBA shall be put
1506  * to offline.
1507  **/
1508 void
1509 lpfc_hb_timeout_handler(struct lpfc_hba *phba)
1510 {
1511 	struct lpfc_vport **vports;
1512 	struct lpfc_dmabuf *buf_ptr;
1513 	int retval = 0;
1514 	int i, tmo;
1515 	struct lpfc_sli *psli = &phba->sli;
1516 	LIST_HEAD(completions);
1517 
1518 	if (phba->cfg_xri_rebalancing) {
1519 		/* Multi-XRI pools handler */
1520 		lpfc_hb_mxp_handler(phba);
1521 	}
1522 
1523 	vports = lpfc_create_vport_work_array(phba);
1524 	if (vports != NULL)
1525 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
1526 			lpfc_rcv_seq_check_edtov(vports[i]);
1527 			lpfc_fdmi_change_check(vports[i]);
1528 		}
1529 	lpfc_destroy_vport_work_array(phba, vports);
1530 
1531 	if (phba->link_state == LPFC_HBA_ERROR ||
1532 	    test_bit(FC_UNLOADING, &phba->pport->load_flag) ||
1533 	    test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag))
1534 		return;
1535 
1536 	if (phba->elsbuf_cnt &&
1537 		(phba->elsbuf_cnt == phba->elsbuf_prev_cnt)) {
1538 		spin_lock_irq(&phba->hbalock);
1539 		list_splice_init(&phba->elsbuf, &completions);
1540 		phba->elsbuf_cnt = 0;
1541 		phba->elsbuf_prev_cnt = 0;
1542 		spin_unlock_irq(&phba->hbalock);
1543 
1544 		while (!list_empty(&completions)) {
1545 			list_remove_head(&completions, buf_ptr,
1546 				struct lpfc_dmabuf, list);
1547 			lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
1548 			kfree(buf_ptr);
1549 		}
1550 	}
1551 	phba->elsbuf_prev_cnt = phba->elsbuf_cnt;
1552 
1553 	/* If there is no heart beat outstanding, issue a heartbeat command */
1554 	if (phba->cfg_enable_hba_heartbeat) {
1555 		/* If IOs are completing, no need to issue a MBX_HEARTBEAT */
1556 		spin_lock_irq(&phba->pport->work_port_lock);
1557 		if (time_after(phba->last_completion_time +
1558 				msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL),
1559 				jiffies)) {
1560 			spin_unlock_irq(&phba->pport->work_port_lock);
1561 			if (test_bit(HBA_HBEAT_INP, &phba->hba_flag))
1562 				tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1563 			else
1564 				tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1565 			goto out;
1566 		}
1567 		spin_unlock_irq(&phba->pport->work_port_lock);
1568 
1569 		/* Check if a MBX_HEARTBEAT is already in progress */
1570 		if (test_bit(HBA_HBEAT_INP, &phba->hba_flag)) {
1571 			/*
1572 			 * If heart beat timeout called with HBA_HBEAT_INP set
1573 			 * we need to give the hb mailbox cmd a chance to
1574 			 * complete or TMO.
1575 			 */
1576 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
1577 				"0459 Adapter heartbeat still outstanding: "
1578 				"last compl time was %d ms.\n",
1579 				jiffies_to_msecs(jiffies
1580 					 - phba->last_completion_time));
1581 			tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1582 		} else {
1583 			if ((!(psli->sli_flag & LPFC_SLI_MBOX_ACTIVE)) &&
1584 				(list_empty(&psli->mboxq))) {
1585 
1586 				retval = lpfc_issue_hb_mbox(phba);
1587 				if (retval) {
1588 					tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1589 					goto out;
1590 				}
1591 				phba->skipped_hb = 0;
1592 			} else if (time_before_eq(phba->last_completion_time,
1593 					phba->skipped_hb)) {
1594 				lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
1595 					"2857 Last completion time not "
1596 					" updated in %d ms\n",
1597 					jiffies_to_msecs(jiffies
1598 						 - phba->last_completion_time));
1599 			} else
1600 				phba->skipped_hb = jiffies;
1601 
1602 			tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1603 			goto out;
1604 		}
1605 	} else {
1606 		/* Check to see if we want to force a MBX_HEARTBEAT */
1607 		if (test_bit(HBA_HBEAT_TMO, &phba->hba_flag)) {
1608 			retval = lpfc_issue_hb_mbox(phba);
1609 			if (retval)
1610 				tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1611 			else
1612 				tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1613 			goto out;
1614 		}
1615 		tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1616 	}
1617 out:
1618 	mod_timer(&phba->hb_tmofunc, jiffies + msecs_to_jiffies(tmo));
1619 }
1620 
1621 /**
1622  * lpfc_offline_eratt - Bring lpfc offline on hardware error attention
1623  * @phba: pointer to lpfc hba data structure.
1624  *
1625  * This routine is called to bring the HBA offline when HBA hardware error
1626  * other than Port Error 6 has been detected.
1627  **/
1628 static void
1629 lpfc_offline_eratt(struct lpfc_hba *phba)
1630 {
1631 	struct lpfc_sli   *psli = &phba->sli;
1632 
1633 	spin_lock_irq(&phba->hbalock);
1634 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1635 	spin_unlock_irq(&phba->hbalock);
1636 	lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
1637 
1638 	lpfc_offline(phba);
1639 	lpfc_reset_barrier(phba);
1640 	spin_lock_irq(&phba->hbalock);
1641 	lpfc_sli_brdreset(phba);
1642 	spin_unlock_irq(&phba->hbalock);
1643 	lpfc_hba_down_post(phba);
1644 	lpfc_sli_brdready(phba, HS_MBRDY);
1645 	lpfc_unblock_mgmt_io(phba);
1646 	phba->link_state = LPFC_HBA_ERROR;
1647 	return;
1648 }
1649 
1650 /**
1651  * lpfc_sli4_offline_eratt - Bring lpfc offline on SLI4 hardware error attention
1652  * @phba: pointer to lpfc hba data structure.
1653  *
1654  * This routine is called to bring a SLI4 HBA offline when HBA hardware error
1655  * other than Port Error 6 has been detected.
1656  **/
1657 void
1658 lpfc_sli4_offline_eratt(struct lpfc_hba *phba)
1659 {
1660 	spin_lock_irq(&phba->hbalock);
1661 	if (phba->link_state == LPFC_HBA_ERROR &&
1662 		test_bit(HBA_PCI_ERR, &phba->bit_flags)) {
1663 		spin_unlock_irq(&phba->hbalock);
1664 		return;
1665 	}
1666 	phba->link_state = LPFC_HBA_ERROR;
1667 	spin_unlock_irq(&phba->hbalock);
1668 
1669 	lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
1670 	lpfc_sli_flush_io_rings(phba);
1671 	lpfc_offline(phba);
1672 	lpfc_hba_down_post(phba);
1673 	lpfc_unblock_mgmt_io(phba);
1674 }
1675 
1676 /**
1677  * lpfc_handle_deferred_eratt - The HBA hardware deferred error handler
1678  * @phba: pointer to lpfc hba data structure.
1679  *
1680  * This routine is invoked to handle the deferred HBA hardware error
1681  * conditions. This type of error is indicated by HBA by setting ER1
1682  * and another ER bit in the host status register. The driver will
1683  * wait until the ER1 bit clears before handling the error condition.
1684  **/
1685 static void
1686 lpfc_handle_deferred_eratt(struct lpfc_hba *phba)
1687 {
1688 	uint32_t old_host_status = phba->work_hs;
1689 	struct lpfc_sli *psli = &phba->sli;
1690 
1691 	/* If the pci channel is offline, ignore possible errors,
1692 	 * since we cannot communicate with the pci card anyway.
1693 	 */
1694 	if (pci_channel_offline(phba->pcidev)) {
1695 		clear_bit(DEFER_ERATT, &phba->hba_flag);
1696 		return;
1697 	}
1698 
1699 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1700 			"0479 Deferred Adapter Hardware Error "
1701 			"Data: x%x x%x x%x\n",
1702 			phba->work_hs, phba->work_status[0],
1703 			phba->work_status[1]);
1704 
1705 	spin_lock_irq(&phba->hbalock);
1706 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1707 	spin_unlock_irq(&phba->hbalock);
1708 
1709 
1710 	/*
1711 	 * Firmware stops when it triggred erratt. That could cause the I/Os
1712 	 * dropped by the firmware. Error iocb (I/O) on txcmplq and let the
1713 	 * SCSI layer retry it after re-establishing link.
1714 	 */
1715 	lpfc_sli_abort_fcp_rings(phba);
1716 
1717 	/*
1718 	 * There was a firmware error. Take the hba offline and then
1719 	 * attempt to restart it.
1720 	 */
1721 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
1722 	lpfc_offline(phba);
1723 
1724 	/* Wait for the ER1 bit to clear.*/
1725 	while (phba->work_hs & HS_FFER1) {
1726 		msleep(100);
1727 		if (lpfc_readl(phba->HSregaddr, &phba->work_hs)) {
1728 			phba->work_hs = UNPLUG_ERR ;
1729 			break;
1730 		}
1731 		/* If driver is unloading let the worker thread continue */
1732 		if (test_bit(FC_UNLOADING, &phba->pport->load_flag)) {
1733 			phba->work_hs = 0;
1734 			break;
1735 		}
1736 	}
1737 
1738 	/*
1739 	 * This is to ptrotect against a race condition in which
1740 	 * first write to the host attention register clear the
1741 	 * host status register.
1742 	 */
1743 	if (!phba->work_hs && !test_bit(FC_UNLOADING, &phba->pport->load_flag))
1744 		phba->work_hs = old_host_status & ~HS_FFER1;
1745 
1746 	clear_bit(DEFER_ERATT, &phba->hba_flag);
1747 	phba->work_status[0] = readl(phba->MBslimaddr + 0xa8);
1748 	phba->work_status[1] = readl(phba->MBslimaddr + 0xac);
1749 }
1750 
1751 static void
1752 lpfc_board_errevt_to_mgmt(struct lpfc_hba *phba)
1753 {
1754 	struct lpfc_board_event_header board_event;
1755 	struct Scsi_Host *shost;
1756 
1757 	board_event.event_type = FC_REG_BOARD_EVENT;
1758 	board_event.subcategory = LPFC_EVENT_PORTINTERR;
1759 	shost = lpfc_shost_from_vport(phba->pport);
1760 	fc_host_post_vendor_event(shost, fc_get_event_number(),
1761 				  sizeof(board_event),
1762 				  (char *) &board_event,
1763 				  LPFC_NL_VENDOR_ID);
1764 }
1765 
1766 /**
1767  * lpfc_handle_eratt_s3 - The SLI3 HBA hardware error handler
1768  * @phba: pointer to lpfc hba data structure.
1769  *
1770  * This routine is invoked to handle the following HBA hardware error
1771  * conditions:
1772  * 1 - HBA error attention interrupt
1773  * 2 - DMA ring index out of range
1774  * 3 - Mailbox command came back as unknown
1775  **/
1776 static void
1777 lpfc_handle_eratt_s3(struct lpfc_hba *phba)
1778 {
1779 	struct lpfc_vport *vport = phba->pport;
1780 	struct lpfc_sli   *psli = &phba->sli;
1781 	uint32_t event_data;
1782 	unsigned long temperature;
1783 	struct temp_event temp_event_data;
1784 	struct Scsi_Host  *shost;
1785 
1786 	/* If the pci channel is offline, ignore possible errors,
1787 	 * since we cannot communicate with the pci card anyway.
1788 	 */
1789 	if (pci_channel_offline(phba->pcidev)) {
1790 		clear_bit(DEFER_ERATT, &phba->hba_flag);
1791 		return;
1792 	}
1793 
1794 	/* If resets are disabled then leave the HBA alone and return */
1795 	if (!phba->cfg_enable_hba_reset)
1796 		return;
1797 
1798 	/* Send an internal error event to mgmt application */
1799 	lpfc_board_errevt_to_mgmt(phba);
1800 
1801 	if (test_bit(DEFER_ERATT, &phba->hba_flag))
1802 		lpfc_handle_deferred_eratt(phba);
1803 
1804 	if ((phba->work_hs & HS_FFER6) || (phba->work_hs & HS_FFER8)) {
1805 		if (phba->work_hs & HS_FFER6)
1806 			/* Re-establishing Link */
1807 			lpfc_printf_log(phba, KERN_INFO, LOG_LINK_EVENT,
1808 					"1301 Re-establishing Link "
1809 					"Data: x%x x%x x%x\n",
1810 					phba->work_hs, phba->work_status[0],
1811 					phba->work_status[1]);
1812 		if (phba->work_hs & HS_FFER8)
1813 			/* Device Zeroization */
1814 			lpfc_printf_log(phba, KERN_INFO, LOG_LINK_EVENT,
1815 					"2861 Host Authentication device "
1816 					"zeroization Data:x%x x%x x%x\n",
1817 					phba->work_hs, phba->work_status[0],
1818 					phba->work_status[1]);
1819 
1820 		spin_lock_irq(&phba->hbalock);
1821 		psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1822 		spin_unlock_irq(&phba->hbalock);
1823 
1824 		/*
1825 		* Firmware stops when it triggled erratt with HS_FFER6.
1826 		* That could cause the I/Os dropped by the firmware.
1827 		* Error iocb (I/O) on txcmplq and let the SCSI layer
1828 		* retry it after re-establishing link.
1829 		*/
1830 		lpfc_sli_abort_fcp_rings(phba);
1831 
1832 		/*
1833 		 * There was a firmware error.  Take the hba offline and then
1834 		 * attempt to restart it.
1835 		 */
1836 		lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
1837 		lpfc_offline(phba);
1838 		lpfc_sli_brdrestart(phba);
1839 		if (lpfc_online(phba) == 0) {	/* Initialize the HBA */
1840 			lpfc_unblock_mgmt_io(phba);
1841 			return;
1842 		}
1843 		lpfc_unblock_mgmt_io(phba);
1844 	} else if (phba->work_hs & HS_CRIT_TEMP) {
1845 		temperature = readl(phba->MBslimaddr + TEMPERATURE_OFFSET);
1846 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
1847 		temp_event_data.event_code = LPFC_CRIT_TEMP;
1848 		temp_event_data.data = (uint32_t)temperature;
1849 
1850 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1851 				"0406 Adapter maximum temperature exceeded "
1852 				"(%ld), taking this port offline "
1853 				"Data: x%x x%x x%x\n",
1854 				temperature, phba->work_hs,
1855 				phba->work_status[0], phba->work_status[1]);
1856 
1857 		shost = lpfc_shost_from_vport(phba->pport);
1858 		fc_host_post_vendor_event(shost, fc_get_event_number(),
1859 					  sizeof(temp_event_data),
1860 					  (char *) &temp_event_data,
1861 					  SCSI_NL_VID_TYPE_PCI
1862 					  | PCI_VENDOR_ID_EMULEX);
1863 
1864 		spin_lock_irq(&phba->hbalock);
1865 		phba->over_temp_state = HBA_OVER_TEMP;
1866 		spin_unlock_irq(&phba->hbalock);
1867 		lpfc_offline_eratt(phba);
1868 
1869 	} else {
1870 		/* The if clause above forces this code path when the status
1871 		 * failure is a value other than FFER6. Do not call the offline
1872 		 * twice. This is the adapter hardware error path.
1873 		 */
1874 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1875 				"0457 Adapter Hardware Error "
1876 				"Data: x%x x%x x%x\n",
1877 				phba->work_hs,
1878 				phba->work_status[0], phba->work_status[1]);
1879 
1880 		event_data = FC_REG_DUMP_EVENT;
1881 		shost = lpfc_shost_from_vport(vport);
1882 		fc_host_post_vendor_event(shost, fc_get_event_number(),
1883 				sizeof(event_data), (char *) &event_data,
1884 				SCSI_NL_VID_TYPE_PCI | PCI_VENDOR_ID_EMULEX);
1885 
1886 		lpfc_offline_eratt(phba);
1887 	}
1888 	return;
1889 }
1890 
1891 /**
1892  * lpfc_sli4_port_sta_fn_reset - The SLI4 function reset due to port status reg
1893  * @phba: pointer to lpfc hba data structure.
1894  * @mbx_action: flag for mailbox shutdown action.
1895  * @en_rn_msg: send reset/port recovery message.
1896  * This routine is invoked to perform an SLI4 port PCI function reset in
1897  * response to port status register polling attention. It waits for port
1898  * status register (ERR, RDY, RN) bits before proceeding with function reset.
1899  * During this process, interrupt vectors are freed and later requested
1900  * for handling possible port resource change.
1901  **/
1902 static int
1903 lpfc_sli4_port_sta_fn_reset(struct lpfc_hba *phba, int mbx_action,
1904 			    bool en_rn_msg)
1905 {
1906 	int rc;
1907 	uint32_t intr_mode;
1908 	LPFC_MBOXQ_t *mboxq;
1909 
1910 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) >=
1911 	    LPFC_SLI_INTF_IF_TYPE_2) {
1912 		/*
1913 		 * On error status condition, driver need to wait for port
1914 		 * ready before performing reset.
1915 		 */
1916 		rc = lpfc_sli4_pdev_status_reg_wait(phba);
1917 		if (rc)
1918 			return rc;
1919 	}
1920 
1921 	/* need reset: attempt for port recovery */
1922 	if (en_rn_msg)
1923 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
1924 				"2887 Reset Needed: Attempting Port "
1925 				"Recovery...\n");
1926 
1927 	/* If we are no wait, the HBA has been reset and is not
1928 	 * functional, thus we should clear
1929 	 * (LPFC_SLI_ACTIVE | LPFC_SLI_MBOX_ACTIVE) flags.
1930 	 */
1931 	if (mbx_action == LPFC_MBX_NO_WAIT) {
1932 		spin_lock_irq(&phba->hbalock);
1933 		phba->sli.sli_flag &= ~LPFC_SLI_ACTIVE;
1934 		if (phba->sli.mbox_active) {
1935 			mboxq = phba->sli.mbox_active;
1936 			mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
1937 			__lpfc_mbox_cmpl_put(phba, mboxq);
1938 			phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
1939 			phba->sli.mbox_active = NULL;
1940 		}
1941 		spin_unlock_irq(&phba->hbalock);
1942 	}
1943 
1944 	lpfc_offline_prep(phba, mbx_action);
1945 	lpfc_sli_flush_io_rings(phba);
1946 	lpfc_nvmels_flush_cmd(phba);
1947 	lpfc_offline(phba);
1948 	/* release interrupt for possible resource change */
1949 	lpfc_sli4_disable_intr(phba);
1950 	rc = lpfc_sli_brdrestart(phba);
1951 	if (rc) {
1952 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1953 				"6309 Failed to restart board\n");
1954 		return rc;
1955 	}
1956 	/* request and enable interrupt */
1957 	intr_mode = lpfc_sli4_enable_intr(phba, phba->intr_mode);
1958 	if (intr_mode == LPFC_INTR_ERROR) {
1959 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1960 				"3175 Failed to enable interrupt\n");
1961 		return -EIO;
1962 	}
1963 	phba->intr_mode = intr_mode;
1964 	rc = lpfc_online(phba);
1965 	if (rc == 0)
1966 		lpfc_unblock_mgmt_io(phba);
1967 
1968 	return rc;
1969 }
1970 
1971 /**
1972  * lpfc_handle_eratt_s4 - The SLI4 HBA hardware error handler
1973  * @phba: pointer to lpfc hba data structure.
1974  *
1975  * This routine is invoked to handle the SLI4 HBA hardware error attention
1976  * conditions.
1977  **/
1978 static void
1979 lpfc_handle_eratt_s4(struct lpfc_hba *phba)
1980 {
1981 	struct lpfc_vport *vport = phba->pport;
1982 	uint32_t event_data;
1983 	struct Scsi_Host *shost;
1984 	uint32_t if_type;
1985 	struct lpfc_register portstat_reg = {0};
1986 	uint32_t reg_err1, reg_err2;
1987 	uint32_t uerrlo_reg, uemasklo_reg;
1988 	uint32_t smphr_port_status = 0, pci_rd_rc1, pci_rd_rc2;
1989 	bool en_rn_msg = true;
1990 	struct temp_event temp_event_data;
1991 	struct lpfc_register portsmphr_reg;
1992 	int rc, i;
1993 
1994 	/* If the pci channel is offline, ignore possible errors, since
1995 	 * we cannot communicate with the pci card anyway.
1996 	 */
1997 	if (pci_channel_offline(phba->pcidev)) {
1998 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1999 				"3166 pci channel is offline\n");
2000 		lpfc_sli_flush_io_rings(phba);
2001 		return;
2002 	}
2003 
2004 	memset(&portsmphr_reg, 0, sizeof(portsmphr_reg));
2005 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
2006 	switch (if_type) {
2007 	case LPFC_SLI_INTF_IF_TYPE_0:
2008 		pci_rd_rc1 = lpfc_readl(
2009 				phba->sli4_hba.u.if_type0.UERRLOregaddr,
2010 				&uerrlo_reg);
2011 		pci_rd_rc2 = lpfc_readl(
2012 				phba->sli4_hba.u.if_type0.UEMASKLOregaddr,
2013 				&uemasklo_reg);
2014 		/* consider PCI bus read error as pci_channel_offline */
2015 		if (pci_rd_rc1 == -EIO && pci_rd_rc2 == -EIO)
2016 			return;
2017 		if (!test_bit(HBA_RECOVERABLE_UE, &phba->hba_flag)) {
2018 			lpfc_sli4_offline_eratt(phba);
2019 			return;
2020 		}
2021 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2022 				"7623 Checking UE recoverable");
2023 
2024 		for (i = 0; i < phba->sli4_hba.ue_to_sr / 1000; i++) {
2025 			if (lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
2026 				       &portsmphr_reg.word0))
2027 				continue;
2028 
2029 			smphr_port_status = bf_get(lpfc_port_smphr_port_status,
2030 						   &portsmphr_reg);
2031 			if ((smphr_port_status & LPFC_PORT_SEM_MASK) ==
2032 			    LPFC_PORT_SEM_UE_RECOVERABLE)
2033 				break;
2034 			/*Sleep for 1Sec, before checking SEMAPHORE */
2035 			msleep(1000);
2036 		}
2037 
2038 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2039 				"4827 smphr_port_status x%x : Waited %dSec",
2040 				smphr_port_status, i);
2041 
2042 		/* Recoverable UE, reset the HBA device */
2043 		if ((smphr_port_status & LPFC_PORT_SEM_MASK) ==
2044 		    LPFC_PORT_SEM_UE_RECOVERABLE) {
2045 			for (i = 0; i < 20; i++) {
2046 				msleep(1000);
2047 				if (!lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
2048 				    &portsmphr_reg.word0) &&
2049 				    (LPFC_POST_STAGE_PORT_READY ==
2050 				     bf_get(lpfc_port_smphr_port_status,
2051 				     &portsmphr_reg))) {
2052 					rc = lpfc_sli4_port_sta_fn_reset(phba,
2053 						LPFC_MBX_NO_WAIT, en_rn_msg);
2054 					if (rc == 0)
2055 						return;
2056 					lpfc_printf_log(phba, KERN_ERR,
2057 						LOG_TRACE_EVENT,
2058 						"4215 Failed to recover UE");
2059 					break;
2060 				}
2061 			}
2062 		}
2063 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2064 				"7624 Firmware not ready: Failing UE recovery,"
2065 				" waited %dSec", i);
2066 		phba->link_state = LPFC_HBA_ERROR;
2067 		break;
2068 
2069 	case LPFC_SLI_INTF_IF_TYPE_2:
2070 	case LPFC_SLI_INTF_IF_TYPE_6:
2071 		pci_rd_rc1 = lpfc_readl(
2072 				phba->sli4_hba.u.if_type2.STATUSregaddr,
2073 				&portstat_reg.word0);
2074 		/* consider PCI bus read error as pci_channel_offline */
2075 		if (pci_rd_rc1 == -EIO) {
2076 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2077 				"3151 PCI bus read access failure: x%x\n",
2078 				readl(phba->sli4_hba.u.if_type2.STATUSregaddr));
2079 			lpfc_sli4_offline_eratt(phba);
2080 			return;
2081 		}
2082 		reg_err1 = readl(phba->sli4_hba.u.if_type2.ERR1regaddr);
2083 		reg_err2 = readl(phba->sli4_hba.u.if_type2.ERR2regaddr);
2084 		if (bf_get(lpfc_sliport_status_oti, &portstat_reg)) {
2085 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2086 					"2889 Port Overtemperature event, "
2087 					"taking port offline Data: x%x x%x\n",
2088 					reg_err1, reg_err2);
2089 
2090 			phba->sfp_alarm |= LPFC_TRANSGRESSION_HIGH_TEMPERATURE;
2091 			temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
2092 			temp_event_data.event_code = LPFC_CRIT_TEMP;
2093 			temp_event_data.data = 0xFFFFFFFF;
2094 
2095 			shost = lpfc_shost_from_vport(phba->pport);
2096 			fc_host_post_vendor_event(shost, fc_get_event_number(),
2097 						  sizeof(temp_event_data),
2098 						  (char *)&temp_event_data,
2099 						  SCSI_NL_VID_TYPE_PCI
2100 						  | PCI_VENDOR_ID_EMULEX);
2101 
2102 			spin_lock_irq(&phba->hbalock);
2103 			phba->over_temp_state = HBA_OVER_TEMP;
2104 			spin_unlock_irq(&phba->hbalock);
2105 			lpfc_sli4_offline_eratt(phba);
2106 			return;
2107 		}
2108 		if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2109 		    reg_err2 == SLIPORT_ERR2_REG_FW_RESTART) {
2110 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2111 					"3143 Port Down: Firmware Update "
2112 					"Detected\n");
2113 			en_rn_msg = false;
2114 		} else if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2115 			 reg_err2 == SLIPORT_ERR2_REG_FORCED_DUMP)
2116 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2117 					"3144 Port Down: Debug Dump\n");
2118 		else if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2119 			 reg_err2 == SLIPORT_ERR2_REG_FUNC_PROVISON)
2120 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2121 					"3145 Port Down: Provisioning\n");
2122 
2123 		/* If resets are disabled then leave the HBA alone and return */
2124 		if (!phba->cfg_enable_hba_reset)
2125 			return;
2126 
2127 		/* Check port status register for function reset */
2128 		rc = lpfc_sli4_port_sta_fn_reset(phba, LPFC_MBX_NO_WAIT,
2129 				en_rn_msg);
2130 		if (rc == 0) {
2131 			/* don't report event on forced debug dump */
2132 			if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2133 			    reg_err2 == SLIPORT_ERR2_REG_FORCED_DUMP)
2134 				return;
2135 			else
2136 				break;
2137 		}
2138 		/* fall through for not able to recover */
2139 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2140 				"3152 Unrecoverable error\n");
2141 		lpfc_sli4_offline_eratt(phba);
2142 		break;
2143 	case LPFC_SLI_INTF_IF_TYPE_1:
2144 	default:
2145 		break;
2146 	}
2147 	lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
2148 			"3123 Report dump event to upper layer\n");
2149 	/* Send an internal error event to mgmt application */
2150 	lpfc_board_errevt_to_mgmt(phba);
2151 
2152 	event_data = FC_REG_DUMP_EVENT;
2153 	shost = lpfc_shost_from_vport(vport);
2154 	fc_host_post_vendor_event(shost, fc_get_event_number(),
2155 				  sizeof(event_data), (char *) &event_data,
2156 				  SCSI_NL_VID_TYPE_PCI | PCI_VENDOR_ID_EMULEX);
2157 }
2158 
2159 /**
2160  * lpfc_handle_eratt - Wrapper func for handling hba error attention
2161  * @phba: pointer to lpfc HBA data structure.
2162  *
2163  * This routine wraps the actual SLI3 or SLI4 hba error attention handling
2164  * routine from the API jump table function pointer from the lpfc_hba struct.
2165  *
2166  * Return codes
2167  *   0 - success.
2168  *   Any other value - error.
2169  **/
2170 void
2171 lpfc_handle_eratt(struct lpfc_hba *phba)
2172 {
2173 	(*phba->lpfc_handle_eratt)(phba);
2174 }
2175 
2176 /**
2177  * lpfc_handle_latt - The HBA link event handler
2178  * @phba: pointer to lpfc hba data structure.
2179  *
2180  * This routine is invoked from the worker thread to handle a HBA host
2181  * attention link event. SLI3 only.
2182  **/
2183 void
2184 lpfc_handle_latt(struct lpfc_hba *phba)
2185 {
2186 	struct lpfc_vport *vport = phba->pport;
2187 	struct lpfc_sli   *psli = &phba->sli;
2188 	LPFC_MBOXQ_t *pmb;
2189 	volatile uint32_t control;
2190 	int rc = 0;
2191 
2192 	pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
2193 	if (!pmb) {
2194 		rc = 1;
2195 		goto lpfc_handle_latt_err_exit;
2196 	}
2197 
2198 	rc = lpfc_mbox_rsrc_prep(phba, pmb);
2199 	if (rc) {
2200 		rc = 2;
2201 		mempool_free(pmb, phba->mbox_mem_pool);
2202 		goto lpfc_handle_latt_err_exit;
2203 	}
2204 
2205 	/* Cleanup any outstanding ELS commands */
2206 	lpfc_els_flush_all_cmd(phba);
2207 	psli->slistat.link_event++;
2208 	lpfc_read_topology(phba, pmb, pmb->ctx_buf);
2209 	pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
2210 	pmb->vport = vport;
2211 	/* Block ELS IOCBs until we have processed this mbox command */
2212 	phba->sli.sli3_ring[LPFC_ELS_RING].flag |= LPFC_STOP_IOCB_EVENT;
2213 	rc = lpfc_sli_issue_mbox (phba, pmb, MBX_NOWAIT);
2214 	if (rc == MBX_NOT_FINISHED) {
2215 		rc = 4;
2216 		goto lpfc_handle_latt_free_mbuf;
2217 	}
2218 
2219 	/* Clear Link Attention in HA REG */
2220 	spin_lock_irq(&phba->hbalock);
2221 	writel(HA_LATT, phba->HAregaddr);
2222 	readl(phba->HAregaddr); /* flush */
2223 	spin_unlock_irq(&phba->hbalock);
2224 
2225 	return;
2226 
2227 lpfc_handle_latt_free_mbuf:
2228 	phba->sli.sli3_ring[LPFC_ELS_RING].flag &= ~LPFC_STOP_IOCB_EVENT;
2229 	lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
2230 lpfc_handle_latt_err_exit:
2231 	/* Enable Link attention interrupts */
2232 	spin_lock_irq(&phba->hbalock);
2233 	psli->sli_flag |= LPFC_PROCESS_LA;
2234 	control = readl(phba->HCregaddr);
2235 	control |= HC_LAINT_ENA;
2236 	writel(control, phba->HCregaddr);
2237 	readl(phba->HCregaddr); /* flush */
2238 
2239 	/* Clear Link Attention in HA REG */
2240 	writel(HA_LATT, phba->HAregaddr);
2241 	readl(phba->HAregaddr); /* flush */
2242 	spin_unlock_irq(&phba->hbalock);
2243 	lpfc_linkdown(phba);
2244 	phba->link_state = LPFC_HBA_ERROR;
2245 
2246 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2247 			"0300 LATT: Cannot issue READ_LA: Data:%d\n", rc);
2248 
2249 	return;
2250 }
2251 
2252 static void
2253 lpfc_fill_vpd(struct lpfc_hba *phba, uint8_t *vpd, int length, int *pindex)
2254 {
2255 	int i, j;
2256 
2257 	while (length > 0) {
2258 		/* Look for Serial Number */
2259 		if ((vpd[*pindex] == 'S') && (vpd[*pindex + 1] == 'N')) {
2260 			*pindex += 2;
2261 			i = vpd[*pindex];
2262 			*pindex += 1;
2263 			j = 0;
2264 			length -= (3+i);
2265 			while (i--) {
2266 				phba->SerialNumber[j++] = vpd[(*pindex)++];
2267 				if (j == 31)
2268 					break;
2269 			}
2270 			phba->SerialNumber[j] = 0;
2271 			continue;
2272 		} else if ((vpd[*pindex] == 'V') && (vpd[*pindex + 1] == '1')) {
2273 			phba->vpd_flag |= VPD_MODEL_DESC;
2274 			*pindex += 2;
2275 			i = vpd[*pindex];
2276 			*pindex += 1;
2277 			j = 0;
2278 			length -= (3+i);
2279 			while (i--) {
2280 				phba->ModelDesc[j++] = vpd[(*pindex)++];
2281 				if (j == 255)
2282 					break;
2283 			}
2284 			phba->ModelDesc[j] = 0;
2285 			continue;
2286 		} else if ((vpd[*pindex] == 'V') && (vpd[*pindex + 1] == '2')) {
2287 			phba->vpd_flag |= VPD_MODEL_NAME;
2288 			*pindex += 2;
2289 			i = vpd[*pindex];
2290 			*pindex += 1;
2291 			j = 0;
2292 			length -= (3+i);
2293 			while (i--) {
2294 				phba->ModelName[j++] = vpd[(*pindex)++];
2295 				if (j == 79)
2296 					break;
2297 			}
2298 			phba->ModelName[j] = 0;
2299 			continue;
2300 		} else if ((vpd[*pindex] == 'V') && (vpd[*pindex + 1] == '3')) {
2301 			phba->vpd_flag |= VPD_PROGRAM_TYPE;
2302 			*pindex += 2;
2303 			i = vpd[*pindex];
2304 			*pindex += 1;
2305 			j = 0;
2306 			length -= (3+i);
2307 			while (i--) {
2308 				phba->ProgramType[j++] = vpd[(*pindex)++];
2309 				if (j == 255)
2310 					break;
2311 			}
2312 			phba->ProgramType[j] = 0;
2313 			continue;
2314 		} else if ((vpd[*pindex] == 'V') && (vpd[*pindex + 1] == '4')) {
2315 			phba->vpd_flag |= VPD_PORT;
2316 			*pindex += 2;
2317 			i = vpd[*pindex];
2318 			*pindex += 1;
2319 			j = 0;
2320 			length -= (3 + i);
2321 			while (i--) {
2322 				if ((phba->sli_rev == LPFC_SLI_REV4) &&
2323 				    (phba->sli4_hba.pport_name_sta ==
2324 				     LPFC_SLI4_PPNAME_GET)) {
2325 					j++;
2326 					(*pindex)++;
2327 				} else
2328 					phba->Port[j++] = vpd[(*pindex)++];
2329 				if (j == 19)
2330 					break;
2331 			}
2332 			if ((phba->sli_rev != LPFC_SLI_REV4) ||
2333 			    (phba->sli4_hba.pport_name_sta ==
2334 			     LPFC_SLI4_PPNAME_NON))
2335 				phba->Port[j] = 0;
2336 			continue;
2337 		} else {
2338 			*pindex += 2;
2339 			i = vpd[*pindex];
2340 			*pindex += 1;
2341 			*pindex += i;
2342 			length -= (3 + i);
2343 		}
2344 	}
2345 }
2346 
2347 /**
2348  * lpfc_parse_vpd - Parse VPD (Vital Product Data)
2349  * @phba: pointer to lpfc hba data structure.
2350  * @vpd: pointer to the vital product data.
2351  * @len: length of the vital product data in bytes.
2352  *
2353  * This routine parses the Vital Product Data (VPD). The VPD is treated as
2354  * an array of characters. In this routine, the ModelName, ProgramType, and
2355  * ModelDesc, etc. fields of the phba data structure will be populated.
2356  *
2357  * Return codes
2358  *   0 - pointer to the VPD passed in is NULL
2359  *   1 - success
2360  **/
2361 int
2362 lpfc_parse_vpd(struct lpfc_hba *phba, uint8_t *vpd, int len)
2363 {
2364 	uint8_t lenlo, lenhi;
2365 	int Length;
2366 	int i;
2367 	int finished = 0;
2368 	int index = 0;
2369 
2370 	if (!vpd)
2371 		return 0;
2372 
2373 	/* Vital Product */
2374 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
2375 			"0455 Vital Product Data: x%x x%x x%x x%x\n",
2376 			(uint32_t) vpd[0], (uint32_t) vpd[1], (uint32_t) vpd[2],
2377 			(uint32_t) vpd[3]);
2378 	while (!finished && (index < (len - 4))) {
2379 		switch (vpd[index]) {
2380 		case 0x82:
2381 		case 0x91:
2382 			index += 1;
2383 			lenlo = vpd[index];
2384 			index += 1;
2385 			lenhi = vpd[index];
2386 			index += 1;
2387 			i = ((((unsigned short)lenhi) << 8) + lenlo);
2388 			index += i;
2389 			break;
2390 		case 0x90:
2391 			index += 1;
2392 			lenlo = vpd[index];
2393 			index += 1;
2394 			lenhi = vpd[index];
2395 			index += 1;
2396 			Length = ((((unsigned short)lenhi) << 8) + lenlo);
2397 			if (Length > len - index)
2398 				Length = len - index;
2399 
2400 			lpfc_fill_vpd(phba, vpd, Length, &index);
2401 			finished = 0;
2402 			break;
2403 		case 0x78:
2404 			finished = 1;
2405 			break;
2406 		default:
2407 			index ++;
2408 			break;
2409 		}
2410 	}
2411 
2412 	return(1);
2413 }
2414 
2415 /**
2416  * lpfc_get_atto_model_desc - Retrieve ATTO HBA device model name and description
2417  * @phba: pointer to lpfc hba data structure.
2418  * @mdp: pointer to the data structure to hold the derived model name.
2419  * @descp: pointer to the data structure to hold the derived description.
2420  *
2421  * This routine retrieves HBA's description based on its registered PCI device
2422  * ID. The @descp passed into this function points to an array of 256 chars. It
2423  * shall be returned with the model name, maximum speed, and the host bus type.
2424  * The @mdp passed into this function points to an array of 80 chars. When the
2425  * function returns, the @mdp will be filled with the model name.
2426  **/
2427 static void
2428 lpfc_get_atto_model_desc(struct lpfc_hba *phba, uint8_t *mdp, uint8_t *descp)
2429 {
2430 	uint16_t sub_dev_id = phba->pcidev->subsystem_device;
2431 	char *model = "<Unknown>";
2432 	int tbolt = 0;
2433 
2434 	switch (sub_dev_id) {
2435 	case PCI_DEVICE_ID_CLRY_161E:
2436 		model = "161E";
2437 		break;
2438 	case PCI_DEVICE_ID_CLRY_162E:
2439 		model = "162E";
2440 		break;
2441 	case PCI_DEVICE_ID_CLRY_164E:
2442 		model = "164E";
2443 		break;
2444 	case PCI_DEVICE_ID_CLRY_161P:
2445 		model = "161P";
2446 		break;
2447 	case PCI_DEVICE_ID_CLRY_162P:
2448 		model = "162P";
2449 		break;
2450 	case PCI_DEVICE_ID_CLRY_164P:
2451 		model = "164P";
2452 		break;
2453 	case PCI_DEVICE_ID_CLRY_321E:
2454 		model = "321E";
2455 		break;
2456 	case PCI_DEVICE_ID_CLRY_322E:
2457 		model = "322E";
2458 		break;
2459 	case PCI_DEVICE_ID_CLRY_324E:
2460 		model = "324E";
2461 		break;
2462 	case PCI_DEVICE_ID_CLRY_321P:
2463 		model = "321P";
2464 		break;
2465 	case PCI_DEVICE_ID_CLRY_322P:
2466 		model = "322P";
2467 		break;
2468 	case PCI_DEVICE_ID_CLRY_324P:
2469 		model = "324P";
2470 		break;
2471 	case PCI_DEVICE_ID_TLFC_2XX2:
2472 		model = "2XX2";
2473 		tbolt = 1;
2474 		break;
2475 	case PCI_DEVICE_ID_TLFC_3162:
2476 		model = "3162";
2477 		tbolt = 1;
2478 		break;
2479 	case PCI_DEVICE_ID_TLFC_3322:
2480 		model = "3322";
2481 		tbolt = 1;
2482 		break;
2483 	default:
2484 		model = "Unknown";
2485 		break;
2486 	}
2487 
2488 	if (mdp && mdp[0] == '\0')
2489 		snprintf(mdp, 79, "%s", model);
2490 
2491 	if (descp && descp[0] == '\0')
2492 		snprintf(descp, 255,
2493 			 "ATTO %s%s, Fibre Channel Adapter Initiator, Port %s",
2494 			 (tbolt) ? "ThunderLink FC " : "Celerity FC-",
2495 			 model,
2496 			 phba->Port);
2497 }
2498 
2499 /**
2500  * lpfc_get_hba_model_desc - Retrieve HBA device model name and description
2501  * @phba: pointer to lpfc hba data structure.
2502  * @mdp: pointer to the data structure to hold the derived model name.
2503  * @descp: pointer to the data structure to hold the derived description.
2504  *
2505  * This routine retrieves HBA's description based on its registered PCI device
2506  * ID. The @descp passed into this function points to an array of 256 chars. It
2507  * shall be returned with the model name, maximum speed, and the host bus type.
2508  * The @mdp passed into this function points to an array of 80 chars. When the
2509  * function returns, the @mdp will be filled with the model name.
2510  **/
2511 static void
2512 lpfc_get_hba_model_desc(struct lpfc_hba *phba, uint8_t *mdp, uint8_t *descp)
2513 {
2514 	lpfc_vpd_t *vp;
2515 	uint16_t dev_id = phba->pcidev->device;
2516 	int max_speed;
2517 	int GE = 0;
2518 	int oneConnect = 0; /* default is not a oneConnect */
2519 	struct {
2520 		char *name;
2521 		char *bus;
2522 		char *function;
2523 	} m = {"<Unknown>", "", ""};
2524 
2525 	if (mdp && mdp[0] != '\0'
2526 		&& descp && descp[0] != '\0')
2527 		return;
2528 
2529 	if (phba->pcidev->vendor == PCI_VENDOR_ID_ATTO) {
2530 		lpfc_get_atto_model_desc(phba, mdp, descp);
2531 		return;
2532 	}
2533 
2534 	if (phba->lmt & LMT_64Gb)
2535 		max_speed = 64;
2536 	else if (phba->lmt & LMT_32Gb)
2537 		max_speed = 32;
2538 	else if (phba->lmt & LMT_16Gb)
2539 		max_speed = 16;
2540 	else if (phba->lmt & LMT_10Gb)
2541 		max_speed = 10;
2542 	else if (phba->lmt & LMT_8Gb)
2543 		max_speed = 8;
2544 	else if (phba->lmt & LMT_4Gb)
2545 		max_speed = 4;
2546 	else if (phba->lmt & LMT_2Gb)
2547 		max_speed = 2;
2548 	else if (phba->lmt & LMT_1Gb)
2549 		max_speed = 1;
2550 	else
2551 		max_speed = 0;
2552 
2553 	vp = &phba->vpd;
2554 
2555 	switch (dev_id) {
2556 	case PCI_DEVICE_ID_FIREFLY:
2557 		m = (typeof(m)){"LP6000", "PCI",
2558 				"Obsolete, Unsupported Fibre Channel Adapter"};
2559 		break;
2560 	case PCI_DEVICE_ID_SUPERFLY:
2561 		if (vp->rev.biuRev >= 1 && vp->rev.biuRev <= 3)
2562 			m = (typeof(m)){"LP7000", "PCI", ""};
2563 		else
2564 			m = (typeof(m)){"LP7000E", "PCI", ""};
2565 		m.function = "Obsolete, Unsupported Fibre Channel Adapter";
2566 		break;
2567 	case PCI_DEVICE_ID_DRAGONFLY:
2568 		m = (typeof(m)){"LP8000", "PCI",
2569 				"Obsolete, Unsupported Fibre Channel Adapter"};
2570 		break;
2571 	case PCI_DEVICE_ID_CENTAUR:
2572 		if (FC_JEDEC_ID(vp->rev.biuRev) == CENTAUR_2G_JEDEC_ID)
2573 			m = (typeof(m)){"LP9002", "PCI", ""};
2574 		else
2575 			m = (typeof(m)){"LP9000", "PCI", ""};
2576 		m.function = "Obsolete, Unsupported Fibre Channel Adapter";
2577 		break;
2578 	case PCI_DEVICE_ID_RFLY:
2579 		m = (typeof(m)){"LP952", "PCI",
2580 				"Obsolete, Unsupported Fibre Channel Adapter"};
2581 		break;
2582 	case PCI_DEVICE_ID_PEGASUS:
2583 		m = (typeof(m)){"LP9802", "PCI-X",
2584 				"Obsolete, Unsupported Fibre Channel Adapter"};
2585 		break;
2586 	case PCI_DEVICE_ID_THOR:
2587 		m = (typeof(m)){"LP10000", "PCI-X",
2588 				"Obsolete, Unsupported Fibre Channel Adapter"};
2589 		break;
2590 	case PCI_DEVICE_ID_VIPER:
2591 		m = (typeof(m)){"LPX1000",  "PCI-X",
2592 				"Obsolete, Unsupported Fibre Channel Adapter"};
2593 		break;
2594 	case PCI_DEVICE_ID_PFLY:
2595 		m = (typeof(m)){"LP982", "PCI-X",
2596 				"Obsolete, Unsupported Fibre Channel Adapter"};
2597 		break;
2598 	case PCI_DEVICE_ID_TFLY:
2599 		m = (typeof(m)){"LP1050", "PCI-X",
2600 				"Obsolete, Unsupported Fibre Channel Adapter"};
2601 		break;
2602 	case PCI_DEVICE_ID_HELIOS:
2603 		m = (typeof(m)){"LP11000", "PCI-X2",
2604 				"Obsolete, Unsupported Fibre Channel Adapter"};
2605 		break;
2606 	case PCI_DEVICE_ID_HELIOS_SCSP:
2607 		m = (typeof(m)){"LP11000-SP", "PCI-X2",
2608 				"Obsolete, Unsupported Fibre Channel Adapter"};
2609 		break;
2610 	case PCI_DEVICE_ID_HELIOS_DCSP:
2611 		m = (typeof(m)){"LP11002-SP",  "PCI-X2",
2612 				"Obsolete, Unsupported Fibre Channel Adapter"};
2613 		break;
2614 	case PCI_DEVICE_ID_NEPTUNE:
2615 		m = (typeof(m)){"LPe1000", "PCIe",
2616 				"Obsolete, Unsupported Fibre Channel Adapter"};
2617 		break;
2618 	case PCI_DEVICE_ID_NEPTUNE_SCSP:
2619 		m = (typeof(m)){"LPe1000-SP", "PCIe",
2620 				"Obsolete, Unsupported Fibre Channel Adapter"};
2621 		break;
2622 	case PCI_DEVICE_ID_NEPTUNE_DCSP:
2623 		m = (typeof(m)){"LPe1002-SP", "PCIe",
2624 				"Obsolete, Unsupported Fibre Channel Adapter"};
2625 		break;
2626 	case PCI_DEVICE_ID_BMID:
2627 		m = (typeof(m)){"LP1150", "PCI-X2", "Fibre Channel Adapter"};
2628 		break;
2629 	case PCI_DEVICE_ID_BSMB:
2630 		m = (typeof(m)){"LP111", "PCI-X2",
2631 				"Obsolete, Unsupported Fibre Channel Adapter"};
2632 		break;
2633 	case PCI_DEVICE_ID_ZEPHYR:
2634 		m = (typeof(m)){"LPe11000", "PCIe", "Fibre Channel Adapter"};
2635 		break;
2636 	case PCI_DEVICE_ID_ZEPHYR_SCSP:
2637 		m = (typeof(m)){"LPe11000", "PCIe", "Fibre Channel Adapter"};
2638 		break;
2639 	case PCI_DEVICE_ID_ZEPHYR_DCSP:
2640 		m = (typeof(m)){"LP2105", "PCIe", "FCoE Adapter"};
2641 		GE = 1;
2642 		break;
2643 	case PCI_DEVICE_ID_ZMID:
2644 		m = (typeof(m)){"LPe1150", "PCIe", "Fibre Channel Adapter"};
2645 		break;
2646 	case PCI_DEVICE_ID_ZSMB:
2647 		m = (typeof(m)){"LPe111", "PCIe", "Fibre Channel Adapter"};
2648 		break;
2649 	case PCI_DEVICE_ID_LP101:
2650 		m = (typeof(m)){"LP101", "PCI-X",
2651 				"Obsolete, Unsupported Fibre Channel Adapter"};
2652 		break;
2653 	case PCI_DEVICE_ID_LP10000S:
2654 		m = (typeof(m)){"LP10000-S", "PCI",
2655 				"Obsolete, Unsupported Fibre Channel Adapter"};
2656 		break;
2657 	case PCI_DEVICE_ID_LP11000S:
2658 		m = (typeof(m)){"LP11000-S", "PCI-X2",
2659 				"Obsolete, Unsupported Fibre Channel Adapter"};
2660 		break;
2661 	case PCI_DEVICE_ID_LPE11000S:
2662 		m = (typeof(m)){"LPe11000-S", "PCIe",
2663 				"Obsolete, Unsupported Fibre Channel Adapter"};
2664 		break;
2665 	case PCI_DEVICE_ID_SAT:
2666 		m = (typeof(m)){"LPe12000", "PCIe", "Fibre Channel Adapter"};
2667 		break;
2668 	case PCI_DEVICE_ID_SAT_MID:
2669 		m = (typeof(m)){"LPe1250", "PCIe", "Fibre Channel Adapter"};
2670 		break;
2671 	case PCI_DEVICE_ID_SAT_SMB:
2672 		m = (typeof(m)){"LPe121", "PCIe", "Fibre Channel Adapter"};
2673 		break;
2674 	case PCI_DEVICE_ID_SAT_DCSP:
2675 		m = (typeof(m)){"LPe12002-SP", "PCIe", "Fibre Channel Adapter"};
2676 		break;
2677 	case PCI_DEVICE_ID_SAT_SCSP:
2678 		m = (typeof(m)){"LPe12000-SP", "PCIe", "Fibre Channel Adapter"};
2679 		break;
2680 	case PCI_DEVICE_ID_SAT_S:
2681 		m = (typeof(m)){"LPe12000-S", "PCIe", "Fibre Channel Adapter"};
2682 		break;
2683 	case PCI_DEVICE_ID_PROTEUS_VF:
2684 		m = (typeof(m)){"LPev12000", "PCIe IOV",
2685 				"Obsolete, Unsupported Fibre Channel Adapter"};
2686 		break;
2687 	case PCI_DEVICE_ID_PROTEUS_PF:
2688 		m = (typeof(m)){"LPev12000", "PCIe IOV",
2689 				"Obsolete, Unsupported Fibre Channel Adapter"};
2690 		break;
2691 	case PCI_DEVICE_ID_PROTEUS_S:
2692 		m = (typeof(m)){"LPemv12002-S", "PCIe IOV",
2693 				"Obsolete, Unsupported Fibre Channel Adapter"};
2694 		break;
2695 	case PCI_DEVICE_ID_TIGERSHARK:
2696 		oneConnect = 1;
2697 		m = (typeof(m)){"OCe10100", "PCIe", "FCoE"};
2698 		break;
2699 	case PCI_DEVICE_ID_TOMCAT:
2700 		oneConnect = 1;
2701 		m = (typeof(m)){"OCe11100", "PCIe", "FCoE"};
2702 		break;
2703 	case PCI_DEVICE_ID_FALCON:
2704 		m = (typeof(m)){"LPSe12002-ML1-E", "PCIe",
2705 				"EmulexSecure Fibre"};
2706 		break;
2707 	case PCI_DEVICE_ID_BALIUS:
2708 		m = (typeof(m)){"LPVe12002", "PCIe Shared I/O",
2709 				"Obsolete, Unsupported Fibre Channel Adapter"};
2710 		break;
2711 	case PCI_DEVICE_ID_LANCER_FC:
2712 		m = (typeof(m)){"LPe16000", "PCIe", "Fibre Channel Adapter"};
2713 		break;
2714 	case PCI_DEVICE_ID_LANCER_FC_VF:
2715 		m = (typeof(m)){"LPe16000", "PCIe",
2716 				"Obsolete, Unsupported Fibre Channel Adapter"};
2717 		break;
2718 	case PCI_DEVICE_ID_LANCER_FCOE:
2719 		oneConnect = 1;
2720 		m = (typeof(m)){"OCe15100", "PCIe", "FCoE"};
2721 		break;
2722 	case PCI_DEVICE_ID_LANCER_FCOE_VF:
2723 		oneConnect = 1;
2724 		m = (typeof(m)){"OCe15100", "PCIe",
2725 				"Obsolete, Unsupported FCoE"};
2726 		break;
2727 	case PCI_DEVICE_ID_LANCER_G6_FC:
2728 		m = (typeof(m)){"LPe32000", "PCIe", "Fibre Channel Adapter"};
2729 		break;
2730 	case PCI_DEVICE_ID_LANCER_G7_FC:
2731 		m = (typeof(m)){"LPe36000", "PCIe", "Fibre Channel Adapter"};
2732 		break;
2733 	case PCI_DEVICE_ID_LANCER_G7P_FC:
2734 		m = (typeof(m)){"LPe38000", "PCIe", "Fibre Channel Adapter"};
2735 		break;
2736 	case PCI_DEVICE_ID_SKYHAWK:
2737 	case PCI_DEVICE_ID_SKYHAWK_VF:
2738 		oneConnect = 1;
2739 		m = (typeof(m)){"OCe14000", "PCIe", "FCoE"};
2740 		break;
2741 	default:
2742 		m = (typeof(m)){"Unknown", "", ""};
2743 		break;
2744 	}
2745 
2746 	if (mdp && mdp[0] == '\0')
2747 		snprintf(mdp, 79,"%s", m.name);
2748 	/*
2749 	 * oneConnect hba requires special processing, they are all initiators
2750 	 * and we put the port number on the end
2751 	 */
2752 	if (descp && descp[0] == '\0') {
2753 		if (oneConnect)
2754 			snprintf(descp, 255,
2755 				"Emulex OneConnect %s, %s Initiator %s",
2756 				m.name, m.function,
2757 				phba->Port);
2758 		else if (max_speed == 0)
2759 			snprintf(descp, 255,
2760 				"Emulex %s %s %s",
2761 				m.name, m.bus, m.function);
2762 		else
2763 			snprintf(descp, 255,
2764 				"Emulex %s %d%s %s %s",
2765 				m.name, max_speed, (GE) ? "GE" : "Gb",
2766 				m.bus, m.function);
2767 	}
2768 }
2769 
2770 /**
2771  * lpfc_sli3_post_buffer - Post IOCB(s) with DMA buffer descriptor(s) to a IOCB ring
2772  * @phba: pointer to lpfc hba data structure.
2773  * @pring: pointer to a IOCB ring.
2774  * @cnt: the number of IOCBs to be posted to the IOCB ring.
2775  *
2776  * This routine posts a given number of IOCBs with the associated DMA buffer
2777  * descriptors specified by the cnt argument to the given IOCB ring.
2778  *
2779  * Return codes
2780  *   The number of IOCBs NOT able to be posted to the IOCB ring.
2781  **/
2782 int
2783 lpfc_sli3_post_buffer(struct lpfc_hba *phba, struct lpfc_sli_ring *pring, int cnt)
2784 {
2785 	IOCB_t *icmd;
2786 	struct lpfc_iocbq *iocb;
2787 	struct lpfc_dmabuf *mp1, *mp2;
2788 
2789 	cnt += pring->missbufcnt;
2790 
2791 	/* While there are buffers to post */
2792 	while (cnt > 0) {
2793 		/* Allocate buffer for  command iocb */
2794 		iocb = lpfc_sli_get_iocbq(phba);
2795 		if (iocb == NULL) {
2796 			pring->missbufcnt = cnt;
2797 			return cnt;
2798 		}
2799 		icmd = &iocb->iocb;
2800 
2801 		/* 2 buffers can be posted per command */
2802 		/* Allocate buffer to post */
2803 		mp1 = kmalloc(sizeof (struct lpfc_dmabuf), GFP_KERNEL);
2804 		if (mp1)
2805 		    mp1->virt = lpfc_mbuf_alloc(phba, MEM_PRI, &mp1->phys);
2806 		if (!mp1 || !mp1->virt) {
2807 			kfree(mp1);
2808 			lpfc_sli_release_iocbq(phba, iocb);
2809 			pring->missbufcnt = cnt;
2810 			return cnt;
2811 		}
2812 
2813 		INIT_LIST_HEAD(&mp1->list);
2814 		/* Allocate buffer to post */
2815 		if (cnt > 1) {
2816 			mp2 = kmalloc(sizeof (struct lpfc_dmabuf), GFP_KERNEL);
2817 			if (mp2)
2818 				mp2->virt = lpfc_mbuf_alloc(phba, MEM_PRI,
2819 							    &mp2->phys);
2820 			if (!mp2 || !mp2->virt) {
2821 				kfree(mp2);
2822 				lpfc_mbuf_free(phba, mp1->virt, mp1->phys);
2823 				kfree(mp1);
2824 				lpfc_sli_release_iocbq(phba, iocb);
2825 				pring->missbufcnt = cnt;
2826 				return cnt;
2827 			}
2828 
2829 			INIT_LIST_HEAD(&mp2->list);
2830 		} else {
2831 			mp2 = NULL;
2832 		}
2833 
2834 		icmd->un.cont64[0].addrHigh = putPaddrHigh(mp1->phys);
2835 		icmd->un.cont64[0].addrLow = putPaddrLow(mp1->phys);
2836 		icmd->un.cont64[0].tus.f.bdeSize = FCELSSIZE;
2837 		icmd->ulpBdeCount = 1;
2838 		cnt--;
2839 		if (mp2) {
2840 			icmd->un.cont64[1].addrHigh = putPaddrHigh(mp2->phys);
2841 			icmd->un.cont64[1].addrLow = putPaddrLow(mp2->phys);
2842 			icmd->un.cont64[1].tus.f.bdeSize = FCELSSIZE;
2843 			cnt--;
2844 			icmd->ulpBdeCount = 2;
2845 		}
2846 
2847 		icmd->ulpCommand = CMD_QUE_RING_BUF64_CN;
2848 		icmd->ulpLe = 1;
2849 
2850 		if (lpfc_sli_issue_iocb(phba, pring->ringno, iocb, 0) ==
2851 		    IOCB_ERROR) {
2852 			lpfc_mbuf_free(phba, mp1->virt, mp1->phys);
2853 			kfree(mp1);
2854 			cnt++;
2855 			if (mp2) {
2856 				lpfc_mbuf_free(phba, mp2->virt, mp2->phys);
2857 				kfree(mp2);
2858 				cnt++;
2859 			}
2860 			lpfc_sli_release_iocbq(phba, iocb);
2861 			pring->missbufcnt = cnt;
2862 			return cnt;
2863 		}
2864 		lpfc_sli_ringpostbuf_put(phba, pring, mp1);
2865 		if (mp2)
2866 			lpfc_sli_ringpostbuf_put(phba, pring, mp2);
2867 	}
2868 	pring->missbufcnt = 0;
2869 	return 0;
2870 }
2871 
2872 /**
2873  * lpfc_post_rcv_buf - Post the initial receive IOCB buffers to ELS ring
2874  * @phba: pointer to lpfc hba data structure.
2875  *
2876  * This routine posts initial receive IOCB buffers to the ELS ring. The
2877  * current number of initial IOCB buffers specified by LPFC_BUF_RING0 is
2878  * set to 64 IOCBs. SLI3 only.
2879  *
2880  * Return codes
2881  *   0 - success (currently always success)
2882  **/
2883 static int
2884 lpfc_post_rcv_buf(struct lpfc_hba *phba)
2885 {
2886 	struct lpfc_sli *psli = &phba->sli;
2887 
2888 	/* Ring 0, ELS / CT buffers */
2889 	lpfc_sli3_post_buffer(phba, &psli->sli3_ring[LPFC_ELS_RING], LPFC_BUF_RING0);
2890 	/* Ring 2 - FCP no buffers needed */
2891 
2892 	return 0;
2893 }
2894 
2895 #define S(N,V) (((V)<<(N))|((V)>>(32-(N))))
2896 
2897 /**
2898  * lpfc_sha_init - Set up initial array of hash table entries
2899  * @HashResultPointer: pointer to an array as hash table.
2900  *
2901  * This routine sets up the initial values to the array of hash table entries
2902  * for the LC HBAs.
2903  **/
2904 static void
2905 lpfc_sha_init(uint32_t * HashResultPointer)
2906 {
2907 	HashResultPointer[0] = 0x67452301;
2908 	HashResultPointer[1] = 0xEFCDAB89;
2909 	HashResultPointer[2] = 0x98BADCFE;
2910 	HashResultPointer[3] = 0x10325476;
2911 	HashResultPointer[4] = 0xC3D2E1F0;
2912 }
2913 
2914 /**
2915  * lpfc_sha_iterate - Iterate initial hash table with the working hash table
2916  * @HashResultPointer: pointer to an initial/result hash table.
2917  * @HashWorkingPointer: pointer to an working hash table.
2918  *
2919  * This routine iterates an initial hash table pointed by @HashResultPointer
2920  * with the values from the working hash table pointeed by @HashWorkingPointer.
2921  * The results are putting back to the initial hash table, returned through
2922  * the @HashResultPointer as the result hash table.
2923  **/
2924 static void
2925 lpfc_sha_iterate(uint32_t * HashResultPointer, uint32_t * HashWorkingPointer)
2926 {
2927 	int t;
2928 	uint32_t TEMP;
2929 	uint32_t A, B, C, D, E;
2930 	t = 16;
2931 	do {
2932 		HashWorkingPointer[t] =
2933 		    S(1,
2934 		      HashWorkingPointer[t - 3] ^ HashWorkingPointer[t -
2935 								     8] ^
2936 		      HashWorkingPointer[t - 14] ^ HashWorkingPointer[t - 16]);
2937 	} while (++t <= 79);
2938 	t = 0;
2939 	A = HashResultPointer[0];
2940 	B = HashResultPointer[1];
2941 	C = HashResultPointer[2];
2942 	D = HashResultPointer[3];
2943 	E = HashResultPointer[4];
2944 
2945 	do {
2946 		if (t < 20) {
2947 			TEMP = ((B & C) | ((~B) & D)) + 0x5A827999;
2948 		} else if (t < 40) {
2949 			TEMP = (B ^ C ^ D) + 0x6ED9EBA1;
2950 		} else if (t < 60) {
2951 			TEMP = ((B & C) | (B & D) | (C & D)) + 0x8F1BBCDC;
2952 		} else {
2953 			TEMP = (B ^ C ^ D) + 0xCA62C1D6;
2954 		}
2955 		TEMP += S(5, A) + E + HashWorkingPointer[t];
2956 		E = D;
2957 		D = C;
2958 		C = S(30, B);
2959 		B = A;
2960 		A = TEMP;
2961 	} while (++t <= 79);
2962 
2963 	HashResultPointer[0] += A;
2964 	HashResultPointer[1] += B;
2965 	HashResultPointer[2] += C;
2966 	HashResultPointer[3] += D;
2967 	HashResultPointer[4] += E;
2968 
2969 }
2970 
2971 /**
2972  * lpfc_challenge_key - Create challenge key based on WWPN of the HBA
2973  * @RandomChallenge: pointer to the entry of host challenge random number array.
2974  * @HashWorking: pointer to the entry of the working hash array.
2975  *
2976  * This routine calculates the working hash array referred by @HashWorking
2977  * from the challenge random numbers associated with the host, referred by
2978  * @RandomChallenge. The result is put into the entry of the working hash
2979  * array and returned by reference through @HashWorking.
2980  **/
2981 static void
2982 lpfc_challenge_key(uint32_t * RandomChallenge, uint32_t * HashWorking)
2983 {
2984 	*HashWorking = (*RandomChallenge ^ *HashWorking);
2985 }
2986 
2987 /**
2988  * lpfc_hba_init - Perform special handling for LC HBA initialization
2989  * @phba: pointer to lpfc hba data structure.
2990  * @hbainit: pointer to an array of unsigned 32-bit integers.
2991  *
2992  * This routine performs the special handling for LC HBA initialization.
2993  **/
2994 void
2995 lpfc_hba_init(struct lpfc_hba *phba, uint32_t *hbainit)
2996 {
2997 	int t;
2998 	uint32_t *HashWorking;
2999 	uint32_t *pwwnn = (uint32_t *) phba->wwnn;
3000 
3001 	HashWorking = kcalloc(80, sizeof(uint32_t), GFP_KERNEL);
3002 	if (!HashWorking)
3003 		return;
3004 
3005 	HashWorking[0] = HashWorking[78] = *pwwnn++;
3006 	HashWorking[1] = HashWorking[79] = *pwwnn;
3007 
3008 	for (t = 0; t < 7; t++)
3009 		lpfc_challenge_key(phba->RandomData + t, HashWorking + t);
3010 
3011 	lpfc_sha_init(hbainit);
3012 	lpfc_sha_iterate(hbainit, HashWorking);
3013 	kfree(HashWorking);
3014 }
3015 
3016 /**
3017  * lpfc_cleanup - Performs vport cleanups before deleting a vport
3018  * @vport: pointer to a virtual N_Port data structure.
3019  *
3020  * This routine performs the necessary cleanups before deleting the @vport.
3021  * It invokes the discovery state machine to perform necessary state
3022  * transitions and to release the ndlps associated with the @vport. Note,
3023  * the physical port is treated as @vport 0.
3024  **/
3025 void
3026 lpfc_cleanup(struct lpfc_vport *vport)
3027 {
3028 	struct lpfc_hba   *phba = vport->phba;
3029 	struct lpfc_nodelist *ndlp, *next_ndlp;
3030 	int i = 0;
3031 
3032 	if (phba->link_state > LPFC_LINK_DOWN)
3033 		lpfc_port_link_failure(vport);
3034 
3035 	/* Clean up VMID resources */
3036 	if (lpfc_is_vmid_enabled(phba))
3037 		lpfc_vmid_vport_cleanup(vport);
3038 
3039 	list_for_each_entry_safe(ndlp, next_ndlp, &vport->fc_nodes, nlp_listp) {
3040 		if (vport->port_type != LPFC_PHYSICAL_PORT &&
3041 		    ndlp->nlp_DID == Fabric_DID) {
3042 			/* Just free up ndlp with Fabric_DID for vports */
3043 			lpfc_nlp_put(ndlp);
3044 			continue;
3045 		}
3046 
3047 		if (ndlp->nlp_DID == Fabric_Cntl_DID &&
3048 		    ndlp->nlp_state == NLP_STE_UNUSED_NODE) {
3049 			lpfc_nlp_put(ndlp);
3050 			continue;
3051 		}
3052 
3053 		/* Fabric Ports not in UNMAPPED state are cleaned up in the
3054 		 * DEVICE_RM event.
3055 		 */
3056 		if (ndlp->nlp_type & NLP_FABRIC &&
3057 		    ndlp->nlp_state == NLP_STE_UNMAPPED_NODE)
3058 			lpfc_disc_state_machine(vport, ndlp, NULL,
3059 					NLP_EVT_DEVICE_RECOVERY);
3060 
3061 		if (!(ndlp->fc4_xpt_flags & (NVME_XPT_REGD|SCSI_XPT_REGD)))
3062 			lpfc_disc_state_machine(vport, ndlp, NULL,
3063 					NLP_EVT_DEVICE_RM);
3064 	}
3065 
3066 	/* This is a special case flush to return all
3067 	 * IOs before entering this loop. There are
3068 	 * two points in the code where a flush is
3069 	 * avoided if the FC_UNLOADING flag is set.
3070 	 * one is in the multipool destroy,
3071 	 * (this prevents a crash) and the other is
3072 	 * in the nvme abort handler, ( also prevents
3073 	 * a crash). Both of these exceptions are
3074 	 * cases where the slot is still accessible.
3075 	 * The flush here is only when the pci slot
3076 	 * is offline.
3077 	 */
3078 	if (test_bit(FC_UNLOADING, &vport->load_flag) &&
3079 	    pci_channel_offline(phba->pcidev))
3080 		lpfc_sli_flush_io_rings(vport->phba);
3081 
3082 	/* At this point, ALL ndlp's should be gone
3083 	 * because of the previous NLP_EVT_DEVICE_RM.
3084 	 * Lets wait for this to happen, if needed.
3085 	 */
3086 	while (!list_empty(&vport->fc_nodes)) {
3087 		if (i++ > 3000) {
3088 			lpfc_printf_vlog(vport, KERN_ERR,
3089 					 LOG_TRACE_EVENT,
3090 				"0233 Nodelist not empty\n");
3091 			list_for_each_entry_safe(ndlp, next_ndlp,
3092 						&vport->fc_nodes, nlp_listp) {
3093 				lpfc_printf_vlog(ndlp->vport, KERN_ERR,
3094 						 LOG_DISCOVERY,
3095 						 "0282 did:x%x ndlp:x%px "
3096 						 "refcnt:%d xflags x%x "
3097 						 "nflag x%lx\n",
3098 						 ndlp->nlp_DID, (void *)ndlp,
3099 						 kref_read(&ndlp->kref),
3100 						 ndlp->fc4_xpt_flags,
3101 						 ndlp->nlp_flag);
3102 			}
3103 			break;
3104 		}
3105 
3106 		/* Wait for any activity on ndlps to settle */
3107 		msleep(10);
3108 	}
3109 	lpfc_cleanup_vports_rrqs(vport, NULL);
3110 }
3111 
3112 /**
3113  * lpfc_stop_vport_timers - Stop all the timers associated with a vport
3114  * @vport: pointer to a virtual N_Port data structure.
3115  *
3116  * This routine stops all the timers associated with a @vport. This function
3117  * is invoked before disabling or deleting a @vport. Note that the physical
3118  * port is treated as @vport 0.
3119  **/
3120 void
3121 lpfc_stop_vport_timers(struct lpfc_vport *vport)
3122 {
3123 	del_timer_sync(&vport->els_tmofunc);
3124 	del_timer_sync(&vport->delayed_disc_tmo);
3125 	lpfc_can_disctmo(vport);
3126 	return;
3127 }
3128 
3129 /**
3130  * __lpfc_sli4_stop_fcf_redisc_wait_timer - Stop FCF rediscovery wait timer
3131  * @phba: pointer to lpfc hba data structure.
3132  *
3133  * This routine stops the SLI4 FCF rediscover wait timer if it's on. The
3134  * caller of this routine should already hold the host lock.
3135  **/
3136 void
3137 __lpfc_sli4_stop_fcf_redisc_wait_timer(struct lpfc_hba *phba)
3138 {
3139 	/* Clear pending FCF rediscovery wait flag */
3140 	phba->fcf.fcf_flag &= ~FCF_REDISC_PEND;
3141 
3142 	/* Now, try to stop the timer */
3143 	del_timer(&phba->fcf.redisc_wait);
3144 }
3145 
3146 /**
3147  * lpfc_sli4_stop_fcf_redisc_wait_timer - Stop FCF rediscovery wait timer
3148  * @phba: pointer to lpfc hba data structure.
3149  *
3150  * This routine stops the SLI4 FCF rediscover wait timer if it's on. It
3151  * checks whether the FCF rediscovery wait timer is pending with the host
3152  * lock held before proceeding with disabling the timer and clearing the
3153  * wait timer pendig flag.
3154  **/
3155 void
3156 lpfc_sli4_stop_fcf_redisc_wait_timer(struct lpfc_hba *phba)
3157 {
3158 	spin_lock_irq(&phba->hbalock);
3159 	if (!(phba->fcf.fcf_flag & FCF_REDISC_PEND)) {
3160 		/* FCF rediscovery timer already fired or stopped */
3161 		spin_unlock_irq(&phba->hbalock);
3162 		return;
3163 	}
3164 	__lpfc_sli4_stop_fcf_redisc_wait_timer(phba);
3165 	/* Clear failover in progress flags */
3166 	phba->fcf.fcf_flag &= ~(FCF_DEAD_DISC | FCF_ACVL_DISC);
3167 	spin_unlock_irq(&phba->hbalock);
3168 }
3169 
3170 /**
3171  * lpfc_cmf_stop - Stop CMF processing
3172  * @phba: pointer to lpfc hba data structure.
3173  *
3174  * This is called when the link goes down or if CMF mode is turned OFF.
3175  * It is also called when going offline or unloaded just before the
3176  * congestion info buffer is unregistered.
3177  **/
3178 void
3179 lpfc_cmf_stop(struct lpfc_hba *phba)
3180 {
3181 	int cpu;
3182 	struct lpfc_cgn_stat *cgs;
3183 
3184 	/* We only do something if CMF is enabled */
3185 	if (!phba->sli4_hba.pc_sli4_params.cmf)
3186 		return;
3187 
3188 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
3189 			"6221 Stop CMF / Cancel Timer\n");
3190 
3191 	/* Cancel the CMF timer */
3192 	hrtimer_cancel(&phba->cmf_stats_timer);
3193 	hrtimer_cancel(&phba->cmf_timer);
3194 
3195 	/* Zero CMF counters */
3196 	atomic_set(&phba->cmf_busy, 0);
3197 	for_each_present_cpu(cpu) {
3198 		cgs = per_cpu_ptr(phba->cmf_stat, cpu);
3199 		atomic64_set(&cgs->total_bytes, 0);
3200 		atomic64_set(&cgs->rcv_bytes, 0);
3201 		atomic_set(&cgs->rx_io_cnt, 0);
3202 		atomic64_set(&cgs->rx_latency, 0);
3203 	}
3204 	atomic_set(&phba->cmf_bw_wait, 0);
3205 
3206 	/* Resume any blocked IO - Queue unblock on workqueue */
3207 	queue_work(phba->wq, &phba->unblock_request_work);
3208 }
3209 
3210 static inline uint64_t
3211 lpfc_get_max_line_rate(struct lpfc_hba *phba)
3212 {
3213 	uint64_t rate = lpfc_sli_port_speed_get(phba);
3214 
3215 	return ((((unsigned long)rate) * 1024 * 1024) / 10);
3216 }
3217 
3218 void
3219 lpfc_cmf_signal_init(struct lpfc_hba *phba)
3220 {
3221 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
3222 			"6223 Signal CMF init\n");
3223 
3224 	/* Use the new fc_linkspeed to recalculate */
3225 	phba->cmf_interval_rate = LPFC_CMF_INTERVAL;
3226 	phba->cmf_max_line_rate = lpfc_get_max_line_rate(phba);
3227 	phba->cmf_link_byte_count = div_u64(phba->cmf_max_line_rate *
3228 					    phba->cmf_interval_rate, 1000);
3229 	phba->cmf_max_bytes_per_interval = phba->cmf_link_byte_count;
3230 
3231 	/* This is a signal to firmware to sync up CMF BW with link speed */
3232 	lpfc_issue_cmf_sync_wqe(phba, 0, 0);
3233 }
3234 
3235 /**
3236  * lpfc_cmf_start - Start CMF processing
3237  * @phba: pointer to lpfc hba data structure.
3238  *
3239  * This is called when the link comes up or if CMF mode is turned OFF
3240  * to Monitor or Managed.
3241  **/
3242 void
3243 lpfc_cmf_start(struct lpfc_hba *phba)
3244 {
3245 	struct lpfc_cgn_stat *cgs;
3246 	int cpu;
3247 
3248 	/* We only do something if CMF is enabled */
3249 	if (!phba->sli4_hba.pc_sli4_params.cmf ||
3250 	    phba->cmf_active_mode == LPFC_CFG_OFF)
3251 		return;
3252 
3253 	/* Reinitialize congestion buffer info */
3254 	lpfc_init_congestion_buf(phba);
3255 
3256 	atomic_set(&phba->cgn_fabric_warn_cnt, 0);
3257 	atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
3258 	atomic_set(&phba->cgn_sync_alarm_cnt, 0);
3259 	atomic_set(&phba->cgn_sync_warn_cnt, 0);
3260 
3261 	atomic_set(&phba->cmf_busy, 0);
3262 	for_each_present_cpu(cpu) {
3263 		cgs = per_cpu_ptr(phba->cmf_stat, cpu);
3264 		atomic64_set(&cgs->total_bytes, 0);
3265 		atomic64_set(&cgs->rcv_bytes, 0);
3266 		atomic_set(&cgs->rx_io_cnt, 0);
3267 		atomic64_set(&cgs->rx_latency, 0);
3268 	}
3269 	phba->cmf_latency.tv_sec = 0;
3270 	phba->cmf_latency.tv_nsec = 0;
3271 
3272 	lpfc_cmf_signal_init(phba);
3273 
3274 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
3275 			"6222 Start CMF / Timer\n");
3276 
3277 	phba->cmf_timer_cnt = 0;
3278 	hrtimer_start(&phba->cmf_timer,
3279 		      ktime_set(0, LPFC_CMF_INTERVAL * NSEC_PER_MSEC),
3280 		      HRTIMER_MODE_REL);
3281 	hrtimer_start(&phba->cmf_stats_timer,
3282 		      ktime_set(0, LPFC_SEC_MIN * NSEC_PER_SEC),
3283 		      HRTIMER_MODE_REL);
3284 	/* Setup for latency check in IO cmpl routines */
3285 	ktime_get_real_ts64(&phba->cmf_latency);
3286 
3287 	atomic_set(&phba->cmf_bw_wait, 0);
3288 	atomic_set(&phba->cmf_stop_io, 0);
3289 }
3290 
3291 /**
3292  * lpfc_stop_hba_timers - Stop all the timers associated with an HBA
3293  * @phba: pointer to lpfc hba data structure.
3294  *
3295  * This routine stops all the timers associated with a HBA. This function is
3296  * invoked before either putting a HBA offline or unloading the driver.
3297  **/
3298 void
3299 lpfc_stop_hba_timers(struct lpfc_hba *phba)
3300 {
3301 	if (phba->pport)
3302 		lpfc_stop_vport_timers(phba->pport);
3303 	cancel_delayed_work_sync(&phba->eq_delay_work);
3304 	cancel_delayed_work_sync(&phba->idle_stat_delay_work);
3305 	del_timer_sync(&phba->sli.mbox_tmo);
3306 	del_timer_sync(&phba->fabric_block_timer);
3307 	del_timer_sync(&phba->eratt_poll);
3308 	del_timer_sync(&phba->hb_tmofunc);
3309 	if (phba->sli_rev == LPFC_SLI_REV4) {
3310 		del_timer_sync(&phba->rrq_tmr);
3311 		clear_bit(HBA_RRQ_ACTIVE, &phba->hba_flag);
3312 	}
3313 	clear_bit(HBA_HBEAT_INP, &phba->hba_flag);
3314 	clear_bit(HBA_HBEAT_TMO, &phba->hba_flag);
3315 
3316 	switch (phba->pci_dev_grp) {
3317 	case LPFC_PCI_DEV_LP:
3318 		/* Stop any LightPulse device specific driver timers */
3319 		del_timer_sync(&phba->fcp_poll_timer);
3320 		break;
3321 	case LPFC_PCI_DEV_OC:
3322 		/* Stop any OneConnect device specific driver timers */
3323 		lpfc_sli4_stop_fcf_redisc_wait_timer(phba);
3324 		break;
3325 	default:
3326 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3327 				"0297 Invalid device group (x%x)\n",
3328 				phba->pci_dev_grp);
3329 		break;
3330 	}
3331 	return;
3332 }
3333 
3334 /**
3335  * lpfc_block_mgmt_io - Mark a HBA's management interface as blocked
3336  * @phba: pointer to lpfc hba data structure.
3337  * @mbx_action: flag for mailbox no wait action.
3338  *
3339  * This routine marks a HBA's management interface as blocked. Once the HBA's
3340  * management interface is marked as blocked, all the user space access to
3341  * the HBA, whether they are from sysfs interface or libdfc interface will
3342  * all be blocked. The HBA is set to block the management interface when the
3343  * driver prepares the HBA interface for online or offline.
3344  **/
3345 static void
3346 lpfc_block_mgmt_io(struct lpfc_hba *phba, int mbx_action)
3347 {
3348 	unsigned long iflag;
3349 	uint8_t actcmd = MBX_HEARTBEAT;
3350 	unsigned long timeout;
3351 
3352 	spin_lock_irqsave(&phba->hbalock, iflag);
3353 	phba->sli.sli_flag |= LPFC_BLOCK_MGMT_IO;
3354 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3355 	if (mbx_action == LPFC_MBX_NO_WAIT)
3356 		return;
3357 	timeout = msecs_to_jiffies(LPFC_MBOX_TMO * 1000) + jiffies;
3358 	spin_lock_irqsave(&phba->hbalock, iflag);
3359 	if (phba->sli.mbox_active) {
3360 		actcmd = phba->sli.mbox_active->u.mb.mbxCommand;
3361 		/* Determine how long we might wait for the active mailbox
3362 		 * command to be gracefully completed by firmware.
3363 		 */
3364 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
3365 				phba->sli.mbox_active) * 1000) + jiffies;
3366 	}
3367 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3368 
3369 	/* Wait for the outstnading mailbox command to complete */
3370 	while (phba->sli.mbox_active) {
3371 		/* Check active mailbox complete status every 2ms */
3372 		msleep(2);
3373 		if (time_after(jiffies, timeout)) {
3374 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3375 					"2813 Mgmt IO is Blocked %x "
3376 					"- mbox cmd %x still active\n",
3377 					phba->sli.sli_flag, actcmd);
3378 			break;
3379 		}
3380 	}
3381 }
3382 
3383 /**
3384  * lpfc_sli4_node_rpi_restore - Recover assigned RPIs for active nodes.
3385  * @phba: pointer to lpfc hba data structure.
3386  *
3387  * Allocate RPIs for all active remote nodes. This is needed whenever
3388  * an SLI4 adapter is reset and the driver is not unloading. Its purpose
3389  * is to fixup the temporary rpi assignments.
3390  **/
3391 void
3392 lpfc_sli4_node_rpi_restore(struct lpfc_hba *phba)
3393 {
3394 	struct lpfc_nodelist  *ndlp, *next_ndlp;
3395 	struct lpfc_vport **vports;
3396 	int i, rpi;
3397 
3398 	if (phba->sli_rev != LPFC_SLI_REV4)
3399 		return;
3400 
3401 	vports = lpfc_create_vport_work_array(phba);
3402 	if (!vports)
3403 		return;
3404 
3405 	for (i = 0; i <= phba->max_vports && vports[i]; i++) {
3406 		if (test_bit(FC_UNLOADING, &vports[i]->load_flag))
3407 			continue;
3408 
3409 		list_for_each_entry_safe(ndlp, next_ndlp,
3410 					 &vports[i]->fc_nodes,
3411 					 nlp_listp) {
3412 			rpi = lpfc_sli4_alloc_rpi(phba);
3413 			if (rpi == LPFC_RPI_ALLOC_ERROR) {
3414 				lpfc_printf_vlog(ndlp->vport, KERN_INFO,
3415 						 LOG_NODE | LOG_DISCOVERY,
3416 						 "0099 RPI alloc error for "
3417 						 "ndlp x%px DID:x%06x "
3418 						 "flg:x%lx\n",
3419 						 ndlp, ndlp->nlp_DID,
3420 						 ndlp->nlp_flag);
3421 				continue;
3422 			}
3423 			ndlp->nlp_rpi = rpi;
3424 			lpfc_printf_vlog(ndlp->vport, KERN_INFO,
3425 					 LOG_NODE | LOG_DISCOVERY,
3426 					 "0009 Assign RPI x%x to ndlp x%px "
3427 					 "DID:x%06x flg:x%lx\n",
3428 					 ndlp->nlp_rpi, ndlp, ndlp->nlp_DID,
3429 					 ndlp->nlp_flag);
3430 		}
3431 	}
3432 	lpfc_destroy_vport_work_array(phba, vports);
3433 }
3434 
3435 /**
3436  * lpfc_create_expedite_pool - create expedite pool
3437  * @phba: pointer to lpfc hba data structure.
3438  *
3439  * This routine moves a batch of XRIs from lpfc_io_buf_list_put of HWQ 0
3440  * to expedite pool. Mark them as expedite.
3441  **/
3442 static void lpfc_create_expedite_pool(struct lpfc_hba *phba)
3443 {
3444 	struct lpfc_sli4_hdw_queue *qp;
3445 	struct lpfc_io_buf *lpfc_ncmd;
3446 	struct lpfc_io_buf *lpfc_ncmd_next;
3447 	struct lpfc_epd_pool *epd_pool;
3448 	unsigned long iflag;
3449 
3450 	epd_pool = &phba->epd_pool;
3451 	qp = &phba->sli4_hba.hdwq[0];
3452 
3453 	spin_lock_init(&epd_pool->lock);
3454 	spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3455 	spin_lock(&epd_pool->lock);
3456 	INIT_LIST_HEAD(&epd_pool->list);
3457 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3458 				 &qp->lpfc_io_buf_list_put, list) {
3459 		list_move_tail(&lpfc_ncmd->list, &epd_pool->list);
3460 		lpfc_ncmd->expedite = true;
3461 		qp->put_io_bufs--;
3462 		epd_pool->count++;
3463 		if (epd_pool->count >= XRI_BATCH)
3464 			break;
3465 	}
3466 	spin_unlock(&epd_pool->lock);
3467 	spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3468 }
3469 
3470 /**
3471  * lpfc_destroy_expedite_pool - destroy expedite pool
3472  * @phba: pointer to lpfc hba data structure.
3473  *
3474  * This routine returns XRIs from expedite pool to lpfc_io_buf_list_put
3475  * of HWQ 0. Clear the mark.
3476  **/
3477 static void lpfc_destroy_expedite_pool(struct lpfc_hba *phba)
3478 {
3479 	struct lpfc_sli4_hdw_queue *qp;
3480 	struct lpfc_io_buf *lpfc_ncmd;
3481 	struct lpfc_io_buf *lpfc_ncmd_next;
3482 	struct lpfc_epd_pool *epd_pool;
3483 	unsigned long iflag;
3484 
3485 	epd_pool = &phba->epd_pool;
3486 	qp = &phba->sli4_hba.hdwq[0];
3487 
3488 	spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3489 	spin_lock(&epd_pool->lock);
3490 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3491 				 &epd_pool->list, list) {
3492 		list_move_tail(&lpfc_ncmd->list,
3493 			       &qp->lpfc_io_buf_list_put);
3494 		lpfc_ncmd->flags = false;
3495 		qp->put_io_bufs++;
3496 		epd_pool->count--;
3497 	}
3498 	spin_unlock(&epd_pool->lock);
3499 	spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3500 }
3501 
3502 /**
3503  * lpfc_create_multixri_pools - create multi-XRI pools
3504  * @phba: pointer to lpfc hba data structure.
3505  *
3506  * This routine initialize public, private per HWQ. Then, move XRIs from
3507  * lpfc_io_buf_list_put to public pool. High and low watermark are also
3508  * Initialized.
3509  **/
3510 void lpfc_create_multixri_pools(struct lpfc_hba *phba)
3511 {
3512 	u32 i, j;
3513 	u32 hwq_count;
3514 	u32 count_per_hwq;
3515 	struct lpfc_io_buf *lpfc_ncmd;
3516 	struct lpfc_io_buf *lpfc_ncmd_next;
3517 	unsigned long iflag;
3518 	struct lpfc_sli4_hdw_queue *qp;
3519 	struct lpfc_multixri_pool *multixri_pool;
3520 	struct lpfc_pbl_pool *pbl_pool;
3521 	struct lpfc_pvt_pool *pvt_pool;
3522 
3523 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3524 			"1234 num_hdw_queue=%d num_present_cpu=%d common_xri_cnt=%d\n",
3525 			phba->cfg_hdw_queue, phba->sli4_hba.num_present_cpu,
3526 			phba->sli4_hba.io_xri_cnt);
3527 
3528 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
3529 		lpfc_create_expedite_pool(phba);
3530 
3531 	hwq_count = phba->cfg_hdw_queue;
3532 	count_per_hwq = phba->sli4_hba.io_xri_cnt / hwq_count;
3533 
3534 	for (i = 0; i < hwq_count; i++) {
3535 		multixri_pool = kzalloc(sizeof(*multixri_pool), GFP_KERNEL);
3536 
3537 		if (!multixri_pool) {
3538 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3539 					"1238 Failed to allocate memory for "
3540 					"multixri_pool\n");
3541 
3542 			if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
3543 				lpfc_destroy_expedite_pool(phba);
3544 
3545 			j = 0;
3546 			while (j < i) {
3547 				qp = &phba->sli4_hba.hdwq[j];
3548 				kfree(qp->p_multixri_pool);
3549 				j++;
3550 			}
3551 			phba->cfg_xri_rebalancing = 0;
3552 			return;
3553 		}
3554 
3555 		qp = &phba->sli4_hba.hdwq[i];
3556 		qp->p_multixri_pool = multixri_pool;
3557 
3558 		multixri_pool->xri_limit = count_per_hwq;
3559 		multixri_pool->rrb_next_hwqid = i;
3560 
3561 		/* Deal with public free xri pool */
3562 		pbl_pool = &multixri_pool->pbl_pool;
3563 		spin_lock_init(&pbl_pool->lock);
3564 		spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3565 		spin_lock(&pbl_pool->lock);
3566 		INIT_LIST_HEAD(&pbl_pool->list);
3567 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3568 					 &qp->lpfc_io_buf_list_put, list) {
3569 			list_move_tail(&lpfc_ncmd->list, &pbl_pool->list);
3570 			qp->put_io_bufs--;
3571 			pbl_pool->count++;
3572 		}
3573 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3574 				"1235 Moved %d buffers from PUT list over to pbl_pool[%d]\n",
3575 				pbl_pool->count, i);
3576 		spin_unlock(&pbl_pool->lock);
3577 		spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3578 
3579 		/* Deal with private free xri pool */
3580 		pvt_pool = &multixri_pool->pvt_pool;
3581 		pvt_pool->high_watermark = multixri_pool->xri_limit / 2;
3582 		pvt_pool->low_watermark = XRI_BATCH;
3583 		spin_lock_init(&pvt_pool->lock);
3584 		spin_lock_irqsave(&pvt_pool->lock, iflag);
3585 		INIT_LIST_HEAD(&pvt_pool->list);
3586 		pvt_pool->count = 0;
3587 		spin_unlock_irqrestore(&pvt_pool->lock, iflag);
3588 	}
3589 }
3590 
3591 /**
3592  * lpfc_destroy_multixri_pools - destroy multi-XRI pools
3593  * @phba: pointer to lpfc hba data structure.
3594  *
3595  * This routine returns XRIs from public/private to lpfc_io_buf_list_put.
3596  **/
3597 static void lpfc_destroy_multixri_pools(struct lpfc_hba *phba)
3598 {
3599 	u32 i;
3600 	u32 hwq_count;
3601 	struct lpfc_io_buf *lpfc_ncmd;
3602 	struct lpfc_io_buf *lpfc_ncmd_next;
3603 	unsigned long iflag;
3604 	struct lpfc_sli4_hdw_queue *qp;
3605 	struct lpfc_multixri_pool *multixri_pool;
3606 	struct lpfc_pbl_pool *pbl_pool;
3607 	struct lpfc_pvt_pool *pvt_pool;
3608 
3609 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
3610 		lpfc_destroy_expedite_pool(phba);
3611 
3612 	if (!test_bit(FC_UNLOADING, &phba->pport->load_flag))
3613 		lpfc_sli_flush_io_rings(phba);
3614 
3615 	hwq_count = phba->cfg_hdw_queue;
3616 
3617 	for (i = 0; i < hwq_count; i++) {
3618 		qp = &phba->sli4_hba.hdwq[i];
3619 		multixri_pool = qp->p_multixri_pool;
3620 		if (!multixri_pool)
3621 			continue;
3622 
3623 		qp->p_multixri_pool = NULL;
3624 
3625 		spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3626 
3627 		/* Deal with public free xri pool */
3628 		pbl_pool = &multixri_pool->pbl_pool;
3629 		spin_lock(&pbl_pool->lock);
3630 
3631 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3632 				"1236 Moving %d buffers from pbl_pool[%d] TO PUT list\n",
3633 				pbl_pool->count, i);
3634 
3635 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3636 					 &pbl_pool->list, list) {
3637 			list_move_tail(&lpfc_ncmd->list,
3638 				       &qp->lpfc_io_buf_list_put);
3639 			qp->put_io_bufs++;
3640 			pbl_pool->count--;
3641 		}
3642 
3643 		INIT_LIST_HEAD(&pbl_pool->list);
3644 		pbl_pool->count = 0;
3645 
3646 		spin_unlock(&pbl_pool->lock);
3647 
3648 		/* Deal with private free xri pool */
3649 		pvt_pool = &multixri_pool->pvt_pool;
3650 		spin_lock(&pvt_pool->lock);
3651 
3652 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3653 				"1237 Moving %d buffers from pvt_pool[%d] TO PUT list\n",
3654 				pvt_pool->count, i);
3655 
3656 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3657 					 &pvt_pool->list, list) {
3658 			list_move_tail(&lpfc_ncmd->list,
3659 				       &qp->lpfc_io_buf_list_put);
3660 			qp->put_io_bufs++;
3661 			pvt_pool->count--;
3662 		}
3663 
3664 		INIT_LIST_HEAD(&pvt_pool->list);
3665 		pvt_pool->count = 0;
3666 
3667 		spin_unlock(&pvt_pool->lock);
3668 		spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3669 
3670 		kfree(multixri_pool);
3671 	}
3672 }
3673 
3674 /**
3675  * lpfc_online - Initialize and bring a HBA online
3676  * @phba: pointer to lpfc hba data structure.
3677  *
3678  * This routine initializes the HBA and brings a HBA online. During this
3679  * process, the management interface is blocked to prevent user space access
3680  * to the HBA interfering with the driver initialization.
3681  *
3682  * Return codes
3683  *   0 - successful
3684  *   1 - failed
3685  **/
3686 int
3687 lpfc_online(struct lpfc_hba *phba)
3688 {
3689 	struct lpfc_vport *vport;
3690 	struct lpfc_vport **vports;
3691 	int i, error = 0;
3692 	bool vpis_cleared = false;
3693 
3694 	if (!phba)
3695 		return 0;
3696 	vport = phba->pport;
3697 
3698 	if (!test_bit(FC_OFFLINE_MODE, &vport->fc_flag))
3699 		return 0;
3700 
3701 	lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
3702 			"0458 Bring Adapter online\n");
3703 
3704 	lpfc_block_mgmt_io(phba, LPFC_MBX_WAIT);
3705 
3706 	if (phba->sli_rev == LPFC_SLI_REV4) {
3707 		if (lpfc_sli4_hba_setup(phba)) { /* Initialize SLI4 HBA */
3708 			lpfc_unblock_mgmt_io(phba);
3709 			return 1;
3710 		}
3711 		spin_lock_irq(&phba->hbalock);
3712 		if (!phba->sli4_hba.max_cfg_param.vpi_used)
3713 			vpis_cleared = true;
3714 		spin_unlock_irq(&phba->hbalock);
3715 
3716 		/* Reestablish the local initiator port.
3717 		 * The offline process destroyed the previous lport.
3718 		 */
3719 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME &&
3720 				!phba->nvmet_support) {
3721 			error = lpfc_nvme_create_localport(phba->pport);
3722 			if (error)
3723 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3724 					"6132 NVME restore reg failed "
3725 					"on nvmei error x%x\n", error);
3726 		}
3727 	} else {
3728 		lpfc_sli_queue_init(phba);
3729 		if (lpfc_sli_hba_setup(phba)) {	/* Initialize SLI2/SLI3 HBA */
3730 			lpfc_unblock_mgmt_io(phba);
3731 			return 1;
3732 		}
3733 	}
3734 
3735 	vports = lpfc_create_vport_work_array(phba);
3736 	if (vports != NULL) {
3737 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3738 			clear_bit(FC_OFFLINE_MODE, &vports[i]->fc_flag);
3739 			if (phba->sli3_options & LPFC_SLI3_NPIV_ENABLED)
3740 				set_bit(FC_VPORT_NEEDS_REG_VPI,
3741 					&vports[i]->fc_flag);
3742 			if (phba->sli_rev == LPFC_SLI_REV4) {
3743 				set_bit(FC_VPORT_NEEDS_INIT_VPI,
3744 					&vports[i]->fc_flag);
3745 				if ((vpis_cleared) &&
3746 				    (vports[i]->port_type !=
3747 					LPFC_PHYSICAL_PORT))
3748 					vports[i]->vpi = 0;
3749 			}
3750 		}
3751 	}
3752 	lpfc_destroy_vport_work_array(phba, vports);
3753 
3754 	if (phba->cfg_xri_rebalancing)
3755 		lpfc_create_multixri_pools(phba);
3756 
3757 	lpfc_cpuhp_add(phba);
3758 
3759 	lpfc_unblock_mgmt_io(phba);
3760 	return 0;
3761 }
3762 
3763 /**
3764  * lpfc_unblock_mgmt_io - Mark a HBA's management interface to be not blocked
3765  * @phba: pointer to lpfc hba data structure.
3766  *
3767  * This routine marks a HBA's management interface as not blocked. Once the
3768  * HBA's management interface is marked as not blocked, all the user space
3769  * access to the HBA, whether they are from sysfs interface or libdfc
3770  * interface will be allowed. The HBA is set to block the management interface
3771  * when the driver prepares the HBA interface for online or offline and then
3772  * set to unblock the management interface afterwards.
3773  **/
3774 void
3775 lpfc_unblock_mgmt_io(struct lpfc_hba * phba)
3776 {
3777 	unsigned long iflag;
3778 
3779 	spin_lock_irqsave(&phba->hbalock, iflag);
3780 	phba->sli.sli_flag &= ~LPFC_BLOCK_MGMT_IO;
3781 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3782 }
3783 
3784 /**
3785  * lpfc_offline_prep - Prepare a HBA to be brought offline
3786  * @phba: pointer to lpfc hba data structure.
3787  * @mbx_action: flag for mailbox shutdown action.
3788  *
3789  * This routine is invoked to prepare a HBA to be brought offline. It performs
3790  * unregistration login to all the nodes on all vports and flushes the mailbox
3791  * queue to make it ready to be brought offline.
3792  **/
3793 void
3794 lpfc_offline_prep(struct lpfc_hba *phba, int mbx_action)
3795 {
3796 	struct lpfc_vport *vport = phba->pport;
3797 	struct lpfc_nodelist  *ndlp, *next_ndlp;
3798 	struct lpfc_vport **vports;
3799 	struct Scsi_Host *shost;
3800 	int i;
3801 	int offline;
3802 	bool hba_pci_err;
3803 
3804 	if (test_bit(FC_OFFLINE_MODE, &vport->fc_flag))
3805 		return;
3806 
3807 	lpfc_block_mgmt_io(phba, mbx_action);
3808 
3809 	lpfc_linkdown(phba);
3810 
3811 	offline =  pci_channel_offline(phba->pcidev);
3812 	hba_pci_err = test_bit(HBA_PCI_ERR, &phba->bit_flags);
3813 
3814 	/* Issue an unreg_login to all nodes on all vports */
3815 	vports = lpfc_create_vport_work_array(phba);
3816 	if (vports != NULL) {
3817 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3818 			if (test_bit(FC_UNLOADING, &vports[i]->load_flag))
3819 				continue;
3820 			shost = lpfc_shost_from_vport(vports[i]);
3821 			spin_lock_irq(shost->host_lock);
3822 			vports[i]->vpi_state &= ~LPFC_VPI_REGISTERED;
3823 			spin_unlock_irq(shost->host_lock);
3824 			set_bit(FC_VPORT_NEEDS_REG_VPI, &vports[i]->fc_flag);
3825 			clear_bit(FC_VFI_REGISTERED, &vports[i]->fc_flag);
3826 
3827 			list_for_each_entry_safe(ndlp, next_ndlp,
3828 						 &vports[i]->fc_nodes,
3829 						 nlp_listp) {
3830 
3831 				clear_bit(NLP_NPR_ADISC, &ndlp->nlp_flag);
3832 				if (offline || hba_pci_err) {
3833 					clear_bit(NLP_UNREG_INP,
3834 						  &ndlp->nlp_flag);
3835 					clear_bit(NLP_RPI_REGISTERED,
3836 						  &ndlp->nlp_flag);
3837 				}
3838 
3839 				if (ndlp->nlp_type & NLP_FABRIC) {
3840 					lpfc_disc_state_machine(vports[i], ndlp,
3841 						NULL, NLP_EVT_DEVICE_RECOVERY);
3842 
3843 					/* Don't remove the node unless the node
3844 					 * has been unregistered with the
3845 					 * transport, and we're not in recovery
3846 					 * before dev_loss_tmo triggered.
3847 					 * Otherwise, let dev_loss take care of
3848 					 * the node.
3849 					 */
3850 					if (!(ndlp->save_flags &
3851 					      NLP_IN_RECOV_POST_DEV_LOSS) &&
3852 					    !(ndlp->fc4_xpt_flags &
3853 					      (NVME_XPT_REGD | SCSI_XPT_REGD)))
3854 						lpfc_disc_state_machine
3855 							(vports[i], ndlp,
3856 							 NULL,
3857 							 NLP_EVT_DEVICE_RM);
3858 				}
3859 			}
3860 		}
3861 	}
3862 	lpfc_destroy_vport_work_array(phba, vports);
3863 
3864 	lpfc_sli_mbox_sys_shutdown(phba, mbx_action);
3865 
3866 	if (phba->wq)
3867 		flush_workqueue(phba->wq);
3868 }
3869 
3870 /**
3871  * lpfc_offline - Bring a HBA offline
3872  * @phba: pointer to lpfc hba data structure.
3873  *
3874  * This routine actually brings a HBA offline. It stops all the timers
3875  * associated with the HBA, brings down the SLI layer, and eventually
3876  * marks the HBA as in offline state for the upper layer protocol.
3877  **/
3878 void
3879 lpfc_offline(struct lpfc_hba *phba)
3880 {
3881 	struct Scsi_Host  *shost;
3882 	struct lpfc_vport **vports;
3883 	int i;
3884 
3885 	if (test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag))
3886 		return;
3887 
3888 	/* stop port and all timers associated with this hba */
3889 	lpfc_stop_port(phba);
3890 
3891 	/* Tear down the local and target port registrations.  The
3892 	 * nvme transports need to cleanup.
3893 	 */
3894 	lpfc_nvmet_destroy_targetport(phba);
3895 	lpfc_nvme_destroy_localport(phba->pport);
3896 
3897 	vports = lpfc_create_vport_work_array(phba);
3898 	if (vports != NULL)
3899 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++)
3900 			lpfc_stop_vport_timers(vports[i]);
3901 	lpfc_destroy_vport_work_array(phba, vports);
3902 	lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
3903 			"0460 Bring Adapter offline\n");
3904 	/* Bring down the SLI Layer and cleanup.  The HBA is offline
3905 	   now.  */
3906 	lpfc_sli_hba_down(phba);
3907 	spin_lock_irq(&phba->hbalock);
3908 	phba->work_ha = 0;
3909 	spin_unlock_irq(&phba->hbalock);
3910 	vports = lpfc_create_vport_work_array(phba);
3911 	if (vports != NULL)
3912 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3913 			shost = lpfc_shost_from_vport(vports[i]);
3914 			spin_lock_irq(shost->host_lock);
3915 			vports[i]->work_port_events = 0;
3916 			spin_unlock_irq(shost->host_lock);
3917 			set_bit(FC_OFFLINE_MODE, &vports[i]->fc_flag);
3918 		}
3919 	lpfc_destroy_vport_work_array(phba, vports);
3920 	/* If OFFLINE flag is clear (i.e. unloading), cpuhp removal is handled
3921 	 * in hba_unset
3922 	 */
3923 	if (test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag))
3924 		__lpfc_cpuhp_remove(phba);
3925 
3926 	if (phba->cfg_xri_rebalancing)
3927 		lpfc_destroy_multixri_pools(phba);
3928 }
3929 
3930 /**
3931  * lpfc_scsi_free - Free all the SCSI buffers and IOCBs from driver lists
3932  * @phba: pointer to lpfc hba data structure.
3933  *
3934  * This routine is to free all the SCSI buffers and IOCBs from the driver
3935  * list back to kernel. It is called from lpfc_pci_remove_one to free
3936  * the internal resources before the device is removed from the system.
3937  **/
3938 static void
3939 lpfc_scsi_free(struct lpfc_hba *phba)
3940 {
3941 	struct lpfc_io_buf *sb, *sb_next;
3942 
3943 	if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP))
3944 		return;
3945 
3946 	spin_lock_irq(&phba->hbalock);
3947 
3948 	/* Release all the lpfc_scsi_bufs maintained by this host. */
3949 
3950 	spin_lock(&phba->scsi_buf_list_put_lock);
3951 	list_for_each_entry_safe(sb, sb_next, &phba->lpfc_scsi_buf_list_put,
3952 				 list) {
3953 		list_del(&sb->list);
3954 		dma_pool_free(phba->lpfc_sg_dma_buf_pool, sb->data,
3955 			      sb->dma_handle);
3956 		kfree(sb);
3957 		phba->total_scsi_bufs--;
3958 	}
3959 	spin_unlock(&phba->scsi_buf_list_put_lock);
3960 
3961 	spin_lock(&phba->scsi_buf_list_get_lock);
3962 	list_for_each_entry_safe(sb, sb_next, &phba->lpfc_scsi_buf_list_get,
3963 				 list) {
3964 		list_del(&sb->list);
3965 		dma_pool_free(phba->lpfc_sg_dma_buf_pool, sb->data,
3966 			      sb->dma_handle);
3967 		kfree(sb);
3968 		phba->total_scsi_bufs--;
3969 	}
3970 	spin_unlock(&phba->scsi_buf_list_get_lock);
3971 	spin_unlock_irq(&phba->hbalock);
3972 }
3973 
3974 /**
3975  * lpfc_io_free - Free all the IO buffers and IOCBs from driver lists
3976  * @phba: pointer to lpfc hba data structure.
3977  *
3978  * This routine is to free all the IO buffers and IOCBs from the driver
3979  * list back to kernel. It is called from lpfc_pci_remove_one to free
3980  * the internal resources before the device is removed from the system.
3981  **/
3982 void
3983 lpfc_io_free(struct lpfc_hba *phba)
3984 {
3985 	struct lpfc_io_buf *lpfc_ncmd, *lpfc_ncmd_next;
3986 	struct lpfc_sli4_hdw_queue *qp;
3987 	int idx;
3988 
3989 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
3990 		qp = &phba->sli4_hba.hdwq[idx];
3991 		/* Release all the lpfc_nvme_bufs maintained by this host. */
3992 		spin_lock(&qp->io_buf_list_put_lock);
3993 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3994 					 &qp->lpfc_io_buf_list_put,
3995 					 list) {
3996 			list_del(&lpfc_ncmd->list);
3997 			qp->put_io_bufs--;
3998 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
3999 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4000 			if (phba->cfg_xpsgl && !phba->nvmet_support)
4001 				lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
4002 			lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
4003 			kfree(lpfc_ncmd);
4004 			qp->total_io_bufs--;
4005 		}
4006 		spin_unlock(&qp->io_buf_list_put_lock);
4007 
4008 		spin_lock(&qp->io_buf_list_get_lock);
4009 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
4010 					 &qp->lpfc_io_buf_list_get,
4011 					 list) {
4012 			list_del(&lpfc_ncmd->list);
4013 			qp->get_io_bufs--;
4014 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4015 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4016 			if (phba->cfg_xpsgl && !phba->nvmet_support)
4017 				lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
4018 			lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
4019 			kfree(lpfc_ncmd);
4020 			qp->total_io_bufs--;
4021 		}
4022 		spin_unlock(&qp->io_buf_list_get_lock);
4023 	}
4024 }
4025 
4026 /**
4027  * lpfc_sli4_els_sgl_update - update ELS xri-sgl sizing and mapping
4028  * @phba: pointer to lpfc hba data structure.
4029  *
4030  * This routine first calculates the sizes of the current els and allocated
4031  * scsi sgl lists, and then goes through all sgls to updates the physical
4032  * XRIs assigned due to port function reset. During port initialization, the
4033  * current els and allocated scsi sgl lists are 0s.
4034  *
4035  * Return codes
4036  *   0 - successful (for now, it always returns 0)
4037  **/
4038 int
4039 lpfc_sli4_els_sgl_update(struct lpfc_hba *phba)
4040 {
4041 	struct lpfc_sglq *sglq_entry = NULL, *sglq_entry_next = NULL;
4042 	uint16_t i, lxri, xri_cnt, els_xri_cnt;
4043 	LIST_HEAD(els_sgl_list);
4044 	int rc;
4045 
4046 	/*
4047 	 * update on pci function's els xri-sgl list
4048 	 */
4049 	els_xri_cnt = lpfc_sli4_get_els_iocb_cnt(phba);
4050 
4051 	if (els_xri_cnt > phba->sli4_hba.els_xri_cnt) {
4052 		/* els xri-sgl expanded */
4053 		xri_cnt = els_xri_cnt - phba->sli4_hba.els_xri_cnt;
4054 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4055 				"3157 ELS xri-sgl count increased from "
4056 				"%d to %d\n", phba->sli4_hba.els_xri_cnt,
4057 				els_xri_cnt);
4058 		/* allocate the additional els sgls */
4059 		for (i = 0; i < xri_cnt; i++) {
4060 			sglq_entry = kzalloc(sizeof(struct lpfc_sglq),
4061 					     GFP_KERNEL);
4062 			if (sglq_entry == NULL) {
4063 				lpfc_printf_log(phba, KERN_ERR,
4064 						LOG_TRACE_EVENT,
4065 						"2562 Failure to allocate an "
4066 						"ELS sgl entry:%d\n", i);
4067 				rc = -ENOMEM;
4068 				goto out_free_mem;
4069 			}
4070 			sglq_entry->buff_type = GEN_BUFF_TYPE;
4071 			sglq_entry->virt = lpfc_mbuf_alloc(phba, 0,
4072 							   &sglq_entry->phys);
4073 			if (sglq_entry->virt == NULL) {
4074 				kfree(sglq_entry);
4075 				lpfc_printf_log(phba, KERN_ERR,
4076 						LOG_TRACE_EVENT,
4077 						"2563 Failure to allocate an "
4078 						"ELS mbuf:%d\n", i);
4079 				rc = -ENOMEM;
4080 				goto out_free_mem;
4081 			}
4082 			sglq_entry->sgl = sglq_entry->virt;
4083 			memset(sglq_entry->sgl, 0, LPFC_BPL_SIZE);
4084 			sglq_entry->state = SGL_FREED;
4085 			list_add_tail(&sglq_entry->list, &els_sgl_list);
4086 		}
4087 		spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
4088 		list_splice_init(&els_sgl_list,
4089 				 &phba->sli4_hba.lpfc_els_sgl_list);
4090 		spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
4091 	} else if (els_xri_cnt < phba->sli4_hba.els_xri_cnt) {
4092 		/* els xri-sgl shrinked */
4093 		xri_cnt = phba->sli4_hba.els_xri_cnt - els_xri_cnt;
4094 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4095 				"3158 ELS xri-sgl count decreased from "
4096 				"%d to %d\n", phba->sli4_hba.els_xri_cnt,
4097 				els_xri_cnt);
4098 		spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
4099 		list_splice_init(&phba->sli4_hba.lpfc_els_sgl_list,
4100 				 &els_sgl_list);
4101 		/* release extra els sgls from list */
4102 		for (i = 0; i < xri_cnt; i++) {
4103 			list_remove_head(&els_sgl_list,
4104 					 sglq_entry, struct lpfc_sglq, list);
4105 			if (sglq_entry) {
4106 				__lpfc_mbuf_free(phba, sglq_entry->virt,
4107 						 sglq_entry->phys);
4108 				kfree(sglq_entry);
4109 			}
4110 		}
4111 		list_splice_init(&els_sgl_list,
4112 				 &phba->sli4_hba.lpfc_els_sgl_list);
4113 		spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
4114 	} else
4115 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4116 				"3163 ELS xri-sgl count unchanged: %d\n",
4117 				els_xri_cnt);
4118 	phba->sli4_hba.els_xri_cnt = els_xri_cnt;
4119 
4120 	/* update xris to els sgls on the list */
4121 	sglq_entry = NULL;
4122 	sglq_entry_next = NULL;
4123 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
4124 				 &phba->sli4_hba.lpfc_els_sgl_list, list) {
4125 		lxri = lpfc_sli4_next_xritag(phba);
4126 		if (lxri == NO_XRI) {
4127 			lpfc_printf_log(phba, KERN_ERR,
4128 					LOG_TRACE_EVENT,
4129 					"2400 Failed to allocate xri for "
4130 					"ELS sgl\n");
4131 			rc = -ENOMEM;
4132 			goto out_free_mem;
4133 		}
4134 		sglq_entry->sli4_lxritag = lxri;
4135 		sglq_entry->sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4136 	}
4137 	return 0;
4138 
4139 out_free_mem:
4140 	lpfc_free_els_sgl_list(phba);
4141 	return rc;
4142 }
4143 
4144 /**
4145  * lpfc_sli4_nvmet_sgl_update - update xri-sgl sizing and mapping
4146  * @phba: pointer to lpfc hba data structure.
4147  *
4148  * This routine first calculates the sizes of the current els and allocated
4149  * scsi sgl lists, and then goes through all sgls to updates the physical
4150  * XRIs assigned due to port function reset. During port initialization, the
4151  * current els and allocated scsi sgl lists are 0s.
4152  *
4153  * Return codes
4154  *   0 - successful (for now, it always returns 0)
4155  **/
4156 int
4157 lpfc_sli4_nvmet_sgl_update(struct lpfc_hba *phba)
4158 {
4159 	struct lpfc_sglq *sglq_entry = NULL, *sglq_entry_next = NULL;
4160 	uint16_t i, lxri, xri_cnt, els_xri_cnt;
4161 	uint16_t nvmet_xri_cnt;
4162 	LIST_HEAD(nvmet_sgl_list);
4163 	int rc;
4164 
4165 	/*
4166 	 * update on pci function's nvmet xri-sgl list
4167 	 */
4168 	els_xri_cnt = lpfc_sli4_get_els_iocb_cnt(phba);
4169 
4170 	/* For NVMET, ALL remaining XRIs are dedicated for IO processing */
4171 	nvmet_xri_cnt = phba->sli4_hba.max_cfg_param.max_xri - els_xri_cnt;
4172 	if (nvmet_xri_cnt > phba->sli4_hba.nvmet_xri_cnt) {
4173 		/* els xri-sgl expanded */
4174 		xri_cnt = nvmet_xri_cnt - phba->sli4_hba.nvmet_xri_cnt;
4175 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4176 				"6302 NVMET xri-sgl cnt grew from %d to %d\n",
4177 				phba->sli4_hba.nvmet_xri_cnt, nvmet_xri_cnt);
4178 		/* allocate the additional nvmet sgls */
4179 		for (i = 0; i < xri_cnt; i++) {
4180 			sglq_entry = kzalloc(sizeof(struct lpfc_sglq),
4181 					     GFP_KERNEL);
4182 			if (sglq_entry == NULL) {
4183 				lpfc_printf_log(phba, KERN_ERR,
4184 						LOG_TRACE_EVENT,
4185 						"6303 Failure to allocate an "
4186 						"NVMET sgl entry:%d\n", i);
4187 				rc = -ENOMEM;
4188 				goto out_free_mem;
4189 			}
4190 			sglq_entry->buff_type = NVMET_BUFF_TYPE;
4191 			sglq_entry->virt = lpfc_nvmet_buf_alloc(phba, 0,
4192 							   &sglq_entry->phys);
4193 			if (sglq_entry->virt == NULL) {
4194 				kfree(sglq_entry);
4195 				lpfc_printf_log(phba, KERN_ERR,
4196 						LOG_TRACE_EVENT,
4197 						"6304 Failure to allocate an "
4198 						"NVMET buf:%d\n", i);
4199 				rc = -ENOMEM;
4200 				goto out_free_mem;
4201 			}
4202 			sglq_entry->sgl = sglq_entry->virt;
4203 			memset(sglq_entry->sgl, 0,
4204 			       phba->cfg_sg_dma_buf_size);
4205 			sglq_entry->state = SGL_FREED;
4206 			list_add_tail(&sglq_entry->list, &nvmet_sgl_list);
4207 		}
4208 		spin_lock_irq(&phba->hbalock);
4209 		spin_lock(&phba->sli4_hba.sgl_list_lock);
4210 		list_splice_init(&nvmet_sgl_list,
4211 				 &phba->sli4_hba.lpfc_nvmet_sgl_list);
4212 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
4213 		spin_unlock_irq(&phba->hbalock);
4214 	} else if (nvmet_xri_cnt < phba->sli4_hba.nvmet_xri_cnt) {
4215 		/* nvmet xri-sgl shrunk */
4216 		xri_cnt = phba->sli4_hba.nvmet_xri_cnt - nvmet_xri_cnt;
4217 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4218 				"6305 NVMET xri-sgl count decreased from "
4219 				"%d to %d\n", phba->sli4_hba.nvmet_xri_cnt,
4220 				nvmet_xri_cnt);
4221 		spin_lock_irq(&phba->hbalock);
4222 		spin_lock(&phba->sli4_hba.sgl_list_lock);
4223 		list_splice_init(&phba->sli4_hba.lpfc_nvmet_sgl_list,
4224 				 &nvmet_sgl_list);
4225 		/* release extra nvmet sgls from list */
4226 		for (i = 0; i < xri_cnt; i++) {
4227 			list_remove_head(&nvmet_sgl_list,
4228 					 sglq_entry, struct lpfc_sglq, list);
4229 			if (sglq_entry) {
4230 				lpfc_nvmet_buf_free(phba, sglq_entry->virt,
4231 						    sglq_entry->phys);
4232 				kfree(sglq_entry);
4233 			}
4234 		}
4235 		list_splice_init(&nvmet_sgl_list,
4236 				 &phba->sli4_hba.lpfc_nvmet_sgl_list);
4237 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
4238 		spin_unlock_irq(&phba->hbalock);
4239 	} else
4240 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4241 				"6306 NVMET xri-sgl count unchanged: %d\n",
4242 				nvmet_xri_cnt);
4243 	phba->sli4_hba.nvmet_xri_cnt = nvmet_xri_cnt;
4244 
4245 	/* update xris to nvmet sgls on the list */
4246 	sglq_entry = NULL;
4247 	sglq_entry_next = NULL;
4248 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
4249 				 &phba->sli4_hba.lpfc_nvmet_sgl_list, list) {
4250 		lxri = lpfc_sli4_next_xritag(phba);
4251 		if (lxri == NO_XRI) {
4252 			lpfc_printf_log(phba, KERN_ERR,
4253 					LOG_TRACE_EVENT,
4254 					"6307 Failed to allocate xri for "
4255 					"NVMET sgl\n");
4256 			rc = -ENOMEM;
4257 			goto out_free_mem;
4258 		}
4259 		sglq_entry->sli4_lxritag = lxri;
4260 		sglq_entry->sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4261 	}
4262 	return 0;
4263 
4264 out_free_mem:
4265 	lpfc_free_nvmet_sgl_list(phba);
4266 	return rc;
4267 }
4268 
4269 int
4270 lpfc_io_buf_flush(struct lpfc_hba *phba, struct list_head *cbuf)
4271 {
4272 	LIST_HEAD(blist);
4273 	struct lpfc_sli4_hdw_queue *qp;
4274 	struct lpfc_io_buf *lpfc_cmd;
4275 	struct lpfc_io_buf *iobufp, *prev_iobufp;
4276 	int idx, cnt, xri, inserted;
4277 
4278 	cnt = 0;
4279 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
4280 		qp = &phba->sli4_hba.hdwq[idx];
4281 		spin_lock_irq(&qp->io_buf_list_get_lock);
4282 		spin_lock(&qp->io_buf_list_put_lock);
4283 
4284 		/* Take everything off the get and put lists */
4285 		list_splice_init(&qp->lpfc_io_buf_list_get, &blist);
4286 		list_splice(&qp->lpfc_io_buf_list_put, &blist);
4287 		INIT_LIST_HEAD(&qp->lpfc_io_buf_list_get);
4288 		INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
4289 		cnt += qp->get_io_bufs + qp->put_io_bufs;
4290 		qp->get_io_bufs = 0;
4291 		qp->put_io_bufs = 0;
4292 		qp->total_io_bufs = 0;
4293 		spin_unlock(&qp->io_buf_list_put_lock);
4294 		spin_unlock_irq(&qp->io_buf_list_get_lock);
4295 	}
4296 
4297 	/*
4298 	 * Take IO buffers off blist and put on cbuf sorted by XRI.
4299 	 * This is because POST_SGL takes a sequential range of XRIs
4300 	 * to post to the firmware.
4301 	 */
4302 	for (idx = 0; idx < cnt; idx++) {
4303 		list_remove_head(&blist, lpfc_cmd, struct lpfc_io_buf, list);
4304 		if (!lpfc_cmd)
4305 			return cnt;
4306 		if (idx == 0) {
4307 			list_add_tail(&lpfc_cmd->list, cbuf);
4308 			continue;
4309 		}
4310 		xri = lpfc_cmd->cur_iocbq.sli4_xritag;
4311 		inserted = 0;
4312 		prev_iobufp = NULL;
4313 		list_for_each_entry(iobufp, cbuf, list) {
4314 			if (xri < iobufp->cur_iocbq.sli4_xritag) {
4315 				if (prev_iobufp)
4316 					list_add(&lpfc_cmd->list,
4317 						 &prev_iobufp->list);
4318 				else
4319 					list_add(&lpfc_cmd->list, cbuf);
4320 				inserted = 1;
4321 				break;
4322 			}
4323 			prev_iobufp = iobufp;
4324 		}
4325 		if (!inserted)
4326 			list_add_tail(&lpfc_cmd->list, cbuf);
4327 	}
4328 	return cnt;
4329 }
4330 
4331 int
4332 lpfc_io_buf_replenish(struct lpfc_hba *phba, struct list_head *cbuf)
4333 {
4334 	struct lpfc_sli4_hdw_queue *qp;
4335 	struct lpfc_io_buf *lpfc_cmd;
4336 	int idx, cnt;
4337 	unsigned long iflags;
4338 
4339 	qp = phba->sli4_hba.hdwq;
4340 	cnt = 0;
4341 	while (!list_empty(cbuf)) {
4342 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
4343 			list_remove_head(cbuf, lpfc_cmd,
4344 					 struct lpfc_io_buf, list);
4345 			if (!lpfc_cmd)
4346 				return cnt;
4347 			cnt++;
4348 			qp = &phba->sli4_hba.hdwq[idx];
4349 			lpfc_cmd->hdwq_no = idx;
4350 			lpfc_cmd->hdwq = qp;
4351 			lpfc_cmd->cur_iocbq.cmd_cmpl = NULL;
4352 			spin_lock_irqsave(&qp->io_buf_list_put_lock, iflags);
4353 			list_add_tail(&lpfc_cmd->list,
4354 				      &qp->lpfc_io_buf_list_put);
4355 			qp->put_io_bufs++;
4356 			qp->total_io_bufs++;
4357 			spin_unlock_irqrestore(&qp->io_buf_list_put_lock,
4358 					       iflags);
4359 		}
4360 	}
4361 	return cnt;
4362 }
4363 
4364 /**
4365  * lpfc_sli4_io_sgl_update - update xri-sgl sizing and mapping
4366  * @phba: pointer to lpfc hba data structure.
4367  *
4368  * This routine first calculates the sizes of the current els and allocated
4369  * scsi sgl lists, and then goes through all sgls to updates the physical
4370  * XRIs assigned due to port function reset. During port initialization, the
4371  * current els and allocated scsi sgl lists are 0s.
4372  *
4373  * Return codes
4374  *   0 - successful (for now, it always returns 0)
4375  **/
4376 int
4377 lpfc_sli4_io_sgl_update(struct lpfc_hba *phba)
4378 {
4379 	struct lpfc_io_buf *lpfc_ncmd = NULL, *lpfc_ncmd_next = NULL;
4380 	uint16_t i, lxri, els_xri_cnt;
4381 	uint16_t io_xri_cnt, io_xri_max;
4382 	LIST_HEAD(io_sgl_list);
4383 	int rc, cnt;
4384 
4385 	/*
4386 	 * update on pci function's allocated nvme xri-sgl list
4387 	 */
4388 
4389 	/* maximum number of xris available for nvme buffers */
4390 	els_xri_cnt = lpfc_sli4_get_els_iocb_cnt(phba);
4391 	io_xri_max = phba->sli4_hba.max_cfg_param.max_xri - els_xri_cnt;
4392 	phba->sli4_hba.io_xri_max = io_xri_max;
4393 
4394 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4395 			"6074 Current allocated XRI sgl count:%d, "
4396 			"maximum XRI count:%d els_xri_cnt:%d\n\n",
4397 			phba->sli4_hba.io_xri_cnt,
4398 			phba->sli4_hba.io_xri_max,
4399 			els_xri_cnt);
4400 
4401 	cnt = lpfc_io_buf_flush(phba, &io_sgl_list);
4402 
4403 	if (phba->sli4_hba.io_xri_cnt > phba->sli4_hba.io_xri_max) {
4404 		/* max nvme xri shrunk below the allocated nvme buffers */
4405 		io_xri_cnt = phba->sli4_hba.io_xri_cnt -
4406 					phba->sli4_hba.io_xri_max;
4407 		/* release the extra allocated nvme buffers */
4408 		for (i = 0; i < io_xri_cnt; i++) {
4409 			list_remove_head(&io_sgl_list, lpfc_ncmd,
4410 					 struct lpfc_io_buf, list);
4411 			if (lpfc_ncmd) {
4412 				dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4413 					      lpfc_ncmd->data,
4414 					      lpfc_ncmd->dma_handle);
4415 				kfree(lpfc_ncmd);
4416 			}
4417 		}
4418 		phba->sli4_hba.io_xri_cnt -= io_xri_cnt;
4419 	}
4420 
4421 	/* update xris associated to remaining allocated nvme buffers */
4422 	lpfc_ncmd = NULL;
4423 	lpfc_ncmd_next = NULL;
4424 	phba->sli4_hba.io_xri_cnt = cnt;
4425 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
4426 				 &io_sgl_list, list) {
4427 		lxri = lpfc_sli4_next_xritag(phba);
4428 		if (lxri == NO_XRI) {
4429 			lpfc_printf_log(phba, KERN_ERR,
4430 					LOG_TRACE_EVENT,
4431 					"6075 Failed to allocate xri for "
4432 					"nvme buffer\n");
4433 			rc = -ENOMEM;
4434 			goto out_free_mem;
4435 		}
4436 		lpfc_ncmd->cur_iocbq.sli4_lxritag = lxri;
4437 		lpfc_ncmd->cur_iocbq.sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4438 	}
4439 	cnt = lpfc_io_buf_replenish(phba, &io_sgl_list);
4440 	return 0;
4441 
4442 out_free_mem:
4443 	lpfc_io_free(phba);
4444 	return rc;
4445 }
4446 
4447 /**
4448  * lpfc_new_io_buf - IO buffer allocator for HBA with SLI4 IF spec
4449  * @phba: Pointer to lpfc hba data structure.
4450  * @num_to_alloc: The requested number of buffers to allocate.
4451  *
4452  * This routine allocates nvme buffers for device with SLI-4 interface spec,
4453  * the nvme buffer contains all the necessary information needed to initiate
4454  * an I/O. After allocating up to @num_to_allocate IO buffers and put
4455  * them on a list, it post them to the port by using SGL block post.
4456  *
4457  * Return codes:
4458  *   int - number of IO buffers that were allocated and posted.
4459  *   0 = failure, less than num_to_alloc is a partial failure.
4460  **/
4461 int
4462 lpfc_new_io_buf(struct lpfc_hba *phba, int num_to_alloc)
4463 {
4464 	struct lpfc_io_buf *lpfc_ncmd;
4465 	struct lpfc_iocbq *pwqeq;
4466 	uint16_t iotag, lxri = 0;
4467 	int bcnt, num_posted;
4468 	LIST_HEAD(prep_nblist);
4469 	LIST_HEAD(post_nblist);
4470 	LIST_HEAD(nvme_nblist);
4471 
4472 	phba->sli4_hba.io_xri_cnt = 0;
4473 	for (bcnt = 0; bcnt < num_to_alloc; bcnt++) {
4474 		lpfc_ncmd = kzalloc(sizeof(*lpfc_ncmd), GFP_KERNEL);
4475 		if (!lpfc_ncmd)
4476 			break;
4477 		/*
4478 		 * Get memory from the pci pool to map the virt space to
4479 		 * pci bus space for an I/O. The DMA buffer includes the
4480 		 * number of SGE's necessary to support the sg_tablesize.
4481 		 */
4482 		lpfc_ncmd->data = dma_pool_zalloc(phba->lpfc_sg_dma_buf_pool,
4483 						  GFP_KERNEL,
4484 						  &lpfc_ncmd->dma_handle);
4485 		if (!lpfc_ncmd->data) {
4486 			kfree(lpfc_ncmd);
4487 			break;
4488 		}
4489 
4490 		if (phba->cfg_xpsgl && !phba->nvmet_support) {
4491 			INIT_LIST_HEAD(&lpfc_ncmd->dma_sgl_xtra_list);
4492 		} else {
4493 			/*
4494 			 * 4K Page alignment is CRITICAL to BlockGuard, double
4495 			 * check to be sure.
4496 			 */
4497 			if ((phba->sli3_options & LPFC_SLI3_BG_ENABLED) &&
4498 			    (((unsigned long)(lpfc_ncmd->data) &
4499 			    (unsigned long)(SLI4_PAGE_SIZE - 1)) != 0)) {
4500 				lpfc_printf_log(phba, KERN_ERR,
4501 						LOG_TRACE_EVENT,
4502 						"3369 Memory alignment err: "
4503 						"addr=%lx\n",
4504 						(unsigned long)lpfc_ncmd->data);
4505 				dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4506 					      lpfc_ncmd->data,
4507 					      lpfc_ncmd->dma_handle);
4508 				kfree(lpfc_ncmd);
4509 				break;
4510 			}
4511 		}
4512 
4513 		INIT_LIST_HEAD(&lpfc_ncmd->dma_cmd_rsp_list);
4514 
4515 		lxri = lpfc_sli4_next_xritag(phba);
4516 		if (lxri == NO_XRI) {
4517 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4518 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4519 			kfree(lpfc_ncmd);
4520 			break;
4521 		}
4522 		pwqeq = &lpfc_ncmd->cur_iocbq;
4523 
4524 		/* Allocate iotag for lpfc_ncmd->cur_iocbq. */
4525 		iotag = lpfc_sli_next_iotag(phba, pwqeq);
4526 		if (iotag == 0) {
4527 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4528 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4529 			kfree(lpfc_ncmd);
4530 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4531 					"6121 Failed to allocate IOTAG for"
4532 					" XRI:0x%x\n", lxri);
4533 			lpfc_sli4_free_xri(phba, lxri);
4534 			break;
4535 		}
4536 		pwqeq->sli4_lxritag = lxri;
4537 		pwqeq->sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4538 
4539 		/* Initialize local short-hand pointers. */
4540 		lpfc_ncmd->dma_sgl = lpfc_ncmd->data;
4541 		lpfc_ncmd->dma_phys_sgl = lpfc_ncmd->dma_handle;
4542 		lpfc_ncmd->cur_iocbq.io_buf = lpfc_ncmd;
4543 		spin_lock_init(&lpfc_ncmd->buf_lock);
4544 
4545 		/* add the nvme buffer to a post list */
4546 		list_add_tail(&lpfc_ncmd->list, &post_nblist);
4547 		phba->sli4_hba.io_xri_cnt++;
4548 	}
4549 	lpfc_printf_log(phba, KERN_INFO, LOG_NVME,
4550 			"6114 Allocate %d out of %d requested new NVME "
4551 			"buffers of size x%zu bytes\n", bcnt, num_to_alloc,
4552 			sizeof(*lpfc_ncmd));
4553 
4554 
4555 	/* post the list of nvme buffer sgls to port if available */
4556 	if (!list_empty(&post_nblist))
4557 		num_posted = lpfc_sli4_post_io_sgl_list(
4558 				phba, &post_nblist, bcnt);
4559 	else
4560 		num_posted = 0;
4561 
4562 	return num_posted;
4563 }
4564 
4565 static uint64_t
4566 lpfc_get_wwpn(struct lpfc_hba *phba)
4567 {
4568 	uint64_t wwn;
4569 	int rc;
4570 	LPFC_MBOXQ_t *mboxq;
4571 	MAILBOX_t *mb;
4572 
4573 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
4574 						GFP_KERNEL);
4575 	if (!mboxq)
4576 		return (uint64_t)-1;
4577 
4578 	/* First get WWN of HBA instance */
4579 	lpfc_read_nv(phba, mboxq);
4580 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
4581 	if (rc != MBX_SUCCESS) {
4582 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4583 				"6019 Mailbox failed , mbxCmd x%x "
4584 				"READ_NV, mbxStatus x%x\n",
4585 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
4586 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
4587 		mempool_free(mboxq, phba->mbox_mem_pool);
4588 		return (uint64_t) -1;
4589 	}
4590 	mb = &mboxq->u.mb;
4591 	memcpy(&wwn, (char *)mb->un.varRDnvp.portname, sizeof(uint64_t));
4592 	/* wwn is WWPN of HBA instance */
4593 	mempool_free(mboxq, phba->mbox_mem_pool);
4594 	if (phba->sli_rev == LPFC_SLI_REV4)
4595 		return be64_to_cpu(wwn);
4596 	else
4597 		return rol64(wwn, 32);
4598 }
4599 
4600 static unsigned short lpfc_get_sg_tablesize(struct lpfc_hba *phba)
4601 {
4602 	if (phba->sli_rev == LPFC_SLI_REV4)
4603 		if (phba->cfg_xpsgl && !phba->nvmet_support)
4604 			return LPFC_MAX_SG_TABLESIZE;
4605 		else
4606 			return phba->cfg_scsi_seg_cnt;
4607 	else
4608 		return phba->cfg_sg_seg_cnt;
4609 }
4610 
4611 /**
4612  * lpfc_vmid_res_alloc - Allocates resources for VMID
4613  * @phba: pointer to lpfc hba data structure.
4614  * @vport: pointer to vport data structure
4615  *
4616  * This routine allocated the resources needed for the VMID.
4617  *
4618  * Return codes
4619  *	0 on Success
4620  *	Non-0 on Failure
4621  */
4622 static int
4623 lpfc_vmid_res_alloc(struct lpfc_hba *phba, struct lpfc_vport *vport)
4624 {
4625 	/* VMID feature is supported only on SLI4 */
4626 	if (phba->sli_rev == LPFC_SLI_REV3) {
4627 		phba->cfg_vmid_app_header = 0;
4628 		phba->cfg_vmid_priority_tagging = 0;
4629 	}
4630 
4631 	if (lpfc_is_vmid_enabled(phba)) {
4632 		vport->vmid =
4633 		    kcalloc(phba->cfg_max_vmid, sizeof(struct lpfc_vmid),
4634 			    GFP_KERNEL);
4635 		if (!vport->vmid)
4636 			return -ENOMEM;
4637 
4638 		rwlock_init(&vport->vmid_lock);
4639 
4640 		/* Set the VMID parameters for the vport */
4641 		vport->vmid_priority_tagging = phba->cfg_vmid_priority_tagging;
4642 		vport->vmid_inactivity_timeout =
4643 		    phba->cfg_vmid_inactivity_timeout;
4644 		vport->max_vmid = phba->cfg_max_vmid;
4645 		vport->cur_vmid_cnt = 0;
4646 
4647 		vport->vmid_priority_range = bitmap_zalloc
4648 			(LPFC_VMID_MAX_PRIORITY_RANGE, GFP_KERNEL);
4649 
4650 		if (!vport->vmid_priority_range) {
4651 			kfree(vport->vmid);
4652 			return -ENOMEM;
4653 		}
4654 
4655 		hash_init(vport->hash_table);
4656 	}
4657 	return 0;
4658 }
4659 
4660 /**
4661  * lpfc_create_port - Create an FC port
4662  * @phba: pointer to lpfc hba data structure.
4663  * @instance: a unique integer ID to this FC port.
4664  * @dev: pointer to the device data structure.
4665  *
4666  * This routine creates a FC port for the upper layer protocol. The FC port
4667  * can be created on top of either a physical port or a virtual port provided
4668  * by the HBA. This routine also allocates a SCSI host data structure (shost)
4669  * and associates the FC port created before adding the shost into the SCSI
4670  * layer.
4671  *
4672  * Return codes
4673  *   @vport - pointer to the virtual N_Port data structure.
4674  *   NULL - port create failed.
4675  **/
4676 struct lpfc_vport *
4677 lpfc_create_port(struct lpfc_hba *phba, int instance, struct device *dev)
4678 {
4679 	struct lpfc_vport *vport;
4680 	struct Scsi_Host  *shost = NULL;
4681 	struct scsi_host_template *template;
4682 	int error = 0;
4683 	int i;
4684 	uint64_t wwn;
4685 	bool use_no_reset_hba = false;
4686 	int rc;
4687 	u8 if_type;
4688 
4689 	if (lpfc_no_hba_reset_cnt) {
4690 		if (phba->sli_rev < LPFC_SLI_REV4 &&
4691 		    dev == &phba->pcidev->dev) {
4692 			/* Reset the port first */
4693 			lpfc_sli_brdrestart(phba);
4694 			rc = lpfc_sli_chipset_init(phba);
4695 			if (rc)
4696 				return NULL;
4697 		}
4698 		wwn = lpfc_get_wwpn(phba);
4699 	}
4700 
4701 	for (i = 0; i < lpfc_no_hba_reset_cnt; i++) {
4702 		if (wwn == lpfc_no_hba_reset[i]) {
4703 			lpfc_printf_log(phba, KERN_ERR,
4704 					LOG_TRACE_EVENT,
4705 					"6020 Setting use_no_reset port=%llx\n",
4706 					wwn);
4707 			use_no_reset_hba = true;
4708 			break;
4709 		}
4710 	}
4711 
4712 	/* Seed template for SCSI host registration */
4713 	if (dev == &phba->pcidev->dev) {
4714 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP) {
4715 			/* Seed physical port template */
4716 			template = &lpfc_template;
4717 
4718 			if (use_no_reset_hba)
4719 				/* template is for a no reset SCSI Host */
4720 				template->eh_host_reset_handler = NULL;
4721 
4722 			/* Seed updated value of sg_tablesize */
4723 			template->sg_tablesize = lpfc_get_sg_tablesize(phba);
4724 		} else {
4725 			/* NVMET is for physical port only */
4726 			template = &lpfc_template_nvme;
4727 		}
4728 	} else {
4729 		/* Seed vport template */
4730 		template = &lpfc_vport_template;
4731 
4732 		/* Seed updated value of sg_tablesize */
4733 		template->sg_tablesize = lpfc_get_sg_tablesize(phba);
4734 	}
4735 
4736 	shost = scsi_host_alloc(template, sizeof(struct lpfc_vport));
4737 	if (!shost)
4738 		goto out;
4739 
4740 	vport = (struct lpfc_vport *) shost->hostdata;
4741 	vport->phba = phba;
4742 	set_bit(FC_LOADING, &vport->load_flag);
4743 	set_bit(FC_VPORT_NEEDS_REG_VPI, &vport->fc_flag);
4744 	vport->fc_rscn_flush = 0;
4745 	atomic_set(&vport->fc_plogi_cnt, 0);
4746 	atomic_set(&vport->fc_adisc_cnt, 0);
4747 	atomic_set(&vport->fc_reglogin_cnt, 0);
4748 	atomic_set(&vport->fc_prli_cnt, 0);
4749 	atomic_set(&vport->fc_unmap_cnt, 0);
4750 	atomic_set(&vport->fc_map_cnt, 0);
4751 	atomic_set(&vport->fc_npr_cnt, 0);
4752 	atomic_set(&vport->fc_unused_cnt, 0);
4753 	lpfc_get_vport_cfgparam(vport);
4754 
4755 	/* Adjust value in vport */
4756 	vport->cfg_enable_fc4_type = phba->cfg_enable_fc4_type;
4757 
4758 	shost->unique_id = instance;
4759 	shost->max_id = LPFC_MAX_TARGET;
4760 	shost->max_lun = vport->cfg_max_luns;
4761 	shost->this_id = -1;
4762 
4763 	/* Set max_cmd_len applicable to ASIC support */
4764 	if (phba->sli_rev == LPFC_SLI_REV4) {
4765 		if_type = bf_get(lpfc_sli_intf_if_type,
4766 				 &phba->sli4_hba.sli_intf);
4767 		switch (if_type) {
4768 		case LPFC_SLI_INTF_IF_TYPE_2:
4769 			fallthrough;
4770 		case LPFC_SLI_INTF_IF_TYPE_6:
4771 			shost->max_cmd_len = LPFC_FCP_CDB_LEN_32;
4772 			break;
4773 		default:
4774 			shost->max_cmd_len = LPFC_FCP_CDB_LEN;
4775 			break;
4776 		}
4777 	} else {
4778 		shost->max_cmd_len = LPFC_FCP_CDB_LEN;
4779 	}
4780 
4781 	if (phba->sli_rev == LPFC_SLI_REV4) {
4782 		if (!phba->cfg_fcp_mq_threshold ||
4783 		    phba->cfg_fcp_mq_threshold > phba->cfg_hdw_queue)
4784 			phba->cfg_fcp_mq_threshold = phba->cfg_hdw_queue;
4785 
4786 		shost->nr_hw_queues = min_t(int, 2 * num_possible_nodes(),
4787 					    phba->cfg_fcp_mq_threshold);
4788 
4789 		shost->dma_boundary =
4790 			phba->sli4_hba.pc_sli4_params.sge_supp_len-1;
4791 	} else
4792 		/* SLI-3 has a limited number of hardware queues (3),
4793 		 * thus there is only one for FCP processing.
4794 		 */
4795 		shost->nr_hw_queues = 1;
4796 
4797 	/*
4798 	 * Set initial can_queue value since 0 is no longer supported and
4799 	 * scsi_add_host will fail. This will be adjusted later based on the
4800 	 * max xri value determined in hba setup.
4801 	 */
4802 	shost->can_queue = phba->cfg_hba_queue_depth - 10;
4803 	if (dev != &phba->pcidev->dev) {
4804 		shost->transportt = lpfc_vport_transport_template;
4805 		vport->port_type = LPFC_NPIV_PORT;
4806 	} else {
4807 		shost->transportt = lpfc_transport_template;
4808 		vport->port_type = LPFC_PHYSICAL_PORT;
4809 	}
4810 
4811 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP,
4812 			"9081 CreatePort TMPLATE type %x TBLsize %d "
4813 			"SEGcnt %d/%d\n",
4814 			vport->port_type, shost->sg_tablesize,
4815 			phba->cfg_scsi_seg_cnt, phba->cfg_sg_seg_cnt);
4816 
4817 	/* Allocate the resources for VMID */
4818 	rc = lpfc_vmid_res_alloc(phba, vport);
4819 
4820 	if (rc)
4821 		goto out_put_shost;
4822 
4823 	/* Initialize all internally managed lists. */
4824 	INIT_LIST_HEAD(&vport->fc_nodes);
4825 	spin_lock_init(&vport->fc_nodes_list_lock);
4826 	INIT_LIST_HEAD(&vport->rcv_buffer_list);
4827 	spin_lock_init(&vport->work_port_lock);
4828 
4829 	timer_setup(&vport->fc_disctmo, lpfc_disc_timeout, 0);
4830 
4831 	timer_setup(&vport->els_tmofunc, lpfc_els_timeout, 0);
4832 
4833 	timer_setup(&vport->delayed_disc_tmo, lpfc_delayed_disc_tmo, 0);
4834 
4835 	if (phba->sli3_options & LPFC_SLI3_BG_ENABLED)
4836 		lpfc_setup_bg(phba, shost);
4837 
4838 	error = scsi_add_host_with_dma(shost, dev, &phba->pcidev->dev);
4839 	if (error)
4840 		goto out_free_vmid;
4841 
4842 	spin_lock_irq(&phba->port_list_lock);
4843 	list_add_tail(&vport->listentry, &phba->port_list);
4844 	spin_unlock_irq(&phba->port_list_lock);
4845 	return vport;
4846 
4847 out_free_vmid:
4848 	kfree(vport->vmid);
4849 	bitmap_free(vport->vmid_priority_range);
4850 out_put_shost:
4851 	scsi_host_put(shost);
4852 out:
4853 	return NULL;
4854 }
4855 
4856 /**
4857  * destroy_port -  destroy an FC port
4858  * @vport: pointer to an lpfc virtual N_Port data structure.
4859  *
4860  * This routine destroys a FC port from the upper layer protocol. All the
4861  * resources associated with the port are released.
4862  **/
4863 void
4864 destroy_port(struct lpfc_vport *vport)
4865 {
4866 	struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
4867 	struct lpfc_hba  *phba = vport->phba;
4868 
4869 	lpfc_debugfs_terminate(vport);
4870 	fc_remove_host(shost);
4871 	scsi_remove_host(shost);
4872 
4873 	spin_lock_irq(&phba->port_list_lock);
4874 	list_del_init(&vport->listentry);
4875 	spin_unlock_irq(&phba->port_list_lock);
4876 
4877 	lpfc_cleanup(vport);
4878 	return;
4879 }
4880 
4881 /**
4882  * lpfc_get_instance - Get a unique integer ID
4883  *
4884  * This routine allocates a unique integer ID from lpfc_hba_index pool. It
4885  * uses the kernel idr facility to perform the task.
4886  *
4887  * Return codes:
4888  *   instance - a unique integer ID allocated as the new instance.
4889  *   -1 - lpfc get instance failed.
4890  **/
4891 int
4892 lpfc_get_instance(void)
4893 {
4894 	int ret;
4895 
4896 	ret = idr_alloc(&lpfc_hba_index, NULL, 0, 0, GFP_KERNEL);
4897 	return ret < 0 ? -1 : ret;
4898 }
4899 
4900 /**
4901  * lpfc_scan_finished - method for SCSI layer to detect whether scan is done
4902  * @shost: pointer to SCSI host data structure.
4903  * @time: elapsed time of the scan in jiffies.
4904  *
4905  * This routine is called by the SCSI layer with a SCSI host to determine
4906  * whether the scan host is finished.
4907  *
4908  * Note: there is no scan_start function as adapter initialization will have
4909  * asynchronously kicked off the link initialization.
4910  *
4911  * Return codes
4912  *   0 - SCSI host scan is not over yet.
4913  *   1 - SCSI host scan is over.
4914  **/
4915 int lpfc_scan_finished(struct Scsi_Host *shost, unsigned long time)
4916 {
4917 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
4918 	struct lpfc_hba   *phba = vport->phba;
4919 	int stat = 0;
4920 
4921 	spin_lock_irq(shost->host_lock);
4922 
4923 	if (test_bit(FC_UNLOADING, &vport->load_flag)) {
4924 		stat = 1;
4925 		goto finished;
4926 	}
4927 	if (time >= msecs_to_jiffies(30 * 1000)) {
4928 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4929 				"0461 Scanning longer than 30 "
4930 				"seconds.  Continuing initialization\n");
4931 		stat = 1;
4932 		goto finished;
4933 	}
4934 	if (time >= msecs_to_jiffies(15 * 1000) &&
4935 	    phba->link_state <= LPFC_LINK_DOWN) {
4936 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4937 				"0465 Link down longer than 15 "
4938 				"seconds.  Continuing initialization\n");
4939 		stat = 1;
4940 		goto finished;
4941 	}
4942 
4943 	if (vport->port_state != LPFC_VPORT_READY)
4944 		goto finished;
4945 	if (vport->num_disc_nodes || vport->fc_prli_sent)
4946 		goto finished;
4947 	if (!atomic_read(&vport->fc_map_cnt) &&
4948 	    time < msecs_to_jiffies(2 * 1000))
4949 		goto finished;
4950 	if ((phba->sli.sli_flag & LPFC_SLI_MBOX_ACTIVE) != 0)
4951 		goto finished;
4952 
4953 	stat = 1;
4954 
4955 finished:
4956 	spin_unlock_irq(shost->host_lock);
4957 	return stat;
4958 }
4959 
4960 static void lpfc_host_supported_speeds_set(struct Scsi_Host *shost)
4961 {
4962 	struct lpfc_vport *vport = (struct lpfc_vport *)shost->hostdata;
4963 	struct lpfc_hba   *phba = vport->phba;
4964 
4965 	fc_host_supported_speeds(shost) = 0;
4966 	/*
4967 	 * Avoid reporting supported link speed for FCoE as it can't be
4968 	 * controlled via FCoE.
4969 	 */
4970 	if (test_bit(HBA_FCOE_MODE, &phba->hba_flag))
4971 		return;
4972 
4973 	if (phba->lmt & LMT_256Gb)
4974 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_256GBIT;
4975 	if (phba->lmt & LMT_128Gb)
4976 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_128GBIT;
4977 	if (phba->lmt & LMT_64Gb)
4978 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_64GBIT;
4979 	if (phba->lmt & LMT_32Gb)
4980 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_32GBIT;
4981 	if (phba->lmt & LMT_16Gb)
4982 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_16GBIT;
4983 	if (phba->lmt & LMT_10Gb)
4984 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_10GBIT;
4985 	if (phba->lmt & LMT_8Gb)
4986 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_8GBIT;
4987 	if (phba->lmt & LMT_4Gb)
4988 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_4GBIT;
4989 	if (phba->lmt & LMT_2Gb)
4990 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_2GBIT;
4991 	if (phba->lmt & LMT_1Gb)
4992 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_1GBIT;
4993 }
4994 
4995 /**
4996  * lpfc_host_attrib_init - Initialize SCSI host attributes on a FC port
4997  * @shost: pointer to SCSI host data structure.
4998  *
4999  * This routine initializes a given SCSI host attributes on a FC port. The
5000  * SCSI host can be either on top of a physical port or a virtual port.
5001  **/
5002 void lpfc_host_attrib_init(struct Scsi_Host *shost)
5003 {
5004 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
5005 	struct lpfc_hba   *phba = vport->phba;
5006 	/*
5007 	 * Set fixed host attributes.  Must done after lpfc_sli_hba_setup().
5008 	 */
5009 
5010 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
5011 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
5012 	fc_host_supported_classes(shost) = FC_COS_CLASS3;
5013 
5014 	memset(fc_host_supported_fc4s(shost), 0,
5015 	       sizeof(fc_host_supported_fc4s(shost)));
5016 	fc_host_supported_fc4s(shost)[2] = 1;
5017 	fc_host_supported_fc4s(shost)[7] = 1;
5018 
5019 	lpfc_vport_symbolic_node_name(vport, fc_host_symbolic_name(shost),
5020 				 sizeof fc_host_symbolic_name(shost));
5021 
5022 	lpfc_host_supported_speeds_set(shost);
5023 
5024 	fc_host_maxframe_size(shost) =
5025 		(((uint32_t) vport->fc_sparam.cmn.bbRcvSizeMsb & 0x0F) << 8) |
5026 		(uint32_t) vport->fc_sparam.cmn.bbRcvSizeLsb;
5027 
5028 	fc_host_dev_loss_tmo(shost) = vport->cfg_devloss_tmo;
5029 
5030 	/* This value is also unchanging */
5031 	memset(fc_host_active_fc4s(shost), 0,
5032 	       sizeof(fc_host_active_fc4s(shost)));
5033 	fc_host_active_fc4s(shost)[2] = 1;
5034 	fc_host_active_fc4s(shost)[7] = 1;
5035 
5036 	fc_host_max_npiv_vports(shost) = phba->max_vpi;
5037 	clear_bit(FC_LOADING, &vport->load_flag);
5038 }
5039 
5040 /**
5041  * lpfc_stop_port_s3 - Stop SLI3 device port
5042  * @phba: pointer to lpfc hba data structure.
5043  *
5044  * This routine is invoked to stop an SLI3 device port, it stops the device
5045  * from generating interrupts and stops the device driver's timers for the
5046  * device.
5047  **/
5048 static void
5049 lpfc_stop_port_s3(struct lpfc_hba *phba)
5050 {
5051 	/* Clear all interrupt enable conditions */
5052 	writel(0, phba->HCregaddr);
5053 	readl(phba->HCregaddr); /* flush */
5054 	/* Clear all pending interrupts */
5055 	writel(0xffffffff, phba->HAregaddr);
5056 	readl(phba->HAregaddr); /* flush */
5057 
5058 	/* Reset some HBA SLI setup states */
5059 	lpfc_stop_hba_timers(phba);
5060 	phba->pport->work_port_events = 0;
5061 }
5062 
5063 /**
5064  * lpfc_stop_port_s4 - Stop SLI4 device port
5065  * @phba: pointer to lpfc hba data structure.
5066  *
5067  * This routine is invoked to stop an SLI4 device port, it stops the device
5068  * from generating interrupts and stops the device driver's timers for the
5069  * device.
5070  **/
5071 static void
5072 lpfc_stop_port_s4(struct lpfc_hba *phba)
5073 {
5074 	/* Reset some HBA SLI4 setup states */
5075 	lpfc_stop_hba_timers(phba);
5076 	if (phba->pport)
5077 		phba->pport->work_port_events = 0;
5078 	phba->sli4_hba.intr_enable = 0;
5079 }
5080 
5081 /**
5082  * lpfc_stop_port - Wrapper function for stopping hba port
5083  * @phba: Pointer to HBA context object.
5084  *
5085  * This routine wraps the actual SLI3 or SLI4 hba stop port routine from
5086  * the API jump table function pointer from the lpfc_hba struct.
5087  **/
5088 void
5089 lpfc_stop_port(struct lpfc_hba *phba)
5090 {
5091 	phba->lpfc_stop_port(phba);
5092 
5093 	if (phba->wq)
5094 		flush_workqueue(phba->wq);
5095 }
5096 
5097 /**
5098  * lpfc_fcf_redisc_wait_start_timer - Start fcf rediscover wait timer
5099  * @phba: Pointer to hba for which this call is being executed.
5100  *
5101  * This routine starts the timer waiting for the FCF rediscovery to complete.
5102  **/
5103 void
5104 lpfc_fcf_redisc_wait_start_timer(struct lpfc_hba *phba)
5105 {
5106 	unsigned long fcf_redisc_wait_tmo =
5107 		(jiffies + msecs_to_jiffies(LPFC_FCF_REDISCOVER_WAIT_TMO));
5108 	/* Start fcf rediscovery wait period timer */
5109 	mod_timer(&phba->fcf.redisc_wait, fcf_redisc_wait_tmo);
5110 	spin_lock_irq(&phba->hbalock);
5111 	/* Allow action to new fcf asynchronous event */
5112 	phba->fcf.fcf_flag &= ~(FCF_AVAILABLE | FCF_SCAN_DONE);
5113 	/* Mark the FCF rediscovery pending state */
5114 	phba->fcf.fcf_flag |= FCF_REDISC_PEND;
5115 	spin_unlock_irq(&phba->hbalock);
5116 }
5117 
5118 /**
5119  * lpfc_sli4_fcf_redisc_wait_tmo - FCF table rediscover wait timeout
5120  * @t: Timer context used to obtain the pointer to lpfc hba data structure.
5121  *
5122  * This routine is invoked when waiting for FCF table rediscover has been
5123  * timed out. If new FCF record(s) has (have) been discovered during the
5124  * wait period, a new FCF event shall be added to the FCOE async event
5125  * list, and then worker thread shall be waked up for processing from the
5126  * worker thread context.
5127  **/
5128 static void
5129 lpfc_sli4_fcf_redisc_wait_tmo(struct timer_list *t)
5130 {
5131 	struct lpfc_hba *phba = from_timer(phba, t, fcf.redisc_wait);
5132 
5133 	/* Don't send FCF rediscovery event if timer cancelled */
5134 	spin_lock_irq(&phba->hbalock);
5135 	if (!(phba->fcf.fcf_flag & FCF_REDISC_PEND)) {
5136 		spin_unlock_irq(&phba->hbalock);
5137 		return;
5138 	}
5139 	/* Clear FCF rediscovery timer pending flag */
5140 	phba->fcf.fcf_flag &= ~FCF_REDISC_PEND;
5141 	/* FCF rediscovery event to worker thread */
5142 	phba->fcf.fcf_flag |= FCF_REDISC_EVT;
5143 	spin_unlock_irq(&phba->hbalock);
5144 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
5145 			"2776 FCF rediscover quiescent timer expired\n");
5146 	/* wake up worker thread */
5147 	lpfc_worker_wake_up(phba);
5148 }
5149 
5150 /**
5151  * lpfc_vmid_poll - VMID timeout detection
5152  * @t: Timer context used to obtain the pointer to lpfc hba data structure.
5153  *
5154  * This routine is invoked when there is no I/O on by a VM for the specified
5155  * amount of time. When this situation is detected, the VMID has to be
5156  * deregistered from the switch and all the local resources freed. The VMID
5157  * will be reassigned to the VM once the I/O begins.
5158  **/
5159 static void
5160 lpfc_vmid_poll(struct timer_list *t)
5161 {
5162 	struct lpfc_hba *phba = from_timer(phba, t, inactive_vmid_poll);
5163 	u32 wake_up = 0;
5164 
5165 	/* check if there is a need to issue QFPA */
5166 	if (phba->pport->vmid_priority_tagging) {
5167 		wake_up = 1;
5168 		phba->pport->work_port_events |= WORKER_CHECK_VMID_ISSUE_QFPA;
5169 	}
5170 
5171 	/* Is the vmid inactivity timer enabled */
5172 	if (phba->pport->vmid_inactivity_timeout ||
5173 	    test_bit(FC_DEREGISTER_ALL_APP_ID, &phba->pport->load_flag)) {
5174 		wake_up = 1;
5175 		phba->pport->work_port_events |= WORKER_CHECK_INACTIVE_VMID;
5176 	}
5177 
5178 	if (wake_up)
5179 		lpfc_worker_wake_up(phba);
5180 
5181 	/* restart the timer for the next iteration */
5182 	mod_timer(&phba->inactive_vmid_poll, jiffies + msecs_to_jiffies(1000 *
5183 							LPFC_VMID_TIMER));
5184 }
5185 
5186 /**
5187  * lpfc_sli4_parse_latt_fault - Parse sli4 link-attention link fault code
5188  * @phba: pointer to lpfc hba data structure.
5189  * @acqe_link: pointer to the async link completion queue entry.
5190  *
5191  * This routine is to parse the SLI4 link-attention link fault code.
5192  **/
5193 static void
5194 lpfc_sli4_parse_latt_fault(struct lpfc_hba *phba,
5195 			   struct lpfc_acqe_link *acqe_link)
5196 {
5197 	switch (bf_get(lpfc_acqe_fc_la_att_type, acqe_link)) {
5198 	case LPFC_FC_LA_TYPE_LINK_DOWN:
5199 	case LPFC_FC_LA_TYPE_TRUNKING_EVENT:
5200 	case LPFC_FC_LA_TYPE_ACTIVATE_FAIL:
5201 	case LPFC_FC_LA_TYPE_LINK_RESET_PRTCL_EVT:
5202 		break;
5203 	default:
5204 		switch (bf_get(lpfc_acqe_link_fault, acqe_link)) {
5205 		case LPFC_ASYNC_LINK_FAULT_NONE:
5206 		case LPFC_ASYNC_LINK_FAULT_LOCAL:
5207 		case LPFC_ASYNC_LINK_FAULT_REMOTE:
5208 		case LPFC_ASYNC_LINK_FAULT_LR_LRR:
5209 			break;
5210 		default:
5211 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5212 					"0398 Unknown link fault code: x%x\n",
5213 					bf_get(lpfc_acqe_link_fault, acqe_link));
5214 			break;
5215 		}
5216 		break;
5217 	}
5218 }
5219 
5220 /**
5221  * lpfc_sli4_parse_latt_type - Parse sli4 link attention type
5222  * @phba: pointer to lpfc hba data structure.
5223  * @acqe_link: pointer to the async link completion queue entry.
5224  *
5225  * This routine is to parse the SLI4 link attention type and translate it
5226  * into the base driver's link attention type coding.
5227  *
5228  * Return: Link attention type in terms of base driver's coding.
5229  **/
5230 static uint8_t
5231 lpfc_sli4_parse_latt_type(struct lpfc_hba *phba,
5232 			  struct lpfc_acqe_link *acqe_link)
5233 {
5234 	uint8_t att_type;
5235 
5236 	switch (bf_get(lpfc_acqe_link_status, acqe_link)) {
5237 	case LPFC_ASYNC_LINK_STATUS_DOWN:
5238 	case LPFC_ASYNC_LINK_STATUS_LOGICAL_DOWN:
5239 		att_type = LPFC_ATT_LINK_DOWN;
5240 		break;
5241 	case LPFC_ASYNC_LINK_STATUS_UP:
5242 		/* Ignore physical link up events - wait for logical link up */
5243 		att_type = LPFC_ATT_RESERVED;
5244 		break;
5245 	case LPFC_ASYNC_LINK_STATUS_LOGICAL_UP:
5246 		att_type = LPFC_ATT_LINK_UP;
5247 		break;
5248 	default:
5249 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5250 				"0399 Invalid link attention type: x%x\n",
5251 				bf_get(lpfc_acqe_link_status, acqe_link));
5252 		att_type = LPFC_ATT_RESERVED;
5253 		break;
5254 	}
5255 	return att_type;
5256 }
5257 
5258 /**
5259  * lpfc_sli_port_speed_get - Get sli3 link speed code to link speed
5260  * @phba: pointer to lpfc hba data structure.
5261  *
5262  * This routine is to get an SLI3 FC port's link speed in Mbps.
5263  *
5264  * Return: link speed in terms of Mbps.
5265  **/
5266 uint32_t
5267 lpfc_sli_port_speed_get(struct lpfc_hba *phba)
5268 {
5269 	uint32_t link_speed;
5270 
5271 	if (!lpfc_is_link_up(phba))
5272 		return 0;
5273 
5274 	if (phba->sli_rev <= LPFC_SLI_REV3) {
5275 		switch (phba->fc_linkspeed) {
5276 		case LPFC_LINK_SPEED_1GHZ:
5277 			link_speed = 1000;
5278 			break;
5279 		case LPFC_LINK_SPEED_2GHZ:
5280 			link_speed = 2000;
5281 			break;
5282 		case LPFC_LINK_SPEED_4GHZ:
5283 			link_speed = 4000;
5284 			break;
5285 		case LPFC_LINK_SPEED_8GHZ:
5286 			link_speed = 8000;
5287 			break;
5288 		case LPFC_LINK_SPEED_10GHZ:
5289 			link_speed = 10000;
5290 			break;
5291 		case LPFC_LINK_SPEED_16GHZ:
5292 			link_speed = 16000;
5293 			break;
5294 		default:
5295 			link_speed = 0;
5296 		}
5297 	} else {
5298 		if (phba->sli4_hba.link_state.logical_speed)
5299 			link_speed =
5300 			      phba->sli4_hba.link_state.logical_speed;
5301 		else
5302 			link_speed = phba->sli4_hba.link_state.speed;
5303 	}
5304 	return link_speed;
5305 }
5306 
5307 /**
5308  * lpfc_sli4_port_speed_parse - Parse async evt link speed code to link speed
5309  * @phba: pointer to lpfc hba data structure.
5310  * @evt_code: asynchronous event code.
5311  * @speed_code: asynchronous event link speed code.
5312  *
5313  * This routine is to parse the giving SLI4 async event link speed code into
5314  * value of Mbps for the link speed.
5315  *
5316  * Return: link speed in terms of Mbps.
5317  **/
5318 static uint32_t
5319 lpfc_sli4_port_speed_parse(struct lpfc_hba *phba, uint32_t evt_code,
5320 			   uint8_t speed_code)
5321 {
5322 	uint32_t port_speed;
5323 
5324 	switch (evt_code) {
5325 	case LPFC_TRAILER_CODE_LINK:
5326 		switch (speed_code) {
5327 		case LPFC_ASYNC_LINK_SPEED_ZERO:
5328 			port_speed = 0;
5329 			break;
5330 		case LPFC_ASYNC_LINK_SPEED_10MBPS:
5331 			port_speed = 10;
5332 			break;
5333 		case LPFC_ASYNC_LINK_SPEED_100MBPS:
5334 			port_speed = 100;
5335 			break;
5336 		case LPFC_ASYNC_LINK_SPEED_1GBPS:
5337 			port_speed = 1000;
5338 			break;
5339 		case LPFC_ASYNC_LINK_SPEED_10GBPS:
5340 			port_speed = 10000;
5341 			break;
5342 		case LPFC_ASYNC_LINK_SPEED_20GBPS:
5343 			port_speed = 20000;
5344 			break;
5345 		case LPFC_ASYNC_LINK_SPEED_25GBPS:
5346 			port_speed = 25000;
5347 			break;
5348 		case LPFC_ASYNC_LINK_SPEED_40GBPS:
5349 			port_speed = 40000;
5350 			break;
5351 		case LPFC_ASYNC_LINK_SPEED_100GBPS:
5352 			port_speed = 100000;
5353 			break;
5354 		default:
5355 			port_speed = 0;
5356 		}
5357 		break;
5358 	case LPFC_TRAILER_CODE_FC:
5359 		switch (speed_code) {
5360 		case LPFC_FC_LA_SPEED_UNKNOWN:
5361 			port_speed = 0;
5362 			break;
5363 		case LPFC_FC_LA_SPEED_1G:
5364 			port_speed = 1000;
5365 			break;
5366 		case LPFC_FC_LA_SPEED_2G:
5367 			port_speed = 2000;
5368 			break;
5369 		case LPFC_FC_LA_SPEED_4G:
5370 			port_speed = 4000;
5371 			break;
5372 		case LPFC_FC_LA_SPEED_8G:
5373 			port_speed = 8000;
5374 			break;
5375 		case LPFC_FC_LA_SPEED_10G:
5376 			port_speed = 10000;
5377 			break;
5378 		case LPFC_FC_LA_SPEED_16G:
5379 			port_speed = 16000;
5380 			break;
5381 		case LPFC_FC_LA_SPEED_32G:
5382 			port_speed = 32000;
5383 			break;
5384 		case LPFC_FC_LA_SPEED_64G:
5385 			port_speed = 64000;
5386 			break;
5387 		case LPFC_FC_LA_SPEED_128G:
5388 			port_speed = 128000;
5389 			break;
5390 		case LPFC_FC_LA_SPEED_256G:
5391 			port_speed = 256000;
5392 			break;
5393 		default:
5394 			port_speed = 0;
5395 		}
5396 		break;
5397 	default:
5398 		port_speed = 0;
5399 	}
5400 	return port_speed;
5401 }
5402 
5403 /**
5404  * lpfc_sli4_async_link_evt - Process the asynchronous FCoE link event
5405  * @phba: pointer to lpfc hba data structure.
5406  * @acqe_link: pointer to the async link completion queue entry.
5407  *
5408  * This routine is to handle the SLI4 asynchronous FCoE link event.
5409  **/
5410 static void
5411 lpfc_sli4_async_link_evt(struct lpfc_hba *phba,
5412 			 struct lpfc_acqe_link *acqe_link)
5413 {
5414 	LPFC_MBOXQ_t *pmb;
5415 	MAILBOX_t *mb;
5416 	struct lpfc_mbx_read_top *la;
5417 	uint8_t att_type;
5418 	int rc;
5419 
5420 	att_type = lpfc_sli4_parse_latt_type(phba, acqe_link);
5421 	if (att_type != LPFC_ATT_LINK_DOWN && att_type != LPFC_ATT_LINK_UP)
5422 		return;
5423 	phba->fcoe_eventtag = acqe_link->event_tag;
5424 	pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5425 	if (!pmb) {
5426 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5427 				"0395 The mboxq allocation failed\n");
5428 		return;
5429 	}
5430 
5431 	rc = lpfc_mbox_rsrc_prep(phba, pmb);
5432 	if (rc) {
5433 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5434 				"0396 mailbox allocation failed\n");
5435 		goto out_free_pmb;
5436 	}
5437 
5438 	/* Cleanup any outstanding ELS commands */
5439 	lpfc_els_flush_all_cmd(phba);
5440 
5441 	/* Block ELS IOCBs until we have done process link event */
5442 	phba->sli4_hba.els_wq->pring->flag |= LPFC_STOP_IOCB_EVENT;
5443 
5444 	/* Update link event statistics */
5445 	phba->sli.slistat.link_event++;
5446 
5447 	/* Create lpfc_handle_latt mailbox command from link ACQE */
5448 	lpfc_read_topology(phba, pmb, pmb->ctx_buf);
5449 	pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
5450 	pmb->vport = phba->pport;
5451 
5452 	/* Keep the link status for extra SLI4 state machine reference */
5453 	phba->sli4_hba.link_state.speed =
5454 			lpfc_sli4_port_speed_parse(phba, LPFC_TRAILER_CODE_LINK,
5455 				bf_get(lpfc_acqe_link_speed, acqe_link));
5456 	phba->sli4_hba.link_state.duplex =
5457 				bf_get(lpfc_acqe_link_duplex, acqe_link);
5458 	phba->sli4_hba.link_state.status =
5459 				bf_get(lpfc_acqe_link_status, acqe_link);
5460 	phba->sli4_hba.link_state.type =
5461 				bf_get(lpfc_acqe_link_type, acqe_link);
5462 	phba->sli4_hba.link_state.number =
5463 				bf_get(lpfc_acqe_link_number, acqe_link);
5464 	phba->sli4_hba.link_state.fault =
5465 				bf_get(lpfc_acqe_link_fault, acqe_link);
5466 	phba->sli4_hba.link_state.logical_speed =
5467 			bf_get(lpfc_acqe_logical_link_speed, acqe_link) * 10;
5468 
5469 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5470 			"2900 Async FC/FCoE Link event - Speed:%dGBit "
5471 			"duplex:x%x LA Type:x%x Port Type:%d Port Number:%d "
5472 			"Logical speed:%dMbps Fault:%d\n",
5473 			phba->sli4_hba.link_state.speed,
5474 			phba->sli4_hba.link_state.topology,
5475 			phba->sli4_hba.link_state.status,
5476 			phba->sli4_hba.link_state.type,
5477 			phba->sli4_hba.link_state.number,
5478 			phba->sli4_hba.link_state.logical_speed,
5479 			phba->sli4_hba.link_state.fault);
5480 	/*
5481 	 * For FC Mode: issue the READ_TOPOLOGY mailbox command to fetch
5482 	 * topology info. Note: Optional for non FC-AL ports.
5483 	 */
5484 	if (!test_bit(HBA_FCOE_MODE, &phba->hba_flag)) {
5485 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
5486 		if (rc == MBX_NOT_FINISHED)
5487 			goto out_free_pmb;
5488 		return;
5489 	}
5490 	/*
5491 	 * For FCoE Mode: fill in all the topology information we need and call
5492 	 * the READ_TOPOLOGY completion routine to continue without actually
5493 	 * sending the READ_TOPOLOGY mailbox command to the port.
5494 	 */
5495 	/* Initialize completion status */
5496 	mb = &pmb->u.mb;
5497 	mb->mbxStatus = MBX_SUCCESS;
5498 
5499 	/* Parse port fault information field */
5500 	lpfc_sli4_parse_latt_fault(phba, acqe_link);
5501 
5502 	/* Parse and translate link attention fields */
5503 	la = (struct lpfc_mbx_read_top *) &pmb->u.mb.un.varReadTop;
5504 	la->eventTag = acqe_link->event_tag;
5505 	bf_set(lpfc_mbx_read_top_att_type, la, att_type);
5506 	bf_set(lpfc_mbx_read_top_link_spd, la,
5507 	       (bf_get(lpfc_acqe_link_speed, acqe_link)));
5508 
5509 	/* Fake the following irrelevant fields */
5510 	bf_set(lpfc_mbx_read_top_topology, la, LPFC_TOPOLOGY_PT_PT);
5511 	bf_set(lpfc_mbx_read_top_alpa_granted, la, 0);
5512 	bf_set(lpfc_mbx_read_top_il, la, 0);
5513 	bf_set(lpfc_mbx_read_top_pb, la, 0);
5514 	bf_set(lpfc_mbx_read_top_fa, la, 0);
5515 	bf_set(lpfc_mbx_read_top_mm, la, 0);
5516 
5517 	/* Invoke the lpfc_handle_latt mailbox command callback function */
5518 	lpfc_mbx_cmpl_read_topology(phba, pmb);
5519 
5520 	return;
5521 
5522 out_free_pmb:
5523 	lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
5524 }
5525 
5526 /**
5527  * lpfc_async_link_speed_to_read_top - Parse async evt link speed code to read
5528  * topology.
5529  * @phba: pointer to lpfc hba data structure.
5530  * @speed_code: asynchronous event link speed code.
5531  *
5532  * This routine is to parse the giving SLI4 async event link speed code into
5533  * value of Read topology link speed.
5534  *
5535  * Return: link speed in terms of Read topology.
5536  **/
5537 static uint8_t
5538 lpfc_async_link_speed_to_read_top(struct lpfc_hba *phba, uint8_t speed_code)
5539 {
5540 	uint8_t port_speed;
5541 
5542 	switch (speed_code) {
5543 	case LPFC_FC_LA_SPEED_1G:
5544 		port_speed = LPFC_LINK_SPEED_1GHZ;
5545 		break;
5546 	case LPFC_FC_LA_SPEED_2G:
5547 		port_speed = LPFC_LINK_SPEED_2GHZ;
5548 		break;
5549 	case LPFC_FC_LA_SPEED_4G:
5550 		port_speed = LPFC_LINK_SPEED_4GHZ;
5551 		break;
5552 	case LPFC_FC_LA_SPEED_8G:
5553 		port_speed = LPFC_LINK_SPEED_8GHZ;
5554 		break;
5555 	case LPFC_FC_LA_SPEED_16G:
5556 		port_speed = LPFC_LINK_SPEED_16GHZ;
5557 		break;
5558 	case LPFC_FC_LA_SPEED_32G:
5559 		port_speed = LPFC_LINK_SPEED_32GHZ;
5560 		break;
5561 	case LPFC_FC_LA_SPEED_64G:
5562 		port_speed = LPFC_LINK_SPEED_64GHZ;
5563 		break;
5564 	case LPFC_FC_LA_SPEED_128G:
5565 		port_speed = LPFC_LINK_SPEED_128GHZ;
5566 		break;
5567 	case LPFC_FC_LA_SPEED_256G:
5568 		port_speed = LPFC_LINK_SPEED_256GHZ;
5569 		break;
5570 	default:
5571 		port_speed = 0;
5572 		break;
5573 	}
5574 
5575 	return port_speed;
5576 }
5577 
5578 void
5579 lpfc_cgn_dump_rxmonitor(struct lpfc_hba *phba)
5580 {
5581 	if (!phba->rx_monitor) {
5582 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5583 				"4411 Rx Monitor Info is empty.\n");
5584 	} else {
5585 		lpfc_rx_monitor_report(phba, phba->rx_monitor, NULL, 0,
5586 				       LPFC_MAX_RXMONITOR_DUMP);
5587 	}
5588 }
5589 
5590 /**
5591  * lpfc_cgn_update_stat - Save data into congestion stats buffer
5592  * @phba: pointer to lpfc hba data structure.
5593  * @dtag: FPIN descriptor received
5594  *
5595  * Increment the FPIN received counter/time when it happens.
5596  */
5597 void
5598 lpfc_cgn_update_stat(struct lpfc_hba *phba, uint32_t dtag)
5599 {
5600 	struct lpfc_cgn_info *cp;
5601 	u32 value;
5602 
5603 	/* Make sure we have a congestion info buffer */
5604 	if (!phba->cgn_i)
5605 		return;
5606 	cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
5607 
5608 	/* Update congestion statistics */
5609 	switch (dtag) {
5610 	case ELS_DTAG_LNK_INTEGRITY:
5611 		le32_add_cpu(&cp->link_integ_notification, 1);
5612 		lpfc_cgn_update_tstamp(phba, &cp->stat_lnk);
5613 		break;
5614 	case ELS_DTAG_DELIVERY:
5615 		le32_add_cpu(&cp->delivery_notification, 1);
5616 		lpfc_cgn_update_tstamp(phba, &cp->stat_delivery);
5617 		break;
5618 	case ELS_DTAG_PEER_CONGEST:
5619 		le32_add_cpu(&cp->cgn_peer_notification, 1);
5620 		lpfc_cgn_update_tstamp(phba, &cp->stat_peer);
5621 		break;
5622 	case ELS_DTAG_CONGESTION:
5623 		le32_add_cpu(&cp->cgn_notification, 1);
5624 		lpfc_cgn_update_tstamp(phba, &cp->stat_fpin);
5625 	}
5626 	if (phba->cgn_fpin_frequency &&
5627 	    phba->cgn_fpin_frequency != LPFC_FPIN_INIT_FREQ) {
5628 		value = LPFC_CGN_TIMER_TO_MIN / phba->cgn_fpin_frequency;
5629 		cp->cgn_stat_npm = value;
5630 	}
5631 
5632 	value = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ,
5633 				    LPFC_CGN_CRC32_SEED);
5634 	cp->cgn_info_crc = cpu_to_le32(value);
5635 }
5636 
5637 /**
5638  * lpfc_cgn_update_tstamp - Update cmf timestamp
5639  * @phba: pointer to lpfc hba data structure.
5640  * @ts: structure to write the timestamp to.
5641  */
5642 void
5643 lpfc_cgn_update_tstamp(struct lpfc_hba *phba, struct lpfc_cgn_ts *ts)
5644 {
5645 	struct timespec64 cur_time;
5646 	struct tm tm_val;
5647 
5648 	ktime_get_real_ts64(&cur_time);
5649 	time64_to_tm(cur_time.tv_sec, 0, &tm_val);
5650 
5651 	ts->month = tm_val.tm_mon + 1;
5652 	ts->day	= tm_val.tm_mday;
5653 	ts->year = tm_val.tm_year - 100;
5654 	ts->hour = tm_val.tm_hour;
5655 	ts->minute = tm_val.tm_min;
5656 	ts->second = tm_val.tm_sec;
5657 
5658 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5659 			"2646 Updated CMF timestamp : "
5660 			"%u/%u/%u %u:%u:%u\n",
5661 			ts->day, ts->month,
5662 			ts->year, ts->hour,
5663 			ts->minute, ts->second);
5664 }
5665 
5666 /**
5667  * lpfc_cmf_stats_timer - Save data into registered congestion buffer
5668  * @timer: Timer cookie to access lpfc private data
5669  *
5670  * Save the congestion event data every minute.
5671  * On the hour collapse all the minute data into hour data. Every day
5672  * collapse all the hour data into daily data. Separate driver
5673  * and fabrc congestion event counters that will be saved out
5674  * to the registered congestion buffer every minute.
5675  */
5676 static enum hrtimer_restart
5677 lpfc_cmf_stats_timer(struct hrtimer *timer)
5678 {
5679 	struct lpfc_hba *phba;
5680 	struct lpfc_cgn_info *cp;
5681 	uint32_t i, index;
5682 	uint16_t value, mvalue;
5683 	uint64_t bps;
5684 	uint32_t mbps;
5685 	uint32_t dvalue, wvalue, lvalue, avalue;
5686 	uint64_t latsum;
5687 	__le16 *ptr;
5688 	__le32 *lptr;
5689 	__le16 *mptr;
5690 
5691 	phba = container_of(timer, struct lpfc_hba, cmf_stats_timer);
5692 	/* Make sure we have a congestion info buffer */
5693 	if (!phba->cgn_i)
5694 		return HRTIMER_NORESTART;
5695 	cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
5696 
5697 	phba->cgn_evt_timestamp = jiffies +
5698 			msecs_to_jiffies(LPFC_CGN_TIMER_TO_MIN);
5699 	phba->cgn_evt_minute++;
5700 
5701 	/* We should get to this point in the routine on 1 minute intervals */
5702 	lpfc_cgn_update_tstamp(phba, &cp->base_time);
5703 
5704 	if (phba->cgn_fpin_frequency &&
5705 	    phba->cgn_fpin_frequency != LPFC_FPIN_INIT_FREQ) {
5706 		value = LPFC_CGN_TIMER_TO_MIN / phba->cgn_fpin_frequency;
5707 		cp->cgn_stat_npm = value;
5708 	}
5709 
5710 	/* Read and clear the latency counters for this minute */
5711 	lvalue = atomic_read(&phba->cgn_latency_evt_cnt);
5712 	latsum = atomic64_read(&phba->cgn_latency_evt);
5713 	atomic_set(&phba->cgn_latency_evt_cnt, 0);
5714 	atomic64_set(&phba->cgn_latency_evt, 0);
5715 
5716 	/* We need to store MB/sec bandwidth in the congestion information.
5717 	 * block_cnt is count of 512 byte blocks for the entire minute,
5718 	 * bps will get bytes per sec before finally converting to MB/sec.
5719 	 */
5720 	bps = div_u64(phba->rx_block_cnt, LPFC_SEC_MIN) * 512;
5721 	phba->rx_block_cnt = 0;
5722 	mvalue = bps / (1024 * 1024); /* convert to MB/sec */
5723 
5724 	/* Every minute */
5725 	/* cgn parameters */
5726 	cp->cgn_info_mode = phba->cgn_p.cgn_param_mode;
5727 	cp->cgn_info_level0 = phba->cgn_p.cgn_param_level0;
5728 	cp->cgn_info_level1 = phba->cgn_p.cgn_param_level1;
5729 	cp->cgn_info_level2 = phba->cgn_p.cgn_param_level2;
5730 
5731 	/* Fill in default LUN qdepth */
5732 	value = (uint16_t)(phba->pport->cfg_lun_queue_depth);
5733 	cp->cgn_lunq = cpu_to_le16(value);
5734 
5735 	/* Record congestion buffer info - every minute
5736 	 * cgn_driver_evt_cnt (Driver events)
5737 	 * cgn_fabric_warn_cnt (Congestion Warnings)
5738 	 * cgn_latency_evt_cnt / cgn_latency_evt (IO Latency)
5739 	 * cgn_fabric_alarm_cnt (Congestion Alarms)
5740 	 */
5741 	index = ++cp->cgn_index_minute;
5742 	if (cp->cgn_index_minute == LPFC_MIN_HOUR) {
5743 		cp->cgn_index_minute = 0;
5744 		index = 0;
5745 	}
5746 
5747 	/* Get the number of driver events in this sample and reset counter */
5748 	dvalue = atomic_read(&phba->cgn_driver_evt_cnt);
5749 	atomic_set(&phba->cgn_driver_evt_cnt, 0);
5750 
5751 	/* Get the number of warning events - FPIN and Signal for this minute */
5752 	wvalue = 0;
5753 	if ((phba->cgn_reg_fpin & LPFC_CGN_FPIN_WARN) ||
5754 	    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY ||
5755 	    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM)
5756 		wvalue = atomic_read(&phba->cgn_fabric_warn_cnt);
5757 	atomic_set(&phba->cgn_fabric_warn_cnt, 0);
5758 
5759 	/* Get the number of alarm events - FPIN and Signal for this minute */
5760 	avalue = 0;
5761 	if ((phba->cgn_reg_fpin & LPFC_CGN_FPIN_ALARM) ||
5762 	    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM)
5763 		avalue = atomic_read(&phba->cgn_fabric_alarm_cnt);
5764 	atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
5765 
5766 	/* Collect the driver, warning, alarm and latency counts for this
5767 	 * minute into the driver congestion buffer.
5768 	 */
5769 	ptr = &cp->cgn_drvr_min[index];
5770 	value = (uint16_t)dvalue;
5771 	*ptr = cpu_to_le16(value);
5772 
5773 	ptr = &cp->cgn_warn_min[index];
5774 	value = (uint16_t)wvalue;
5775 	*ptr = cpu_to_le16(value);
5776 
5777 	ptr = &cp->cgn_alarm_min[index];
5778 	value = (uint16_t)avalue;
5779 	*ptr = cpu_to_le16(value);
5780 
5781 	lptr = &cp->cgn_latency_min[index];
5782 	if (lvalue) {
5783 		lvalue = (uint32_t)div_u64(latsum, lvalue);
5784 		*lptr = cpu_to_le32(lvalue);
5785 	} else {
5786 		*lptr = 0;
5787 	}
5788 
5789 	/* Collect the bandwidth value into the driver's congesion buffer. */
5790 	mptr = &cp->cgn_bw_min[index];
5791 	*mptr = cpu_to_le16(mvalue);
5792 
5793 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5794 			"2418 Congestion Info - minute (%d): %d %d %d %d %d\n",
5795 			index, dvalue, wvalue, *lptr, mvalue, avalue);
5796 
5797 	/* Every hour */
5798 	if ((phba->cgn_evt_minute % LPFC_MIN_HOUR) == 0) {
5799 		/* Record congestion buffer info - every hour
5800 		 * Collapse all minutes into an hour
5801 		 */
5802 		index = ++cp->cgn_index_hour;
5803 		if (cp->cgn_index_hour == LPFC_HOUR_DAY) {
5804 			cp->cgn_index_hour = 0;
5805 			index = 0;
5806 		}
5807 
5808 		dvalue = 0;
5809 		wvalue = 0;
5810 		lvalue = 0;
5811 		avalue = 0;
5812 		mvalue = 0;
5813 		mbps = 0;
5814 		for (i = 0; i < LPFC_MIN_HOUR; i++) {
5815 			dvalue += le16_to_cpu(cp->cgn_drvr_min[i]);
5816 			wvalue += le16_to_cpu(cp->cgn_warn_min[i]);
5817 			lvalue += le32_to_cpu(cp->cgn_latency_min[i]);
5818 			mbps += le16_to_cpu(cp->cgn_bw_min[i]);
5819 			avalue += le16_to_cpu(cp->cgn_alarm_min[i]);
5820 		}
5821 		if (lvalue)		/* Avg of latency averages */
5822 			lvalue /= LPFC_MIN_HOUR;
5823 		if (mbps)		/* Avg of Bandwidth averages */
5824 			mvalue = mbps / LPFC_MIN_HOUR;
5825 
5826 		lptr = &cp->cgn_drvr_hr[index];
5827 		*lptr = cpu_to_le32(dvalue);
5828 		lptr = &cp->cgn_warn_hr[index];
5829 		*lptr = cpu_to_le32(wvalue);
5830 		lptr = &cp->cgn_latency_hr[index];
5831 		*lptr = cpu_to_le32(lvalue);
5832 		mptr = &cp->cgn_bw_hr[index];
5833 		*mptr = cpu_to_le16(mvalue);
5834 		lptr = &cp->cgn_alarm_hr[index];
5835 		*lptr = cpu_to_le32(avalue);
5836 
5837 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5838 				"2419 Congestion Info - hour "
5839 				"(%d): %d %d %d %d %d\n",
5840 				index, dvalue, wvalue, lvalue, mvalue, avalue);
5841 	}
5842 
5843 	/* Every day */
5844 	if ((phba->cgn_evt_minute % LPFC_MIN_DAY) == 0) {
5845 		/* Record congestion buffer info - every hour
5846 		 * Collapse all hours into a day. Rotate days
5847 		 * after LPFC_MAX_CGN_DAYS.
5848 		 */
5849 		index = ++cp->cgn_index_day;
5850 		if (cp->cgn_index_day == LPFC_MAX_CGN_DAYS) {
5851 			cp->cgn_index_day = 0;
5852 			index = 0;
5853 		}
5854 
5855 		dvalue = 0;
5856 		wvalue = 0;
5857 		lvalue = 0;
5858 		mvalue = 0;
5859 		mbps = 0;
5860 		avalue = 0;
5861 		for (i = 0; i < LPFC_HOUR_DAY; i++) {
5862 			dvalue += le32_to_cpu(cp->cgn_drvr_hr[i]);
5863 			wvalue += le32_to_cpu(cp->cgn_warn_hr[i]);
5864 			lvalue += le32_to_cpu(cp->cgn_latency_hr[i]);
5865 			mbps += le16_to_cpu(cp->cgn_bw_hr[i]);
5866 			avalue += le32_to_cpu(cp->cgn_alarm_hr[i]);
5867 		}
5868 		if (lvalue)		/* Avg of latency averages */
5869 			lvalue /= LPFC_HOUR_DAY;
5870 		if (mbps)		/* Avg of Bandwidth averages */
5871 			mvalue = mbps / LPFC_HOUR_DAY;
5872 
5873 		lptr = &cp->cgn_drvr_day[index];
5874 		*lptr = cpu_to_le32(dvalue);
5875 		lptr = &cp->cgn_warn_day[index];
5876 		*lptr = cpu_to_le32(wvalue);
5877 		lptr = &cp->cgn_latency_day[index];
5878 		*lptr = cpu_to_le32(lvalue);
5879 		mptr = &cp->cgn_bw_day[index];
5880 		*mptr = cpu_to_le16(mvalue);
5881 		lptr = &cp->cgn_alarm_day[index];
5882 		*lptr = cpu_to_le32(avalue);
5883 
5884 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5885 				"2420 Congestion Info - daily (%d): "
5886 				"%d %d %d %d %d\n",
5887 				index, dvalue, wvalue, lvalue, mvalue, avalue);
5888 	}
5889 
5890 	/* Use the frequency found in the last rcv'ed FPIN */
5891 	value = phba->cgn_fpin_frequency;
5892 	cp->cgn_warn_freq = cpu_to_le16(value);
5893 	cp->cgn_alarm_freq = cpu_to_le16(value);
5894 
5895 	lvalue = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ,
5896 				     LPFC_CGN_CRC32_SEED);
5897 	cp->cgn_info_crc = cpu_to_le32(lvalue);
5898 
5899 	hrtimer_forward_now(timer, ktime_set(0, LPFC_SEC_MIN * NSEC_PER_SEC));
5900 
5901 	return HRTIMER_RESTART;
5902 }
5903 
5904 /**
5905  * lpfc_calc_cmf_latency - latency from start of rxate timer interval
5906  * @phba: The Hba for which this call is being executed.
5907  *
5908  * The routine calculates the latency from the beginning of the CMF timer
5909  * interval to the current point in time. It is called from IO completion
5910  * when we exceed our Bandwidth limitation for the time interval.
5911  */
5912 uint32_t
5913 lpfc_calc_cmf_latency(struct lpfc_hba *phba)
5914 {
5915 	struct timespec64 cmpl_time;
5916 	uint32_t msec = 0;
5917 
5918 	ktime_get_real_ts64(&cmpl_time);
5919 
5920 	/* This routine works on a ms granularity so sec and usec are
5921 	 * converted accordingly.
5922 	 */
5923 	if (cmpl_time.tv_sec == phba->cmf_latency.tv_sec) {
5924 		msec = (cmpl_time.tv_nsec - phba->cmf_latency.tv_nsec) /
5925 			NSEC_PER_MSEC;
5926 	} else {
5927 		if (cmpl_time.tv_nsec >= phba->cmf_latency.tv_nsec) {
5928 			msec = (cmpl_time.tv_sec -
5929 				phba->cmf_latency.tv_sec) * MSEC_PER_SEC;
5930 			msec += ((cmpl_time.tv_nsec -
5931 				  phba->cmf_latency.tv_nsec) / NSEC_PER_MSEC);
5932 		} else {
5933 			msec = (cmpl_time.tv_sec - phba->cmf_latency.tv_sec -
5934 				1) * MSEC_PER_SEC;
5935 			msec += (((NSEC_PER_SEC - phba->cmf_latency.tv_nsec) +
5936 				 cmpl_time.tv_nsec) / NSEC_PER_MSEC);
5937 		}
5938 	}
5939 	return msec;
5940 }
5941 
5942 /**
5943  * lpfc_cmf_timer -  This is the timer function for one congestion
5944  * rate interval.
5945  * @timer: Pointer to the high resolution timer that expired
5946  */
5947 static enum hrtimer_restart
5948 lpfc_cmf_timer(struct hrtimer *timer)
5949 {
5950 	struct lpfc_hba *phba = container_of(timer, struct lpfc_hba,
5951 					     cmf_timer);
5952 	struct rx_info_entry entry;
5953 	uint32_t io_cnt;
5954 	uint32_t busy, max_read;
5955 	uint64_t total, rcv, lat, mbpi, extra, cnt;
5956 	int timer_interval = LPFC_CMF_INTERVAL;
5957 	uint32_t ms;
5958 	struct lpfc_cgn_stat *cgs;
5959 	int cpu;
5960 
5961 	/* Only restart the timer if congestion mgmt is on */
5962 	if (phba->cmf_active_mode == LPFC_CFG_OFF ||
5963 	    !phba->cmf_latency.tv_sec) {
5964 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5965 				"6224 CMF timer exit: %d %lld\n",
5966 				phba->cmf_active_mode,
5967 				(uint64_t)phba->cmf_latency.tv_sec);
5968 		return HRTIMER_NORESTART;
5969 	}
5970 
5971 	/* If pport is not ready yet, just exit and wait for
5972 	 * the next timer cycle to hit.
5973 	 */
5974 	if (!phba->pport)
5975 		goto skip;
5976 
5977 	/* Do not block SCSI IO while in the timer routine since
5978 	 * total_bytes will be cleared
5979 	 */
5980 	atomic_set(&phba->cmf_stop_io, 1);
5981 
5982 	/* First we need to calculate the actual ms between
5983 	 * the last timer interrupt and this one. We ask for
5984 	 * LPFC_CMF_INTERVAL, however the actual time may
5985 	 * vary depending on system overhead.
5986 	 */
5987 	ms = lpfc_calc_cmf_latency(phba);
5988 
5989 
5990 	/* Immediately after we calculate the time since the last
5991 	 * timer interrupt, set the start time for the next
5992 	 * interrupt
5993 	 */
5994 	ktime_get_real_ts64(&phba->cmf_latency);
5995 
5996 	phba->cmf_link_byte_count =
5997 		div_u64(phba->cmf_max_line_rate * LPFC_CMF_INTERVAL, 1000);
5998 
5999 	/* Collect all the stats from the prior timer interval */
6000 	total = 0;
6001 	io_cnt = 0;
6002 	lat = 0;
6003 	rcv = 0;
6004 	for_each_present_cpu(cpu) {
6005 		cgs = per_cpu_ptr(phba->cmf_stat, cpu);
6006 		total += atomic64_xchg(&cgs->total_bytes, 0);
6007 		io_cnt += atomic_xchg(&cgs->rx_io_cnt, 0);
6008 		lat += atomic64_xchg(&cgs->rx_latency, 0);
6009 		rcv += atomic64_xchg(&cgs->rcv_bytes, 0);
6010 	}
6011 
6012 	/* Before we issue another CMF_SYNC_WQE, retrieve the BW
6013 	 * returned from the last CMF_SYNC_WQE issued, from
6014 	 * cmf_last_sync_bw. This will be the target BW for
6015 	 * this next timer interval.
6016 	 */
6017 	if (phba->cmf_active_mode == LPFC_CFG_MANAGED &&
6018 	    phba->link_state != LPFC_LINK_DOWN &&
6019 	    test_bit(HBA_SETUP, &phba->hba_flag)) {
6020 		mbpi = phba->cmf_last_sync_bw;
6021 		phba->cmf_last_sync_bw = 0;
6022 		extra = 0;
6023 
6024 		/* Calculate any extra bytes needed to account for the
6025 		 * timer accuracy. If we are less than LPFC_CMF_INTERVAL
6026 		 * calculate the adjustment needed for total to reflect
6027 		 * a full LPFC_CMF_INTERVAL.
6028 		 */
6029 		if (ms && ms < LPFC_CMF_INTERVAL) {
6030 			cnt = div_u64(total, ms); /* bytes per ms */
6031 			cnt *= LPFC_CMF_INTERVAL; /* what total should be */
6032 			extra = cnt - total;
6033 		}
6034 		lpfc_issue_cmf_sync_wqe(phba, LPFC_CMF_INTERVAL, total + extra);
6035 	} else {
6036 		/* For Monitor mode or link down we want mbpi
6037 		 * to be the full link speed
6038 		 */
6039 		mbpi = phba->cmf_link_byte_count;
6040 		extra = 0;
6041 	}
6042 	phba->cmf_timer_cnt++;
6043 
6044 	if (io_cnt) {
6045 		/* Update congestion info buffer latency in us */
6046 		atomic_add(io_cnt, &phba->cgn_latency_evt_cnt);
6047 		atomic64_add(lat, &phba->cgn_latency_evt);
6048 	}
6049 	busy = atomic_xchg(&phba->cmf_busy, 0);
6050 	max_read = atomic_xchg(&phba->rx_max_read_cnt, 0);
6051 
6052 	/* Calculate MBPI for the next timer interval */
6053 	if (mbpi) {
6054 		if (mbpi > phba->cmf_link_byte_count ||
6055 		    phba->cmf_active_mode == LPFC_CFG_MONITOR)
6056 			mbpi = phba->cmf_link_byte_count;
6057 
6058 		/* Change max_bytes_per_interval to what the prior
6059 		 * CMF_SYNC_WQE cmpl indicated.
6060 		 */
6061 		if (mbpi != phba->cmf_max_bytes_per_interval)
6062 			phba->cmf_max_bytes_per_interval = mbpi;
6063 	}
6064 
6065 	/* Save rxmonitor information for debug */
6066 	if (phba->rx_monitor) {
6067 		entry.total_bytes = total;
6068 		entry.cmf_bytes = total + extra;
6069 		entry.rcv_bytes = rcv;
6070 		entry.cmf_busy = busy;
6071 		entry.cmf_info = phba->cmf_active_info;
6072 		if (io_cnt) {
6073 			entry.avg_io_latency = div_u64(lat, io_cnt);
6074 			entry.avg_io_size = div_u64(rcv, io_cnt);
6075 		} else {
6076 			entry.avg_io_latency = 0;
6077 			entry.avg_io_size = 0;
6078 		}
6079 		entry.max_read_cnt = max_read;
6080 		entry.io_cnt = io_cnt;
6081 		entry.max_bytes_per_interval = mbpi;
6082 		if (phba->cmf_active_mode == LPFC_CFG_MANAGED)
6083 			entry.timer_utilization = phba->cmf_last_ts;
6084 		else
6085 			entry.timer_utilization = ms;
6086 		entry.timer_interval = ms;
6087 		phba->cmf_last_ts = 0;
6088 
6089 		lpfc_rx_monitor_record(phba->rx_monitor, &entry);
6090 	}
6091 
6092 	if (phba->cmf_active_mode == LPFC_CFG_MONITOR) {
6093 		/* If Monitor mode, check if we are oversubscribed
6094 		 * against the full line rate.
6095 		 */
6096 		if (mbpi && total > mbpi)
6097 			atomic_inc(&phba->cgn_driver_evt_cnt);
6098 	}
6099 	phba->rx_block_cnt += div_u64(rcv, 512);  /* save 512 byte block cnt */
6100 
6101 	/* Since total_bytes has already been zero'ed, its okay to unblock
6102 	 * after max_bytes_per_interval is setup.
6103 	 */
6104 	if (atomic_xchg(&phba->cmf_bw_wait, 0))
6105 		queue_work(phba->wq, &phba->unblock_request_work);
6106 
6107 	/* SCSI IO is now unblocked */
6108 	atomic_set(&phba->cmf_stop_io, 0);
6109 
6110 skip:
6111 	hrtimer_forward_now(timer,
6112 			    ktime_set(0, timer_interval * NSEC_PER_MSEC));
6113 	return HRTIMER_RESTART;
6114 }
6115 
6116 #define trunk_link_status(__idx)\
6117 	bf_get(lpfc_acqe_fc_la_trunk_config_port##__idx, acqe_fc) ?\
6118 	       ((phba->trunk_link.link##__idx.state == LPFC_LINK_UP) ?\
6119 		"Link up" : "Link down") : "NA"
6120 /* Did port __idx reported an error */
6121 #define trunk_port_fault(__idx)\
6122 	bf_get(lpfc_acqe_fc_la_trunk_config_port##__idx, acqe_fc) ?\
6123 	       (port_fault & (1 << __idx) ? "YES" : "NO") : "NA"
6124 
6125 static void
6126 lpfc_update_trunk_link_status(struct lpfc_hba *phba,
6127 			      struct lpfc_acqe_fc_la *acqe_fc)
6128 {
6129 	uint8_t port_fault = bf_get(lpfc_acqe_fc_la_trunk_linkmask, acqe_fc);
6130 	uint8_t err = bf_get(lpfc_acqe_fc_la_trunk_fault, acqe_fc);
6131 	u8 cnt = 0;
6132 
6133 	phba->sli4_hba.link_state.speed =
6134 		lpfc_sli4_port_speed_parse(phba, LPFC_TRAILER_CODE_FC,
6135 				bf_get(lpfc_acqe_fc_la_speed, acqe_fc));
6136 
6137 	phba->sli4_hba.link_state.logical_speed =
6138 				bf_get(lpfc_acqe_fc_la_llink_spd, acqe_fc) * 10;
6139 	/* We got FC link speed, convert to fc_linkspeed (READ_TOPOLOGY) */
6140 	phba->fc_linkspeed =
6141 		 lpfc_async_link_speed_to_read_top(
6142 				phba,
6143 				bf_get(lpfc_acqe_fc_la_speed, acqe_fc));
6144 
6145 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port0, acqe_fc)) {
6146 		phba->trunk_link.link0.state =
6147 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port0, acqe_fc)
6148 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
6149 		phba->trunk_link.link0.fault = port_fault & 0x1 ? err : 0;
6150 		cnt++;
6151 	}
6152 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port1, acqe_fc)) {
6153 		phba->trunk_link.link1.state =
6154 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port1, acqe_fc)
6155 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
6156 		phba->trunk_link.link1.fault = port_fault & 0x2 ? err : 0;
6157 		cnt++;
6158 	}
6159 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port2, acqe_fc)) {
6160 		phba->trunk_link.link2.state =
6161 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port2, acqe_fc)
6162 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
6163 		phba->trunk_link.link2.fault = port_fault & 0x4 ? err : 0;
6164 		cnt++;
6165 	}
6166 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port3, acqe_fc)) {
6167 		phba->trunk_link.link3.state =
6168 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port3, acqe_fc)
6169 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
6170 		phba->trunk_link.link3.fault = port_fault & 0x8 ? err : 0;
6171 		cnt++;
6172 	}
6173 
6174 	if (cnt)
6175 		phba->trunk_link.phy_lnk_speed =
6176 			phba->sli4_hba.link_state.logical_speed / (cnt * 1000);
6177 	else
6178 		phba->trunk_link.phy_lnk_speed = LPFC_LINK_SPEED_UNKNOWN;
6179 
6180 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6181 			"2910 Async FC Trunking Event - Speed:%d\n"
6182 			"\tLogical speed:%d "
6183 			"port0: %s port1: %s port2: %s port3: %s\n",
6184 			phba->sli4_hba.link_state.speed,
6185 			phba->sli4_hba.link_state.logical_speed,
6186 			trunk_link_status(0), trunk_link_status(1),
6187 			trunk_link_status(2), trunk_link_status(3));
6188 
6189 	if (phba->cmf_active_mode != LPFC_CFG_OFF)
6190 		lpfc_cmf_signal_init(phba);
6191 
6192 	if (port_fault)
6193 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6194 				"3202 trunk error:0x%x (%s) seen on port0:%s "
6195 				/*
6196 				 * SLI-4: We have only 0xA error codes
6197 				 * defined as of now. print an appropriate
6198 				 * message in case driver needs to be updated.
6199 				 */
6200 				"port1:%s port2:%s port3:%s\n", err, err > 0xA ?
6201 				"UNDEFINED. update driver." : trunk_errmsg[err],
6202 				trunk_port_fault(0), trunk_port_fault(1),
6203 				trunk_port_fault(2), trunk_port_fault(3));
6204 }
6205 
6206 
6207 /**
6208  * lpfc_sli4_async_fc_evt - Process the asynchronous FC link event
6209  * @phba: pointer to lpfc hba data structure.
6210  * @acqe_fc: pointer to the async fc completion queue entry.
6211  *
6212  * This routine is to handle the SLI4 asynchronous FC event. It will simply log
6213  * that the event was received and then issue a read_topology mailbox command so
6214  * that the rest of the driver will treat it the same as SLI3.
6215  **/
6216 static void
6217 lpfc_sli4_async_fc_evt(struct lpfc_hba *phba, struct lpfc_acqe_fc_la *acqe_fc)
6218 {
6219 	LPFC_MBOXQ_t *pmb;
6220 	MAILBOX_t *mb;
6221 	struct lpfc_mbx_read_top *la;
6222 	char *log_level;
6223 	int rc;
6224 
6225 	if (bf_get(lpfc_trailer_type, acqe_fc) !=
6226 	    LPFC_FC_LA_EVENT_TYPE_FC_LINK) {
6227 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6228 				"2895 Non FC link Event detected.(%d)\n",
6229 				bf_get(lpfc_trailer_type, acqe_fc));
6230 		return;
6231 	}
6232 
6233 	if (bf_get(lpfc_acqe_fc_la_att_type, acqe_fc) ==
6234 	    LPFC_FC_LA_TYPE_TRUNKING_EVENT) {
6235 		lpfc_update_trunk_link_status(phba, acqe_fc);
6236 		return;
6237 	}
6238 
6239 	/* Keep the link status for extra SLI4 state machine reference */
6240 	phba->sli4_hba.link_state.speed =
6241 			lpfc_sli4_port_speed_parse(phba, LPFC_TRAILER_CODE_FC,
6242 				bf_get(lpfc_acqe_fc_la_speed, acqe_fc));
6243 	phba->sli4_hba.link_state.duplex = LPFC_ASYNC_LINK_DUPLEX_FULL;
6244 	phba->sli4_hba.link_state.topology =
6245 				bf_get(lpfc_acqe_fc_la_topology, acqe_fc);
6246 	phba->sli4_hba.link_state.status =
6247 				bf_get(lpfc_acqe_fc_la_att_type, acqe_fc);
6248 	phba->sli4_hba.link_state.type =
6249 				bf_get(lpfc_acqe_fc_la_port_type, acqe_fc);
6250 	phba->sli4_hba.link_state.number =
6251 				bf_get(lpfc_acqe_fc_la_port_number, acqe_fc);
6252 	phba->sli4_hba.link_state.fault =
6253 				bf_get(lpfc_acqe_link_fault, acqe_fc);
6254 	phba->sli4_hba.link_state.link_status =
6255 				bf_get(lpfc_acqe_fc_la_link_status, acqe_fc);
6256 
6257 	/*
6258 	 * Only select attention types need logical speed modification to what
6259 	 * was previously set.
6260 	 */
6261 	if (phba->sli4_hba.link_state.status >= LPFC_FC_LA_TYPE_LINK_UP &&
6262 	    phba->sli4_hba.link_state.status < LPFC_FC_LA_TYPE_ACTIVATE_FAIL) {
6263 		if (bf_get(lpfc_acqe_fc_la_att_type, acqe_fc) ==
6264 		    LPFC_FC_LA_TYPE_LINK_DOWN)
6265 			phba->sli4_hba.link_state.logical_speed = 0;
6266 		else if (!phba->sli4_hba.conf_trunk)
6267 			phba->sli4_hba.link_state.logical_speed =
6268 				bf_get(lpfc_acqe_fc_la_llink_spd, acqe_fc) * 10;
6269 	}
6270 
6271 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6272 			"2896 Async FC event - Speed:%dGBaud Topology:x%x "
6273 			"LA Type:x%x Port Type:%d Port Number:%d Logical speed:"
6274 			"%dMbps Fault:x%x Link Status:x%x\n",
6275 			phba->sli4_hba.link_state.speed,
6276 			phba->sli4_hba.link_state.topology,
6277 			phba->sli4_hba.link_state.status,
6278 			phba->sli4_hba.link_state.type,
6279 			phba->sli4_hba.link_state.number,
6280 			phba->sli4_hba.link_state.logical_speed,
6281 			phba->sli4_hba.link_state.fault,
6282 			phba->sli4_hba.link_state.link_status);
6283 
6284 	/*
6285 	 * The following attention types are informational only, providing
6286 	 * further details about link status.  Overwrite the value of
6287 	 * link_state.status appropriately.  No further action is required.
6288 	 */
6289 	if (phba->sli4_hba.link_state.status >= LPFC_FC_LA_TYPE_ACTIVATE_FAIL) {
6290 		switch (phba->sli4_hba.link_state.status) {
6291 		case LPFC_FC_LA_TYPE_ACTIVATE_FAIL:
6292 			log_level = KERN_WARNING;
6293 			phba->sli4_hba.link_state.status =
6294 					LPFC_FC_LA_TYPE_LINK_DOWN;
6295 			break;
6296 		case LPFC_FC_LA_TYPE_LINK_RESET_PRTCL_EVT:
6297 			/*
6298 			 * During bb credit recovery establishment, receiving
6299 			 * this attention type is normal.  Link Up attention
6300 			 * type is expected to occur before this informational
6301 			 * attention type so keep the Link Up status.
6302 			 */
6303 			log_level = KERN_INFO;
6304 			phba->sli4_hba.link_state.status =
6305 					LPFC_FC_LA_TYPE_LINK_UP;
6306 			break;
6307 		default:
6308 			log_level = KERN_INFO;
6309 			break;
6310 		}
6311 		lpfc_log_msg(phba, log_level, LOG_SLI,
6312 			     "2992 Async FC event - Informational Link "
6313 			     "Attention Type x%x\n",
6314 			     bf_get(lpfc_acqe_fc_la_att_type, acqe_fc));
6315 		return;
6316 	}
6317 
6318 	pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6319 	if (!pmb) {
6320 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6321 				"2897 The mboxq allocation failed\n");
6322 		return;
6323 	}
6324 	rc = lpfc_mbox_rsrc_prep(phba, pmb);
6325 	if (rc) {
6326 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6327 				"2898 The mboxq prep failed\n");
6328 		goto out_free_pmb;
6329 	}
6330 
6331 	/* Cleanup any outstanding ELS commands */
6332 	lpfc_els_flush_all_cmd(phba);
6333 
6334 	/* Block ELS IOCBs until we have done process link event */
6335 	phba->sli4_hba.els_wq->pring->flag |= LPFC_STOP_IOCB_EVENT;
6336 
6337 	/* Update link event statistics */
6338 	phba->sli.slistat.link_event++;
6339 
6340 	/* Create lpfc_handle_latt mailbox command from link ACQE */
6341 	lpfc_read_topology(phba, pmb, pmb->ctx_buf);
6342 	pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
6343 	pmb->vport = phba->pport;
6344 
6345 	if (phba->sli4_hba.link_state.status != LPFC_FC_LA_TYPE_LINK_UP) {
6346 		phba->link_flag &= ~(LS_MDS_LINK_DOWN | LS_MDS_LOOPBACK);
6347 
6348 		switch (phba->sli4_hba.link_state.status) {
6349 		case LPFC_FC_LA_TYPE_MDS_LINK_DOWN:
6350 			phba->link_flag |= LS_MDS_LINK_DOWN;
6351 			break;
6352 		case LPFC_FC_LA_TYPE_MDS_LOOPBACK:
6353 			phba->link_flag |= LS_MDS_LOOPBACK;
6354 			break;
6355 		default:
6356 			break;
6357 		}
6358 
6359 		/* Initialize completion status */
6360 		mb = &pmb->u.mb;
6361 		mb->mbxStatus = MBX_SUCCESS;
6362 
6363 		/* Parse port fault information field */
6364 		lpfc_sli4_parse_latt_fault(phba, (void *)acqe_fc);
6365 
6366 		/* Parse and translate link attention fields */
6367 		la = (struct lpfc_mbx_read_top *)&pmb->u.mb.un.varReadTop;
6368 		la->eventTag = acqe_fc->event_tag;
6369 
6370 		if (phba->sli4_hba.link_state.status ==
6371 		    LPFC_FC_LA_TYPE_UNEXP_WWPN) {
6372 			bf_set(lpfc_mbx_read_top_att_type, la,
6373 			       LPFC_FC_LA_TYPE_UNEXP_WWPN);
6374 		} else {
6375 			bf_set(lpfc_mbx_read_top_att_type, la,
6376 			       LPFC_FC_LA_TYPE_LINK_DOWN);
6377 		}
6378 		/* Invoke the mailbox command callback function */
6379 		lpfc_mbx_cmpl_read_topology(phba, pmb);
6380 
6381 		return;
6382 	}
6383 
6384 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
6385 	if (rc == MBX_NOT_FINISHED)
6386 		goto out_free_pmb;
6387 	return;
6388 
6389 out_free_pmb:
6390 	lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
6391 }
6392 
6393 /**
6394  * lpfc_sli4_async_sli_evt - Process the asynchronous SLI link event
6395  * @phba: pointer to lpfc hba data structure.
6396  * @acqe_sli: pointer to the async SLI completion queue entry.
6397  *
6398  * This routine is to handle the SLI4 asynchronous SLI events.
6399  **/
6400 static void
6401 lpfc_sli4_async_sli_evt(struct lpfc_hba *phba, struct lpfc_acqe_sli *acqe_sli)
6402 {
6403 	char port_name;
6404 	char message[128];
6405 	uint8_t status;
6406 	uint8_t evt_type;
6407 	uint8_t operational = 0;
6408 	struct temp_event temp_event_data;
6409 	struct lpfc_acqe_misconfigured_event *misconfigured;
6410 	struct lpfc_acqe_cgn_signal *cgn_signal;
6411 	struct Scsi_Host  *shost;
6412 	struct lpfc_vport **vports;
6413 	int rc, i, cnt;
6414 
6415 	evt_type = bf_get(lpfc_trailer_type, acqe_sli);
6416 
6417 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6418 			"2901 Async SLI event - Type:%d, Event Data: x%08x "
6419 			"x%08x x%08x x%08x\n", evt_type,
6420 			acqe_sli->event_data1, acqe_sli->event_data2,
6421 			acqe_sli->event_data3, acqe_sli->trailer);
6422 
6423 	port_name = phba->Port[0];
6424 	if (port_name == 0x00)
6425 		port_name = '?'; /* get port name is empty */
6426 
6427 	switch (evt_type) {
6428 	case LPFC_SLI_EVENT_TYPE_OVER_TEMP:
6429 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
6430 		temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
6431 		temp_event_data.data = (uint32_t)acqe_sli->event_data1;
6432 
6433 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6434 				"3190 Over Temperature:%d Celsius- Port Name %c\n",
6435 				acqe_sli->event_data1, port_name);
6436 
6437 		phba->sfp_warning |= LPFC_TRANSGRESSION_HIGH_TEMPERATURE;
6438 		shost = lpfc_shost_from_vport(phba->pport);
6439 		fc_host_post_vendor_event(shost, fc_get_event_number(),
6440 					  sizeof(temp_event_data),
6441 					  (char *)&temp_event_data,
6442 					  SCSI_NL_VID_TYPE_PCI
6443 					  | PCI_VENDOR_ID_EMULEX);
6444 		break;
6445 	case LPFC_SLI_EVENT_TYPE_NORM_TEMP:
6446 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
6447 		temp_event_data.event_code = LPFC_NORMAL_TEMP;
6448 		temp_event_data.data = (uint32_t)acqe_sli->event_data1;
6449 
6450 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI | LOG_LDS_EVENT,
6451 				"3191 Normal Temperature:%d Celsius - Port Name %c\n",
6452 				acqe_sli->event_data1, port_name);
6453 
6454 		shost = lpfc_shost_from_vport(phba->pport);
6455 		fc_host_post_vendor_event(shost, fc_get_event_number(),
6456 					  sizeof(temp_event_data),
6457 					  (char *)&temp_event_data,
6458 					  SCSI_NL_VID_TYPE_PCI
6459 					  | PCI_VENDOR_ID_EMULEX);
6460 		break;
6461 	case LPFC_SLI_EVENT_TYPE_MISCONFIGURED:
6462 		misconfigured = (struct lpfc_acqe_misconfigured_event *)
6463 					&acqe_sli->event_data1;
6464 
6465 		/* fetch the status for this port */
6466 		switch (phba->sli4_hba.lnk_info.lnk_no) {
6467 		case LPFC_LINK_NUMBER_0:
6468 			status = bf_get(lpfc_sli_misconfigured_port0_state,
6469 					&misconfigured->theEvent);
6470 			operational = bf_get(lpfc_sli_misconfigured_port0_op,
6471 					&misconfigured->theEvent);
6472 			break;
6473 		case LPFC_LINK_NUMBER_1:
6474 			status = bf_get(lpfc_sli_misconfigured_port1_state,
6475 					&misconfigured->theEvent);
6476 			operational = bf_get(lpfc_sli_misconfigured_port1_op,
6477 					&misconfigured->theEvent);
6478 			break;
6479 		case LPFC_LINK_NUMBER_2:
6480 			status = bf_get(lpfc_sli_misconfigured_port2_state,
6481 					&misconfigured->theEvent);
6482 			operational = bf_get(lpfc_sli_misconfigured_port2_op,
6483 					&misconfigured->theEvent);
6484 			break;
6485 		case LPFC_LINK_NUMBER_3:
6486 			status = bf_get(lpfc_sli_misconfigured_port3_state,
6487 					&misconfigured->theEvent);
6488 			operational = bf_get(lpfc_sli_misconfigured_port3_op,
6489 					&misconfigured->theEvent);
6490 			break;
6491 		default:
6492 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6493 					"3296 "
6494 					"LPFC_SLI_EVENT_TYPE_MISCONFIGURED "
6495 					"event: Invalid link %d",
6496 					phba->sli4_hba.lnk_info.lnk_no);
6497 			return;
6498 		}
6499 
6500 		/* Skip if optic state unchanged */
6501 		if (phba->sli4_hba.lnk_info.optic_state == status)
6502 			return;
6503 
6504 		switch (status) {
6505 		case LPFC_SLI_EVENT_STATUS_VALID:
6506 			sprintf(message, "Physical Link is functional");
6507 			break;
6508 		case LPFC_SLI_EVENT_STATUS_NOT_PRESENT:
6509 			sprintf(message, "Optics faulted/incorrectly "
6510 				"installed/not installed - Reseat optics, "
6511 				"if issue not resolved, replace.");
6512 			break;
6513 		case LPFC_SLI_EVENT_STATUS_WRONG_TYPE:
6514 			sprintf(message,
6515 				"Optics of two types installed - Remove one "
6516 				"optic or install matching pair of optics.");
6517 			break;
6518 		case LPFC_SLI_EVENT_STATUS_UNSUPPORTED:
6519 			sprintf(message, "Incompatible optics - Replace with "
6520 				"compatible optics for card to function.");
6521 			break;
6522 		case LPFC_SLI_EVENT_STATUS_UNQUALIFIED:
6523 			sprintf(message, "Unqualified optics - Replace with "
6524 				"Avago optics for Warranty and Technical "
6525 				"Support - Link is%s operational",
6526 				(operational) ? " not" : "");
6527 			break;
6528 		case LPFC_SLI_EVENT_STATUS_UNCERTIFIED:
6529 			sprintf(message, "Uncertified optics - Replace with "
6530 				"Avago-certified optics to enable link "
6531 				"operation - Link is%s operational",
6532 				(operational) ? " not" : "");
6533 			break;
6534 		default:
6535 			/* firmware is reporting a status we don't know about */
6536 			sprintf(message, "Unknown event status x%02x", status);
6537 			break;
6538 		}
6539 
6540 		/* Issue READ_CONFIG mbox command to refresh supported speeds */
6541 		rc = lpfc_sli4_read_config(phba);
6542 		if (rc) {
6543 			phba->lmt = 0;
6544 			lpfc_printf_log(phba, KERN_ERR,
6545 					LOG_TRACE_EVENT,
6546 					"3194 Unable to retrieve supported "
6547 					"speeds, rc = 0x%x\n", rc);
6548 		}
6549 		rc = lpfc_sli4_refresh_params(phba);
6550 		if (rc) {
6551 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6552 					"3174 Unable to update pls support, "
6553 					"rc x%x\n", rc);
6554 		}
6555 		vports = lpfc_create_vport_work_array(phba);
6556 		if (vports != NULL) {
6557 			for (i = 0; i <= phba->max_vports && vports[i] != NULL;
6558 					i++) {
6559 				shost = lpfc_shost_from_vport(vports[i]);
6560 				lpfc_host_supported_speeds_set(shost);
6561 			}
6562 		}
6563 		lpfc_destroy_vport_work_array(phba, vports);
6564 
6565 		phba->sli4_hba.lnk_info.optic_state = status;
6566 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6567 				"3176 Port Name %c %s\n", port_name, message);
6568 		break;
6569 	case LPFC_SLI_EVENT_TYPE_REMOTE_DPORT:
6570 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6571 				"3192 Remote DPort Test Initiated - "
6572 				"Event Data1:x%08x Event Data2: x%08x\n",
6573 				acqe_sli->event_data1, acqe_sli->event_data2);
6574 		break;
6575 	case LPFC_SLI_EVENT_TYPE_PORT_PARAMS_CHG:
6576 		/* Call FW to obtain active parms */
6577 		lpfc_sli4_cgn_parm_chg_evt(phba);
6578 		break;
6579 	case LPFC_SLI_EVENT_TYPE_MISCONF_FAWWN:
6580 		/* Misconfigured WWN. Reports that the SLI Port is configured
6581 		 * to use FA-WWN, but the attached device doesn’t support it.
6582 		 * Event Data1 - N.A, Event Data2 - N.A
6583 		 * This event only happens on the physical port.
6584 		 */
6585 		lpfc_log_msg(phba, KERN_WARNING, LOG_SLI | LOG_DISCOVERY,
6586 			     "2699 Misconfigured FA-PWWN - Attached device "
6587 			     "does not support FA-PWWN\n");
6588 		phba->sli4_hba.fawwpn_flag &= ~LPFC_FAWWPN_FABRIC;
6589 		memset(phba->pport->fc_portname.u.wwn, 0,
6590 		       sizeof(struct lpfc_name));
6591 		break;
6592 	case LPFC_SLI_EVENT_TYPE_EEPROM_FAILURE:
6593 		/* EEPROM failure. No driver action is required */
6594 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6595 			     "2518 EEPROM failure - "
6596 			     "Event Data1: x%08x Event Data2: x%08x\n",
6597 			     acqe_sli->event_data1, acqe_sli->event_data2);
6598 		break;
6599 	case LPFC_SLI_EVENT_TYPE_CGN_SIGNAL:
6600 		if (phba->cmf_active_mode == LPFC_CFG_OFF)
6601 			break;
6602 		cgn_signal = (struct lpfc_acqe_cgn_signal *)
6603 					&acqe_sli->event_data1;
6604 		phba->cgn_acqe_cnt++;
6605 
6606 		cnt = bf_get(lpfc_warn_acqe, cgn_signal);
6607 		atomic64_add(cnt, &phba->cgn_acqe_stat.warn);
6608 		atomic64_add(cgn_signal->alarm_cnt, &phba->cgn_acqe_stat.alarm);
6609 
6610 		/* no threshold for CMF, even 1 signal will trigger an event */
6611 
6612 		/* Alarm overrides warning, so check that first */
6613 		if (cgn_signal->alarm_cnt) {
6614 			if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
6615 				/* Keep track of alarm cnt for CMF_SYNC_WQE */
6616 				atomic_add(cgn_signal->alarm_cnt,
6617 					   &phba->cgn_sync_alarm_cnt);
6618 			}
6619 		} else if (cnt) {
6620 			/* signal action needs to be taken */
6621 			if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY ||
6622 			    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
6623 				/* Keep track of warning cnt for CMF_SYNC_WQE */
6624 				atomic_add(cnt, &phba->cgn_sync_warn_cnt);
6625 			}
6626 		}
6627 		break;
6628 	case LPFC_SLI_EVENT_TYPE_RD_SIGNAL:
6629 		/* May be accompanied by a temperature event */
6630 		lpfc_printf_log(phba, KERN_INFO,
6631 				LOG_SLI | LOG_LINK_EVENT | LOG_LDS_EVENT,
6632 				"2902 Remote Degrade Signaling: x%08x x%08x "
6633 				"x%08x\n",
6634 				acqe_sli->event_data1, acqe_sli->event_data2,
6635 				acqe_sli->event_data3);
6636 		break;
6637 	case LPFC_SLI_EVENT_TYPE_RESET_CM_STATS:
6638 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
6639 				"2905 Reset CM statistics\n");
6640 		lpfc_sli4_async_cmstat_evt(phba);
6641 		break;
6642 	default:
6643 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6644 				"3193 Unrecognized SLI event, type: 0x%x",
6645 				evt_type);
6646 		break;
6647 	}
6648 }
6649 
6650 /**
6651  * lpfc_sli4_perform_vport_cvl - Perform clear virtual link on a vport
6652  * @vport: pointer to vport data structure.
6653  *
6654  * This routine is to perform Clear Virtual Link (CVL) on a vport in
6655  * response to a CVL event.
6656  *
6657  * Return the pointer to the ndlp with the vport if successful, otherwise
6658  * return NULL.
6659  **/
6660 static struct lpfc_nodelist *
6661 lpfc_sli4_perform_vport_cvl(struct lpfc_vport *vport)
6662 {
6663 	struct lpfc_nodelist *ndlp;
6664 	struct Scsi_Host *shost;
6665 	struct lpfc_hba *phba;
6666 
6667 	if (!vport)
6668 		return NULL;
6669 	phba = vport->phba;
6670 	if (!phba)
6671 		return NULL;
6672 	ndlp = lpfc_findnode_did(vport, Fabric_DID);
6673 	if (!ndlp) {
6674 		/* Cannot find existing Fabric ndlp, so allocate a new one */
6675 		ndlp = lpfc_nlp_init(vport, Fabric_DID);
6676 		if (!ndlp)
6677 			return NULL;
6678 		/* Set the node type */
6679 		ndlp->nlp_type |= NLP_FABRIC;
6680 		/* Put ndlp onto node list */
6681 		lpfc_enqueue_node(vport, ndlp);
6682 	}
6683 	if ((phba->pport->port_state < LPFC_FLOGI) &&
6684 		(phba->pport->port_state != LPFC_VPORT_FAILED))
6685 		return NULL;
6686 	/* If virtual link is not yet instantiated ignore CVL */
6687 	if ((vport != phba->pport) && (vport->port_state < LPFC_FDISC)
6688 		&& (vport->port_state != LPFC_VPORT_FAILED))
6689 		return NULL;
6690 	shost = lpfc_shost_from_vport(vport);
6691 	if (!shost)
6692 		return NULL;
6693 	lpfc_linkdown_port(vport);
6694 	lpfc_cleanup_pending_mbox(vport);
6695 	set_bit(FC_VPORT_CVL_RCVD, &vport->fc_flag);
6696 
6697 	return ndlp;
6698 }
6699 
6700 /**
6701  * lpfc_sli4_perform_all_vport_cvl - Perform clear virtual link on all vports
6702  * @phba: pointer to lpfc hba data structure.
6703  *
6704  * This routine is to perform Clear Virtual Link (CVL) on all vports in
6705  * response to a FCF dead event.
6706  **/
6707 static void
6708 lpfc_sli4_perform_all_vport_cvl(struct lpfc_hba *phba)
6709 {
6710 	struct lpfc_vport **vports;
6711 	int i;
6712 
6713 	vports = lpfc_create_vport_work_array(phba);
6714 	if (vports)
6715 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++)
6716 			lpfc_sli4_perform_vport_cvl(vports[i]);
6717 	lpfc_destroy_vport_work_array(phba, vports);
6718 }
6719 
6720 /**
6721  * lpfc_sli4_async_fip_evt - Process the asynchronous FCoE FIP event
6722  * @phba: pointer to lpfc hba data structure.
6723  * @acqe_fip: pointer to the async fcoe completion queue entry.
6724  *
6725  * This routine is to handle the SLI4 asynchronous fcoe event.
6726  **/
6727 static void
6728 lpfc_sli4_async_fip_evt(struct lpfc_hba *phba,
6729 			struct lpfc_acqe_fip *acqe_fip)
6730 {
6731 	uint8_t event_type = bf_get(lpfc_trailer_type, acqe_fip);
6732 	int rc;
6733 	struct lpfc_vport *vport;
6734 	struct lpfc_nodelist *ndlp;
6735 	int active_vlink_present;
6736 	struct lpfc_vport **vports;
6737 	int i;
6738 
6739 	phba->fc_eventTag = acqe_fip->event_tag;
6740 	phba->fcoe_eventtag = acqe_fip->event_tag;
6741 	switch (event_type) {
6742 	case LPFC_FIP_EVENT_TYPE_NEW_FCF:
6743 	case LPFC_FIP_EVENT_TYPE_FCF_PARAM_MOD:
6744 		if (event_type == LPFC_FIP_EVENT_TYPE_NEW_FCF)
6745 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6746 					"2546 New FCF event, evt_tag:x%x, "
6747 					"index:x%x\n",
6748 					acqe_fip->event_tag,
6749 					acqe_fip->index);
6750 		else
6751 			lpfc_printf_log(phba, KERN_WARNING, LOG_FIP |
6752 					LOG_DISCOVERY,
6753 					"2788 FCF param modified event, "
6754 					"evt_tag:x%x, index:x%x\n",
6755 					acqe_fip->event_tag,
6756 					acqe_fip->index);
6757 		if (phba->fcf.fcf_flag & FCF_DISCOVERY) {
6758 			/*
6759 			 * During period of FCF discovery, read the FCF
6760 			 * table record indexed by the event to update
6761 			 * FCF roundrobin failover eligible FCF bmask.
6762 			 */
6763 			lpfc_printf_log(phba, KERN_INFO, LOG_FIP |
6764 					LOG_DISCOVERY,
6765 					"2779 Read FCF (x%x) for updating "
6766 					"roundrobin FCF failover bmask\n",
6767 					acqe_fip->index);
6768 			rc = lpfc_sli4_read_fcf_rec(phba, acqe_fip->index);
6769 		}
6770 
6771 		/* If the FCF discovery is in progress, do nothing. */
6772 		if (test_bit(FCF_TS_INPROG, &phba->hba_flag))
6773 			break;
6774 		spin_lock_irq(&phba->hbalock);
6775 		/* If fast FCF failover rescan event is pending, do nothing */
6776 		if (phba->fcf.fcf_flag & (FCF_REDISC_EVT | FCF_REDISC_PEND)) {
6777 			spin_unlock_irq(&phba->hbalock);
6778 			break;
6779 		}
6780 
6781 		/* If the FCF has been in discovered state, do nothing. */
6782 		if (phba->fcf.fcf_flag & FCF_SCAN_DONE) {
6783 			spin_unlock_irq(&phba->hbalock);
6784 			break;
6785 		}
6786 		spin_unlock_irq(&phba->hbalock);
6787 
6788 		/* Otherwise, scan the entire FCF table and re-discover SAN */
6789 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
6790 				"2770 Start FCF table scan per async FCF "
6791 				"event, evt_tag:x%x, index:x%x\n",
6792 				acqe_fip->event_tag, acqe_fip->index);
6793 		rc = lpfc_sli4_fcf_scan_read_fcf_rec(phba,
6794 						     LPFC_FCOE_FCF_GET_FIRST);
6795 		if (rc)
6796 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6797 					"2547 Issue FCF scan read FCF mailbox "
6798 					"command failed (x%x)\n", rc);
6799 		break;
6800 
6801 	case LPFC_FIP_EVENT_TYPE_FCF_TABLE_FULL:
6802 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6803 				"2548 FCF Table full count 0x%x tag 0x%x\n",
6804 				bf_get(lpfc_acqe_fip_fcf_count, acqe_fip),
6805 				acqe_fip->event_tag);
6806 		break;
6807 
6808 	case LPFC_FIP_EVENT_TYPE_FCF_DEAD:
6809 		phba->fcoe_cvl_eventtag = acqe_fip->event_tag;
6810 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6811 				"2549 FCF (x%x) disconnected from network, "
6812 				 "tag:x%x\n", acqe_fip->index,
6813 				 acqe_fip->event_tag);
6814 		/*
6815 		 * If we are in the middle of FCF failover process, clear
6816 		 * the corresponding FCF bit in the roundrobin bitmap.
6817 		 */
6818 		spin_lock_irq(&phba->hbalock);
6819 		if ((phba->fcf.fcf_flag & FCF_DISCOVERY) &&
6820 		    (phba->fcf.current_rec.fcf_indx != acqe_fip->index)) {
6821 			spin_unlock_irq(&phba->hbalock);
6822 			/* Update FLOGI FCF failover eligible FCF bmask */
6823 			lpfc_sli4_fcf_rr_index_clear(phba, acqe_fip->index);
6824 			break;
6825 		}
6826 		spin_unlock_irq(&phba->hbalock);
6827 
6828 		/* If the event is not for currently used fcf do nothing */
6829 		if (phba->fcf.current_rec.fcf_indx != acqe_fip->index)
6830 			break;
6831 
6832 		/*
6833 		 * Otherwise, request the port to rediscover the entire FCF
6834 		 * table for a fast recovery from case that the current FCF
6835 		 * is no longer valid as we are not in the middle of FCF
6836 		 * failover process already.
6837 		 */
6838 		spin_lock_irq(&phba->hbalock);
6839 		/* Mark the fast failover process in progress */
6840 		phba->fcf.fcf_flag |= FCF_DEAD_DISC;
6841 		spin_unlock_irq(&phba->hbalock);
6842 
6843 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
6844 				"2771 Start FCF fast failover process due to "
6845 				"FCF DEAD event: evt_tag:x%x, fcf_index:x%x "
6846 				"\n", acqe_fip->event_tag, acqe_fip->index);
6847 		rc = lpfc_sli4_redisc_fcf_table(phba);
6848 		if (rc) {
6849 			lpfc_printf_log(phba, KERN_ERR, LOG_FIP |
6850 					LOG_TRACE_EVENT,
6851 					"2772 Issue FCF rediscover mailbox "
6852 					"command failed, fail through to FCF "
6853 					"dead event\n");
6854 			spin_lock_irq(&phba->hbalock);
6855 			phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
6856 			spin_unlock_irq(&phba->hbalock);
6857 			/*
6858 			 * Last resort will fail over by treating this
6859 			 * as a link down to FCF registration.
6860 			 */
6861 			lpfc_sli4_fcf_dead_failthrough(phba);
6862 		} else {
6863 			/* Reset FCF roundrobin bmask for new discovery */
6864 			lpfc_sli4_clear_fcf_rr_bmask(phba);
6865 			/*
6866 			 * Handling fast FCF failover to a DEAD FCF event is
6867 			 * considered equalivant to receiving CVL to all vports.
6868 			 */
6869 			lpfc_sli4_perform_all_vport_cvl(phba);
6870 		}
6871 		break;
6872 	case LPFC_FIP_EVENT_TYPE_CVL:
6873 		phba->fcoe_cvl_eventtag = acqe_fip->event_tag;
6874 		lpfc_printf_log(phba, KERN_ERR,
6875 				LOG_TRACE_EVENT,
6876 			"2718 Clear Virtual Link Received for VPI 0x%x"
6877 			" tag 0x%x\n", acqe_fip->index, acqe_fip->event_tag);
6878 
6879 		vport = lpfc_find_vport_by_vpid(phba,
6880 						acqe_fip->index);
6881 		ndlp = lpfc_sli4_perform_vport_cvl(vport);
6882 		if (!ndlp)
6883 			break;
6884 		active_vlink_present = 0;
6885 
6886 		vports = lpfc_create_vport_work_array(phba);
6887 		if (vports) {
6888 			for (i = 0; i <= phba->max_vports && vports[i] != NULL;
6889 					i++) {
6890 				if (!test_bit(FC_VPORT_CVL_RCVD,
6891 					      &vports[i]->fc_flag) &&
6892 				    vports[i]->port_state > LPFC_FDISC) {
6893 					active_vlink_present = 1;
6894 					break;
6895 				}
6896 			}
6897 			lpfc_destroy_vport_work_array(phba, vports);
6898 		}
6899 
6900 		/*
6901 		 * Don't re-instantiate if vport is marked for deletion.
6902 		 * If we are here first then vport_delete is going to wait
6903 		 * for discovery to complete.
6904 		 */
6905 		if (!test_bit(FC_UNLOADING, &vport->load_flag) &&
6906 		    active_vlink_present) {
6907 			/*
6908 			 * If there are other active VLinks present,
6909 			 * re-instantiate the Vlink using FDISC.
6910 			 */
6911 			mod_timer(&ndlp->nlp_delayfunc,
6912 				  jiffies + msecs_to_jiffies(1000));
6913 			set_bit(NLP_DELAY_TMO, &ndlp->nlp_flag);
6914 			ndlp->nlp_last_elscmd = ELS_CMD_FDISC;
6915 			vport->port_state = LPFC_FDISC;
6916 		} else {
6917 			/*
6918 			 * Otherwise, we request port to rediscover
6919 			 * the entire FCF table for a fast recovery
6920 			 * from possible case that the current FCF
6921 			 * is no longer valid if we are not already
6922 			 * in the FCF failover process.
6923 			 */
6924 			spin_lock_irq(&phba->hbalock);
6925 			if (phba->fcf.fcf_flag & FCF_DISCOVERY) {
6926 				spin_unlock_irq(&phba->hbalock);
6927 				break;
6928 			}
6929 			/* Mark the fast failover process in progress */
6930 			phba->fcf.fcf_flag |= FCF_ACVL_DISC;
6931 			spin_unlock_irq(&phba->hbalock);
6932 			lpfc_printf_log(phba, KERN_INFO, LOG_FIP |
6933 					LOG_DISCOVERY,
6934 					"2773 Start FCF failover per CVL, "
6935 					"evt_tag:x%x\n", acqe_fip->event_tag);
6936 			rc = lpfc_sli4_redisc_fcf_table(phba);
6937 			if (rc) {
6938 				lpfc_printf_log(phba, KERN_ERR, LOG_FIP |
6939 						LOG_TRACE_EVENT,
6940 						"2774 Issue FCF rediscover "
6941 						"mailbox command failed, "
6942 						"through to CVL event\n");
6943 				spin_lock_irq(&phba->hbalock);
6944 				phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
6945 				spin_unlock_irq(&phba->hbalock);
6946 				/*
6947 				 * Last resort will be re-try on the
6948 				 * the current registered FCF entry.
6949 				 */
6950 				lpfc_retry_pport_discovery(phba);
6951 			} else
6952 				/*
6953 				 * Reset FCF roundrobin bmask for new
6954 				 * discovery.
6955 				 */
6956 				lpfc_sli4_clear_fcf_rr_bmask(phba);
6957 		}
6958 		break;
6959 	default:
6960 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6961 				"0288 Unknown FCoE event type 0x%x event tag "
6962 				"0x%x\n", event_type, acqe_fip->event_tag);
6963 		break;
6964 	}
6965 }
6966 
6967 /**
6968  * lpfc_sli4_async_dcbx_evt - Process the asynchronous dcbx event
6969  * @phba: pointer to lpfc hba data structure.
6970  * @acqe_dcbx: pointer to the async dcbx completion queue entry.
6971  *
6972  * This routine is to handle the SLI4 asynchronous dcbx event.
6973  **/
6974 static void
6975 lpfc_sli4_async_dcbx_evt(struct lpfc_hba *phba,
6976 			 struct lpfc_acqe_dcbx *acqe_dcbx)
6977 {
6978 	phba->fc_eventTag = acqe_dcbx->event_tag;
6979 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6980 			"0290 The SLI4 DCBX asynchronous event is not "
6981 			"handled yet\n");
6982 }
6983 
6984 /**
6985  * lpfc_sli4_async_grp5_evt - Process the asynchronous group5 event
6986  * @phba: pointer to lpfc hba data structure.
6987  * @acqe_grp5: pointer to the async grp5 completion queue entry.
6988  *
6989  * This routine is to handle the SLI4 asynchronous grp5 event. A grp5 event
6990  * is an asynchronous notified of a logical link speed change.  The Port
6991  * reports the logical link speed in units of 10Mbps.
6992  **/
6993 static void
6994 lpfc_sli4_async_grp5_evt(struct lpfc_hba *phba,
6995 			 struct lpfc_acqe_grp5 *acqe_grp5)
6996 {
6997 	uint16_t prev_ll_spd;
6998 
6999 	phba->fc_eventTag = acqe_grp5->event_tag;
7000 	phba->fcoe_eventtag = acqe_grp5->event_tag;
7001 	prev_ll_spd = phba->sli4_hba.link_state.logical_speed;
7002 	phba->sli4_hba.link_state.logical_speed =
7003 		(bf_get(lpfc_acqe_grp5_llink_spd, acqe_grp5)) * 10;
7004 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
7005 			"2789 GRP5 Async Event: Updating logical link speed "
7006 			"from %dMbps to %dMbps\n", prev_ll_spd,
7007 			phba->sli4_hba.link_state.logical_speed);
7008 }
7009 
7010 /**
7011  * lpfc_sli4_async_cmstat_evt - Process the asynchronous cmstat event
7012  * @phba: pointer to lpfc hba data structure.
7013  *
7014  * This routine is to handle the SLI4 asynchronous cmstat event. A cmstat event
7015  * is an asynchronous notification of a request to reset CM stats.
7016  **/
7017 static void
7018 lpfc_sli4_async_cmstat_evt(struct lpfc_hba *phba)
7019 {
7020 	if (!phba->cgn_i)
7021 		return;
7022 	lpfc_init_congestion_stat(phba);
7023 }
7024 
7025 /**
7026  * lpfc_cgn_params_val - Validate FW congestion parameters.
7027  * @phba: pointer to lpfc hba data structure.
7028  * @p_cfg_param: pointer to FW provided congestion parameters.
7029  *
7030  * This routine validates the congestion parameters passed
7031  * by the FW to the driver via an ACQE event.
7032  **/
7033 static void
7034 lpfc_cgn_params_val(struct lpfc_hba *phba, struct lpfc_cgn_param *p_cfg_param)
7035 {
7036 	spin_lock_irq(&phba->hbalock);
7037 
7038 	if (!lpfc_rangecheck(p_cfg_param->cgn_param_mode, LPFC_CFG_OFF,
7039 			     LPFC_CFG_MONITOR)) {
7040 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT,
7041 				"6225 CMF mode param out of range: %d\n",
7042 				 p_cfg_param->cgn_param_mode);
7043 		p_cfg_param->cgn_param_mode = LPFC_CFG_OFF;
7044 	}
7045 
7046 	spin_unlock_irq(&phba->hbalock);
7047 }
7048 
7049 static const char * const lpfc_cmf_mode_to_str[] = {
7050 	"OFF",
7051 	"MANAGED",
7052 	"MONITOR",
7053 };
7054 
7055 /**
7056  * lpfc_cgn_params_parse - Process a FW cong parm change event
7057  * @phba: pointer to lpfc hba data structure.
7058  * @p_cgn_param: pointer to a data buffer with the FW cong params.
7059  * @len: the size of pdata in bytes.
7060  *
7061  * This routine validates the congestion management buffer signature
7062  * from the FW, validates the contents and makes corrections for
7063  * valid, in-range values.  If the signature magic is correct and
7064  * after parameter validation, the contents are copied to the driver's
7065  * @phba structure. If the magic is incorrect, an error message is
7066  * logged.
7067  **/
7068 static void
7069 lpfc_cgn_params_parse(struct lpfc_hba *phba,
7070 		      struct lpfc_cgn_param *p_cgn_param, uint32_t len)
7071 {
7072 	struct lpfc_cgn_info *cp;
7073 	uint32_t crc, oldmode;
7074 	char acr_string[4] = {0};
7075 
7076 	/* Make sure the FW has encoded the correct magic number to
7077 	 * validate the congestion parameter in FW memory.
7078 	 */
7079 	if (p_cgn_param->cgn_param_magic == LPFC_CFG_PARAM_MAGIC_NUM) {
7080 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT | LOG_INIT,
7081 				"4668 FW cgn parm buffer data: "
7082 				"magic 0x%x version %d mode %d "
7083 				"level0 %d level1 %d "
7084 				"level2 %d byte13 %d "
7085 				"byte14 %d byte15 %d "
7086 				"byte11 %d byte12 %d activeMode %d\n",
7087 				p_cgn_param->cgn_param_magic,
7088 				p_cgn_param->cgn_param_version,
7089 				p_cgn_param->cgn_param_mode,
7090 				p_cgn_param->cgn_param_level0,
7091 				p_cgn_param->cgn_param_level1,
7092 				p_cgn_param->cgn_param_level2,
7093 				p_cgn_param->byte13,
7094 				p_cgn_param->byte14,
7095 				p_cgn_param->byte15,
7096 				p_cgn_param->byte11,
7097 				p_cgn_param->byte12,
7098 				phba->cmf_active_mode);
7099 
7100 		oldmode = phba->cmf_active_mode;
7101 
7102 		/* Any parameters out of range are corrected to defaults
7103 		 * by this routine.  No need to fail.
7104 		 */
7105 		lpfc_cgn_params_val(phba, p_cgn_param);
7106 
7107 		/* Parameters are verified, move them into driver storage */
7108 		spin_lock_irq(&phba->hbalock);
7109 		memcpy(&phba->cgn_p, p_cgn_param,
7110 		       sizeof(struct lpfc_cgn_param));
7111 
7112 		/* Update parameters in congestion info buffer now */
7113 		if (phba->cgn_i) {
7114 			cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
7115 			cp->cgn_info_mode = phba->cgn_p.cgn_param_mode;
7116 			cp->cgn_info_level0 = phba->cgn_p.cgn_param_level0;
7117 			cp->cgn_info_level1 = phba->cgn_p.cgn_param_level1;
7118 			cp->cgn_info_level2 = phba->cgn_p.cgn_param_level2;
7119 			crc = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ,
7120 						  LPFC_CGN_CRC32_SEED);
7121 			cp->cgn_info_crc = cpu_to_le32(crc);
7122 		}
7123 		spin_unlock_irq(&phba->hbalock);
7124 
7125 		phba->cmf_active_mode = phba->cgn_p.cgn_param_mode;
7126 
7127 		switch (oldmode) {
7128 		case LPFC_CFG_OFF:
7129 			if (phba->cgn_p.cgn_param_mode != LPFC_CFG_OFF) {
7130 				/* Turning CMF on */
7131 				lpfc_cmf_start(phba);
7132 
7133 				if (phba->link_state >= LPFC_LINK_UP) {
7134 					phba->cgn_reg_fpin =
7135 						phba->cgn_init_reg_fpin;
7136 					phba->cgn_reg_signal =
7137 						phba->cgn_init_reg_signal;
7138 					lpfc_issue_els_edc(phba->pport, 0);
7139 				}
7140 			}
7141 			break;
7142 		case LPFC_CFG_MANAGED:
7143 			switch (phba->cgn_p.cgn_param_mode) {
7144 			case LPFC_CFG_OFF:
7145 				/* Turning CMF off */
7146 				lpfc_cmf_stop(phba);
7147 				if (phba->link_state >= LPFC_LINK_UP)
7148 					lpfc_issue_els_edc(phba->pport, 0);
7149 				break;
7150 			case LPFC_CFG_MONITOR:
7151 				phba->cmf_max_bytes_per_interval =
7152 					phba->cmf_link_byte_count;
7153 
7154 				/* Resume blocked IO - unblock on workqueue */
7155 				queue_work(phba->wq,
7156 					   &phba->unblock_request_work);
7157 				break;
7158 			}
7159 			break;
7160 		case LPFC_CFG_MONITOR:
7161 			switch (phba->cgn_p.cgn_param_mode) {
7162 			case LPFC_CFG_OFF:
7163 				/* Turning CMF off */
7164 				lpfc_cmf_stop(phba);
7165 				if (phba->link_state >= LPFC_LINK_UP)
7166 					lpfc_issue_els_edc(phba->pport, 0);
7167 				break;
7168 			case LPFC_CFG_MANAGED:
7169 				lpfc_cmf_signal_init(phba);
7170 				break;
7171 			}
7172 			break;
7173 		}
7174 		if (oldmode != LPFC_CFG_OFF ||
7175 		    oldmode != phba->cgn_p.cgn_param_mode) {
7176 			if (phba->cgn_p.cgn_param_mode == LPFC_CFG_MANAGED)
7177 				scnprintf(acr_string, sizeof(acr_string), "%u",
7178 					  phba->cgn_p.cgn_param_level0);
7179 			else
7180 				scnprintf(acr_string, sizeof(acr_string), "NA");
7181 
7182 			dev_info(&phba->pcidev->dev, "%d: "
7183 				 "4663 CMF: Mode %s acr %s\n",
7184 				 phba->brd_no,
7185 				 lpfc_cmf_mode_to_str
7186 				 [phba->cgn_p.cgn_param_mode],
7187 				 acr_string);
7188 		}
7189 	} else {
7190 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7191 				"4669 FW cgn parm buf wrong magic 0x%x "
7192 				"version %d\n", p_cgn_param->cgn_param_magic,
7193 				p_cgn_param->cgn_param_version);
7194 	}
7195 }
7196 
7197 /**
7198  * lpfc_sli4_cgn_params_read - Read and Validate FW congestion parameters.
7199  * @phba: pointer to lpfc hba data structure.
7200  *
7201  * This routine issues a read_object mailbox command to
7202  * get the congestion management parameters from the FW
7203  * parses it and updates the driver maintained values.
7204  *
7205  * Returns
7206  *  0     if the object was empty
7207  *  -Eval if an error was encountered
7208  *  Count if bytes were read from object
7209  **/
7210 int
7211 lpfc_sli4_cgn_params_read(struct lpfc_hba *phba)
7212 {
7213 	int ret = 0;
7214 	struct lpfc_cgn_param *p_cgn_param = NULL;
7215 	u32 *pdata = NULL;
7216 	u32 len = 0;
7217 
7218 	/* Find out if the FW has a new set of congestion parameters. */
7219 	len = sizeof(struct lpfc_cgn_param);
7220 	pdata = kzalloc(len, GFP_KERNEL);
7221 	if (!pdata)
7222 		return -ENOMEM;
7223 	ret = lpfc_read_object(phba, (char *)LPFC_PORT_CFG_NAME,
7224 			       pdata, len);
7225 
7226 	/* 0 means no data.  A negative means error.  A positive means
7227 	 * bytes were copied.
7228 	 */
7229 	if (!ret) {
7230 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7231 				"4670 CGN RD OBJ returns no data\n");
7232 		goto rd_obj_err;
7233 	} else if (ret < 0) {
7234 		/* Some error.  Just exit and return it to the caller.*/
7235 		goto rd_obj_err;
7236 	}
7237 
7238 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT | LOG_INIT,
7239 			"6234 READ CGN PARAMS Successful %d\n", len);
7240 
7241 	/* Parse data pointer over len and update the phba congestion
7242 	 * parameters with values passed back.  The receive rate values
7243 	 * may have been altered in FW, but take no action here.
7244 	 */
7245 	p_cgn_param = (struct lpfc_cgn_param *)pdata;
7246 	lpfc_cgn_params_parse(phba, p_cgn_param, len);
7247 
7248  rd_obj_err:
7249 	kfree(pdata);
7250 	return ret;
7251 }
7252 
7253 /**
7254  * lpfc_sli4_cgn_parm_chg_evt - Process a FW congestion param change event
7255  * @phba: pointer to lpfc hba data structure.
7256  *
7257  * The FW generated Async ACQE SLI event calls this routine when
7258  * the event type is an SLI Internal Port Event and the Event Code
7259  * indicates a change to the FW maintained congestion parameters.
7260  *
7261  * This routine executes a Read_Object mailbox call to obtain the
7262  * current congestion parameters maintained in FW and corrects
7263  * the driver's active congestion parameters.
7264  *
7265  * The acqe event is not passed because there is no further data
7266  * required.
7267  *
7268  * Returns nonzero error if event processing encountered an error.
7269  * Zero otherwise for success.
7270  **/
7271 static int
7272 lpfc_sli4_cgn_parm_chg_evt(struct lpfc_hba *phba)
7273 {
7274 	int ret = 0;
7275 
7276 	if (!phba->sli4_hba.pc_sli4_params.cmf) {
7277 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7278 				"4664 Cgn Evt when E2E off. Drop event\n");
7279 		return -EACCES;
7280 	}
7281 
7282 	/* If the event is claiming an empty object, it's ok.  A write
7283 	 * could have cleared it.  Only error is a negative return
7284 	 * status.
7285 	 */
7286 	ret = lpfc_sli4_cgn_params_read(phba);
7287 	if (ret < 0) {
7288 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7289 				"4667 Error reading Cgn Params (%d)\n",
7290 				ret);
7291 	} else if (!ret) {
7292 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7293 				"4673 CGN Event empty object.\n");
7294 	}
7295 	return ret;
7296 }
7297 
7298 /**
7299  * lpfc_sli4_async_event_proc - Process all the pending asynchronous event
7300  * @phba: pointer to lpfc hba data structure.
7301  *
7302  * This routine is invoked by the worker thread to process all the pending
7303  * SLI4 asynchronous events.
7304  **/
7305 void lpfc_sli4_async_event_proc(struct lpfc_hba *phba)
7306 {
7307 	struct lpfc_cq_event *cq_event;
7308 	unsigned long iflags;
7309 
7310 	/* First, declare the async event has been handled */
7311 	clear_bit(ASYNC_EVENT, &phba->hba_flag);
7312 
7313 	/* Now, handle all the async events */
7314 	spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
7315 	while (!list_empty(&phba->sli4_hba.sp_asynce_work_queue)) {
7316 		list_remove_head(&phba->sli4_hba.sp_asynce_work_queue,
7317 				 cq_event, struct lpfc_cq_event, list);
7318 		spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock,
7319 				       iflags);
7320 
7321 		/* Process the asynchronous event */
7322 		switch (bf_get(lpfc_trailer_code, &cq_event->cqe.mcqe_cmpl)) {
7323 		case LPFC_TRAILER_CODE_LINK:
7324 			lpfc_sli4_async_link_evt(phba,
7325 						 &cq_event->cqe.acqe_link);
7326 			break;
7327 		case LPFC_TRAILER_CODE_FCOE:
7328 			lpfc_sli4_async_fip_evt(phba, &cq_event->cqe.acqe_fip);
7329 			break;
7330 		case LPFC_TRAILER_CODE_DCBX:
7331 			lpfc_sli4_async_dcbx_evt(phba,
7332 						 &cq_event->cqe.acqe_dcbx);
7333 			break;
7334 		case LPFC_TRAILER_CODE_GRP5:
7335 			lpfc_sli4_async_grp5_evt(phba,
7336 						 &cq_event->cqe.acqe_grp5);
7337 			break;
7338 		case LPFC_TRAILER_CODE_FC:
7339 			lpfc_sli4_async_fc_evt(phba, &cq_event->cqe.acqe_fc);
7340 			break;
7341 		case LPFC_TRAILER_CODE_SLI:
7342 			lpfc_sli4_async_sli_evt(phba, &cq_event->cqe.acqe_sli);
7343 			break;
7344 		default:
7345 			lpfc_printf_log(phba, KERN_ERR,
7346 					LOG_TRACE_EVENT,
7347 					"1804 Invalid asynchronous event code: "
7348 					"x%x\n", bf_get(lpfc_trailer_code,
7349 					&cq_event->cqe.mcqe_cmpl));
7350 			break;
7351 		}
7352 
7353 		/* Free the completion event processed to the free pool */
7354 		lpfc_sli4_cq_event_release(phba, cq_event);
7355 		spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
7356 	}
7357 	spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock, iflags);
7358 }
7359 
7360 /**
7361  * lpfc_sli4_fcf_redisc_event_proc - Process fcf table rediscovery event
7362  * @phba: pointer to lpfc hba data structure.
7363  *
7364  * This routine is invoked by the worker thread to process FCF table
7365  * rediscovery pending completion event.
7366  **/
7367 void lpfc_sli4_fcf_redisc_event_proc(struct lpfc_hba *phba)
7368 {
7369 	int rc;
7370 
7371 	spin_lock_irq(&phba->hbalock);
7372 	/* Clear FCF rediscovery timeout event */
7373 	phba->fcf.fcf_flag &= ~FCF_REDISC_EVT;
7374 	/* Clear driver fast failover FCF record flag */
7375 	phba->fcf.failover_rec.flag = 0;
7376 	/* Set state for FCF fast failover */
7377 	phba->fcf.fcf_flag |= FCF_REDISC_FOV;
7378 	spin_unlock_irq(&phba->hbalock);
7379 
7380 	/* Scan FCF table from the first entry to re-discover SAN */
7381 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
7382 			"2777 Start post-quiescent FCF table scan\n");
7383 	rc = lpfc_sli4_fcf_scan_read_fcf_rec(phba, LPFC_FCOE_FCF_GET_FIRST);
7384 	if (rc)
7385 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7386 				"2747 Issue FCF scan read FCF mailbox "
7387 				"command failed 0x%x\n", rc);
7388 }
7389 
7390 /**
7391  * lpfc_api_table_setup - Set up per hba pci-device group func api jump table
7392  * @phba: pointer to lpfc hba data structure.
7393  * @dev_grp: The HBA PCI-Device group number.
7394  *
7395  * This routine is invoked to set up the per HBA PCI-Device group function
7396  * API jump table entries.
7397  *
7398  * Return: 0 if success, otherwise -ENODEV
7399  **/
7400 int
7401 lpfc_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
7402 {
7403 	int rc;
7404 
7405 	/* Set up lpfc PCI-device group */
7406 	phba->pci_dev_grp = dev_grp;
7407 
7408 	/* The LPFC_PCI_DEV_OC uses SLI4 */
7409 	if (dev_grp == LPFC_PCI_DEV_OC)
7410 		phba->sli_rev = LPFC_SLI_REV4;
7411 
7412 	/* Set up device INIT API function jump table */
7413 	rc = lpfc_init_api_table_setup(phba, dev_grp);
7414 	if (rc)
7415 		return -ENODEV;
7416 	/* Set up SCSI API function jump table */
7417 	rc = lpfc_scsi_api_table_setup(phba, dev_grp);
7418 	if (rc)
7419 		return -ENODEV;
7420 	/* Set up SLI API function jump table */
7421 	rc = lpfc_sli_api_table_setup(phba, dev_grp);
7422 	if (rc)
7423 		return -ENODEV;
7424 	/* Set up MBOX API function jump table */
7425 	rc = lpfc_mbox_api_table_setup(phba, dev_grp);
7426 	if (rc)
7427 		return -ENODEV;
7428 
7429 	return 0;
7430 }
7431 
7432 /**
7433  * lpfc_log_intr_mode - Log the active interrupt mode
7434  * @phba: pointer to lpfc hba data structure.
7435  * @intr_mode: active interrupt mode adopted.
7436  *
7437  * This routine it invoked to log the currently used active interrupt mode
7438  * to the device.
7439  **/
7440 static void lpfc_log_intr_mode(struct lpfc_hba *phba, uint32_t intr_mode)
7441 {
7442 	switch (intr_mode) {
7443 	case 0:
7444 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7445 				"0470 Enable INTx interrupt mode.\n");
7446 		break;
7447 	case 1:
7448 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7449 				"0481 Enabled MSI interrupt mode.\n");
7450 		break;
7451 	case 2:
7452 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7453 				"0480 Enabled MSI-X interrupt mode.\n");
7454 		break;
7455 	default:
7456 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7457 				"0482 Illegal interrupt mode.\n");
7458 		break;
7459 	}
7460 	return;
7461 }
7462 
7463 /**
7464  * lpfc_enable_pci_dev - Enable a generic PCI device.
7465  * @phba: pointer to lpfc hba data structure.
7466  *
7467  * This routine is invoked to enable the PCI device that is common to all
7468  * PCI devices.
7469  *
7470  * Return codes
7471  * 	0 - successful
7472  * 	other values - error
7473  **/
7474 static int
7475 lpfc_enable_pci_dev(struct lpfc_hba *phba)
7476 {
7477 	struct pci_dev *pdev;
7478 
7479 	/* Obtain PCI device reference */
7480 	if (!phba->pcidev)
7481 		goto out_error;
7482 	else
7483 		pdev = phba->pcidev;
7484 	/* Enable PCI device */
7485 	if (pci_enable_device_mem(pdev))
7486 		goto out_error;
7487 	/* Request PCI resource for the device */
7488 	if (pci_request_mem_regions(pdev, LPFC_DRIVER_NAME))
7489 		goto out_disable_device;
7490 	/* Set up device as PCI master and save state for EEH */
7491 	pci_set_master(pdev);
7492 	pci_try_set_mwi(pdev);
7493 	pci_save_state(pdev);
7494 
7495 	/* PCIe EEH recovery on powerpc platforms needs fundamental reset */
7496 	if (pci_is_pcie(pdev))
7497 		pdev->needs_freset = 1;
7498 
7499 	return 0;
7500 
7501 out_disable_device:
7502 	pci_disable_device(pdev);
7503 out_error:
7504 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7505 			"1401 Failed to enable pci device\n");
7506 	return -ENODEV;
7507 }
7508 
7509 /**
7510  * lpfc_disable_pci_dev - Disable a generic PCI device.
7511  * @phba: pointer to lpfc hba data structure.
7512  *
7513  * This routine is invoked to disable the PCI device that is common to all
7514  * PCI devices.
7515  **/
7516 static void
7517 lpfc_disable_pci_dev(struct lpfc_hba *phba)
7518 {
7519 	struct pci_dev *pdev;
7520 
7521 	/* Obtain PCI device reference */
7522 	if (!phba->pcidev)
7523 		return;
7524 	else
7525 		pdev = phba->pcidev;
7526 	/* Release PCI resource and disable PCI device */
7527 	pci_release_mem_regions(pdev);
7528 	pci_disable_device(pdev);
7529 
7530 	return;
7531 }
7532 
7533 /**
7534  * lpfc_reset_hba - Reset a hba
7535  * @phba: pointer to lpfc hba data structure.
7536  *
7537  * This routine is invoked to reset a hba device. It brings the HBA
7538  * offline, performs a board restart, and then brings the board back
7539  * online. The lpfc_offline calls lpfc_sli_hba_down which will clean up
7540  * on outstanding mailbox commands.
7541  **/
7542 void
7543 lpfc_reset_hba(struct lpfc_hba *phba)
7544 {
7545 	int rc = 0;
7546 
7547 	/* If resets are disabled then set error state and return. */
7548 	if (!phba->cfg_enable_hba_reset) {
7549 		phba->link_state = LPFC_HBA_ERROR;
7550 		return;
7551 	}
7552 
7553 	/* If not LPFC_SLI_ACTIVE, force all IO to be flushed */
7554 	if (phba->sli.sli_flag & LPFC_SLI_ACTIVE) {
7555 		lpfc_offline_prep(phba, LPFC_MBX_WAIT);
7556 	} else {
7557 		if (test_bit(MBX_TMO_ERR, &phba->bit_flags)) {
7558 			/* Perform a PCI function reset to start from clean */
7559 			rc = lpfc_pci_function_reset(phba);
7560 			lpfc_els_flush_all_cmd(phba);
7561 		}
7562 		lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
7563 		lpfc_sli_flush_io_rings(phba);
7564 	}
7565 	lpfc_offline(phba);
7566 	clear_bit(MBX_TMO_ERR, &phba->bit_flags);
7567 	if (unlikely(rc)) {
7568 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
7569 				"8888 PCI function reset failed rc %x\n",
7570 				rc);
7571 	} else {
7572 		lpfc_sli_brdrestart(phba);
7573 		lpfc_online(phba);
7574 		lpfc_unblock_mgmt_io(phba);
7575 	}
7576 }
7577 
7578 /**
7579  * lpfc_sli_sriov_nr_virtfn_get - Get the number of sr-iov virtual functions
7580  * @phba: pointer to lpfc hba data structure.
7581  *
7582  * This function enables the PCI SR-IOV virtual functions to a physical
7583  * function. It invokes the PCI SR-IOV api with the @nr_vfn provided to
7584  * enable the number of virtual functions to the physical function. As
7585  * not all devices support SR-IOV, the return code from the pci_enable_sriov()
7586  * API call does not considered as an error condition for most of the device.
7587  **/
7588 uint16_t
7589 lpfc_sli_sriov_nr_virtfn_get(struct lpfc_hba *phba)
7590 {
7591 	struct pci_dev *pdev = phba->pcidev;
7592 	uint16_t nr_virtfn;
7593 	int pos;
7594 
7595 	pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_SRIOV);
7596 	if (pos == 0)
7597 		return 0;
7598 
7599 	pci_read_config_word(pdev, pos + PCI_SRIOV_TOTAL_VF, &nr_virtfn);
7600 	return nr_virtfn;
7601 }
7602 
7603 /**
7604  * lpfc_sli_probe_sriov_nr_virtfn - Enable a number of sr-iov virtual functions
7605  * @phba: pointer to lpfc hba data structure.
7606  * @nr_vfn: number of virtual functions to be enabled.
7607  *
7608  * This function enables the PCI SR-IOV virtual functions to a physical
7609  * function. It invokes the PCI SR-IOV api with the @nr_vfn provided to
7610  * enable the number of virtual functions to the physical function. As
7611  * not all devices support SR-IOV, the return code from the pci_enable_sriov()
7612  * API call does not considered as an error condition for most of the device.
7613  **/
7614 int
7615 lpfc_sli_probe_sriov_nr_virtfn(struct lpfc_hba *phba, int nr_vfn)
7616 {
7617 	struct pci_dev *pdev = phba->pcidev;
7618 	uint16_t max_nr_vfn;
7619 	int rc;
7620 
7621 	max_nr_vfn = lpfc_sli_sriov_nr_virtfn_get(phba);
7622 	if (nr_vfn > max_nr_vfn) {
7623 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7624 				"3057 Requested vfs (%d) greater than "
7625 				"supported vfs (%d)", nr_vfn, max_nr_vfn);
7626 		return -EINVAL;
7627 	}
7628 
7629 	rc = pci_enable_sriov(pdev, nr_vfn);
7630 	if (rc) {
7631 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7632 				"2806 Failed to enable sriov on this device "
7633 				"with vfn number nr_vf:%d, rc:%d\n",
7634 				nr_vfn, rc);
7635 	} else
7636 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7637 				"2807 Successful enable sriov on this device "
7638 				"with vfn number nr_vf:%d\n", nr_vfn);
7639 	return rc;
7640 }
7641 
7642 static void
7643 lpfc_unblock_requests_work(struct work_struct *work)
7644 {
7645 	struct lpfc_hba *phba = container_of(work, struct lpfc_hba,
7646 					     unblock_request_work);
7647 
7648 	lpfc_unblock_requests(phba);
7649 }
7650 
7651 /**
7652  * lpfc_setup_driver_resource_phase1 - Phase1 etup driver internal resources.
7653  * @phba: pointer to lpfc hba data structure.
7654  *
7655  * This routine is invoked to set up the driver internal resources before the
7656  * device specific resource setup to support the HBA device it attached to.
7657  *
7658  * Return codes
7659  *	0 - successful
7660  *	other values - error
7661  **/
7662 static int
7663 lpfc_setup_driver_resource_phase1(struct lpfc_hba *phba)
7664 {
7665 	struct lpfc_sli *psli = &phba->sli;
7666 
7667 	/*
7668 	 * Driver resources common to all SLI revisions
7669 	 */
7670 	atomic_set(&phba->fast_event_count, 0);
7671 	atomic_set(&phba->dbg_log_idx, 0);
7672 	atomic_set(&phba->dbg_log_cnt, 0);
7673 	atomic_set(&phba->dbg_log_dmping, 0);
7674 	spin_lock_init(&phba->hbalock);
7675 
7676 	/* Initialize port_list spinlock */
7677 	spin_lock_init(&phba->port_list_lock);
7678 	INIT_LIST_HEAD(&phba->port_list);
7679 
7680 	INIT_LIST_HEAD(&phba->work_list);
7681 
7682 	/* Initialize the wait queue head for the kernel thread */
7683 	init_waitqueue_head(&phba->work_waitq);
7684 
7685 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7686 			"1403 Protocols supported %s %s %s\n",
7687 			((phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP) ?
7688 				"SCSI" : " "),
7689 			((phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) ?
7690 				"NVME" : " "),
7691 			(phba->nvmet_support ? "NVMET" : " "));
7692 
7693 	/* ras_fwlog state */
7694 	spin_lock_init(&phba->ras_fwlog_lock);
7695 
7696 	/* Initialize the IO buffer list used by driver for SLI3 SCSI */
7697 	spin_lock_init(&phba->scsi_buf_list_get_lock);
7698 	INIT_LIST_HEAD(&phba->lpfc_scsi_buf_list_get);
7699 	spin_lock_init(&phba->scsi_buf_list_put_lock);
7700 	INIT_LIST_HEAD(&phba->lpfc_scsi_buf_list_put);
7701 
7702 	/* Initialize the fabric iocb list */
7703 	INIT_LIST_HEAD(&phba->fabric_iocb_list);
7704 
7705 	/* Initialize list to save ELS buffers */
7706 	INIT_LIST_HEAD(&phba->elsbuf);
7707 
7708 	/* Initialize FCF connection rec list */
7709 	INIT_LIST_HEAD(&phba->fcf_conn_rec_list);
7710 
7711 	/* Initialize OAS configuration list */
7712 	spin_lock_init(&phba->devicelock);
7713 	INIT_LIST_HEAD(&phba->luns);
7714 
7715 	/* MBOX heartbeat timer */
7716 	timer_setup(&psli->mbox_tmo, lpfc_mbox_timeout, 0);
7717 	/* Fabric block timer */
7718 	timer_setup(&phba->fabric_block_timer, lpfc_fabric_block_timeout, 0);
7719 	/* EA polling mode timer */
7720 	timer_setup(&phba->eratt_poll, lpfc_poll_eratt, 0);
7721 	/* Heartbeat timer */
7722 	timer_setup(&phba->hb_tmofunc, lpfc_hb_timeout, 0);
7723 
7724 	INIT_DELAYED_WORK(&phba->eq_delay_work, lpfc_hb_eq_delay_work);
7725 
7726 	INIT_DELAYED_WORK(&phba->idle_stat_delay_work,
7727 			  lpfc_idle_stat_delay_work);
7728 	INIT_WORK(&phba->unblock_request_work, lpfc_unblock_requests_work);
7729 	return 0;
7730 }
7731 
7732 /**
7733  * lpfc_sli_driver_resource_setup - Setup driver internal resources for SLI3 dev
7734  * @phba: pointer to lpfc hba data structure.
7735  *
7736  * This routine is invoked to set up the driver internal resources specific to
7737  * support the SLI-3 HBA device it attached to.
7738  *
7739  * Return codes
7740  * 0 - successful
7741  * other values - error
7742  **/
7743 static int
7744 lpfc_sli_driver_resource_setup(struct lpfc_hba *phba)
7745 {
7746 	int rc, entry_sz;
7747 
7748 	/*
7749 	 * Initialize timers used by driver
7750 	 */
7751 
7752 	/* FCP polling mode timer */
7753 	timer_setup(&phba->fcp_poll_timer, lpfc_poll_timeout, 0);
7754 
7755 	/* Host attention work mask setup */
7756 	phba->work_ha_mask = (HA_ERATT | HA_MBATT | HA_LATT);
7757 	phba->work_ha_mask |= (HA_RXMASK << (LPFC_ELS_RING * 4));
7758 
7759 	/* Get all the module params for configuring this host */
7760 	lpfc_get_cfgparam(phba);
7761 	/* Set up phase-1 common device driver resources */
7762 
7763 	rc = lpfc_setup_driver_resource_phase1(phba);
7764 	if (rc)
7765 		return -ENODEV;
7766 
7767 	if (!phba->sli.sli3_ring)
7768 		phba->sli.sli3_ring = kcalloc(LPFC_SLI3_MAX_RING,
7769 					      sizeof(struct lpfc_sli_ring),
7770 					      GFP_KERNEL);
7771 	if (!phba->sli.sli3_ring)
7772 		return -ENOMEM;
7773 
7774 	/*
7775 	 * Since lpfc_sg_seg_cnt is module parameter, the sg_dma_buf_size
7776 	 * used to create the sg_dma_buf_pool must be dynamically calculated.
7777 	 */
7778 
7779 	if (phba->sli_rev == LPFC_SLI_REV4)
7780 		entry_sz = sizeof(struct sli4_sge);
7781 	else
7782 		entry_sz = sizeof(struct ulp_bde64);
7783 
7784 	/* There are going to be 2 reserved BDEs: 1 FCP cmnd + 1 FCP rsp */
7785 	if (phba->cfg_enable_bg) {
7786 		/*
7787 		 * The scsi_buf for a T10-DIF I/O will hold the FCP cmnd,
7788 		 * the FCP rsp, and a BDE for each. Sice we have no control
7789 		 * over how many protection data segments the SCSI Layer
7790 		 * will hand us (ie: there could be one for every block
7791 		 * in the IO), we just allocate enough BDEs to accomidate
7792 		 * our max amount and we need to limit lpfc_sg_seg_cnt to
7793 		 * minimize the risk of running out.
7794 		 */
7795 		phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd) +
7796 			sizeof(struct fcp_rsp) +
7797 			(LPFC_MAX_SG_SEG_CNT * entry_sz);
7798 
7799 		if (phba->cfg_sg_seg_cnt > LPFC_MAX_SG_SEG_CNT_DIF)
7800 			phba->cfg_sg_seg_cnt = LPFC_MAX_SG_SEG_CNT_DIF;
7801 
7802 		/* Total BDEs in BPL for scsi_sg_list and scsi_sg_prot_list */
7803 		phba->cfg_total_seg_cnt = LPFC_MAX_SG_SEG_CNT;
7804 	} else {
7805 		/*
7806 		 * The scsi_buf for a regular I/O will hold the FCP cmnd,
7807 		 * the FCP rsp, a BDE for each, and a BDE for up to
7808 		 * cfg_sg_seg_cnt data segments.
7809 		 */
7810 		phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd) +
7811 			sizeof(struct fcp_rsp) +
7812 			((phba->cfg_sg_seg_cnt + 2) * entry_sz);
7813 
7814 		/* Total BDEs in BPL for scsi_sg_list */
7815 		phba->cfg_total_seg_cnt = phba->cfg_sg_seg_cnt + 2;
7816 	}
7817 
7818 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP,
7819 			"9088 INIT sg_tablesize:%d dmabuf_size:%d total_bde:%d\n",
7820 			phba->cfg_sg_seg_cnt, phba->cfg_sg_dma_buf_size,
7821 			phba->cfg_total_seg_cnt);
7822 
7823 	phba->max_vpi = LPFC_MAX_VPI;
7824 	/* This will be set to correct value after config_port mbox */
7825 	phba->max_vports = 0;
7826 
7827 	/*
7828 	 * Initialize the SLI Layer to run with lpfc HBAs.
7829 	 */
7830 	lpfc_sli_setup(phba);
7831 	lpfc_sli_queue_init(phba);
7832 
7833 	/* Allocate device driver memory */
7834 	if (lpfc_mem_alloc(phba, BPL_ALIGN_SZ))
7835 		return -ENOMEM;
7836 
7837 	phba->lpfc_sg_dma_buf_pool =
7838 		dma_pool_create("lpfc_sg_dma_buf_pool",
7839 				&phba->pcidev->dev, phba->cfg_sg_dma_buf_size,
7840 				BPL_ALIGN_SZ, 0);
7841 
7842 	if (!phba->lpfc_sg_dma_buf_pool)
7843 		goto fail_free_mem;
7844 
7845 	phba->lpfc_cmd_rsp_buf_pool =
7846 			dma_pool_create("lpfc_cmd_rsp_buf_pool",
7847 					&phba->pcidev->dev,
7848 					sizeof(struct fcp_cmnd) +
7849 					sizeof(struct fcp_rsp),
7850 					BPL_ALIGN_SZ, 0);
7851 
7852 	if (!phba->lpfc_cmd_rsp_buf_pool)
7853 		goto fail_free_dma_buf_pool;
7854 
7855 	/*
7856 	 * Enable sr-iov virtual functions if supported and configured
7857 	 * through the module parameter.
7858 	 */
7859 	if (phba->cfg_sriov_nr_virtfn > 0) {
7860 		rc = lpfc_sli_probe_sriov_nr_virtfn(phba,
7861 						 phba->cfg_sriov_nr_virtfn);
7862 		if (rc) {
7863 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7864 					"2808 Requested number of SR-IOV "
7865 					"virtual functions (%d) is not "
7866 					"supported\n",
7867 					phba->cfg_sriov_nr_virtfn);
7868 			phba->cfg_sriov_nr_virtfn = 0;
7869 		}
7870 	}
7871 
7872 	return 0;
7873 
7874 fail_free_dma_buf_pool:
7875 	dma_pool_destroy(phba->lpfc_sg_dma_buf_pool);
7876 	phba->lpfc_sg_dma_buf_pool = NULL;
7877 fail_free_mem:
7878 	lpfc_mem_free(phba);
7879 	return -ENOMEM;
7880 }
7881 
7882 /**
7883  * lpfc_sli_driver_resource_unset - Unset drvr internal resources for SLI3 dev
7884  * @phba: pointer to lpfc hba data structure.
7885  *
7886  * This routine is invoked to unset the driver internal resources set up
7887  * specific for supporting the SLI-3 HBA device it attached to.
7888  **/
7889 static void
7890 lpfc_sli_driver_resource_unset(struct lpfc_hba *phba)
7891 {
7892 	/* Free device driver memory allocated */
7893 	lpfc_mem_free_all(phba);
7894 
7895 	return;
7896 }
7897 
7898 /**
7899  * lpfc_sli4_driver_resource_setup - Setup drvr internal resources for SLI4 dev
7900  * @phba: pointer to lpfc hba data structure.
7901  *
7902  * This routine is invoked to set up the driver internal resources specific to
7903  * support the SLI-4 HBA device it attached to.
7904  *
7905  * Return codes
7906  * 	0 - successful
7907  * 	other values - error
7908  **/
7909 static int
7910 lpfc_sli4_driver_resource_setup(struct lpfc_hba *phba)
7911 {
7912 	LPFC_MBOXQ_t *mboxq;
7913 	MAILBOX_t *mb;
7914 	int rc, i, max_buf_size;
7915 	int longs;
7916 	int extra;
7917 	uint64_t wwn;
7918 	u32 if_type;
7919 	u32 if_fam;
7920 
7921 	phba->sli4_hba.num_present_cpu = lpfc_present_cpu;
7922 	phba->sli4_hba.num_possible_cpu = cpumask_last(cpu_possible_mask) + 1;
7923 	phba->sli4_hba.curr_disp_cpu = 0;
7924 
7925 	/* Get all the module params for configuring this host */
7926 	lpfc_get_cfgparam(phba);
7927 
7928 	/* Set up phase-1 common device driver resources */
7929 	rc = lpfc_setup_driver_resource_phase1(phba);
7930 	if (rc)
7931 		return -ENODEV;
7932 
7933 	/* Before proceed, wait for POST done and device ready */
7934 	rc = lpfc_sli4_post_status_check(phba);
7935 	if (rc)
7936 		return -ENODEV;
7937 
7938 	/* Allocate all driver workqueues here */
7939 
7940 	/* The lpfc_wq workqueue for deferred irq use */
7941 	phba->wq = alloc_workqueue("lpfc_wq", WQ_MEM_RECLAIM, 0);
7942 	if (!phba->wq)
7943 		return -ENOMEM;
7944 
7945 	/*
7946 	 * Initialize timers used by driver
7947 	 */
7948 
7949 	timer_setup(&phba->rrq_tmr, lpfc_rrq_timeout, 0);
7950 
7951 	/* FCF rediscover timer */
7952 	timer_setup(&phba->fcf.redisc_wait, lpfc_sli4_fcf_redisc_wait_tmo, 0);
7953 
7954 	/* CMF congestion timer */
7955 	hrtimer_init(&phba->cmf_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
7956 	phba->cmf_timer.function = lpfc_cmf_timer;
7957 	/* CMF 1 minute stats collection timer */
7958 	hrtimer_init(&phba->cmf_stats_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
7959 	phba->cmf_stats_timer.function = lpfc_cmf_stats_timer;
7960 
7961 	/*
7962 	 * Control structure for handling external multi-buffer mailbox
7963 	 * command pass-through.
7964 	 */
7965 	memset((uint8_t *)&phba->mbox_ext_buf_ctx, 0,
7966 		sizeof(struct lpfc_mbox_ext_buf_ctx));
7967 	INIT_LIST_HEAD(&phba->mbox_ext_buf_ctx.ext_dmabuf_list);
7968 
7969 	phba->max_vpi = LPFC_MAX_VPI;
7970 
7971 	/* This will be set to correct value after the read_config mbox */
7972 	phba->max_vports = 0;
7973 
7974 	/* Program the default value of vlan_id and fc_map */
7975 	phba->valid_vlan = 0;
7976 	phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
7977 	phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
7978 	phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
7979 
7980 	/*
7981 	 * For SLI4, instead of using ring 0 (LPFC_FCP_RING) for FCP commands
7982 	 * we will associate a new ring, for each EQ/CQ/WQ tuple.
7983 	 * The WQ create will allocate the ring.
7984 	 */
7985 
7986 	/* Initialize buffer queue management fields */
7987 	INIT_LIST_HEAD(&phba->hbqs[LPFC_ELS_HBQ].hbq_buffer_list);
7988 	phba->hbqs[LPFC_ELS_HBQ].hbq_alloc_buffer = lpfc_sli4_rb_alloc;
7989 	phba->hbqs[LPFC_ELS_HBQ].hbq_free_buffer = lpfc_sli4_rb_free;
7990 
7991 	/* for VMID idle timeout if VMID is enabled */
7992 	if (lpfc_is_vmid_enabled(phba))
7993 		timer_setup(&phba->inactive_vmid_poll, lpfc_vmid_poll, 0);
7994 
7995 	/*
7996 	 * Initialize the SLI Layer to run with lpfc SLI4 HBAs.
7997 	 */
7998 	/* Initialize the Abort buffer list used by driver */
7999 	spin_lock_init(&phba->sli4_hba.abts_io_buf_list_lock);
8000 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_io_buf_list);
8001 
8002 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
8003 		/* Initialize the Abort nvme buffer list used by driver */
8004 		spin_lock_init(&phba->sli4_hba.abts_nvmet_buf_list_lock);
8005 		INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
8006 		INIT_LIST_HEAD(&phba->sli4_hba.lpfc_nvmet_io_wait_list);
8007 		spin_lock_init(&phba->sli4_hba.t_active_list_lock);
8008 		INIT_LIST_HEAD(&phba->sli4_hba.t_active_ctx_list);
8009 	}
8010 
8011 	/* This abort list used by worker thread */
8012 	spin_lock_init(&phba->sli4_hba.sgl_list_lock);
8013 	spin_lock_init(&phba->sli4_hba.nvmet_io_wait_lock);
8014 	spin_lock_init(&phba->sli4_hba.asynce_list_lock);
8015 	spin_lock_init(&phba->sli4_hba.els_xri_abrt_list_lock);
8016 
8017 	/*
8018 	 * Initialize driver internal slow-path work queues
8019 	 */
8020 
8021 	/* Driver internel slow-path CQ Event pool */
8022 	INIT_LIST_HEAD(&phba->sli4_hba.sp_cqe_event_pool);
8023 	/* Response IOCB work queue list */
8024 	INIT_LIST_HEAD(&phba->sli4_hba.sp_queue_event);
8025 	/* Asynchronous event CQ Event work queue list */
8026 	INIT_LIST_HEAD(&phba->sli4_hba.sp_asynce_work_queue);
8027 	/* Slow-path XRI aborted CQ Event work queue list */
8028 	INIT_LIST_HEAD(&phba->sli4_hba.sp_els_xri_aborted_work_queue);
8029 	/* Receive queue CQ Event work queue list */
8030 	INIT_LIST_HEAD(&phba->sli4_hba.sp_unsol_work_queue);
8031 
8032 	/* Initialize extent block lists. */
8033 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_rpi_blk_list);
8034 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_xri_blk_list);
8035 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_vfi_blk_list);
8036 	INIT_LIST_HEAD(&phba->lpfc_vpi_blk_list);
8037 
8038 	/* Initialize mboxq lists. If the early init routines fail
8039 	 * these lists need to be correctly initialized.
8040 	 */
8041 	INIT_LIST_HEAD(&phba->sli.mboxq);
8042 	INIT_LIST_HEAD(&phba->sli.mboxq_cmpl);
8043 
8044 	/* initialize optic_state to 0xFF */
8045 	phba->sli4_hba.lnk_info.optic_state = 0xff;
8046 
8047 	/* Allocate device driver memory */
8048 	rc = lpfc_mem_alloc(phba, SGL_ALIGN_SZ);
8049 	if (rc)
8050 		goto out_destroy_workqueue;
8051 
8052 	/* IF Type 2 ports get initialized now. */
8053 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) >=
8054 	    LPFC_SLI_INTF_IF_TYPE_2) {
8055 		rc = lpfc_pci_function_reset(phba);
8056 		if (unlikely(rc)) {
8057 			rc = -ENODEV;
8058 			goto out_free_mem;
8059 		}
8060 		phba->temp_sensor_support = 1;
8061 	}
8062 
8063 	/* Create the bootstrap mailbox command */
8064 	rc = lpfc_create_bootstrap_mbox(phba);
8065 	if (unlikely(rc))
8066 		goto out_free_mem;
8067 
8068 	/* Set up the host's endian order with the device. */
8069 	rc = lpfc_setup_endian_order(phba);
8070 	if (unlikely(rc))
8071 		goto out_free_bsmbx;
8072 
8073 	/* Set up the hba's configuration parameters. */
8074 	rc = lpfc_sli4_read_config(phba);
8075 	if (unlikely(rc))
8076 		goto out_free_bsmbx;
8077 
8078 	if (phba->sli4_hba.fawwpn_flag & LPFC_FAWWPN_CONFIG) {
8079 		/* Right now the link is down, if FA-PWWN is configured the
8080 		 * firmware will try FLOGI before the driver gets a link up.
8081 		 * If it fails, the driver should get a MISCONFIGURED async
8082 		 * event which will clear this flag. The only notification
8083 		 * the driver gets is if it fails, if it succeeds there is no
8084 		 * notification given. Assume success.
8085 		 */
8086 		phba->sli4_hba.fawwpn_flag |= LPFC_FAWWPN_FABRIC;
8087 	}
8088 
8089 	rc = lpfc_mem_alloc_active_rrq_pool_s4(phba);
8090 	if (unlikely(rc))
8091 		goto out_free_bsmbx;
8092 
8093 	/* IF Type 0 ports get initialized now. */
8094 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
8095 	    LPFC_SLI_INTF_IF_TYPE_0) {
8096 		rc = lpfc_pci_function_reset(phba);
8097 		if (unlikely(rc))
8098 			goto out_free_bsmbx;
8099 	}
8100 
8101 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
8102 						       GFP_KERNEL);
8103 	if (!mboxq) {
8104 		rc = -ENOMEM;
8105 		goto out_free_bsmbx;
8106 	}
8107 
8108 	/* Check for NVMET being configured */
8109 	phba->nvmet_support = 0;
8110 	if (lpfc_enable_nvmet_cnt) {
8111 
8112 		/* First get WWN of HBA instance */
8113 		lpfc_read_nv(phba, mboxq);
8114 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8115 		if (rc != MBX_SUCCESS) {
8116 			lpfc_printf_log(phba, KERN_ERR,
8117 					LOG_TRACE_EVENT,
8118 					"6016 Mailbox failed , mbxCmd x%x "
8119 					"READ_NV, mbxStatus x%x\n",
8120 					bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8121 					bf_get(lpfc_mqe_status, &mboxq->u.mqe));
8122 			mempool_free(mboxq, phba->mbox_mem_pool);
8123 			rc = -EIO;
8124 			goto out_free_bsmbx;
8125 		}
8126 		mb = &mboxq->u.mb;
8127 		memcpy(&wwn, (char *)mb->un.varRDnvp.nodename,
8128 		       sizeof(uint64_t));
8129 		wwn = cpu_to_be64(wwn);
8130 		phba->sli4_hba.wwnn.u.name = wwn;
8131 		memcpy(&wwn, (char *)mb->un.varRDnvp.portname,
8132 		       sizeof(uint64_t));
8133 		/* wwn is WWPN of HBA instance */
8134 		wwn = cpu_to_be64(wwn);
8135 		phba->sli4_hba.wwpn.u.name = wwn;
8136 
8137 		/* Check to see if it matches any module parameter */
8138 		for (i = 0; i < lpfc_enable_nvmet_cnt; i++) {
8139 			if (wwn == lpfc_enable_nvmet[i]) {
8140 #if (IS_ENABLED(CONFIG_NVME_TARGET_FC))
8141 				if (lpfc_nvmet_mem_alloc(phba))
8142 					break;
8143 
8144 				phba->nvmet_support = 1; /* a match */
8145 
8146 				lpfc_printf_log(phba, KERN_ERR,
8147 						LOG_TRACE_EVENT,
8148 						"6017 NVME Target %016llx\n",
8149 						wwn);
8150 #else
8151 				lpfc_printf_log(phba, KERN_ERR,
8152 						LOG_TRACE_EVENT,
8153 						"6021 Can't enable NVME Target."
8154 						" NVME_TARGET_FC infrastructure"
8155 						" is not in kernel\n");
8156 #endif
8157 				/* Not supported for NVMET */
8158 				phba->cfg_xri_rebalancing = 0;
8159 				if (phba->irq_chann_mode == NHT_MODE) {
8160 					phba->cfg_irq_chann =
8161 						phba->sli4_hba.num_present_cpu;
8162 					phba->cfg_hdw_queue =
8163 						phba->sli4_hba.num_present_cpu;
8164 					phba->irq_chann_mode = NORMAL_MODE;
8165 				}
8166 				break;
8167 			}
8168 		}
8169 	}
8170 
8171 	lpfc_nvme_mod_param_dep(phba);
8172 
8173 	/*
8174 	 * Get sli4 parameters that override parameters from Port capabilities.
8175 	 * If this call fails, it isn't critical unless the SLI4 parameters come
8176 	 * back in conflict.
8177 	 */
8178 	rc = lpfc_get_sli4_parameters(phba, mboxq);
8179 	if (rc) {
8180 		if_type = bf_get(lpfc_sli_intf_if_type,
8181 				 &phba->sli4_hba.sli_intf);
8182 		if_fam = bf_get(lpfc_sli_intf_sli_family,
8183 				&phba->sli4_hba.sli_intf);
8184 		if (phba->sli4_hba.extents_in_use &&
8185 		    phba->sli4_hba.rpi_hdrs_in_use) {
8186 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8187 					"2999 Unsupported SLI4 Parameters "
8188 					"Extents and RPI headers enabled.\n");
8189 			if (if_type == LPFC_SLI_INTF_IF_TYPE_0 &&
8190 			    if_fam ==  LPFC_SLI_INTF_FAMILY_BE2) {
8191 				mempool_free(mboxq, phba->mbox_mem_pool);
8192 				rc = -EIO;
8193 				goto out_free_bsmbx;
8194 			}
8195 		}
8196 		if (!(if_type == LPFC_SLI_INTF_IF_TYPE_0 &&
8197 		      if_fam == LPFC_SLI_INTF_FAMILY_BE2)) {
8198 			mempool_free(mboxq, phba->mbox_mem_pool);
8199 			rc = -EIO;
8200 			goto out_free_bsmbx;
8201 		}
8202 	}
8203 
8204 	/*
8205 	 * 1 for cmd, 1 for rsp, NVME adds an extra one
8206 	 * for boundary conditions in its max_sgl_segment template.
8207 	 */
8208 	extra = 2;
8209 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
8210 		extra++;
8211 
8212 	/*
8213 	 * It doesn't matter what family our adapter is in, we are
8214 	 * limited to 2 Pages, 512 SGEs, for our SGL.
8215 	 * There are going to be 2 reserved SGEs: 1 FCP cmnd + 1 FCP rsp
8216 	 */
8217 	max_buf_size = (2 * SLI4_PAGE_SIZE);
8218 
8219 	/*
8220 	 * Since lpfc_sg_seg_cnt is module param, the sg_dma_buf_size
8221 	 * used to create the sg_dma_buf_pool must be calculated.
8222 	 */
8223 	if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
8224 		/* Both cfg_enable_bg and cfg_external_dif code paths */
8225 
8226 		/*
8227 		 * The scsi_buf for a T10-DIF I/O holds the FCP cmnd,
8228 		 * the FCP rsp, and a SGE. Sice we have no control
8229 		 * over how many protection segments the SCSI Layer
8230 		 * will hand us (ie: there could be one for every block
8231 		 * in the IO), just allocate enough SGEs to accomidate
8232 		 * our max amount and we need to limit lpfc_sg_seg_cnt
8233 		 * to minimize the risk of running out.
8234 		 */
8235 		phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd32) +
8236 				sizeof(struct fcp_rsp) + max_buf_size;
8237 
8238 		/* Total SGEs for scsi_sg_list and scsi_sg_prot_list */
8239 		phba->cfg_total_seg_cnt = LPFC_MAX_SGL_SEG_CNT;
8240 
8241 		/*
8242 		 * If supporting DIF, reduce the seg count for scsi to
8243 		 * allow room for the DIF sges.
8244 		 */
8245 		if (phba->cfg_enable_bg &&
8246 		    phba->cfg_sg_seg_cnt > LPFC_MAX_BG_SLI4_SEG_CNT_DIF)
8247 			phba->cfg_scsi_seg_cnt = LPFC_MAX_BG_SLI4_SEG_CNT_DIF;
8248 		else
8249 			phba->cfg_scsi_seg_cnt = phba->cfg_sg_seg_cnt;
8250 
8251 	} else {
8252 		/*
8253 		 * The scsi_buf for a regular I/O holds the FCP cmnd,
8254 		 * the FCP rsp, a SGE for each, and a SGE for up to
8255 		 * cfg_sg_seg_cnt data segments.
8256 		 */
8257 		phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd32) +
8258 				sizeof(struct fcp_rsp) +
8259 				((phba->cfg_sg_seg_cnt + extra) *
8260 				sizeof(struct sli4_sge));
8261 
8262 		/* Total SGEs for scsi_sg_list */
8263 		phba->cfg_total_seg_cnt = phba->cfg_sg_seg_cnt + extra;
8264 		phba->cfg_scsi_seg_cnt = phba->cfg_sg_seg_cnt;
8265 
8266 		/*
8267 		 * NOTE: if (phba->cfg_sg_seg_cnt + extra) <= 256 we only
8268 		 * need to post 1 page for the SGL.
8269 		 */
8270 	}
8271 
8272 	if (phba->cfg_xpsgl && !phba->nvmet_support)
8273 		phba->cfg_sg_dma_buf_size = LPFC_DEFAULT_XPSGL_SIZE;
8274 	else if (phba->cfg_sg_dma_buf_size  <= LPFC_MIN_SG_SLI4_BUF_SZ)
8275 		phba->cfg_sg_dma_buf_size = LPFC_MIN_SG_SLI4_BUF_SZ;
8276 	else
8277 		phba->cfg_sg_dma_buf_size =
8278 				SLI4_PAGE_ALIGN(phba->cfg_sg_dma_buf_size);
8279 
8280 	phba->border_sge_num = phba->cfg_sg_dma_buf_size /
8281 			       sizeof(struct sli4_sge);
8282 
8283 	/* Limit to LPFC_MAX_NVME_SEG_CNT for NVME. */
8284 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
8285 		if (phba->cfg_sg_seg_cnt > LPFC_MAX_NVME_SEG_CNT) {
8286 			lpfc_printf_log(phba, KERN_INFO, LOG_NVME | LOG_INIT,
8287 					"6300 Reducing NVME sg segment "
8288 					"cnt to %d\n",
8289 					LPFC_MAX_NVME_SEG_CNT);
8290 			phba->cfg_nvme_seg_cnt = LPFC_MAX_NVME_SEG_CNT;
8291 		} else
8292 			phba->cfg_nvme_seg_cnt = phba->cfg_sg_seg_cnt;
8293 	}
8294 
8295 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP,
8296 			"9087 sg_seg_cnt:%d dmabuf_size:%d "
8297 			"total:%d scsi:%d nvme:%d\n",
8298 			phba->cfg_sg_seg_cnt, phba->cfg_sg_dma_buf_size,
8299 			phba->cfg_total_seg_cnt,  phba->cfg_scsi_seg_cnt,
8300 			phba->cfg_nvme_seg_cnt);
8301 
8302 	if (phba->cfg_sg_dma_buf_size < SLI4_PAGE_SIZE)
8303 		i = phba->cfg_sg_dma_buf_size;
8304 	else
8305 		i = SLI4_PAGE_SIZE;
8306 
8307 	phba->lpfc_sg_dma_buf_pool =
8308 			dma_pool_create("lpfc_sg_dma_buf_pool",
8309 					&phba->pcidev->dev,
8310 					phba->cfg_sg_dma_buf_size,
8311 					i, 0);
8312 	if (!phba->lpfc_sg_dma_buf_pool) {
8313 		rc = -ENOMEM;
8314 		goto out_free_bsmbx;
8315 	}
8316 
8317 	phba->lpfc_cmd_rsp_buf_pool =
8318 			dma_pool_create("lpfc_cmd_rsp_buf_pool",
8319 					&phba->pcidev->dev,
8320 					sizeof(struct fcp_cmnd32) +
8321 					sizeof(struct fcp_rsp),
8322 					i, 0);
8323 	if (!phba->lpfc_cmd_rsp_buf_pool) {
8324 		rc = -ENOMEM;
8325 		goto out_free_sg_dma_buf;
8326 	}
8327 
8328 	mempool_free(mboxq, phba->mbox_mem_pool);
8329 
8330 	/* Verify OAS is supported */
8331 	lpfc_sli4_oas_verify(phba);
8332 
8333 	/* Verify RAS support on adapter */
8334 	lpfc_sli4_ras_init(phba);
8335 
8336 	/* Verify all the SLI4 queues */
8337 	rc = lpfc_sli4_queue_verify(phba);
8338 	if (rc)
8339 		goto out_free_cmd_rsp_buf;
8340 
8341 	/* Create driver internal CQE event pool */
8342 	rc = lpfc_sli4_cq_event_pool_create(phba);
8343 	if (rc)
8344 		goto out_free_cmd_rsp_buf;
8345 
8346 	/* Initialize sgl lists per host */
8347 	lpfc_init_sgl_list(phba);
8348 
8349 	/* Allocate and initialize active sgl array */
8350 	rc = lpfc_init_active_sgl_array(phba);
8351 	if (rc) {
8352 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8353 				"1430 Failed to initialize sgl list.\n");
8354 		goto out_destroy_cq_event_pool;
8355 	}
8356 	rc = lpfc_sli4_init_rpi_hdrs(phba);
8357 	if (rc) {
8358 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8359 				"1432 Failed to initialize rpi headers.\n");
8360 		goto out_free_active_sgl;
8361 	}
8362 
8363 	/* Allocate eligible FCF bmask memory for FCF roundrobin failover */
8364 	longs = (LPFC_SLI4_FCF_TBL_INDX_MAX + BITS_PER_LONG - 1)/BITS_PER_LONG;
8365 	phba->fcf.fcf_rr_bmask = kcalloc(longs, sizeof(unsigned long),
8366 					 GFP_KERNEL);
8367 	if (!phba->fcf.fcf_rr_bmask) {
8368 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8369 				"2759 Failed allocate memory for FCF round "
8370 				"robin failover bmask\n");
8371 		rc = -ENOMEM;
8372 		goto out_remove_rpi_hdrs;
8373 	}
8374 
8375 	phba->sli4_hba.hba_eq_hdl = kcalloc(phba->cfg_irq_chann,
8376 					    sizeof(struct lpfc_hba_eq_hdl),
8377 					    GFP_KERNEL);
8378 	if (!phba->sli4_hba.hba_eq_hdl) {
8379 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8380 				"2572 Failed allocate memory for "
8381 				"fast-path per-EQ handle array\n");
8382 		rc = -ENOMEM;
8383 		goto out_free_fcf_rr_bmask;
8384 	}
8385 
8386 	phba->sli4_hba.cpu_map = kcalloc(phba->sli4_hba.num_possible_cpu,
8387 					sizeof(struct lpfc_vector_map_info),
8388 					GFP_KERNEL);
8389 	if (!phba->sli4_hba.cpu_map) {
8390 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8391 				"3327 Failed allocate memory for msi-x "
8392 				"interrupt vector mapping\n");
8393 		rc = -ENOMEM;
8394 		goto out_free_hba_eq_hdl;
8395 	}
8396 
8397 	phba->sli4_hba.eq_info = alloc_percpu(struct lpfc_eq_intr_info);
8398 	if (!phba->sli4_hba.eq_info) {
8399 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8400 				"3321 Failed allocation for per_cpu stats\n");
8401 		rc = -ENOMEM;
8402 		goto out_free_hba_cpu_map;
8403 	}
8404 
8405 	phba->sli4_hba.idle_stat = kcalloc(phba->sli4_hba.num_possible_cpu,
8406 					   sizeof(*phba->sli4_hba.idle_stat),
8407 					   GFP_KERNEL);
8408 	if (!phba->sli4_hba.idle_stat) {
8409 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8410 				"3390 Failed allocation for idle_stat\n");
8411 		rc = -ENOMEM;
8412 		goto out_free_hba_eq_info;
8413 	}
8414 
8415 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
8416 	phba->sli4_hba.c_stat = alloc_percpu(struct lpfc_hdwq_stat);
8417 	if (!phba->sli4_hba.c_stat) {
8418 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8419 				"3332 Failed allocating per cpu hdwq stats\n");
8420 		rc = -ENOMEM;
8421 		goto out_free_hba_idle_stat;
8422 	}
8423 #endif
8424 
8425 	phba->cmf_stat = alloc_percpu(struct lpfc_cgn_stat);
8426 	if (!phba->cmf_stat) {
8427 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8428 				"3331 Failed allocating per cpu cgn stats\n");
8429 		rc = -ENOMEM;
8430 		goto out_free_hba_hdwq_info;
8431 	}
8432 
8433 	/*
8434 	 * Enable sr-iov virtual functions if supported and configured
8435 	 * through the module parameter.
8436 	 */
8437 	if (phba->cfg_sriov_nr_virtfn > 0) {
8438 		rc = lpfc_sli_probe_sriov_nr_virtfn(phba,
8439 						 phba->cfg_sriov_nr_virtfn);
8440 		if (rc) {
8441 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
8442 					"3020 Requested number of SR-IOV "
8443 					"virtual functions (%d) is not "
8444 					"supported\n",
8445 					phba->cfg_sriov_nr_virtfn);
8446 			phba->cfg_sriov_nr_virtfn = 0;
8447 		}
8448 	}
8449 
8450 	return 0;
8451 
8452 out_free_hba_hdwq_info:
8453 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
8454 	free_percpu(phba->sli4_hba.c_stat);
8455 out_free_hba_idle_stat:
8456 #endif
8457 	kfree(phba->sli4_hba.idle_stat);
8458 out_free_hba_eq_info:
8459 	free_percpu(phba->sli4_hba.eq_info);
8460 out_free_hba_cpu_map:
8461 	kfree(phba->sli4_hba.cpu_map);
8462 out_free_hba_eq_hdl:
8463 	kfree(phba->sli4_hba.hba_eq_hdl);
8464 out_free_fcf_rr_bmask:
8465 	kfree(phba->fcf.fcf_rr_bmask);
8466 out_remove_rpi_hdrs:
8467 	lpfc_sli4_remove_rpi_hdrs(phba);
8468 out_free_active_sgl:
8469 	lpfc_free_active_sgl(phba);
8470 out_destroy_cq_event_pool:
8471 	lpfc_sli4_cq_event_pool_destroy(phba);
8472 out_free_cmd_rsp_buf:
8473 	dma_pool_destroy(phba->lpfc_cmd_rsp_buf_pool);
8474 	phba->lpfc_cmd_rsp_buf_pool = NULL;
8475 out_free_sg_dma_buf:
8476 	dma_pool_destroy(phba->lpfc_sg_dma_buf_pool);
8477 	phba->lpfc_sg_dma_buf_pool = NULL;
8478 out_free_bsmbx:
8479 	lpfc_destroy_bootstrap_mbox(phba);
8480 out_free_mem:
8481 	lpfc_mem_free(phba);
8482 out_destroy_workqueue:
8483 	destroy_workqueue(phba->wq);
8484 	phba->wq = NULL;
8485 	return rc;
8486 }
8487 
8488 /**
8489  * lpfc_sli4_driver_resource_unset - Unset drvr internal resources for SLI4 dev
8490  * @phba: pointer to lpfc hba data structure.
8491  *
8492  * This routine is invoked to unset the driver internal resources set up
8493  * specific for supporting the SLI-4 HBA device it attached to.
8494  **/
8495 static void
8496 lpfc_sli4_driver_resource_unset(struct lpfc_hba *phba)
8497 {
8498 	struct lpfc_fcf_conn_entry *conn_entry, *next_conn_entry;
8499 
8500 	free_percpu(phba->sli4_hba.eq_info);
8501 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
8502 	free_percpu(phba->sli4_hba.c_stat);
8503 #endif
8504 	free_percpu(phba->cmf_stat);
8505 	kfree(phba->sli4_hba.idle_stat);
8506 
8507 	/* Free memory allocated for msi-x interrupt vector to CPU mapping */
8508 	kfree(phba->sli4_hba.cpu_map);
8509 	phba->sli4_hba.num_possible_cpu = 0;
8510 	phba->sli4_hba.num_present_cpu = 0;
8511 	phba->sli4_hba.curr_disp_cpu = 0;
8512 	cpumask_clear(&phba->sli4_hba.irq_aff_mask);
8513 
8514 	/* Free memory allocated for fast-path work queue handles */
8515 	kfree(phba->sli4_hba.hba_eq_hdl);
8516 
8517 	/* Free the allocated rpi headers. */
8518 	lpfc_sli4_remove_rpi_hdrs(phba);
8519 	lpfc_sli4_remove_rpis(phba);
8520 
8521 	/* Free eligible FCF index bmask */
8522 	kfree(phba->fcf.fcf_rr_bmask);
8523 
8524 	/* Free the ELS sgl list */
8525 	lpfc_free_active_sgl(phba);
8526 	lpfc_free_els_sgl_list(phba);
8527 	lpfc_free_nvmet_sgl_list(phba);
8528 
8529 	/* Free the completion queue EQ event pool */
8530 	lpfc_sli4_cq_event_release_all(phba);
8531 	lpfc_sli4_cq_event_pool_destroy(phba);
8532 
8533 	/* Release resource identifiers. */
8534 	lpfc_sli4_dealloc_resource_identifiers(phba);
8535 
8536 	/* Free the bsmbx region. */
8537 	lpfc_destroy_bootstrap_mbox(phba);
8538 
8539 	/* Free the SLI Layer memory with SLI4 HBAs */
8540 	lpfc_mem_free_all(phba);
8541 
8542 	/* Free the current connect table */
8543 	list_for_each_entry_safe(conn_entry, next_conn_entry,
8544 		&phba->fcf_conn_rec_list, list) {
8545 		list_del_init(&conn_entry->list);
8546 		kfree(conn_entry);
8547 	}
8548 
8549 	return;
8550 }
8551 
8552 /**
8553  * lpfc_init_api_table_setup - Set up init api function jump table
8554  * @phba: The hba struct for which this call is being executed.
8555  * @dev_grp: The HBA PCI-Device group number.
8556  *
8557  * This routine sets up the device INIT interface API function jump table
8558  * in @phba struct.
8559  *
8560  * Returns: 0 - success, -ENODEV - failure.
8561  **/
8562 int
8563 lpfc_init_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
8564 {
8565 	phba->lpfc_hba_init_link = lpfc_hba_init_link;
8566 	phba->lpfc_hba_down_link = lpfc_hba_down_link;
8567 	phba->lpfc_selective_reset = lpfc_selective_reset;
8568 	switch (dev_grp) {
8569 	case LPFC_PCI_DEV_LP:
8570 		phba->lpfc_hba_down_post = lpfc_hba_down_post_s3;
8571 		phba->lpfc_handle_eratt = lpfc_handle_eratt_s3;
8572 		phba->lpfc_stop_port = lpfc_stop_port_s3;
8573 		break;
8574 	case LPFC_PCI_DEV_OC:
8575 		phba->lpfc_hba_down_post = lpfc_hba_down_post_s4;
8576 		phba->lpfc_handle_eratt = lpfc_handle_eratt_s4;
8577 		phba->lpfc_stop_port = lpfc_stop_port_s4;
8578 		break;
8579 	default:
8580 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8581 				"1431 Invalid HBA PCI-device group: 0x%x\n",
8582 				dev_grp);
8583 		return -ENODEV;
8584 	}
8585 	return 0;
8586 }
8587 
8588 /**
8589  * lpfc_setup_driver_resource_phase2 - Phase2 setup driver internal resources.
8590  * @phba: pointer to lpfc hba data structure.
8591  *
8592  * This routine is invoked to set up the driver internal resources after the
8593  * device specific resource setup to support the HBA device it attached to.
8594  *
8595  * Return codes
8596  * 	0 - successful
8597  * 	other values - error
8598  **/
8599 static int
8600 lpfc_setup_driver_resource_phase2(struct lpfc_hba *phba)
8601 {
8602 	int error;
8603 
8604 	/* Startup the kernel thread for this host adapter. */
8605 	phba->worker_thread = kthread_run(lpfc_do_work, phba,
8606 					  "lpfc_worker_%d", phba->brd_no);
8607 	if (IS_ERR(phba->worker_thread)) {
8608 		error = PTR_ERR(phba->worker_thread);
8609 		return error;
8610 	}
8611 
8612 	return 0;
8613 }
8614 
8615 /**
8616  * lpfc_unset_driver_resource_phase2 - Phase2 unset driver internal resources.
8617  * @phba: pointer to lpfc hba data structure.
8618  *
8619  * This routine is invoked to unset the driver internal resources set up after
8620  * the device specific resource setup for supporting the HBA device it
8621  * attached to.
8622  **/
8623 static void
8624 lpfc_unset_driver_resource_phase2(struct lpfc_hba *phba)
8625 {
8626 	if (phba->wq) {
8627 		destroy_workqueue(phba->wq);
8628 		phba->wq = NULL;
8629 	}
8630 
8631 	/* Stop kernel worker thread */
8632 	if (phba->worker_thread)
8633 		kthread_stop(phba->worker_thread);
8634 }
8635 
8636 /**
8637  * lpfc_free_iocb_list - Free iocb list.
8638  * @phba: pointer to lpfc hba data structure.
8639  *
8640  * This routine is invoked to free the driver's IOCB list and memory.
8641  **/
8642 void
8643 lpfc_free_iocb_list(struct lpfc_hba *phba)
8644 {
8645 	struct lpfc_iocbq *iocbq_entry = NULL, *iocbq_next = NULL;
8646 
8647 	spin_lock_irq(&phba->hbalock);
8648 	list_for_each_entry_safe(iocbq_entry, iocbq_next,
8649 				 &phba->lpfc_iocb_list, list) {
8650 		list_del(&iocbq_entry->list);
8651 		kfree(iocbq_entry);
8652 		phba->total_iocbq_bufs--;
8653 	}
8654 	spin_unlock_irq(&phba->hbalock);
8655 
8656 	return;
8657 }
8658 
8659 /**
8660  * lpfc_init_iocb_list - Allocate and initialize iocb list.
8661  * @phba: pointer to lpfc hba data structure.
8662  * @iocb_count: number of requested iocbs
8663  *
8664  * This routine is invoked to allocate and initizlize the driver's IOCB
8665  * list and set up the IOCB tag array accordingly.
8666  *
8667  * Return codes
8668  *	0 - successful
8669  *	other values - error
8670  **/
8671 int
8672 lpfc_init_iocb_list(struct lpfc_hba *phba, int iocb_count)
8673 {
8674 	struct lpfc_iocbq *iocbq_entry = NULL;
8675 	uint16_t iotag;
8676 	int i;
8677 
8678 	/* Initialize and populate the iocb list per host.  */
8679 	INIT_LIST_HEAD(&phba->lpfc_iocb_list);
8680 	for (i = 0; i < iocb_count; i++) {
8681 		iocbq_entry = kzalloc(sizeof(struct lpfc_iocbq), GFP_KERNEL);
8682 		if (iocbq_entry == NULL) {
8683 			printk(KERN_ERR "%s: only allocated %d iocbs of "
8684 				"expected %d count. Unloading driver.\n",
8685 				__func__, i, iocb_count);
8686 			goto out_free_iocbq;
8687 		}
8688 
8689 		iotag = lpfc_sli_next_iotag(phba, iocbq_entry);
8690 		if (iotag == 0) {
8691 			kfree(iocbq_entry);
8692 			printk(KERN_ERR "%s: failed to allocate IOTAG. "
8693 				"Unloading driver.\n", __func__);
8694 			goto out_free_iocbq;
8695 		}
8696 		iocbq_entry->sli4_lxritag = NO_XRI;
8697 		iocbq_entry->sli4_xritag = NO_XRI;
8698 
8699 		spin_lock_irq(&phba->hbalock);
8700 		list_add(&iocbq_entry->list, &phba->lpfc_iocb_list);
8701 		phba->total_iocbq_bufs++;
8702 		spin_unlock_irq(&phba->hbalock);
8703 	}
8704 
8705 	return 0;
8706 
8707 out_free_iocbq:
8708 	lpfc_free_iocb_list(phba);
8709 
8710 	return -ENOMEM;
8711 }
8712 
8713 /**
8714  * lpfc_free_sgl_list - Free a given sgl list.
8715  * @phba: pointer to lpfc hba data structure.
8716  * @sglq_list: pointer to the head of sgl list.
8717  *
8718  * This routine is invoked to free a give sgl list and memory.
8719  **/
8720 void
8721 lpfc_free_sgl_list(struct lpfc_hba *phba, struct list_head *sglq_list)
8722 {
8723 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
8724 
8725 	list_for_each_entry_safe(sglq_entry, sglq_next, sglq_list, list) {
8726 		list_del(&sglq_entry->list);
8727 		lpfc_mbuf_free(phba, sglq_entry->virt, sglq_entry->phys);
8728 		kfree(sglq_entry);
8729 	}
8730 }
8731 
8732 /**
8733  * lpfc_free_els_sgl_list - Free els sgl list.
8734  * @phba: pointer to lpfc hba data structure.
8735  *
8736  * This routine is invoked to free the driver's els sgl list and memory.
8737  **/
8738 static void
8739 lpfc_free_els_sgl_list(struct lpfc_hba *phba)
8740 {
8741 	LIST_HEAD(sglq_list);
8742 
8743 	/* Retrieve all els sgls from driver list */
8744 	spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
8745 	list_splice_init(&phba->sli4_hba.lpfc_els_sgl_list, &sglq_list);
8746 	spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
8747 
8748 	/* Now free the sgl list */
8749 	lpfc_free_sgl_list(phba, &sglq_list);
8750 }
8751 
8752 /**
8753  * lpfc_free_nvmet_sgl_list - Free nvmet sgl list.
8754  * @phba: pointer to lpfc hba data structure.
8755  *
8756  * This routine is invoked to free the driver's nvmet sgl list and memory.
8757  **/
8758 static void
8759 lpfc_free_nvmet_sgl_list(struct lpfc_hba *phba)
8760 {
8761 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
8762 	LIST_HEAD(sglq_list);
8763 
8764 	/* Retrieve all nvmet sgls from driver list */
8765 	spin_lock_irq(&phba->hbalock);
8766 	spin_lock(&phba->sli4_hba.sgl_list_lock);
8767 	list_splice_init(&phba->sli4_hba.lpfc_nvmet_sgl_list, &sglq_list);
8768 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
8769 	spin_unlock_irq(&phba->hbalock);
8770 
8771 	/* Now free the sgl list */
8772 	list_for_each_entry_safe(sglq_entry, sglq_next, &sglq_list, list) {
8773 		list_del(&sglq_entry->list);
8774 		lpfc_nvmet_buf_free(phba, sglq_entry->virt, sglq_entry->phys);
8775 		kfree(sglq_entry);
8776 	}
8777 
8778 	/* Update the nvmet_xri_cnt to reflect no current sgls.
8779 	 * The next initialization cycle sets the count and allocates
8780 	 * the sgls over again.
8781 	 */
8782 	phba->sli4_hba.nvmet_xri_cnt = 0;
8783 }
8784 
8785 /**
8786  * lpfc_init_active_sgl_array - Allocate the buf to track active ELS XRIs.
8787  * @phba: pointer to lpfc hba data structure.
8788  *
8789  * This routine is invoked to allocate the driver's active sgl memory.
8790  * This array will hold the sglq_entry's for active IOs.
8791  **/
8792 static int
8793 lpfc_init_active_sgl_array(struct lpfc_hba *phba)
8794 {
8795 	int size;
8796 	size = sizeof(struct lpfc_sglq *);
8797 	size *= phba->sli4_hba.max_cfg_param.max_xri;
8798 
8799 	phba->sli4_hba.lpfc_sglq_active_list =
8800 		kzalloc(size, GFP_KERNEL);
8801 	if (!phba->sli4_hba.lpfc_sglq_active_list)
8802 		return -ENOMEM;
8803 	return 0;
8804 }
8805 
8806 /**
8807  * lpfc_free_active_sgl - Free the buf that tracks active ELS XRIs.
8808  * @phba: pointer to lpfc hba data structure.
8809  *
8810  * This routine is invoked to walk through the array of active sglq entries
8811  * and free all of the resources.
8812  * This is just a place holder for now.
8813  **/
8814 static void
8815 lpfc_free_active_sgl(struct lpfc_hba *phba)
8816 {
8817 	kfree(phba->sli4_hba.lpfc_sglq_active_list);
8818 }
8819 
8820 /**
8821  * lpfc_init_sgl_list - Allocate and initialize sgl list.
8822  * @phba: pointer to lpfc hba data structure.
8823  *
8824  * This routine is invoked to allocate and initizlize the driver's sgl
8825  * list and set up the sgl xritag tag array accordingly.
8826  *
8827  **/
8828 static void
8829 lpfc_init_sgl_list(struct lpfc_hba *phba)
8830 {
8831 	/* Initialize and populate the sglq list per host/VF. */
8832 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_els_sgl_list);
8833 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_els_sgl_list);
8834 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_nvmet_sgl_list);
8835 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
8836 
8837 	/* els xri-sgl book keeping */
8838 	phba->sli4_hba.els_xri_cnt = 0;
8839 
8840 	/* nvme xri-buffer book keeping */
8841 	phba->sli4_hba.io_xri_cnt = 0;
8842 }
8843 
8844 /**
8845  * lpfc_sli4_init_rpi_hdrs - Post the rpi header memory region to the port
8846  * @phba: pointer to lpfc hba data structure.
8847  *
8848  * This routine is invoked to post rpi header templates to the
8849  * port for those SLI4 ports that do not support extents.  This routine
8850  * posts a PAGE_SIZE memory region to the port to hold up to
8851  * PAGE_SIZE modulo 64 rpi context headers.  This is an initialization routine
8852  * and should be called only when interrupts are disabled.
8853  *
8854  * Return codes
8855  * 	0 - successful
8856  *	-ERROR - otherwise.
8857  **/
8858 int
8859 lpfc_sli4_init_rpi_hdrs(struct lpfc_hba *phba)
8860 {
8861 	int rc = 0;
8862 	struct lpfc_rpi_hdr *rpi_hdr;
8863 
8864 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_rpi_hdr_list);
8865 	if (!phba->sli4_hba.rpi_hdrs_in_use)
8866 		return rc;
8867 	if (phba->sli4_hba.extents_in_use)
8868 		return -EIO;
8869 
8870 	rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
8871 	if (!rpi_hdr) {
8872 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8873 				"0391 Error during rpi post operation\n");
8874 		lpfc_sli4_remove_rpis(phba);
8875 		rc = -ENODEV;
8876 	}
8877 
8878 	return rc;
8879 }
8880 
8881 /**
8882  * lpfc_sli4_create_rpi_hdr - Allocate an rpi header memory region
8883  * @phba: pointer to lpfc hba data structure.
8884  *
8885  * This routine is invoked to allocate a single 4KB memory region to
8886  * support rpis and stores them in the phba.  This single region
8887  * provides support for up to 64 rpis.  The region is used globally
8888  * by the device.
8889  *
8890  * Returns:
8891  *   A valid rpi hdr on success.
8892  *   A NULL pointer on any failure.
8893  **/
8894 struct lpfc_rpi_hdr *
8895 lpfc_sli4_create_rpi_hdr(struct lpfc_hba *phba)
8896 {
8897 	uint16_t rpi_limit, curr_rpi_range;
8898 	struct lpfc_dmabuf *dmabuf;
8899 	struct lpfc_rpi_hdr *rpi_hdr;
8900 
8901 	/*
8902 	 * If the SLI4 port supports extents, posting the rpi header isn't
8903 	 * required.  Set the expected maximum count and let the actual value
8904 	 * get set when extents are fully allocated.
8905 	 */
8906 	if (!phba->sli4_hba.rpi_hdrs_in_use)
8907 		return NULL;
8908 	if (phba->sli4_hba.extents_in_use)
8909 		return NULL;
8910 
8911 	/* The limit on the logical index is just the max_rpi count. */
8912 	rpi_limit = phba->sli4_hba.max_cfg_param.max_rpi;
8913 
8914 	spin_lock_irq(&phba->hbalock);
8915 	/*
8916 	 * Establish the starting RPI in this header block.  The starting
8917 	 * rpi is normalized to a zero base because the physical rpi is
8918 	 * port based.
8919 	 */
8920 	curr_rpi_range = phba->sli4_hba.next_rpi;
8921 	spin_unlock_irq(&phba->hbalock);
8922 
8923 	/* Reached full RPI range */
8924 	if (curr_rpi_range == rpi_limit)
8925 		return NULL;
8926 
8927 	/*
8928 	 * First allocate the protocol header region for the port.  The
8929 	 * port expects a 4KB DMA-mapped memory region that is 4K aligned.
8930 	 */
8931 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
8932 	if (!dmabuf)
8933 		return NULL;
8934 
8935 	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
8936 					  LPFC_HDR_TEMPLATE_SIZE,
8937 					  &dmabuf->phys, GFP_KERNEL);
8938 	if (!dmabuf->virt) {
8939 		rpi_hdr = NULL;
8940 		goto err_free_dmabuf;
8941 	}
8942 
8943 	if (!IS_ALIGNED(dmabuf->phys, LPFC_HDR_TEMPLATE_SIZE)) {
8944 		rpi_hdr = NULL;
8945 		goto err_free_coherent;
8946 	}
8947 
8948 	/* Save the rpi header data for cleanup later. */
8949 	rpi_hdr = kzalloc(sizeof(struct lpfc_rpi_hdr), GFP_KERNEL);
8950 	if (!rpi_hdr)
8951 		goto err_free_coherent;
8952 
8953 	rpi_hdr->dmabuf = dmabuf;
8954 	rpi_hdr->len = LPFC_HDR_TEMPLATE_SIZE;
8955 	rpi_hdr->page_count = 1;
8956 	spin_lock_irq(&phba->hbalock);
8957 
8958 	/* The rpi_hdr stores the logical index only. */
8959 	rpi_hdr->start_rpi = curr_rpi_range;
8960 	rpi_hdr->next_rpi = phba->sli4_hba.next_rpi + LPFC_RPI_HDR_COUNT;
8961 	list_add_tail(&rpi_hdr->list, &phba->sli4_hba.lpfc_rpi_hdr_list);
8962 
8963 	spin_unlock_irq(&phba->hbalock);
8964 	return rpi_hdr;
8965 
8966  err_free_coherent:
8967 	dma_free_coherent(&phba->pcidev->dev, LPFC_HDR_TEMPLATE_SIZE,
8968 			  dmabuf->virt, dmabuf->phys);
8969  err_free_dmabuf:
8970 	kfree(dmabuf);
8971 	return NULL;
8972 }
8973 
8974 /**
8975  * lpfc_sli4_remove_rpi_hdrs - Remove all rpi header memory regions
8976  * @phba: pointer to lpfc hba data structure.
8977  *
8978  * This routine is invoked to remove all memory resources allocated
8979  * to support rpis for SLI4 ports not supporting extents. This routine
8980  * presumes the caller has released all rpis consumed by fabric or port
8981  * logins and is prepared to have the header pages removed.
8982  **/
8983 void
8984 lpfc_sli4_remove_rpi_hdrs(struct lpfc_hba *phba)
8985 {
8986 	struct lpfc_rpi_hdr *rpi_hdr, *next_rpi_hdr;
8987 
8988 	if (!phba->sli4_hba.rpi_hdrs_in_use)
8989 		goto exit;
8990 
8991 	list_for_each_entry_safe(rpi_hdr, next_rpi_hdr,
8992 				 &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
8993 		list_del(&rpi_hdr->list);
8994 		dma_free_coherent(&phba->pcidev->dev, rpi_hdr->len,
8995 				  rpi_hdr->dmabuf->virt, rpi_hdr->dmabuf->phys);
8996 		kfree(rpi_hdr->dmabuf);
8997 		kfree(rpi_hdr);
8998 	}
8999  exit:
9000 	/* There are no rpis available to the port now. */
9001 	phba->sli4_hba.next_rpi = 0;
9002 }
9003 
9004 /**
9005  * lpfc_hba_alloc - Allocate driver hba data structure for a device.
9006  * @pdev: pointer to pci device data structure.
9007  *
9008  * This routine is invoked to allocate the driver hba data structure for an
9009  * HBA device. If the allocation is successful, the phba reference to the
9010  * PCI device data structure is set.
9011  *
9012  * Return codes
9013  *      pointer to @phba - successful
9014  *      NULL - error
9015  **/
9016 static struct lpfc_hba *
9017 lpfc_hba_alloc(struct pci_dev *pdev)
9018 {
9019 	struct lpfc_hba *phba;
9020 
9021 	/* Allocate memory for HBA structure */
9022 	phba = kzalloc(sizeof(struct lpfc_hba), GFP_KERNEL);
9023 	if (!phba) {
9024 		dev_err(&pdev->dev, "failed to allocate hba struct\n");
9025 		return NULL;
9026 	}
9027 
9028 	/* Set reference to PCI device in HBA structure */
9029 	phba->pcidev = pdev;
9030 
9031 	/* Assign an unused board number */
9032 	phba->brd_no = lpfc_get_instance();
9033 	if (phba->brd_no < 0) {
9034 		kfree(phba);
9035 		return NULL;
9036 	}
9037 	phba->eratt_poll_interval = LPFC_ERATT_POLL_INTERVAL;
9038 
9039 	spin_lock_init(&phba->ct_ev_lock);
9040 	INIT_LIST_HEAD(&phba->ct_ev_waiters);
9041 
9042 	return phba;
9043 }
9044 
9045 /**
9046  * lpfc_hba_free - Free driver hba data structure with a device.
9047  * @phba: pointer to lpfc hba data structure.
9048  *
9049  * This routine is invoked to free the driver hba data structure with an
9050  * HBA device.
9051  **/
9052 static void
9053 lpfc_hba_free(struct lpfc_hba *phba)
9054 {
9055 	if (phba->sli_rev == LPFC_SLI_REV4)
9056 		kfree(phba->sli4_hba.hdwq);
9057 
9058 	/* Release the driver assigned board number */
9059 	idr_remove(&lpfc_hba_index, phba->brd_no);
9060 
9061 	/* Free memory allocated with sli3 rings */
9062 	kfree(phba->sli.sli3_ring);
9063 	phba->sli.sli3_ring = NULL;
9064 
9065 	kfree(phba);
9066 	return;
9067 }
9068 
9069 /**
9070  * lpfc_setup_fdmi_mask - Setup initial FDMI mask for HBA and Port attributes
9071  * @vport: pointer to lpfc vport data structure.
9072  *
9073  * This routine is will setup initial FDMI attribute masks for
9074  * FDMI2 or SmartSAN depending on module parameters. The driver will attempt
9075  * to get these attributes first before falling back, the attribute
9076  * fallback hierarchy is SmartSAN -> FDMI2 -> FMDI1
9077  **/
9078 void
9079 lpfc_setup_fdmi_mask(struct lpfc_vport *vport)
9080 {
9081 	struct lpfc_hba *phba = vport->phba;
9082 
9083 	set_bit(FC_ALLOW_FDMI, &vport->load_flag);
9084 	if (phba->cfg_enable_SmartSAN ||
9085 	    phba->cfg_fdmi_on == LPFC_FDMI_SUPPORT) {
9086 		/* Setup appropriate attribute masks */
9087 		vport->fdmi_hba_mask = LPFC_FDMI2_HBA_ATTR;
9088 		if (phba->cfg_enable_SmartSAN)
9089 			vport->fdmi_port_mask = LPFC_FDMI2_SMART_ATTR;
9090 		else
9091 			vport->fdmi_port_mask = LPFC_FDMI2_PORT_ATTR;
9092 	}
9093 
9094 	lpfc_printf_log(phba, KERN_INFO, LOG_DISCOVERY,
9095 			"6077 Setup FDMI mask: hba x%x port x%x\n",
9096 			vport->fdmi_hba_mask, vport->fdmi_port_mask);
9097 }
9098 
9099 /**
9100  * lpfc_create_shost - Create hba physical port with associated scsi host.
9101  * @phba: pointer to lpfc hba data structure.
9102  *
9103  * This routine is invoked to create HBA physical port and associate a SCSI
9104  * host with it.
9105  *
9106  * Return codes
9107  *      0 - successful
9108  *      other values - error
9109  **/
9110 static int
9111 lpfc_create_shost(struct lpfc_hba *phba)
9112 {
9113 	struct lpfc_vport *vport;
9114 	struct Scsi_Host  *shost;
9115 
9116 	/* Initialize HBA FC structure */
9117 	phba->fc_edtov = FF_DEF_EDTOV;
9118 	phba->fc_ratov = FF_DEF_RATOV;
9119 	phba->fc_altov = FF_DEF_ALTOV;
9120 	phba->fc_arbtov = FF_DEF_ARBTOV;
9121 
9122 	atomic_set(&phba->sdev_cnt, 0);
9123 	vport = lpfc_create_port(phba, phba->brd_no, &phba->pcidev->dev);
9124 	if (!vport)
9125 		return -ENODEV;
9126 
9127 	shost = lpfc_shost_from_vport(vport);
9128 	phba->pport = vport;
9129 
9130 	if (phba->nvmet_support) {
9131 		/* Only 1 vport (pport) will support NVME target */
9132 		phba->targetport = NULL;
9133 		phba->cfg_enable_fc4_type = LPFC_ENABLE_NVME;
9134 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_NVME_DISC,
9135 				"6076 NVME Target Found\n");
9136 	}
9137 
9138 	lpfc_debugfs_initialize(vport);
9139 	/* Put reference to SCSI host to driver's device private data */
9140 	pci_set_drvdata(phba->pcidev, shost);
9141 
9142 	lpfc_setup_fdmi_mask(vport);
9143 
9144 	/*
9145 	 * At this point we are fully registered with PSA. In addition,
9146 	 * any initial discovery should be completed.
9147 	 */
9148 	return 0;
9149 }
9150 
9151 /**
9152  * lpfc_destroy_shost - Destroy hba physical port with associated scsi host.
9153  * @phba: pointer to lpfc hba data structure.
9154  *
9155  * This routine is invoked to destroy HBA physical port and the associated
9156  * SCSI host.
9157  **/
9158 static void
9159 lpfc_destroy_shost(struct lpfc_hba *phba)
9160 {
9161 	struct lpfc_vport *vport = phba->pport;
9162 
9163 	/* Destroy physical port that associated with the SCSI host */
9164 	destroy_port(vport);
9165 
9166 	return;
9167 }
9168 
9169 /**
9170  * lpfc_setup_bg - Setup Block guard structures and debug areas.
9171  * @phba: pointer to lpfc hba data structure.
9172  * @shost: the shost to be used to detect Block guard settings.
9173  *
9174  * This routine sets up the local Block guard protocol settings for @shost.
9175  * This routine also allocates memory for debugging bg buffers.
9176  **/
9177 static void
9178 lpfc_setup_bg(struct lpfc_hba *phba, struct Scsi_Host *shost)
9179 {
9180 	uint32_t old_mask;
9181 	uint32_t old_guard;
9182 
9183 	if (phba->cfg_prot_mask && phba->cfg_prot_guard) {
9184 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9185 				"1478 Registering BlockGuard with the "
9186 				"SCSI layer\n");
9187 
9188 		old_mask = phba->cfg_prot_mask;
9189 		old_guard = phba->cfg_prot_guard;
9190 
9191 		/* Only allow supported values */
9192 		phba->cfg_prot_mask &= (SHOST_DIF_TYPE1_PROTECTION |
9193 			SHOST_DIX_TYPE0_PROTECTION |
9194 			SHOST_DIX_TYPE1_PROTECTION);
9195 		phba->cfg_prot_guard &= (SHOST_DIX_GUARD_IP |
9196 					 SHOST_DIX_GUARD_CRC);
9197 
9198 		/* DIF Type 1 protection for profiles AST1/C1 is end to end */
9199 		if (phba->cfg_prot_mask == SHOST_DIX_TYPE1_PROTECTION)
9200 			phba->cfg_prot_mask |= SHOST_DIF_TYPE1_PROTECTION;
9201 
9202 		if (phba->cfg_prot_mask && phba->cfg_prot_guard) {
9203 			if ((old_mask != phba->cfg_prot_mask) ||
9204 				(old_guard != phba->cfg_prot_guard))
9205 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9206 					"1475 Registering BlockGuard with the "
9207 					"SCSI layer: mask %d  guard %d\n",
9208 					phba->cfg_prot_mask,
9209 					phba->cfg_prot_guard);
9210 
9211 			scsi_host_set_prot(shost, phba->cfg_prot_mask);
9212 			scsi_host_set_guard(shost, phba->cfg_prot_guard);
9213 		} else
9214 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9215 				"1479 Not Registering BlockGuard with the SCSI "
9216 				"layer, Bad protection parameters: %d %d\n",
9217 				old_mask, old_guard);
9218 	}
9219 }
9220 
9221 /**
9222  * lpfc_post_init_setup - Perform necessary device post initialization setup.
9223  * @phba: pointer to lpfc hba data structure.
9224  *
9225  * This routine is invoked to perform all the necessary post initialization
9226  * setup for the device.
9227  **/
9228 static void
9229 lpfc_post_init_setup(struct lpfc_hba *phba)
9230 {
9231 	struct Scsi_Host  *shost;
9232 	struct lpfc_adapter_event_header adapter_event;
9233 
9234 	/* Get the default values for Model Name and Description */
9235 	lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
9236 
9237 	/*
9238 	 * hba setup may have changed the hba_queue_depth so we need to
9239 	 * adjust the value of can_queue.
9240 	 */
9241 	shost = pci_get_drvdata(phba->pcidev);
9242 	shost->can_queue = phba->cfg_hba_queue_depth - 10;
9243 
9244 	lpfc_host_attrib_init(shost);
9245 
9246 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
9247 		spin_lock_irq(shost->host_lock);
9248 		lpfc_poll_start_timer(phba);
9249 		spin_unlock_irq(shost->host_lock);
9250 	}
9251 
9252 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9253 			"0428 Perform SCSI scan\n");
9254 	/* Send board arrival event to upper layer */
9255 	adapter_event.event_type = FC_REG_ADAPTER_EVENT;
9256 	adapter_event.subcategory = LPFC_EVENT_ARRIVAL;
9257 	fc_host_post_vendor_event(shost, fc_get_event_number(),
9258 				  sizeof(adapter_event),
9259 				  (char *) &adapter_event,
9260 				  LPFC_NL_VENDOR_ID);
9261 	return;
9262 }
9263 
9264 /**
9265  * lpfc_sli_pci_mem_setup - Setup SLI3 HBA PCI memory space.
9266  * @phba: pointer to lpfc hba data structure.
9267  *
9268  * This routine is invoked to set up the PCI device memory space for device
9269  * with SLI-3 interface spec.
9270  *
9271  * Return codes
9272  * 	0 - successful
9273  * 	other values - error
9274  **/
9275 static int
9276 lpfc_sli_pci_mem_setup(struct lpfc_hba *phba)
9277 {
9278 	struct pci_dev *pdev = phba->pcidev;
9279 	unsigned long bar0map_len, bar2map_len;
9280 	int i, hbq_count;
9281 	void *ptr;
9282 	int error;
9283 
9284 	if (!pdev)
9285 		return -ENODEV;
9286 
9287 	/* Set the device DMA mask size */
9288 	error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
9289 	if (error)
9290 		error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32));
9291 	if (error)
9292 		return error;
9293 	error = -ENODEV;
9294 
9295 	/* Get the bus address of Bar0 and Bar2 and the number of bytes
9296 	 * required by each mapping.
9297 	 */
9298 	phba->pci_bar0_map = pci_resource_start(pdev, 0);
9299 	bar0map_len = pci_resource_len(pdev, 0);
9300 
9301 	phba->pci_bar2_map = pci_resource_start(pdev, 2);
9302 	bar2map_len = pci_resource_len(pdev, 2);
9303 
9304 	/* Map HBA SLIM to a kernel virtual address. */
9305 	phba->slim_memmap_p = ioremap(phba->pci_bar0_map, bar0map_len);
9306 	if (!phba->slim_memmap_p) {
9307 		dev_printk(KERN_ERR, &pdev->dev,
9308 			   "ioremap failed for SLIM memory.\n");
9309 		goto out;
9310 	}
9311 
9312 	/* Map HBA Control Registers to a kernel virtual address. */
9313 	phba->ctrl_regs_memmap_p = ioremap(phba->pci_bar2_map, bar2map_len);
9314 	if (!phba->ctrl_regs_memmap_p) {
9315 		dev_printk(KERN_ERR, &pdev->dev,
9316 			   "ioremap failed for HBA control registers.\n");
9317 		goto out_iounmap_slim;
9318 	}
9319 
9320 	/* Allocate memory for SLI-2 structures */
9321 	phba->slim2p.virt = dma_alloc_coherent(&pdev->dev, SLI2_SLIM_SIZE,
9322 					       &phba->slim2p.phys, GFP_KERNEL);
9323 	if (!phba->slim2p.virt)
9324 		goto out_iounmap;
9325 
9326 	phba->mbox = phba->slim2p.virt + offsetof(struct lpfc_sli2_slim, mbx);
9327 	phba->mbox_ext = (phba->slim2p.virt +
9328 		offsetof(struct lpfc_sli2_slim, mbx_ext_words));
9329 	phba->pcb = (phba->slim2p.virt + offsetof(struct lpfc_sli2_slim, pcb));
9330 	phba->IOCBs = (phba->slim2p.virt +
9331 		       offsetof(struct lpfc_sli2_slim, IOCBs));
9332 
9333 	phba->hbqslimp.virt = dma_alloc_coherent(&pdev->dev,
9334 						 lpfc_sli_hbq_size(),
9335 						 &phba->hbqslimp.phys,
9336 						 GFP_KERNEL);
9337 	if (!phba->hbqslimp.virt)
9338 		goto out_free_slim;
9339 
9340 	hbq_count = lpfc_sli_hbq_count();
9341 	ptr = phba->hbqslimp.virt;
9342 	for (i = 0; i < hbq_count; ++i) {
9343 		phba->hbqs[i].hbq_virt = ptr;
9344 		INIT_LIST_HEAD(&phba->hbqs[i].hbq_buffer_list);
9345 		ptr += (lpfc_hbq_defs[i]->entry_count *
9346 			sizeof(struct lpfc_hbq_entry));
9347 	}
9348 	phba->hbqs[LPFC_ELS_HBQ].hbq_alloc_buffer = lpfc_els_hbq_alloc;
9349 	phba->hbqs[LPFC_ELS_HBQ].hbq_free_buffer = lpfc_els_hbq_free;
9350 
9351 	memset(phba->hbqslimp.virt, 0, lpfc_sli_hbq_size());
9352 
9353 	phba->MBslimaddr = phba->slim_memmap_p;
9354 	phba->HAregaddr = phba->ctrl_regs_memmap_p + HA_REG_OFFSET;
9355 	phba->CAregaddr = phba->ctrl_regs_memmap_p + CA_REG_OFFSET;
9356 	phba->HSregaddr = phba->ctrl_regs_memmap_p + HS_REG_OFFSET;
9357 	phba->HCregaddr = phba->ctrl_regs_memmap_p + HC_REG_OFFSET;
9358 
9359 	return 0;
9360 
9361 out_free_slim:
9362 	dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
9363 			  phba->slim2p.virt, phba->slim2p.phys);
9364 out_iounmap:
9365 	iounmap(phba->ctrl_regs_memmap_p);
9366 out_iounmap_slim:
9367 	iounmap(phba->slim_memmap_p);
9368 out:
9369 	return error;
9370 }
9371 
9372 /**
9373  * lpfc_sli_pci_mem_unset - Unset SLI3 HBA PCI memory space.
9374  * @phba: pointer to lpfc hba data structure.
9375  *
9376  * This routine is invoked to unset the PCI device memory space for device
9377  * with SLI-3 interface spec.
9378  **/
9379 static void
9380 lpfc_sli_pci_mem_unset(struct lpfc_hba *phba)
9381 {
9382 	struct pci_dev *pdev;
9383 
9384 	/* Obtain PCI device reference */
9385 	if (!phba->pcidev)
9386 		return;
9387 	else
9388 		pdev = phba->pcidev;
9389 
9390 	/* Free coherent DMA memory allocated */
9391 	dma_free_coherent(&pdev->dev, lpfc_sli_hbq_size(),
9392 			  phba->hbqslimp.virt, phba->hbqslimp.phys);
9393 	dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
9394 			  phba->slim2p.virt, phba->slim2p.phys);
9395 
9396 	/* I/O memory unmap */
9397 	iounmap(phba->ctrl_regs_memmap_p);
9398 	iounmap(phba->slim_memmap_p);
9399 
9400 	return;
9401 }
9402 
9403 /**
9404  * lpfc_sli4_post_status_check - Wait for SLI4 POST done and check status
9405  * @phba: pointer to lpfc hba data structure.
9406  *
9407  * This routine is invoked to wait for SLI4 device Power On Self Test (POST)
9408  * done and check status.
9409  *
9410  * Return 0 if successful, otherwise -ENODEV.
9411  **/
9412 int
9413 lpfc_sli4_post_status_check(struct lpfc_hba *phba)
9414 {
9415 	struct lpfc_register portsmphr_reg, uerrlo_reg, uerrhi_reg;
9416 	struct lpfc_register reg_data;
9417 	int i, port_error = 0;
9418 	uint32_t if_type;
9419 
9420 	memset(&portsmphr_reg, 0, sizeof(portsmphr_reg));
9421 	memset(&reg_data, 0, sizeof(reg_data));
9422 	if (!phba->sli4_hba.PSMPHRregaddr)
9423 		return -ENODEV;
9424 
9425 	/* Wait up to 30 seconds for the SLI Port POST done and ready */
9426 	for (i = 0; i < 3000; i++) {
9427 		if (lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
9428 			&portsmphr_reg.word0) ||
9429 			(bf_get(lpfc_port_smphr_perr, &portsmphr_reg))) {
9430 			/* Port has a fatal POST error, break out */
9431 			port_error = -ENODEV;
9432 			break;
9433 		}
9434 		if (LPFC_POST_STAGE_PORT_READY ==
9435 		    bf_get(lpfc_port_smphr_port_status, &portsmphr_reg))
9436 			break;
9437 		msleep(10);
9438 	}
9439 
9440 	/*
9441 	 * If there was a port error during POST, then don't proceed with
9442 	 * other register reads as the data may not be valid.  Just exit.
9443 	 */
9444 	if (port_error) {
9445 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9446 			"1408 Port Failed POST - portsmphr=0x%x, "
9447 			"perr=x%x, sfi=x%x, nip=x%x, ipc=x%x, scr1=x%x, "
9448 			"scr2=x%x, hscratch=x%x, pstatus=x%x\n",
9449 			portsmphr_reg.word0,
9450 			bf_get(lpfc_port_smphr_perr, &portsmphr_reg),
9451 			bf_get(lpfc_port_smphr_sfi, &portsmphr_reg),
9452 			bf_get(lpfc_port_smphr_nip, &portsmphr_reg),
9453 			bf_get(lpfc_port_smphr_ipc, &portsmphr_reg),
9454 			bf_get(lpfc_port_smphr_scr1, &portsmphr_reg),
9455 			bf_get(lpfc_port_smphr_scr2, &portsmphr_reg),
9456 			bf_get(lpfc_port_smphr_host_scratch, &portsmphr_reg),
9457 			bf_get(lpfc_port_smphr_port_status, &portsmphr_reg));
9458 	} else {
9459 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9460 				"2534 Device Info: SLIFamily=0x%x, "
9461 				"SLIRev=0x%x, IFType=0x%x, SLIHint_1=0x%x, "
9462 				"SLIHint_2=0x%x, FT=0x%x\n",
9463 				bf_get(lpfc_sli_intf_sli_family,
9464 				       &phba->sli4_hba.sli_intf),
9465 				bf_get(lpfc_sli_intf_slirev,
9466 				       &phba->sli4_hba.sli_intf),
9467 				bf_get(lpfc_sli_intf_if_type,
9468 				       &phba->sli4_hba.sli_intf),
9469 				bf_get(lpfc_sli_intf_sli_hint1,
9470 				       &phba->sli4_hba.sli_intf),
9471 				bf_get(lpfc_sli_intf_sli_hint2,
9472 				       &phba->sli4_hba.sli_intf),
9473 				bf_get(lpfc_sli_intf_func_type,
9474 				       &phba->sli4_hba.sli_intf));
9475 		/*
9476 		 * Check for other Port errors during the initialization
9477 		 * process.  Fail the load if the port did not come up
9478 		 * correctly.
9479 		 */
9480 		if_type = bf_get(lpfc_sli_intf_if_type,
9481 				 &phba->sli4_hba.sli_intf);
9482 		switch (if_type) {
9483 		case LPFC_SLI_INTF_IF_TYPE_0:
9484 			phba->sli4_hba.ue_mask_lo =
9485 			      readl(phba->sli4_hba.u.if_type0.UEMASKLOregaddr);
9486 			phba->sli4_hba.ue_mask_hi =
9487 			      readl(phba->sli4_hba.u.if_type0.UEMASKHIregaddr);
9488 			uerrlo_reg.word0 =
9489 			      readl(phba->sli4_hba.u.if_type0.UERRLOregaddr);
9490 			uerrhi_reg.word0 =
9491 				readl(phba->sli4_hba.u.if_type0.UERRHIregaddr);
9492 			if ((~phba->sli4_hba.ue_mask_lo & uerrlo_reg.word0) ||
9493 			    (~phba->sli4_hba.ue_mask_hi & uerrhi_reg.word0)) {
9494 				lpfc_printf_log(phba, KERN_ERR,
9495 						LOG_TRACE_EVENT,
9496 						"1422 Unrecoverable Error "
9497 						"Detected during POST "
9498 						"uerr_lo_reg=0x%x, "
9499 						"uerr_hi_reg=0x%x, "
9500 						"ue_mask_lo_reg=0x%x, "
9501 						"ue_mask_hi_reg=0x%x\n",
9502 						uerrlo_reg.word0,
9503 						uerrhi_reg.word0,
9504 						phba->sli4_hba.ue_mask_lo,
9505 						phba->sli4_hba.ue_mask_hi);
9506 				port_error = -ENODEV;
9507 			}
9508 			break;
9509 		case LPFC_SLI_INTF_IF_TYPE_2:
9510 		case LPFC_SLI_INTF_IF_TYPE_6:
9511 			/* Final checks.  The port status should be clean. */
9512 			if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
9513 				&reg_data.word0) ||
9514 				lpfc_sli4_unrecoverable_port(&reg_data)) {
9515 				phba->work_status[0] =
9516 					readl(phba->sli4_hba.u.if_type2.
9517 					      ERR1regaddr);
9518 				phba->work_status[1] =
9519 					readl(phba->sli4_hba.u.if_type2.
9520 					      ERR2regaddr);
9521 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9522 					"2888 Unrecoverable port error "
9523 					"following POST: port status reg "
9524 					"0x%x, port_smphr reg 0x%x, "
9525 					"error 1=0x%x, error 2=0x%x\n",
9526 					reg_data.word0,
9527 					portsmphr_reg.word0,
9528 					phba->work_status[0],
9529 					phba->work_status[1]);
9530 				port_error = -ENODEV;
9531 				break;
9532 			}
9533 
9534 			if (lpfc_pldv_detect &&
9535 			    bf_get(lpfc_sli_intf_sli_family,
9536 				   &phba->sli4_hba.sli_intf) ==
9537 					LPFC_SLI_INTF_FAMILY_G6)
9538 				pci_write_config_byte(phba->pcidev,
9539 						      LPFC_SLI_INTF, CFG_PLD);
9540 			break;
9541 		case LPFC_SLI_INTF_IF_TYPE_1:
9542 		default:
9543 			break;
9544 		}
9545 	}
9546 	return port_error;
9547 }
9548 
9549 /**
9550  * lpfc_sli4_bar0_register_memmap - Set up SLI4 BAR0 register memory map.
9551  * @phba: pointer to lpfc hba data structure.
9552  * @if_type:  The SLI4 interface type getting configured.
9553  *
9554  * This routine is invoked to set up SLI4 BAR0 PCI config space register
9555  * memory map.
9556  **/
9557 static void
9558 lpfc_sli4_bar0_register_memmap(struct lpfc_hba *phba, uint32_t if_type)
9559 {
9560 	switch (if_type) {
9561 	case LPFC_SLI_INTF_IF_TYPE_0:
9562 		phba->sli4_hba.u.if_type0.UERRLOregaddr =
9563 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UERR_STATUS_LO;
9564 		phba->sli4_hba.u.if_type0.UERRHIregaddr =
9565 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UERR_STATUS_HI;
9566 		phba->sli4_hba.u.if_type0.UEMASKLOregaddr =
9567 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UE_MASK_LO;
9568 		phba->sli4_hba.u.if_type0.UEMASKHIregaddr =
9569 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UE_MASK_HI;
9570 		phba->sli4_hba.SLIINTFregaddr =
9571 			phba->sli4_hba.conf_regs_memmap_p + LPFC_SLI_INTF;
9572 		break;
9573 	case LPFC_SLI_INTF_IF_TYPE_2:
9574 		phba->sli4_hba.u.if_type2.EQDregaddr =
9575 			phba->sli4_hba.conf_regs_memmap_p +
9576 						LPFC_CTL_PORT_EQ_DELAY_OFFSET;
9577 		phba->sli4_hba.u.if_type2.ERR1regaddr =
9578 			phba->sli4_hba.conf_regs_memmap_p +
9579 						LPFC_CTL_PORT_ER1_OFFSET;
9580 		phba->sli4_hba.u.if_type2.ERR2regaddr =
9581 			phba->sli4_hba.conf_regs_memmap_p +
9582 						LPFC_CTL_PORT_ER2_OFFSET;
9583 		phba->sli4_hba.u.if_type2.CTRLregaddr =
9584 			phba->sli4_hba.conf_regs_memmap_p +
9585 						LPFC_CTL_PORT_CTL_OFFSET;
9586 		phba->sli4_hba.u.if_type2.STATUSregaddr =
9587 			phba->sli4_hba.conf_regs_memmap_p +
9588 						LPFC_CTL_PORT_STA_OFFSET;
9589 		phba->sli4_hba.SLIINTFregaddr =
9590 			phba->sli4_hba.conf_regs_memmap_p + LPFC_SLI_INTF;
9591 		phba->sli4_hba.PSMPHRregaddr =
9592 			phba->sli4_hba.conf_regs_memmap_p +
9593 						LPFC_CTL_PORT_SEM_OFFSET;
9594 		phba->sli4_hba.RQDBregaddr =
9595 			phba->sli4_hba.conf_regs_memmap_p +
9596 						LPFC_ULP0_RQ_DOORBELL;
9597 		phba->sli4_hba.WQDBregaddr =
9598 			phba->sli4_hba.conf_regs_memmap_p +
9599 						LPFC_ULP0_WQ_DOORBELL;
9600 		phba->sli4_hba.CQDBregaddr =
9601 			phba->sli4_hba.conf_regs_memmap_p + LPFC_EQCQ_DOORBELL;
9602 		phba->sli4_hba.EQDBregaddr = phba->sli4_hba.CQDBregaddr;
9603 		phba->sli4_hba.MQDBregaddr =
9604 			phba->sli4_hba.conf_regs_memmap_p + LPFC_MQ_DOORBELL;
9605 		phba->sli4_hba.BMBXregaddr =
9606 			phba->sli4_hba.conf_regs_memmap_p + LPFC_BMBX;
9607 		break;
9608 	case LPFC_SLI_INTF_IF_TYPE_6:
9609 		phba->sli4_hba.u.if_type2.EQDregaddr =
9610 			phba->sli4_hba.conf_regs_memmap_p +
9611 						LPFC_CTL_PORT_EQ_DELAY_OFFSET;
9612 		phba->sli4_hba.u.if_type2.ERR1regaddr =
9613 			phba->sli4_hba.conf_regs_memmap_p +
9614 						LPFC_CTL_PORT_ER1_OFFSET;
9615 		phba->sli4_hba.u.if_type2.ERR2regaddr =
9616 			phba->sli4_hba.conf_regs_memmap_p +
9617 						LPFC_CTL_PORT_ER2_OFFSET;
9618 		phba->sli4_hba.u.if_type2.CTRLregaddr =
9619 			phba->sli4_hba.conf_regs_memmap_p +
9620 						LPFC_CTL_PORT_CTL_OFFSET;
9621 		phba->sli4_hba.u.if_type2.STATUSregaddr =
9622 			phba->sli4_hba.conf_regs_memmap_p +
9623 						LPFC_CTL_PORT_STA_OFFSET;
9624 		phba->sli4_hba.PSMPHRregaddr =
9625 			phba->sli4_hba.conf_regs_memmap_p +
9626 						LPFC_CTL_PORT_SEM_OFFSET;
9627 		phba->sli4_hba.BMBXregaddr =
9628 			phba->sli4_hba.conf_regs_memmap_p + LPFC_BMBX;
9629 		break;
9630 	case LPFC_SLI_INTF_IF_TYPE_1:
9631 	default:
9632 		dev_printk(KERN_ERR, &phba->pcidev->dev,
9633 			   "FATAL - unsupported SLI4 interface type - %d\n",
9634 			   if_type);
9635 		break;
9636 	}
9637 }
9638 
9639 /**
9640  * lpfc_sli4_bar1_register_memmap - Set up SLI4 BAR1 register memory map.
9641  * @phba: pointer to lpfc hba data structure.
9642  * @if_type: sli if type to operate on.
9643  *
9644  * This routine is invoked to set up SLI4 BAR1 register memory map.
9645  **/
9646 static void
9647 lpfc_sli4_bar1_register_memmap(struct lpfc_hba *phba, uint32_t if_type)
9648 {
9649 	switch (if_type) {
9650 	case LPFC_SLI_INTF_IF_TYPE_0:
9651 		phba->sli4_hba.PSMPHRregaddr =
9652 			phba->sli4_hba.ctrl_regs_memmap_p +
9653 			LPFC_SLIPORT_IF0_SMPHR;
9654 		phba->sli4_hba.ISRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
9655 			LPFC_HST_ISR0;
9656 		phba->sli4_hba.IMRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
9657 			LPFC_HST_IMR0;
9658 		phba->sli4_hba.ISCRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
9659 			LPFC_HST_ISCR0;
9660 		break;
9661 	case LPFC_SLI_INTF_IF_TYPE_6:
9662 		phba->sli4_hba.RQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9663 			LPFC_IF6_RQ_DOORBELL;
9664 		phba->sli4_hba.WQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9665 			LPFC_IF6_WQ_DOORBELL;
9666 		phba->sli4_hba.CQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9667 			LPFC_IF6_CQ_DOORBELL;
9668 		phba->sli4_hba.EQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9669 			LPFC_IF6_EQ_DOORBELL;
9670 		phba->sli4_hba.MQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9671 			LPFC_IF6_MQ_DOORBELL;
9672 		break;
9673 	case LPFC_SLI_INTF_IF_TYPE_2:
9674 	case LPFC_SLI_INTF_IF_TYPE_1:
9675 	default:
9676 		dev_err(&phba->pcidev->dev,
9677 			   "FATAL - unsupported SLI4 interface type - %d\n",
9678 			   if_type);
9679 		break;
9680 	}
9681 }
9682 
9683 /**
9684  * lpfc_sli4_bar2_register_memmap - Set up SLI4 BAR2 register memory map.
9685  * @phba: pointer to lpfc hba data structure.
9686  * @vf: virtual function number
9687  *
9688  * This routine is invoked to set up SLI4 BAR2 doorbell register memory map
9689  * based on the given viftual function number, @vf.
9690  *
9691  * Return 0 if successful, otherwise -ENODEV.
9692  **/
9693 static int
9694 lpfc_sli4_bar2_register_memmap(struct lpfc_hba *phba, uint32_t vf)
9695 {
9696 	if (vf > LPFC_VIR_FUNC_MAX)
9697 		return -ENODEV;
9698 
9699 	phba->sli4_hba.RQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9700 				vf * LPFC_VFR_PAGE_SIZE +
9701 					LPFC_ULP0_RQ_DOORBELL);
9702 	phba->sli4_hba.WQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9703 				vf * LPFC_VFR_PAGE_SIZE +
9704 					LPFC_ULP0_WQ_DOORBELL);
9705 	phba->sli4_hba.CQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9706 				vf * LPFC_VFR_PAGE_SIZE +
9707 					LPFC_EQCQ_DOORBELL);
9708 	phba->sli4_hba.EQDBregaddr = phba->sli4_hba.CQDBregaddr;
9709 	phba->sli4_hba.MQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9710 				vf * LPFC_VFR_PAGE_SIZE + LPFC_MQ_DOORBELL);
9711 	phba->sli4_hba.BMBXregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9712 				vf * LPFC_VFR_PAGE_SIZE + LPFC_BMBX);
9713 	return 0;
9714 }
9715 
9716 /**
9717  * lpfc_create_bootstrap_mbox - Create the bootstrap mailbox
9718  * @phba: pointer to lpfc hba data structure.
9719  *
9720  * This routine is invoked to create the bootstrap mailbox
9721  * region consistent with the SLI-4 interface spec.  This
9722  * routine allocates all memory necessary to communicate
9723  * mailbox commands to the port and sets up all alignment
9724  * needs.  No locks are expected to be held when calling
9725  * this routine.
9726  *
9727  * Return codes
9728  * 	0 - successful
9729  * 	-ENOMEM - could not allocated memory.
9730  **/
9731 static int
9732 lpfc_create_bootstrap_mbox(struct lpfc_hba *phba)
9733 {
9734 	uint32_t bmbx_size;
9735 	struct lpfc_dmabuf *dmabuf;
9736 	struct dma_address *dma_address;
9737 	uint32_t pa_addr;
9738 	uint64_t phys_addr;
9739 
9740 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
9741 	if (!dmabuf)
9742 		return -ENOMEM;
9743 
9744 	/*
9745 	 * The bootstrap mailbox region is comprised of 2 parts
9746 	 * plus an alignment restriction of 16 bytes.
9747 	 */
9748 	bmbx_size = sizeof(struct lpfc_bmbx_create) + (LPFC_ALIGN_16_BYTE - 1);
9749 	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev, bmbx_size,
9750 					  &dmabuf->phys, GFP_KERNEL);
9751 	if (!dmabuf->virt) {
9752 		kfree(dmabuf);
9753 		return -ENOMEM;
9754 	}
9755 
9756 	/*
9757 	 * Initialize the bootstrap mailbox pointers now so that the register
9758 	 * operations are simple later.  The mailbox dma address is required
9759 	 * to be 16-byte aligned.  Also align the virtual memory as each
9760 	 * maibox is copied into the bmbx mailbox region before issuing the
9761 	 * command to the port.
9762 	 */
9763 	phba->sli4_hba.bmbx.dmabuf = dmabuf;
9764 	phba->sli4_hba.bmbx.bmbx_size = bmbx_size;
9765 
9766 	phba->sli4_hba.bmbx.avirt = PTR_ALIGN(dmabuf->virt,
9767 					      LPFC_ALIGN_16_BYTE);
9768 	phba->sli4_hba.bmbx.aphys = ALIGN(dmabuf->phys,
9769 					      LPFC_ALIGN_16_BYTE);
9770 
9771 	/*
9772 	 * Set the high and low physical addresses now.  The SLI4 alignment
9773 	 * requirement is 16 bytes and the mailbox is posted to the port
9774 	 * as two 30-bit addresses.  The other data is a bit marking whether
9775 	 * the 30-bit address is the high or low address.
9776 	 * Upcast bmbx aphys to 64bits so shift instruction compiles
9777 	 * clean on 32 bit machines.
9778 	 */
9779 	dma_address = &phba->sli4_hba.bmbx.dma_address;
9780 	phys_addr = (uint64_t)phba->sli4_hba.bmbx.aphys;
9781 	pa_addr = (uint32_t) ((phys_addr >> 34) & 0x3fffffff);
9782 	dma_address->addr_hi = (uint32_t) ((pa_addr << 2) |
9783 					   LPFC_BMBX_BIT1_ADDR_HI);
9784 
9785 	pa_addr = (uint32_t) ((phba->sli4_hba.bmbx.aphys >> 4) & 0x3fffffff);
9786 	dma_address->addr_lo = (uint32_t) ((pa_addr << 2) |
9787 					   LPFC_BMBX_BIT1_ADDR_LO);
9788 	return 0;
9789 }
9790 
9791 /**
9792  * lpfc_destroy_bootstrap_mbox - Destroy all bootstrap mailbox resources
9793  * @phba: pointer to lpfc hba data structure.
9794  *
9795  * This routine is invoked to teardown the bootstrap mailbox
9796  * region and release all host resources. This routine requires
9797  * the caller to ensure all mailbox commands recovered, no
9798  * additional mailbox comands are sent, and interrupts are disabled
9799  * before calling this routine.
9800  *
9801  **/
9802 static void
9803 lpfc_destroy_bootstrap_mbox(struct lpfc_hba *phba)
9804 {
9805 	dma_free_coherent(&phba->pcidev->dev,
9806 			  phba->sli4_hba.bmbx.bmbx_size,
9807 			  phba->sli4_hba.bmbx.dmabuf->virt,
9808 			  phba->sli4_hba.bmbx.dmabuf->phys);
9809 
9810 	kfree(phba->sli4_hba.bmbx.dmabuf);
9811 	memset(&phba->sli4_hba.bmbx, 0, sizeof(struct lpfc_bmbx));
9812 }
9813 
9814 static const char * const lpfc_topo_to_str[] = {
9815 	"Loop then P2P",
9816 	"Loopback",
9817 	"P2P Only",
9818 	"Unsupported",
9819 	"Loop Only",
9820 	"Unsupported",
9821 	"P2P then Loop",
9822 };
9823 
9824 #define	LINK_FLAGS_DEF	0x0
9825 #define	LINK_FLAGS_P2P	0x1
9826 #define	LINK_FLAGS_LOOP	0x2
9827 /**
9828  * lpfc_map_topology - Map the topology read from READ_CONFIG
9829  * @phba: pointer to lpfc hba data structure.
9830  * @rd_config: pointer to read config data
9831  *
9832  * This routine is invoked to map the topology values as read
9833  * from the read config mailbox command. If the persistent
9834  * topology feature is supported, the firmware will provide the
9835  * saved topology information to be used in INIT_LINK
9836  **/
9837 static void
9838 lpfc_map_topology(struct lpfc_hba *phba, struct lpfc_mbx_read_config *rd_config)
9839 {
9840 	u8 ptv, tf, pt;
9841 
9842 	ptv = bf_get(lpfc_mbx_rd_conf_ptv, rd_config);
9843 	tf = bf_get(lpfc_mbx_rd_conf_tf, rd_config);
9844 	pt = bf_get(lpfc_mbx_rd_conf_pt, rd_config);
9845 
9846 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9847 			"2027 Read Config Data : ptv:0x%x, tf:0x%x pt:0x%x",
9848 			 ptv, tf, pt);
9849 	if (!ptv) {
9850 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9851 				"2019 FW does not support persistent topology "
9852 				"Using driver parameter defined value [%s]",
9853 				lpfc_topo_to_str[phba->cfg_topology]);
9854 		return;
9855 	}
9856 	/* FW supports persistent topology - override module parameter value */
9857 	set_bit(HBA_PERSISTENT_TOPO, &phba->hba_flag);
9858 
9859 	/* if ASIC_GEN_NUM >= 0xC) */
9860 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
9861 		    LPFC_SLI_INTF_IF_TYPE_6) ||
9862 	    (bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf) ==
9863 		    LPFC_SLI_INTF_FAMILY_G6)) {
9864 		if (!tf)
9865 			phba->cfg_topology = ((pt == LINK_FLAGS_LOOP)
9866 					? FLAGS_TOPOLOGY_MODE_LOOP
9867 					: FLAGS_TOPOLOGY_MODE_PT_PT);
9868 		else
9869 			clear_bit(HBA_PERSISTENT_TOPO, &phba->hba_flag);
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 	if (test_bit(HBA_PERSISTENT_TOPO, &phba->hba_flag))
9881 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9882 				"2020 Using persistent topology value [%s]",
9883 				lpfc_topo_to_str[phba->cfg_topology]);
9884 	else
9885 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9886 				"2021 Invalid topology values from FW "
9887 				"Using driver parameter defined value [%s]",
9888 				lpfc_topo_to_str[phba->cfg_topology]);
9889 }
9890 
9891 /**
9892  * lpfc_sli4_read_config - Get the config parameters.
9893  * @phba: pointer to lpfc hba data structure.
9894  *
9895  * This routine is invoked to read the configuration parameters from the HBA.
9896  * The configuration parameters are used to set the base and maximum values
9897  * for RPI's XRI's VPI's VFI's and FCFIs. These values also affect the resource
9898  * allocation for the port.
9899  *
9900  * Return codes
9901  * 	0 - successful
9902  * 	-ENOMEM - No available memory
9903  *      -EIO - The mailbox failed to complete successfully.
9904  **/
9905 int
9906 lpfc_sli4_read_config(struct lpfc_hba *phba)
9907 {
9908 	LPFC_MBOXQ_t *pmb;
9909 	struct lpfc_mbx_read_config *rd_config;
9910 	union  lpfc_sli4_cfg_shdr *shdr;
9911 	uint32_t shdr_status, shdr_add_status;
9912 	struct lpfc_mbx_get_func_cfg *get_func_cfg;
9913 	struct lpfc_rsrc_desc_fcfcoe *desc;
9914 	char *pdesc_0;
9915 	uint16_t forced_link_speed;
9916 	uint32_t if_type, qmin, fawwpn;
9917 	int length, i, rc = 0, rc2;
9918 
9919 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
9920 	if (!pmb) {
9921 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9922 				"2011 Unable to allocate memory for issuing "
9923 				"SLI_CONFIG_SPECIAL mailbox command\n");
9924 		return -ENOMEM;
9925 	}
9926 
9927 	lpfc_read_config(phba, pmb);
9928 
9929 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
9930 	if (rc != MBX_SUCCESS) {
9931 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9932 				"2012 Mailbox failed , mbxCmd x%x "
9933 				"READ_CONFIG, mbxStatus x%x\n",
9934 				bf_get(lpfc_mqe_command, &pmb->u.mqe),
9935 				bf_get(lpfc_mqe_status, &pmb->u.mqe));
9936 		rc = -EIO;
9937 	} else {
9938 		rd_config = &pmb->u.mqe.un.rd_config;
9939 		if (bf_get(lpfc_mbx_rd_conf_lnk_ldv, rd_config)) {
9940 			phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL;
9941 			phba->sli4_hba.lnk_info.lnk_tp =
9942 				bf_get(lpfc_mbx_rd_conf_lnk_type, rd_config);
9943 			phba->sli4_hba.lnk_info.lnk_no =
9944 				bf_get(lpfc_mbx_rd_conf_lnk_numb, rd_config);
9945 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9946 					"3081 lnk_type:%d, lnk_numb:%d\n",
9947 					phba->sli4_hba.lnk_info.lnk_tp,
9948 					phba->sli4_hba.lnk_info.lnk_no);
9949 		} else
9950 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9951 					"3082 Mailbox (x%x) returned ldv:x0\n",
9952 					bf_get(lpfc_mqe_command, &pmb->u.mqe));
9953 		if (bf_get(lpfc_mbx_rd_conf_bbscn_def, rd_config)) {
9954 			phba->bbcredit_support = 1;
9955 			phba->sli4_hba.bbscn_params.word0 = rd_config->word8;
9956 		}
9957 
9958 		fawwpn = bf_get(lpfc_mbx_rd_conf_fawwpn, rd_config);
9959 
9960 		if (fawwpn) {
9961 			lpfc_printf_log(phba, KERN_INFO,
9962 					LOG_INIT | LOG_DISCOVERY,
9963 					"2702 READ_CONFIG: FA-PWWN is "
9964 					"configured on\n");
9965 			phba->sli4_hba.fawwpn_flag |= LPFC_FAWWPN_CONFIG;
9966 		} else {
9967 			/* Clear FW configured flag, preserve driver flag */
9968 			phba->sli4_hba.fawwpn_flag &= ~LPFC_FAWWPN_CONFIG;
9969 		}
9970 
9971 		phba->sli4_hba.conf_trunk =
9972 			bf_get(lpfc_mbx_rd_conf_trunk, rd_config);
9973 		phba->sli4_hba.extents_in_use =
9974 			bf_get(lpfc_mbx_rd_conf_extnts_inuse, rd_config);
9975 
9976 		phba->sli4_hba.max_cfg_param.max_xri =
9977 			bf_get(lpfc_mbx_rd_conf_xri_count, rd_config);
9978 		/* Reduce resource usage in kdump environment */
9979 		if (is_kdump_kernel() &&
9980 		    phba->sli4_hba.max_cfg_param.max_xri > 512)
9981 			phba->sli4_hba.max_cfg_param.max_xri = 512;
9982 		phba->sli4_hba.max_cfg_param.xri_base =
9983 			bf_get(lpfc_mbx_rd_conf_xri_base, rd_config);
9984 		phba->sli4_hba.max_cfg_param.max_vpi =
9985 			bf_get(lpfc_mbx_rd_conf_vpi_count, rd_config);
9986 		/* Limit the max we support */
9987 		if (phba->sli4_hba.max_cfg_param.max_vpi > LPFC_MAX_VPORTS)
9988 			phba->sli4_hba.max_cfg_param.max_vpi = LPFC_MAX_VPORTS;
9989 		phba->sli4_hba.max_cfg_param.vpi_base =
9990 			bf_get(lpfc_mbx_rd_conf_vpi_base, rd_config);
9991 		phba->sli4_hba.max_cfg_param.max_rpi =
9992 			bf_get(lpfc_mbx_rd_conf_rpi_count, rd_config);
9993 		phba->sli4_hba.max_cfg_param.rpi_base =
9994 			bf_get(lpfc_mbx_rd_conf_rpi_base, rd_config);
9995 		phba->sli4_hba.max_cfg_param.max_vfi =
9996 			bf_get(lpfc_mbx_rd_conf_vfi_count, rd_config);
9997 		phba->sli4_hba.max_cfg_param.vfi_base =
9998 			bf_get(lpfc_mbx_rd_conf_vfi_base, rd_config);
9999 		phba->sli4_hba.max_cfg_param.max_fcfi =
10000 			bf_get(lpfc_mbx_rd_conf_fcfi_count, rd_config);
10001 		phba->sli4_hba.max_cfg_param.max_eq =
10002 			bf_get(lpfc_mbx_rd_conf_eq_count, rd_config);
10003 		phba->sli4_hba.max_cfg_param.max_rq =
10004 			bf_get(lpfc_mbx_rd_conf_rq_count, rd_config);
10005 		phba->sli4_hba.max_cfg_param.max_wq =
10006 			bf_get(lpfc_mbx_rd_conf_wq_count, rd_config);
10007 		phba->sli4_hba.max_cfg_param.max_cq =
10008 			bf_get(lpfc_mbx_rd_conf_cq_count, rd_config);
10009 		phba->lmt = bf_get(lpfc_mbx_rd_conf_lmt, rd_config);
10010 		phba->sli4_hba.next_xri = phba->sli4_hba.max_cfg_param.xri_base;
10011 		phba->vpi_base = phba->sli4_hba.max_cfg_param.vpi_base;
10012 		phba->vfi_base = phba->sli4_hba.max_cfg_param.vfi_base;
10013 		phba->max_vpi = (phba->sli4_hba.max_cfg_param.max_vpi > 0) ?
10014 				(phba->sli4_hba.max_cfg_param.max_vpi - 1) : 0;
10015 		phba->max_vports = phba->max_vpi;
10016 
10017 		/* Next decide on FPIN or Signal E2E CGN support
10018 		 * For congestion alarms and warnings valid combination are:
10019 		 * 1. FPIN alarms / FPIN warnings
10020 		 * 2. Signal alarms / Signal warnings
10021 		 * 3. FPIN alarms / Signal warnings
10022 		 * 4. Signal alarms / FPIN warnings
10023 		 *
10024 		 * Initialize the adapter frequency to 100 mSecs
10025 		 */
10026 		phba->cgn_reg_fpin = LPFC_CGN_FPIN_BOTH;
10027 		phba->cgn_reg_signal = EDC_CG_SIG_NOTSUPPORTED;
10028 		phba->cgn_sig_freq = lpfc_fabric_cgn_frequency;
10029 
10030 		if (lpfc_use_cgn_signal) {
10031 			if (bf_get(lpfc_mbx_rd_conf_wcs, rd_config)) {
10032 				phba->cgn_reg_signal = EDC_CG_SIG_WARN_ONLY;
10033 				phba->cgn_reg_fpin &= ~LPFC_CGN_FPIN_WARN;
10034 			}
10035 			if (bf_get(lpfc_mbx_rd_conf_acs, rd_config)) {
10036 				/* MUST support both alarm and warning
10037 				 * because EDC does not support alarm alone.
10038 				 */
10039 				if (phba->cgn_reg_signal !=
10040 				    EDC_CG_SIG_WARN_ONLY) {
10041 					/* Must support both or none */
10042 					phba->cgn_reg_fpin = LPFC_CGN_FPIN_BOTH;
10043 					phba->cgn_reg_signal =
10044 						EDC_CG_SIG_NOTSUPPORTED;
10045 				} else {
10046 					phba->cgn_reg_signal =
10047 						EDC_CG_SIG_WARN_ALARM;
10048 					phba->cgn_reg_fpin =
10049 						LPFC_CGN_FPIN_NONE;
10050 				}
10051 			}
10052 		}
10053 
10054 		/* Set the congestion initial signal and fpin values. */
10055 		phba->cgn_init_reg_fpin = phba->cgn_reg_fpin;
10056 		phba->cgn_init_reg_signal = phba->cgn_reg_signal;
10057 
10058 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
10059 				"6446 READ_CONFIG reg_sig x%x reg_fpin:x%x\n",
10060 				phba->cgn_reg_signal, phba->cgn_reg_fpin);
10061 
10062 		lpfc_map_topology(phba, rd_config);
10063 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10064 				"2003 cfg params Extents? %d "
10065 				"XRI(B:%d M:%d), "
10066 				"VPI(B:%d M:%d) "
10067 				"VFI(B:%d M:%d) "
10068 				"RPI(B:%d M:%d) "
10069 				"FCFI:%d EQ:%d CQ:%d WQ:%d RQ:%d lmt:x%x\n",
10070 				phba->sli4_hba.extents_in_use,
10071 				phba->sli4_hba.max_cfg_param.xri_base,
10072 				phba->sli4_hba.max_cfg_param.max_xri,
10073 				phba->sli4_hba.max_cfg_param.vpi_base,
10074 				phba->sli4_hba.max_cfg_param.max_vpi,
10075 				phba->sli4_hba.max_cfg_param.vfi_base,
10076 				phba->sli4_hba.max_cfg_param.max_vfi,
10077 				phba->sli4_hba.max_cfg_param.rpi_base,
10078 				phba->sli4_hba.max_cfg_param.max_rpi,
10079 				phba->sli4_hba.max_cfg_param.max_fcfi,
10080 				phba->sli4_hba.max_cfg_param.max_eq,
10081 				phba->sli4_hba.max_cfg_param.max_cq,
10082 				phba->sli4_hba.max_cfg_param.max_wq,
10083 				phba->sli4_hba.max_cfg_param.max_rq,
10084 				phba->lmt);
10085 
10086 		/*
10087 		 * Calculate queue resources based on how
10088 		 * many WQ/CQ/EQs are available.
10089 		 */
10090 		qmin = phba->sli4_hba.max_cfg_param.max_wq;
10091 		if (phba->sli4_hba.max_cfg_param.max_cq < qmin)
10092 			qmin = phba->sli4_hba.max_cfg_param.max_cq;
10093 		/*
10094 		 * Reserve 4 (ELS, NVME LS, MBOX, plus one extra) and
10095 		 * the remainder can be used for NVME / FCP.
10096 		 */
10097 		qmin -= 4;
10098 		if (phba->sli4_hba.max_cfg_param.max_eq < qmin)
10099 			qmin = phba->sli4_hba.max_cfg_param.max_eq;
10100 
10101 		/* Check to see if there is enough for default cfg */
10102 		if ((phba->cfg_irq_chann > qmin) ||
10103 		    (phba->cfg_hdw_queue > qmin)) {
10104 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10105 					"2005 Reducing Queues - "
10106 					"FW resource limitation: "
10107 					"WQ %d CQ %d EQ %d: min %d: "
10108 					"IRQ %d HDWQ %d\n",
10109 					phba->sli4_hba.max_cfg_param.max_wq,
10110 					phba->sli4_hba.max_cfg_param.max_cq,
10111 					phba->sli4_hba.max_cfg_param.max_eq,
10112 					qmin, phba->cfg_irq_chann,
10113 					phba->cfg_hdw_queue);
10114 
10115 			if (phba->cfg_irq_chann > qmin)
10116 				phba->cfg_irq_chann = qmin;
10117 			if (phba->cfg_hdw_queue > qmin)
10118 				phba->cfg_hdw_queue = qmin;
10119 		}
10120 	}
10121 
10122 	if (rc)
10123 		goto read_cfg_out;
10124 
10125 	/* Update link speed if forced link speed is supported */
10126 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
10127 	if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
10128 		forced_link_speed =
10129 			bf_get(lpfc_mbx_rd_conf_link_speed, rd_config);
10130 		if (forced_link_speed) {
10131 			set_bit(HBA_FORCED_LINK_SPEED, &phba->hba_flag);
10132 
10133 			switch (forced_link_speed) {
10134 			case LINK_SPEED_1G:
10135 				phba->cfg_link_speed =
10136 					LPFC_USER_LINK_SPEED_1G;
10137 				break;
10138 			case LINK_SPEED_2G:
10139 				phba->cfg_link_speed =
10140 					LPFC_USER_LINK_SPEED_2G;
10141 				break;
10142 			case LINK_SPEED_4G:
10143 				phba->cfg_link_speed =
10144 					LPFC_USER_LINK_SPEED_4G;
10145 				break;
10146 			case LINK_SPEED_8G:
10147 				phba->cfg_link_speed =
10148 					LPFC_USER_LINK_SPEED_8G;
10149 				break;
10150 			case LINK_SPEED_10G:
10151 				phba->cfg_link_speed =
10152 					LPFC_USER_LINK_SPEED_10G;
10153 				break;
10154 			case LINK_SPEED_16G:
10155 				phba->cfg_link_speed =
10156 					LPFC_USER_LINK_SPEED_16G;
10157 				break;
10158 			case LINK_SPEED_32G:
10159 				phba->cfg_link_speed =
10160 					LPFC_USER_LINK_SPEED_32G;
10161 				break;
10162 			case LINK_SPEED_64G:
10163 				phba->cfg_link_speed =
10164 					LPFC_USER_LINK_SPEED_64G;
10165 				break;
10166 			case 0xffff:
10167 				phba->cfg_link_speed =
10168 					LPFC_USER_LINK_SPEED_AUTO;
10169 				break;
10170 			default:
10171 				lpfc_printf_log(phba, KERN_ERR,
10172 						LOG_TRACE_EVENT,
10173 						"0047 Unrecognized link "
10174 						"speed : %d\n",
10175 						forced_link_speed);
10176 				phba->cfg_link_speed =
10177 					LPFC_USER_LINK_SPEED_AUTO;
10178 			}
10179 		}
10180 	}
10181 
10182 	/* Reset the DFT_HBA_Q_DEPTH to the max xri  */
10183 	length = phba->sli4_hba.max_cfg_param.max_xri -
10184 			lpfc_sli4_get_els_iocb_cnt(phba);
10185 	if (phba->cfg_hba_queue_depth > length) {
10186 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
10187 				"3361 HBA queue depth changed from %d to %d\n",
10188 				phba->cfg_hba_queue_depth, length);
10189 		phba->cfg_hba_queue_depth = length;
10190 	}
10191 
10192 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) <
10193 	    LPFC_SLI_INTF_IF_TYPE_2)
10194 		goto read_cfg_out;
10195 
10196 	/* get the pf# and vf# for SLI4 if_type 2 port */
10197 	length = (sizeof(struct lpfc_mbx_get_func_cfg) -
10198 		  sizeof(struct lpfc_sli4_cfg_mhdr));
10199 	lpfc_sli4_config(phba, pmb, LPFC_MBOX_SUBSYSTEM_COMMON,
10200 			 LPFC_MBOX_OPCODE_GET_FUNCTION_CONFIG,
10201 			 length, LPFC_SLI4_MBX_EMBED);
10202 
10203 	rc2 = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
10204 	shdr = (union lpfc_sli4_cfg_shdr *)
10205 				&pmb->u.mqe.un.sli4_config.header.cfg_shdr;
10206 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
10207 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
10208 	if (rc2 || shdr_status || shdr_add_status) {
10209 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10210 				"3026 Mailbox failed , mbxCmd x%x "
10211 				"GET_FUNCTION_CONFIG, mbxStatus x%x\n",
10212 				bf_get(lpfc_mqe_command, &pmb->u.mqe),
10213 				bf_get(lpfc_mqe_status, &pmb->u.mqe));
10214 		goto read_cfg_out;
10215 	}
10216 
10217 	/* search for fc_fcoe resrouce descriptor */
10218 	get_func_cfg = &pmb->u.mqe.un.get_func_cfg;
10219 
10220 	pdesc_0 = (char *)&get_func_cfg->func_cfg.desc[0];
10221 	desc = (struct lpfc_rsrc_desc_fcfcoe *)pdesc_0;
10222 	length = bf_get(lpfc_rsrc_desc_fcfcoe_length, desc);
10223 	if (length == LPFC_RSRC_DESC_TYPE_FCFCOE_V0_RSVD)
10224 		length = LPFC_RSRC_DESC_TYPE_FCFCOE_V0_LENGTH;
10225 	else if (length != LPFC_RSRC_DESC_TYPE_FCFCOE_V1_LENGTH)
10226 		goto read_cfg_out;
10227 
10228 	for (i = 0; i < LPFC_RSRC_DESC_MAX_NUM; i++) {
10229 		desc = (struct lpfc_rsrc_desc_fcfcoe *)(pdesc_0 + length * i);
10230 		if (LPFC_RSRC_DESC_TYPE_FCFCOE ==
10231 		    bf_get(lpfc_rsrc_desc_fcfcoe_type, desc)) {
10232 			phba->sli4_hba.iov.pf_number =
10233 				bf_get(lpfc_rsrc_desc_fcfcoe_pfnum, desc);
10234 			phba->sli4_hba.iov.vf_number =
10235 				bf_get(lpfc_rsrc_desc_fcfcoe_vfnum, desc);
10236 			break;
10237 		}
10238 	}
10239 
10240 	if (i < LPFC_RSRC_DESC_MAX_NUM)
10241 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10242 				"3027 GET_FUNCTION_CONFIG: pf_number:%d, "
10243 				"vf_number:%d\n", phba->sli4_hba.iov.pf_number,
10244 				phba->sli4_hba.iov.vf_number);
10245 	else
10246 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10247 				"3028 GET_FUNCTION_CONFIG: failed to find "
10248 				"Resource Descriptor:x%x\n",
10249 				LPFC_RSRC_DESC_TYPE_FCFCOE);
10250 
10251 read_cfg_out:
10252 	mempool_free(pmb, phba->mbox_mem_pool);
10253 	return rc;
10254 }
10255 
10256 /**
10257  * lpfc_setup_endian_order - Write endian order to an SLI4 if_type 0 port.
10258  * @phba: pointer to lpfc hba data structure.
10259  *
10260  * This routine is invoked to setup the port-side endian order when
10261  * the port if_type is 0.  This routine has no function for other
10262  * if_types.
10263  *
10264  * Return codes
10265  * 	0 - successful
10266  * 	-ENOMEM - No available memory
10267  *      -EIO - The mailbox failed to complete successfully.
10268  **/
10269 static int
10270 lpfc_setup_endian_order(struct lpfc_hba *phba)
10271 {
10272 	LPFC_MBOXQ_t *mboxq;
10273 	uint32_t if_type, rc = 0;
10274 	uint32_t endian_mb_data[2] = {HOST_ENDIAN_LOW_WORD0,
10275 				      HOST_ENDIAN_HIGH_WORD1};
10276 
10277 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
10278 	switch (if_type) {
10279 	case LPFC_SLI_INTF_IF_TYPE_0:
10280 		mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
10281 						       GFP_KERNEL);
10282 		if (!mboxq) {
10283 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10284 					"0492 Unable to allocate memory for "
10285 					"issuing SLI_CONFIG_SPECIAL mailbox "
10286 					"command\n");
10287 			return -ENOMEM;
10288 		}
10289 
10290 		/*
10291 		 * The SLI4_CONFIG_SPECIAL mailbox command requires the first
10292 		 * two words to contain special data values and no other data.
10293 		 */
10294 		memset(mboxq, 0, sizeof(LPFC_MBOXQ_t));
10295 		memcpy(&mboxq->u.mqe, &endian_mb_data, sizeof(endian_mb_data));
10296 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
10297 		if (rc != MBX_SUCCESS) {
10298 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10299 					"0493 SLI_CONFIG_SPECIAL mailbox "
10300 					"failed with status x%x\n",
10301 					rc);
10302 			rc = -EIO;
10303 		}
10304 		mempool_free(mboxq, phba->mbox_mem_pool);
10305 		break;
10306 	case LPFC_SLI_INTF_IF_TYPE_6:
10307 	case LPFC_SLI_INTF_IF_TYPE_2:
10308 	case LPFC_SLI_INTF_IF_TYPE_1:
10309 	default:
10310 		break;
10311 	}
10312 	return rc;
10313 }
10314 
10315 /**
10316  * lpfc_sli4_queue_verify - Verify and update EQ counts
10317  * @phba: pointer to lpfc hba data structure.
10318  *
10319  * This routine is invoked to check the user settable queue counts for EQs.
10320  * After this routine is called the counts will be set to valid values that
10321  * adhere to the constraints of the system's interrupt vectors and the port's
10322  * queue resources.
10323  *
10324  * Return codes
10325  *      0 - successful
10326  *      -ENOMEM - No available memory
10327  **/
10328 static int
10329 lpfc_sli4_queue_verify(struct lpfc_hba *phba)
10330 {
10331 	/*
10332 	 * Sanity check for configured queue parameters against the run-time
10333 	 * device parameters
10334 	 */
10335 
10336 	if (phba->nvmet_support) {
10337 		if (phba->cfg_hdw_queue < phba->cfg_nvmet_mrq)
10338 			phba->cfg_nvmet_mrq = phba->cfg_hdw_queue;
10339 		if (phba->cfg_nvmet_mrq > LPFC_NVMET_MRQ_MAX)
10340 			phba->cfg_nvmet_mrq = LPFC_NVMET_MRQ_MAX;
10341 	}
10342 
10343 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10344 			"2574 IO channels: hdwQ %d IRQ %d MRQ: %d\n",
10345 			phba->cfg_hdw_queue, phba->cfg_irq_chann,
10346 			phba->cfg_nvmet_mrq);
10347 
10348 	/* Get EQ depth from module parameter, fake the default for now */
10349 	phba->sli4_hba.eq_esize = LPFC_EQE_SIZE_4B;
10350 	phba->sli4_hba.eq_ecount = LPFC_EQE_DEF_COUNT;
10351 
10352 	/* Get CQ depth from module parameter, fake the default for now */
10353 	phba->sli4_hba.cq_esize = LPFC_CQE_SIZE;
10354 	phba->sli4_hba.cq_ecount = LPFC_CQE_DEF_COUNT;
10355 	return 0;
10356 }
10357 
10358 static int
10359 lpfc_alloc_io_wq_cq(struct lpfc_hba *phba, int idx)
10360 {
10361 	struct lpfc_queue *qdesc;
10362 	u32 wqesize;
10363 	int cpu;
10364 
10365 	cpu = lpfc_find_cpu_handle(phba, idx, LPFC_FIND_BY_HDWQ);
10366 	/* Create Fast Path IO CQs */
10367 	if (phba->enab_exp_wqcq_pages)
10368 		/* Increase the CQ size when WQEs contain an embedded cdb */
10369 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_EXPANDED_PAGE_SIZE,
10370 					      phba->sli4_hba.cq_esize,
10371 					      LPFC_CQE_EXP_COUNT, cpu);
10372 
10373 	else
10374 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10375 					      phba->sli4_hba.cq_esize,
10376 					      phba->sli4_hba.cq_ecount, cpu);
10377 	if (!qdesc) {
10378 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10379 				"0499 Failed allocate fast-path IO CQ (%d)\n",
10380 				idx);
10381 		return 1;
10382 	}
10383 	qdesc->qe_valid = 1;
10384 	qdesc->hdwq = idx;
10385 	qdesc->chann = cpu;
10386 	phba->sli4_hba.hdwq[idx].io_cq = qdesc;
10387 
10388 	/* Create Fast Path IO WQs */
10389 	if (phba->enab_exp_wqcq_pages) {
10390 		/* Increase the WQ size when WQEs contain an embedded cdb */
10391 		wqesize = (phba->fcp_embed_io) ?
10392 			LPFC_WQE128_SIZE : phba->sli4_hba.wq_esize;
10393 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_EXPANDED_PAGE_SIZE,
10394 					      wqesize,
10395 					      LPFC_WQE_EXP_COUNT, cpu);
10396 	} else
10397 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10398 					      phba->sli4_hba.wq_esize,
10399 					      phba->sli4_hba.wq_ecount, cpu);
10400 
10401 	if (!qdesc) {
10402 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10403 				"0503 Failed allocate fast-path IO WQ (%d)\n",
10404 				idx);
10405 		return 1;
10406 	}
10407 	qdesc->hdwq = idx;
10408 	qdesc->chann = cpu;
10409 	phba->sli4_hba.hdwq[idx].io_wq = qdesc;
10410 	list_add_tail(&qdesc->wq_list, &phba->sli4_hba.lpfc_wq_list);
10411 	return 0;
10412 }
10413 
10414 /**
10415  * lpfc_sli4_queue_create - Create all the SLI4 queues
10416  * @phba: pointer to lpfc hba data structure.
10417  *
10418  * This routine is invoked to allocate all the SLI4 queues for the FCoE HBA
10419  * operation. For each SLI4 queue type, the parameters such as queue entry
10420  * count (queue depth) shall be taken from the module parameter. For now,
10421  * we just use some constant number as place holder.
10422  *
10423  * Return codes
10424  *      0 - successful
10425  *      -ENOMEM - No availble memory
10426  *      -EIO - The mailbox failed to complete successfully.
10427  **/
10428 int
10429 lpfc_sli4_queue_create(struct lpfc_hba *phba)
10430 {
10431 	struct lpfc_queue *qdesc;
10432 	int idx, cpu, eqcpu;
10433 	struct lpfc_sli4_hdw_queue *qp;
10434 	struct lpfc_vector_map_info *cpup;
10435 	struct lpfc_vector_map_info *eqcpup;
10436 	struct lpfc_eq_intr_info *eqi;
10437 	u32 wqesize;
10438 
10439 	/*
10440 	 * Create HBA Record arrays.
10441 	 * Both NVME and FCP will share that same vectors / EQs
10442 	 */
10443 	phba->sli4_hba.mq_esize = LPFC_MQE_SIZE;
10444 	phba->sli4_hba.mq_ecount = LPFC_MQE_DEF_COUNT;
10445 	phba->sli4_hba.wq_esize = LPFC_WQE_SIZE;
10446 	phba->sli4_hba.wq_ecount = LPFC_WQE_DEF_COUNT;
10447 	phba->sli4_hba.rq_esize = LPFC_RQE_SIZE;
10448 	phba->sli4_hba.rq_ecount = LPFC_RQE_DEF_COUNT;
10449 	phba->sli4_hba.eq_esize = LPFC_EQE_SIZE_4B;
10450 	phba->sli4_hba.eq_ecount = LPFC_EQE_DEF_COUNT;
10451 	phba->sli4_hba.cq_esize = LPFC_CQE_SIZE;
10452 	phba->sli4_hba.cq_ecount = LPFC_CQE_DEF_COUNT;
10453 
10454 	if (!phba->sli4_hba.hdwq) {
10455 		phba->sli4_hba.hdwq = kcalloc(
10456 			phba->cfg_hdw_queue, sizeof(struct lpfc_sli4_hdw_queue),
10457 			GFP_KERNEL);
10458 		if (!phba->sli4_hba.hdwq) {
10459 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10460 					"6427 Failed allocate memory for "
10461 					"fast-path Hardware Queue array\n");
10462 			goto out_error;
10463 		}
10464 		/* Prepare hardware queues to take IO buffers */
10465 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10466 			qp = &phba->sli4_hba.hdwq[idx];
10467 			spin_lock_init(&qp->io_buf_list_get_lock);
10468 			spin_lock_init(&qp->io_buf_list_put_lock);
10469 			INIT_LIST_HEAD(&qp->lpfc_io_buf_list_get);
10470 			INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
10471 			qp->get_io_bufs = 0;
10472 			qp->put_io_bufs = 0;
10473 			qp->total_io_bufs = 0;
10474 			spin_lock_init(&qp->abts_io_buf_list_lock);
10475 			INIT_LIST_HEAD(&qp->lpfc_abts_io_buf_list);
10476 			qp->abts_scsi_io_bufs = 0;
10477 			qp->abts_nvme_io_bufs = 0;
10478 			INIT_LIST_HEAD(&qp->sgl_list);
10479 			INIT_LIST_HEAD(&qp->cmd_rsp_buf_list);
10480 			spin_lock_init(&qp->hdwq_lock);
10481 		}
10482 	}
10483 
10484 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
10485 		if (phba->nvmet_support) {
10486 			phba->sli4_hba.nvmet_cqset = kcalloc(
10487 					phba->cfg_nvmet_mrq,
10488 					sizeof(struct lpfc_queue *),
10489 					GFP_KERNEL);
10490 			if (!phba->sli4_hba.nvmet_cqset) {
10491 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10492 					"3121 Fail allocate memory for "
10493 					"fast-path CQ set array\n");
10494 				goto out_error;
10495 			}
10496 			phba->sli4_hba.nvmet_mrq_hdr = kcalloc(
10497 					phba->cfg_nvmet_mrq,
10498 					sizeof(struct lpfc_queue *),
10499 					GFP_KERNEL);
10500 			if (!phba->sli4_hba.nvmet_mrq_hdr) {
10501 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10502 					"3122 Fail allocate memory for "
10503 					"fast-path RQ set hdr array\n");
10504 				goto out_error;
10505 			}
10506 			phba->sli4_hba.nvmet_mrq_data = kcalloc(
10507 					phba->cfg_nvmet_mrq,
10508 					sizeof(struct lpfc_queue *),
10509 					GFP_KERNEL);
10510 			if (!phba->sli4_hba.nvmet_mrq_data) {
10511 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10512 					"3124 Fail allocate memory for "
10513 					"fast-path RQ set data array\n");
10514 				goto out_error;
10515 			}
10516 		}
10517 	}
10518 
10519 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_wq_list);
10520 
10521 	/* Create HBA Event Queues (EQs) */
10522 	for_each_present_cpu(cpu) {
10523 		/* We only want to create 1 EQ per vector, even though
10524 		 * multiple CPUs might be using that vector. so only
10525 		 * selects the CPUs that are LPFC_CPU_FIRST_IRQ.
10526 		 */
10527 		cpup = &phba->sli4_hba.cpu_map[cpu];
10528 		if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
10529 			continue;
10530 
10531 		/* Get a ptr to the Hardware Queue associated with this CPU */
10532 		qp = &phba->sli4_hba.hdwq[cpup->hdwq];
10533 
10534 		/* Allocate an EQ */
10535 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10536 					      phba->sli4_hba.eq_esize,
10537 					      phba->sli4_hba.eq_ecount, cpu);
10538 		if (!qdesc) {
10539 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10540 					"0497 Failed allocate EQ (%d)\n",
10541 					cpup->hdwq);
10542 			goto out_error;
10543 		}
10544 		qdesc->qe_valid = 1;
10545 		qdesc->hdwq = cpup->hdwq;
10546 		qdesc->chann = cpu; /* First CPU this EQ is affinitized to */
10547 		qdesc->last_cpu = qdesc->chann;
10548 
10549 		/* Save the allocated EQ in the Hardware Queue */
10550 		qp->hba_eq = qdesc;
10551 
10552 		eqi = per_cpu_ptr(phba->sli4_hba.eq_info, qdesc->last_cpu);
10553 		list_add(&qdesc->cpu_list, &eqi->list);
10554 	}
10555 
10556 	/* Now we need to populate the other Hardware Queues, that share
10557 	 * an IRQ vector, with the associated EQ ptr.
10558 	 */
10559 	for_each_present_cpu(cpu) {
10560 		cpup = &phba->sli4_hba.cpu_map[cpu];
10561 
10562 		/* Check for EQ already allocated in previous loop */
10563 		if (cpup->flag & LPFC_CPU_FIRST_IRQ)
10564 			continue;
10565 
10566 		/* Check for multiple CPUs per hdwq */
10567 		qp = &phba->sli4_hba.hdwq[cpup->hdwq];
10568 		if (qp->hba_eq)
10569 			continue;
10570 
10571 		/* We need to share an EQ for this hdwq */
10572 		eqcpu = lpfc_find_cpu_handle(phba, cpup->eq, LPFC_FIND_BY_EQ);
10573 		eqcpup = &phba->sli4_hba.cpu_map[eqcpu];
10574 		qp->hba_eq = phba->sli4_hba.hdwq[eqcpup->hdwq].hba_eq;
10575 	}
10576 
10577 	/* Allocate IO Path SLI4 CQ/WQs */
10578 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10579 		if (lpfc_alloc_io_wq_cq(phba, idx))
10580 			goto out_error;
10581 	}
10582 
10583 	if (phba->nvmet_support) {
10584 		for (idx = 0; idx < phba->cfg_nvmet_mrq; idx++) {
10585 			cpu = lpfc_find_cpu_handle(phba, idx,
10586 						   LPFC_FIND_BY_HDWQ);
10587 			qdesc = lpfc_sli4_queue_alloc(phba,
10588 						      LPFC_DEFAULT_PAGE_SIZE,
10589 						      phba->sli4_hba.cq_esize,
10590 						      phba->sli4_hba.cq_ecount,
10591 						      cpu);
10592 			if (!qdesc) {
10593 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10594 						"3142 Failed allocate NVME "
10595 						"CQ Set (%d)\n", idx);
10596 				goto out_error;
10597 			}
10598 			qdesc->qe_valid = 1;
10599 			qdesc->hdwq = idx;
10600 			qdesc->chann = cpu;
10601 			phba->sli4_hba.nvmet_cqset[idx] = qdesc;
10602 		}
10603 	}
10604 
10605 	/*
10606 	 * Create Slow Path Completion Queues (CQs)
10607 	 */
10608 
10609 	cpu = lpfc_find_cpu_handle(phba, 0, LPFC_FIND_BY_EQ);
10610 	/* Create slow-path Mailbox Command Complete Queue */
10611 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10612 				      phba->sli4_hba.cq_esize,
10613 				      phba->sli4_hba.cq_ecount, cpu);
10614 	if (!qdesc) {
10615 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10616 				"0500 Failed allocate slow-path mailbox CQ\n");
10617 		goto out_error;
10618 	}
10619 	qdesc->qe_valid = 1;
10620 	phba->sli4_hba.mbx_cq = qdesc;
10621 
10622 	/* Create slow-path ELS Complete Queue */
10623 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10624 				      phba->sli4_hba.cq_esize,
10625 				      phba->sli4_hba.cq_ecount, cpu);
10626 	if (!qdesc) {
10627 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10628 				"0501 Failed allocate slow-path ELS CQ\n");
10629 		goto out_error;
10630 	}
10631 	qdesc->qe_valid = 1;
10632 	qdesc->chann = cpu;
10633 	phba->sli4_hba.els_cq = qdesc;
10634 
10635 
10636 	/*
10637 	 * Create Slow Path Work Queues (WQs)
10638 	 */
10639 
10640 	/* Create Mailbox Command Queue */
10641 
10642 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10643 				      phba->sli4_hba.mq_esize,
10644 				      phba->sli4_hba.mq_ecount, cpu);
10645 	if (!qdesc) {
10646 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10647 				"0505 Failed allocate slow-path MQ\n");
10648 		goto out_error;
10649 	}
10650 	qdesc->chann = cpu;
10651 	phba->sli4_hba.mbx_wq = qdesc;
10652 
10653 	/*
10654 	 * Create ELS Work Queues
10655 	 */
10656 
10657 	/*
10658 	 * Create slow-path ELS Work Queue.
10659 	 * Increase the ELS WQ size when WQEs contain an embedded cdb
10660 	 */
10661 	wqesize = (phba->fcp_embed_io) ?
10662 			LPFC_WQE128_SIZE : phba->sli4_hba.wq_esize;
10663 
10664 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10665 				      wqesize,
10666 				      phba->sli4_hba.wq_ecount, cpu);
10667 	if (!qdesc) {
10668 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10669 				"0504 Failed allocate slow-path ELS WQ\n");
10670 		goto out_error;
10671 	}
10672 	qdesc->chann = cpu;
10673 	phba->sli4_hba.els_wq = qdesc;
10674 	list_add_tail(&qdesc->wq_list, &phba->sli4_hba.lpfc_wq_list);
10675 
10676 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
10677 		/* Create NVME LS Complete Queue */
10678 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10679 					      phba->sli4_hba.cq_esize,
10680 					      phba->sli4_hba.cq_ecount, cpu);
10681 		if (!qdesc) {
10682 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10683 					"6079 Failed allocate NVME LS CQ\n");
10684 			goto out_error;
10685 		}
10686 		qdesc->chann = cpu;
10687 		qdesc->qe_valid = 1;
10688 		phba->sli4_hba.nvmels_cq = qdesc;
10689 
10690 		/* Create NVME LS Work Queue */
10691 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10692 					      phba->sli4_hba.wq_esize,
10693 					      phba->sli4_hba.wq_ecount, cpu);
10694 		if (!qdesc) {
10695 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10696 					"6080 Failed allocate NVME LS WQ\n");
10697 			goto out_error;
10698 		}
10699 		qdesc->chann = cpu;
10700 		phba->sli4_hba.nvmels_wq = qdesc;
10701 		list_add_tail(&qdesc->wq_list, &phba->sli4_hba.lpfc_wq_list);
10702 	}
10703 
10704 	/*
10705 	 * Create Receive Queue (RQ)
10706 	 */
10707 
10708 	/* Create Receive Queue for header */
10709 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10710 				      phba->sli4_hba.rq_esize,
10711 				      phba->sli4_hba.rq_ecount, cpu);
10712 	if (!qdesc) {
10713 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10714 				"0506 Failed allocate receive HRQ\n");
10715 		goto out_error;
10716 	}
10717 	phba->sli4_hba.hdr_rq = qdesc;
10718 
10719 	/* Create Receive Queue for data */
10720 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10721 				      phba->sli4_hba.rq_esize,
10722 				      phba->sli4_hba.rq_ecount, cpu);
10723 	if (!qdesc) {
10724 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10725 				"0507 Failed allocate receive DRQ\n");
10726 		goto out_error;
10727 	}
10728 	phba->sli4_hba.dat_rq = qdesc;
10729 
10730 	if ((phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) &&
10731 	    phba->nvmet_support) {
10732 		for (idx = 0; idx < phba->cfg_nvmet_mrq; idx++) {
10733 			cpu = lpfc_find_cpu_handle(phba, idx,
10734 						   LPFC_FIND_BY_HDWQ);
10735 			/* Create NVMET Receive Queue for header */
10736 			qdesc = lpfc_sli4_queue_alloc(phba,
10737 						      LPFC_DEFAULT_PAGE_SIZE,
10738 						      phba->sli4_hba.rq_esize,
10739 						      LPFC_NVMET_RQE_DEF_COUNT,
10740 						      cpu);
10741 			if (!qdesc) {
10742 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10743 						"3146 Failed allocate "
10744 						"receive HRQ\n");
10745 				goto out_error;
10746 			}
10747 			qdesc->hdwq = idx;
10748 			phba->sli4_hba.nvmet_mrq_hdr[idx] = qdesc;
10749 
10750 			/* Only needed for header of RQ pair */
10751 			qdesc->rqbp = kzalloc_node(sizeof(*qdesc->rqbp),
10752 						   GFP_KERNEL,
10753 						   cpu_to_node(cpu));
10754 			if (qdesc->rqbp == NULL) {
10755 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10756 						"6131 Failed allocate "
10757 						"Header RQBP\n");
10758 				goto out_error;
10759 			}
10760 
10761 			/* Put list in known state in case driver load fails. */
10762 			INIT_LIST_HEAD(&qdesc->rqbp->rqb_buffer_list);
10763 
10764 			/* Create NVMET Receive Queue for data */
10765 			qdesc = lpfc_sli4_queue_alloc(phba,
10766 						      LPFC_DEFAULT_PAGE_SIZE,
10767 						      phba->sli4_hba.rq_esize,
10768 						      LPFC_NVMET_RQE_DEF_COUNT,
10769 						      cpu);
10770 			if (!qdesc) {
10771 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10772 						"3156 Failed allocate "
10773 						"receive DRQ\n");
10774 				goto out_error;
10775 			}
10776 			qdesc->hdwq = idx;
10777 			phba->sli4_hba.nvmet_mrq_data[idx] = qdesc;
10778 		}
10779 	}
10780 
10781 	/* Clear NVME stats */
10782 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
10783 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10784 			memset(&phba->sli4_hba.hdwq[idx].nvme_cstat, 0,
10785 			       sizeof(phba->sli4_hba.hdwq[idx].nvme_cstat));
10786 		}
10787 	}
10788 
10789 	/* Clear SCSI stats */
10790 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP) {
10791 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10792 			memset(&phba->sli4_hba.hdwq[idx].scsi_cstat, 0,
10793 			       sizeof(phba->sli4_hba.hdwq[idx].scsi_cstat));
10794 		}
10795 	}
10796 
10797 	return 0;
10798 
10799 out_error:
10800 	lpfc_sli4_queue_destroy(phba);
10801 	return -ENOMEM;
10802 }
10803 
10804 static inline void
10805 __lpfc_sli4_release_queue(struct lpfc_queue **qp)
10806 {
10807 	if (*qp != NULL) {
10808 		lpfc_sli4_queue_free(*qp);
10809 		*qp = NULL;
10810 	}
10811 }
10812 
10813 static inline void
10814 lpfc_sli4_release_queues(struct lpfc_queue ***qs, int max)
10815 {
10816 	int idx;
10817 
10818 	if (*qs == NULL)
10819 		return;
10820 
10821 	for (idx = 0; idx < max; idx++)
10822 		__lpfc_sli4_release_queue(&(*qs)[idx]);
10823 
10824 	kfree(*qs);
10825 	*qs = NULL;
10826 }
10827 
10828 static inline void
10829 lpfc_sli4_release_hdwq(struct lpfc_hba *phba)
10830 {
10831 	struct lpfc_sli4_hdw_queue *hdwq;
10832 	struct lpfc_queue *eq;
10833 	uint32_t idx;
10834 
10835 	hdwq = phba->sli4_hba.hdwq;
10836 
10837 	/* Loop thru all Hardware Queues */
10838 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10839 		/* Free the CQ/WQ corresponding to the Hardware Queue */
10840 		lpfc_sli4_queue_free(hdwq[idx].io_cq);
10841 		lpfc_sli4_queue_free(hdwq[idx].io_wq);
10842 		hdwq[idx].hba_eq = NULL;
10843 		hdwq[idx].io_cq = NULL;
10844 		hdwq[idx].io_wq = NULL;
10845 		if (phba->cfg_xpsgl && !phba->nvmet_support)
10846 			lpfc_free_sgl_per_hdwq(phba, &hdwq[idx]);
10847 		lpfc_free_cmd_rsp_buf_per_hdwq(phba, &hdwq[idx]);
10848 	}
10849 	/* Loop thru all IRQ vectors */
10850 	for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
10851 		/* Free the EQ corresponding to the IRQ vector */
10852 		eq = phba->sli4_hba.hba_eq_hdl[idx].eq;
10853 		lpfc_sli4_queue_free(eq);
10854 		phba->sli4_hba.hba_eq_hdl[idx].eq = NULL;
10855 	}
10856 }
10857 
10858 /**
10859  * lpfc_sli4_queue_destroy - Destroy all the SLI4 queues
10860  * @phba: pointer to lpfc hba data structure.
10861  *
10862  * This routine is invoked to release all the SLI4 queues with the FCoE HBA
10863  * operation.
10864  *
10865  * Return codes
10866  *      0 - successful
10867  *      -ENOMEM - No available memory
10868  *      -EIO - The mailbox failed to complete successfully.
10869  **/
10870 void
10871 lpfc_sli4_queue_destroy(struct lpfc_hba *phba)
10872 {
10873 	/*
10874 	 * Set FREE_INIT before beginning to free the queues.
10875 	 * Wait until the users of queues to acknowledge to
10876 	 * release queues by clearing FREE_WAIT.
10877 	 */
10878 	spin_lock_irq(&phba->hbalock);
10879 	phba->sli.sli_flag |= LPFC_QUEUE_FREE_INIT;
10880 	while (phba->sli.sli_flag & LPFC_QUEUE_FREE_WAIT) {
10881 		spin_unlock_irq(&phba->hbalock);
10882 		msleep(20);
10883 		spin_lock_irq(&phba->hbalock);
10884 	}
10885 	spin_unlock_irq(&phba->hbalock);
10886 
10887 	lpfc_sli4_cleanup_poll_list(phba);
10888 
10889 	/* Release HBA eqs */
10890 	if (phba->sli4_hba.hdwq)
10891 		lpfc_sli4_release_hdwq(phba);
10892 
10893 	if (phba->nvmet_support) {
10894 		lpfc_sli4_release_queues(&phba->sli4_hba.nvmet_cqset,
10895 					 phba->cfg_nvmet_mrq);
10896 
10897 		lpfc_sli4_release_queues(&phba->sli4_hba.nvmet_mrq_hdr,
10898 					 phba->cfg_nvmet_mrq);
10899 		lpfc_sli4_release_queues(&phba->sli4_hba.nvmet_mrq_data,
10900 					 phba->cfg_nvmet_mrq);
10901 	}
10902 
10903 	/* Release mailbox command work queue */
10904 	__lpfc_sli4_release_queue(&phba->sli4_hba.mbx_wq);
10905 
10906 	/* Release ELS work queue */
10907 	__lpfc_sli4_release_queue(&phba->sli4_hba.els_wq);
10908 
10909 	/* Release ELS work queue */
10910 	__lpfc_sli4_release_queue(&phba->sli4_hba.nvmels_wq);
10911 
10912 	/* Release unsolicited receive queue */
10913 	__lpfc_sli4_release_queue(&phba->sli4_hba.hdr_rq);
10914 	__lpfc_sli4_release_queue(&phba->sli4_hba.dat_rq);
10915 
10916 	/* Release ELS complete queue */
10917 	__lpfc_sli4_release_queue(&phba->sli4_hba.els_cq);
10918 
10919 	/* Release NVME LS complete queue */
10920 	__lpfc_sli4_release_queue(&phba->sli4_hba.nvmels_cq);
10921 
10922 	/* Release mailbox command complete queue */
10923 	__lpfc_sli4_release_queue(&phba->sli4_hba.mbx_cq);
10924 
10925 	/* Everything on this list has been freed */
10926 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_wq_list);
10927 
10928 	/* Done with freeing the queues */
10929 	spin_lock_irq(&phba->hbalock);
10930 	phba->sli.sli_flag &= ~LPFC_QUEUE_FREE_INIT;
10931 	spin_unlock_irq(&phba->hbalock);
10932 }
10933 
10934 int
10935 lpfc_free_rq_buffer(struct lpfc_hba *phba, struct lpfc_queue *rq)
10936 {
10937 	struct lpfc_rqb *rqbp;
10938 	struct lpfc_dmabuf *h_buf;
10939 	struct rqb_dmabuf *rqb_buffer;
10940 
10941 	rqbp = rq->rqbp;
10942 	while (!list_empty(&rqbp->rqb_buffer_list)) {
10943 		list_remove_head(&rqbp->rqb_buffer_list, h_buf,
10944 				 struct lpfc_dmabuf, list);
10945 
10946 		rqb_buffer = container_of(h_buf, struct rqb_dmabuf, hbuf);
10947 		(rqbp->rqb_free_buffer)(phba, rqb_buffer);
10948 		rqbp->buffer_count--;
10949 	}
10950 	return 1;
10951 }
10952 
10953 static int
10954 lpfc_create_wq_cq(struct lpfc_hba *phba, struct lpfc_queue *eq,
10955 	struct lpfc_queue *cq, struct lpfc_queue *wq, uint16_t *cq_map,
10956 	int qidx, uint32_t qtype)
10957 {
10958 	struct lpfc_sli_ring *pring;
10959 	int rc;
10960 
10961 	if (!eq || !cq || !wq) {
10962 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10963 			"6085 Fast-path %s (%d) not allocated\n",
10964 			((eq) ? ((cq) ? "WQ" : "CQ") : "EQ"), qidx);
10965 		return -ENOMEM;
10966 	}
10967 
10968 	/* create the Cq first */
10969 	rc = lpfc_cq_create(phba, cq, eq,
10970 			(qtype == LPFC_MBOX) ? LPFC_MCQ : LPFC_WCQ, qtype);
10971 	if (rc) {
10972 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10973 				"6086 Failed setup of CQ (%d), rc = 0x%x\n",
10974 				qidx, (uint32_t)rc);
10975 		return rc;
10976 	}
10977 
10978 	if (qtype != LPFC_MBOX) {
10979 		/* Setup cq_map for fast lookup */
10980 		if (cq_map)
10981 			*cq_map = cq->queue_id;
10982 
10983 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
10984 			"6087 CQ setup: cq[%d]-id=%d, parent eq[%d]-id=%d\n",
10985 			qidx, cq->queue_id, qidx, eq->queue_id);
10986 
10987 		/* create the wq */
10988 		rc = lpfc_wq_create(phba, wq, cq, qtype);
10989 		if (rc) {
10990 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10991 				"4618 Fail setup fastpath WQ (%d), rc = 0x%x\n",
10992 				qidx, (uint32_t)rc);
10993 			/* no need to tear down cq - caller will do so */
10994 			return rc;
10995 		}
10996 
10997 		/* Bind this CQ/WQ to the NVME ring */
10998 		pring = wq->pring;
10999 		pring->sli.sli4.wqp = (void *)wq;
11000 		cq->pring = pring;
11001 
11002 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11003 			"2593 WQ setup: wq[%d]-id=%d assoc=%d, cq[%d]-id=%d\n",
11004 			qidx, wq->queue_id, wq->assoc_qid, qidx, cq->queue_id);
11005 	} else {
11006 		rc = lpfc_mq_create(phba, wq, cq, LPFC_MBOX);
11007 		if (rc) {
11008 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11009 					"0539 Failed setup of slow-path MQ: "
11010 					"rc = 0x%x\n", rc);
11011 			/* no need to tear down cq - caller will do so */
11012 			return rc;
11013 		}
11014 
11015 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11016 			"2589 MBX MQ setup: wq-id=%d, parent cq-id=%d\n",
11017 			phba->sli4_hba.mbx_wq->queue_id,
11018 			phba->sli4_hba.mbx_cq->queue_id);
11019 	}
11020 
11021 	return 0;
11022 }
11023 
11024 /**
11025  * lpfc_setup_cq_lookup - Setup the CQ lookup table
11026  * @phba: pointer to lpfc hba data structure.
11027  *
11028  * This routine will populate the cq_lookup table by all
11029  * available CQ queue_id's.
11030  **/
11031 static void
11032 lpfc_setup_cq_lookup(struct lpfc_hba *phba)
11033 {
11034 	struct lpfc_queue *eq, *childq;
11035 	int qidx;
11036 
11037 	memset(phba->sli4_hba.cq_lookup, 0,
11038 	       (sizeof(struct lpfc_queue *) * (phba->sli4_hba.cq_max + 1)));
11039 	/* Loop thru all IRQ vectors */
11040 	for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
11041 		/* Get the EQ corresponding to the IRQ vector */
11042 		eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
11043 		if (!eq)
11044 			continue;
11045 		/* Loop through all CQs associated with that EQ */
11046 		list_for_each_entry(childq, &eq->child_list, list) {
11047 			if (childq->queue_id > phba->sli4_hba.cq_max)
11048 				continue;
11049 			if (childq->subtype == LPFC_IO)
11050 				phba->sli4_hba.cq_lookup[childq->queue_id] =
11051 					childq;
11052 		}
11053 	}
11054 }
11055 
11056 /**
11057  * lpfc_sli4_queue_setup - Set up all the SLI4 queues
11058  * @phba: pointer to lpfc hba data structure.
11059  *
11060  * This routine is invoked to set up all the SLI4 queues for the FCoE HBA
11061  * operation.
11062  *
11063  * Return codes
11064  *      0 - successful
11065  *      -ENOMEM - No available memory
11066  *      -EIO - The mailbox failed to complete successfully.
11067  **/
11068 int
11069 lpfc_sli4_queue_setup(struct lpfc_hba *phba)
11070 {
11071 	uint32_t shdr_status, shdr_add_status;
11072 	union lpfc_sli4_cfg_shdr *shdr;
11073 	struct lpfc_vector_map_info *cpup;
11074 	struct lpfc_sli4_hdw_queue *qp;
11075 	LPFC_MBOXQ_t *mboxq;
11076 	int qidx, cpu;
11077 	uint32_t length, usdelay;
11078 	int rc = -ENOMEM;
11079 
11080 	/* Check for dual-ULP support */
11081 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
11082 	if (!mboxq) {
11083 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11084 				"3249 Unable to allocate memory for "
11085 				"QUERY_FW_CFG mailbox command\n");
11086 		return -ENOMEM;
11087 	}
11088 	length = (sizeof(struct lpfc_mbx_query_fw_config) -
11089 		  sizeof(struct lpfc_sli4_cfg_mhdr));
11090 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
11091 			 LPFC_MBOX_OPCODE_QUERY_FW_CFG,
11092 			 length, LPFC_SLI4_MBX_EMBED);
11093 
11094 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
11095 
11096 	shdr = (union lpfc_sli4_cfg_shdr *)
11097 			&mboxq->u.mqe.un.sli4_config.header.cfg_shdr;
11098 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
11099 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
11100 	if (shdr_status || shdr_add_status || rc) {
11101 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11102 				"3250 QUERY_FW_CFG mailbox failed with status "
11103 				"x%x add_status x%x, mbx status x%x\n",
11104 				shdr_status, shdr_add_status, rc);
11105 		mempool_free(mboxq, phba->mbox_mem_pool);
11106 		rc = -ENXIO;
11107 		goto out_error;
11108 	}
11109 
11110 	phba->sli4_hba.fw_func_mode =
11111 			mboxq->u.mqe.un.query_fw_cfg.rsp.function_mode;
11112 	phba->sli4_hba.ulp0_mode = mboxq->u.mqe.un.query_fw_cfg.rsp.ulp0_mode;
11113 	phba->sli4_hba.ulp1_mode = mboxq->u.mqe.un.query_fw_cfg.rsp.ulp1_mode;
11114 	phba->sli4_hba.physical_port =
11115 			mboxq->u.mqe.un.query_fw_cfg.rsp.physical_port;
11116 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11117 			"3251 QUERY_FW_CFG: func_mode:x%x, ulp0_mode:x%x, "
11118 			"ulp1_mode:x%x\n", phba->sli4_hba.fw_func_mode,
11119 			phba->sli4_hba.ulp0_mode, phba->sli4_hba.ulp1_mode);
11120 
11121 	mempool_free(mboxq, phba->mbox_mem_pool);
11122 
11123 	/*
11124 	 * Set up HBA Event Queues (EQs)
11125 	 */
11126 	qp = phba->sli4_hba.hdwq;
11127 
11128 	/* Set up HBA event queue */
11129 	if (!qp) {
11130 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11131 				"3147 Fast-path EQs not allocated\n");
11132 		rc = -ENOMEM;
11133 		goto out_error;
11134 	}
11135 
11136 	/* Loop thru all IRQ vectors */
11137 	for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
11138 		/* Create HBA Event Queues (EQs) in order */
11139 		for_each_present_cpu(cpu) {
11140 			cpup = &phba->sli4_hba.cpu_map[cpu];
11141 
11142 			/* Look for the CPU thats using that vector with
11143 			 * LPFC_CPU_FIRST_IRQ set.
11144 			 */
11145 			if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
11146 				continue;
11147 			if (qidx != cpup->eq)
11148 				continue;
11149 
11150 			/* Create an EQ for that vector */
11151 			rc = lpfc_eq_create(phba, qp[cpup->hdwq].hba_eq,
11152 					    phba->cfg_fcp_imax);
11153 			if (rc) {
11154 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11155 						"0523 Failed setup of fast-path"
11156 						" EQ (%d), rc = 0x%x\n",
11157 						cpup->eq, (uint32_t)rc);
11158 				goto out_destroy;
11159 			}
11160 
11161 			/* Save the EQ for that vector in the hba_eq_hdl */
11162 			phba->sli4_hba.hba_eq_hdl[cpup->eq].eq =
11163 				qp[cpup->hdwq].hba_eq;
11164 
11165 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11166 					"2584 HBA EQ setup: queue[%d]-id=%d\n",
11167 					cpup->eq,
11168 					qp[cpup->hdwq].hba_eq->queue_id);
11169 		}
11170 	}
11171 
11172 	/* Loop thru all Hardware Queues */
11173 	for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
11174 		cpu = lpfc_find_cpu_handle(phba, qidx, LPFC_FIND_BY_HDWQ);
11175 		cpup = &phba->sli4_hba.cpu_map[cpu];
11176 
11177 		/* Create the CQ/WQ corresponding to the Hardware Queue */
11178 		rc = lpfc_create_wq_cq(phba,
11179 				       phba->sli4_hba.hdwq[cpup->hdwq].hba_eq,
11180 				       qp[qidx].io_cq,
11181 				       qp[qidx].io_wq,
11182 				       &phba->sli4_hba.hdwq[qidx].io_cq_map,
11183 				       qidx,
11184 				       LPFC_IO);
11185 		if (rc) {
11186 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11187 					"0535 Failed to setup fastpath "
11188 					"IO WQ/CQ (%d), rc = 0x%x\n",
11189 					qidx, (uint32_t)rc);
11190 			goto out_destroy;
11191 		}
11192 	}
11193 
11194 	/*
11195 	 * Set up Slow Path Complete Queues (CQs)
11196 	 */
11197 
11198 	/* Set up slow-path MBOX CQ/MQ */
11199 
11200 	if (!phba->sli4_hba.mbx_cq || !phba->sli4_hba.mbx_wq) {
11201 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11202 				"0528 %s not allocated\n",
11203 				phba->sli4_hba.mbx_cq ?
11204 				"Mailbox WQ" : "Mailbox CQ");
11205 		rc = -ENOMEM;
11206 		goto out_destroy;
11207 	}
11208 
11209 	rc = lpfc_create_wq_cq(phba, qp[0].hba_eq,
11210 			       phba->sli4_hba.mbx_cq,
11211 			       phba->sli4_hba.mbx_wq,
11212 			       NULL, 0, LPFC_MBOX);
11213 	if (rc) {
11214 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11215 			"0529 Failed setup of mailbox WQ/CQ: rc = 0x%x\n",
11216 			(uint32_t)rc);
11217 		goto out_destroy;
11218 	}
11219 	if (phba->nvmet_support) {
11220 		if (!phba->sli4_hba.nvmet_cqset) {
11221 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11222 					"3165 Fast-path NVME CQ Set "
11223 					"array not allocated\n");
11224 			rc = -ENOMEM;
11225 			goto out_destroy;
11226 		}
11227 		if (phba->cfg_nvmet_mrq > 1) {
11228 			rc = lpfc_cq_create_set(phba,
11229 					phba->sli4_hba.nvmet_cqset,
11230 					qp,
11231 					LPFC_WCQ, LPFC_NVMET);
11232 			if (rc) {
11233 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11234 						"3164 Failed setup of NVME CQ "
11235 						"Set, rc = 0x%x\n",
11236 						(uint32_t)rc);
11237 				goto out_destroy;
11238 			}
11239 		} else {
11240 			/* Set up NVMET Receive Complete Queue */
11241 			rc = lpfc_cq_create(phba, phba->sli4_hba.nvmet_cqset[0],
11242 					    qp[0].hba_eq,
11243 					    LPFC_WCQ, LPFC_NVMET);
11244 			if (rc) {
11245 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11246 						"6089 Failed setup NVMET CQ: "
11247 						"rc = 0x%x\n", (uint32_t)rc);
11248 				goto out_destroy;
11249 			}
11250 			phba->sli4_hba.nvmet_cqset[0]->chann = 0;
11251 
11252 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11253 					"6090 NVMET CQ setup: cq-id=%d, "
11254 					"parent eq-id=%d\n",
11255 					phba->sli4_hba.nvmet_cqset[0]->queue_id,
11256 					qp[0].hba_eq->queue_id);
11257 		}
11258 	}
11259 
11260 	/* Set up slow-path ELS WQ/CQ */
11261 	if (!phba->sli4_hba.els_cq || !phba->sli4_hba.els_wq) {
11262 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11263 				"0530 ELS %s not allocated\n",
11264 				phba->sli4_hba.els_cq ? "WQ" : "CQ");
11265 		rc = -ENOMEM;
11266 		goto out_destroy;
11267 	}
11268 	rc = lpfc_create_wq_cq(phba, qp[0].hba_eq,
11269 			       phba->sli4_hba.els_cq,
11270 			       phba->sli4_hba.els_wq,
11271 			       NULL, 0, LPFC_ELS);
11272 	if (rc) {
11273 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11274 				"0525 Failed setup of ELS WQ/CQ: rc = 0x%x\n",
11275 				(uint32_t)rc);
11276 		goto out_destroy;
11277 	}
11278 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11279 			"2590 ELS WQ setup: wq-id=%d, parent cq-id=%d\n",
11280 			phba->sli4_hba.els_wq->queue_id,
11281 			phba->sli4_hba.els_cq->queue_id);
11282 
11283 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
11284 		/* Set up NVME LS Complete Queue */
11285 		if (!phba->sli4_hba.nvmels_cq || !phba->sli4_hba.nvmels_wq) {
11286 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11287 					"6091 LS %s not allocated\n",
11288 					phba->sli4_hba.nvmels_cq ? "WQ" : "CQ");
11289 			rc = -ENOMEM;
11290 			goto out_destroy;
11291 		}
11292 		rc = lpfc_create_wq_cq(phba, qp[0].hba_eq,
11293 				       phba->sli4_hba.nvmels_cq,
11294 				       phba->sli4_hba.nvmels_wq,
11295 				       NULL, 0, LPFC_NVME_LS);
11296 		if (rc) {
11297 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11298 					"0526 Failed setup of NVVME LS WQ/CQ: "
11299 					"rc = 0x%x\n", (uint32_t)rc);
11300 			goto out_destroy;
11301 		}
11302 
11303 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11304 				"6096 ELS WQ setup: wq-id=%d, "
11305 				"parent cq-id=%d\n",
11306 				phba->sli4_hba.nvmels_wq->queue_id,
11307 				phba->sli4_hba.nvmels_cq->queue_id);
11308 	}
11309 
11310 	/*
11311 	 * Create NVMET Receive Queue (RQ)
11312 	 */
11313 	if (phba->nvmet_support) {
11314 		if ((!phba->sli4_hba.nvmet_cqset) ||
11315 		    (!phba->sli4_hba.nvmet_mrq_hdr) ||
11316 		    (!phba->sli4_hba.nvmet_mrq_data)) {
11317 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11318 					"6130 MRQ CQ Queues not "
11319 					"allocated\n");
11320 			rc = -ENOMEM;
11321 			goto out_destroy;
11322 		}
11323 		if (phba->cfg_nvmet_mrq > 1) {
11324 			rc = lpfc_mrq_create(phba,
11325 					     phba->sli4_hba.nvmet_mrq_hdr,
11326 					     phba->sli4_hba.nvmet_mrq_data,
11327 					     phba->sli4_hba.nvmet_cqset,
11328 					     LPFC_NVMET);
11329 			if (rc) {
11330 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11331 						"6098 Failed setup of NVMET "
11332 						"MRQ: rc = 0x%x\n",
11333 						(uint32_t)rc);
11334 				goto out_destroy;
11335 			}
11336 
11337 		} else {
11338 			rc = lpfc_rq_create(phba,
11339 					    phba->sli4_hba.nvmet_mrq_hdr[0],
11340 					    phba->sli4_hba.nvmet_mrq_data[0],
11341 					    phba->sli4_hba.nvmet_cqset[0],
11342 					    LPFC_NVMET);
11343 			if (rc) {
11344 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11345 						"6057 Failed setup of NVMET "
11346 						"Receive Queue: rc = 0x%x\n",
11347 						(uint32_t)rc);
11348 				goto out_destroy;
11349 			}
11350 
11351 			lpfc_printf_log(
11352 				phba, KERN_INFO, LOG_INIT,
11353 				"6099 NVMET RQ setup: hdr-rq-id=%d, "
11354 				"dat-rq-id=%d parent cq-id=%d\n",
11355 				phba->sli4_hba.nvmet_mrq_hdr[0]->queue_id,
11356 				phba->sli4_hba.nvmet_mrq_data[0]->queue_id,
11357 				phba->sli4_hba.nvmet_cqset[0]->queue_id);
11358 
11359 		}
11360 	}
11361 
11362 	if (!phba->sli4_hba.hdr_rq || !phba->sli4_hba.dat_rq) {
11363 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11364 				"0540 Receive Queue not allocated\n");
11365 		rc = -ENOMEM;
11366 		goto out_destroy;
11367 	}
11368 
11369 	rc = lpfc_rq_create(phba, phba->sli4_hba.hdr_rq, phba->sli4_hba.dat_rq,
11370 			    phba->sli4_hba.els_cq, LPFC_USOL);
11371 	if (rc) {
11372 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11373 				"0541 Failed setup of Receive Queue: "
11374 				"rc = 0x%x\n", (uint32_t)rc);
11375 		goto out_destroy;
11376 	}
11377 
11378 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11379 			"2592 USL RQ setup: hdr-rq-id=%d, dat-rq-id=%d "
11380 			"parent cq-id=%d\n",
11381 			phba->sli4_hba.hdr_rq->queue_id,
11382 			phba->sli4_hba.dat_rq->queue_id,
11383 			phba->sli4_hba.els_cq->queue_id);
11384 
11385 	if (phba->cfg_fcp_imax)
11386 		usdelay = LPFC_SEC_TO_USEC / phba->cfg_fcp_imax;
11387 	else
11388 		usdelay = 0;
11389 
11390 	for (qidx = 0; qidx < phba->cfg_irq_chann;
11391 	     qidx += LPFC_MAX_EQ_DELAY_EQID_CNT)
11392 		lpfc_modify_hba_eq_delay(phba, qidx, LPFC_MAX_EQ_DELAY_EQID_CNT,
11393 					 usdelay);
11394 
11395 	if (phba->sli4_hba.cq_max) {
11396 		kfree(phba->sli4_hba.cq_lookup);
11397 		phba->sli4_hba.cq_lookup = kcalloc((phba->sli4_hba.cq_max + 1),
11398 			sizeof(struct lpfc_queue *), GFP_KERNEL);
11399 		if (!phba->sli4_hba.cq_lookup) {
11400 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11401 					"0549 Failed setup of CQ Lookup table: "
11402 					"size 0x%x\n", phba->sli4_hba.cq_max);
11403 			rc = -ENOMEM;
11404 			goto out_destroy;
11405 		}
11406 		lpfc_setup_cq_lookup(phba);
11407 	}
11408 	return 0;
11409 
11410 out_destroy:
11411 	lpfc_sli4_queue_unset(phba);
11412 out_error:
11413 	return rc;
11414 }
11415 
11416 /**
11417  * lpfc_sli4_queue_unset - Unset all the SLI4 queues
11418  * @phba: pointer to lpfc hba data structure.
11419  *
11420  * This routine is invoked to unset all the SLI4 queues with the FCoE HBA
11421  * operation.
11422  *
11423  * Return codes
11424  *      0 - successful
11425  *      -ENOMEM - No available memory
11426  *      -EIO - The mailbox failed to complete successfully.
11427  **/
11428 void
11429 lpfc_sli4_queue_unset(struct lpfc_hba *phba)
11430 {
11431 	struct lpfc_sli4_hdw_queue *qp;
11432 	struct lpfc_queue *eq;
11433 	int qidx;
11434 
11435 	/* Unset mailbox command work queue */
11436 	if (phba->sli4_hba.mbx_wq)
11437 		lpfc_mq_destroy(phba, phba->sli4_hba.mbx_wq);
11438 
11439 	/* Unset NVME LS work queue */
11440 	if (phba->sli4_hba.nvmels_wq)
11441 		lpfc_wq_destroy(phba, phba->sli4_hba.nvmels_wq);
11442 
11443 	/* Unset ELS work queue */
11444 	if (phba->sli4_hba.els_wq)
11445 		lpfc_wq_destroy(phba, phba->sli4_hba.els_wq);
11446 
11447 	/* Unset unsolicited receive queue */
11448 	if (phba->sli4_hba.hdr_rq)
11449 		lpfc_rq_destroy(phba, phba->sli4_hba.hdr_rq,
11450 				phba->sli4_hba.dat_rq);
11451 
11452 	/* Unset mailbox command complete queue */
11453 	if (phba->sli4_hba.mbx_cq)
11454 		lpfc_cq_destroy(phba, phba->sli4_hba.mbx_cq);
11455 
11456 	/* Unset ELS complete queue */
11457 	if (phba->sli4_hba.els_cq)
11458 		lpfc_cq_destroy(phba, phba->sli4_hba.els_cq);
11459 
11460 	/* Unset NVME LS complete queue */
11461 	if (phba->sli4_hba.nvmels_cq)
11462 		lpfc_cq_destroy(phba, phba->sli4_hba.nvmels_cq);
11463 
11464 	if (phba->nvmet_support) {
11465 		/* Unset NVMET MRQ queue */
11466 		if (phba->sli4_hba.nvmet_mrq_hdr) {
11467 			for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++)
11468 				lpfc_rq_destroy(
11469 					phba,
11470 					phba->sli4_hba.nvmet_mrq_hdr[qidx],
11471 					phba->sli4_hba.nvmet_mrq_data[qidx]);
11472 		}
11473 
11474 		/* Unset NVMET CQ Set complete queue */
11475 		if (phba->sli4_hba.nvmet_cqset) {
11476 			for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++)
11477 				lpfc_cq_destroy(
11478 					phba, phba->sli4_hba.nvmet_cqset[qidx]);
11479 		}
11480 	}
11481 
11482 	/* Unset fast-path SLI4 queues */
11483 	if (phba->sli4_hba.hdwq) {
11484 		/* Loop thru all Hardware Queues */
11485 		for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
11486 			/* Destroy the CQ/WQ corresponding to Hardware Queue */
11487 			qp = &phba->sli4_hba.hdwq[qidx];
11488 			lpfc_wq_destroy(phba, qp->io_wq);
11489 			lpfc_cq_destroy(phba, qp->io_cq);
11490 		}
11491 		/* Loop thru all IRQ vectors */
11492 		for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
11493 			/* Destroy the EQ corresponding to the IRQ vector */
11494 			eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
11495 			lpfc_eq_destroy(phba, eq);
11496 		}
11497 	}
11498 
11499 	kfree(phba->sli4_hba.cq_lookup);
11500 	phba->sli4_hba.cq_lookup = NULL;
11501 	phba->sli4_hba.cq_max = 0;
11502 }
11503 
11504 /**
11505  * lpfc_sli4_cq_event_pool_create - Create completion-queue event free pool
11506  * @phba: pointer to lpfc hba data structure.
11507  *
11508  * This routine is invoked to allocate and set up a pool of completion queue
11509  * events. The body of the completion queue event is a completion queue entry
11510  * CQE. For now, this pool is used for the interrupt service routine to queue
11511  * the following HBA completion queue events for the worker thread to process:
11512  *   - Mailbox asynchronous events
11513  *   - Receive queue completion unsolicited events
11514  * Later, this can be used for all the slow-path events.
11515  *
11516  * Return codes
11517  *      0 - successful
11518  *      -ENOMEM - No available memory
11519  **/
11520 static int
11521 lpfc_sli4_cq_event_pool_create(struct lpfc_hba *phba)
11522 {
11523 	struct lpfc_cq_event *cq_event;
11524 	int i;
11525 
11526 	for (i = 0; i < (4 * phba->sli4_hba.cq_ecount); i++) {
11527 		cq_event = kmalloc(sizeof(struct lpfc_cq_event), GFP_KERNEL);
11528 		if (!cq_event)
11529 			goto out_pool_create_fail;
11530 		list_add_tail(&cq_event->list,
11531 			      &phba->sli4_hba.sp_cqe_event_pool);
11532 	}
11533 	return 0;
11534 
11535 out_pool_create_fail:
11536 	lpfc_sli4_cq_event_pool_destroy(phba);
11537 	return -ENOMEM;
11538 }
11539 
11540 /**
11541  * lpfc_sli4_cq_event_pool_destroy - Free completion-queue event free pool
11542  * @phba: pointer to lpfc hba data structure.
11543  *
11544  * This routine is invoked to free the pool of completion queue events at
11545  * driver unload time. Note that, it is the responsibility of the driver
11546  * cleanup routine to free all the outstanding completion-queue events
11547  * allocated from this pool back into the pool before invoking this routine
11548  * to destroy the pool.
11549  **/
11550 static void
11551 lpfc_sli4_cq_event_pool_destroy(struct lpfc_hba *phba)
11552 {
11553 	struct lpfc_cq_event *cq_event, *next_cq_event;
11554 
11555 	list_for_each_entry_safe(cq_event, next_cq_event,
11556 				 &phba->sli4_hba.sp_cqe_event_pool, list) {
11557 		list_del(&cq_event->list);
11558 		kfree(cq_event);
11559 	}
11560 }
11561 
11562 /**
11563  * __lpfc_sli4_cq_event_alloc - Allocate a completion-queue event from free pool
11564  * @phba: pointer to lpfc hba data structure.
11565  *
11566  * This routine is the lock free version of the API invoked to allocate a
11567  * completion-queue event from the free pool.
11568  *
11569  * Return: Pointer to the newly allocated completion-queue event if successful
11570  *         NULL otherwise.
11571  **/
11572 struct lpfc_cq_event *
11573 __lpfc_sli4_cq_event_alloc(struct lpfc_hba *phba)
11574 {
11575 	struct lpfc_cq_event *cq_event = NULL;
11576 
11577 	list_remove_head(&phba->sli4_hba.sp_cqe_event_pool, cq_event,
11578 			 struct lpfc_cq_event, list);
11579 	return cq_event;
11580 }
11581 
11582 /**
11583  * lpfc_sli4_cq_event_alloc - Allocate a completion-queue event from free pool
11584  * @phba: pointer to lpfc hba data structure.
11585  *
11586  * This routine is the lock version of the API invoked to allocate a
11587  * completion-queue event from the free pool.
11588  *
11589  * Return: Pointer to the newly allocated completion-queue event if successful
11590  *         NULL otherwise.
11591  **/
11592 struct lpfc_cq_event *
11593 lpfc_sli4_cq_event_alloc(struct lpfc_hba *phba)
11594 {
11595 	struct lpfc_cq_event *cq_event;
11596 	unsigned long iflags;
11597 
11598 	spin_lock_irqsave(&phba->hbalock, iflags);
11599 	cq_event = __lpfc_sli4_cq_event_alloc(phba);
11600 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11601 	return cq_event;
11602 }
11603 
11604 /**
11605  * __lpfc_sli4_cq_event_release - Release a completion-queue event to free pool
11606  * @phba: pointer to lpfc hba data structure.
11607  * @cq_event: pointer to the completion queue event to be freed.
11608  *
11609  * This routine is the lock free version of the API invoked to release a
11610  * completion-queue event back into the free pool.
11611  **/
11612 void
11613 __lpfc_sli4_cq_event_release(struct lpfc_hba *phba,
11614 			     struct lpfc_cq_event *cq_event)
11615 {
11616 	list_add_tail(&cq_event->list, &phba->sli4_hba.sp_cqe_event_pool);
11617 }
11618 
11619 /**
11620  * lpfc_sli4_cq_event_release - Release a completion-queue event to free pool
11621  * @phba: pointer to lpfc hba data structure.
11622  * @cq_event: pointer to the completion queue event to be freed.
11623  *
11624  * This routine is the lock version of the API invoked to release a
11625  * completion-queue event back into the free pool.
11626  **/
11627 void
11628 lpfc_sli4_cq_event_release(struct lpfc_hba *phba,
11629 			   struct lpfc_cq_event *cq_event)
11630 {
11631 	unsigned long iflags;
11632 	spin_lock_irqsave(&phba->hbalock, iflags);
11633 	__lpfc_sli4_cq_event_release(phba, cq_event);
11634 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11635 }
11636 
11637 /**
11638  * lpfc_sli4_cq_event_release_all - Release all cq events to the free pool
11639  * @phba: pointer to lpfc hba data structure.
11640  *
11641  * This routine is to free all the pending completion-queue events to the
11642  * back into the free pool for device reset.
11643  **/
11644 static void
11645 lpfc_sli4_cq_event_release_all(struct lpfc_hba *phba)
11646 {
11647 	LIST_HEAD(cq_event_list);
11648 	struct lpfc_cq_event *cq_event;
11649 	unsigned long iflags;
11650 
11651 	/* Retrieve all the pending WCQEs from pending WCQE lists */
11652 
11653 	/* Pending ELS XRI abort events */
11654 	spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
11655 	list_splice_init(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
11656 			 &cq_event_list);
11657 	spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
11658 
11659 	/* Pending asynnc events */
11660 	spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
11661 	list_splice_init(&phba->sli4_hba.sp_asynce_work_queue,
11662 			 &cq_event_list);
11663 	spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock, iflags);
11664 
11665 	while (!list_empty(&cq_event_list)) {
11666 		list_remove_head(&cq_event_list, cq_event,
11667 				 struct lpfc_cq_event, list);
11668 		lpfc_sli4_cq_event_release(phba, cq_event);
11669 	}
11670 }
11671 
11672 /**
11673  * lpfc_pci_function_reset - Reset pci function.
11674  * @phba: pointer to lpfc hba data structure.
11675  *
11676  * This routine is invoked to request a PCI function reset. It will destroys
11677  * all resources assigned to the PCI function which originates this request.
11678  *
11679  * Return codes
11680  *      0 - successful
11681  *      -ENOMEM - No available memory
11682  *      -EIO - The mailbox failed to complete successfully.
11683  **/
11684 int
11685 lpfc_pci_function_reset(struct lpfc_hba *phba)
11686 {
11687 	LPFC_MBOXQ_t *mboxq;
11688 	uint32_t rc = 0, if_type;
11689 	uint32_t shdr_status, shdr_add_status;
11690 	uint32_t rdy_chk;
11691 	uint32_t port_reset = 0;
11692 	union lpfc_sli4_cfg_shdr *shdr;
11693 	struct lpfc_register reg_data;
11694 	uint16_t devid;
11695 
11696 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
11697 	switch (if_type) {
11698 	case LPFC_SLI_INTF_IF_TYPE_0:
11699 		mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
11700 						       GFP_KERNEL);
11701 		if (!mboxq) {
11702 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11703 					"0494 Unable to allocate memory for "
11704 					"issuing SLI_FUNCTION_RESET mailbox "
11705 					"command\n");
11706 			return -ENOMEM;
11707 		}
11708 
11709 		/* Setup PCI function reset mailbox-ioctl command */
11710 		lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
11711 				 LPFC_MBOX_OPCODE_FUNCTION_RESET, 0,
11712 				 LPFC_SLI4_MBX_EMBED);
11713 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
11714 		shdr = (union lpfc_sli4_cfg_shdr *)
11715 			&mboxq->u.mqe.un.sli4_config.header.cfg_shdr;
11716 		shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
11717 		shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
11718 					 &shdr->response);
11719 		mempool_free(mboxq, phba->mbox_mem_pool);
11720 		if (shdr_status || shdr_add_status || rc) {
11721 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11722 					"0495 SLI_FUNCTION_RESET mailbox "
11723 					"failed with status x%x add_status x%x,"
11724 					" mbx status x%x\n",
11725 					shdr_status, shdr_add_status, rc);
11726 			rc = -ENXIO;
11727 		}
11728 		break;
11729 	case LPFC_SLI_INTF_IF_TYPE_2:
11730 	case LPFC_SLI_INTF_IF_TYPE_6:
11731 wait:
11732 		/*
11733 		 * Poll the Port Status Register and wait for RDY for
11734 		 * up to 30 seconds. If the port doesn't respond, treat
11735 		 * it as an error.
11736 		 */
11737 		for (rdy_chk = 0; rdy_chk < 1500; rdy_chk++) {
11738 			if (lpfc_readl(phba->sli4_hba.u.if_type2.
11739 				STATUSregaddr, &reg_data.word0)) {
11740 				rc = -ENODEV;
11741 				goto out;
11742 			}
11743 			if (bf_get(lpfc_sliport_status_rdy, &reg_data))
11744 				break;
11745 			msleep(20);
11746 		}
11747 
11748 		if (!bf_get(lpfc_sliport_status_rdy, &reg_data)) {
11749 			phba->work_status[0] = readl(
11750 				phba->sli4_hba.u.if_type2.ERR1regaddr);
11751 			phba->work_status[1] = readl(
11752 				phba->sli4_hba.u.if_type2.ERR2regaddr);
11753 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11754 					"2890 Port not ready, port status reg "
11755 					"0x%x error 1=0x%x, error 2=0x%x\n",
11756 					reg_data.word0,
11757 					phba->work_status[0],
11758 					phba->work_status[1]);
11759 			rc = -ENODEV;
11760 			goto out;
11761 		}
11762 
11763 		if (bf_get(lpfc_sliport_status_pldv, &reg_data))
11764 			lpfc_pldv_detect = true;
11765 
11766 		if (!port_reset) {
11767 			/*
11768 			 * Reset the port now
11769 			 */
11770 			reg_data.word0 = 0;
11771 			bf_set(lpfc_sliport_ctrl_end, &reg_data,
11772 			       LPFC_SLIPORT_LITTLE_ENDIAN);
11773 			bf_set(lpfc_sliport_ctrl_ip, &reg_data,
11774 			       LPFC_SLIPORT_INIT_PORT);
11775 			writel(reg_data.word0, phba->sli4_hba.u.if_type2.
11776 			       CTRLregaddr);
11777 			/* flush */
11778 			pci_read_config_word(phba->pcidev,
11779 					     PCI_DEVICE_ID, &devid);
11780 
11781 			port_reset = 1;
11782 			msleep(20);
11783 			goto wait;
11784 		} else if (bf_get(lpfc_sliport_status_rn, &reg_data)) {
11785 			rc = -ENODEV;
11786 			goto out;
11787 		}
11788 		break;
11789 
11790 	case LPFC_SLI_INTF_IF_TYPE_1:
11791 	default:
11792 		break;
11793 	}
11794 
11795 out:
11796 	/* Catch the not-ready port failure after a port reset. */
11797 	if (rc) {
11798 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11799 				"3317 HBA not functional: IP Reset Failed "
11800 				"try: echo fw_reset > board_mode\n");
11801 		rc = -ENODEV;
11802 	}
11803 
11804 	return rc;
11805 }
11806 
11807 /**
11808  * lpfc_sli4_pci_mem_setup - Setup SLI4 HBA PCI memory space.
11809  * @phba: pointer to lpfc hba data structure.
11810  *
11811  * This routine is invoked to set up the PCI device memory space for device
11812  * with SLI-4 interface spec.
11813  *
11814  * Return codes
11815  * 	0 - successful
11816  * 	other values - error
11817  **/
11818 static int
11819 lpfc_sli4_pci_mem_setup(struct lpfc_hba *phba)
11820 {
11821 	struct pci_dev *pdev = phba->pcidev;
11822 	unsigned long bar0map_len, bar1map_len, bar2map_len;
11823 	int error;
11824 	uint32_t if_type;
11825 
11826 	if (!pdev)
11827 		return -ENODEV;
11828 
11829 	/* Set the device DMA mask size */
11830 	error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
11831 	if (error)
11832 		error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32));
11833 	if (error)
11834 		return error;
11835 
11836 	/*
11837 	 * The BARs and register set definitions and offset locations are
11838 	 * dependent on the if_type.
11839 	 */
11840 	if (pci_read_config_dword(pdev, LPFC_SLI_INTF,
11841 				  &phba->sli4_hba.sli_intf.word0)) {
11842 		return -ENODEV;
11843 	}
11844 
11845 	/* There is no SLI3 failback for SLI4 devices. */
11846 	if (bf_get(lpfc_sli_intf_valid, &phba->sli4_hba.sli_intf) !=
11847 	    LPFC_SLI_INTF_VALID) {
11848 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11849 				"2894 SLI_INTF reg contents invalid "
11850 				"sli_intf reg 0x%x\n",
11851 				phba->sli4_hba.sli_intf.word0);
11852 		return -ENODEV;
11853 	}
11854 
11855 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
11856 	/*
11857 	 * Get the bus address of SLI4 device Bar regions and the
11858 	 * number of bytes required by each mapping. The mapping of the
11859 	 * particular PCI BARs regions is dependent on the type of
11860 	 * SLI4 device.
11861 	 */
11862 	if (pci_resource_start(pdev, PCI_64BIT_BAR0)) {
11863 		phba->pci_bar0_map = pci_resource_start(pdev, PCI_64BIT_BAR0);
11864 		bar0map_len = pci_resource_len(pdev, PCI_64BIT_BAR0);
11865 
11866 		/*
11867 		 * Map SLI4 PCI Config Space Register base to a kernel virtual
11868 		 * addr
11869 		 */
11870 		phba->sli4_hba.conf_regs_memmap_p =
11871 			ioremap(phba->pci_bar0_map, bar0map_len);
11872 		if (!phba->sli4_hba.conf_regs_memmap_p) {
11873 			dev_printk(KERN_ERR, &pdev->dev,
11874 				   "ioremap failed for SLI4 PCI config "
11875 				   "registers.\n");
11876 			return -ENODEV;
11877 		}
11878 		phba->pci_bar0_memmap_p = phba->sli4_hba.conf_regs_memmap_p;
11879 		/* Set up BAR0 PCI config space register memory map */
11880 		lpfc_sli4_bar0_register_memmap(phba, if_type);
11881 	} else {
11882 		phba->pci_bar0_map = pci_resource_start(pdev, 1);
11883 		bar0map_len = pci_resource_len(pdev, 1);
11884 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
11885 			dev_printk(KERN_ERR, &pdev->dev,
11886 			   "FATAL - No BAR0 mapping for SLI4, if_type 2\n");
11887 			return -ENODEV;
11888 		}
11889 		phba->sli4_hba.conf_regs_memmap_p =
11890 				ioremap(phba->pci_bar0_map, bar0map_len);
11891 		if (!phba->sli4_hba.conf_regs_memmap_p) {
11892 			dev_printk(KERN_ERR, &pdev->dev,
11893 				"ioremap failed for SLI4 PCI config "
11894 				"registers.\n");
11895 			return -ENODEV;
11896 		}
11897 		lpfc_sli4_bar0_register_memmap(phba, if_type);
11898 	}
11899 
11900 	if (if_type == LPFC_SLI_INTF_IF_TYPE_0) {
11901 		if (pci_resource_start(pdev, PCI_64BIT_BAR2)) {
11902 			/*
11903 			 * Map SLI4 if type 0 HBA Control Register base to a
11904 			 * kernel virtual address and setup the registers.
11905 			 */
11906 			phba->pci_bar1_map = pci_resource_start(pdev,
11907 								PCI_64BIT_BAR2);
11908 			bar1map_len = pci_resource_len(pdev, PCI_64BIT_BAR2);
11909 			phba->sli4_hba.ctrl_regs_memmap_p =
11910 					ioremap(phba->pci_bar1_map,
11911 						bar1map_len);
11912 			if (!phba->sli4_hba.ctrl_regs_memmap_p) {
11913 				dev_err(&pdev->dev,
11914 					   "ioremap failed for SLI4 HBA "
11915 					    "control registers.\n");
11916 				error = -ENOMEM;
11917 				goto out_iounmap_conf;
11918 			}
11919 			phba->pci_bar2_memmap_p =
11920 					 phba->sli4_hba.ctrl_regs_memmap_p;
11921 			lpfc_sli4_bar1_register_memmap(phba, if_type);
11922 		} else {
11923 			error = -ENOMEM;
11924 			goto out_iounmap_conf;
11925 		}
11926 	}
11927 
11928 	if ((if_type == LPFC_SLI_INTF_IF_TYPE_6) &&
11929 	    (pci_resource_start(pdev, PCI_64BIT_BAR2))) {
11930 		/*
11931 		 * Map SLI4 if type 6 HBA Doorbell Register base to a kernel
11932 		 * virtual address and setup the registers.
11933 		 */
11934 		phba->pci_bar1_map = pci_resource_start(pdev, PCI_64BIT_BAR2);
11935 		bar1map_len = pci_resource_len(pdev, PCI_64BIT_BAR2);
11936 		phba->sli4_hba.drbl_regs_memmap_p =
11937 				ioremap(phba->pci_bar1_map, bar1map_len);
11938 		if (!phba->sli4_hba.drbl_regs_memmap_p) {
11939 			dev_err(&pdev->dev,
11940 			   "ioremap failed for SLI4 HBA doorbell registers.\n");
11941 			error = -ENOMEM;
11942 			goto out_iounmap_conf;
11943 		}
11944 		phba->pci_bar2_memmap_p = phba->sli4_hba.drbl_regs_memmap_p;
11945 		lpfc_sli4_bar1_register_memmap(phba, if_type);
11946 	}
11947 
11948 	if (if_type == LPFC_SLI_INTF_IF_TYPE_0) {
11949 		if (pci_resource_start(pdev, PCI_64BIT_BAR4)) {
11950 			/*
11951 			 * Map SLI4 if type 0 HBA Doorbell Register base to
11952 			 * a kernel virtual address and setup the registers.
11953 			 */
11954 			phba->pci_bar2_map = pci_resource_start(pdev,
11955 								PCI_64BIT_BAR4);
11956 			bar2map_len = pci_resource_len(pdev, PCI_64BIT_BAR4);
11957 			phba->sli4_hba.drbl_regs_memmap_p =
11958 					ioremap(phba->pci_bar2_map,
11959 						bar2map_len);
11960 			if (!phba->sli4_hba.drbl_regs_memmap_p) {
11961 				dev_err(&pdev->dev,
11962 					   "ioremap failed for SLI4 HBA"
11963 					   " doorbell registers.\n");
11964 				error = -ENOMEM;
11965 				goto out_iounmap_ctrl;
11966 			}
11967 			phba->pci_bar4_memmap_p =
11968 					phba->sli4_hba.drbl_regs_memmap_p;
11969 			error = lpfc_sli4_bar2_register_memmap(phba, LPFC_VF0);
11970 			if (error)
11971 				goto out_iounmap_all;
11972 		} else {
11973 			error = -ENOMEM;
11974 			goto out_iounmap_ctrl;
11975 		}
11976 	}
11977 
11978 	if (if_type == LPFC_SLI_INTF_IF_TYPE_6 &&
11979 	    pci_resource_start(pdev, PCI_64BIT_BAR4)) {
11980 		/*
11981 		 * Map SLI4 if type 6 HBA DPP Register base to a kernel
11982 		 * virtual address and setup the registers.
11983 		 */
11984 		phba->pci_bar2_map = pci_resource_start(pdev, PCI_64BIT_BAR4);
11985 		bar2map_len = pci_resource_len(pdev, PCI_64BIT_BAR4);
11986 		phba->sli4_hba.dpp_regs_memmap_p =
11987 				ioremap(phba->pci_bar2_map, bar2map_len);
11988 		if (!phba->sli4_hba.dpp_regs_memmap_p) {
11989 			dev_err(&pdev->dev,
11990 			   "ioremap failed for SLI4 HBA dpp registers.\n");
11991 			error = -ENOMEM;
11992 			goto out_iounmap_all;
11993 		}
11994 		phba->pci_bar4_memmap_p = phba->sli4_hba.dpp_regs_memmap_p;
11995 	}
11996 
11997 	/* Set up the EQ/CQ register handeling functions now */
11998 	switch (if_type) {
11999 	case LPFC_SLI_INTF_IF_TYPE_0:
12000 	case LPFC_SLI_INTF_IF_TYPE_2:
12001 		phba->sli4_hba.sli4_eq_clr_intr = lpfc_sli4_eq_clr_intr;
12002 		phba->sli4_hba.sli4_write_eq_db = lpfc_sli4_write_eq_db;
12003 		phba->sli4_hba.sli4_write_cq_db = lpfc_sli4_write_cq_db;
12004 		break;
12005 	case LPFC_SLI_INTF_IF_TYPE_6:
12006 		phba->sli4_hba.sli4_eq_clr_intr = lpfc_sli4_if6_eq_clr_intr;
12007 		phba->sli4_hba.sli4_write_eq_db = lpfc_sli4_if6_write_eq_db;
12008 		phba->sli4_hba.sli4_write_cq_db = lpfc_sli4_if6_write_cq_db;
12009 		break;
12010 	default:
12011 		break;
12012 	}
12013 
12014 	return 0;
12015 
12016 out_iounmap_all:
12017 	if (phba->sli4_hba.drbl_regs_memmap_p)
12018 		iounmap(phba->sli4_hba.drbl_regs_memmap_p);
12019 out_iounmap_ctrl:
12020 	if (phba->sli4_hba.ctrl_regs_memmap_p)
12021 		iounmap(phba->sli4_hba.ctrl_regs_memmap_p);
12022 out_iounmap_conf:
12023 	iounmap(phba->sli4_hba.conf_regs_memmap_p);
12024 
12025 	return error;
12026 }
12027 
12028 /**
12029  * lpfc_sli4_pci_mem_unset - Unset SLI4 HBA PCI memory space.
12030  * @phba: pointer to lpfc hba data structure.
12031  *
12032  * This routine is invoked to unset the PCI device memory space for device
12033  * with SLI-4 interface spec.
12034  **/
12035 static void
12036 lpfc_sli4_pci_mem_unset(struct lpfc_hba *phba)
12037 {
12038 	uint32_t if_type;
12039 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
12040 
12041 	switch (if_type) {
12042 	case LPFC_SLI_INTF_IF_TYPE_0:
12043 		iounmap(phba->sli4_hba.drbl_regs_memmap_p);
12044 		iounmap(phba->sli4_hba.ctrl_regs_memmap_p);
12045 		iounmap(phba->sli4_hba.conf_regs_memmap_p);
12046 		break;
12047 	case LPFC_SLI_INTF_IF_TYPE_2:
12048 		iounmap(phba->sli4_hba.conf_regs_memmap_p);
12049 		break;
12050 	case LPFC_SLI_INTF_IF_TYPE_6:
12051 		iounmap(phba->sli4_hba.drbl_regs_memmap_p);
12052 		iounmap(phba->sli4_hba.conf_regs_memmap_p);
12053 		if (phba->sli4_hba.dpp_regs_memmap_p)
12054 			iounmap(phba->sli4_hba.dpp_regs_memmap_p);
12055 		break;
12056 	case LPFC_SLI_INTF_IF_TYPE_1:
12057 		break;
12058 	default:
12059 		dev_printk(KERN_ERR, &phba->pcidev->dev,
12060 			   "FATAL - unsupported SLI4 interface type - %d\n",
12061 			   if_type);
12062 		break;
12063 	}
12064 }
12065 
12066 /**
12067  * lpfc_sli_enable_msix - Enable MSI-X interrupt mode on SLI-3 device
12068  * @phba: pointer to lpfc hba data structure.
12069  *
12070  * This routine is invoked to enable the MSI-X interrupt vectors to device
12071  * with SLI-3 interface specs.
12072  *
12073  * Return codes
12074  *   0 - successful
12075  *   other values - error
12076  **/
12077 static int
12078 lpfc_sli_enable_msix(struct lpfc_hba *phba)
12079 {
12080 	int rc;
12081 	LPFC_MBOXQ_t *pmb;
12082 
12083 	/* Set up MSI-X multi-message vectors */
12084 	rc = pci_alloc_irq_vectors(phba->pcidev,
12085 			LPFC_MSIX_VECTORS, LPFC_MSIX_VECTORS, PCI_IRQ_MSIX);
12086 	if (rc < 0) {
12087 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12088 				"0420 PCI enable MSI-X failed (%d)\n", rc);
12089 		goto vec_fail_out;
12090 	}
12091 
12092 	/*
12093 	 * Assign MSI-X vectors to interrupt handlers
12094 	 */
12095 
12096 	/* vector-0 is associated to slow-path handler */
12097 	rc = request_irq(pci_irq_vector(phba->pcidev, 0),
12098 			 &lpfc_sli_sp_intr_handler, 0,
12099 			 LPFC_SP_DRIVER_HANDLER_NAME, phba);
12100 	if (rc) {
12101 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
12102 				"0421 MSI-X slow-path request_irq failed "
12103 				"(%d)\n", rc);
12104 		goto msi_fail_out;
12105 	}
12106 
12107 	/* vector-1 is associated to fast-path handler */
12108 	rc = request_irq(pci_irq_vector(phba->pcidev, 1),
12109 			 &lpfc_sli_fp_intr_handler, 0,
12110 			 LPFC_FP_DRIVER_HANDLER_NAME, phba);
12111 
12112 	if (rc) {
12113 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
12114 				"0429 MSI-X fast-path request_irq failed "
12115 				"(%d)\n", rc);
12116 		goto irq_fail_out;
12117 	}
12118 
12119 	/*
12120 	 * Configure HBA MSI-X attention conditions to messages
12121 	 */
12122 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
12123 
12124 	if (!pmb) {
12125 		rc = -ENOMEM;
12126 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12127 				"0474 Unable to allocate memory for issuing "
12128 				"MBOX_CONFIG_MSI command\n");
12129 		goto mem_fail_out;
12130 	}
12131 	rc = lpfc_config_msi(phba, pmb);
12132 	if (rc)
12133 		goto mbx_fail_out;
12134 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
12135 	if (rc != MBX_SUCCESS) {
12136 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX,
12137 				"0351 Config MSI mailbox command failed, "
12138 				"mbxCmd x%x, mbxStatus x%x\n",
12139 				pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus);
12140 		goto mbx_fail_out;
12141 	}
12142 
12143 	/* Free memory allocated for mailbox command */
12144 	mempool_free(pmb, phba->mbox_mem_pool);
12145 	return rc;
12146 
12147 mbx_fail_out:
12148 	/* Free memory allocated for mailbox command */
12149 	mempool_free(pmb, phba->mbox_mem_pool);
12150 
12151 mem_fail_out:
12152 	/* free the irq already requested */
12153 	free_irq(pci_irq_vector(phba->pcidev, 1), phba);
12154 
12155 irq_fail_out:
12156 	/* free the irq already requested */
12157 	free_irq(pci_irq_vector(phba->pcidev, 0), phba);
12158 
12159 msi_fail_out:
12160 	/* Unconfigure MSI-X capability structure */
12161 	pci_free_irq_vectors(phba->pcidev);
12162 
12163 vec_fail_out:
12164 	return rc;
12165 }
12166 
12167 /**
12168  * lpfc_sli_enable_msi - Enable MSI interrupt mode on SLI-3 device.
12169  * @phba: pointer to lpfc hba data structure.
12170  *
12171  * This routine is invoked to enable the MSI interrupt mode to device with
12172  * SLI-3 interface spec. The kernel function pci_enable_msi() is called to
12173  * enable the MSI vector. The device driver is responsible for calling the
12174  * request_irq() to register MSI vector with a interrupt the handler, which
12175  * is done in this function.
12176  *
12177  * Return codes
12178  * 	0 - successful
12179  * 	other values - error
12180  */
12181 static int
12182 lpfc_sli_enable_msi(struct lpfc_hba *phba)
12183 {
12184 	int rc;
12185 
12186 	rc = pci_enable_msi(phba->pcidev);
12187 	if (!rc)
12188 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12189 				"0012 PCI enable MSI mode success.\n");
12190 	else {
12191 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12192 				"0471 PCI enable MSI mode failed (%d)\n", rc);
12193 		return rc;
12194 	}
12195 
12196 	rc = request_irq(phba->pcidev->irq, lpfc_sli_intr_handler,
12197 			 0, LPFC_DRIVER_NAME, phba);
12198 	if (rc) {
12199 		pci_disable_msi(phba->pcidev);
12200 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
12201 				"0478 MSI request_irq failed (%d)\n", rc);
12202 	}
12203 	return rc;
12204 }
12205 
12206 /**
12207  * lpfc_sli_enable_intr - Enable device interrupt to SLI-3 device.
12208  * @phba: pointer to lpfc hba data structure.
12209  * @cfg_mode: Interrupt configuration mode (INTx, MSI or MSI-X).
12210  *
12211  * This routine is invoked to enable device interrupt and associate driver's
12212  * interrupt handler(s) to interrupt vector(s) to device with SLI-3 interface
12213  * spec. Depends on the interrupt mode configured to the driver, the driver
12214  * will try to fallback from the configured interrupt mode to an interrupt
12215  * mode which is supported by the platform, kernel, and device in the order
12216  * of:
12217  * MSI-X -> MSI -> IRQ.
12218  *
12219  * Return codes
12220  *   0 - successful
12221  *   other values - error
12222  **/
12223 static uint32_t
12224 lpfc_sli_enable_intr(struct lpfc_hba *phba, uint32_t cfg_mode)
12225 {
12226 	uint32_t intr_mode = LPFC_INTR_ERROR;
12227 	int retval;
12228 
12229 	/* Need to issue conf_port mbox cmd before conf_msi mbox cmd */
12230 	retval = lpfc_sli_config_port(phba, LPFC_SLI_REV3);
12231 	if (retval)
12232 		return intr_mode;
12233 	clear_bit(HBA_NEEDS_CFG_PORT, &phba->hba_flag);
12234 
12235 	if (cfg_mode == 2) {
12236 		/* Now, try to enable MSI-X interrupt mode */
12237 		retval = lpfc_sli_enable_msix(phba);
12238 		if (!retval) {
12239 			/* Indicate initialization to MSI-X mode */
12240 			phba->intr_type = MSIX;
12241 			intr_mode = 2;
12242 		}
12243 	}
12244 
12245 	/* Fallback to MSI if MSI-X initialization failed */
12246 	if (cfg_mode >= 1 && phba->intr_type == NONE) {
12247 		retval = lpfc_sli_enable_msi(phba);
12248 		if (!retval) {
12249 			/* Indicate initialization to MSI mode */
12250 			phba->intr_type = MSI;
12251 			intr_mode = 1;
12252 		}
12253 	}
12254 
12255 	/* Fallback to INTx if both MSI-X/MSI initalization failed */
12256 	if (phba->intr_type == NONE) {
12257 		retval = request_irq(phba->pcidev->irq, lpfc_sli_intr_handler,
12258 				     IRQF_SHARED, LPFC_DRIVER_NAME, phba);
12259 		if (!retval) {
12260 			/* Indicate initialization to INTx mode */
12261 			phba->intr_type = INTx;
12262 			intr_mode = 0;
12263 		}
12264 	}
12265 	return intr_mode;
12266 }
12267 
12268 /**
12269  * lpfc_sli_disable_intr - Disable device interrupt to SLI-3 device.
12270  * @phba: pointer to lpfc hba data structure.
12271  *
12272  * This routine is invoked to disable device interrupt and disassociate the
12273  * driver's interrupt handler(s) from interrupt vector(s) to device with
12274  * SLI-3 interface spec. Depending on the interrupt mode, the driver will
12275  * release the interrupt vector(s) for the message signaled interrupt.
12276  **/
12277 static void
12278 lpfc_sli_disable_intr(struct lpfc_hba *phba)
12279 {
12280 	int nr_irqs, i;
12281 
12282 	if (phba->intr_type == MSIX)
12283 		nr_irqs = LPFC_MSIX_VECTORS;
12284 	else
12285 		nr_irqs = 1;
12286 
12287 	for (i = 0; i < nr_irqs; i++)
12288 		free_irq(pci_irq_vector(phba->pcidev, i), phba);
12289 	pci_free_irq_vectors(phba->pcidev);
12290 
12291 	/* Reset interrupt management states */
12292 	phba->intr_type = NONE;
12293 	phba->sli.slistat.sli_intr = 0;
12294 }
12295 
12296 /**
12297  * lpfc_find_cpu_handle - Find the CPU that corresponds to the specified Queue
12298  * @phba: pointer to lpfc hba data structure.
12299  * @id: EQ vector index or Hardware Queue index
12300  * @match: LPFC_FIND_BY_EQ = match by EQ
12301  *         LPFC_FIND_BY_HDWQ = match by Hardware Queue
12302  * Return the CPU that matches the selection criteria
12303  */
12304 static uint16_t
12305 lpfc_find_cpu_handle(struct lpfc_hba *phba, uint16_t id, int match)
12306 {
12307 	struct lpfc_vector_map_info *cpup;
12308 	int cpu;
12309 
12310 	/* Loop through all CPUs */
12311 	for_each_present_cpu(cpu) {
12312 		cpup = &phba->sli4_hba.cpu_map[cpu];
12313 
12314 		/* If we are matching by EQ, there may be multiple CPUs using
12315 		 * using the same vector, so select the one with
12316 		 * LPFC_CPU_FIRST_IRQ set.
12317 		 */
12318 		if ((match == LPFC_FIND_BY_EQ) &&
12319 		    (cpup->flag & LPFC_CPU_FIRST_IRQ) &&
12320 		    (cpup->eq == id))
12321 			return cpu;
12322 
12323 		/* If matching by HDWQ, select the first CPU that matches */
12324 		if ((match == LPFC_FIND_BY_HDWQ) && (cpup->hdwq == id))
12325 			return cpu;
12326 	}
12327 	return 0;
12328 }
12329 
12330 #ifdef CONFIG_X86
12331 /**
12332  * lpfc_find_hyper - Determine if the CPU map entry is hyper-threaded
12333  * @phba: pointer to lpfc hba data structure.
12334  * @cpu: CPU map index
12335  * @phys_id: CPU package physical id
12336  * @core_id: CPU core id
12337  */
12338 static int
12339 lpfc_find_hyper(struct lpfc_hba *phba, int cpu,
12340 		uint16_t phys_id, uint16_t core_id)
12341 {
12342 	struct lpfc_vector_map_info *cpup;
12343 	int idx;
12344 
12345 	for_each_present_cpu(idx) {
12346 		cpup = &phba->sli4_hba.cpu_map[idx];
12347 		/* Does the cpup match the one we are looking for */
12348 		if ((cpup->phys_id == phys_id) &&
12349 		    (cpup->core_id == core_id) &&
12350 		    (cpu != idx))
12351 			return 1;
12352 	}
12353 	return 0;
12354 }
12355 #endif
12356 
12357 /*
12358  * lpfc_assign_eq_map_info - Assigns eq for vector_map structure
12359  * @phba: pointer to lpfc hba data structure.
12360  * @eqidx: index for eq and irq vector
12361  * @flag: flags to set for vector_map structure
12362  * @cpu: cpu used to index vector_map structure
12363  *
12364  * The routine assigns eq info into vector_map structure
12365  */
12366 static inline void
12367 lpfc_assign_eq_map_info(struct lpfc_hba *phba, uint16_t eqidx, uint16_t flag,
12368 			unsigned int cpu)
12369 {
12370 	struct lpfc_vector_map_info *cpup = &phba->sli4_hba.cpu_map[cpu];
12371 	struct lpfc_hba_eq_hdl *eqhdl = lpfc_get_eq_hdl(eqidx);
12372 
12373 	cpup->eq = eqidx;
12374 	cpup->flag |= flag;
12375 
12376 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12377 			"3336 Set Affinity: CPU %d irq %d eq %d flag x%x\n",
12378 			cpu, eqhdl->irq, cpup->eq, cpup->flag);
12379 }
12380 
12381 /**
12382  * lpfc_cpu_map_array_init - Initialize cpu_map structure
12383  * @phba: pointer to lpfc hba data structure.
12384  *
12385  * The routine initializes the cpu_map array structure
12386  */
12387 static void
12388 lpfc_cpu_map_array_init(struct lpfc_hba *phba)
12389 {
12390 	struct lpfc_vector_map_info *cpup;
12391 	struct lpfc_eq_intr_info *eqi;
12392 	int cpu;
12393 
12394 	for_each_possible_cpu(cpu) {
12395 		cpup = &phba->sli4_hba.cpu_map[cpu];
12396 		cpup->phys_id = LPFC_VECTOR_MAP_EMPTY;
12397 		cpup->core_id = LPFC_VECTOR_MAP_EMPTY;
12398 		cpup->hdwq = LPFC_VECTOR_MAP_EMPTY;
12399 		cpup->eq = LPFC_VECTOR_MAP_EMPTY;
12400 		cpup->flag = 0;
12401 		eqi = per_cpu_ptr(phba->sli4_hba.eq_info, cpu);
12402 		INIT_LIST_HEAD(&eqi->list);
12403 		eqi->icnt = 0;
12404 	}
12405 }
12406 
12407 /**
12408  * lpfc_hba_eq_hdl_array_init - Initialize hba_eq_hdl structure
12409  * @phba: pointer to lpfc hba data structure.
12410  *
12411  * The routine initializes the hba_eq_hdl array structure
12412  */
12413 static void
12414 lpfc_hba_eq_hdl_array_init(struct lpfc_hba *phba)
12415 {
12416 	struct lpfc_hba_eq_hdl *eqhdl;
12417 	int i;
12418 
12419 	for (i = 0; i < phba->cfg_irq_chann; i++) {
12420 		eqhdl = lpfc_get_eq_hdl(i);
12421 		eqhdl->irq = LPFC_IRQ_EMPTY;
12422 		eqhdl->phba = phba;
12423 	}
12424 }
12425 
12426 /**
12427  * lpfc_cpu_affinity_check - Check vector CPU affinity mappings
12428  * @phba: pointer to lpfc hba data structure.
12429  * @vectors: number of msix vectors allocated.
12430  *
12431  * The routine will figure out the CPU affinity assignment for every
12432  * MSI-X vector allocated for the HBA.
12433  * In addition, the CPU to IO channel mapping will be calculated
12434  * and the phba->sli4_hba.cpu_map array will reflect this.
12435  */
12436 static void
12437 lpfc_cpu_affinity_check(struct lpfc_hba *phba, int vectors)
12438 {
12439 	int i, cpu, idx, next_idx, new_cpu, start_cpu, first_cpu;
12440 	int max_phys_id, min_phys_id;
12441 	int max_core_id, min_core_id;
12442 	struct lpfc_vector_map_info *cpup;
12443 	struct lpfc_vector_map_info *new_cpup;
12444 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
12445 	struct lpfc_hdwq_stat *c_stat;
12446 #endif
12447 
12448 	max_phys_id = 0;
12449 	min_phys_id = LPFC_VECTOR_MAP_EMPTY;
12450 	max_core_id = 0;
12451 	min_core_id = LPFC_VECTOR_MAP_EMPTY;
12452 
12453 	/* Update CPU map with physical id and core id of each CPU */
12454 	for_each_present_cpu(cpu) {
12455 		cpup = &phba->sli4_hba.cpu_map[cpu];
12456 #ifdef CONFIG_X86
12457 		cpup->phys_id = topology_physical_package_id(cpu);
12458 		cpup->core_id = topology_core_id(cpu);
12459 		if (lpfc_find_hyper(phba, cpu, cpup->phys_id, cpup->core_id))
12460 			cpup->flag |= LPFC_CPU_MAP_HYPER;
12461 #else
12462 		/* No distinction between CPUs for other platforms */
12463 		cpup->phys_id = 0;
12464 		cpup->core_id = cpu;
12465 #endif
12466 
12467 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12468 				"3328 CPU %d physid %d coreid %d flag x%x\n",
12469 				cpu, cpup->phys_id, cpup->core_id, cpup->flag);
12470 
12471 		if (cpup->phys_id > max_phys_id)
12472 			max_phys_id = cpup->phys_id;
12473 		if (cpup->phys_id < min_phys_id)
12474 			min_phys_id = cpup->phys_id;
12475 
12476 		if (cpup->core_id > max_core_id)
12477 			max_core_id = cpup->core_id;
12478 		if (cpup->core_id < min_core_id)
12479 			min_core_id = cpup->core_id;
12480 	}
12481 
12482 	/* After looking at each irq vector assigned to this pcidev, its
12483 	 * possible to see that not ALL CPUs have been accounted for.
12484 	 * Next we will set any unassigned (unaffinitized) cpu map
12485 	 * entries to a IRQ on the same phys_id.
12486 	 */
12487 	first_cpu = cpumask_first(cpu_present_mask);
12488 	start_cpu = first_cpu;
12489 
12490 	for_each_present_cpu(cpu) {
12491 		cpup = &phba->sli4_hba.cpu_map[cpu];
12492 
12493 		/* Is this CPU entry unassigned */
12494 		if (cpup->eq == LPFC_VECTOR_MAP_EMPTY) {
12495 			/* Mark CPU as IRQ not assigned by the kernel */
12496 			cpup->flag |= LPFC_CPU_MAP_UNASSIGN;
12497 
12498 			/* If so, find a new_cpup that is on the SAME
12499 			 * phys_id as cpup. start_cpu will start where we
12500 			 * left off so all unassigned entries don't get assgined
12501 			 * the IRQ of the first entry.
12502 			 */
12503 			new_cpu = start_cpu;
12504 			for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12505 				new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12506 				if (!(new_cpup->flag & LPFC_CPU_MAP_UNASSIGN) &&
12507 				    (new_cpup->eq != LPFC_VECTOR_MAP_EMPTY) &&
12508 				    (new_cpup->phys_id == cpup->phys_id))
12509 					goto found_same;
12510 				new_cpu = lpfc_next_present_cpu(new_cpu);
12511 			}
12512 			/* At this point, we leave the CPU as unassigned */
12513 			continue;
12514 found_same:
12515 			/* We found a matching phys_id, so copy the IRQ info */
12516 			cpup->eq = new_cpup->eq;
12517 
12518 			/* Bump start_cpu to the next slot to minmize the
12519 			 * chance of having multiple unassigned CPU entries
12520 			 * selecting the same IRQ.
12521 			 */
12522 			start_cpu = lpfc_next_present_cpu(new_cpu);
12523 
12524 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12525 					"3337 Set Affinity: CPU %d "
12526 					"eq %d from peer cpu %d same "
12527 					"phys_id (%d)\n",
12528 					cpu, cpup->eq, new_cpu,
12529 					cpup->phys_id);
12530 		}
12531 	}
12532 
12533 	/* Set any unassigned cpu map entries to a IRQ on any phys_id */
12534 	start_cpu = first_cpu;
12535 
12536 	for_each_present_cpu(cpu) {
12537 		cpup = &phba->sli4_hba.cpu_map[cpu];
12538 
12539 		/* Is this entry unassigned */
12540 		if (cpup->eq == LPFC_VECTOR_MAP_EMPTY) {
12541 			/* Mark it as IRQ not assigned by the kernel */
12542 			cpup->flag |= LPFC_CPU_MAP_UNASSIGN;
12543 
12544 			/* If so, find a new_cpup thats on ANY phys_id
12545 			 * as the cpup. start_cpu will start where we
12546 			 * left off so all unassigned entries don't get
12547 			 * assigned the IRQ of the first entry.
12548 			 */
12549 			new_cpu = start_cpu;
12550 			for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12551 				new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12552 				if (!(new_cpup->flag & LPFC_CPU_MAP_UNASSIGN) &&
12553 				    (new_cpup->eq != LPFC_VECTOR_MAP_EMPTY))
12554 					goto found_any;
12555 				new_cpu = lpfc_next_present_cpu(new_cpu);
12556 			}
12557 			/* We should never leave an entry unassigned */
12558 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12559 					"3339 Set Affinity: CPU %d "
12560 					"eq %d UNASSIGNED\n",
12561 					cpup->hdwq, cpup->eq);
12562 			continue;
12563 found_any:
12564 			/* We found an available entry, copy the IRQ info */
12565 			cpup->eq = new_cpup->eq;
12566 
12567 			/* Bump start_cpu to the next slot to minmize the
12568 			 * chance of having multiple unassigned CPU entries
12569 			 * selecting the same IRQ.
12570 			 */
12571 			start_cpu = lpfc_next_present_cpu(new_cpu);
12572 
12573 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12574 					"3338 Set Affinity: CPU %d "
12575 					"eq %d from peer cpu %d (%d/%d)\n",
12576 					cpu, cpup->eq, new_cpu,
12577 					new_cpup->phys_id, new_cpup->core_id);
12578 		}
12579 	}
12580 
12581 	/* Assign hdwq indices that are unique across all cpus in the map
12582 	 * that are also FIRST_CPUs.
12583 	 */
12584 	idx = 0;
12585 	for_each_present_cpu(cpu) {
12586 		cpup = &phba->sli4_hba.cpu_map[cpu];
12587 
12588 		/* Only FIRST IRQs get a hdwq index assignment. */
12589 		if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
12590 			continue;
12591 
12592 		/* 1 to 1, the first LPFC_CPU_FIRST_IRQ cpus to a unique hdwq */
12593 		cpup->hdwq = idx;
12594 		idx++;
12595 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12596 				"3333 Set Affinity: CPU %d (phys %d core %d): "
12597 				"hdwq %d eq %d flg x%x\n",
12598 				cpu, cpup->phys_id, cpup->core_id,
12599 				cpup->hdwq, cpup->eq, cpup->flag);
12600 	}
12601 	/* Associate a hdwq with each cpu_map entry
12602 	 * This will be 1 to 1 - hdwq to cpu, unless there are less
12603 	 * hardware queues then CPUs. For that case we will just round-robin
12604 	 * the available hardware queues as they get assigned to CPUs.
12605 	 * The next_idx is the idx from the FIRST_CPU loop above to account
12606 	 * for irq_chann < hdwq.  The idx is used for round-robin assignments
12607 	 * and needs to start at 0.
12608 	 */
12609 	next_idx = idx;
12610 	start_cpu = 0;
12611 	idx = 0;
12612 	for_each_present_cpu(cpu) {
12613 		cpup = &phba->sli4_hba.cpu_map[cpu];
12614 
12615 		/* FIRST cpus are already mapped. */
12616 		if (cpup->flag & LPFC_CPU_FIRST_IRQ)
12617 			continue;
12618 
12619 		/* If the cfg_irq_chann < cfg_hdw_queue, set the hdwq
12620 		 * of the unassigned cpus to the next idx so that all
12621 		 * hdw queues are fully utilized.
12622 		 */
12623 		if (next_idx < phba->cfg_hdw_queue) {
12624 			cpup->hdwq = next_idx;
12625 			next_idx++;
12626 			continue;
12627 		}
12628 
12629 		/* Not a First CPU and all hdw_queues are used.  Reuse a
12630 		 * Hardware Queue for another CPU, so be smart about it
12631 		 * and pick one that has its IRQ/EQ mapped to the same phys_id
12632 		 * (CPU package) and core_id.
12633 		 */
12634 		new_cpu = start_cpu;
12635 		for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12636 			new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12637 			if (new_cpup->hdwq != LPFC_VECTOR_MAP_EMPTY &&
12638 			    new_cpup->phys_id == cpup->phys_id &&
12639 			    new_cpup->core_id == cpup->core_id) {
12640 				goto found_hdwq;
12641 			}
12642 			new_cpu = lpfc_next_present_cpu(new_cpu);
12643 		}
12644 
12645 		/* If we can't match both phys_id and core_id,
12646 		 * settle for just a phys_id match.
12647 		 */
12648 		new_cpu = start_cpu;
12649 		for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12650 			new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12651 			if (new_cpup->hdwq != LPFC_VECTOR_MAP_EMPTY &&
12652 			    new_cpup->phys_id == cpup->phys_id)
12653 				goto found_hdwq;
12654 			new_cpu = lpfc_next_present_cpu(new_cpu);
12655 		}
12656 
12657 		/* Otherwise just round robin on cfg_hdw_queue */
12658 		cpup->hdwq = idx % phba->cfg_hdw_queue;
12659 		idx++;
12660 		goto logit;
12661  found_hdwq:
12662 		/* We found an available entry, copy the IRQ info */
12663 		start_cpu = lpfc_next_present_cpu(new_cpu);
12664 		cpup->hdwq = new_cpup->hdwq;
12665  logit:
12666 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12667 				"3335 Set Affinity: CPU %d (phys %d core %d): "
12668 				"hdwq %d eq %d flg x%x\n",
12669 				cpu, cpup->phys_id, cpup->core_id,
12670 				cpup->hdwq, cpup->eq, cpup->flag);
12671 	}
12672 
12673 	/*
12674 	 * Initialize the cpu_map slots for not-present cpus in case
12675 	 * a cpu is hot-added. Perform a simple hdwq round robin assignment.
12676 	 */
12677 	idx = 0;
12678 	for_each_possible_cpu(cpu) {
12679 		cpup = &phba->sli4_hba.cpu_map[cpu];
12680 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
12681 		c_stat = per_cpu_ptr(phba->sli4_hba.c_stat, cpu);
12682 		c_stat->hdwq_no = cpup->hdwq;
12683 #endif
12684 		if (cpup->hdwq != LPFC_VECTOR_MAP_EMPTY)
12685 			continue;
12686 
12687 		cpup->hdwq = idx++ % phba->cfg_hdw_queue;
12688 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
12689 		c_stat->hdwq_no = cpup->hdwq;
12690 #endif
12691 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12692 				"3340 Set Affinity: not present "
12693 				"CPU %d hdwq %d\n",
12694 				cpu, cpup->hdwq);
12695 	}
12696 
12697 	/* The cpu_map array will be used later during initialization
12698 	 * when EQ / CQ / WQs are allocated and configured.
12699 	 */
12700 	return;
12701 }
12702 
12703 /**
12704  * lpfc_cpuhp_get_eq
12705  *
12706  * @phba:   pointer to lpfc hba data structure.
12707  * @cpu:    cpu going offline
12708  * @eqlist: eq list to append to
12709  */
12710 static int
12711 lpfc_cpuhp_get_eq(struct lpfc_hba *phba, unsigned int cpu,
12712 		  struct list_head *eqlist)
12713 {
12714 	const struct cpumask *maskp;
12715 	struct lpfc_queue *eq;
12716 	struct cpumask *tmp;
12717 	u16 idx;
12718 
12719 	tmp = kzalloc(cpumask_size(), GFP_KERNEL);
12720 	if (!tmp)
12721 		return -ENOMEM;
12722 
12723 	for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
12724 		maskp = pci_irq_get_affinity(phba->pcidev, idx);
12725 		if (!maskp)
12726 			continue;
12727 		/*
12728 		 * if irq is not affinitized to the cpu going
12729 		 * then we don't need to poll the eq attached
12730 		 * to it.
12731 		 */
12732 		if (!cpumask_and(tmp, maskp, cpumask_of(cpu)))
12733 			continue;
12734 		/* get the cpus that are online and are affini-
12735 		 * tized to this irq vector.  If the count is
12736 		 * more than 1 then cpuhp is not going to shut-
12737 		 * down this vector.  Since this cpu has not
12738 		 * gone offline yet, we need >1.
12739 		 */
12740 		cpumask_and(tmp, maskp, cpu_online_mask);
12741 		if (cpumask_weight(tmp) > 1)
12742 			continue;
12743 
12744 		/* Now that we have an irq to shutdown, get the eq
12745 		 * mapped to this irq.  Note: multiple hdwq's in
12746 		 * the software can share an eq, but eventually
12747 		 * only eq will be mapped to this vector
12748 		 */
12749 		eq = phba->sli4_hba.hba_eq_hdl[idx].eq;
12750 		list_add(&eq->_poll_list, eqlist);
12751 	}
12752 	kfree(tmp);
12753 	return 0;
12754 }
12755 
12756 static void __lpfc_cpuhp_remove(struct lpfc_hba *phba)
12757 {
12758 	if (phba->sli_rev != LPFC_SLI_REV4)
12759 		return;
12760 
12761 	cpuhp_state_remove_instance_nocalls(lpfc_cpuhp_state,
12762 					    &phba->cpuhp);
12763 	/*
12764 	 * unregistering the instance doesn't stop the polling
12765 	 * timer. Wait for the poll timer to retire.
12766 	 */
12767 	synchronize_rcu();
12768 	del_timer_sync(&phba->cpuhp_poll_timer);
12769 }
12770 
12771 static void lpfc_cpuhp_remove(struct lpfc_hba *phba)
12772 {
12773 	if (phba->pport &&
12774 	    test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag))
12775 		return;
12776 
12777 	__lpfc_cpuhp_remove(phba);
12778 }
12779 
12780 static void lpfc_cpuhp_add(struct lpfc_hba *phba)
12781 {
12782 	if (phba->sli_rev != LPFC_SLI_REV4)
12783 		return;
12784 
12785 	rcu_read_lock();
12786 
12787 	if (!list_empty(&phba->poll_list))
12788 		mod_timer(&phba->cpuhp_poll_timer,
12789 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
12790 
12791 	rcu_read_unlock();
12792 
12793 	cpuhp_state_add_instance_nocalls(lpfc_cpuhp_state,
12794 					 &phba->cpuhp);
12795 }
12796 
12797 static int __lpfc_cpuhp_checks(struct lpfc_hba *phba, int *retval)
12798 {
12799 	if (test_bit(FC_UNLOADING, &phba->pport->load_flag)) {
12800 		*retval = -EAGAIN;
12801 		return true;
12802 	}
12803 
12804 	if (phba->sli_rev != LPFC_SLI_REV4) {
12805 		*retval = 0;
12806 		return true;
12807 	}
12808 
12809 	/* proceed with the hotplug */
12810 	return false;
12811 }
12812 
12813 /**
12814  * lpfc_irq_set_aff - set IRQ affinity
12815  * @eqhdl: EQ handle
12816  * @cpu: cpu to set affinity
12817  *
12818  **/
12819 static inline void
12820 lpfc_irq_set_aff(struct lpfc_hba_eq_hdl *eqhdl, unsigned int cpu)
12821 {
12822 	cpumask_clear(&eqhdl->aff_mask);
12823 	cpumask_set_cpu(cpu, &eqhdl->aff_mask);
12824 	irq_set_status_flags(eqhdl->irq, IRQ_NO_BALANCING);
12825 	irq_set_affinity(eqhdl->irq, &eqhdl->aff_mask);
12826 }
12827 
12828 /**
12829  * lpfc_irq_clear_aff - clear IRQ affinity
12830  * @eqhdl: EQ handle
12831  *
12832  **/
12833 static inline void
12834 lpfc_irq_clear_aff(struct lpfc_hba_eq_hdl *eqhdl)
12835 {
12836 	cpumask_clear(&eqhdl->aff_mask);
12837 	irq_clear_status_flags(eqhdl->irq, IRQ_NO_BALANCING);
12838 }
12839 
12840 /**
12841  * lpfc_irq_rebalance - rebalances IRQ affinity according to cpuhp event
12842  * @phba: pointer to HBA context object.
12843  * @cpu: cpu going offline/online
12844  * @offline: true, cpu is going offline. false, cpu is coming online.
12845  *
12846  * If cpu is going offline, we'll try our best effort to find the next
12847  * online cpu on the phba's original_mask and migrate all offlining IRQ
12848  * affinities.
12849  *
12850  * If cpu is coming online, reaffinitize the IRQ back to the onlining cpu.
12851  *
12852  * Note: Call only if NUMA or NHT mode is enabled, otherwise rely on
12853  *	 PCI_IRQ_AFFINITY to auto-manage IRQ affinity.
12854  *
12855  **/
12856 static void
12857 lpfc_irq_rebalance(struct lpfc_hba *phba, unsigned int cpu, bool offline)
12858 {
12859 	struct lpfc_vector_map_info *cpup;
12860 	struct cpumask *aff_mask;
12861 	unsigned int cpu_select, cpu_next, idx;
12862 	const struct cpumask *orig_mask;
12863 
12864 	if (phba->irq_chann_mode == NORMAL_MODE)
12865 		return;
12866 
12867 	orig_mask = &phba->sli4_hba.irq_aff_mask;
12868 
12869 	if (!cpumask_test_cpu(cpu, orig_mask))
12870 		return;
12871 
12872 	cpup = &phba->sli4_hba.cpu_map[cpu];
12873 
12874 	if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
12875 		return;
12876 
12877 	if (offline) {
12878 		/* Find next online CPU on original mask */
12879 		cpu_next = cpumask_next_wrap(cpu, orig_mask, cpu, true);
12880 		cpu_select = lpfc_next_online_cpu(orig_mask, cpu_next);
12881 
12882 		/* Found a valid CPU */
12883 		if ((cpu_select < nr_cpu_ids) && (cpu_select != cpu)) {
12884 			/* Go through each eqhdl and ensure offlining
12885 			 * cpu aff_mask is migrated
12886 			 */
12887 			for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
12888 				aff_mask = lpfc_get_aff_mask(idx);
12889 
12890 				/* Migrate affinity */
12891 				if (cpumask_test_cpu(cpu, aff_mask))
12892 					lpfc_irq_set_aff(lpfc_get_eq_hdl(idx),
12893 							 cpu_select);
12894 			}
12895 		} else {
12896 			/* Rely on irqbalance if no online CPUs left on NUMA */
12897 			for (idx = 0; idx < phba->cfg_irq_chann; idx++)
12898 				lpfc_irq_clear_aff(lpfc_get_eq_hdl(idx));
12899 		}
12900 	} else {
12901 		/* Migrate affinity back to this CPU */
12902 		lpfc_irq_set_aff(lpfc_get_eq_hdl(cpup->eq), cpu);
12903 	}
12904 }
12905 
12906 static int lpfc_cpu_offline(unsigned int cpu, struct hlist_node *node)
12907 {
12908 	struct lpfc_hba *phba = hlist_entry_safe(node, struct lpfc_hba, cpuhp);
12909 	struct lpfc_queue *eq, *next;
12910 	LIST_HEAD(eqlist);
12911 	int retval;
12912 
12913 	if (!phba) {
12914 		WARN_ONCE(!phba, "cpu: %u. phba:NULL", raw_smp_processor_id());
12915 		return 0;
12916 	}
12917 
12918 	if (__lpfc_cpuhp_checks(phba, &retval))
12919 		return retval;
12920 
12921 	lpfc_irq_rebalance(phba, cpu, true);
12922 
12923 	retval = lpfc_cpuhp_get_eq(phba, cpu, &eqlist);
12924 	if (retval)
12925 		return retval;
12926 
12927 	/* start polling on these eq's */
12928 	list_for_each_entry_safe(eq, next, &eqlist, _poll_list) {
12929 		list_del_init(&eq->_poll_list);
12930 		lpfc_sli4_start_polling(eq);
12931 	}
12932 
12933 	return 0;
12934 }
12935 
12936 static int lpfc_cpu_online(unsigned int cpu, struct hlist_node *node)
12937 {
12938 	struct lpfc_hba *phba = hlist_entry_safe(node, struct lpfc_hba, cpuhp);
12939 	struct lpfc_queue *eq, *next;
12940 	unsigned int n;
12941 	int retval;
12942 
12943 	if (!phba) {
12944 		WARN_ONCE(!phba, "cpu: %u. phba:NULL", raw_smp_processor_id());
12945 		return 0;
12946 	}
12947 
12948 	if (__lpfc_cpuhp_checks(phba, &retval))
12949 		return retval;
12950 
12951 	lpfc_irq_rebalance(phba, cpu, false);
12952 
12953 	list_for_each_entry_safe(eq, next, &phba->poll_list, _poll_list) {
12954 		n = lpfc_find_cpu_handle(phba, eq->hdwq, LPFC_FIND_BY_HDWQ);
12955 		if (n == cpu)
12956 			lpfc_sli4_stop_polling(eq);
12957 	}
12958 
12959 	return 0;
12960 }
12961 
12962 /**
12963  * lpfc_sli4_enable_msix - Enable MSI-X interrupt mode to SLI-4 device
12964  * @phba: pointer to lpfc hba data structure.
12965  *
12966  * This routine is invoked to enable the MSI-X interrupt vectors to device
12967  * with SLI-4 interface spec.  It also allocates MSI-X vectors and maps them
12968  * to cpus on the system.
12969  *
12970  * When cfg_irq_numa is enabled, the adapter will only allocate vectors for
12971  * the number of cpus on the same numa node as this adapter.  The vectors are
12972  * allocated without requesting OS affinity mapping.  A vector will be
12973  * allocated and assigned to each online and offline cpu.  If the cpu is
12974  * online, then affinity will be set to that cpu.  If the cpu is offline, then
12975  * affinity will be set to the nearest peer cpu within the numa node that is
12976  * online.  If there are no online cpus within the numa node, affinity is not
12977  * assigned and the OS may do as it pleases. Note: cpu vector affinity mapping
12978  * is consistent with the way cpu online/offline is handled when cfg_irq_numa is
12979  * configured.
12980  *
12981  * If numa mode is not enabled and there is more than 1 vector allocated, then
12982  * the driver relies on the managed irq interface where the OS assigns vector to
12983  * cpu affinity.  The driver will then use that affinity mapping to setup its
12984  * cpu mapping table.
12985  *
12986  * Return codes
12987  * 0 - successful
12988  * other values - error
12989  **/
12990 static int
12991 lpfc_sli4_enable_msix(struct lpfc_hba *phba)
12992 {
12993 	int vectors, rc, index;
12994 	char *name;
12995 	const struct cpumask *aff_mask = NULL;
12996 	unsigned int cpu = 0, cpu_cnt = 0, cpu_select = nr_cpu_ids;
12997 	struct lpfc_vector_map_info *cpup;
12998 	struct lpfc_hba_eq_hdl *eqhdl;
12999 	const struct cpumask *maskp;
13000 	unsigned int flags = PCI_IRQ_MSIX;
13001 
13002 	/* Set up MSI-X multi-message vectors */
13003 	vectors = phba->cfg_irq_chann;
13004 
13005 	if (phba->irq_chann_mode != NORMAL_MODE)
13006 		aff_mask = &phba->sli4_hba.irq_aff_mask;
13007 
13008 	if (aff_mask) {
13009 		cpu_cnt = cpumask_weight(aff_mask);
13010 		vectors = min(phba->cfg_irq_chann, cpu_cnt);
13011 
13012 		/* cpu: iterates over aff_mask including offline or online
13013 		 * cpu_select: iterates over online aff_mask to set affinity
13014 		 */
13015 		cpu = cpumask_first(aff_mask);
13016 		cpu_select = lpfc_next_online_cpu(aff_mask, cpu);
13017 	} else {
13018 		flags |= PCI_IRQ_AFFINITY;
13019 	}
13020 
13021 	rc = pci_alloc_irq_vectors(phba->pcidev, 1, vectors, flags);
13022 	if (rc < 0) {
13023 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13024 				"0484 PCI enable MSI-X failed (%d)\n", rc);
13025 		goto vec_fail_out;
13026 	}
13027 	vectors = rc;
13028 
13029 	/* Assign MSI-X vectors to interrupt handlers */
13030 	for (index = 0; index < vectors; index++) {
13031 		eqhdl = lpfc_get_eq_hdl(index);
13032 		name = eqhdl->handler_name;
13033 		memset(name, 0, LPFC_SLI4_HANDLER_NAME_SZ);
13034 		snprintf(name, LPFC_SLI4_HANDLER_NAME_SZ,
13035 			 LPFC_DRIVER_HANDLER_NAME"%d", index);
13036 
13037 		eqhdl->idx = index;
13038 		rc = pci_irq_vector(phba->pcidev, index);
13039 		if (rc < 0) {
13040 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13041 					"0489 MSI-X fast-path (%d) "
13042 					"pci_irq_vec failed (%d)\n", index, rc);
13043 			goto cfg_fail_out;
13044 		}
13045 		eqhdl->irq = rc;
13046 
13047 		rc = request_threaded_irq(eqhdl->irq,
13048 					  &lpfc_sli4_hba_intr_handler,
13049 					  &lpfc_sli4_hba_intr_handler_th,
13050 					  0, name, eqhdl);
13051 		if (rc) {
13052 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13053 					"0486 MSI-X fast-path (%d) "
13054 					"request_irq failed (%d)\n", index, rc);
13055 			goto cfg_fail_out;
13056 		}
13057 
13058 		if (aff_mask) {
13059 			/* If found a neighboring online cpu, set affinity */
13060 			if (cpu_select < nr_cpu_ids)
13061 				lpfc_irq_set_aff(eqhdl, cpu_select);
13062 
13063 			/* Assign EQ to cpu_map */
13064 			lpfc_assign_eq_map_info(phba, index,
13065 						LPFC_CPU_FIRST_IRQ,
13066 						cpu);
13067 
13068 			/* Iterate to next offline or online cpu in aff_mask */
13069 			cpu = cpumask_next(cpu, aff_mask);
13070 
13071 			/* Find next online cpu in aff_mask to set affinity */
13072 			cpu_select = lpfc_next_online_cpu(aff_mask, cpu);
13073 		} else if (vectors == 1) {
13074 			cpu = cpumask_first(cpu_present_mask);
13075 			lpfc_assign_eq_map_info(phba, index, LPFC_CPU_FIRST_IRQ,
13076 						cpu);
13077 		} else {
13078 			maskp = pci_irq_get_affinity(phba->pcidev, index);
13079 
13080 			/* Loop through all CPUs associated with vector index */
13081 			for_each_cpu_and(cpu, maskp, cpu_present_mask) {
13082 				cpup = &phba->sli4_hba.cpu_map[cpu];
13083 
13084 				/* If this is the first CPU thats assigned to
13085 				 * this vector, set LPFC_CPU_FIRST_IRQ.
13086 				 *
13087 				 * With certain platforms its possible that irq
13088 				 * vectors are affinitized to all the cpu's.
13089 				 * This can result in each cpu_map.eq to be set
13090 				 * to the last vector, resulting in overwrite
13091 				 * of all the previous cpu_map.eq.  Ensure that
13092 				 * each vector receives a place in cpu_map.
13093 				 * Later call to lpfc_cpu_affinity_check will
13094 				 * ensure we are nicely balanced out.
13095 				 */
13096 				if (cpup->eq != LPFC_VECTOR_MAP_EMPTY)
13097 					continue;
13098 				lpfc_assign_eq_map_info(phba, index,
13099 							LPFC_CPU_FIRST_IRQ,
13100 							cpu);
13101 				break;
13102 			}
13103 		}
13104 	}
13105 
13106 	if (vectors != phba->cfg_irq_chann) {
13107 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13108 				"3238 Reducing IO channels to match number of "
13109 				"MSI-X vectors, requested %d got %d\n",
13110 				phba->cfg_irq_chann, vectors);
13111 		if (phba->cfg_irq_chann > vectors)
13112 			phba->cfg_irq_chann = vectors;
13113 	}
13114 
13115 	return rc;
13116 
13117 cfg_fail_out:
13118 	/* free the irq already requested */
13119 	for (--index; index >= 0; index--) {
13120 		eqhdl = lpfc_get_eq_hdl(index);
13121 		lpfc_irq_clear_aff(eqhdl);
13122 		free_irq(eqhdl->irq, eqhdl);
13123 	}
13124 
13125 	/* Unconfigure MSI-X capability structure */
13126 	pci_free_irq_vectors(phba->pcidev);
13127 
13128 vec_fail_out:
13129 	return rc;
13130 }
13131 
13132 /**
13133  * lpfc_sli4_enable_msi - Enable MSI interrupt mode to SLI-4 device
13134  * @phba: pointer to lpfc hba data structure.
13135  *
13136  * This routine is invoked to enable the MSI interrupt mode to device with
13137  * SLI-4 interface spec. The kernel function pci_alloc_irq_vectors() is
13138  * called to enable the MSI vector. The device driver is responsible for
13139  * calling the request_irq() to register MSI vector with a interrupt the
13140  * handler, which is done in this function.
13141  *
13142  * Return codes
13143  * 	0 - successful
13144  * 	other values - error
13145  **/
13146 static int
13147 lpfc_sli4_enable_msi(struct lpfc_hba *phba)
13148 {
13149 	int rc, index;
13150 	unsigned int cpu;
13151 	struct lpfc_hba_eq_hdl *eqhdl;
13152 
13153 	rc = pci_alloc_irq_vectors(phba->pcidev, 1, 1,
13154 				   PCI_IRQ_MSI | PCI_IRQ_AFFINITY);
13155 	if (rc > 0)
13156 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13157 				"0487 PCI enable MSI mode success.\n");
13158 	else {
13159 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13160 				"0488 PCI enable MSI mode failed (%d)\n", rc);
13161 		return rc ? rc : -1;
13162 	}
13163 
13164 	rc = request_irq(phba->pcidev->irq, lpfc_sli4_intr_handler,
13165 			 0, LPFC_DRIVER_NAME, phba);
13166 	if (rc) {
13167 		pci_free_irq_vectors(phba->pcidev);
13168 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13169 				"0490 MSI request_irq failed (%d)\n", rc);
13170 		return rc;
13171 	}
13172 
13173 	eqhdl = lpfc_get_eq_hdl(0);
13174 	rc = pci_irq_vector(phba->pcidev, 0);
13175 	if (rc < 0) {
13176 		pci_free_irq_vectors(phba->pcidev);
13177 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13178 				"0496 MSI pci_irq_vec failed (%d)\n", rc);
13179 		return rc;
13180 	}
13181 	eqhdl->irq = rc;
13182 
13183 	cpu = cpumask_first(cpu_present_mask);
13184 	lpfc_assign_eq_map_info(phba, 0, LPFC_CPU_FIRST_IRQ, cpu);
13185 
13186 	for (index = 0; index < phba->cfg_irq_chann; index++) {
13187 		eqhdl = lpfc_get_eq_hdl(index);
13188 		eqhdl->idx = index;
13189 	}
13190 
13191 	return 0;
13192 }
13193 
13194 /**
13195  * lpfc_sli4_enable_intr - Enable device interrupt to SLI-4 device
13196  * @phba: pointer to lpfc hba data structure.
13197  * @cfg_mode: Interrupt configuration mode (INTx, MSI or MSI-X).
13198  *
13199  * This routine is invoked to enable device interrupt and associate driver's
13200  * interrupt handler(s) to interrupt vector(s) to device with SLI-4
13201  * interface spec. Depends on the interrupt mode configured to the driver,
13202  * the driver will try to fallback from the configured interrupt mode to an
13203  * interrupt mode which is supported by the platform, kernel, and device in
13204  * the order of:
13205  * MSI-X -> MSI -> IRQ.
13206  *
13207  * Return codes
13208  *	Interrupt mode (2, 1, 0) - successful
13209  *	LPFC_INTR_ERROR - error
13210  **/
13211 static uint32_t
13212 lpfc_sli4_enable_intr(struct lpfc_hba *phba, uint32_t cfg_mode)
13213 {
13214 	uint32_t intr_mode = LPFC_INTR_ERROR;
13215 	int retval, idx;
13216 
13217 	if (cfg_mode == 2) {
13218 		/* Preparation before conf_msi mbox cmd */
13219 		retval = 0;
13220 		if (!retval) {
13221 			/* Now, try to enable MSI-X interrupt mode */
13222 			retval = lpfc_sli4_enable_msix(phba);
13223 			if (!retval) {
13224 				/* Indicate initialization to MSI-X mode */
13225 				phba->intr_type = MSIX;
13226 				intr_mode = 2;
13227 			}
13228 		}
13229 	}
13230 
13231 	/* Fallback to MSI if MSI-X initialization failed */
13232 	if (cfg_mode >= 1 && phba->intr_type == NONE) {
13233 		retval = lpfc_sli4_enable_msi(phba);
13234 		if (!retval) {
13235 			/* Indicate initialization to MSI mode */
13236 			phba->intr_type = MSI;
13237 			intr_mode = 1;
13238 		}
13239 	}
13240 
13241 	/* Fallback to INTx if both MSI-X/MSI initalization failed */
13242 	if (phba->intr_type == NONE) {
13243 		retval = request_irq(phba->pcidev->irq, lpfc_sli4_intr_handler,
13244 				     IRQF_SHARED, LPFC_DRIVER_NAME, phba);
13245 		if (!retval) {
13246 			struct lpfc_hba_eq_hdl *eqhdl;
13247 			unsigned int cpu;
13248 
13249 			/* Indicate initialization to INTx mode */
13250 			phba->intr_type = INTx;
13251 			intr_mode = 0;
13252 
13253 			eqhdl = lpfc_get_eq_hdl(0);
13254 			retval = pci_irq_vector(phba->pcidev, 0);
13255 			if (retval < 0) {
13256 				lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13257 					"0502 INTR pci_irq_vec failed (%d)\n",
13258 					 retval);
13259 				return LPFC_INTR_ERROR;
13260 			}
13261 			eqhdl->irq = retval;
13262 
13263 			cpu = cpumask_first(cpu_present_mask);
13264 			lpfc_assign_eq_map_info(phba, 0, LPFC_CPU_FIRST_IRQ,
13265 						cpu);
13266 			for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
13267 				eqhdl = lpfc_get_eq_hdl(idx);
13268 				eqhdl->idx = idx;
13269 			}
13270 		}
13271 	}
13272 	return intr_mode;
13273 }
13274 
13275 /**
13276  * lpfc_sli4_disable_intr - Disable device interrupt to SLI-4 device
13277  * @phba: pointer to lpfc hba data structure.
13278  *
13279  * This routine is invoked to disable device interrupt and disassociate
13280  * the driver's interrupt handler(s) from interrupt vector(s) to device
13281  * with SLI-4 interface spec. Depending on the interrupt mode, the driver
13282  * will release the interrupt vector(s) for the message signaled interrupt.
13283  **/
13284 static void
13285 lpfc_sli4_disable_intr(struct lpfc_hba *phba)
13286 {
13287 	/* Disable the currently initialized interrupt mode */
13288 	if (phba->intr_type == MSIX) {
13289 		int index;
13290 		struct lpfc_hba_eq_hdl *eqhdl;
13291 
13292 		/* Free up MSI-X multi-message vectors */
13293 		for (index = 0; index < phba->cfg_irq_chann; index++) {
13294 			eqhdl = lpfc_get_eq_hdl(index);
13295 			lpfc_irq_clear_aff(eqhdl);
13296 			free_irq(eqhdl->irq, eqhdl);
13297 		}
13298 	} else {
13299 		free_irq(phba->pcidev->irq, phba);
13300 	}
13301 
13302 	pci_free_irq_vectors(phba->pcidev);
13303 
13304 	/* Reset interrupt management states */
13305 	phba->intr_type = NONE;
13306 	phba->sli.slistat.sli_intr = 0;
13307 }
13308 
13309 /**
13310  * lpfc_unset_hba - Unset SLI3 hba device initialization
13311  * @phba: pointer to lpfc hba data structure.
13312  *
13313  * This routine is invoked to unset the HBA device initialization steps to
13314  * a device with SLI-3 interface spec.
13315  **/
13316 static void
13317 lpfc_unset_hba(struct lpfc_hba *phba)
13318 {
13319 	set_bit(FC_UNLOADING, &phba->pport->load_flag);
13320 
13321 	kfree(phba->vpi_bmask);
13322 	kfree(phba->vpi_ids);
13323 
13324 	lpfc_stop_hba_timers(phba);
13325 
13326 	phba->pport->work_port_events = 0;
13327 
13328 	lpfc_sli_hba_down(phba);
13329 
13330 	lpfc_sli_brdrestart(phba);
13331 
13332 	lpfc_sli_disable_intr(phba);
13333 
13334 	return;
13335 }
13336 
13337 /**
13338  * lpfc_sli4_xri_exchange_busy_wait - Wait for device XRI exchange busy
13339  * @phba: Pointer to HBA context object.
13340  *
13341  * This function is called in the SLI4 code path to wait for completion
13342  * of device's XRIs exchange busy. It will check the XRI exchange busy
13343  * on outstanding FCP and ELS I/Os every 10ms for up to 10 seconds; after
13344  * that, it will check the XRI exchange busy on outstanding FCP and ELS
13345  * I/Os every 30 seconds, log error message, and wait forever. Only when
13346  * all XRI exchange busy complete, the driver unload shall proceed with
13347  * invoking the function reset ioctl mailbox command to the CNA and the
13348  * the rest of the driver unload resource release.
13349  **/
13350 static void
13351 lpfc_sli4_xri_exchange_busy_wait(struct lpfc_hba *phba)
13352 {
13353 	struct lpfc_sli4_hdw_queue *qp;
13354 	int idx, ccnt;
13355 	int wait_time = 0;
13356 	int io_xri_cmpl = 1;
13357 	int nvmet_xri_cmpl = 1;
13358 	int els_xri_cmpl = list_empty(&phba->sli4_hba.lpfc_abts_els_sgl_list);
13359 
13360 	/* Driver just aborted IOs during the hba_unset process.  Pause
13361 	 * here to give the HBA time to complete the IO and get entries
13362 	 * into the abts lists.
13363 	 */
13364 	msleep(LPFC_XRI_EXCH_BUSY_WAIT_T1 * 5);
13365 
13366 	/* Wait for NVME pending IO to flush back to transport. */
13367 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
13368 		lpfc_nvme_wait_for_io_drain(phba);
13369 
13370 	ccnt = 0;
13371 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
13372 		qp = &phba->sli4_hba.hdwq[idx];
13373 		io_xri_cmpl = list_empty(&qp->lpfc_abts_io_buf_list);
13374 		if (!io_xri_cmpl) /* if list is NOT empty */
13375 			ccnt++;
13376 	}
13377 	if (ccnt)
13378 		io_xri_cmpl = 0;
13379 
13380 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13381 		nvmet_xri_cmpl =
13382 			list_empty(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
13383 	}
13384 
13385 	while (!els_xri_cmpl || !io_xri_cmpl || !nvmet_xri_cmpl) {
13386 		if (wait_time > LPFC_XRI_EXCH_BUSY_WAIT_TMO) {
13387 			if (!nvmet_xri_cmpl)
13388 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13389 						"6424 NVMET XRI exchange busy "
13390 						"wait time: %d seconds.\n",
13391 						wait_time/1000);
13392 			if (!io_xri_cmpl)
13393 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13394 						"6100 IO XRI exchange busy "
13395 						"wait time: %d seconds.\n",
13396 						wait_time/1000);
13397 			if (!els_xri_cmpl)
13398 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13399 						"2878 ELS XRI exchange busy "
13400 						"wait time: %d seconds.\n",
13401 						wait_time/1000);
13402 			msleep(LPFC_XRI_EXCH_BUSY_WAIT_T2);
13403 			wait_time += LPFC_XRI_EXCH_BUSY_WAIT_T2;
13404 		} else {
13405 			msleep(LPFC_XRI_EXCH_BUSY_WAIT_T1);
13406 			wait_time += LPFC_XRI_EXCH_BUSY_WAIT_T1;
13407 		}
13408 
13409 		ccnt = 0;
13410 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
13411 			qp = &phba->sli4_hba.hdwq[idx];
13412 			io_xri_cmpl = list_empty(
13413 			    &qp->lpfc_abts_io_buf_list);
13414 			if (!io_xri_cmpl) /* if list is NOT empty */
13415 				ccnt++;
13416 		}
13417 		if (ccnt)
13418 			io_xri_cmpl = 0;
13419 
13420 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13421 			nvmet_xri_cmpl = list_empty(
13422 				&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
13423 		}
13424 		els_xri_cmpl =
13425 			list_empty(&phba->sli4_hba.lpfc_abts_els_sgl_list);
13426 
13427 	}
13428 }
13429 
13430 /**
13431  * lpfc_sli4_hba_unset - Unset the fcoe hba
13432  * @phba: Pointer to HBA context object.
13433  *
13434  * This function is called in the SLI4 code path to reset the HBA's FCoE
13435  * function. The caller is not required to hold any lock. This routine
13436  * issues PCI function reset mailbox command to reset the FCoE function.
13437  * At the end of the function, it calls lpfc_hba_down_post function to
13438  * free any pending commands.
13439  **/
13440 static void
13441 lpfc_sli4_hba_unset(struct lpfc_hba *phba)
13442 {
13443 	int wait_cnt = 0;
13444 	LPFC_MBOXQ_t *mboxq;
13445 	struct pci_dev *pdev = phba->pcidev;
13446 
13447 	lpfc_stop_hba_timers(phba);
13448 	hrtimer_cancel(&phba->cmf_stats_timer);
13449 	hrtimer_cancel(&phba->cmf_timer);
13450 
13451 	if (phba->pport)
13452 		phba->sli4_hba.intr_enable = 0;
13453 
13454 	/*
13455 	 * Gracefully wait out the potential current outstanding asynchronous
13456 	 * mailbox command.
13457 	 */
13458 
13459 	/* First, block any pending async mailbox command from posted */
13460 	spin_lock_irq(&phba->hbalock);
13461 	phba->sli.sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
13462 	spin_unlock_irq(&phba->hbalock);
13463 	/* Now, trying to wait it out if we can */
13464 	while (phba->sli.sli_flag & LPFC_SLI_MBOX_ACTIVE) {
13465 		msleep(10);
13466 		if (++wait_cnt > LPFC_ACTIVE_MBOX_WAIT_CNT)
13467 			break;
13468 	}
13469 	/* Forcefully release the outstanding mailbox command if timed out */
13470 	if (phba->sli.sli_flag & LPFC_SLI_MBOX_ACTIVE) {
13471 		spin_lock_irq(&phba->hbalock);
13472 		mboxq = phba->sli.mbox_active;
13473 		mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
13474 		__lpfc_mbox_cmpl_put(phba, mboxq);
13475 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
13476 		phba->sli.mbox_active = NULL;
13477 		spin_unlock_irq(&phba->hbalock);
13478 	}
13479 
13480 	/* Abort all iocbs associated with the hba */
13481 	lpfc_sli_hba_iocb_abort(phba);
13482 
13483 	if (!pci_channel_offline(phba->pcidev))
13484 		/* Wait for completion of device XRI exchange busy */
13485 		lpfc_sli4_xri_exchange_busy_wait(phba);
13486 
13487 	/* per-phba callback de-registration for hotplug event */
13488 	if (phba->pport)
13489 		lpfc_cpuhp_remove(phba);
13490 
13491 	/* Disable PCI subsystem interrupt */
13492 	lpfc_sli4_disable_intr(phba);
13493 
13494 	/* Disable SR-IOV if enabled */
13495 	if (phba->cfg_sriov_nr_virtfn)
13496 		pci_disable_sriov(pdev);
13497 
13498 	/* Stop kthread signal shall trigger work_done one more time */
13499 	kthread_stop(phba->worker_thread);
13500 
13501 	/* Disable FW logging to host memory */
13502 	lpfc_ras_stop_fwlog(phba);
13503 
13504 	lpfc_sli4_queue_unset(phba);
13505 
13506 	/* Reset SLI4 HBA FCoE function */
13507 	lpfc_pci_function_reset(phba);
13508 
13509 	/* release all queue allocated resources. */
13510 	lpfc_sli4_queue_destroy(phba);
13511 
13512 	/* Free RAS DMA memory */
13513 	if (phba->ras_fwlog.ras_enabled)
13514 		lpfc_sli4_ras_dma_free(phba);
13515 
13516 	/* Stop the SLI4 device port */
13517 	if (phba->pport)
13518 		phba->pport->work_port_events = 0;
13519 }
13520 
13521 static uint32_t
13522 lpfc_cgn_crc32(uint32_t crc, u8 byte)
13523 {
13524 	uint32_t msb = 0;
13525 	uint32_t bit;
13526 
13527 	for (bit = 0; bit < 8; bit++) {
13528 		msb = (crc >> 31) & 1;
13529 		crc <<= 1;
13530 
13531 		if (msb ^ (byte & 1)) {
13532 			crc ^= LPFC_CGN_CRC32_MAGIC_NUMBER;
13533 			crc |= 1;
13534 		}
13535 		byte >>= 1;
13536 	}
13537 	return crc;
13538 }
13539 
13540 static uint32_t
13541 lpfc_cgn_reverse_bits(uint32_t wd)
13542 {
13543 	uint32_t result = 0;
13544 	uint32_t i;
13545 
13546 	for (i = 0; i < 32; i++) {
13547 		result <<= 1;
13548 		result |= (1 & (wd >> i));
13549 	}
13550 	return result;
13551 }
13552 
13553 /*
13554  * The routine corresponds with the algorithm the HBA firmware
13555  * uses to validate the data integrity.
13556  */
13557 uint32_t
13558 lpfc_cgn_calc_crc32(void *ptr, uint32_t byteLen, uint32_t crc)
13559 {
13560 	uint32_t  i;
13561 	uint32_t result;
13562 	uint8_t  *data = (uint8_t *)ptr;
13563 
13564 	for (i = 0; i < byteLen; ++i)
13565 		crc = lpfc_cgn_crc32(crc, data[i]);
13566 
13567 	result = ~lpfc_cgn_reverse_bits(crc);
13568 	return result;
13569 }
13570 
13571 void
13572 lpfc_init_congestion_buf(struct lpfc_hba *phba)
13573 {
13574 	struct lpfc_cgn_info *cp;
13575 	uint16_t size;
13576 	uint32_t crc;
13577 
13578 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
13579 			"6235 INIT Congestion Buffer %p\n", phba->cgn_i);
13580 
13581 	if (!phba->cgn_i)
13582 		return;
13583 	cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
13584 
13585 	atomic_set(&phba->cgn_fabric_warn_cnt, 0);
13586 	atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
13587 	atomic_set(&phba->cgn_sync_alarm_cnt, 0);
13588 	atomic_set(&phba->cgn_sync_warn_cnt, 0);
13589 
13590 	atomic_set(&phba->cgn_driver_evt_cnt, 0);
13591 	atomic_set(&phba->cgn_latency_evt_cnt, 0);
13592 	atomic64_set(&phba->cgn_latency_evt, 0);
13593 	phba->cgn_evt_minute = 0;
13594 
13595 	memset(cp, 0xff, offsetof(struct lpfc_cgn_info, cgn_stat));
13596 	cp->cgn_info_size = cpu_to_le16(LPFC_CGN_INFO_SZ);
13597 	cp->cgn_info_version = LPFC_CGN_INFO_V4;
13598 
13599 	/* cgn parameters */
13600 	cp->cgn_info_mode = phba->cgn_p.cgn_param_mode;
13601 	cp->cgn_info_level0 = phba->cgn_p.cgn_param_level0;
13602 	cp->cgn_info_level1 = phba->cgn_p.cgn_param_level1;
13603 	cp->cgn_info_level2 = phba->cgn_p.cgn_param_level2;
13604 
13605 	lpfc_cgn_update_tstamp(phba, &cp->base_time);
13606 
13607 	/* Fill in default LUN qdepth */
13608 	if (phba->pport) {
13609 		size = (uint16_t)(phba->pport->cfg_lun_queue_depth);
13610 		cp->cgn_lunq = cpu_to_le16(size);
13611 	}
13612 
13613 	/* last used Index initialized to 0xff already */
13614 
13615 	cp->cgn_warn_freq = cpu_to_le16(LPFC_FPIN_INIT_FREQ);
13616 	cp->cgn_alarm_freq = cpu_to_le16(LPFC_FPIN_INIT_FREQ);
13617 	crc = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ, LPFC_CGN_CRC32_SEED);
13618 	cp->cgn_info_crc = cpu_to_le32(crc);
13619 
13620 	phba->cgn_evt_timestamp = jiffies +
13621 		msecs_to_jiffies(LPFC_CGN_TIMER_TO_MIN);
13622 }
13623 
13624 void
13625 lpfc_init_congestion_stat(struct lpfc_hba *phba)
13626 {
13627 	struct lpfc_cgn_info *cp;
13628 	uint32_t crc;
13629 
13630 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
13631 			"6236 INIT Congestion Stat %p\n", phba->cgn_i);
13632 
13633 	if (!phba->cgn_i)
13634 		return;
13635 
13636 	cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
13637 	memset(&cp->cgn_stat, 0, sizeof(cp->cgn_stat));
13638 
13639 	lpfc_cgn_update_tstamp(phba, &cp->stat_start);
13640 	crc = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ, LPFC_CGN_CRC32_SEED);
13641 	cp->cgn_info_crc = cpu_to_le32(crc);
13642 }
13643 
13644 /**
13645  * __lpfc_reg_congestion_buf - register congestion info buffer with HBA
13646  * @phba: Pointer to hba context object.
13647  * @reg: flag to determine register or unregister.
13648  */
13649 static int
13650 __lpfc_reg_congestion_buf(struct lpfc_hba *phba, int reg)
13651 {
13652 	struct lpfc_mbx_reg_congestion_buf *reg_congestion_buf;
13653 	union  lpfc_sli4_cfg_shdr *shdr;
13654 	uint32_t shdr_status, shdr_add_status;
13655 	LPFC_MBOXQ_t *mboxq;
13656 	int length, rc;
13657 
13658 	if (!phba->cgn_i)
13659 		return -ENXIO;
13660 
13661 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
13662 	if (!mboxq) {
13663 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX,
13664 				"2641 REG_CONGESTION_BUF mbox allocation fail: "
13665 				"HBA state x%x reg %d\n",
13666 				phba->pport->port_state, reg);
13667 		return -ENOMEM;
13668 	}
13669 
13670 	length = (sizeof(struct lpfc_mbx_reg_congestion_buf) -
13671 		sizeof(struct lpfc_sli4_cfg_mhdr));
13672 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
13673 			 LPFC_MBOX_OPCODE_REG_CONGESTION_BUF, length,
13674 			 LPFC_SLI4_MBX_EMBED);
13675 	reg_congestion_buf = &mboxq->u.mqe.un.reg_congestion_buf;
13676 	bf_set(lpfc_mbx_reg_cgn_buf_type, reg_congestion_buf, 1);
13677 	if (reg > 0)
13678 		bf_set(lpfc_mbx_reg_cgn_buf_cnt, reg_congestion_buf, 1);
13679 	else
13680 		bf_set(lpfc_mbx_reg_cgn_buf_cnt, reg_congestion_buf, 0);
13681 	reg_congestion_buf->length = sizeof(struct lpfc_cgn_info);
13682 	reg_congestion_buf->addr_lo =
13683 		putPaddrLow(phba->cgn_i->phys);
13684 	reg_congestion_buf->addr_hi =
13685 		putPaddrHigh(phba->cgn_i->phys);
13686 
13687 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
13688 	shdr = (union lpfc_sli4_cfg_shdr *)
13689 		&mboxq->u.mqe.un.sli4_config.header.cfg_shdr;
13690 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13691 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
13692 				 &shdr->response);
13693 	mempool_free(mboxq, phba->mbox_mem_pool);
13694 	if (shdr_status || shdr_add_status || rc) {
13695 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13696 				"2642 REG_CONGESTION_BUF mailbox "
13697 				"failed with status x%x add_status x%x,"
13698 				" mbx status x%x reg %d\n",
13699 				shdr_status, shdr_add_status, rc, reg);
13700 		return -ENXIO;
13701 	}
13702 	return 0;
13703 }
13704 
13705 int
13706 lpfc_unreg_congestion_buf(struct lpfc_hba *phba)
13707 {
13708 	lpfc_cmf_stop(phba);
13709 	return __lpfc_reg_congestion_buf(phba, 0);
13710 }
13711 
13712 int
13713 lpfc_reg_congestion_buf(struct lpfc_hba *phba)
13714 {
13715 	return __lpfc_reg_congestion_buf(phba, 1);
13716 }
13717 
13718 /**
13719  * lpfc_get_sli4_parameters - Get the SLI4 Config PARAMETERS.
13720  * @phba: Pointer to HBA context object.
13721  * @mboxq: Pointer to the mailboxq memory for the mailbox command response.
13722  *
13723  * This function is called in the SLI4 code path to read the port's
13724  * sli4 capabilities.
13725  *
13726  * This function may be be called from any context that can block-wait
13727  * for the completion.  The expectation is that this routine is called
13728  * typically from probe_one or from the online routine.
13729  **/
13730 int
13731 lpfc_get_sli4_parameters(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
13732 {
13733 	int rc;
13734 	struct lpfc_mqe *mqe = &mboxq->u.mqe;
13735 	struct lpfc_pc_sli4_params *sli4_params;
13736 	uint32_t mbox_tmo;
13737 	int length;
13738 	bool exp_wqcq_pages = true;
13739 	struct lpfc_sli4_parameters *mbx_sli4_parameters;
13740 
13741 	/*
13742 	 * By default, the driver assumes the SLI4 port requires RPI
13743 	 * header postings.  The SLI4_PARAM response will correct this
13744 	 * assumption.
13745 	 */
13746 	phba->sli4_hba.rpi_hdrs_in_use = 1;
13747 
13748 	/* Read the port's SLI4 Config Parameters */
13749 	length = (sizeof(struct lpfc_mbx_get_sli4_parameters) -
13750 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13751 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
13752 			 LPFC_MBOX_OPCODE_GET_SLI4_PARAMETERS,
13753 			 length, LPFC_SLI4_MBX_EMBED);
13754 	if (!phba->sli4_hba.intr_enable)
13755 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
13756 	else {
13757 		mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
13758 		rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
13759 	}
13760 	if (unlikely(rc))
13761 		return rc;
13762 	sli4_params = &phba->sli4_hba.pc_sli4_params;
13763 	mbx_sli4_parameters = &mqe->un.get_sli4_parameters.sli4_parameters;
13764 	sli4_params->if_type = bf_get(cfg_if_type, mbx_sli4_parameters);
13765 	sli4_params->sli_rev = bf_get(cfg_sli_rev, mbx_sli4_parameters);
13766 	sli4_params->sli_family = bf_get(cfg_sli_family, mbx_sli4_parameters);
13767 	sli4_params->featurelevel_1 = bf_get(cfg_sli_hint_1,
13768 					     mbx_sli4_parameters);
13769 	sli4_params->featurelevel_2 = bf_get(cfg_sli_hint_2,
13770 					     mbx_sli4_parameters);
13771 	if (bf_get(cfg_phwq, mbx_sli4_parameters))
13772 		phba->sli3_options |= LPFC_SLI4_PHWQ_ENABLED;
13773 	else
13774 		phba->sli3_options &= ~LPFC_SLI4_PHWQ_ENABLED;
13775 	sli4_params->sge_supp_len = mbx_sli4_parameters->sge_supp_len;
13776 	sli4_params->loopbk_scope = bf_get(cfg_loopbk_scope,
13777 					   mbx_sli4_parameters);
13778 	sli4_params->oas_supported = bf_get(cfg_oas, mbx_sli4_parameters);
13779 	sli4_params->cqv = bf_get(cfg_cqv, mbx_sli4_parameters);
13780 	sli4_params->mqv = bf_get(cfg_mqv, mbx_sli4_parameters);
13781 	sli4_params->wqv = bf_get(cfg_wqv, mbx_sli4_parameters);
13782 	sli4_params->rqv = bf_get(cfg_rqv, mbx_sli4_parameters);
13783 	sli4_params->eqav = bf_get(cfg_eqav, mbx_sli4_parameters);
13784 	sli4_params->cqav = bf_get(cfg_cqav, mbx_sli4_parameters);
13785 	sli4_params->wqsize = bf_get(cfg_wqsize, mbx_sli4_parameters);
13786 	sli4_params->bv1s = bf_get(cfg_bv1s, mbx_sli4_parameters);
13787 	sli4_params->pls = bf_get(cfg_pvl, mbx_sli4_parameters);
13788 	sli4_params->sgl_pages_max = bf_get(cfg_sgl_page_cnt,
13789 					    mbx_sli4_parameters);
13790 	sli4_params->wqpcnt = bf_get(cfg_wqpcnt, mbx_sli4_parameters);
13791 	sli4_params->sgl_pp_align = bf_get(cfg_sgl_pp_align,
13792 					   mbx_sli4_parameters);
13793 	phba->sli4_hba.extents_in_use = bf_get(cfg_ext, mbx_sli4_parameters);
13794 	phba->sli4_hba.rpi_hdrs_in_use = bf_get(cfg_hdrr, mbx_sli4_parameters);
13795 	sli4_params->mi_cap = bf_get(cfg_mi_ver, mbx_sli4_parameters);
13796 
13797 	/* Check for Extended Pre-Registered SGL support */
13798 	phba->cfg_xpsgl = bf_get(cfg_xpsgl, mbx_sli4_parameters);
13799 
13800 	/* Check for firmware nvme support */
13801 	rc = (bf_get(cfg_nvme, mbx_sli4_parameters) &&
13802 		     bf_get(cfg_xib, mbx_sli4_parameters));
13803 
13804 	if (rc) {
13805 		/* Save this to indicate the Firmware supports NVME */
13806 		sli4_params->nvme = 1;
13807 
13808 		/* Firmware NVME support, check driver FC4 NVME support */
13809 		if (phba->cfg_enable_fc4_type == LPFC_ENABLE_FCP) {
13810 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_NVME,
13811 					"6133 Disabling NVME support: "
13812 					"FC4 type not supported: x%x\n",
13813 					phba->cfg_enable_fc4_type);
13814 			goto fcponly;
13815 		}
13816 	} else {
13817 		/* No firmware NVME support, check driver FC4 NVME support */
13818 		sli4_params->nvme = 0;
13819 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13820 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_NVME,
13821 					"6101 Disabling NVME support: Not "
13822 					"supported by firmware (%d %d) x%x\n",
13823 					bf_get(cfg_nvme, mbx_sli4_parameters),
13824 					bf_get(cfg_xib, mbx_sli4_parameters),
13825 					phba->cfg_enable_fc4_type);
13826 fcponly:
13827 			phba->nvmet_support = 0;
13828 			phba->cfg_nvmet_mrq = 0;
13829 			phba->cfg_nvme_seg_cnt = 0;
13830 
13831 			/* If no FC4 type support, move to just SCSI support */
13832 			if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP))
13833 				return -ENODEV;
13834 			phba->cfg_enable_fc4_type = LPFC_ENABLE_FCP;
13835 		}
13836 	}
13837 
13838 	/* If the NVME FC4 type is enabled, scale the sg_seg_cnt to
13839 	 * accommodate 512K and 1M IOs in a single nvme buf.
13840 	 */
13841 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
13842 		phba->cfg_sg_seg_cnt = LPFC_MAX_NVME_SEG_CNT;
13843 
13844 	/* Enable embedded Payload BDE if support is indicated */
13845 	if (bf_get(cfg_pbde, mbx_sli4_parameters))
13846 		phba->cfg_enable_pbde = 1;
13847 	else
13848 		phba->cfg_enable_pbde = 0;
13849 
13850 	/*
13851 	 * To support Suppress Response feature we must satisfy 3 conditions.
13852 	 * lpfc_suppress_rsp module parameter must be set (default).
13853 	 * In SLI4-Parameters Descriptor:
13854 	 * Extended Inline Buffers (XIB) must be supported.
13855 	 * Suppress Response IU Not Supported (SRIUNS) must NOT be supported
13856 	 * (double negative).
13857 	 */
13858 	if (phba->cfg_suppress_rsp && bf_get(cfg_xib, mbx_sli4_parameters) &&
13859 	    !(bf_get(cfg_nosr, mbx_sli4_parameters)))
13860 		phba->sli.sli_flag |= LPFC_SLI_SUPPRESS_RSP;
13861 	else
13862 		phba->cfg_suppress_rsp = 0;
13863 
13864 	if (bf_get(cfg_eqdr, mbx_sli4_parameters))
13865 		phba->sli.sli_flag |= LPFC_SLI_USE_EQDR;
13866 
13867 	/* Make sure that sge_supp_len can be handled by the driver */
13868 	if (sli4_params->sge_supp_len > LPFC_MAX_SGE_SIZE)
13869 		sli4_params->sge_supp_len = LPFC_MAX_SGE_SIZE;
13870 
13871 	dma_set_max_seg_size(&phba->pcidev->dev, sli4_params->sge_supp_len);
13872 
13873 	/*
13874 	 * Check whether the adapter supports an embedded copy of the
13875 	 * FCP CMD IU within the WQE for FCP_Ixxx commands. In order
13876 	 * to use this option, 128-byte WQEs must be used.
13877 	 */
13878 	if (bf_get(cfg_ext_embed_cb, mbx_sli4_parameters))
13879 		phba->fcp_embed_io = 1;
13880 	else
13881 		phba->fcp_embed_io = 0;
13882 
13883 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_NVME,
13884 			"6422 XIB %d PBDE %d: FCP %d NVME %d %d %d\n",
13885 			bf_get(cfg_xib, mbx_sli4_parameters),
13886 			phba->cfg_enable_pbde,
13887 			phba->fcp_embed_io, sli4_params->nvme,
13888 			phba->cfg_nvme_embed_cmd, phba->cfg_suppress_rsp);
13889 
13890 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
13891 	    LPFC_SLI_INTF_IF_TYPE_2) &&
13892 	    (bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf) ==
13893 		 LPFC_SLI_INTF_FAMILY_LNCR_A0))
13894 		exp_wqcq_pages = false;
13895 
13896 	if ((bf_get(cfg_cqpsize, mbx_sli4_parameters) & LPFC_CQ_16K_PAGE_SZ) &&
13897 	    (bf_get(cfg_wqpsize, mbx_sli4_parameters) & LPFC_WQ_16K_PAGE_SZ) &&
13898 	    exp_wqcq_pages &&
13899 	    (sli4_params->wqsize & LPFC_WQ_SZ128_SUPPORT))
13900 		phba->enab_exp_wqcq_pages = 1;
13901 	else
13902 		phba->enab_exp_wqcq_pages = 0;
13903 	/*
13904 	 * Check if the SLI port supports MDS Diagnostics
13905 	 */
13906 	if (bf_get(cfg_mds_diags, mbx_sli4_parameters))
13907 		phba->mds_diags_support = 1;
13908 	else
13909 		phba->mds_diags_support = 0;
13910 
13911 	/*
13912 	 * Check if the SLI port supports NSLER
13913 	 */
13914 	if (bf_get(cfg_nsler, mbx_sli4_parameters))
13915 		phba->nsler = 1;
13916 	else
13917 		phba->nsler = 0;
13918 
13919 	return 0;
13920 }
13921 
13922 /**
13923  * lpfc_pci_probe_one_s3 - PCI probe func to reg SLI-3 device to PCI subsystem.
13924  * @pdev: pointer to PCI device
13925  * @pid: pointer to PCI device identifier
13926  *
13927  * This routine is to be called to attach a device with SLI-3 interface spec
13928  * to the PCI subsystem. When an Emulex HBA with SLI-3 interface spec is
13929  * presented on PCI bus, the kernel PCI subsystem looks at PCI device-specific
13930  * information of the device and driver to see if the driver state that it can
13931  * support this kind of device. If the match is successful, the driver core
13932  * invokes this routine. If this routine determines it can claim the HBA, it
13933  * does all the initialization that it needs to do to handle the HBA properly.
13934  *
13935  * Return code
13936  * 	0 - driver can claim the device
13937  * 	negative value - driver can not claim the device
13938  **/
13939 static int
13940 lpfc_pci_probe_one_s3(struct pci_dev *pdev, const struct pci_device_id *pid)
13941 {
13942 	struct lpfc_hba   *phba;
13943 	struct lpfc_vport *vport = NULL;
13944 	struct Scsi_Host  *shost = NULL;
13945 	int error;
13946 	uint32_t cfg_mode, intr_mode;
13947 
13948 	/* Allocate memory for HBA structure */
13949 	phba = lpfc_hba_alloc(pdev);
13950 	if (!phba)
13951 		return -ENOMEM;
13952 
13953 	/* Perform generic PCI device enabling operation */
13954 	error = lpfc_enable_pci_dev(phba);
13955 	if (error)
13956 		goto out_free_phba;
13957 
13958 	/* Set up SLI API function jump table for PCI-device group-0 HBAs */
13959 	error = lpfc_api_table_setup(phba, LPFC_PCI_DEV_LP);
13960 	if (error)
13961 		goto out_disable_pci_dev;
13962 
13963 	/* Set up SLI-3 specific device PCI memory space */
13964 	error = lpfc_sli_pci_mem_setup(phba);
13965 	if (error) {
13966 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13967 				"1402 Failed to set up pci memory space.\n");
13968 		goto out_disable_pci_dev;
13969 	}
13970 
13971 	/* Set up SLI-3 specific device driver resources */
13972 	error = lpfc_sli_driver_resource_setup(phba);
13973 	if (error) {
13974 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13975 				"1404 Failed to set up driver resource.\n");
13976 		goto out_unset_pci_mem_s3;
13977 	}
13978 
13979 	/* Initialize and populate the iocb list per host */
13980 
13981 	error = lpfc_init_iocb_list(phba, LPFC_IOCB_LIST_CNT);
13982 	if (error) {
13983 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13984 				"1405 Failed to initialize iocb list.\n");
13985 		goto out_unset_driver_resource_s3;
13986 	}
13987 
13988 	/* Set up common device driver resources */
13989 	error = lpfc_setup_driver_resource_phase2(phba);
13990 	if (error) {
13991 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13992 				"1406 Failed to set up driver resource.\n");
13993 		goto out_free_iocb_list;
13994 	}
13995 
13996 	/* Get the default values for Model Name and Description */
13997 	lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
13998 
13999 	/* Create SCSI host to the physical port */
14000 	error = lpfc_create_shost(phba);
14001 	if (error) {
14002 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14003 				"1407 Failed to create scsi host.\n");
14004 		goto out_unset_driver_resource;
14005 	}
14006 
14007 	/* Configure sysfs attributes */
14008 	vport = phba->pport;
14009 	error = lpfc_alloc_sysfs_attr(vport);
14010 	if (error) {
14011 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14012 				"1476 Failed to allocate sysfs attr\n");
14013 		goto out_destroy_shost;
14014 	}
14015 
14016 	shost = lpfc_shost_from_vport(vport); /* save shost for error cleanup */
14017 	/* Now, trying to enable interrupt and bring up the device */
14018 	cfg_mode = phba->cfg_use_msi;
14019 	while (true) {
14020 		/* Put device to a known state before enabling interrupt */
14021 		lpfc_stop_port(phba);
14022 		/* Configure and enable interrupt */
14023 		intr_mode = lpfc_sli_enable_intr(phba, cfg_mode);
14024 		if (intr_mode == LPFC_INTR_ERROR) {
14025 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14026 					"0431 Failed to enable interrupt.\n");
14027 			error = -ENODEV;
14028 			goto out_free_sysfs_attr;
14029 		}
14030 		/* SLI-3 HBA setup */
14031 		if (lpfc_sli_hba_setup(phba)) {
14032 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14033 					"1477 Failed to set up hba\n");
14034 			error = -ENODEV;
14035 			goto out_remove_device;
14036 		}
14037 
14038 		/* Wait 50ms for the interrupts of previous mailbox commands */
14039 		msleep(50);
14040 		/* Check active interrupts on message signaled interrupts */
14041 		if (intr_mode == 0 ||
14042 		    phba->sli.slistat.sli_intr > LPFC_MSIX_VECTORS) {
14043 			/* Log the current active interrupt mode */
14044 			phba->intr_mode = intr_mode;
14045 			lpfc_log_intr_mode(phba, intr_mode);
14046 			break;
14047 		} else {
14048 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
14049 					"0447 Configure interrupt mode (%d) "
14050 					"failed active interrupt test.\n",
14051 					intr_mode);
14052 			/* Disable the current interrupt mode */
14053 			lpfc_sli_disable_intr(phba);
14054 			/* Try next level of interrupt mode */
14055 			cfg_mode = --intr_mode;
14056 		}
14057 	}
14058 
14059 	/* Perform post initialization setup */
14060 	lpfc_post_init_setup(phba);
14061 
14062 	/* Check if there are static vports to be created. */
14063 	lpfc_create_static_vport(phba);
14064 
14065 	return 0;
14066 
14067 out_remove_device:
14068 	lpfc_unset_hba(phba);
14069 out_free_sysfs_attr:
14070 	lpfc_free_sysfs_attr(vport);
14071 out_destroy_shost:
14072 	lpfc_destroy_shost(phba);
14073 out_unset_driver_resource:
14074 	lpfc_unset_driver_resource_phase2(phba);
14075 out_free_iocb_list:
14076 	lpfc_free_iocb_list(phba);
14077 out_unset_driver_resource_s3:
14078 	lpfc_sli_driver_resource_unset(phba);
14079 out_unset_pci_mem_s3:
14080 	lpfc_sli_pci_mem_unset(phba);
14081 out_disable_pci_dev:
14082 	lpfc_disable_pci_dev(phba);
14083 	if (shost)
14084 		scsi_host_put(shost);
14085 out_free_phba:
14086 	lpfc_hba_free(phba);
14087 	return error;
14088 }
14089 
14090 /**
14091  * lpfc_pci_remove_one_s3 - PCI func to unreg SLI-3 device from PCI subsystem.
14092  * @pdev: pointer to PCI device
14093  *
14094  * This routine is to be called to disattach a device with SLI-3 interface
14095  * spec from PCI subsystem. When an Emulex HBA with SLI-3 interface spec is
14096  * removed from PCI bus, it performs all the necessary cleanup for the HBA
14097  * device to be removed from the PCI subsystem properly.
14098  **/
14099 static void
14100 lpfc_pci_remove_one_s3(struct pci_dev *pdev)
14101 {
14102 	struct Scsi_Host  *shost = pci_get_drvdata(pdev);
14103 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
14104 	struct lpfc_vport **vports;
14105 	struct lpfc_hba   *phba = vport->phba;
14106 	int i;
14107 
14108 	set_bit(FC_UNLOADING, &vport->load_flag);
14109 
14110 	lpfc_free_sysfs_attr(vport);
14111 
14112 	/* Release all the vports against this physical port */
14113 	vports = lpfc_create_vport_work_array(phba);
14114 	if (vports != NULL)
14115 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
14116 			if (vports[i]->port_type == LPFC_PHYSICAL_PORT)
14117 				continue;
14118 			fc_vport_terminate(vports[i]->fc_vport);
14119 		}
14120 	lpfc_destroy_vport_work_array(phba, vports);
14121 
14122 	/* Remove FC host with the physical port */
14123 	fc_remove_host(shost);
14124 	scsi_remove_host(shost);
14125 
14126 	/* Clean up all nodes, mailboxes and IOs. */
14127 	lpfc_cleanup(vport);
14128 
14129 	/*
14130 	 * Bring down the SLI Layer. This step disable all interrupts,
14131 	 * clears the rings, discards all mailbox commands, and resets
14132 	 * the HBA.
14133 	 */
14134 
14135 	/* HBA interrupt will be disabled after this call */
14136 	lpfc_sli_hba_down(phba);
14137 	/* Stop kthread signal shall trigger work_done one more time */
14138 	kthread_stop(phba->worker_thread);
14139 	/* Final cleanup of txcmplq and reset the HBA */
14140 	lpfc_sli_brdrestart(phba);
14141 
14142 	kfree(phba->vpi_bmask);
14143 	kfree(phba->vpi_ids);
14144 
14145 	lpfc_stop_hba_timers(phba);
14146 	spin_lock_irq(&phba->port_list_lock);
14147 	list_del_init(&vport->listentry);
14148 	spin_unlock_irq(&phba->port_list_lock);
14149 
14150 	lpfc_debugfs_terminate(vport);
14151 
14152 	/* Disable SR-IOV if enabled */
14153 	if (phba->cfg_sriov_nr_virtfn)
14154 		pci_disable_sriov(pdev);
14155 
14156 	/* Disable interrupt */
14157 	lpfc_sli_disable_intr(phba);
14158 
14159 	scsi_host_put(shost);
14160 
14161 	/*
14162 	 * Call scsi_free before mem_free since scsi bufs are released to their
14163 	 * corresponding pools here.
14164 	 */
14165 	lpfc_scsi_free(phba);
14166 	lpfc_free_iocb_list(phba);
14167 
14168 	lpfc_mem_free_all(phba);
14169 
14170 	dma_free_coherent(&pdev->dev, lpfc_sli_hbq_size(),
14171 			  phba->hbqslimp.virt, phba->hbqslimp.phys);
14172 
14173 	/* Free resources associated with SLI2 interface */
14174 	dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
14175 			  phba->slim2p.virt, phba->slim2p.phys);
14176 
14177 	/* unmap adapter SLIM and Control Registers */
14178 	iounmap(phba->ctrl_regs_memmap_p);
14179 	iounmap(phba->slim_memmap_p);
14180 
14181 	lpfc_hba_free(phba);
14182 
14183 	pci_release_mem_regions(pdev);
14184 	pci_disable_device(pdev);
14185 }
14186 
14187 /**
14188  * lpfc_pci_suspend_one_s3 - PCI func to suspend SLI-3 device for power mgmnt
14189  * @dev_d: pointer to device
14190  *
14191  * This routine is to be called from the kernel's PCI subsystem to support
14192  * system Power Management (PM) to device with SLI-3 interface spec. When
14193  * PM invokes this method, it quiesces the device by stopping the driver's
14194  * worker thread for the device, turning off device's interrupt and DMA,
14195  * and bring the device offline. Note that as the driver implements the
14196  * minimum PM requirements to a power-aware driver's PM support for the
14197  * suspend/resume -- all the possible PM messages (SUSPEND, HIBERNATE, FREEZE)
14198  * to the suspend() method call will be treated as SUSPEND and the driver will
14199  * fully reinitialize its device during resume() method call, the driver will
14200  * set device to PCI_D3hot state in PCI config space instead of setting it
14201  * according to the @msg provided by the PM.
14202  *
14203  * Return code
14204  * 	0 - driver suspended the device
14205  * 	Error otherwise
14206  **/
14207 static int __maybe_unused
14208 lpfc_pci_suspend_one_s3(struct device *dev_d)
14209 {
14210 	struct Scsi_Host *shost = dev_get_drvdata(dev_d);
14211 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14212 
14213 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
14214 			"0473 PCI device Power Management suspend.\n");
14215 
14216 	/* Bring down the device */
14217 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
14218 	lpfc_offline(phba);
14219 	kthread_stop(phba->worker_thread);
14220 
14221 	/* Disable interrupt from device */
14222 	lpfc_sli_disable_intr(phba);
14223 
14224 	return 0;
14225 }
14226 
14227 /**
14228  * lpfc_pci_resume_one_s3 - PCI func to resume SLI-3 device for power mgmnt
14229  * @dev_d: pointer to device
14230  *
14231  * This routine is to be called from the kernel's PCI subsystem to support
14232  * system Power Management (PM) to device with SLI-3 interface spec. When PM
14233  * invokes this method, it restores the device's PCI config space state and
14234  * fully reinitializes the device and brings it online. Note that as the
14235  * driver implements the minimum PM requirements to a power-aware driver's
14236  * PM for suspend/resume -- all the possible PM messages (SUSPEND, HIBERNATE,
14237  * FREEZE) to the suspend() method call will be treated as SUSPEND and the
14238  * driver will fully reinitialize its device during resume() method call,
14239  * the device will be set to PCI_D0 directly in PCI config space before
14240  * restoring the state.
14241  *
14242  * Return code
14243  * 	0 - driver suspended the device
14244  * 	Error otherwise
14245  **/
14246 static int __maybe_unused
14247 lpfc_pci_resume_one_s3(struct device *dev_d)
14248 {
14249 	struct Scsi_Host *shost = dev_get_drvdata(dev_d);
14250 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14251 	uint32_t intr_mode;
14252 	int error;
14253 
14254 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
14255 			"0452 PCI device Power Management resume.\n");
14256 
14257 	/* Startup the kernel thread for this host adapter. */
14258 	phba->worker_thread = kthread_run(lpfc_do_work, phba,
14259 					"lpfc_worker_%d", phba->brd_no);
14260 	if (IS_ERR(phba->worker_thread)) {
14261 		error = PTR_ERR(phba->worker_thread);
14262 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14263 				"0434 PM resume failed to start worker "
14264 				"thread: error=x%x.\n", error);
14265 		return error;
14266 	}
14267 
14268 	/* Init cpu_map array */
14269 	lpfc_cpu_map_array_init(phba);
14270 	/* Init hba_eq_hdl array */
14271 	lpfc_hba_eq_hdl_array_init(phba);
14272 	/* Configure and enable interrupt */
14273 	intr_mode = lpfc_sli_enable_intr(phba, phba->intr_mode);
14274 	if (intr_mode == LPFC_INTR_ERROR) {
14275 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14276 				"0430 PM resume Failed to enable interrupt\n");
14277 		return -EIO;
14278 	} else
14279 		phba->intr_mode = intr_mode;
14280 
14281 	/* Restart HBA and bring it online */
14282 	lpfc_sli_brdrestart(phba);
14283 	lpfc_online(phba);
14284 
14285 	/* Log the current active interrupt mode */
14286 	lpfc_log_intr_mode(phba, phba->intr_mode);
14287 
14288 	return 0;
14289 }
14290 
14291 /**
14292  * lpfc_sli_prep_dev_for_recover - Prepare SLI3 device for pci slot recover
14293  * @phba: pointer to lpfc hba data structure.
14294  *
14295  * This routine is called to prepare the SLI3 device for PCI slot recover. It
14296  * aborts all the outstanding SCSI I/Os to the pci device.
14297  **/
14298 static void
14299 lpfc_sli_prep_dev_for_recover(struct lpfc_hba *phba)
14300 {
14301 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14302 			"2723 PCI channel I/O abort preparing for recovery\n");
14303 
14304 	/*
14305 	 * There may be errored I/Os through HBA, abort all I/Os on txcmplq
14306 	 * and let the SCSI mid-layer to retry them to recover.
14307 	 */
14308 	lpfc_sli_abort_fcp_rings(phba);
14309 }
14310 
14311 /**
14312  * lpfc_sli_prep_dev_for_reset - Prepare SLI3 device for pci slot reset
14313  * @phba: pointer to lpfc hba data structure.
14314  *
14315  * This routine is called to prepare the SLI3 device for PCI slot reset. It
14316  * disables the device interrupt and pci device, and aborts the internal FCP
14317  * pending I/Os.
14318  **/
14319 static void
14320 lpfc_sli_prep_dev_for_reset(struct lpfc_hba *phba)
14321 {
14322 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14323 			"2710 PCI channel disable preparing for reset\n");
14324 
14325 	/* Block any management I/Os to the device */
14326 	lpfc_block_mgmt_io(phba, LPFC_MBX_WAIT);
14327 
14328 	/* Block all SCSI devices' I/Os on the host */
14329 	lpfc_scsi_dev_block(phba);
14330 
14331 	/* Flush all driver's outstanding SCSI I/Os as we are to reset */
14332 	lpfc_sli_flush_io_rings(phba);
14333 
14334 	/* stop all timers */
14335 	lpfc_stop_hba_timers(phba);
14336 
14337 	/* Disable interrupt and pci device */
14338 	lpfc_sli_disable_intr(phba);
14339 	pci_disable_device(phba->pcidev);
14340 }
14341 
14342 /**
14343  * lpfc_sli_prep_dev_for_perm_failure - Prepare SLI3 dev for pci slot disable
14344  * @phba: pointer to lpfc hba data structure.
14345  *
14346  * This routine is called to prepare the SLI3 device for PCI slot permanently
14347  * disabling. It blocks the SCSI transport layer traffic and flushes the FCP
14348  * pending I/Os.
14349  **/
14350 static void
14351 lpfc_sli_prep_dev_for_perm_failure(struct lpfc_hba *phba)
14352 {
14353 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14354 			"2711 PCI channel permanent disable for failure\n");
14355 	/* Block all SCSI devices' I/Os on the host */
14356 	lpfc_scsi_dev_block(phba);
14357 	lpfc_sli4_prep_dev_for_reset(phba);
14358 
14359 	/* stop all timers */
14360 	lpfc_stop_hba_timers(phba);
14361 
14362 	/* Clean up all driver's outstanding SCSI I/Os */
14363 	lpfc_sli_flush_io_rings(phba);
14364 }
14365 
14366 /**
14367  * lpfc_io_error_detected_s3 - Method for handling SLI-3 device PCI I/O error
14368  * @pdev: pointer to PCI device.
14369  * @state: the current PCI connection state.
14370  *
14371  * This routine is called from the PCI subsystem for I/O error handling to
14372  * device with SLI-3 interface spec. This function is called by the PCI
14373  * subsystem after a PCI bus error affecting this device has been detected.
14374  * When this function is invoked, it will need to stop all the I/Os and
14375  * interrupt(s) to the device. Once that is done, it will return
14376  * PCI_ERS_RESULT_NEED_RESET for the PCI subsystem to perform proper recovery
14377  * as desired.
14378  *
14379  * Return codes
14380  * 	PCI_ERS_RESULT_CAN_RECOVER - can be recovered with reset_link
14381  * 	PCI_ERS_RESULT_NEED_RESET - need to reset before recovery
14382  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
14383  **/
14384 static pci_ers_result_t
14385 lpfc_io_error_detected_s3(struct pci_dev *pdev, pci_channel_state_t state)
14386 {
14387 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
14388 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14389 
14390 	switch (state) {
14391 	case pci_channel_io_normal:
14392 		/* Non-fatal error, prepare for recovery */
14393 		lpfc_sli_prep_dev_for_recover(phba);
14394 		return PCI_ERS_RESULT_CAN_RECOVER;
14395 	case pci_channel_io_frozen:
14396 		/* Fatal error, prepare for slot reset */
14397 		lpfc_sli_prep_dev_for_reset(phba);
14398 		return PCI_ERS_RESULT_NEED_RESET;
14399 	case pci_channel_io_perm_failure:
14400 		/* Permanent failure, prepare for device down */
14401 		lpfc_sli_prep_dev_for_perm_failure(phba);
14402 		return PCI_ERS_RESULT_DISCONNECT;
14403 	default:
14404 		/* Unknown state, prepare and request slot reset */
14405 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14406 				"0472 Unknown PCI error state: x%x\n", state);
14407 		lpfc_sli_prep_dev_for_reset(phba);
14408 		return PCI_ERS_RESULT_NEED_RESET;
14409 	}
14410 }
14411 
14412 /**
14413  * lpfc_io_slot_reset_s3 - Method for restarting PCI SLI-3 device from scratch.
14414  * @pdev: pointer to PCI device.
14415  *
14416  * This routine is called from the PCI subsystem for error handling to
14417  * device with SLI-3 interface spec. This is called after PCI bus has been
14418  * reset to restart the PCI card from scratch, as if from a cold-boot.
14419  * During the PCI subsystem error recovery, after driver returns
14420  * PCI_ERS_RESULT_NEED_RESET, the PCI subsystem will perform proper error
14421  * recovery and then call this routine before calling the .resume method
14422  * to recover the device. This function will initialize the HBA device,
14423  * enable the interrupt, but it will just put the HBA to offline state
14424  * without passing any I/O traffic.
14425  *
14426  * Return codes
14427  * 	PCI_ERS_RESULT_RECOVERED - the device has been recovered
14428  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
14429  */
14430 static pci_ers_result_t
14431 lpfc_io_slot_reset_s3(struct pci_dev *pdev)
14432 {
14433 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
14434 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14435 	struct lpfc_sli *psli = &phba->sli;
14436 	uint32_t intr_mode;
14437 
14438 	dev_printk(KERN_INFO, &pdev->dev, "recovering from a slot reset.\n");
14439 	if (pci_enable_device_mem(pdev)) {
14440 		printk(KERN_ERR "lpfc: Cannot re-enable "
14441 			"PCI device after reset.\n");
14442 		return PCI_ERS_RESULT_DISCONNECT;
14443 	}
14444 
14445 	pci_restore_state(pdev);
14446 
14447 	/*
14448 	 * As the new kernel behavior of pci_restore_state() API call clears
14449 	 * device saved_state flag, need to save the restored state again.
14450 	 */
14451 	pci_save_state(pdev);
14452 
14453 	if (pdev->is_busmaster)
14454 		pci_set_master(pdev);
14455 
14456 	spin_lock_irq(&phba->hbalock);
14457 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
14458 	spin_unlock_irq(&phba->hbalock);
14459 
14460 	/* Configure and enable interrupt */
14461 	intr_mode = lpfc_sli_enable_intr(phba, phba->intr_mode);
14462 	if (intr_mode == LPFC_INTR_ERROR) {
14463 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14464 				"0427 Cannot re-enable interrupt after "
14465 				"slot reset.\n");
14466 		return PCI_ERS_RESULT_DISCONNECT;
14467 	} else
14468 		phba->intr_mode = intr_mode;
14469 
14470 	/* Take device offline, it will perform cleanup */
14471 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
14472 	lpfc_offline(phba);
14473 	lpfc_sli_brdrestart(phba);
14474 
14475 	/* Log the current active interrupt mode */
14476 	lpfc_log_intr_mode(phba, phba->intr_mode);
14477 
14478 	return PCI_ERS_RESULT_RECOVERED;
14479 }
14480 
14481 /**
14482  * lpfc_io_resume_s3 - Method for resuming PCI I/O operation on SLI-3 device.
14483  * @pdev: pointer to PCI device
14484  *
14485  * This routine is called from the PCI subsystem for error handling to device
14486  * with SLI-3 interface spec. It is called when kernel error recovery tells
14487  * the lpfc driver that it is ok to resume normal PCI operation after PCI bus
14488  * error recovery. After this call, traffic can start to flow from this device
14489  * again.
14490  */
14491 static void
14492 lpfc_io_resume_s3(struct pci_dev *pdev)
14493 {
14494 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
14495 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14496 
14497 	/* Bring device online, it will be no-op for non-fatal error resume */
14498 	lpfc_online(phba);
14499 }
14500 
14501 /**
14502  * lpfc_sli4_get_els_iocb_cnt - Calculate the # of ELS IOCBs to reserve
14503  * @phba: pointer to lpfc hba data structure.
14504  *
14505  * returns the number of ELS/CT IOCBs to reserve
14506  **/
14507 int
14508 lpfc_sli4_get_els_iocb_cnt(struct lpfc_hba *phba)
14509 {
14510 	int max_xri = phba->sli4_hba.max_cfg_param.max_xri;
14511 
14512 	if (phba->sli_rev == LPFC_SLI_REV4) {
14513 		if (max_xri <= 100)
14514 			return 10;
14515 		else if (max_xri <= 256)
14516 			return 25;
14517 		else if (max_xri <= 512)
14518 			return 50;
14519 		else if (max_xri <= 1024)
14520 			return 100;
14521 		else if (max_xri <= 1536)
14522 			return 150;
14523 		else if (max_xri <= 2048)
14524 			return 200;
14525 		else
14526 			return 250;
14527 	} else
14528 		return 0;
14529 }
14530 
14531 /**
14532  * lpfc_sli4_get_iocb_cnt - Calculate the # of total IOCBs to reserve
14533  * @phba: pointer to lpfc hba data structure.
14534  *
14535  * returns the number of ELS/CT + NVMET IOCBs to reserve
14536  **/
14537 int
14538 lpfc_sli4_get_iocb_cnt(struct lpfc_hba *phba)
14539 {
14540 	int max_xri = lpfc_sli4_get_els_iocb_cnt(phba);
14541 
14542 	if (phba->nvmet_support)
14543 		max_xri += LPFC_NVMET_BUF_POST;
14544 	return max_xri;
14545 }
14546 
14547 
14548 static int
14549 lpfc_log_write_firmware_error(struct lpfc_hba *phba, uint32_t offset,
14550 	uint32_t magic_number, uint32_t ftype, uint32_t fid, uint32_t fsize,
14551 	const struct firmware *fw)
14552 {
14553 	int rc;
14554 	u8 sli_family;
14555 
14556 	sli_family = bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf);
14557 	/* Three cases:  (1) FW was not supported on the detected adapter.
14558 	 * (2) FW update has been locked out administratively.
14559 	 * (3) Some other error during FW update.
14560 	 * In each case, an unmaskable message is written to the console
14561 	 * for admin diagnosis.
14562 	 */
14563 	if (offset == ADD_STATUS_FW_NOT_SUPPORTED ||
14564 	    (sli_family == LPFC_SLI_INTF_FAMILY_G6 &&
14565 	     magic_number != MAGIC_NUMBER_G6) ||
14566 	    (sli_family == LPFC_SLI_INTF_FAMILY_G7 &&
14567 	     magic_number != MAGIC_NUMBER_G7) ||
14568 	    (sli_family == LPFC_SLI_INTF_FAMILY_G7P &&
14569 	     magic_number != MAGIC_NUMBER_G7P)) {
14570 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14571 				"3030 This firmware version is not supported on"
14572 				" this HBA model. Device:%x Magic:%x Type:%x "
14573 				"ID:%x Size %d %zd\n",
14574 				phba->pcidev->device, magic_number, ftype, fid,
14575 				fsize, fw->size);
14576 		rc = -EINVAL;
14577 	} else if (offset == ADD_STATUS_FW_DOWNLOAD_HW_DISABLED) {
14578 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14579 				"3021 Firmware downloads have been prohibited "
14580 				"by a system configuration setting on "
14581 				"Device:%x Magic:%x Type:%x ID:%x Size %d "
14582 				"%zd\n",
14583 				phba->pcidev->device, magic_number, ftype, fid,
14584 				fsize, fw->size);
14585 		rc = -EACCES;
14586 	} else {
14587 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14588 				"3022 FW Download failed. Add Status x%x "
14589 				"Device:%x Magic:%x Type:%x ID:%x Size %d "
14590 				"%zd\n",
14591 				offset, phba->pcidev->device, magic_number,
14592 				ftype, fid, fsize, fw->size);
14593 		rc = -EIO;
14594 	}
14595 	return rc;
14596 }
14597 
14598 /**
14599  * lpfc_write_firmware - attempt to write a firmware image to the port
14600  * @fw: pointer to firmware image returned from request_firmware.
14601  * @context: pointer to firmware image returned from request_firmware.
14602  *
14603  **/
14604 static void
14605 lpfc_write_firmware(const struct firmware *fw, void *context)
14606 {
14607 	struct lpfc_hba *phba = (struct lpfc_hba *)context;
14608 	char fwrev[FW_REV_STR_SIZE];
14609 	struct lpfc_grp_hdr *image;
14610 	struct list_head dma_buffer_list;
14611 	int i, rc = 0;
14612 	struct lpfc_dmabuf *dmabuf, *next;
14613 	uint32_t offset = 0, temp_offset = 0;
14614 	uint32_t magic_number, ftype, fid, fsize;
14615 
14616 	/* It can be null in no-wait mode, sanity check */
14617 	if (!fw) {
14618 		rc = -ENXIO;
14619 		goto out;
14620 	}
14621 	image = (struct lpfc_grp_hdr *)fw->data;
14622 
14623 	magic_number = be32_to_cpu(image->magic_number);
14624 	ftype = bf_get_be32(lpfc_grp_hdr_file_type, image);
14625 	fid = bf_get_be32(lpfc_grp_hdr_id, image);
14626 	fsize = be32_to_cpu(image->size);
14627 
14628 	INIT_LIST_HEAD(&dma_buffer_list);
14629 	lpfc_decode_firmware_rev(phba, fwrev, 1);
14630 	if (strncmp(fwrev, image->revision, strnlen(image->revision, 16))) {
14631 		lpfc_log_msg(phba, KERN_NOTICE, LOG_INIT | LOG_SLI,
14632 			     "3023 Updating Firmware, Current Version:%s "
14633 			     "New Version:%s\n",
14634 			     fwrev, image->revision);
14635 		for (i = 0; i < LPFC_MBX_WR_CONFIG_MAX_BDE; i++) {
14636 			dmabuf = kzalloc(sizeof(struct lpfc_dmabuf),
14637 					 GFP_KERNEL);
14638 			if (!dmabuf) {
14639 				rc = -ENOMEM;
14640 				goto release_out;
14641 			}
14642 			dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
14643 							  SLI4_PAGE_SIZE,
14644 							  &dmabuf->phys,
14645 							  GFP_KERNEL);
14646 			if (!dmabuf->virt) {
14647 				kfree(dmabuf);
14648 				rc = -ENOMEM;
14649 				goto release_out;
14650 			}
14651 			list_add_tail(&dmabuf->list, &dma_buffer_list);
14652 		}
14653 		while (offset < fw->size) {
14654 			temp_offset = offset;
14655 			list_for_each_entry(dmabuf, &dma_buffer_list, list) {
14656 				if (temp_offset + SLI4_PAGE_SIZE > fw->size) {
14657 					memcpy(dmabuf->virt,
14658 					       fw->data + temp_offset,
14659 					       fw->size - temp_offset);
14660 					temp_offset = fw->size;
14661 					break;
14662 				}
14663 				memcpy(dmabuf->virt, fw->data + temp_offset,
14664 				       SLI4_PAGE_SIZE);
14665 				temp_offset += SLI4_PAGE_SIZE;
14666 			}
14667 			rc = lpfc_wr_object(phba, &dma_buffer_list,
14668 				    (fw->size - offset), &offset);
14669 			if (rc) {
14670 				rc = lpfc_log_write_firmware_error(phba, offset,
14671 								   magic_number,
14672 								   ftype,
14673 								   fid,
14674 								   fsize,
14675 								   fw);
14676 				goto release_out;
14677 			}
14678 		}
14679 		rc = offset;
14680 	} else
14681 		lpfc_log_msg(phba, KERN_NOTICE, LOG_INIT | LOG_SLI,
14682 			     "3029 Skipped Firmware update, Current "
14683 			     "Version:%s New Version:%s\n",
14684 			     fwrev, image->revision);
14685 
14686 release_out:
14687 	list_for_each_entry_safe(dmabuf, next, &dma_buffer_list, list) {
14688 		list_del(&dmabuf->list);
14689 		dma_free_coherent(&phba->pcidev->dev, SLI4_PAGE_SIZE,
14690 				  dmabuf->virt, dmabuf->phys);
14691 		kfree(dmabuf);
14692 	}
14693 	release_firmware(fw);
14694 out:
14695 	if (rc < 0)
14696 		lpfc_log_msg(phba, KERN_ERR, LOG_INIT | LOG_SLI,
14697 			     "3062 Firmware update error, status %d.\n", rc);
14698 	else
14699 		lpfc_log_msg(phba, KERN_NOTICE, LOG_INIT | LOG_SLI,
14700 			     "3024 Firmware update success: size %d.\n", rc);
14701 }
14702 
14703 /**
14704  * lpfc_sli4_request_firmware_update - Request linux generic firmware upgrade
14705  * @phba: pointer to lpfc hba data structure.
14706  * @fw_upgrade: which firmware to update.
14707  *
14708  * This routine is called to perform Linux generic firmware upgrade on device
14709  * that supports such feature.
14710  **/
14711 int
14712 lpfc_sli4_request_firmware_update(struct lpfc_hba *phba, uint8_t fw_upgrade)
14713 {
14714 	char file_name[ELX_FW_NAME_SIZE] = {0};
14715 	int ret;
14716 	const struct firmware *fw;
14717 
14718 	/* Only supported on SLI4 interface type 2 for now */
14719 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) <
14720 	    LPFC_SLI_INTF_IF_TYPE_2)
14721 		return -EPERM;
14722 
14723 	scnprintf(file_name, sizeof(file_name), "%s.grp", phba->ModelName);
14724 
14725 	if (fw_upgrade == INT_FW_UPGRADE) {
14726 		ret = request_firmware_nowait(THIS_MODULE, FW_ACTION_UEVENT,
14727 					file_name, &phba->pcidev->dev,
14728 					GFP_KERNEL, (void *)phba,
14729 					lpfc_write_firmware);
14730 	} else if (fw_upgrade == RUN_FW_UPGRADE) {
14731 		ret = request_firmware(&fw, file_name, &phba->pcidev->dev);
14732 		if (!ret)
14733 			lpfc_write_firmware(fw, (void *)phba);
14734 	} else {
14735 		ret = -EINVAL;
14736 	}
14737 
14738 	return ret;
14739 }
14740 
14741 /**
14742  * lpfc_pci_probe_one_s4 - PCI probe func to reg SLI-4 device to PCI subsys
14743  * @pdev: pointer to PCI device
14744  * @pid: pointer to PCI device identifier
14745  *
14746  * This routine is called from the kernel's PCI subsystem to device with
14747  * SLI-4 interface spec. When an Emulex HBA with SLI-4 interface spec is
14748  * presented on PCI bus, the kernel PCI subsystem looks at PCI device-specific
14749  * information of the device and driver to see if the driver state that it
14750  * can support this kind of device. If the match is successful, the driver
14751  * core invokes this routine. If this routine determines it can claim the HBA,
14752  * it does all the initialization that it needs to do to handle the HBA
14753  * properly.
14754  *
14755  * Return code
14756  * 	0 - driver can claim the device
14757  * 	negative value - driver can not claim the device
14758  **/
14759 static int
14760 lpfc_pci_probe_one_s4(struct pci_dev *pdev, const struct pci_device_id *pid)
14761 {
14762 	struct lpfc_hba   *phba;
14763 	struct lpfc_vport *vport = NULL;
14764 	struct Scsi_Host  *shost = NULL;
14765 	int error;
14766 	uint32_t cfg_mode, intr_mode;
14767 
14768 	/* Allocate memory for HBA structure */
14769 	phba = lpfc_hba_alloc(pdev);
14770 	if (!phba)
14771 		return -ENOMEM;
14772 
14773 	INIT_LIST_HEAD(&phba->poll_list);
14774 
14775 	/* Perform generic PCI device enabling operation */
14776 	error = lpfc_enable_pci_dev(phba);
14777 	if (error)
14778 		goto out_free_phba;
14779 
14780 	/* Set up SLI API function jump table for PCI-device group-1 HBAs */
14781 	error = lpfc_api_table_setup(phba, LPFC_PCI_DEV_OC);
14782 	if (error)
14783 		goto out_disable_pci_dev;
14784 
14785 	/* Set up SLI-4 specific device PCI memory space */
14786 	error = lpfc_sli4_pci_mem_setup(phba);
14787 	if (error) {
14788 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14789 				"1410 Failed to set up pci memory space.\n");
14790 		goto out_disable_pci_dev;
14791 	}
14792 
14793 	/* Set up SLI-4 Specific device driver resources */
14794 	error = lpfc_sli4_driver_resource_setup(phba);
14795 	if (error) {
14796 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14797 				"1412 Failed to set up driver resource.\n");
14798 		goto out_unset_pci_mem_s4;
14799 	}
14800 
14801 	spin_lock_init(&phba->rrq_list_lock);
14802 	INIT_LIST_HEAD(&phba->active_rrq_list);
14803 	INIT_LIST_HEAD(&phba->fcf.fcf_pri_list);
14804 
14805 	/* Set up common device driver resources */
14806 	error = lpfc_setup_driver_resource_phase2(phba);
14807 	if (error) {
14808 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14809 				"1414 Failed to set up driver resource.\n");
14810 		goto out_unset_driver_resource_s4;
14811 	}
14812 
14813 	/* Get the default values for Model Name and Description */
14814 	lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
14815 
14816 	/* Now, trying to enable interrupt and bring up the device */
14817 	cfg_mode = phba->cfg_use_msi;
14818 
14819 	/* Put device to a known state before enabling interrupt */
14820 	phba->pport = NULL;
14821 	lpfc_stop_port(phba);
14822 
14823 	/* Init cpu_map array */
14824 	lpfc_cpu_map_array_init(phba);
14825 
14826 	/* Init hba_eq_hdl array */
14827 	lpfc_hba_eq_hdl_array_init(phba);
14828 
14829 	/* Configure and enable interrupt */
14830 	intr_mode = lpfc_sli4_enable_intr(phba, cfg_mode);
14831 	if (intr_mode == LPFC_INTR_ERROR) {
14832 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14833 				"0426 Failed to enable interrupt.\n");
14834 		error = -ENODEV;
14835 		goto out_unset_driver_resource;
14836 	}
14837 	/* Default to single EQ for non-MSI-X */
14838 	if (phba->intr_type != MSIX) {
14839 		phba->cfg_irq_chann = 1;
14840 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
14841 			if (phba->nvmet_support)
14842 				phba->cfg_nvmet_mrq = 1;
14843 		}
14844 	}
14845 	lpfc_cpu_affinity_check(phba, phba->cfg_irq_chann);
14846 
14847 	/* Create SCSI host to the physical port */
14848 	error = lpfc_create_shost(phba);
14849 	if (error) {
14850 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14851 				"1415 Failed to create scsi host.\n");
14852 		goto out_disable_intr;
14853 	}
14854 	vport = phba->pport;
14855 	shost = lpfc_shost_from_vport(vport); /* save shost for error cleanup */
14856 
14857 	/* Configure sysfs attributes */
14858 	error = lpfc_alloc_sysfs_attr(vport);
14859 	if (error) {
14860 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14861 				"1416 Failed to allocate sysfs attr\n");
14862 		goto out_destroy_shost;
14863 	}
14864 
14865 	/* Set up SLI-4 HBA */
14866 	if (lpfc_sli4_hba_setup(phba)) {
14867 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14868 				"1421 Failed to set up hba\n");
14869 		error = -ENODEV;
14870 		goto out_free_sysfs_attr;
14871 	}
14872 
14873 	/* Log the current active interrupt mode */
14874 	phba->intr_mode = intr_mode;
14875 	lpfc_log_intr_mode(phba, intr_mode);
14876 
14877 	/* Perform post initialization setup */
14878 	lpfc_post_init_setup(phba);
14879 
14880 	/* NVME support in FW earlier in the driver load corrects the
14881 	 * FC4 type making a check for nvme_support unnecessary.
14882 	 */
14883 	if (phba->nvmet_support == 0) {
14884 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
14885 			/* Create NVME binding with nvme_fc_transport. This
14886 			 * ensures the vport is initialized.  If the localport
14887 			 * create fails, it should not unload the driver to
14888 			 * support field issues.
14889 			 */
14890 			error = lpfc_nvme_create_localport(vport);
14891 			if (error) {
14892 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14893 						"6004 NVME registration "
14894 						"failed, error x%x\n",
14895 						error);
14896 			}
14897 		}
14898 	}
14899 
14900 	/* check for firmware upgrade or downgrade */
14901 	if (phba->cfg_request_firmware_upgrade)
14902 		lpfc_sli4_request_firmware_update(phba, INT_FW_UPGRADE);
14903 
14904 	/* Check if there are static vports to be created. */
14905 	lpfc_create_static_vport(phba);
14906 
14907 	timer_setup(&phba->cpuhp_poll_timer, lpfc_sli4_poll_hbtimer, 0);
14908 	cpuhp_state_add_instance_nocalls(lpfc_cpuhp_state, &phba->cpuhp);
14909 
14910 	return 0;
14911 
14912 out_free_sysfs_attr:
14913 	lpfc_free_sysfs_attr(vport);
14914 out_destroy_shost:
14915 	lpfc_destroy_shost(phba);
14916 out_disable_intr:
14917 	lpfc_sli4_disable_intr(phba);
14918 out_unset_driver_resource:
14919 	lpfc_unset_driver_resource_phase2(phba);
14920 out_unset_driver_resource_s4:
14921 	lpfc_sli4_driver_resource_unset(phba);
14922 out_unset_pci_mem_s4:
14923 	lpfc_sli4_pci_mem_unset(phba);
14924 out_disable_pci_dev:
14925 	lpfc_disable_pci_dev(phba);
14926 	if (shost)
14927 		scsi_host_put(shost);
14928 out_free_phba:
14929 	lpfc_hba_free(phba);
14930 	return error;
14931 }
14932 
14933 /**
14934  * lpfc_pci_remove_one_s4 - PCI func to unreg SLI-4 device from PCI subsystem
14935  * @pdev: pointer to PCI device
14936  *
14937  * This routine is called from the kernel's PCI subsystem to device with
14938  * SLI-4 interface spec. When an Emulex HBA with SLI-4 interface spec is
14939  * removed from PCI bus, it performs all the necessary cleanup for the HBA
14940  * device to be removed from the PCI subsystem properly.
14941  **/
14942 static void
14943 lpfc_pci_remove_one_s4(struct pci_dev *pdev)
14944 {
14945 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
14946 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
14947 	struct lpfc_vport **vports;
14948 	struct lpfc_hba *phba = vport->phba;
14949 	int i;
14950 
14951 	/* Mark the device unloading flag */
14952 	set_bit(FC_UNLOADING, &vport->load_flag);
14953 	if (phba->cgn_i)
14954 		lpfc_unreg_congestion_buf(phba);
14955 
14956 	lpfc_free_sysfs_attr(vport);
14957 
14958 	/* Release all the vports against this physical port */
14959 	vports = lpfc_create_vport_work_array(phba);
14960 	if (vports != NULL)
14961 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
14962 			if (vports[i]->port_type == LPFC_PHYSICAL_PORT)
14963 				continue;
14964 			fc_vport_terminate(vports[i]->fc_vport);
14965 		}
14966 	lpfc_destroy_vport_work_array(phba, vports);
14967 
14968 	/* Remove FC host with the physical port */
14969 	fc_remove_host(shost);
14970 	scsi_remove_host(shost);
14971 
14972 	/* Perform ndlp cleanup on the physical port.  The nvme and nvmet
14973 	 * localports are destroyed after to cleanup all transport memory.
14974 	 */
14975 	lpfc_cleanup(vport);
14976 	lpfc_nvmet_destroy_targetport(phba);
14977 	lpfc_nvme_destroy_localport(vport);
14978 
14979 	/* De-allocate multi-XRI pools */
14980 	if (phba->cfg_xri_rebalancing)
14981 		lpfc_destroy_multixri_pools(phba);
14982 
14983 	/*
14984 	 * Bring down the SLI Layer. This step disables all interrupts,
14985 	 * clears the rings, discards all mailbox commands, and resets
14986 	 * the HBA FCoE function.
14987 	 */
14988 	lpfc_debugfs_terminate(vport);
14989 
14990 	lpfc_stop_hba_timers(phba);
14991 	spin_lock_irq(&phba->port_list_lock);
14992 	list_del_init(&vport->listentry);
14993 	spin_unlock_irq(&phba->port_list_lock);
14994 
14995 	/* Perform scsi free before driver resource_unset since scsi
14996 	 * buffers are released to their corresponding pools here.
14997 	 */
14998 	lpfc_io_free(phba);
14999 	lpfc_free_iocb_list(phba);
15000 	lpfc_sli4_hba_unset(phba);
15001 
15002 	lpfc_unset_driver_resource_phase2(phba);
15003 	lpfc_sli4_driver_resource_unset(phba);
15004 
15005 	/* Unmap adapter Control and Doorbell registers */
15006 	lpfc_sli4_pci_mem_unset(phba);
15007 
15008 	/* Release PCI resources and disable device's PCI function */
15009 	scsi_host_put(shost);
15010 	lpfc_disable_pci_dev(phba);
15011 
15012 	/* Finally, free the driver's device data structure */
15013 	lpfc_hba_free(phba);
15014 
15015 	return;
15016 }
15017 
15018 /**
15019  * lpfc_pci_suspend_one_s4 - PCI func to suspend SLI-4 device for power mgmnt
15020  * @dev_d: pointer to device
15021  *
15022  * This routine is called from the kernel's PCI subsystem to support system
15023  * Power Management (PM) to device with SLI-4 interface spec. When PM invokes
15024  * this method, it quiesces the device by stopping the driver's worker
15025  * thread for the device, turning off device's interrupt and DMA, and bring
15026  * the device offline. Note that as the driver implements the minimum PM
15027  * requirements to a power-aware driver's PM support for suspend/resume -- all
15028  * the possible PM messages (SUSPEND, HIBERNATE, FREEZE) to the suspend()
15029  * method call will be treated as SUSPEND and the driver will fully
15030  * reinitialize its device during resume() method call, the driver will set
15031  * device to PCI_D3hot state in PCI config space instead of setting it
15032  * according to the @msg provided by the PM.
15033  *
15034  * Return code
15035  * 	0 - driver suspended the device
15036  * 	Error otherwise
15037  **/
15038 static int __maybe_unused
15039 lpfc_pci_suspend_one_s4(struct device *dev_d)
15040 {
15041 	struct Scsi_Host *shost = dev_get_drvdata(dev_d);
15042 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15043 
15044 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
15045 			"2843 PCI device Power Management suspend.\n");
15046 
15047 	/* Bring down the device */
15048 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
15049 	lpfc_offline(phba);
15050 	kthread_stop(phba->worker_thread);
15051 
15052 	/* Disable interrupt from device */
15053 	lpfc_sli4_disable_intr(phba);
15054 	lpfc_sli4_queue_destroy(phba);
15055 
15056 	return 0;
15057 }
15058 
15059 /**
15060  * lpfc_pci_resume_one_s4 - PCI func to resume SLI-4 device for power mgmnt
15061  * @dev_d: pointer to device
15062  *
15063  * This routine is called from the kernel's PCI subsystem to support system
15064  * Power Management (PM) to device with SLI-4 interface spac. When PM invokes
15065  * this method, it restores the device's PCI config space state and fully
15066  * reinitializes the device and brings it online. Note that as the driver
15067  * implements the minimum PM requirements to a power-aware driver's PM for
15068  * suspend/resume -- all the possible PM messages (SUSPEND, HIBERNATE, FREEZE)
15069  * to the suspend() method call will be treated as SUSPEND and the driver
15070  * will fully reinitialize its device during resume() method call, the device
15071  * will be set to PCI_D0 directly in PCI config space before restoring the
15072  * state.
15073  *
15074  * Return code
15075  * 	0 - driver suspended the device
15076  * 	Error otherwise
15077  **/
15078 static int __maybe_unused
15079 lpfc_pci_resume_one_s4(struct device *dev_d)
15080 {
15081 	struct Scsi_Host *shost = dev_get_drvdata(dev_d);
15082 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15083 	uint32_t intr_mode;
15084 	int error;
15085 
15086 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
15087 			"0292 PCI device Power Management resume.\n");
15088 
15089 	 /* Startup the kernel thread for this host adapter. */
15090 	phba->worker_thread = kthread_run(lpfc_do_work, phba,
15091 					"lpfc_worker_%d", phba->brd_no);
15092 	if (IS_ERR(phba->worker_thread)) {
15093 		error = PTR_ERR(phba->worker_thread);
15094 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15095 				"0293 PM resume failed to start worker "
15096 				"thread: error=x%x.\n", error);
15097 		return error;
15098 	}
15099 
15100 	/* Configure and enable interrupt */
15101 	intr_mode = lpfc_sli4_enable_intr(phba, phba->intr_mode);
15102 	if (intr_mode == LPFC_INTR_ERROR) {
15103 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15104 				"0294 PM resume Failed to enable interrupt\n");
15105 		return -EIO;
15106 	} else
15107 		phba->intr_mode = intr_mode;
15108 
15109 	/* Restart HBA and bring it online */
15110 	lpfc_sli_brdrestart(phba);
15111 	lpfc_online(phba);
15112 
15113 	/* Log the current active interrupt mode */
15114 	lpfc_log_intr_mode(phba, phba->intr_mode);
15115 
15116 	return 0;
15117 }
15118 
15119 /**
15120  * lpfc_sli4_prep_dev_for_recover - Prepare SLI4 device for pci slot recover
15121  * @phba: pointer to lpfc hba data structure.
15122  *
15123  * This routine is called to prepare the SLI4 device for PCI slot recover. It
15124  * aborts all the outstanding SCSI I/Os to the pci device.
15125  **/
15126 static void
15127 lpfc_sli4_prep_dev_for_recover(struct lpfc_hba *phba)
15128 {
15129 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15130 			"2828 PCI channel I/O abort preparing for recovery\n");
15131 	/*
15132 	 * There may be errored I/Os through HBA, abort all I/Os on txcmplq
15133 	 * and let the SCSI mid-layer to retry them to recover.
15134 	 */
15135 	lpfc_sli_abort_fcp_rings(phba);
15136 }
15137 
15138 /**
15139  * lpfc_sli4_prep_dev_for_reset - Prepare SLI4 device for pci slot reset
15140  * @phba: pointer to lpfc hba data structure.
15141  *
15142  * This routine is called to prepare the SLI4 device for PCI slot reset. It
15143  * disables the device interrupt and pci device, and aborts the internal FCP
15144  * pending I/Os.
15145  **/
15146 static void
15147 lpfc_sli4_prep_dev_for_reset(struct lpfc_hba *phba)
15148 {
15149 	int offline =  pci_channel_offline(phba->pcidev);
15150 
15151 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15152 			"2826 PCI channel disable preparing for reset offline"
15153 			" %d\n", offline);
15154 
15155 	/* Block any management I/Os to the device */
15156 	lpfc_block_mgmt_io(phba, LPFC_MBX_NO_WAIT);
15157 
15158 
15159 	/* HBA_PCI_ERR was set in io_error_detect */
15160 	lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
15161 	/* Flush all driver's outstanding I/Os as we are to reset */
15162 	lpfc_sli_flush_io_rings(phba);
15163 	lpfc_offline(phba);
15164 
15165 	/* stop all timers */
15166 	lpfc_stop_hba_timers(phba);
15167 
15168 	lpfc_sli4_queue_destroy(phba);
15169 	/* Disable interrupt and pci device */
15170 	lpfc_sli4_disable_intr(phba);
15171 	pci_disable_device(phba->pcidev);
15172 }
15173 
15174 /**
15175  * lpfc_sli4_prep_dev_for_perm_failure - Prepare SLI4 dev for pci slot disable
15176  * @phba: pointer to lpfc hba data structure.
15177  *
15178  * This routine is called to prepare the SLI4 device for PCI slot permanently
15179  * disabling. It blocks the SCSI transport layer traffic and flushes the FCP
15180  * pending I/Os.
15181  **/
15182 static void
15183 lpfc_sli4_prep_dev_for_perm_failure(struct lpfc_hba *phba)
15184 {
15185 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15186 			"2827 PCI channel permanent disable for failure\n");
15187 
15188 	/* Block all SCSI devices' I/Os on the host */
15189 	lpfc_scsi_dev_block(phba);
15190 
15191 	/* stop all timers */
15192 	lpfc_stop_hba_timers(phba);
15193 
15194 	/* Clean up all driver's outstanding I/Os */
15195 	lpfc_sli_flush_io_rings(phba);
15196 }
15197 
15198 /**
15199  * lpfc_io_error_detected_s4 - Method for handling PCI I/O error to SLI-4 device
15200  * @pdev: pointer to PCI device.
15201  * @state: the current PCI connection state.
15202  *
15203  * This routine is called from the PCI subsystem for error handling to device
15204  * with SLI-4 interface spec. This function is called by the PCI subsystem
15205  * after a PCI bus error affecting this device has been detected. When this
15206  * function is invoked, it will need to stop all the I/Os and interrupt(s)
15207  * to the device. Once that is done, it will return PCI_ERS_RESULT_NEED_RESET
15208  * for the PCI subsystem to perform proper recovery as desired.
15209  *
15210  * Return codes
15211  * 	PCI_ERS_RESULT_NEED_RESET - need to reset before recovery
15212  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15213  **/
15214 static pci_ers_result_t
15215 lpfc_io_error_detected_s4(struct pci_dev *pdev, pci_channel_state_t state)
15216 {
15217 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15218 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15219 	bool hba_pci_err;
15220 
15221 	switch (state) {
15222 	case pci_channel_io_normal:
15223 		/* Non-fatal error, prepare for recovery */
15224 		lpfc_sli4_prep_dev_for_recover(phba);
15225 		return PCI_ERS_RESULT_CAN_RECOVER;
15226 	case pci_channel_io_frozen:
15227 		hba_pci_err = test_and_set_bit(HBA_PCI_ERR, &phba->bit_flags);
15228 		/* Fatal error, prepare for slot reset */
15229 		if (!hba_pci_err)
15230 			lpfc_sli4_prep_dev_for_reset(phba);
15231 		else
15232 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15233 					"2832  Already handling PCI error "
15234 					"state: x%x\n", state);
15235 		return PCI_ERS_RESULT_NEED_RESET;
15236 	case pci_channel_io_perm_failure:
15237 		set_bit(HBA_PCI_ERR, &phba->bit_flags);
15238 		/* Permanent failure, prepare for device down */
15239 		lpfc_sli4_prep_dev_for_perm_failure(phba);
15240 		return PCI_ERS_RESULT_DISCONNECT;
15241 	default:
15242 		hba_pci_err = test_and_set_bit(HBA_PCI_ERR, &phba->bit_flags);
15243 		if (!hba_pci_err)
15244 			lpfc_sli4_prep_dev_for_reset(phba);
15245 		/* Unknown state, prepare and request slot reset */
15246 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15247 				"2825 Unknown PCI error state: x%x\n", state);
15248 		lpfc_sli4_prep_dev_for_reset(phba);
15249 		return PCI_ERS_RESULT_NEED_RESET;
15250 	}
15251 }
15252 
15253 /**
15254  * lpfc_io_slot_reset_s4 - Method for restart PCI SLI-4 device from scratch
15255  * @pdev: pointer to PCI device.
15256  *
15257  * This routine is called from the PCI subsystem for error handling to device
15258  * with SLI-4 interface spec. It is called after PCI bus has been reset to
15259  * restart the PCI card from scratch, as if from a cold-boot. During the
15260  * PCI subsystem error recovery, after the driver returns
15261  * PCI_ERS_RESULT_NEED_RESET, the PCI subsystem will perform proper error
15262  * recovery and then call this routine before calling the .resume method to
15263  * recover the device. This function will initialize the HBA device, enable
15264  * the interrupt, but it will just put the HBA to offline state without
15265  * passing any I/O traffic.
15266  *
15267  * Return codes
15268  * 	PCI_ERS_RESULT_RECOVERED - the device has been recovered
15269  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15270  */
15271 static pci_ers_result_t
15272 lpfc_io_slot_reset_s4(struct pci_dev *pdev)
15273 {
15274 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15275 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15276 	struct lpfc_sli *psli = &phba->sli;
15277 	uint32_t intr_mode;
15278 	bool hba_pci_err;
15279 
15280 	dev_printk(KERN_INFO, &pdev->dev, "recovering from a slot reset.\n");
15281 	if (pci_enable_device_mem(pdev)) {
15282 		printk(KERN_ERR "lpfc: Cannot re-enable "
15283 		       "PCI device after reset.\n");
15284 		return PCI_ERS_RESULT_DISCONNECT;
15285 	}
15286 
15287 	pci_restore_state(pdev);
15288 
15289 	hba_pci_err = test_and_clear_bit(HBA_PCI_ERR, &phba->bit_flags);
15290 	if (!hba_pci_err)
15291 		dev_info(&pdev->dev,
15292 			 "hba_pci_err was not set, recovering slot reset.\n");
15293 	/*
15294 	 * As the new kernel behavior of pci_restore_state() API call clears
15295 	 * device saved_state flag, need to save the restored state again.
15296 	 */
15297 	pci_save_state(pdev);
15298 
15299 	if (pdev->is_busmaster)
15300 		pci_set_master(pdev);
15301 
15302 	spin_lock_irq(&phba->hbalock);
15303 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
15304 	spin_unlock_irq(&phba->hbalock);
15305 
15306 	/* Init cpu_map array */
15307 	lpfc_cpu_map_array_init(phba);
15308 	/* Configure and enable interrupt */
15309 	intr_mode = lpfc_sli4_enable_intr(phba, phba->intr_mode);
15310 	if (intr_mode == LPFC_INTR_ERROR) {
15311 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15312 				"2824 Cannot re-enable interrupt after "
15313 				"slot reset.\n");
15314 		return PCI_ERS_RESULT_DISCONNECT;
15315 	} else
15316 		phba->intr_mode = intr_mode;
15317 	lpfc_cpu_affinity_check(phba, phba->cfg_irq_chann);
15318 
15319 	/* Log the current active interrupt mode */
15320 	lpfc_log_intr_mode(phba, phba->intr_mode);
15321 
15322 	return PCI_ERS_RESULT_RECOVERED;
15323 }
15324 
15325 /**
15326  * lpfc_io_resume_s4 - Method for resuming PCI I/O operation to SLI-4 device
15327  * @pdev: pointer to PCI device
15328  *
15329  * This routine is called from the PCI subsystem for error handling to device
15330  * with SLI-4 interface spec. It is called when kernel error recovery tells
15331  * the lpfc driver that it is ok to resume normal PCI operation after PCI bus
15332  * error recovery. After this call, traffic can start to flow from this device
15333  * again.
15334  **/
15335 static void
15336 lpfc_io_resume_s4(struct pci_dev *pdev)
15337 {
15338 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15339 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15340 
15341 	/*
15342 	 * In case of slot reset, as function reset is performed through
15343 	 * mailbox command which needs DMA to be enabled, this operation
15344 	 * has to be moved to the io resume phase. Taking device offline
15345 	 * will perform the necessary cleanup.
15346 	 */
15347 	if (!(phba->sli.sli_flag & LPFC_SLI_ACTIVE)) {
15348 		/* Perform device reset */
15349 		lpfc_sli_brdrestart(phba);
15350 		/* Bring the device back online */
15351 		lpfc_online(phba);
15352 	}
15353 }
15354 
15355 /**
15356  * lpfc_pci_probe_one - lpfc PCI probe func to reg dev to PCI subsystem
15357  * @pdev: pointer to PCI device
15358  * @pid: pointer to PCI device identifier
15359  *
15360  * This routine is to be registered to the kernel's PCI subsystem. When an
15361  * Emulex HBA device is presented on PCI bus, the kernel PCI subsystem looks
15362  * at PCI device-specific information of the device and driver to see if the
15363  * driver state that it can support this kind of device. If the match is
15364  * successful, the driver core invokes this routine. This routine dispatches
15365  * the action to the proper SLI-3 or SLI-4 device probing routine, which will
15366  * do all the initialization that it needs to do to handle the HBA device
15367  * properly.
15368  *
15369  * Return code
15370  * 	0 - driver can claim the device
15371  * 	negative value - driver can not claim the device
15372  **/
15373 static int
15374 lpfc_pci_probe_one(struct pci_dev *pdev, const struct pci_device_id *pid)
15375 {
15376 	int rc;
15377 	struct lpfc_sli_intf intf;
15378 
15379 	if (pci_read_config_dword(pdev, LPFC_SLI_INTF, &intf.word0))
15380 		return -ENODEV;
15381 
15382 	if ((bf_get(lpfc_sli_intf_valid, &intf) == LPFC_SLI_INTF_VALID) &&
15383 	    (bf_get(lpfc_sli_intf_slirev, &intf) == LPFC_SLI_INTF_REV_SLI4))
15384 		rc = lpfc_pci_probe_one_s4(pdev, pid);
15385 	else
15386 		rc = lpfc_pci_probe_one_s3(pdev, pid);
15387 
15388 	return rc;
15389 }
15390 
15391 /**
15392  * lpfc_pci_remove_one - lpfc PCI func to unreg dev from PCI subsystem
15393  * @pdev: pointer to PCI device
15394  *
15395  * This routine is to be registered to the kernel's PCI subsystem. When an
15396  * Emulex HBA is removed from PCI bus, the driver core invokes this routine.
15397  * This routine dispatches the action to the proper SLI-3 or SLI-4 device
15398  * remove routine, which will perform all the necessary cleanup for the
15399  * device to be removed from the PCI subsystem properly.
15400  **/
15401 static void
15402 lpfc_pci_remove_one(struct pci_dev *pdev)
15403 {
15404 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15405 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15406 
15407 	switch (phba->pci_dev_grp) {
15408 	case LPFC_PCI_DEV_LP:
15409 		lpfc_pci_remove_one_s3(pdev);
15410 		break;
15411 	case LPFC_PCI_DEV_OC:
15412 		lpfc_pci_remove_one_s4(pdev);
15413 		break;
15414 	default:
15415 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15416 				"1424 Invalid PCI device group: 0x%x\n",
15417 				phba->pci_dev_grp);
15418 		break;
15419 	}
15420 	return;
15421 }
15422 
15423 /**
15424  * lpfc_pci_suspend_one - lpfc PCI func to suspend dev for power management
15425  * @dev: pointer to device
15426  *
15427  * This routine is to be registered to the kernel's PCI subsystem to support
15428  * system Power Management (PM). When PM invokes this method, it dispatches
15429  * the action to the proper SLI-3 or SLI-4 device suspend routine, which will
15430  * suspend the device.
15431  *
15432  * Return code
15433  * 	0 - driver suspended the device
15434  * 	Error otherwise
15435  **/
15436 static int __maybe_unused
15437 lpfc_pci_suspend_one(struct device *dev)
15438 {
15439 	struct Scsi_Host *shost = dev_get_drvdata(dev);
15440 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15441 	int rc = -ENODEV;
15442 
15443 	switch (phba->pci_dev_grp) {
15444 	case LPFC_PCI_DEV_LP:
15445 		rc = lpfc_pci_suspend_one_s3(dev);
15446 		break;
15447 	case LPFC_PCI_DEV_OC:
15448 		rc = lpfc_pci_suspend_one_s4(dev);
15449 		break;
15450 	default:
15451 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15452 				"1425 Invalid PCI device group: 0x%x\n",
15453 				phba->pci_dev_grp);
15454 		break;
15455 	}
15456 	return rc;
15457 }
15458 
15459 /**
15460  * lpfc_pci_resume_one - lpfc PCI func to resume dev for power management
15461  * @dev: pointer to device
15462  *
15463  * This routine is to be registered to the kernel's PCI subsystem to support
15464  * system Power Management (PM). When PM invokes this method, it dispatches
15465  * the action to the proper SLI-3 or SLI-4 device resume routine, which will
15466  * resume the device.
15467  *
15468  * Return code
15469  * 	0 - driver suspended the device
15470  * 	Error otherwise
15471  **/
15472 static int __maybe_unused
15473 lpfc_pci_resume_one(struct device *dev)
15474 {
15475 	struct Scsi_Host *shost = dev_get_drvdata(dev);
15476 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15477 	int rc = -ENODEV;
15478 
15479 	switch (phba->pci_dev_grp) {
15480 	case LPFC_PCI_DEV_LP:
15481 		rc = lpfc_pci_resume_one_s3(dev);
15482 		break;
15483 	case LPFC_PCI_DEV_OC:
15484 		rc = lpfc_pci_resume_one_s4(dev);
15485 		break;
15486 	default:
15487 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15488 				"1426 Invalid PCI device group: 0x%x\n",
15489 				phba->pci_dev_grp);
15490 		break;
15491 	}
15492 	return rc;
15493 }
15494 
15495 /**
15496  * lpfc_io_error_detected - lpfc method for handling PCI I/O error
15497  * @pdev: pointer to PCI device.
15498  * @state: the current PCI connection state.
15499  *
15500  * This routine is registered to the PCI subsystem for error handling. This
15501  * function is called by the PCI subsystem after a PCI bus error affecting
15502  * this device has been detected. When this routine is invoked, it dispatches
15503  * the action to the proper SLI-3 or SLI-4 device error detected handling
15504  * routine, which will perform the proper error detected operation.
15505  *
15506  * Return codes
15507  * 	PCI_ERS_RESULT_NEED_RESET - need to reset before recovery
15508  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15509  **/
15510 static pci_ers_result_t
15511 lpfc_io_error_detected(struct pci_dev *pdev, pci_channel_state_t state)
15512 {
15513 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15514 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15515 	pci_ers_result_t rc = PCI_ERS_RESULT_DISCONNECT;
15516 
15517 	if (phba->link_state == LPFC_HBA_ERROR &&
15518 	    test_bit(HBA_IOQ_FLUSH, &phba->hba_flag))
15519 		return PCI_ERS_RESULT_NEED_RESET;
15520 
15521 	switch (phba->pci_dev_grp) {
15522 	case LPFC_PCI_DEV_LP:
15523 		rc = lpfc_io_error_detected_s3(pdev, state);
15524 		break;
15525 	case LPFC_PCI_DEV_OC:
15526 		rc = lpfc_io_error_detected_s4(pdev, state);
15527 		break;
15528 	default:
15529 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15530 				"1427 Invalid PCI device group: 0x%x\n",
15531 				phba->pci_dev_grp);
15532 		break;
15533 	}
15534 	return rc;
15535 }
15536 
15537 /**
15538  * lpfc_io_slot_reset - lpfc method for restart PCI dev from scratch
15539  * @pdev: pointer to PCI device.
15540  *
15541  * This routine is registered to the PCI subsystem for error handling. This
15542  * function is called after PCI bus has been reset to restart the PCI card
15543  * from scratch, as if from a cold-boot. When this routine is invoked, it
15544  * dispatches the action to the proper SLI-3 or SLI-4 device reset handling
15545  * routine, which will perform the proper device reset.
15546  *
15547  * Return codes
15548  * 	PCI_ERS_RESULT_RECOVERED - the device has been recovered
15549  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15550  **/
15551 static pci_ers_result_t
15552 lpfc_io_slot_reset(struct pci_dev *pdev)
15553 {
15554 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15555 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15556 	pci_ers_result_t rc = PCI_ERS_RESULT_DISCONNECT;
15557 
15558 	switch (phba->pci_dev_grp) {
15559 	case LPFC_PCI_DEV_LP:
15560 		rc = lpfc_io_slot_reset_s3(pdev);
15561 		break;
15562 	case LPFC_PCI_DEV_OC:
15563 		rc = lpfc_io_slot_reset_s4(pdev);
15564 		break;
15565 	default:
15566 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15567 				"1428 Invalid PCI device group: 0x%x\n",
15568 				phba->pci_dev_grp);
15569 		break;
15570 	}
15571 	return rc;
15572 }
15573 
15574 /**
15575  * lpfc_io_resume - lpfc method for resuming PCI I/O operation
15576  * @pdev: pointer to PCI device
15577  *
15578  * This routine is registered to the PCI subsystem for error handling. It
15579  * is called when kernel error recovery tells the lpfc driver that it is
15580  * OK to resume normal PCI operation after PCI bus error recovery. When
15581  * this routine is invoked, it dispatches the action to the proper SLI-3
15582  * or SLI-4 device io_resume routine, which will resume the device operation.
15583  **/
15584 static void
15585 lpfc_io_resume(struct pci_dev *pdev)
15586 {
15587 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15588 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15589 
15590 	switch (phba->pci_dev_grp) {
15591 	case LPFC_PCI_DEV_LP:
15592 		lpfc_io_resume_s3(pdev);
15593 		break;
15594 	case LPFC_PCI_DEV_OC:
15595 		lpfc_io_resume_s4(pdev);
15596 		break;
15597 	default:
15598 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15599 				"1429 Invalid PCI device group: 0x%x\n",
15600 				phba->pci_dev_grp);
15601 		break;
15602 	}
15603 	return;
15604 }
15605 
15606 /**
15607  * lpfc_sli4_oas_verify - Verify OAS is supported by this adapter
15608  * @phba: pointer to lpfc hba data structure.
15609  *
15610  * This routine checks to see if OAS is supported for this adapter. If
15611  * supported, the configure Flash Optimized Fabric flag is set.  Otherwise,
15612  * the enable oas flag is cleared and the pool created for OAS device data
15613  * is destroyed.
15614  *
15615  **/
15616 static void
15617 lpfc_sli4_oas_verify(struct lpfc_hba *phba)
15618 {
15619 
15620 	if (!phba->cfg_EnableXLane)
15621 		return;
15622 
15623 	if (phba->sli4_hba.pc_sli4_params.oas_supported) {
15624 		phba->cfg_fof = 1;
15625 	} else {
15626 		phba->cfg_fof = 0;
15627 		mempool_destroy(phba->device_data_mem_pool);
15628 		phba->device_data_mem_pool = NULL;
15629 	}
15630 
15631 	return;
15632 }
15633 
15634 /**
15635  * lpfc_sli4_ras_init - Verify RAS-FW log is supported by this adapter
15636  * @phba: pointer to lpfc hba data structure.
15637  *
15638  * This routine checks to see if RAS is supported by the adapter. Check the
15639  * function through which RAS support enablement is to be done.
15640  **/
15641 void
15642 lpfc_sli4_ras_init(struct lpfc_hba *phba)
15643 {
15644 	/* if ASIC_GEN_NUM >= 0xC) */
15645 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
15646 		    LPFC_SLI_INTF_IF_TYPE_6) ||
15647 	    (bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf) ==
15648 		    LPFC_SLI_INTF_FAMILY_G6)) {
15649 		phba->ras_fwlog.ras_hwsupport = true;
15650 		if (phba->cfg_ras_fwlog_func == PCI_FUNC(phba->pcidev->devfn) &&
15651 		    phba->cfg_ras_fwlog_buffsize)
15652 			phba->ras_fwlog.ras_enabled = true;
15653 		else
15654 			phba->ras_fwlog.ras_enabled = false;
15655 	} else {
15656 		phba->ras_fwlog.ras_hwsupport = false;
15657 	}
15658 }
15659 
15660 
15661 MODULE_DEVICE_TABLE(pci, lpfc_id_table);
15662 
15663 static const struct pci_error_handlers lpfc_err_handler = {
15664 	.error_detected = lpfc_io_error_detected,
15665 	.slot_reset = lpfc_io_slot_reset,
15666 	.resume = lpfc_io_resume,
15667 };
15668 
15669 static SIMPLE_DEV_PM_OPS(lpfc_pci_pm_ops_one,
15670 			 lpfc_pci_suspend_one,
15671 			 lpfc_pci_resume_one);
15672 
15673 static struct pci_driver lpfc_driver = {
15674 	.name		= LPFC_DRIVER_NAME,
15675 	.id_table	= lpfc_id_table,
15676 	.probe		= lpfc_pci_probe_one,
15677 	.remove		= lpfc_pci_remove_one,
15678 	.shutdown	= lpfc_pci_remove_one,
15679 	.driver.pm	= &lpfc_pci_pm_ops_one,
15680 	.err_handler    = &lpfc_err_handler,
15681 };
15682 
15683 static const struct file_operations lpfc_mgmt_fop = {
15684 	.owner = THIS_MODULE,
15685 };
15686 
15687 static struct miscdevice lpfc_mgmt_dev = {
15688 	.minor = MISC_DYNAMIC_MINOR,
15689 	.name = "lpfcmgmt",
15690 	.fops = &lpfc_mgmt_fop,
15691 };
15692 
15693 /**
15694  * lpfc_init - lpfc module initialization routine
15695  *
15696  * This routine is to be invoked when the lpfc module is loaded into the
15697  * kernel. The special kernel macro module_init() is used to indicate the
15698  * role of this routine to the kernel as lpfc module entry point.
15699  *
15700  * Return codes
15701  *   0 - successful
15702  *   -ENOMEM - FC attach transport failed
15703  *   all others - failed
15704  */
15705 static int __init
15706 lpfc_init(void)
15707 {
15708 	int error = 0;
15709 
15710 	pr_info(LPFC_MODULE_DESC "\n");
15711 	pr_info(LPFC_COPYRIGHT "\n");
15712 
15713 	error = misc_register(&lpfc_mgmt_dev);
15714 	if (error)
15715 		printk(KERN_ERR "Could not register lpfcmgmt device, "
15716 			"misc_register returned with status %d", error);
15717 
15718 	error = -ENOMEM;
15719 	lpfc_transport_functions.vport_create = lpfc_vport_create;
15720 	lpfc_transport_functions.vport_delete = lpfc_vport_delete;
15721 	lpfc_transport_template =
15722 				fc_attach_transport(&lpfc_transport_functions);
15723 	if (lpfc_transport_template == NULL)
15724 		goto unregister;
15725 	lpfc_vport_transport_template =
15726 		fc_attach_transport(&lpfc_vport_transport_functions);
15727 	if (lpfc_vport_transport_template == NULL) {
15728 		fc_release_transport(lpfc_transport_template);
15729 		goto unregister;
15730 	}
15731 	lpfc_wqe_cmd_template();
15732 	lpfc_nvmet_cmd_template();
15733 
15734 	/* Initialize in case vector mapping is needed */
15735 	lpfc_present_cpu = num_present_cpus();
15736 
15737 	lpfc_pldv_detect = false;
15738 
15739 	error = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN,
15740 					"lpfc/sli4:online",
15741 					lpfc_cpu_online, lpfc_cpu_offline);
15742 	if (error < 0)
15743 		goto cpuhp_failure;
15744 	lpfc_cpuhp_state = error;
15745 
15746 	error = pci_register_driver(&lpfc_driver);
15747 	if (error)
15748 		goto unwind;
15749 
15750 	return error;
15751 
15752 unwind:
15753 	cpuhp_remove_multi_state(lpfc_cpuhp_state);
15754 cpuhp_failure:
15755 	fc_release_transport(lpfc_transport_template);
15756 	fc_release_transport(lpfc_vport_transport_template);
15757 unregister:
15758 	misc_deregister(&lpfc_mgmt_dev);
15759 
15760 	return error;
15761 }
15762 
15763 void lpfc_dmp_dbg(struct lpfc_hba *phba)
15764 {
15765 	unsigned int start_idx;
15766 	unsigned int dbg_cnt;
15767 	unsigned int temp_idx;
15768 	int i;
15769 	int j = 0;
15770 	unsigned long rem_nsec;
15771 
15772 	if (atomic_cmpxchg(&phba->dbg_log_dmping, 0, 1) != 0)
15773 		return;
15774 
15775 	start_idx = (unsigned int)atomic_read(&phba->dbg_log_idx) % DBG_LOG_SZ;
15776 	dbg_cnt = (unsigned int)atomic_read(&phba->dbg_log_cnt);
15777 	if (!dbg_cnt)
15778 		goto out;
15779 	temp_idx = start_idx;
15780 	if (dbg_cnt >= DBG_LOG_SZ) {
15781 		dbg_cnt = DBG_LOG_SZ;
15782 		temp_idx -= 1;
15783 	} else {
15784 		if ((start_idx + dbg_cnt) > (DBG_LOG_SZ - 1)) {
15785 			temp_idx = (start_idx + dbg_cnt) % DBG_LOG_SZ;
15786 		} else {
15787 			if (start_idx < dbg_cnt)
15788 				start_idx = DBG_LOG_SZ - (dbg_cnt - start_idx);
15789 			else
15790 				start_idx -= dbg_cnt;
15791 		}
15792 	}
15793 	dev_info(&phba->pcidev->dev, "start %d end %d cnt %d\n",
15794 		 start_idx, temp_idx, dbg_cnt);
15795 
15796 	for (i = 0; i < dbg_cnt; i++) {
15797 		if ((start_idx + i) < DBG_LOG_SZ)
15798 			temp_idx = (start_idx + i) % DBG_LOG_SZ;
15799 		else
15800 			temp_idx = j++;
15801 		rem_nsec = do_div(phba->dbg_log[temp_idx].t_ns, NSEC_PER_SEC);
15802 		dev_info(&phba->pcidev->dev, "%d: [%5lu.%06lu] %s",
15803 			 temp_idx,
15804 			 (unsigned long)phba->dbg_log[temp_idx].t_ns,
15805 			 rem_nsec / 1000,
15806 			 phba->dbg_log[temp_idx].log);
15807 	}
15808 out:
15809 	atomic_set(&phba->dbg_log_cnt, 0);
15810 	atomic_set(&phba->dbg_log_dmping, 0);
15811 }
15812 
15813 __printf(2, 3)
15814 void lpfc_dbg_print(struct lpfc_hba *phba, const char *fmt, ...)
15815 {
15816 	unsigned int idx;
15817 	va_list args;
15818 	int dbg_dmping = atomic_read(&phba->dbg_log_dmping);
15819 	struct va_format vaf;
15820 
15821 
15822 	va_start(args, fmt);
15823 	if (unlikely(dbg_dmping)) {
15824 		vaf.fmt = fmt;
15825 		vaf.va = &args;
15826 		dev_info(&phba->pcidev->dev, "%pV", &vaf);
15827 		va_end(args);
15828 		return;
15829 	}
15830 	idx = (unsigned int)atomic_fetch_add(1, &phba->dbg_log_idx) %
15831 		DBG_LOG_SZ;
15832 
15833 	atomic_inc(&phba->dbg_log_cnt);
15834 
15835 	vscnprintf(phba->dbg_log[idx].log,
15836 		   sizeof(phba->dbg_log[idx].log), fmt, args);
15837 	va_end(args);
15838 
15839 	phba->dbg_log[idx].t_ns = local_clock();
15840 }
15841 
15842 /**
15843  * lpfc_exit - lpfc module removal routine
15844  *
15845  * This routine is invoked when the lpfc module is removed from the kernel.
15846  * The special kernel macro module_exit() is used to indicate the role of
15847  * this routine to the kernel as lpfc module exit point.
15848  */
15849 static void __exit
15850 lpfc_exit(void)
15851 {
15852 	misc_deregister(&lpfc_mgmt_dev);
15853 	pci_unregister_driver(&lpfc_driver);
15854 	cpuhp_remove_multi_state(lpfc_cpuhp_state);
15855 	fc_release_transport(lpfc_transport_template);
15856 	fc_release_transport(lpfc_vport_transport_template);
15857 	idr_destroy(&lpfc_hba_index);
15858 }
15859 
15860 module_init(lpfc_init);
15861 module_exit(lpfc_exit);
15862 MODULE_LICENSE("GPL");
15863 MODULE_DESCRIPTION(LPFC_MODULE_DESC);
15864 MODULE_AUTHOR("Broadcom");
15865 MODULE_VERSION("0:" LPFC_DRIVER_VERSION);
15866