xref: /linux/drivers/scsi/lpfc/lpfc_init.c (revision 674b0ddb7586a192612442c3aed9cf523faeed7a)
1 /*******************************************************************
2  * This file is part of the Emulex Linux Device Driver for         *
3  * Fibre Channel Host Bus Adapters.                                *
4  * Copyright (C) 2017-2025 Broadcom. All Rights Reserved. The term *
5  * “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.  *
6  * Copyright (C) 2004-2016 Emulex.  All rights reserved.           *
7  * EMULEX and SLI are trademarks of Emulex.                        *
8  * www.broadcom.com                                                *
9  * Portions Copyright (C) 2004-2005 Christoph Hellwig              *
10  *                                                                 *
11  * This program is free software; you can redistribute it and/or   *
12  * modify it under the terms of version 2 of the GNU General       *
13  * Public License as published by the Free Software Foundation.    *
14  * This program is distributed in the hope that it will be useful. *
15  * ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND          *
16  * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,  *
17  * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE      *
18  * DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD *
19  * TO BE LEGALLY INVALID.  See the GNU General Public License for  *
20  * more details, a copy of which can be found in the file COPYING  *
21  * included with this package.                                     *
22  *******************************************************************/
23 
24 #include <linux/blkdev.h>
25 #include <linux/delay.h>
26 #include <linux/dma-mapping.h>
27 #include <linux/idr.h>
28 #include <linux/interrupt.h>
29 #include <linux/module.h>
30 #include <linux/kthread.h>
31 #include <linux/pci.h>
32 #include <linux/spinlock.h>
33 #include <linux/sched/clock.h>
34 #include <linux/ctype.h>
35 #include <linux/slab.h>
36 #include <linux/firmware.h>
37 #include <linux/miscdevice.h>
38 #include <linux/percpu.h>
39 #include <linux/irq.h>
40 #include <linux/bitops.h>
41 #include <linux/crash_dump.h>
42 #include <linux/cpu.h>
43 #include <linux/cpuhotplug.h>
44 
45 #include <scsi/scsi.h>
46 #include <scsi/scsi_device.h>
47 #include <scsi/scsi_host.h>
48 #include <scsi/scsi_transport_fc.h>
49 #include <scsi/scsi_tcq.h>
50 #include <scsi/fc/fc_fs.h>
51 
52 #include "lpfc_hw4.h"
53 #include "lpfc_hw.h"
54 #include "lpfc_sli.h"
55 #include "lpfc_sli4.h"
56 #include "lpfc_nl.h"
57 #include "lpfc_disc.h"
58 #include "lpfc.h"
59 #include "lpfc_scsi.h"
60 #include "lpfc_nvme.h"
61 #include "lpfc_logmsg.h"
62 #include "lpfc_crtn.h"
63 #include "lpfc_vport.h"
64 #include "lpfc_version.h"
65 #include "lpfc_ids.h"
66 
67 static enum cpuhp_state lpfc_cpuhp_state;
68 /* Used when mapping IRQ vectors in a driver centric manner */
69 static uint32_t lpfc_present_cpu;
70 static bool lpfc_pldv_detect;
71 
72 static void __lpfc_cpuhp_remove(struct lpfc_hba *phba);
73 static void lpfc_cpuhp_remove(struct lpfc_hba *phba);
74 static void lpfc_cpuhp_add(struct lpfc_hba *phba);
75 static void lpfc_get_hba_model_desc(struct lpfc_hba *, uint8_t *, uint8_t *);
76 static int lpfc_post_rcv_buf(struct lpfc_hba *);
77 static int lpfc_sli4_queue_verify(struct lpfc_hba *);
78 static int lpfc_create_bootstrap_mbox(struct lpfc_hba *);
79 static int lpfc_setup_endian_order(struct lpfc_hba *);
80 static void lpfc_destroy_bootstrap_mbox(struct lpfc_hba *);
81 static void lpfc_free_els_sgl_list(struct lpfc_hba *);
82 static void lpfc_free_nvmet_sgl_list(struct lpfc_hba *);
83 static void lpfc_init_sgl_list(struct lpfc_hba *);
84 static int lpfc_init_active_sgl_array(struct lpfc_hba *);
85 static void lpfc_free_active_sgl(struct lpfc_hba *);
86 static int lpfc_hba_down_post_s3(struct lpfc_hba *phba);
87 static int lpfc_hba_down_post_s4(struct lpfc_hba *phba);
88 static int lpfc_sli4_cq_event_pool_create(struct lpfc_hba *);
89 static void lpfc_sli4_cq_event_pool_destroy(struct lpfc_hba *);
90 static void lpfc_sli4_cq_event_release_all(struct lpfc_hba *);
91 static void lpfc_sli4_disable_intr(struct lpfc_hba *);
92 static uint32_t lpfc_sli4_enable_intr(struct lpfc_hba *, uint32_t);
93 static void lpfc_sli4_oas_verify(struct lpfc_hba *phba);
94 static uint16_t lpfc_find_cpu_handle(struct lpfc_hba *, uint16_t, int);
95 static void lpfc_setup_bg(struct lpfc_hba *, struct Scsi_Host *);
96 static int lpfc_sli4_cgn_parm_chg_evt(struct lpfc_hba *);
97 static void lpfc_sli4_async_cmstat_evt(struct lpfc_hba *phba);
98 static void lpfc_sli4_prep_dev_for_reset(struct lpfc_hba *phba);
99 
100 static struct scsi_transport_template *lpfc_transport_template = NULL;
101 static struct scsi_transport_template *lpfc_vport_transport_template = NULL;
102 static DEFINE_IDR(lpfc_hba_index);
103 #define LPFC_NVMET_BUF_POST 254
104 static int lpfc_vmid_res_alloc(struct lpfc_hba *phba, struct lpfc_vport *vport);
105 static void lpfc_cgn_update_tstamp(struct lpfc_hba *phba, struct lpfc_cgn_ts *ts);
106 
107 /**
108  * lpfc_config_port_prep - Perform lpfc initialization prior to config port
109  * @phba: pointer to lpfc hba data structure.
110  *
111  * This routine will do LPFC initialization prior to issuing the CONFIG_PORT
112  * mailbox command. It retrieves the revision information from the HBA and
113  * collects the Vital Product Data (VPD) about the HBA for preparing the
114  * configuration of the HBA.
115  *
116  * Return codes:
117  *   0 - success.
118  *   -ERESTART - requests the SLI layer to reset the HBA and try again.
119  *   Any other value - indicates an error.
120  **/
121 int
122 lpfc_config_port_prep(struct lpfc_hba *phba)
123 {
124 	lpfc_vpd_t *vp = &phba->vpd;
125 	int i = 0, rc;
126 	LPFC_MBOXQ_t *pmb;
127 	MAILBOX_t *mb;
128 	char *lpfc_vpd_data = NULL;
129 	uint16_t offset = 0;
130 	static char licensed[56] =
131 		    "key unlock for use with gnu public licensed code only\0";
132 	static int init_key = 1;
133 
134 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
135 	if (!pmb) {
136 		phba->link_state = LPFC_HBA_ERROR;
137 		return -ENOMEM;
138 	}
139 
140 	mb = &pmb->u.mb;
141 	phba->link_state = LPFC_INIT_MBX_CMDS;
142 
143 	if (lpfc_is_LC_HBA(phba->pcidev->device)) {
144 		if (init_key) {
145 			uint32_t *ptext = (uint32_t *) licensed;
146 
147 			for (i = 0; i < 56; i += sizeof (uint32_t), ptext++)
148 				*ptext = cpu_to_be32(*ptext);
149 			init_key = 0;
150 		}
151 
152 		lpfc_read_nv(phba, pmb);
153 		memset((char*)mb->un.varRDnvp.rsvd3, 0,
154 			sizeof (mb->un.varRDnvp.rsvd3));
155 		memcpy((char*)mb->un.varRDnvp.rsvd3, licensed,
156 			 sizeof (licensed));
157 
158 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
159 
160 		if (rc != MBX_SUCCESS) {
161 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
162 					"0324 Config Port initialization "
163 					"error, mbxCmd x%x READ_NVPARM, "
164 					"mbxStatus x%x\n",
165 					mb->mbxCommand, mb->mbxStatus);
166 			mempool_free(pmb, phba->mbox_mem_pool);
167 			return -ERESTART;
168 		}
169 		memcpy(phba->wwnn, (char *)mb->un.varRDnvp.nodename,
170 		       sizeof(phba->wwnn));
171 		memcpy(phba->wwpn, (char *)mb->un.varRDnvp.portname,
172 		       sizeof(phba->wwpn));
173 	}
174 
175 	/*
176 	 * Clear all option bits except LPFC_SLI3_BG_ENABLED,
177 	 * which was already set in lpfc_get_cfgparam()
178 	 */
179 	phba->sli3_options &= (uint32_t)LPFC_SLI3_BG_ENABLED;
180 
181 	/* Setup and issue mailbox READ REV command */
182 	lpfc_read_rev(phba, pmb);
183 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
184 	if (rc != MBX_SUCCESS) {
185 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
186 				"0439 Adapter failed to init, mbxCmd x%x "
187 				"READ_REV, mbxStatus x%x\n",
188 				mb->mbxCommand, mb->mbxStatus);
189 		mempool_free( pmb, phba->mbox_mem_pool);
190 		return -ERESTART;
191 	}
192 
193 
194 	/*
195 	 * The value of rr must be 1 since the driver set the cv field to 1.
196 	 * This setting requires the FW to set all revision fields.
197 	 */
198 	if (mb->un.varRdRev.rr == 0) {
199 		vp->rev.rBit = 0;
200 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
201 				"0440 Adapter failed to init, READ_REV has "
202 				"missing revision information.\n");
203 		mempool_free(pmb, phba->mbox_mem_pool);
204 		return -ERESTART;
205 	}
206 
207 	if (phba->sli_rev == 3 && !mb->un.varRdRev.v3rsp) {
208 		mempool_free(pmb, phba->mbox_mem_pool);
209 		return -EINVAL;
210 	}
211 
212 	/* Save information as VPD data */
213 	vp->rev.rBit = 1;
214 	memcpy(&vp->sli3Feat, &mb->un.varRdRev.sli3Feat, sizeof(uint32_t));
215 	vp->rev.sli1FwRev = mb->un.varRdRev.sli1FwRev;
216 	memcpy(vp->rev.sli1FwName, (char*) mb->un.varRdRev.sli1FwName, 16);
217 	vp->rev.sli2FwRev = mb->un.varRdRev.sli2FwRev;
218 	memcpy(vp->rev.sli2FwName, (char *) mb->un.varRdRev.sli2FwName, 16);
219 	vp->rev.biuRev = mb->un.varRdRev.biuRev;
220 	vp->rev.smRev = mb->un.varRdRev.smRev;
221 	vp->rev.smFwRev = mb->un.varRdRev.un.smFwRev;
222 	vp->rev.endecRev = mb->un.varRdRev.endecRev;
223 	vp->rev.fcphHigh = mb->un.varRdRev.fcphHigh;
224 	vp->rev.fcphLow = mb->un.varRdRev.fcphLow;
225 	vp->rev.feaLevelHigh = mb->un.varRdRev.feaLevelHigh;
226 	vp->rev.feaLevelLow = mb->un.varRdRev.feaLevelLow;
227 	vp->rev.postKernRev = mb->un.varRdRev.postKernRev;
228 	vp->rev.opFwRev = mb->un.varRdRev.opFwRev;
229 
230 	/* If the sli feature level is less then 9, we must
231 	 * tear down all RPIs and VPIs on link down if NPIV
232 	 * is enabled.
233 	 */
234 	if (vp->rev.feaLevelHigh < 9)
235 		phba->sli3_options |= LPFC_SLI3_VPORT_TEARDOWN;
236 
237 	if (lpfc_is_LC_HBA(phba->pcidev->device))
238 		memcpy(phba->RandomData, (char *)&mb->un.varWords[24],
239 						sizeof (phba->RandomData));
240 
241 	/* Get adapter VPD information */
242 	lpfc_vpd_data = kmalloc(DMP_VPD_SIZE, GFP_KERNEL);
243 	if (!lpfc_vpd_data)
244 		goto out_free_mbox;
245 	do {
246 		lpfc_dump_mem(phba, pmb, offset, DMP_REGION_VPD);
247 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
248 
249 		if (rc != MBX_SUCCESS) {
250 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
251 					"0441 VPD not present on adapter, "
252 					"mbxCmd x%x DUMP VPD, mbxStatus x%x\n",
253 					mb->mbxCommand, mb->mbxStatus);
254 			mb->un.varDmp.word_cnt = 0;
255 		}
256 		/* dump mem may return a zero when finished or we got a
257 		 * mailbox error, either way we are done.
258 		 */
259 		if (mb->un.varDmp.word_cnt == 0)
260 			break;
261 
262 		if (mb->un.varDmp.word_cnt > DMP_VPD_SIZE - offset)
263 			mb->un.varDmp.word_cnt = DMP_VPD_SIZE - offset;
264 		lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
265 				      lpfc_vpd_data + offset,
266 				      mb->un.varDmp.word_cnt);
267 		offset += mb->un.varDmp.word_cnt;
268 	} while (mb->un.varDmp.word_cnt && offset < DMP_VPD_SIZE);
269 
270 	lpfc_parse_vpd(phba, lpfc_vpd_data, offset);
271 
272 	kfree(lpfc_vpd_data);
273 out_free_mbox:
274 	mempool_free(pmb, phba->mbox_mem_pool);
275 	return 0;
276 }
277 
278 /**
279  * lpfc_config_async_cmpl - Completion handler for config async event mbox cmd
280  * @phba: pointer to lpfc hba data structure.
281  * @pmboxq: pointer to the driver internal queue element for mailbox command.
282  *
283  * This is the completion handler for driver's configuring asynchronous event
284  * mailbox command to the device. If the mailbox command returns successfully,
285  * it will set internal async event support flag to 1; otherwise, it will
286  * set internal async event support flag to 0.
287  **/
288 static void
289 lpfc_config_async_cmpl(struct lpfc_hba * phba, LPFC_MBOXQ_t * pmboxq)
290 {
291 	if (pmboxq->u.mb.mbxStatus == MBX_SUCCESS)
292 		phba->temp_sensor_support = 1;
293 	else
294 		phba->temp_sensor_support = 0;
295 	mempool_free(pmboxq, phba->mbox_mem_pool);
296 	return;
297 }
298 
299 /**
300  * lpfc_dump_wakeup_param_cmpl - dump memory mailbox command completion handler
301  * @phba: pointer to lpfc hba data structure.
302  * @pmboxq: pointer to the driver internal queue element for mailbox command.
303  *
304  * This is the completion handler for dump mailbox command for getting
305  * wake up parameters. When this command complete, the response contain
306  * Option rom version of the HBA. This function translate the version number
307  * into a human readable string and store it in OptionROMVersion.
308  **/
309 static void
310 lpfc_dump_wakeup_param_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
311 {
312 	struct prog_id *prg;
313 	uint32_t prog_id_word;
314 	char dist = ' ';
315 	/* character array used for decoding dist type. */
316 	char dist_char[] = "nabx";
317 
318 	if (pmboxq->u.mb.mbxStatus != MBX_SUCCESS) {
319 		mempool_free(pmboxq, phba->mbox_mem_pool);
320 		return;
321 	}
322 
323 	prg = (struct prog_id *) &prog_id_word;
324 
325 	/* word 7 contain option rom version */
326 	prog_id_word = pmboxq->u.mb.un.varWords[7];
327 
328 	/* Decode the Option rom version word to a readable string */
329 	dist = dist_char[prg->dist];
330 
331 	if ((prg->dist == 3) && (prg->num == 0))
332 		snprintf(phba->OptionROMVersion, 32, "%d.%d%d",
333 			prg->ver, prg->rev, prg->lev);
334 	else
335 		snprintf(phba->OptionROMVersion, 32, "%d.%d%d%c%d",
336 			prg->ver, prg->rev, prg->lev,
337 			dist, prg->num);
338 	mempool_free(pmboxq, phba->mbox_mem_pool);
339 	return;
340 }
341 
342 /**
343  * lpfc_update_vport_wwn - Updates the fc_nodename, fc_portname,
344  * @vport: pointer to lpfc vport data structure.
345  *
346  *
347  * Return codes
348  *   None.
349  **/
350 void
351 lpfc_update_vport_wwn(struct lpfc_vport *vport)
352 {
353 	struct lpfc_hba *phba = vport->phba;
354 
355 	/*
356 	 * If the name is empty or there exists a soft name
357 	 * then copy the service params name, otherwise use the fc name
358 	 */
359 	if (vport->fc_nodename.u.wwn[0] == 0)
360 		memcpy(&vport->fc_nodename, &vport->fc_sparam.nodeName,
361 			sizeof(struct lpfc_name));
362 	else
363 		memcpy(&vport->fc_sparam.nodeName, &vport->fc_nodename,
364 			sizeof(struct lpfc_name));
365 
366 	/*
367 	 * If the port name has changed, then set the Param changes flag
368 	 * to unreg the login
369 	 */
370 	if (vport->fc_portname.u.wwn[0] != 0 &&
371 		memcmp(&vport->fc_portname, &vport->fc_sparam.portName,
372 		       sizeof(struct lpfc_name))) {
373 		vport->vport_flag |= FAWWPN_PARAM_CHG;
374 
375 		if (phba->sli_rev == LPFC_SLI_REV4 &&
376 		    vport->port_type == LPFC_PHYSICAL_PORT &&
377 		    phba->sli4_hba.fawwpn_flag & LPFC_FAWWPN_FABRIC) {
378 			if (!(phba->sli4_hba.fawwpn_flag & LPFC_FAWWPN_CONFIG))
379 				phba->sli4_hba.fawwpn_flag &=
380 						~LPFC_FAWWPN_FABRIC;
381 			lpfc_printf_log(phba, KERN_INFO,
382 					LOG_SLI | LOG_DISCOVERY | LOG_ELS,
383 					"2701 FA-PWWN change WWPN from %llx to "
384 					"%llx: vflag x%x fawwpn_flag x%x\n",
385 					wwn_to_u64(vport->fc_portname.u.wwn),
386 					wwn_to_u64
387 					   (vport->fc_sparam.portName.u.wwn),
388 					vport->vport_flag,
389 					phba->sli4_hba.fawwpn_flag);
390 			memcpy(&vport->fc_portname, &vport->fc_sparam.portName,
391 			       sizeof(struct lpfc_name));
392 		}
393 	}
394 
395 	if (vport->fc_portname.u.wwn[0] == 0)
396 		memcpy(&vport->fc_portname, &vport->fc_sparam.portName,
397 		       sizeof(struct lpfc_name));
398 	else
399 		memcpy(&vport->fc_sparam.portName, &vport->fc_portname,
400 		       sizeof(struct lpfc_name));
401 }
402 
403 /**
404  * lpfc_config_port_post - Perform lpfc initialization after config port
405  * @phba: pointer to lpfc hba data structure.
406  *
407  * This routine will do LPFC initialization after the CONFIG_PORT mailbox
408  * command call. It performs all internal resource and state setups on the
409  * port: post IOCB buffers, enable appropriate host interrupt attentions,
410  * ELS ring timers, etc.
411  *
412  * Return codes
413  *   0 - success.
414  *   Any other value - error.
415  **/
416 int
417 lpfc_config_port_post(struct lpfc_hba *phba)
418 {
419 	struct lpfc_vport *vport = phba->pport;
420 	struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
421 	LPFC_MBOXQ_t *pmb;
422 	MAILBOX_t *mb;
423 	struct lpfc_dmabuf *mp;
424 	struct lpfc_sli *psli = &phba->sli;
425 	uint32_t status, timeout;
426 	int i, j;
427 	int rc;
428 
429 	spin_lock_irq(&phba->hbalock);
430 	/*
431 	 * If the Config port completed correctly the HBA is not
432 	 * over heated any more.
433 	 */
434 	if (phba->over_temp_state == HBA_OVER_TEMP)
435 		phba->over_temp_state = HBA_NORMAL_TEMP;
436 	spin_unlock_irq(&phba->hbalock);
437 
438 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
439 	if (!pmb) {
440 		phba->link_state = LPFC_HBA_ERROR;
441 		return -ENOMEM;
442 	}
443 	mb = &pmb->u.mb;
444 
445 	/* Get login parameters for NID.  */
446 	rc = lpfc_read_sparam(phba, pmb, 0);
447 	if (rc) {
448 		mempool_free(pmb, phba->mbox_mem_pool);
449 		return -ENOMEM;
450 	}
451 
452 	pmb->vport = vport;
453 	if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
454 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
455 				"0448 Adapter failed init, mbxCmd x%x "
456 				"READ_SPARM mbxStatus x%x\n",
457 				mb->mbxCommand, mb->mbxStatus);
458 		phba->link_state = LPFC_HBA_ERROR;
459 		lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
460 		return -EIO;
461 	}
462 
463 	mp = pmb->ctx_buf;
464 
465 	/* This dmabuf was allocated by lpfc_read_sparam. The dmabuf is no
466 	 * longer needed.  Prevent unintended ctx_buf access as the mbox is
467 	 * reused.
468 	 */
469 	memcpy(&vport->fc_sparam, mp->virt, sizeof (struct serv_parm));
470 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
471 	kfree(mp);
472 	pmb->ctx_buf = NULL;
473 	lpfc_update_vport_wwn(vport);
474 
475 	/* Update the fc_host data structures with new wwn. */
476 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
477 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
478 	fc_host_max_npiv_vports(shost) = phba->max_vpi;
479 
480 	/* If no serial number in VPD data, use low 6 bytes of WWNN */
481 	/* This should be consolidated into parse_vpd ? - mr */
482 	if (phba->SerialNumber[0] == 0) {
483 		uint8_t *outptr;
484 
485 		outptr = &vport->fc_nodename.u.s.IEEE[0];
486 		for (i = 0; i < 12; i++) {
487 			status = *outptr++;
488 			j = ((status & 0xf0) >> 4);
489 			if (j <= 9)
490 				phba->SerialNumber[i] =
491 				    (char)((uint8_t) 0x30 + (uint8_t) j);
492 			else
493 				phba->SerialNumber[i] =
494 				    (char)((uint8_t) 0x61 + (uint8_t) (j - 10));
495 			i++;
496 			j = (status & 0xf);
497 			if (j <= 9)
498 				phba->SerialNumber[i] =
499 				    (char)((uint8_t) 0x30 + (uint8_t) j);
500 			else
501 				phba->SerialNumber[i] =
502 				    (char)((uint8_t) 0x61 + (uint8_t) (j - 10));
503 		}
504 	}
505 
506 	lpfc_read_config(phba, pmb);
507 	pmb->vport = vport;
508 	if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
509 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
510 				"0453 Adapter failed to init, mbxCmd x%x "
511 				"READ_CONFIG, mbxStatus x%x\n",
512 				mb->mbxCommand, mb->mbxStatus);
513 		phba->link_state = LPFC_HBA_ERROR;
514 		mempool_free( pmb, phba->mbox_mem_pool);
515 		return -EIO;
516 	}
517 
518 	/* Check if the port is disabled */
519 	lpfc_sli_read_link_ste(phba);
520 
521 	/* Reset the DFT_HBA_Q_DEPTH to the max xri  */
522 	if (phba->cfg_hba_queue_depth > mb->un.varRdConfig.max_xri) {
523 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
524 				"3359 HBA queue depth changed from %d to %d\n",
525 				phba->cfg_hba_queue_depth,
526 				mb->un.varRdConfig.max_xri);
527 		phba->cfg_hba_queue_depth = mb->un.varRdConfig.max_xri;
528 	}
529 
530 	phba->lmt = mb->un.varRdConfig.lmt;
531 
532 	/* Get the default values for Model Name and Description */
533 	lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
534 
535 	phba->link_state = LPFC_LINK_DOWN;
536 
537 	/* Only process IOCBs on ELS ring till hba_state is READY */
538 	if (psli->sli3_ring[LPFC_EXTRA_RING].sli.sli3.cmdringaddr)
539 		psli->sli3_ring[LPFC_EXTRA_RING].flag |= LPFC_STOP_IOCB_EVENT;
540 	if (psli->sli3_ring[LPFC_FCP_RING].sli.sli3.cmdringaddr)
541 		psli->sli3_ring[LPFC_FCP_RING].flag |= LPFC_STOP_IOCB_EVENT;
542 
543 	/* Post receive buffers for desired rings */
544 	if (phba->sli_rev != 3)
545 		lpfc_post_rcv_buf(phba);
546 
547 	/*
548 	 * Configure HBA MSI-X attention conditions to messages if MSI-X mode
549 	 */
550 	if (phba->intr_type == MSIX) {
551 		rc = lpfc_config_msi(phba, pmb);
552 		if (rc) {
553 			mempool_free(pmb, phba->mbox_mem_pool);
554 			return -EIO;
555 		}
556 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
557 		if (rc != MBX_SUCCESS) {
558 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
559 					"0352 Config MSI mailbox command "
560 					"failed, mbxCmd x%x, mbxStatus x%x\n",
561 					pmb->u.mb.mbxCommand,
562 					pmb->u.mb.mbxStatus);
563 			mempool_free(pmb, phba->mbox_mem_pool);
564 			return -EIO;
565 		}
566 	}
567 
568 	spin_lock_irq(&phba->hbalock);
569 	/* Initialize ERATT handling flag */
570 	clear_bit(HBA_ERATT_HANDLED, &phba->hba_flag);
571 
572 	/* Enable appropriate host interrupts */
573 	if (lpfc_readl(phba->HCregaddr, &status)) {
574 		spin_unlock_irq(&phba->hbalock);
575 		return -EIO;
576 	}
577 	status |= HC_MBINT_ENA | HC_ERINT_ENA | HC_LAINT_ENA;
578 	if (psli->num_rings > 0)
579 		status |= HC_R0INT_ENA;
580 	if (psli->num_rings > 1)
581 		status |= HC_R1INT_ENA;
582 	if (psli->num_rings > 2)
583 		status |= HC_R2INT_ENA;
584 	if (psli->num_rings > 3)
585 		status |= HC_R3INT_ENA;
586 
587 	if ((phba->cfg_poll & ENABLE_FCP_RING_POLLING) &&
588 	    (phba->cfg_poll & DISABLE_FCP_RING_INT))
589 		status &= ~(HC_R0INT_ENA);
590 
591 	writel(status, phba->HCregaddr);
592 	readl(phba->HCregaddr); /* flush */
593 	spin_unlock_irq(&phba->hbalock);
594 
595 	/* Set up ring-0 (ELS) timer */
596 	timeout = phba->fc_ratov * 2;
597 	mod_timer(&vport->els_tmofunc,
598 		  jiffies + secs_to_jiffies(timeout));
599 	/* Set up heart beat (HB) timer */
600 	mod_timer(&phba->hb_tmofunc,
601 		  jiffies + secs_to_jiffies(LPFC_HB_MBOX_INTERVAL));
602 	clear_bit(HBA_HBEAT_INP, &phba->hba_flag);
603 	clear_bit(HBA_HBEAT_TMO, &phba->hba_flag);
604 	phba->last_completion_time = jiffies;
605 	/* Set up error attention (ERATT) polling timer */
606 	mod_timer(&phba->eratt_poll,
607 		  jiffies + secs_to_jiffies(phba->eratt_poll_interval));
608 
609 	if (test_bit(LINK_DISABLED, &phba->hba_flag)) {
610 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
611 				"2598 Adapter Link is disabled.\n");
612 		lpfc_down_link(phba, pmb);
613 		pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
614 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
615 		if ((rc != MBX_SUCCESS) && (rc != MBX_BUSY)) {
616 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
617 					"2599 Adapter failed to issue DOWN_LINK"
618 					" mbox command rc 0x%x\n", rc);
619 
620 			mempool_free(pmb, phba->mbox_mem_pool);
621 			return -EIO;
622 		}
623 	} else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
624 		mempool_free(pmb, phba->mbox_mem_pool);
625 		rc = phba->lpfc_hba_init_link(phba, MBX_NOWAIT);
626 		if (rc)
627 			return rc;
628 	}
629 	/* MBOX buffer will be freed in mbox compl */
630 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
631 	if (!pmb) {
632 		phba->link_state = LPFC_HBA_ERROR;
633 		return -ENOMEM;
634 	}
635 
636 	lpfc_config_async(phba, pmb, LPFC_ELS_RING);
637 	pmb->mbox_cmpl = lpfc_config_async_cmpl;
638 	pmb->vport = phba->pport;
639 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
640 
641 	if ((rc != MBX_BUSY) && (rc != MBX_SUCCESS)) {
642 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
643 				"0456 Adapter failed to issue "
644 				"ASYNCEVT_ENABLE mbox status x%x\n",
645 				rc);
646 		mempool_free(pmb, phba->mbox_mem_pool);
647 	}
648 
649 	/* Get Option rom version */
650 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
651 	if (!pmb) {
652 		phba->link_state = LPFC_HBA_ERROR;
653 		return -ENOMEM;
654 	}
655 
656 	lpfc_dump_wakeup_param(phba, pmb);
657 	pmb->mbox_cmpl = lpfc_dump_wakeup_param_cmpl;
658 	pmb->vport = phba->pport;
659 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
660 
661 	if ((rc != MBX_BUSY) && (rc != MBX_SUCCESS)) {
662 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
663 				"0435 Adapter failed "
664 				"to get Option ROM version status x%x\n", rc);
665 		mempool_free(pmb, phba->mbox_mem_pool);
666 	}
667 
668 	return 0;
669 }
670 
671 /**
672  * lpfc_sli4_refresh_params - update driver copy of params.
673  * @phba: Pointer to HBA context object.
674  *
675  * This is called to refresh driver copy of dynamic fields from the
676  * common_get_sli4_parameters descriptor.
677  **/
678 int
679 lpfc_sli4_refresh_params(struct lpfc_hba *phba)
680 {
681 	LPFC_MBOXQ_t *mboxq;
682 	struct lpfc_mqe *mqe;
683 	struct lpfc_sli4_parameters *mbx_sli4_parameters;
684 	int length, rc;
685 
686 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
687 	if (!mboxq)
688 		return -ENOMEM;
689 
690 	mqe = &mboxq->u.mqe;
691 	/* Read the port's SLI4 Config Parameters */
692 	length = (sizeof(struct lpfc_mbx_get_sli4_parameters) -
693 		  sizeof(struct lpfc_sli4_cfg_mhdr));
694 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
695 			 LPFC_MBOX_OPCODE_GET_SLI4_PARAMETERS,
696 			 length, LPFC_SLI4_MBX_EMBED);
697 
698 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
699 	if (unlikely(rc)) {
700 		mempool_free(mboxq, phba->mbox_mem_pool);
701 		return rc;
702 	}
703 	mbx_sli4_parameters = &mqe->un.get_sli4_parameters.sli4_parameters;
704 	phba->sli4_hba.pc_sli4_params.mi_cap =
705 		bf_get(cfg_mi_ver, mbx_sli4_parameters);
706 
707 	/* Are we forcing MI off via module parameter? */
708 	if (phba->cfg_enable_mi)
709 		phba->sli4_hba.pc_sli4_params.mi_ver =
710 			bf_get(cfg_mi_ver, mbx_sli4_parameters);
711 	else
712 		phba->sli4_hba.pc_sli4_params.mi_ver = 0;
713 
714 	phba->sli4_hba.pc_sli4_params.cmf =
715 			bf_get(cfg_cmf, mbx_sli4_parameters);
716 	phba->sli4_hba.pc_sli4_params.pls =
717 			bf_get(cfg_pvl, mbx_sli4_parameters);
718 
719 	mempool_free(mboxq, phba->mbox_mem_pool);
720 	return rc;
721 }
722 
723 /**
724  * lpfc_hba_init_link - Initialize the FC link
725  * @phba: pointer to lpfc hba data structure.
726  * @flag: mailbox command issue mode - either MBX_POLL or MBX_NOWAIT
727  *
728  * This routine will issue the INIT_LINK mailbox command call.
729  * It is available to other drivers through the lpfc_hba data
730  * structure for use as a delayed link up mechanism with the
731  * module parameter lpfc_suppress_link_up.
732  *
733  * Return code
734  *		0 - success
735  *		Any other value - error
736  **/
737 static int
738 lpfc_hba_init_link(struct lpfc_hba *phba, uint32_t flag)
739 {
740 	return lpfc_hba_init_link_fc_topology(phba, phba->cfg_topology, flag);
741 }
742 
743 /**
744  * lpfc_hba_init_link_fc_topology - Initialize FC link with desired topology
745  * @phba: pointer to lpfc hba data structure.
746  * @fc_topology: desired fc topology.
747  * @flag: mailbox command issue mode - either MBX_POLL or MBX_NOWAIT
748  *
749  * This routine will issue the INIT_LINK mailbox command call.
750  * It is available to other drivers through the lpfc_hba data
751  * structure for use as a delayed link up mechanism with the
752  * module parameter lpfc_suppress_link_up.
753  *
754  * Return code
755  *              0 - success
756  *              Any other value - error
757  **/
758 int
759 lpfc_hba_init_link_fc_topology(struct lpfc_hba *phba, uint32_t fc_topology,
760 			       uint32_t flag)
761 {
762 	struct lpfc_vport *vport = phba->pport;
763 	LPFC_MBOXQ_t *pmb;
764 	MAILBOX_t *mb;
765 	int rc;
766 
767 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
768 	if (!pmb) {
769 		phba->link_state = LPFC_HBA_ERROR;
770 		return -ENOMEM;
771 	}
772 	mb = &pmb->u.mb;
773 	pmb->vport = vport;
774 
775 	if ((phba->cfg_link_speed > LPFC_USER_LINK_SPEED_MAX) ||
776 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_1G) &&
777 	     !(phba->lmt & LMT_1Gb)) ||
778 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_2G) &&
779 	     !(phba->lmt & LMT_2Gb)) ||
780 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_4G) &&
781 	     !(phba->lmt & LMT_4Gb)) ||
782 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_8G) &&
783 	     !(phba->lmt & LMT_8Gb)) ||
784 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_10G) &&
785 	     !(phba->lmt & LMT_10Gb)) ||
786 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_16G) &&
787 	     !(phba->lmt & LMT_16Gb)) ||
788 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_32G) &&
789 	     !(phba->lmt & LMT_32Gb)) ||
790 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_64G) &&
791 	     !(phba->lmt & LMT_64Gb))) {
792 		/* Reset link speed to auto */
793 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
794 				"1302 Invalid speed for this board:%d "
795 				"Reset link speed to auto.\n",
796 				phba->cfg_link_speed);
797 			phba->cfg_link_speed = LPFC_USER_LINK_SPEED_AUTO;
798 	}
799 	lpfc_init_link(phba, pmb, fc_topology, phba->cfg_link_speed);
800 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
801 	if (phba->sli_rev < LPFC_SLI_REV4)
802 		lpfc_set_loopback_flag(phba);
803 	rc = lpfc_sli_issue_mbox(phba, pmb, flag);
804 	if ((rc != MBX_BUSY) && (rc != MBX_SUCCESS)) {
805 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
806 				"0498 Adapter failed to init, mbxCmd x%x "
807 				"INIT_LINK, mbxStatus x%x\n",
808 				mb->mbxCommand, mb->mbxStatus);
809 		if (phba->sli_rev <= LPFC_SLI_REV3) {
810 			/* Clear all interrupt enable conditions */
811 			writel(0, phba->HCregaddr);
812 			readl(phba->HCregaddr); /* flush */
813 			/* Clear all pending interrupts */
814 			writel(0xffffffff, phba->HAregaddr);
815 			readl(phba->HAregaddr); /* flush */
816 		}
817 		phba->link_state = LPFC_HBA_ERROR;
818 		if (rc != MBX_BUSY || flag == MBX_POLL)
819 			mempool_free(pmb, phba->mbox_mem_pool);
820 		return -EIO;
821 	}
822 	phba->cfg_suppress_link_up = LPFC_INITIALIZE_LINK;
823 	if (flag == MBX_POLL)
824 		mempool_free(pmb, phba->mbox_mem_pool);
825 
826 	return 0;
827 }
828 
829 /**
830  * lpfc_hba_down_link - this routine downs the FC link
831  * @phba: pointer to lpfc hba data structure.
832  * @flag: mailbox command issue mode - either MBX_POLL or MBX_NOWAIT
833  *
834  * This routine will issue the DOWN_LINK mailbox command call.
835  * It is available to other drivers through the lpfc_hba data
836  * structure for use to stop the link.
837  *
838  * Return code
839  *		0 - success
840  *		Any other value - error
841  **/
842 static int
843 lpfc_hba_down_link(struct lpfc_hba *phba, uint32_t flag)
844 {
845 	LPFC_MBOXQ_t *pmb;
846 	int rc;
847 
848 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
849 	if (!pmb) {
850 		phba->link_state = LPFC_HBA_ERROR;
851 		return -ENOMEM;
852 	}
853 
854 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
855 			"0491 Adapter Link is disabled.\n");
856 	lpfc_down_link(phba, pmb);
857 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
858 	rc = lpfc_sli_issue_mbox(phba, pmb, flag);
859 	if ((rc != MBX_SUCCESS) && (rc != MBX_BUSY)) {
860 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
861 				"2522 Adapter failed to issue DOWN_LINK"
862 				" mbox command rc 0x%x\n", rc);
863 
864 		mempool_free(pmb, phba->mbox_mem_pool);
865 		return -EIO;
866 	}
867 	if (flag == MBX_POLL)
868 		mempool_free(pmb, phba->mbox_mem_pool);
869 
870 	return 0;
871 }
872 
873 /**
874  * lpfc_hba_down_prep - Perform lpfc uninitialization prior to HBA reset
875  * @phba: pointer to lpfc HBA data structure.
876  *
877  * This routine will do LPFC uninitialization before the HBA is reset when
878  * bringing down the SLI Layer.
879  *
880  * Return codes
881  *   0 - success.
882  *   Any other value - error.
883  **/
884 int
885 lpfc_hba_down_prep(struct lpfc_hba *phba)
886 {
887 	struct lpfc_vport **vports;
888 	int i;
889 
890 	if (phba->sli_rev <= LPFC_SLI_REV3) {
891 		/* Disable interrupts */
892 		writel(0, phba->HCregaddr);
893 		readl(phba->HCregaddr); /* flush */
894 	}
895 
896 	if (test_bit(FC_UNLOADING, &phba->pport->load_flag))
897 		lpfc_cleanup_discovery_resources(phba->pport);
898 	else {
899 		vports = lpfc_create_vport_work_array(phba);
900 		if (vports != NULL)
901 			for (i = 0; i <= phba->max_vports &&
902 				vports[i] != NULL; i++)
903 				lpfc_cleanup_discovery_resources(vports[i]);
904 		lpfc_destroy_vport_work_array(phba, vports);
905 	}
906 	return 0;
907 }
908 
909 /**
910  * lpfc_sli4_free_sp_events - Cleanup sp_queue_events to free
911  * rspiocb which got deferred
912  *
913  * @phba: pointer to lpfc HBA data structure.
914  *
915  * This routine will cleanup completed slow path events after HBA is reset
916  * when bringing down the SLI Layer.
917  *
918  *
919  * Return codes
920  *   void.
921  **/
922 static void
923 lpfc_sli4_free_sp_events(struct lpfc_hba *phba)
924 {
925 	struct lpfc_iocbq *rspiocbq;
926 	struct hbq_dmabuf *dmabuf;
927 	struct lpfc_cq_event *cq_event;
928 
929 	clear_bit(HBA_SP_QUEUE_EVT, &phba->hba_flag);
930 
931 	while (!list_empty(&phba->sli4_hba.sp_queue_event)) {
932 		/* Get the response iocb from the head of work queue */
933 		spin_lock_irq(&phba->hbalock);
934 		list_remove_head(&phba->sli4_hba.sp_queue_event,
935 				 cq_event, struct lpfc_cq_event, list);
936 		spin_unlock_irq(&phba->hbalock);
937 
938 		switch (bf_get(lpfc_wcqe_c_code, &cq_event->cqe.wcqe_cmpl)) {
939 		case CQE_CODE_COMPL_WQE:
940 			rspiocbq = container_of(cq_event, struct lpfc_iocbq,
941 						 cq_event);
942 			lpfc_sli_release_iocbq(phba, rspiocbq);
943 			break;
944 		case CQE_CODE_RECEIVE:
945 		case CQE_CODE_RECEIVE_V1:
946 			dmabuf = container_of(cq_event, struct hbq_dmabuf,
947 					      cq_event);
948 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
949 		}
950 	}
951 }
952 
953 /**
954  * lpfc_hba_free_post_buf - Perform lpfc uninitialization after HBA reset
955  * @phba: pointer to lpfc HBA data structure.
956  *
957  * This routine will cleanup posted ELS buffers after the HBA is reset
958  * when bringing down the SLI Layer.
959  *
960  *
961  * Return codes
962  *   void.
963  **/
964 static void
965 lpfc_hba_free_post_buf(struct lpfc_hba *phba)
966 {
967 	struct lpfc_sli *psli = &phba->sli;
968 	struct lpfc_sli_ring *pring;
969 	struct lpfc_dmabuf *mp, *next_mp;
970 	LIST_HEAD(buflist);
971 	int count;
972 
973 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)
974 		lpfc_sli_hbqbuf_free_all(phba);
975 	else {
976 		/* Cleanup preposted buffers on the ELS ring */
977 		pring = &psli->sli3_ring[LPFC_ELS_RING];
978 		spin_lock_irq(&phba->hbalock);
979 		list_splice_init(&pring->postbufq, &buflist);
980 		spin_unlock_irq(&phba->hbalock);
981 
982 		count = 0;
983 		list_for_each_entry_safe(mp, next_mp, &buflist, list) {
984 			list_del(&mp->list);
985 			count++;
986 			lpfc_mbuf_free(phba, mp->virt, mp->phys);
987 			kfree(mp);
988 		}
989 
990 		spin_lock_irq(&phba->hbalock);
991 		pring->postbufq_cnt -= count;
992 		spin_unlock_irq(&phba->hbalock);
993 	}
994 }
995 
996 /**
997  * lpfc_hba_clean_txcmplq - Perform lpfc uninitialization after HBA reset
998  * @phba: pointer to lpfc HBA data structure.
999  *
1000  * This routine will cleanup the txcmplq after the HBA is reset when bringing
1001  * down the SLI Layer.
1002  *
1003  * Return codes
1004  *   void
1005  **/
1006 static void
1007 lpfc_hba_clean_txcmplq(struct lpfc_hba *phba)
1008 {
1009 	struct lpfc_sli *psli = &phba->sli;
1010 	struct lpfc_queue *qp = NULL;
1011 	struct lpfc_sli_ring *pring;
1012 	LIST_HEAD(completions);
1013 	int i;
1014 	struct lpfc_iocbq *piocb, *next_iocb;
1015 
1016 	if (phba->sli_rev != LPFC_SLI_REV4) {
1017 		for (i = 0; i < psli->num_rings; i++) {
1018 			pring = &psli->sli3_ring[i];
1019 			spin_lock_irq(&phba->hbalock);
1020 			/* At this point in time the HBA is either reset or DOA
1021 			 * Nothing should be on txcmplq as it will
1022 			 * NEVER complete.
1023 			 */
1024 			list_splice_init(&pring->txcmplq, &completions);
1025 			pring->txcmplq_cnt = 0;
1026 			spin_unlock_irq(&phba->hbalock);
1027 
1028 			lpfc_sli_abort_iocb_ring(phba, pring);
1029 		}
1030 		/* Cancel all the IOCBs from the completions list */
1031 		lpfc_sli_cancel_iocbs(phba, &completions,
1032 				      IOSTAT_LOCAL_REJECT, IOERR_SLI_ABORTED);
1033 		return;
1034 	}
1035 	list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
1036 		pring = qp->pring;
1037 		if (!pring)
1038 			continue;
1039 		spin_lock_irq(&pring->ring_lock);
1040 		list_for_each_entry_safe(piocb, next_iocb,
1041 					 &pring->txcmplq, list)
1042 			piocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
1043 		list_splice_init(&pring->txcmplq, &completions);
1044 		pring->txcmplq_cnt = 0;
1045 		spin_unlock_irq(&pring->ring_lock);
1046 		lpfc_sli_abort_iocb_ring(phba, pring);
1047 	}
1048 	/* Cancel all the IOCBs from the completions list */
1049 	lpfc_sli_cancel_iocbs(phba, &completions,
1050 			      IOSTAT_LOCAL_REJECT, IOERR_SLI_ABORTED);
1051 }
1052 
1053 /**
1054  * lpfc_hba_down_post_s3 - Perform lpfc uninitialization after HBA reset
1055  * @phba: pointer to lpfc HBA data structure.
1056  *
1057  * This routine will do uninitialization after the HBA is reset when bring
1058  * down the SLI Layer.
1059  *
1060  * Return codes
1061  *   0 - success.
1062  *   Any other value - error.
1063  **/
1064 static int
1065 lpfc_hba_down_post_s3(struct lpfc_hba *phba)
1066 {
1067 	lpfc_hba_free_post_buf(phba);
1068 	lpfc_hba_clean_txcmplq(phba);
1069 	return 0;
1070 }
1071 
1072 /**
1073  * lpfc_hba_down_post_s4 - Perform lpfc uninitialization after HBA reset
1074  * @phba: pointer to lpfc HBA data structure.
1075  *
1076  * This routine will do uninitialization after the HBA is reset when bring
1077  * down the SLI Layer.
1078  *
1079  * Return codes
1080  *   0 - success.
1081  *   Any other value - error.
1082  **/
1083 static int
1084 lpfc_hba_down_post_s4(struct lpfc_hba *phba)
1085 {
1086 	struct lpfc_io_buf *psb, *psb_next;
1087 	struct lpfc_async_xchg_ctx *ctxp, *ctxp_next;
1088 	struct lpfc_sli4_hdw_queue *qp;
1089 	LIST_HEAD(aborts);
1090 	LIST_HEAD(nvme_aborts);
1091 	LIST_HEAD(nvmet_aborts);
1092 	struct lpfc_sglq *sglq_entry = NULL;
1093 	int cnt, idx;
1094 
1095 
1096 	lpfc_sli_hbqbuf_free_all(phba);
1097 	lpfc_hba_clean_txcmplq(phba);
1098 
1099 	/* At this point in time the HBA is either reset or DOA. Either
1100 	 * way, nothing should be on lpfc_abts_els_sgl_list, it needs to be
1101 	 * on the lpfc_els_sgl_list so that it can either be freed if the
1102 	 * driver is unloading or reposted if the driver is restarting
1103 	 * the port.
1104 	 */
1105 
1106 	/* sgl_list_lock required because worker thread uses this
1107 	 * list.
1108 	 */
1109 	spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
1110 	list_for_each_entry(sglq_entry,
1111 		&phba->sli4_hba.lpfc_abts_els_sgl_list, list)
1112 		sglq_entry->state = SGL_FREED;
1113 
1114 	list_splice_init(&phba->sli4_hba.lpfc_abts_els_sgl_list,
1115 			&phba->sli4_hba.lpfc_els_sgl_list);
1116 
1117 
1118 	spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
1119 
1120 	/* abts_xxxx_buf_list_lock required because worker thread uses this
1121 	 * list.
1122 	 */
1123 	spin_lock_irq(&phba->hbalock);
1124 	cnt = 0;
1125 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
1126 		qp = &phba->sli4_hba.hdwq[idx];
1127 
1128 		spin_lock(&qp->abts_io_buf_list_lock);
1129 		list_splice_init(&qp->lpfc_abts_io_buf_list,
1130 				 &aborts);
1131 
1132 		list_for_each_entry_safe(psb, psb_next, &aborts, list) {
1133 			psb->pCmd = NULL;
1134 			psb->status = IOSTAT_SUCCESS;
1135 			cnt++;
1136 		}
1137 		spin_lock(&qp->io_buf_list_put_lock);
1138 		list_splice_init(&aborts, &qp->lpfc_io_buf_list_put);
1139 		qp->put_io_bufs += qp->abts_scsi_io_bufs;
1140 		qp->put_io_bufs += qp->abts_nvme_io_bufs;
1141 		qp->abts_scsi_io_bufs = 0;
1142 		qp->abts_nvme_io_bufs = 0;
1143 		spin_unlock(&qp->io_buf_list_put_lock);
1144 		spin_unlock(&qp->abts_io_buf_list_lock);
1145 	}
1146 	spin_unlock_irq(&phba->hbalock);
1147 
1148 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
1149 		spin_lock_irq(&phba->sli4_hba.abts_nvmet_buf_list_lock);
1150 		list_splice_init(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list,
1151 				 &nvmet_aborts);
1152 		spin_unlock_irq(&phba->sli4_hba.abts_nvmet_buf_list_lock);
1153 		list_for_each_entry_safe(ctxp, ctxp_next, &nvmet_aborts, list) {
1154 			ctxp->flag &= ~(LPFC_NVME_XBUSY | LPFC_NVME_ABORT_OP);
1155 			lpfc_nvmet_ctxbuf_post(phba, ctxp->ctxbuf);
1156 		}
1157 	}
1158 
1159 	lpfc_sli4_free_sp_events(phba);
1160 	return cnt;
1161 }
1162 
1163 /**
1164  * lpfc_hba_down_post - Wrapper func for hba down post routine
1165  * @phba: pointer to lpfc HBA data structure.
1166  *
1167  * This routine wraps the actual SLI3 or SLI4 routine for performing
1168  * uninitialization after the HBA is reset when bring down the SLI Layer.
1169  *
1170  * Return codes
1171  *   0 - success.
1172  *   Any other value - error.
1173  **/
1174 int
1175 lpfc_hba_down_post(struct lpfc_hba *phba)
1176 {
1177 	return (*phba->lpfc_hba_down_post)(phba);
1178 }
1179 
1180 /**
1181  * lpfc_hb_timeout - The HBA-timer timeout handler
1182  * @t: timer context used to obtain the pointer to lpfc hba data structure.
1183  *
1184  * This is the HBA-timer timeout handler registered to the lpfc driver. When
1185  * this timer fires, a HBA timeout event shall be posted to the lpfc driver
1186  * work-port-events bitmap and the worker thread is notified. This timeout
1187  * event will be used by the worker thread to invoke the actual timeout
1188  * handler routine, lpfc_hb_timeout_handler. Any periodical operations will
1189  * be performed in the timeout handler and the HBA timeout event bit shall
1190  * be cleared by the worker thread after it has taken the event bitmap out.
1191  **/
1192 static void
1193 lpfc_hb_timeout(struct timer_list *t)
1194 {
1195 	struct lpfc_hba *phba;
1196 	uint32_t tmo_posted;
1197 	unsigned long iflag;
1198 
1199 	phba = timer_container_of(phba, t, hb_tmofunc);
1200 
1201 	/* Check for heart beat timeout conditions */
1202 	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
1203 	tmo_posted = phba->pport->work_port_events & WORKER_HB_TMO;
1204 	if (!tmo_posted)
1205 		phba->pport->work_port_events |= WORKER_HB_TMO;
1206 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
1207 
1208 	/* Tell the worker thread there is work to do */
1209 	if (!tmo_posted)
1210 		lpfc_worker_wake_up(phba);
1211 	return;
1212 }
1213 
1214 /**
1215  * lpfc_rrq_timeout - The RRQ-timer timeout handler
1216  * @t: timer context used to obtain the pointer to lpfc hba data structure.
1217  *
1218  * This is the RRQ-timer timeout handler registered to the lpfc driver. When
1219  * this timer fires, a RRQ timeout event shall be posted to the lpfc driver
1220  * work-port-events bitmap and the worker thread is notified. This timeout
1221  * event will be used by the worker thread to invoke the actual timeout
1222  * handler routine, lpfc_rrq_handler. Any periodical operations will
1223  * be performed in the timeout handler and the RRQ timeout event bit shall
1224  * be cleared by the worker thread after it has taken the event bitmap out.
1225  **/
1226 static void
1227 lpfc_rrq_timeout(struct timer_list *t)
1228 {
1229 	struct lpfc_hba *phba;
1230 
1231 	phba = timer_container_of(phba, t, rrq_tmr);
1232 	if (test_bit(FC_UNLOADING, &phba->pport->load_flag)) {
1233 		clear_bit(HBA_RRQ_ACTIVE, &phba->hba_flag);
1234 		return;
1235 	}
1236 
1237 	set_bit(HBA_RRQ_ACTIVE, &phba->hba_flag);
1238 	lpfc_worker_wake_up(phba);
1239 }
1240 
1241 /**
1242  * lpfc_hb_mbox_cmpl - The lpfc heart-beat mailbox command callback function
1243  * @phba: pointer to lpfc hba data structure.
1244  * @pmboxq: pointer to the driver internal queue element for mailbox command.
1245  *
1246  * This is the callback function to the lpfc heart-beat mailbox command.
1247  * If configured, the lpfc driver issues the heart-beat mailbox command to
1248  * the HBA every LPFC_HB_MBOX_INTERVAL (current 5) seconds. At the time the
1249  * heart-beat mailbox command is issued, the driver shall set up heart-beat
1250  * timeout timer to LPFC_HB_MBOX_TIMEOUT (current 30) seconds and marks
1251  * heart-beat outstanding state. Once the mailbox command comes back and
1252  * no error conditions detected, the heart-beat mailbox command timer is
1253  * reset to LPFC_HB_MBOX_INTERVAL seconds and the heart-beat outstanding
1254  * state is cleared for the next heart-beat. If the timer expired with the
1255  * heart-beat outstanding state set, the driver will put the HBA offline.
1256  **/
1257 static void
1258 lpfc_hb_mbox_cmpl(struct lpfc_hba * phba, LPFC_MBOXQ_t * pmboxq)
1259 {
1260 	clear_bit(HBA_HBEAT_INP, &phba->hba_flag);
1261 	clear_bit(HBA_HBEAT_TMO, &phba->hba_flag);
1262 
1263 	/* Check and reset heart-beat timer if necessary */
1264 	mempool_free(pmboxq, phba->mbox_mem_pool);
1265 	if (!test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag) &&
1266 	    !(phba->link_state == LPFC_HBA_ERROR) &&
1267 	    !test_bit(FC_UNLOADING, &phba->pport->load_flag))
1268 		mod_timer(&phba->hb_tmofunc,
1269 			  jiffies +
1270 			  secs_to_jiffies(LPFC_HB_MBOX_INTERVAL));
1271 	return;
1272 }
1273 
1274 /*
1275  * lpfc_idle_stat_delay_work - idle_stat tracking
1276  *
1277  * This routine tracks per-eq idle_stat and determines polling decisions.
1278  *
1279  * Return codes:
1280  *   None
1281  **/
1282 static void
1283 lpfc_idle_stat_delay_work(struct work_struct *work)
1284 {
1285 	struct lpfc_hba *phba = container_of(to_delayed_work(work),
1286 					     struct lpfc_hba,
1287 					     idle_stat_delay_work);
1288 	struct lpfc_queue *eq;
1289 	struct lpfc_sli4_hdw_queue *hdwq;
1290 	struct lpfc_idle_stat *idle_stat;
1291 	u32 i, idle_percent;
1292 	u64 wall, wall_idle, diff_wall, diff_idle, busy_time;
1293 
1294 	if (test_bit(FC_UNLOADING, &phba->pport->load_flag))
1295 		return;
1296 
1297 	if (phba->link_state == LPFC_HBA_ERROR ||
1298 	    test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag) ||
1299 	    phba->cmf_active_mode != LPFC_CFG_OFF)
1300 		goto requeue;
1301 
1302 	for_each_present_cpu(i) {
1303 		hdwq = &phba->sli4_hba.hdwq[phba->sli4_hba.cpu_map[i].hdwq];
1304 		eq = hdwq->hba_eq;
1305 
1306 		/* Skip if we've already handled this eq's primary CPU */
1307 		if (eq->chann != i)
1308 			continue;
1309 
1310 		idle_stat = &phba->sli4_hba.idle_stat[i];
1311 
1312 		/* get_cpu_idle_time returns values as running counters. Thus,
1313 		 * to know the amount for this period, the prior counter values
1314 		 * need to be subtracted from the current counter values.
1315 		 * From there, the idle time stat can be calculated as a
1316 		 * percentage of 100 - the sum of the other consumption times.
1317 		 */
1318 		wall_idle = get_cpu_idle_time(i, &wall, 1);
1319 		diff_idle = wall_idle - idle_stat->prev_idle;
1320 		diff_wall = wall - idle_stat->prev_wall;
1321 
1322 		if (diff_wall <= diff_idle)
1323 			busy_time = 0;
1324 		else
1325 			busy_time = diff_wall - diff_idle;
1326 
1327 		idle_percent = div64_u64(100 * busy_time, diff_wall);
1328 		idle_percent = 100 - idle_percent;
1329 
1330 		if (idle_percent < 15)
1331 			eq->poll_mode = LPFC_QUEUE_WORK;
1332 		else
1333 			eq->poll_mode = LPFC_THREADED_IRQ;
1334 
1335 		idle_stat->prev_idle = wall_idle;
1336 		idle_stat->prev_wall = wall;
1337 	}
1338 
1339 requeue:
1340 	schedule_delayed_work(&phba->idle_stat_delay_work,
1341 			      msecs_to_jiffies(LPFC_IDLE_STAT_DELAY));
1342 }
1343 
1344 static void
1345 lpfc_hb_eq_delay_work(struct work_struct *work)
1346 {
1347 	struct lpfc_hba *phba = container_of(to_delayed_work(work),
1348 					     struct lpfc_hba, eq_delay_work);
1349 	struct lpfc_eq_intr_info *eqi, *eqi_new;
1350 	struct lpfc_queue *eq, *eq_next;
1351 	unsigned char *ena_delay = NULL;
1352 	uint32_t usdelay;
1353 	int i;
1354 
1355 	if (!phba->cfg_auto_imax ||
1356 	    test_bit(FC_UNLOADING, &phba->pport->load_flag))
1357 		return;
1358 
1359 	if (phba->link_state == LPFC_HBA_ERROR ||
1360 	    test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag))
1361 		goto requeue;
1362 
1363 	ena_delay = kcalloc(phba->sli4_hba.num_possible_cpu, sizeof(*ena_delay),
1364 			    GFP_KERNEL);
1365 	if (!ena_delay)
1366 		goto requeue;
1367 
1368 	for (i = 0; i < phba->cfg_irq_chann; i++) {
1369 		/* Get the EQ corresponding to the IRQ vector */
1370 		eq = phba->sli4_hba.hba_eq_hdl[i].eq;
1371 		if (!eq)
1372 			continue;
1373 		if (eq->q_mode || eq->q_flag & HBA_EQ_DELAY_CHK) {
1374 			eq->q_flag &= ~HBA_EQ_DELAY_CHK;
1375 			ena_delay[eq->last_cpu] = 1;
1376 		}
1377 	}
1378 
1379 	for_each_present_cpu(i) {
1380 		eqi = per_cpu_ptr(phba->sli4_hba.eq_info, i);
1381 		if (ena_delay[i]) {
1382 			usdelay = (eqi->icnt >> 10) * LPFC_EQ_DELAY_STEP;
1383 			if (usdelay > LPFC_MAX_AUTO_EQ_DELAY)
1384 				usdelay = LPFC_MAX_AUTO_EQ_DELAY;
1385 		} else {
1386 			usdelay = 0;
1387 		}
1388 
1389 		eqi->icnt = 0;
1390 
1391 		list_for_each_entry_safe(eq, eq_next, &eqi->list, cpu_list) {
1392 			if (unlikely(eq->last_cpu != i)) {
1393 				eqi_new = per_cpu_ptr(phba->sli4_hba.eq_info,
1394 						      eq->last_cpu);
1395 				list_move_tail(&eq->cpu_list, &eqi_new->list);
1396 				continue;
1397 			}
1398 			if (usdelay != eq->q_mode)
1399 				lpfc_modify_hba_eq_delay(phba, eq->hdwq, 1,
1400 							 usdelay);
1401 		}
1402 	}
1403 
1404 	kfree(ena_delay);
1405 
1406 requeue:
1407 	queue_delayed_work(phba->wq, &phba->eq_delay_work,
1408 			   msecs_to_jiffies(LPFC_EQ_DELAY_MSECS));
1409 }
1410 
1411 /**
1412  * lpfc_hb_mxp_handler - Multi-XRI pools handler to adjust XRI distribution
1413  * @phba: pointer to lpfc hba data structure.
1414  *
1415  * For each heartbeat, this routine does some heuristic methods to adjust
1416  * XRI distribution. The goal is to fully utilize free XRIs.
1417  **/
1418 static void lpfc_hb_mxp_handler(struct lpfc_hba *phba)
1419 {
1420 	u32 i;
1421 	u32 hwq_count;
1422 
1423 	hwq_count = phba->cfg_hdw_queue;
1424 	for (i = 0; i < hwq_count; i++) {
1425 		/* Adjust XRIs in private pool */
1426 		lpfc_adjust_pvt_pool_count(phba, i);
1427 
1428 		/* Adjust high watermark */
1429 		lpfc_adjust_high_watermark(phba, i);
1430 
1431 #ifdef LPFC_MXP_STAT
1432 		/* Snapshot pbl, pvt and busy count */
1433 		lpfc_snapshot_mxp(phba, i);
1434 #endif
1435 	}
1436 }
1437 
1438 /**
1439  * lpfc_issue_hb_mbox - Issues heart-beat mailbox command
1440  * @phba: pointer to lpfc hba data structure.
1441  *
1442  * If a HB mbox is not already in progrees, this routine will allocate
1443  * a LPFC_MBOXQ_t, populate it with a MBX_HEARTBEAT (0x31) command,
1444  * and issue it. The HBA_HBEAT_INP flag means the command is in progress.
1445  **/
1446 int
1447 lpfc_issue_hb_mbox(struct lpfc_hba *phba)
1448 {
1449 	LPFC_MBOXQ_t *pmboxq;
1450 	int retval;
1451 
1452 	/* Is a Heartbeat mbox already in progress */
1453 	if (test_bit(HBA_HBEAT_INP, &phba->hba_flag))
1454 		return 0;
1455 
1456 	pmboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
1457 	if (!pmboxq)
1458 		return -ENOMEM;
1459 
1460 	lpfc_heart_beat(phba, pmboxq);
1461 	pmboxq->mbox_cmpl = lpfc_hb_mbox_cmpl;
1462 	pmboxq->vport = phba->pport;
1463 	retval = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
1464 
1465 	if (retval != MBX_BUSY && retval != MBX_SUCCESS) {
1466 		mempool_free(pmboxq, phba->mbox_mem_pool);
1467 		return -ENXIO;
1468 	}
1469 	set_bit(HBA_HBEAT_INP, &phba->hba_flag);
1470 
1471 	return 0;
1472 }
1473 
1474 /**
1475  * lpfc_issue_hb_tmo - Signals heartbeat timer to issue mbox command
1476  * @phba: pointer to lpfc hba data structure.
1477  *
1478  * The heartbeat timer (every 5 sec) will fire. If the HBA_HBEAT_TMO
1479  * flag is set, it will force a MBX_HEARTBEAT mbox command, regardless
1480  * of the value of lpfc_enable_hba_heartbeat.
1481  * If lpfc_enable_hba_heartbeat is set, the timeout routine will always
1482  * try to issue a MBX_HEARTBEAT mbox command.
1483  **/
1484 void
1485 lpfc_issue_hb_tmo(struct lpfc_hba *phba)
1486 {
1487 	if (phba->cfg_enable_hba_heartbeat)
1488 		return;
1489 	set_bit(HBA_HBEAT_TMO, &phba->hba_flag);
1490 }
1491 
1492 /**
1493  * lpfc_hb_timeout_handler - The HBA-timer timeout handler
1494  * @phba: pointer to lpfc hba data structure.
1495  *
1496  * This is the actual HBA-timer timeout handler to be invoked by the worker
1497  * thread whenever the HBA timer fired and HBA-timeout event posted. This
1498  * handler performs any periodic operations needed for the device. If such
1499  * periodic event has already been attended to either in the interrupt handler
1500  * or by processing slow-ring or fast-ring events within the HBA-timer
1501  * timeout window (LPFC_HB_MBOX_INTERVAL), this handler just simply resets
1502  * the timer for the next timeout period. If lpfc heart-beat mailbox command
1503  * is configured and there is no heart-beat mailbox command outstanding, a
1504  * heart-beat mailbox is issued and timer set properly. Otherwise, if there
1505  * has been a heart-beat mailbox command outstanding, the HBA shall be put
1506  * to offline.
1507  **/
1508 void
1509 lpfc_hb_timeout_handler(struct lpfc_hba *phba)
1510 {
1511 	struct lpfc_vport **vports;
1512 	struct lpfc_dmabuf *buf_ptr;
1513 	int retval = 0;
1514 	int i, tmo;
1515 	struct lpfc_sli *psli = &phba->sli;
1516 	LIST_HEAD(completions);
1517 
1518 	if (phba->cfg_xri_rebalancing) {
1519 		/* Multi-XRI pools handler */
1520 		lpfc_hb_mxp_handler(phba);
1521 	}
1522 
1523 	vports = lpfc_create_vport_work_array(phba);
1524 	if (vports != NULL)
1525 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
1526 			lpfc_rcv_seq_check_edtov(vports[i]);
1527 			lpfc_fdmi_change_check(vports[i]);
1528 		}
1529 	lpfc_destroy_vport_work_array(phba, vports);
1530 
1531 	if (phba->link_state == LPFC_HBA_ERROR ||
1532 	    test_bit(FC_UNLOADING, &phba->pport->load_flag) ||
1533 	    test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag))
1534 		return;
1535 
1536 	if (phba->elsbuf_cnt &&
1537 		(phba->elsbuf_cnt == phba->elsbuf_prev_cnt)) {
1538 		spin_lock_irq(&phba->hbalock);
1539 		list_splice_init(&phba->elsbuf, &completions);
1540 		phba->elsbuf_cnt = 0;
1541 		phba->elsbuf_prev_cnt = 0;
1542 		spin_unlock_irq(&phba->hbalock);
1543 
1544 		while (!list_empty(&completions)) {
1545 			list_remove_head(&completions, buf_ptr,
1546 				struct lpfc_dmabuf, list);
1547 			lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
1548 			kfree(buf_ptr);
1549 		}
1550 	}
1551 	phba->elsbuf_prev_cnt = phba->elsbuf_cnt;
1552 
1553 	/* If there is no heart beat outstanding, issue a heartbeat command */
1554 	if (phba->cfg_enable_hba_heartbeat) {
1555 		/* If IOs are completing, no need to issue a MBX_HEARTBEAT */
1556 		spin_lock_irq(&phba->pport->work_port_lock);
1557 		if (time_after(phba->last_completion_time +
1558 				secs_to_jiffies(LPFC_HB_MBOX_INTERVAL),
1559 				jiffies)) {
1560 			spin_unlock_irq(&phba->pport->work_port_lock);
1561 			if (test_bit(HBA_HBEAT_INP, &phba->hba_flag))
1562 				tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1563 			else
1564 				tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1565 			goto out;
1566 		}
1567 		spin_unlock_irq(&phba->pport->work_port_lock);
1568 
1569 		/* Check if a MBX_HEARTBEAT is already in progress */
1570 		if (test_bit(HBA_HBEAT_INP, &phba->hba_flag)) {
1571 			/*
1572 			 * If heart beat timeout called with HBA_HBEAT_INP set
1573 			 * we need to give the hb mailbox cmd a chance to
1574 			 * complete or TMO.
1575 			 */
1576 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
1577 				"0459 Adapter heartbeat still outstanding: "
1578 				"last compl time was %d ms.\n",
1579 				jiffies_to_msecs(jiffies
1580 					 - phba->last_completion_time));
1581 			tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1582 		} else {
1583 			if ((!(psli->sli_flag & LPFC_SLI_MBOX_ACTIVE)) &&
1584 				(list_empty(&psli->mboxq))) {
1585 
1586 				retval = lpfc_issue_hb_mbox(phba);
1587 				if (retval) {
1588 					tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1589 					goto out;
1590 				}
1591 				phba->skipped_hb = 0;
1592 			} else if (time_before_eq(phba->last_completion_time,
1593 					phba->skipped_hb)) {
1594 				lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
1595 					"2857 Last completion time not "
1596 					" updated in %d ms\n",
1597 					jiffies_to_msecs(jiffies
1598 						 - phba->last_completion_time));
1599 			} else
1600 				phba->skipped_hb = jiffies;
1601 
1602 			tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1603 			goto out;
1604 		}
1605 	} else {
1606 		/* Check to see if we want to force a MBX_HEARTBEAT */
1607 		if (test_bit(HBA_HBEAT_TMO, &phba->hba_flag)) {
1608 			retval = lpfc_issue_hb_mbox(phba);
1609 			if (retval)
1610 				tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1611 			else
1612 				tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1613 			goto out;
1614 		}
1615 		tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1616 	}
1617 out:
1618 	mod_timer(&phba->hb_tmofunc, jiffies + msecs_to_jiffies(tmo));
1619 }
1620 
1621 /**
1622  * lpfc_offline_eratt - Bring lpfc offline on hardware error attention
1623  * @phba: pointer to lpfc hba data structure.
1624  *
1625  * This routine is called to bring the HBA offline when HBA hardware error
1626  * other than Port Error 6 has been detected.
1627  **/
1628 static void
1629 lpfc_offline_eratt(struct lpfc_hba *phba)
1630 {
1631 	struct lpfc_sli   *psli = &phba->sli;
1632 
1633 	spin_lock_irq(&phba->hbalock);
1634 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1635 	spin_unlock_irq(&phba->hbalock);
1636 	lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
1637 
1638 	lpfc_offline(phba);
1639 	lpfc_reset_barrier(phba);
1640 	spin_lock_irq(&phba->hbalock);
1641 	lpfc_sli_brdreset(phba);
1642 	spin_unlock_irq(&phba->hbalock);
1643 	lpfc_hba_down_post(phba);
1644 	lpfc_sli_brdready(phba, HS_MBRDY);
1645 	lpfc_unblock_mgmt_io(phba);
1646 	phba->link_state = LPFC_HBA_ERROR;
1647 	return;
1648 }
1649 
1650 /**
1651  * lpfc_sli4_offline_eratt - Bring lpfc offline on SLI4 hardware error attention
1652  * @phba: pointer to lpfc hba data structure.
1653  *
1654  * This routine is called to bring a SLI4 HBA offline when HBA hardware error
1655  * other than Port Error 6 has been detected.
1656  **/
1657 void
1658 lpfc_sli4_offline_eratt(struct lpfc_hba *phba)
1659 {
1660 	spin_lock_irq(&phba->hbalock);
1661 	if (phba->link_state == LPFC_HBA_ERROR &&
1662 		test_bit(HBA_PCI_ERR, &phba->bit_flags)) {
1663 		spin_unlock_irq(&phba->hbalock);
1664 		return;
1665 	}
1666 	phba->link_state = LPFC_HBA_ERROR;
1667 	spin_unlock_irq(&phba->hbalock);
1668 
1669 	lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
1670 	lpfc_sli_flush_io_rings(phba);
1671 	lpfc_offline(phba);
1672 	lpfc_hba_down_post(phba);
1673 	lpfc_unblock_mgmt_io(phba);
1674 }
1675 
1676 /**
1677  * lpfc_handle_deferred_eratt - The HBA hardware deferred error handler
1678  * @phba: pointer to lpfc hba data structure.
1679  *
1680  * This routine is invoked to handle the deferred HBA hardware error
1681  * conditions. This type of error is indicated by HBA by setting ER1
1682  * and another ER bit in the host status register. The driver will
1683  * wait until the ER1 bit clears before handling the error condition.
1684  **/
1685 static void
1686 lpfc_handle_deferred_eratt(struct lpfc_hba *phba)
1687 {
1688 	uint32_t old_host_status = phba->work_hs;
1689 	struct lpfc_sli *psli = &phba->sli;
1690 
1691 	/* If the pci channel is offline, ignore possible errors,
1692 	 * since we cannot communicate with the pci card anyway.
1693 	 */
1694 	if (pci_channel_offline(phba->pcidev)) {
1695 		clear_bit(DEFER_ERATT, &phba->hba_flag);
1696 		return;
1697 	}
1698 
1699 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1700 			"0479 Deferred Adapter Hardware Error "
1701 			"Data: x%x x%x x%x\n",
1702 			phba->work_hs, phba->work_status[0],
1703 			phba->work_status[1]);
1704 
1705 	spin_lock_irq(&phba->hbalock);
1706 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1707 	spin_unlock_irq(&phba->hbalock);
1708 
1709 
1710 	/*
1711 	 * Firmware stops when it triggred erratt. That could cause the I/Os
1712 	 * dropped by the firmware. Error iocb (I/O) on txcmplq and let the
1713 	 * SCSI layer retry it after re-establishing link.
1714 	 */
1715 	lpfc_sli_abort_fcp_rings(phba);
1716 
1717 	/*
1718 	 * There was a firmware error. Take the hba offline and then
1719 	 * attempt to restart it.
1720 	 */
1721 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
1722 	lpfc_offline(phba);
1723 
1724 	/* Wait for the ER1 bit to clear.*/
1725 	while (phba->work_hs & HS_FFER1) {
1726 		msleep(100);
1727 		if (lpfc_readl(phba->HSregaddr, &phba->work_hs)) {
1728 			phba->work_hs = UNPLUG_ERR ;
1729 			break;
1730 		}
1731 		/* If driver is unloading let the worker thread continue */
1732 		if (test_bit(FC_UNLOADING, &phba->pport->load_flag)) {
1733 			phba->work_hs = 0;
1734 			break;
1735 		}
1736 	}
1737 
1738 	/*
1739 	 * This is to ptrotect against a race condition in which
1740 	 * first write to the host attention register clear the
1741 	 * host status register.
1742 	 */
1743 	if (!phba->work_hs && !test_bit(FC_UNLOADING, &phba->pport->load_flag))
1744 		phba->work_hs = old_host_status & ~HS_FFER1;
1745 
1746 	clear_bit(DEFER_ERATT, &phba->hba_flag);
1747 	phba->work_status[0] = readl(phba->MBslimaddr + 0xa8);
1748 	phba->work_status[1] = readl(phba->MBslimaddr + 0xac);
1749 }
1750 
1751 static void
1752 lpfc_board_errevt_to_mgmt(struct lpfc_hba *phba)
1753 {
1754 	struct lpfc_board_event_header board_event;
1755 	struct Scsi_Host *shost;
1756 
1757 	board_event.event_type = FC_REG_BOARD_EVENT;
1758 	board_event.subcategory = LPFC_EVENT_PORTINTERR;
1759 	shost = lpfc_shost_from_vport(phba->pport);
1760 	fc_host_post_vendor_event(shost, fc_get_event_number(),
1761 				  sizeof(board_event),
1762 				  (char *) &board_event,
1763 				  LPFC_NL_VENDOR_ID);
1764 }
1765 
1766 /**
1767  * lpfc_handle_eratt_s3 - The SLI3 HBA hardware error handler
1768  * @phba: pointer to lpfc hba data structure.
1769  *
1770  * This routine is invoked to handle the following HBA hardware error
1771  * conditions:
1772  * 1 - HBA error attention interrupt
1773  * 2 - DMA ring index out of range
1774  * 3 - Mailbox command came back as unknown
1775  **/
1776 static void
1777 lpfc_handle_eratt_s3(struct lpfc_hba *phba)
1778 {
1779 	struct lpfc_vport *vport = phba->pport;
1780 	struct lpfc_sli   *psli = &phba->sli;
1781 	uint32_t event_data;
1782 	unsigned long temperature;
1783 	struct temp_event temp_event_data;
1784 	struct Scsi_Host  *shost;
1785 
1786 	/* If the pci channel is offline, ignore possible errors,
1787 	 * since we cannot communicate with the pci card anyway.
1788 	 */
1789 	if (pci_channel_offline(phba->pcidev)) {
1790 		clear_bit(DEFER_ERATT, &phba->hba_flag);
1791 		return;
1792 	}
1793 
1794 	/* If resets are disabled then leave the HBA alone and return */
1795 	if (!phba->cfg_enable_hba_reset)
1796 		return;
1797 
1798 	/* Send an internal error event to mgmt application */
1799 	lpfc_board_errevt_to_mgmt(phba);
1800 
1801 	if (test_bit(DEFER_ERATT, &phba->hba_flag))
1802 		lpfc_handle_deferred_eratt(phba);
1803 
1804 	if ((phba->work_hs & HS_FFER6) || (phba->work_hs & HS_FFER8)) {
1805 		if (phba->work_hs & HS_FFER6)
1806 			/* Re-establishing Link */
1807 			lpfc_printf_log(phba, KERN_INFO, LOG_LINK_EVENT,
1808 					"1301 Re-establishing Link "
1809 					"Data: x%x x%x x%x\n",
1810 					phba->work_hs, phba->work_status[0],
1811 					phba->work_status[1]);
1812 		if (phba->work_hs & HS_FFER8)
1813 			/* Device Zeroization */
1814 			lpfc_printf_log(phba, KERN_INFO, LOG_LINK_EVENT,
1815 					"2861 Host Authentication device "
1816 					"zeroization Data:x%x x%x x%x\n",
1817 					phba->work_hs, phba->work_status[0],
1818 					phba->work_status[1]);
1819 
1820 		spin_lock_irq(&phba->hbalock);
1821 		psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1822 		spin_unlock_irq(&phba->hbalock);
1823 
1824 		/*
1825 		* Firmware stops when it triggled erratt with HS_FFER6.
1826 		* That could cause the I/Os dropped by the firmware.
1827 		* Error iocb (I/O) on txcmplq and let the SCSI layer
1828 		* retry it after re-establishing link.
1829 		*/
1830 		lpfc_sli_abort_fcp_rings(phba);
1831 
1832 		/*
1833 		 * There was a firmware error.  Take the hba offline and then
1834 		 * attempt to restart it.
1835 		 */
1836 		lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
1837 		lpfc_offline(phba);
1838 		lpfc_sli_brdrestart(phba);
1839 		if (lpfc_online(phba) == 0) {	/* Initialize the HBA */
1840 			lpfc_unblock_mgmt_io(phba);
1841 			return;
1842 		}
1843 		lpfc_unblock_mgmt_io(phba);
1844 	} else if (phba->work_hs & HS_CRIT_TEMP) {
1845 		temperature = readl(phba->MBslimaddr + TEMPERATURE_OFFSET);
1846 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
1847 		temp_event_data.event_code = LPFC_CRIT_TEMP;
1848 		temp_event_data.data = (uint32_t)temperature;
1849 
1850 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1851 				"0406 Adapter maximum temperature exceeded "
1852 				"(%ld), taking this port offline "
1853 				"Data: x%x x%x x%x\n",
1854 				temperature, phba->work_hs,
1855 				phba->work_status[0], phba->work_status[1]);
1856 
1857 		shost = lpfc_shost_from_vport(phba->pport);
1858 		fc_host_post_vendor_event(shost, fc_get_event_number(),
1859 					  sizeof(temp_event_data),
1860 					  (char *) &temp_event_data,
1861 					  SCSI_NL_VID_TYPE_PCI
1862 					  | PCI_VENDOR_ID_EMULEX);
1863 
1864 		spin_lock_irq(&phba->hbalock);
1865 		phba->over_temp_state = HBA_OVER_TEMP;
1866 		spin_unlock_irq(&phba->hbalock);
1867 		lpfc_offline_eratt(phba);
1868 
1869 	} else {
1870 		/* The if clause above forces this code path when the status
1871 		 * failure is a value other than FFER6. Do not call the offline
1872 		 * twice. This is the adapter hardware error path.
1873 		 */
1874 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1875 				"0457 Adapter Hardware Error "
1876 				"Data: x%x x%x x%x\n",
1877 				phba->work_hs,
1878 				phba->work_status[0], phba->work_status[1]);
1879 
1880 		event_data = FC_REG_DUMP_EVENT;
1881 		shost = lpfc_shost_from_vport(vport);
1882 		fc_host_post_vendor_event(shost, fc_get_event_number(),
1883 				sizeof(event_data), (char *) &event_data,
1884 				SCSI_NL_VID_TYPE_PCI | PCI_VENDOR_ID_EMULEX);
1885 
1886 		lpfc_offline_eratt(phba);
1887 	}
1888 	return;
1889 }
1890 
1891 /**
1892  * lpfc_sli4_port_sta_fn_reset - The SLI4 function reset due to port status reg
1893  * @phba: pointer to lpfc hba data structure.
1894  * @mbx_action: flag for mailbox shutdown action.
1895  * @en_rn_msg: send reset/port recovery message.
1896  * This routine is invoked to perform an SLI4 port PCI function reset in
1897  * response to port status register polling attention. It waits for port
1898  * status register (ERR, RDY, RN) bits before proceeding with function reset.
1899  * During this process, interrupt vectors are freed and later requested
1900  * for handling possible port resource change.
1901  **/
1902 static int
1903 lpfc_sli4_port_sta_fn_reset(struct lpfc_hba *phba, int mbx_action,
1904 			    bool en_rn_msg)
1905 {
1906 	int rc;
1907 	uint32_t intr_mode;
1908 	LPFC_MBOXQ_t *mboxq;
1909 
1910 	/* Notifying the transport that the targets are going offline. */
1911 	lpfc_scsi_dev_block(phba);
1912 
1913 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) >=
1914 	    LPFC_SLI_INTF_IF_TYPE_2) {
1915 		/*
1916 		 * On error status condition, driver need to wait for port
1917 		 * ready before performing reset.
1918 		 */
1919 		rc = lpfc_sli4_pdev_status_reg_wait(phba);
1920 		if (rc)
1921 			return rc;
1922 	}
1923 
1924 	/* need reset: attempt for port recovery */
1925 	if (en_rn_msg)
1926 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
1927 				"2887 Reset Needed: Attempting Port "
1928 				"Recovery...\n");
1929 
1930 	/* If we are no wait, the HBA has been reset and is not
1931 	 * functional, thus we should clear
1932 	 * (LPFC_SLI_ACTIVE | LPFC_SLI_MBOX_ACTIVE) flags.
1933 	 */
1934 	if (mbx_action == LPFC_MBX_NO_WAIT) {
1935 		spin_lock_irq(&phba->hbalock);
1936 		phba->sli.sli_flag &= ~LPFC_SLI_ACTIVE;
1937 		if (phba->sli.mbox_active) {
1938 			mboxq = phba->sli.mbox_active;
1939 			mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
1940 			__lpfc_mbox_cmpl_put(phba, mboxq);
1941 			phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
1942 			phba->sli.mbox_active = NULL;
1943 		}
1944 		spin_unlock_irq(&phba->hbalock);
1945 	}
1946 
1947 	lpfc_offline_prep(phba, mbx_action);
1948 	lpfc_sli_flush_io_rings(phba);
1949 	lpfc_nvmels_flush_cmd(phba);
1950 	lpfc_offline(phba);
1951 	/* release interrupt for possible resource change */
1952 	lpfc_sli4_disable_intr(phba);
1953 	rc = lpfc_sli_brdrestart(phba);
1954 	if (rc) {
1955 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1956 				"6309 Failed to restart board\n");
1957 		return rc;
1958 	}
1959 	/* request and enable interrupt */
1960 	intr_mode = lpfc_sli4_enable_intr(phba, phba->intr_mode);
1961 	if (intr_mode == LPFC_INTR_ERROR) {
1962 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1963 				"3175 Failed to enable interrupt\n");
1964 		return -EIO;
1965 	}
1966 	phba->intr_mode = intr_mode;
1967 	rc = lpfc_online(phba);
1968 	if (rc == 0)
1969 		lpfc_unblock_mgmt_io(phba);
1970 
1971 	return rc;
1972 }
1973 
1974 /**
1975  * lpfc_handle_eratt_s4 - The SLI4 HBA hardware error handler
1976  * @phba: pointer to lpfc hba data structure.
1977  *
1978  * This routine is invoked to handle the SLI4 HBA hardware error attention
1979  * conditions.
1980  **/
1981 static void
1982 lpfc_handle_eratt_s4(struct lpfc_hba *phba)
1983 {
1984 	struct lpfc_vport *vport = phba->pport;
1985 	uint32_t event_data;
1986 	struct Scsi_Host *shost;
1987 	uint32_t if_type;
1988 	struct lpfc_register portstat_reg = {0};
1989 	uint32_t reg_err1, reg_err2;
1990 	uint32_t uerrlo_reg, uemasklo_reg;
1991 	uint32_t smphr_port_status = 0, pci_rd_rc1, pci_rd_rc2;
1992 	bool en_rn_msg = true;
1993 	struct temp_event temp_event_data;
1994 	struct lpfc_register portsmphr_reg;
1995 	int rc, i;
1996 
1997 	/* If the pci channel is offline, ignore possible errors, since
1998 	 * we cannot communicate with the pci card anyway.
1999 	 */
2000 	if (pci_channel_offline(phba->pcidev)) {
2001 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2002 				"3166 pci channel is offline\n");
2003 		lpfc_sli_flush_io_rings(phba);
2004 		return;
2005 	}
2006 
2007 	memset(&portsmphr_reg, 0, sizeof(portsmphr_reg));
2008 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
2009 	switch (if_type) {
2010 	case LPFC_SLI_INTF_IF_TYPE_0:
2011 		pci_rd_rc1 = lpfc_readl(
2012 				phba->sli4_hba.u.if_type0.UERRLOregaddr,
2013 				&uerrlo_reg);
2014 		pci_rd_rc2 = lpfc_readl(
2015 				phba->sli4_hba.u.if_type0.UEMASKLOregaddr,
2016 				&uemasklo_reg);
2017 		/* consider PCI bus read error as pci_channel_offline */
2018 		if (pci_rd_rc1 == -EIO && pci_rd_rc2 == -EIO)
2019 			return;
2020 		if (!test_bit(HBA_RECOVERABLE_UE, &phba->hba_flag)) {
2021 			lpfc_sli4_offline_eratt(phba);
2022 			return;
2023 		}
2024 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2025 				"7623 Checking UE recoverable");
2026 
2027 		for (i = 0; i < phba->sli4_hba.ue_to_sr / 1000; i++) {
2028 			if (lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
2029 				       &portsmphr_reg.word0))
2030 				continue;
2031 
2032 			smphr_port_status = bf_get(lpfc_port_smphr_port_status,
2033 						   &portsmphr_reg);
2034 			if ((smphr_port_status & LPFC_PORT_SEM_MASK) ==
2035 			    LPFC_PORT_SEM_UE_RECOVERABLE)
2036 				break;
2037 			/*Sleep for 1Sec, before checking SEMAPHORE */
2038 			msleep(1000);
2039 		}
2040 
2041 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2042 				"4827 smphr_port_status x%x : Waited %dSec",
2043 				smphr_port_status, i);
2044 
2045 		/* Recoverable UE, reset the HBA device */
2046 		if ((smphr_port_status & LPFC_PORT_SEM_MASK) ==
2047 		    LPFC_PORT_SEM_UE_RECOVERABLE) {
2048 			for (i = 0; i < 20; i++) {
2049 				msleep(1000);
2050 				if (!lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
2051 				    &portsmphr_reg.word0) &&
2052 				    (LPFC_POST_STAGE_PORT_READY ==
2053 				     bf_get(lpfc_port_smphr_port_status,
2054 				     &portsmphr_reg))) {
2055 					rc = lpfc_sli4_port_sta_fn_reset(phba,
2056 						LPFC_MBX_NO_WAIT, en_rn_msg);
2057 					if (rc == 0)
2058 						return;
2059 					lpfc_printf_log(phba, KERN_ERR,
2060 						LOG_TRACE_EVENT,
2061 						"4215 Failed to recover UE");
2062 					break;
2063 				}
2064 			}
2065 		}
2066 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2067 				"7624 Firmware not ready: Failing UE recovery,"
2068 				" waited %dSec", i);
2069 		phba->link_state = LPFC_HBA_ERROR;
2070 		break;
2071 
2072 	case LPFC_SLI_INTF_IF_TYPE_2:
2073 	case LPFC_SLI_INTF_IF_TYPE_6:
2074 		pci_rd_rc1 = lpfc_readl(
2075 				phba->sli4_hba.u.if_type2.STATUSregaddr,
2076 				&portstat_reg.word0);
2077 		/* consider PCI bus read error as pci_channel_offline */
2078 		if (pci_rd_rc1 == -EIO) {
2079 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2080 				"3151 PCI bus read access failure: x%x\n",
2081 				readl(phba->sli4_hba.u.if_type2.STATUSregaddr));
2082 			lpfc_sli4_offline_eratt(phba);
2083 			return;
2084 		}
2085 		reg_err1 = readl(phba->sli4_hba.u.if_type2.ERR1regaddr);
2086 		reg_err2 = readl(phba->sli4_hba.u.if_type2.ERR2regaddr);
2087 		if (bf_get(lpfc_sliport_status_oti, &portstat_reg)) {
2088 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2089 					"2889 Port Overtemperature event, "
2090 					"taking port offline Data: x%x x%x\n",
2091 					reg_err1, reg_err2);
2092 
2093 			phba->sfp_alarm |= LPFC_TRANSGRESSION_HIGH_TEMPERATURE;
2094 			temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
2095 			temp_event_data.event_code = LPFC_CRIT_TEMP;
2096 			temp_event_data.data = 0xFFFFFFFF;
2097 
2098 			shost = lpfc_shost_from_vport(phba->pport);
2099 			fc_host_post_vendor_event(shost, fc_get_event_number(),
2100 						  sizeof(temp_event_data),
2101 						  (char *)&temp_event_data,
2102 						  SCSI_NL_VID_TYPE_PCI
2103 						  | PCI_VENDOR_ID_EMULEX);
2104 
2105 			spin_lock_irq(&phba->hbalock);
2106 			phba->over_temp_state = HBA_OVER_TEMP;
2107 			spin_unlock_irq(&phba->hbalock);
2108 			lpfc_sli4_offline_eratt(phba);
2109 			return;
2110 		}
2111 		if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2112 		    reg_err2 == SLIPORT_ERR2_REG_FW_RESTART) {
2113 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2114 					"3143 Port Down: Firmware Update "
2115 					"Detected\n");
2116 			en_rn_msg = false;
2117 		} else if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2118 			 reg_err2 == SLIPORT_ERR2_REG_FORCED_DUMP)
2119 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2120 					"3144 Port Down: Debug Dump\n");
2121 		else if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2122 			 reg_err2 == SLIPORT_ERR2_REG_FUNC_PROVISON)
2123 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2124 					"3145 Port Down: Provisioning\n");
2125 
2126 		/* If resets are disabled then leave the HBA alone and return */
2127 		if (!phba->cfg_enable_hba_reset)
2128 			return;
2129 
2130 		/* Check port status register for function reset */
2131 		rc = lpfc_sli4_port_sta_fn_reset(phba, LPFC_MBX_NO_WAIT,
2132 				en_rn_msg);
2133 		if (rc == 0) {
2134 			/* don't report event on forced debug dump */
2135 			if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2136 			    reg_err2 == SLIPORT_ERR2_REG_FORCED_DUMP)
2137 				return;
2138 			else
2139 				break;
2140 		}
2141 		/* fall through for not able to recover */
2142 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2143 				"3152 Unrecoverable error\n");
2144 		lpfc_sli4_offline_eratt(phba);
2145 		break;
2146 	case LPFC_SLI_INTF_IF_TYPE_1:
2147 	default:
2148 		break;
2149 	}
2150 	lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
2151 			"3123 Report dump event to upper layer\n");
2152 	/* Send an internal error event to mgmt application */
2153 	lpfc_board_errevt_to_mgmt(phba);
2154 
2155 	event_data = FC_REG_DUMP_EVENT;
2156 	shost = lpfc_shost_from_vport(vport);
2157 	fc_host_post_vendor_event(shost, fc_get_event_number(),
2158 				  sizeof(event_data), (char *) &event_data,
2159 				  SCSI_NL_VID_TYPE_PCI | PCI_VENDOR_ID_EMULEX);
2160 }
2161 
2162 /**
2163  * lpfc_handle_eratt - Wrapper func for handling hba error attention
2164  * @phba: pointer to lpfc HBA data structure.
2165  *
2166  * This routine wraps the actual SLI3 or SLI4 hba error attention handling
2167  * routine from the API jump table function pointer from the lpfc_hba struct.
2168  *
2169  * Return codes
2170  *   0 - success.
2171  *   Any other value - error.
2172  **/
2173 void
2174 lpfc_handle_eratt(struct lpfc_hba *phba)
2175 {
2176 	(*phba->lpfc_handle_eratt)(phba);
2177 }
2178 
2179 /**
2180  * lpfc_handle_latt - The HBA link event handler
2181  * @phba: pointer to lpfc hba data structure.
2182  *
2183  * This routine is invoked from the worker thread to handle a HBA host
2184  * attention link event. SLI3 only.
2185  **/
2186 void
2187 lpfc_handle_latt(struct lpfc_hba *phba)
2188 {
2189 	struct lpfc_vport *vport = phba->pport;
2190 	struct lpfc_sli   *psli = &phba->sli;
2191 	LPFC_MBOXQ_t *pmb;
2192 	volatile uint32_t control;
2193 	int rc = 0;
2194 
2195 	pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
2196 	if (!pmb) {
2197 		rc = 1;
2198 		goto lpfc_handle_latt_err_exit;
2199 	}
2200 
2201 	rc = lpfc_mbox_rsrc_prep(phba, pmb);
2202 	if (rc) {
2203 		rc = 2;
2204 		mempool_free(pmb, phba->mbox_mem_pool);
2205 		goto lpfc_handle_latt_err_exit;
2206 	}
2207 
2208 	/* Cleanup any outstanding ELS commands */
2209 	lpfc_els_flush_all_cmd(phba);
2210 	psli->slistat.link_event++;
2211 	lpfc_read_topology(phba, pmb, pmb->ctx_buf);
2212 	pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
2213 	pmb->vport = vport;
2214 	/* Block ELS IOCBs until we have processed this mbox command */
2215 	phba->sli.sli3_ring[LPFC_ELS_RING].flag |= LPFC_STOP_IOCB_EVENT;
2216 	rc = lpfc_sli_issue_mbox (phba, pmb, MBX_NOWAIT);
2217 	if (rc == MBX_NOT_FINISHED) {
2218 		rc = 4;
2219 		goto lpfc_handle_latt_free_mbuf;
2220 	}
2221 
2222 	/* Clear Link Attention in HA REG */
2223 	spin_lock_irq(&phba->hbalock);
2224 	writel(HA_LATT, phba->HAregaddr);
2225 	readl(phba->HAregaddr); /* flush */
2226 	spin_unlock_irq(&phba->hbalock);
2227 
2228 	return;
2229 
2230 lpfc_handle_latt_free_mbuf:
2231 	phba->sli.sli3_ring[LPFC_ELS_RING].flag &= ~LPFC_STOP_IOCB_EVENT;
2232 	lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
2233 lpfc_handle_latt_err_exit:
2234 	/* Enable Link attention interrupts */
2235 	spin_lock_irq(&phba->hbalock);
2236 	psli->sli_flag |= LPFC_PROCESS_LA;
2237 	control = readl(phba->HCregaddr);
2238 	control |= HC_LAINT_ENA;
2239 	writel(control, phba->HCregaddr);
2240 	readl(phba->HCregaddr); /* flush */
2241 
2242 	/* Clear Link Attention in HA REG */
2243 	writel(HA_LATT, phba->HAregaddr);
2244 	readl(phba->HAregaddr); /* flush */
2245 	spin_unlock_irq(&phba->hbalock);
2246 	lpfc_linkdown(phba);
2247 	phba->link_state = LPFC_HBA_ERROR;
2248 
2249 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2250 			"0300 LATT: Cannot issue READ_LA: Data:%d\n", rc);
2251 
2252 	return;
2253 }
2254 
2255 static void
2256 lpfc_fill_vpd(struct lpfc_hba *phba, uint8_t *vpd, int length, int *pindex)
2257 {
2258 	int i, j;
2259 
2260 	while (length > 0) {
2261 		/* Look for Serial Number */
2262 		if ((vpd[*pindex] == 'S') && (vpd[*pindex + 1] == 'N')) {
2263 			*pindex += 2;
2264 			i = vpd[*pindex];
2265 			*pindex += 1;
2266 			j = 0;
2267 			length -= (3+i);
2268 			while (i--) {
2269 				phba->SerialNumber[j++] = vpd[(*pindex)++];
2270 				if (j == 31)
2271 					break;
2272 			}
2273 			phba->SerialNumber[j] = 0;
2274 			continue;
2275 		} else if ((vpd[*pindex] == 'V') && (vpd[*pindex + 1] == '1')) {
2276 			phba->vpd_flag |= VPD_MODEL_DESC;
2277 			*pindex += 2;
2278 			i = vpd[*pindex];
2279 			*pindex += 1;
2280 			j = 0;
2281 			length -= (3+i);
2282 			while (i--) {
2283 				phba->ModelDesc[j++] = vpd[(*pindex)++];
2284 				if (j == 255)
2285 					break;
2286 			}
2287 			phba->ModelDesc[j] = 0;
2288 			continue;
2289 		} else if ((vpd[*pindex] == 'V') && (vpd[*pindex + 1] == '2')) {
2290 			phba->vpd_flag |= VPD_MODEL_NAME;
2291 			*pindex += 2;
2292 			i = vpd[*pindex];
2293 			*pindex += 1;
2294 			j = 0;
2295 			length -= (3+i);
2296 			while (i--) {
2297 				phba->ModelName[j++] = vpd[(*pindex)++];
2298 				if (j == 79)
2299 					break;
2300 			}
2301 			phba->ModelName[j] = 0;
2302 			continue;
2303 		} else if ((vpd[*pindex] == 'V') && (vpd[*pindex + 1] == '3')) {
2304 			phba->vpd_flag |= VPD_PROGRAM_TYPE;
2305 			*pindex += 2;
2306 			i = vpd[*pindex];
2307 			*pindex += 1;
2308 			j = 0;
2309 			length -= (3+i);
2310 			while (i--) {
2311 				phba->ProgramType[j++] = vpd[(*pindex)++];
2312 				if (j == 255)
2313 					break;
2314 			}
2315 			phba->ProgramType[j] = 0;
2316 			continue;
2317 		} else if ((vpd[*pindex] == 'V') && (vpd[*pindex + 1] == '4')) {
2318 			phba->vpd_flag |= VPD_PORT;
2319 			*pindex += 2;
2320 			i = vpd[*pindex];
2321 			*pindex += 1;
2322 			j = 0;
2323 			length -= (3 + i);
2324 			while (i--) {
2325 				if ((phba->sli_rev == LPFC_SLI_REV4) &&
2326 				    (phba->sli4_hba.pport_name_sta ==
2327 				     LPFC_SLI4_PPNAME_GET)) {
2328 					j++;
2329 					(*pindex)++;
2330 				} else
2331 					phba->Port[j++] = vpd[(*pindex)++];
2332 				if (j == 19)
2333 					break;
2334 			}
2335 			if ((phba->sli_rev != LPFC_SLI_REV4) ||
2336 			    (phba->sli4_hba.pport_name_sta ==
2337 			     LPFC_SLI4_PPNAME_NON))
2338 				phba->Port[j] = 0;
2339 			continue;
2340 		} else {
2341 			*pindex += 2;
2342 			i = vpd[*pindex];
2343 			*pindex += 1;
2344 			*pindex += i;
2345 			length -= (3 + i);
2346 		}
2347 	}
2348 }
2349 
2350 /**
2351  * lpfc_parse_vpd - Parse VPD (Vital Product Data)
2352  * @phba: pointer to lpfc hba data structure.
2353  * @vpd: pointer to the vital product data.
2354  * @len: length of the vital product data in bytes.
2355  *
2356  * This routine parses the Vital Product Data (VPD). The VPD is treated as
2357  * an array of characters. In this routine, the ModelName, ProgramType, and
2358  * ModelDesc, etc. fields of the phba data structure will be populated.
2359  *
2360  * Return codes
2361  *   0 - pointer to the VPD passed in is NULL
2362  *   1 - success
2363  **/
2364 int
2365 lpfc_parse_vpd(struct lpfc_hba *phba, uint8_t *vpd, int len)
2366 {
2367 	uint8_t lenlo, lenhi;
2368 	int Length;
2369 	int i;
2370 	int finished = 0;
2371 	int index = 0;
2372 
2373 	if (!vpd)
2374 		return 0;
2375 
2376 	/* Vital Product */
2377 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
2378 			"0455 Vital Product Data: x%x x%x x%x x%x\n",
2379 			(uint32_t) vpd[0], (uint32_t) vpd[1], (uint32_t) vpd[2],
2380 			(uint32_t) vpd[3]);
2381 	while (!finished && (index < (len - 4))) {
2382 		switch (vpd[index]) {
2383 		case 0x82:
2384 		case 0x91:
2385 			index += 1;
2386 			lenlo = vpd[index];
2387 			index += 1;
2388 			lenhi = vpd[index];
2389 			index += 1;
2390 			i = ((((unsigned short)lenhi) << 8) + lenlo);
2391 			index += i;
2392 			break;
2393 		case 0x90:
2394 			index += 1;
2395 			lenlo = vpd[index];
2396 			index += 1;
2397 			lenhi = vpd[index];
2398 			index += 1;
2399 			Length = ((((unsigned short)lenhi) << 8) + lenlo);
2400 			if (Length > len - index)
2401 				Length = len - index;
2402 
2403 			lpfc_fill_vpd(phba, vpd, Length, &index);
2404 			finished = 0;
2405 			break;
2406 		case 0x78:
2407 			finished = 1;
2408 			break;
2409 		default:
2410 			index ++;
2411 			break;
2412 		}
2413 	}
2414 
2415 	return(1);
2416 }
2417 
2418 /**
2419  * lpfc_get_atto_model_desc - Retrieve ATTO HBA device model name and description
2420  * @phba: pointer to lpfc hba data structure.
2421  * @mdp: pointer to the data structure to hold the derived model name.
2422  * @descp: pointer to the data structure to hold the derived description.
2423  *
2424  * This routine retrieves HBA's description based on its registered PCI device
2425  * ID. The @descp passed into this function points to an array of 256 chars. It
2426  * shall be returned with the model name, maximum speed, and the host bus type.
2427  * The @mdp passed into this function points to an array of 80 chars. When the
2428  * function returns, the @mdp will be filled with the model name.
2429  **/
2430 static void
2431 lpfc_get_atto_model_desc(struct lpfc_hba *phba, uint8_t *mdp, uint8_t *descp)
2432 {
2433 	uint16_t sub_dev_id = phba->pcidev->subsystem_device;
2434 	char *model = "<Unknown>";
2435 	int tbolt = 0;
2436 
2437 	switch (sub_dev_id) {
2438 	case PCI_DEVICE_ID_CLRY_161E:
2439 		model = "161E";
2440 		break;
2441 	case PCI_DEVICE_ID_CLRY_162E:
2442 		model = "162E";
2443 		break;
2444 	case PCI_DEVICE_ID_CLRY_164E:
2445 		model = "164E";
2446 		break;
2447 	case PCI_DEVICE_ID_CLRY_161P:
2448 		model = "161P";
2449 		break;
2450 	case PCI_DEVICE_ID_CLRY_162P:
2451 		model = "162P";
2452 		break;
2453 	case PCI_DEVICE_ID_CLRY_164P:
2454 		model = "164P";
2455 		break;
2456 	case PCI_DEVICE_ID_CLRY_321E:
2457 		model = "321E";
2458 		break;
2459 	case PCI_DEVICE_ID_CLRY_322E:
2460 		model = "322E";
2461 		break;
2462 	case PCI_DEVICE_ID_CLRY_324E:
2463 		model = "324E";
2464 		break;
2465 	case PCI_DEVICE_ID_CLRY_321P:
2466 		model = "321P";
2467 		break;
2468 	case PCI_DEVICE_ID_CLRY_322P:
2469 		model = "322P";
2470 		break;
2471 	case PCI_DEVICE_ID_CLRY_324P:
2472 		model = "324P";
2473 		break;
2474 	case PCI_DEVICE_ID_TLFC_2XX2:
2475 		model = "2XX2";
2476 		tbolt = 1;
2477 		break;
2478 	case PCI_DEVICE_ID_TLFC_3162:
2479 		model = "3162";
2480 		tbolt = 1;
2481 		break;
2482 	case PCI_DEVICE_ID_TLFC_3322:
2483 		model = "3322";
2484 		tbolt = 1;
2485 		break;
2486 	default:
2487 		model = "Unknown";
2488 		break;
2489 	}
2490 
2491 	if (mdp && mdp[0] == '\0')
2492 		snprintf(mdp, 79, "%s", model);
2493 
2494 	if (descp && descp[0] == '\0')
2495 		snprintf(descp, 255,
2496 			 "ATTO %s%s, Fibre Channel Adapter Initiator, Port %s",
2497 			 (tbolt) ? "ThunderLink FC " : "Celerity FC-",
2498 			 model,
2499 			 phba->Port);
2500 }
2501 
2502 /**
2503  * lpfc_get_hba_model_desc - Retrieve HBA device model name and description
2504  * @phba: pointer to lpfc hba data structure.
2505  * @mdp: pointer to the data structure to hold the derived model name.
2506  * @descp: pointer to the data structure to hold the derived description.
2507  *
2508  * This routine retrieves HBA's description based on its registered PCI device
2509  * ID. The @descp passed into this function points to an array of 256 chars. It
2510  * shall be returned with the model name, maximum speed, and the host bus type.
2511  * The @mdp passed into this function points to an array of 80 chars. When the
2512  * function returns, the @mdp will be filled with the model name.
2513  **/
2514 static void
2515 lpfc_get_hba_model_desc(struct lpfc_hba *phba, uint8_t *mdp, uint8_t *descp)
2516 {
2517 	lpfc_vpd_t *vp;
2518 	uint16_t dev_id = phba->pcidev->device;
2519 	int max_speed;
2520 	int GE = 0;
2521 	int oneConnect = 0; /* default is not a oneConnect */
2522 	struct {
2523 		char *name;
2524 		char *bus;
2525 		char *function;
2526 	} m = {"<Unknown>", "", ""};
2527 
2528 	if (mdp && mdp[0] != '\0'
2529 		&& descp && descp[0] != '\0')
2530 		return;
2531 
2532 	if (phba->pcidev->vendor == PCI_VENDOR_ID_ATTO) {
2533 		lpfc_get_atto_model_desc(phba, mdp, descp);
2534 		return;
2535 	}
2536 
2537 	if (phba->lmt & LMT_64Gb)
2538 		max_speed = 64;
2539 	else if (phba->lmt & LMT_32Gb)
2540 		max_speed = 32;
2541 	else if (phba->lmt & LMT_16Gb)
2542 		max_speed = 16;
2543 	else if (phba->lmt & LMT_10Gb)
2544 		max_speed = 10;
2545 	else if (phba->lmt & LMT_8Gb)
2546 		max_speed = 8;
2547 	else if (phba->lmt & LMT_4Gb)
2548 		max_speed = 4;
2549 	else if (phba->lmt & LMT_2Gb)
2550 		max_speed = 2;
2551 	else if (phba->lmt & LMT_1Gb)
2552 		max_speed = 1;
2553 	else
2554 		max_speed = 0;
2555 
2556 	vp = &phba->vpd;
2557 
2558 	switch (dev_id) {
2559 	case PCI_DEVICE_ID_FIREFLY:
2560 		m = (typeof(m)){"LP6000", "PCI",
2561 				"Obsolete, Unsupported Fibre Channel Adapter"};
2562 		break;
2563 	case PCI_DEVICE_ID_SUPERFLY:
2564 		if (vp->rev.biuRev >= 1 && vp->rev.biuRev <= 3)
2565 			m = (typeof(m)){"LP7000", "PCI", ""};
2566 		else
2567 			m = (typeof(m)){"LP7000E", "PCI", ""};
2568 		m.function = "Obsolete, Unsupported Fibre Channel Adapter";
2569 		break;
2570 	case PCI_DEVICE_ID_DRAGONFLY:
2571 		m = (typeof(m)){"LP8000", "PCI",
2572 				"Obsolete, Unsupported Fibre Channel Adapter"};
2573 		break;
2574 	case PCI_DEVICE_ID_CENTAUR:
2575 		if (FC_JEDEC_ID(vp->rev.biuRev) == CENTAUR_2G_JEDEC_ID)
2576 			m = (typeof(m)){"LP9002", "PCI", ""};
2577 		else
2578 			m = (typeof(m)){"LP9000", "PCI", ""};
2579 		m.function = "Obsolete, Unsupported Fibre Channel Adapter";
2580 		break;
2581 	case PCI_DEVICE_ID_RFLY:
2582 		m = (typeof(m)){"LP952", "PCI",
2583 				"Obsolete, Unsupported Fibre Channel Adapter"};
2584 		break;
2585 	case PCI_DEVICE_ID_PEGASUS:
2586 		m = (typeof(m)){"LP9802", "PCI-X",
2587 				"Obsolete, Unsupported Fibre Channel Adapter"};
2588 		break;
2589 	case PCI_DEVICE_ID_THOR:
2590 		m = (typeof(m)){"LP10000", "PCI-X",
2591 				"Obsolete, Unsupported Fibre Channel Adapter"};
2592 		break;
2593 	case PCI_DEVICE_ID_VIPER:
2594 		m = (typeof(m)){"LPX1000",  "PCI-X",
2595 				"Obsolete, Unsupported Fibre Channel Adapter"};
2596 		break;
2597 	case PCI_DEVICE_ID_PFLY:
2598 		m = (typeof(m)){"LP982", "PCI-X",
2599 				"Obsolete, Unsupported Fibre Channel Adapter"};
2600 		break;
2601 	case PCI_DEVICE_ID_TFLY:
2602 		m = (typeof(m)){"LP1050", "PCI-X",
2603 				"Obsolete, Unsupported Fibre Channel Adapter"};
2604 		break;
2605 	case PCI_DEVICE_ID_HELIOS:
2606 		m = (typeof(m)){"LP11000", "PCI-X2",
2607 				"Obsolete, Unsupported Fibre Channel Adapter"};
2608 		break;
2609 	case PCI_DEVICE_ID_HELIOS_SCSP:
2610 		m = (typeof(m)){"LP11000-SP", "PCI-X2",
2611 				"Obsolete, Unsupported Fibre Channel Adapter"};
2612 		break;
2613 	case PCI_DEVICE_ID_HELIOS_DCSP:
2614 		m = (typeof(m)){"LP11002-SP",  "PCI-X2",
2615 				"Obsolete, Unsupported Fibre Channel Adapter"};
2616 		break;
2617 	case PCI_DEVICE_ID_NEPTUNE:
2618 		m = (typeof(m)){"LPe1000", "PCIe",
2619 				"Obsolete, Unsupported Fibre Channel Adapter"};
2620 		break;
2621 	case PCI_DEVICE_ID_NEPTUNE_SCSP:
2622 		m = (typeof(m)){"LPe1000-SP", "PCIe",
2623 				"Obsolete, Unsupported Fibre Channel Adapter"};
2624 		break;
2625 	case PCI_DEVICE_ID_NEPTUNE_DCSP:
2626 		m = (typeof(m)){"LPe1002-SP", "PCIe",
2627 				"Obsolete, Unsupported Fibre Channel Adapter"};
2628 		break;
2629 	case PCI_DEVICE_ID_BMID:
2630 		m = (typeof(m)){"LP1150", "PCI-X2",
2631 				"Obsolete, Unsupported Fibre Channel Adapter"};
2632 		break;
2633 	case PCI_DEVICE_ID_BSMB:
2634 		m = (typeof(m)){"LP111", "PCI-X2",
2635 				"Obsolete, Unsupported Fibre Channel Adapter"};
2636 		break;
2637 	case PCI_DEVICE_ID_ZEPHYR:
2638 		m = (typeof(m)){"LPe11000", "PCIe",
2639 				"Obsolete, Unsupported Fibre Channel Adapter"};
2640 		break;
2641 	case PCI_DEVICE_ID_ZEPHYR_SCSP:
2642 		m = (typeof(m)){"LPe11000", "PCIe",
2643 				"Obsolete, Unsupported Fibre Channel Adapter"};
2644 		break;
2645 	case PCI_DEVICE_ID_ZEPHYR_DCSP:
2646 		m = (typeof(m)){"LP2105", "PCIe",
2647 				"Obsolete, Unsupported FCoE Adapter"};
2648 		GE = 1;
2649 		break;
2650 	case PCI_DEVICE_ID_ZMID:
2651 		m = (typeof(m)){"LPe1150", "PCIe",
2652 				"Obsolete, Unsupported Fibre Channel Adapter"};
2653 		break;
2654 	case PCI_DEVICE_ID_ZSMB:
2655 		m = (typeof(m)){"LPe111", "PCIe",
2656 				"Obsolete, Unsupported Fibre Channel Adapter"};
2657 		break;
2658 	case PCI_DEVICE_ID_LP101:
2659 		m = (typeof(m)){"LP101", "PCI-X",
2660 				"Obsolete, Unsupported Fibre Channel Adapter"};
2661 		break;
2662 	case PCI_DEVICE_ID_LP10000S:
2663 		m = (typeof(m)){"LP10000-S", "PCI",
2664 				"Obsolete, Unsupported Fibre Channel Adapter"};
2665 		break;
2666 	case PCI_DEVICE_ID_LP11000S:
2667 		m = (typeof(m)){"LP11000-S", "PCI-X2",
2668 				"Obsolete, Unsupported Fibre Channel Adapter"};
2669 		break;
2670 	case PCI_DEVICE_ID_LPE11000S:
2671 		m = (typeof(m)){"LPe11000-S", "PCIe",
2672 				"Obsolete, Unsupported Fibre Channel Adapter"};
2673 		break;
2674 	case PCI_DEVICE_ID_SAT:
2675 		m = (typeof(m)){"LPe12000", "PCIe",
2676 				"Obsolete, Unsupported Fibre Channel Adapter"};
2677 		break;
2678 	case PCI_DEVICE_ID_SAT_MID:
2679 		m = (typeof(m)){"LPe1250", "PCIe",
2680 				"Obsolete, Unsupported Fibre Channel Adapter"};
2681 		break;
2682 	case PCI_DEVICE_ID_SAT_SMB:
2683 		m = (typeof(m)){"LPe121", "PCIe",
2684 				"Obsolete, Unsupported Fibre Channel Adapter"};
2685 		break;
2686 	case PCI_DEVICE_ID_SAT_DCSP:
2687 		m = (typeof(m)){"LPe12002-SP", "PCIe",
2688 				"Obsolete, Unsupported Fibre Channel Adapter"};
2689 		break;
2690 	case PCI_DEVICE_ID_SAT_SCSP:
2691 		m = (typeof(m)){"LPe12000-SP", "PCIe",
2692 				"Obsolete, Unsupported Fibre Channel Adapter"};
2693 		break;
2694 	case PCI_DEVICE_ID_SAT_S:
2695 		m = (typeof(m)){"LPe12000-S", "PCIe",
2696 				"Obsolete, Unsupported Fibre Channel Adapter"};
2697 		break;
2698 	case PCI_DEVICE_ID_PROTEUS_VF:
2699 		m = (typeof(m)){"LPev12000", "PCIe IOV",
2700 				"Obsolete, Unsupported Fibre Channel Adapter"};
2701 		break;
2702 	case PCI_DEVICE_ID_PROTEUS_PF:
2703 		m = (typeof(m)){"LPev12000", "PCIe IOV",
2704 				"Obsolete, Unsupported Fibre Channel Adapter"};
2705 		break;
2706 	case PCI_DEVICE_ID_PROTEUS_S:
2707 		m = (typeof(m)){"LPemv12002-S", "PCIe IOV",
2708 				"Obsolete, Unsupported Fibre Channel Adapter"};
2709 		break;
2710 	case PCI_DEVICE_ID_TIGERSHARK:
2711 		oneConnect = 1;
2712 		m = (typeof(m)){"OCe10100", "PCIe",
2713 				"Obsolete, Unsupported FCoE Adapter"};
2714 		break;
2715 	case PCI_DEVICE_ID_TOMCAT:
2716 		oneConnect = 1;
2717 		m = (typeof(m)){"OCe11100", "PCIe",
2718 				"Obsolete, Unsupported FCoE Adapter"};
2719 		break;
2720 	case PCI_DEVICE_ID_FALCON:
2721 		m = (typeof(m)){"LPSe12002-ML1-E", "PCIe",
2722 				"Obsolete, Unsupported Fibre Channel Adapter"};
2723 		break;
2724 	case PCI_DEVICE_ID_BALIUS:
2725 		m = (typeof(m)){"LPVe12002", "PCIe Shared I/O",
2726 				"Obsolete, Unsupported Fibre Channel Adapter"};
2727 		break;
2728 	case PCI_DEVICE_ID_LANCER_FC:
2729 		m = (typeof(m)){"LPe16000", "PCIe",
2730 				"Obsolete, Unsupported Fibre Channel Adapter"};
2731 		break;
2732 	case PCI_DEVICE_ID_LANCER_FC_VF:
2733 		m = (typeof(m)){"LPe16000", "PCIe",
2734 				"Obsolete, Unsupported Fibre Channel Adapter"};
2735 		break;
2736 	case PCI_DEVICE_ID_LANCER_FCOE:
2737 		oneConnect = 1;
2738 		m = (typeof(m)){"OCe15100", "PCIe",
2739 				"Obsolete, Unsupported FCoE Adapter"};
2740 		break;
2741 	case PCI_DEVICE_ID_LANCER_FCOE_VF:
2742 		oneConnect = 1;
2743 		m = (typeof(m)){"OCe15100", "PCIe",
2744 				"Obsolete, Unsupported FCoE Adapter"};
2745 		break;
2746 	case PCI_DEVICE_ID_LANCER_G6_FC:
2747 		m = (typeof(m)){"LPe32000", "PCIe", "Fibre Channel Adapter"};
2748 		break;
2749 	case PCI_DEVICE_ID_LANCER_G7_FC:
2750 		m = (typeof(m)){"LPe36000", "PCIe", "Fibre Channel Adapter"};
2751 		break;
2752 	case PCI_DEVICE_ID_LANCER_G7P_FC:
2753 		m = (typeof(m)){"LPe38000", "PCIe", "Fibre Channel Adapter"};
2754 		break;
2755 	case PCI_DEVICE_ID_SKYHAWK:
2756 	case PCI_DEVICE_ID_SKYHAWK_VF:
2757 		oneConnect = 1;
2758 		m = (typeof(m)){"OCe14000", "PCIe",
2759 				"Obsolete, Unsupported FCoE Adapter"};
2760 		break;
2761 	default:
2762 		m = (typeof(m)){"Unknown", "", ""};
2763 		break;
2764 	}
2765 
2766 	if (mdp && mdp[0] == '\0')
2767 		snprintf(mdp, 79,"%s", m.name);
2768 	/*
2769 	 * oneConnect hba requires special processing, they are all initiators
2770 	 * and we put the port number on the end
2771 	 */
2772 	if (descp && descp[0] == '\0') {
2773 		if (oneConnect)
2774 			snprintf(descp, 255,
2775 				"Emulex OneConnect %s, %s Initiator %s",
2776 				m.name, m.function,
2777 				phba->Port);
2778 		else if (max_speed == 0)
2779 			snprintf(descp, 255,
2780 				"Emulex %s %s %s",
2781 				m.name, m.bus, m.function);
2782 		else
2783 			snprintf(descp, 255,
2784 				"Emulex %s %d%s %s %s",
2785 				m.name, max_speed, (GE) ? "GE" : "Gb",
2786 				m.bus, m.function);
2787 	}
2788 }
2789 
2790 /**
2791  * lpfc_sli3_post_buffer - Post IOCB(s) with DMA buffer descriptor(s) to a IOCB ring
2792  * @phba: pointer to lpfc hba data structure.
2793  * @pring: pointer to a IOCB ring.
2794  * @cnt: the number of IOCBs to be posted to the IOCB ring.
2795  *
2796  * This routine posts a given number of IOCBs with the associated DMA buffer
2797  * descriptors specified by the cnt argument to the given IOCB ring.
2798  *
2799  * Return codes
2800  *   The number of IOCBs NOT able to be posted to the IOCB ring.
2801  **/
2802 int
2803 lpfc_sli3_post_buffer(struct lpfc_hba *phba, struct lpfc_sli_ring *pring, int cnt)
2804 {
2805 	IOCB_t *icmd;
2806 	struct lpfc_iocbq *iocb;
2807 	struct lpfc_dmabuf *mp1, *mp2;
2808 
2809 	cnt += pring->missbufcnt;
2810 
2811 	/* While there are buffers to post */
2812 	while (cnt > 0) {
2813 		/* Allocate buffer for  command iocb */
2814 		iocb = lpfc_sli_get_iocbq(phba);
2815 		if (iocb == NULL) {
2816 			pring->missbufcnt = cnt;
2817 			return cnt;
2818 		}
2819 		icmd = &iocb->iocb;
2820 
2821 		/* 2 buffers can be posted per command */
2822 		/* Allocate buffer to post */
2823 		mp1 = kmalloc(sizeof (struct lpfc_dmabuf), GFP_KERNEL);
2824 		if (mp1)
2825 		    mp1->virt = lpfc_mbuf_alloc(phba, MEM_PRI, &mp1->phys);
2826 		if (!mp1 || !mp1->virt) {
2827 			kfree(mp1);
2828 			lpfc_sli_release_iocbq(phba, iocb);
2829 			pring->missbufcnt = cnt;
2830 			return cnt;
2831 		}
2832 
2833 		INIT_LIST_HEAD(&mp1->list);
2834 		/* Allocate buffer to post */
2835 		if (cnt > 1) {
2836 			mp2 = kmalloc(sizeof (struct lpfc_dmabuf), GFP_KERNEL);
2837 			if (mp2)
2838 				mp2->virt = lpfc_mbuf_alloc(phba, MEM_PRI,
2839 							    &mp2->phys);
2840 			if (!mp2 || !mp2->virt) {
2841 				kfree(mp2);
2842 				lpfc_mbuf_free(phba, mp1->virt, mp1->phys);
2843 				kfree(mp1);
2844 				lpfc_sli_release_iocbq(phba, iocb);
2845 				pring->missbufcnt = cnt;
2846 				return cnt;
2847 			}
2848 
2849 			INIT_LIST_HEAD(&mp2->list);
2850 		} else {
2851 			mp2 = NULL;
2852 		}
2853 
2854 		icmd->un.cont64[0].addrHigh = putPaddrHigh(mp1->phys);
2855 		icmd->un.cont64[0].addrLow = putPaddrLow(mp1->phys);
2856 		icmd->un.cont64[0].tus.f.bdeSize = FCELSSIZE;
2857 		icmd->ulpBdeCount = 1;
2858 		cnt--;
2859 		if (mp2) {
2860 			icmd->un.cont64[1].addrHigh = putPaddrHigh(mp2->phys);
2861 			icmd->un.cont64[1].addrLow = putPaddrLow(mp2->phys);
2862 			icmd->un.cont64[1].tus.f.bdeSize = FCELSSIZE;
2863 			cnt--;
2864 			icmd->ulpBdeCount = 2;
2865 		}
2866 
2867 		icmd->ulpCommand = CMD_QUE_RING_BUF64_CN;
2868 		icmd->ulpLe = 1;
2869 
2870 		if (lpfc_sli_issue_iocb(phba, pring->ringno, iocb, 0) ==
2871 		    IOCB_ERROR) {
2872 			lpfc_mbuf_free(phba, mp1->virt, mp1->phys);
2873 			kfree(mp1);
2874 			cnt++;
2875 			if (mp2) {
2876 				lpfc_mbuf_free(phba, mp2->virt, mp2->phys);
2877 				kfree(mp2);
2878 				cnt++;
2879 			}
2880 			lpfc_sli_release_iocbq(phba, iocb);
2881 			pring->missbufcnt = cnt;
2882 			return cnt;
2883 		}
2884 		lpfc_sli_ringpostbuf_put(phba, pring, mp1);
2885 		if (mp2)
2886 			lpfc_sli_ringpostbuf_put(phba, pring, mp2);
2887 	}
2888 	pring->missbufcnt = 0;
2889 	return 0;
2890 }
2891 
2892 /**
2893  * lpfc_post_rcv_buf - Post the initial receive IOCB buffers to ELS ring
2894  * @phba: pointer to lpfc hba data structure.
2895  *
2896  * This routine posts initial receive IOCB buffers to the ELS ring. The
2897  * current number of initial IOCB buffers specified by LPFC_BUF_RING0 is
2898  * set to 64 IOCBs. SLI3 only.
2899  *
2900  * Return codes
2901  *   0 - success (currently always success)
2902  **/
2903 static int
2904 lpfc_post_rcv_buf(struct lpfc_hba *phba)
2905 {
2906 	struct lpfc_sli *psli = &phba->sli;
2907 
2908 	/* Ring 0, ELS / CT buffers */
2909 	lpfc_sli3_post_buffer(phba, &psli->sli3_ring[LPFC_ELS_RING], LPFC_BUF_RING0);
2910 	/* Ring 2 - FCP no buffers needed */
2911 
2912 	return 0;
2913 }
2914 
2915 #define S(N,V) (((V)<<(N))|((V)>>(32-(N))))
2916 
2917 /**
2918  * lpfc_sha_init - Set up initial array of hash table entries
2919  * @HashResultPointer: pointer to an array as hash table.
2920  *
2921  * This routine sets up the initial values to the array of hash table entries
2922  * for the LC HBAs.
2923  **/
2924 static void
2925 lpfc_sha_init(uint32_t * HashResultPointer)
2926 {
2927 	HashResultPointer[0] = 0x67452301;
2928 	HashResultPointer[1] = 0xEFCDAB89;
2929 	HashResultPointer[2] = 0x98BADCFE;
2930 	HashResultPointer[3] = 0x10325476;
2931 	HashResultPointer[4] = 0xC3D2E1F0;
2932 }
2933 
2934 /**
2935  * lpfc_sha_iterate - Iterate initial hash table with the working hash table
2936  * @HashResultPointer: pointer to an initial/result hash table.
2937  * @HashWorkingPointer: pointer to an working hash table.
2938  *
2939  * This routine iterates an initial hash table pointed by @HashResultPointer
2940  * with the values from the working hash table pointeed by @HashWorkingPointer.
2941  * The results are putting back to the initial hash table, returned through
2942  * the @HashResultPointer as the result hash table.
2943  **/
2944 static void
2945 lpfc_sha_iterate(uint32_t * HashResultPointer, uint32_t * HashWorkingPointer)
2946 {
2947 	int t;
2948 	uint32_t TEMP;
2949 	uint32_t A, B, C, D, E;
2950 	t = 16;
2951 	do {
2952 		HashWorkingPointer[t] =
2953 		    S(1,
2954 		      HashWorkingPointer[t - 3] ^ HashWorkingPointer[t -
2955 								     8] ^
2956 		      HashWorkingPointer[t - 14] ^ HashWorkingPointer[t - 16]);
2957 	} while (++t <= 79);
2958 	t = 0;
2959 	A = HashResultPointer[0];
2960 	B = HashResultPointer[1];
2961 	C = HashResultPointer[2];
2962 	D = HashResultPointer[3];
2963 	E = HashResultPointer[4];
2964 
2965 	do {
2966 		if (t < 20) {
2967 			TEMP = ((B & C) | ((~B) & D)) + 0x5A827999;
2968 		} else if (t < 40) {
2969 			TEMP = (B ^ C ^ D) + 0x6ED9EBA1;
2970 		} else if (t < 60) {
2971 			TEMP = ((B & C) | (B & D) | (C & D)) + 0x8F1BBCDC;
2972 		} else {
2973 			TEMP = (B ^ C ^ D) + 0xCA62C1D6;
2974 		}
2975 		TEMP += S(5, A) + E + HashWorkingPointer[t];
2976 		E = D;
2977 		D = C;
2978 		C = S(30, B);
2979 		B = A;
2980 		A = TEMP;
2981 	} while (++t <= 79);
2982 
2983 	HashResultPointer[0] += A;
2984 	HashResultPointer[1] += B;
2985 	HashResultPointer[2] += C;
2986 	HashResultPointer[3] += D;
2987 	HashResultPointer[4] += E;
2988 
2989 }
2990 
2991 /**
2992  * lpfc_challenge_key - Create challenge key based on WWPN of the HBA
2993  * @RandomChallenge: pointer to the entry of host challenge random number array.
2994  * @HashWorking: pointer to the entry of the working hash array.
2995  *
2996  * This routine calculates the working hash array referred by @HashWorking
2997  * from the challenge random numbers associated with the host, referred by
2998  * @RandomChallenge. The result is put into the entry of the working hash
2999  * array and returned by reference through @HashWorking.
3000  **/
3001 static void
3002 lpfc_challenge_key(uint32_t * RandomChallenge, uint32_t * HashWorking)
3003 {
3004 	*HashWorking = (*RandomChallenge ^ *HashWorking);
3005 }
3006 
3007 /**
3008  * lpfc_hba_init - Perform special handling for LC HBA initialization
3009  * @phba: pointer to lpfc hba data structure.
3010  * @hbainit: pointer to an array of unsigned 32-bit integers.
3011  *
3012  * This routine performs the special handling for LC HBA initialization.
3013  **/
3014 void
3015 lpfc_hba_init(struct lpfc_hba *phba, uint32_t *hbainit)
3016 {
3017 	int t;
3018 	uint32_t *HashWorking;
3019 	uint32_t *pwwnn = (uint32_t *) phba->wwnn;
3020 
3021 	HashWorking = kcalloc(80, sizeof(uint32_t), GFP_KERNEL);
3022 	if (!HashWorking)
3023 		return;
3024 
3025 	HashWorking[0] = HashWorking[78] = *pwwnn++;
3026 	HashWorking[1] = HashWorking[79] = *pwwnn;
3027 
3028 	for (t = 0; t < 7; t++)
3029 		lpfc_challenge_key(phba->RandomData + t, HashWorking + t);
3030 
3031 	lpfc_sha_init(hbainit);
3032 	lpfc_sha_iterate(hbainit, HashWorking);
3033 	kfree(HashWorking);
3034 }
3035 
3036 /**
3037  * lpfc_cleanup - Performs vport cleanups before deleting a vport
3038  * @vport: pointer to a virtual N_Port data structure.
3039  *
3040  * This routine performs the necessary cleanups before deleting the @vport.
3041  * It invokes the discovery state machine to perform necessary state
3042  * transitions and to release the ndlps associated with the @vport. Note,
3043  * the physical port is treated as @vport 0.
3044  **/
3045 void
3046 lpfc_cleanup(struct lpfc_vport *vport)
3047 {
3048 	struct lpfc_hba   *phba = vport->phba;
3049 	struct lpfc_nodelist *ndlp, *next_ndlp;
3050 	int i = 0;
3051 
3052 	if (phba->link_state > LPFC_LINK_DOWN)
3053 		lpfc_port_link_failure(vport);
3054 
3055 	/* Clean up VMID resources */
3056 	if (lpfc_is_vmid_enabled(phba))
3057 		lpfc_vmid_vport_cleanup(vport);
3058 
3059 	list_for_each_entry_safe(ndlp, next_ndlp, &vport->fc_nodes, nlp_listp) {
3060 		if (ndlp->nlp_DID == Fabric_Cntl_DID &&
3061 		    ndlp->nlp_state == NLP_STE_UNUSED_NODE) {
3062 			lpfc_nlp_put(ndlp);
3063 			continue;
3064 		}
3065 
3066 		/* Fabric Ports not in UNMAPPED state are cleaned up in the
3067 		 * DEVICE_RM event.
3068 		 */
3069 		if (ndlp->nlp_type & NLP_FABRIC &&
3070 		    ndlp->nlp_state == NLP_STE_UNMAPPED_NODE)
3071 			lpfc_disc_state_machine(vport, ndlp, NULL,
3072 					NLP_EVT_DEVICE_RECOVERY);
3073 
3074 		if (!(ndlp->fc4_xpt_flags & (NVME_XPT_REGD|SCSI_XPT_REGD)))
3075 			lpfc_disc_state_machine(vport, ndlp, NULL,
3076 					NLP_EVT_DEVICE_RM);
3077 	}
3078 
3079 	/* This is a special case flush to return all
3080 	 * IOs before entering this loop. There are
3081 	 * two points in the code where a flush is
3082 	 * avoided if the FC_UNLOADING flag is set.
3083 	 * one is in the multipool destroy,
3084 	 * (this prevents a crash) and the other is
3085 	 * in the nvme abort handler, ( also prevents
3086 	 * a crash). Both of these exceptions are
3087 	 * cases where the slot is still accessible.
3088 	 * The flush here is only when the pci slot
3089 	 * is offline.
3090 	 */
3091 	if (test_bit(FC_UNLOADING, &vport->load_flag) &&
3092 	    pci_channel_offline(phba->pcidev))
3093 		lpfc_sli_flush_io_rings(vport->phba);
3094 
3095 	/* At this point, ALL ndlp's should be gone
3096 	 * because of the previous NLP_EVT_DEVICE_RM.
3097 	 * Lets wait for this to happen, if needed.
3098 	 */
3099 	while (!list_empty(&vport->fc_nodes)) {
3100 		if (i++ > 3000) {
3101 			lpfc_printf_vlog(vport, KERN_ERR,
3102 					 LOG_TRACE_EVENT,
3103 				"0233 Nodelist not empty\n");
3104 			list_for_each_entry_safe(ndlp, next_ndlp,
3105 						&vport->fc_nodes, nlp_listp) {
3106 				lpfc_printf_vlog(ndlp->vport, KERN_ERR,
3107 						 LOG_DISCOVERY,
3108 						 "0282 did:x%x ndlp:x%px "
3109 						 "refcnt:%d xflags x%x "
3110 						 "nflag x%lx\n",
3111 						 ndlp->nlp_DID, (void *)ndlp,
3112 						 kref_read(&ndlp->kref),
3113 						 ndlp->fc4_xpt_flags,
3114 						 ndlp->nlp_flag);
3115 			}
3116 			break;
3117 		}
3118 
3119 		/* Wait for any activity on ndlps to settle */
3120 		msleep(10);
3121 	}
3122 	lpfc_cleanup_vports_rrqs(vport, NULL);
3123 }
3124 
3125 /**
3126  * lpfc_stop_vport_timers - Stop all the timers associated with a vport
3127  * @vport: pointer to a virtual N_Port data structure.
3128  *
3129  * This routine stops all the timers associated with a @vport. This function
3130  * is invoked before disabling or deleting a @vport. Note that the physical
3131  * port is treated as @vport 0.
3132  **/
3133 void
3134 lpfc_stop_vport_timers(struct lpfc_vport *vport)
3135 {
3136 	timer_delete_sync(&vport->els_tmofunc);
3137 	timer_delete_sync(&vport->delayed_disc_tmo);
3138 	lpfc_can_disctmo(vport);
3139 	return;
3140 }
3141 
3142 /**
3143  * __lpfc_sli4_stop_fcf_redisc_wait_timer - Stop FCF rediscovery wait timer
3144  * @phba: pointer to lpfc hba data structure.
3145  *
3146  * This routine stops the SLI4 FCF rediscover wait timer if it's on. The
3147  * caller of this routine should already hold the host lock.
3148  **/
3149 void
3150 __lpfc_sli4_stop_fcf_redisc_wait_timer(struct lpfc_hba *phba)
3151 {
3152 	/* Clear pending FCF rediscovery wait flag */
3153 	phba->fcf.fcf_flag &= ~FCF_REDISC_PEND;
3154 
3155 	/* Now, try to stop the timer */
3156 	timer_delete(&phba->fcf.redisc_wait);
3157 }
3158 
3159 /**
3160  * lpfc_sli4_stop_fcf_redisc_wait_timer - Stop FCF rediscovery wait timer
3161  * @phba: pointer to lpfc hba data structure.
3162  *
3163  * This routine stops the SLI4 FCF rediscover wait timer if it's on. It
3164  * checks whether the FCF rediscovery wait timer is pending with the host
3165  * lock held before proceeding with disabling the timer and clearing the
3166  * wait timer pendig flag.
3167  **/
3168 void
3169 lpfc_sli4_stop_fcf_redisc_wait_timer(struct lpfc_hba *phba)
3170 {
3171 	spin_lock_irq(&phba->hbalock);
3172 	if (!(phba->fcf.fcf_flag & FCF_REDISC_PEND)) {
3173 		/* FCF rediscovery timer already fired or stopped */
3174 		spin_unlock_irq(&phba->hbalock);
3175 		return;
3176 	}
3177 	__lpfc_sli4_stop_fcf_redisc_wait_timer(phba);
3178 	/* Clear failover in progress flags */
3179 	phba->fcf.fcf_flag &= ~(FCF_DEAD_DISC | FCF_ACVL_DISC);
3180 	spin_unlock_irq(&phba->hbalock);
3181 }
3182 
3183 /**
3184  * lpfc_cmf_stop - Stop CMF processing
3185  * @phba: pointer to lpfc hba data structure.
3186  *
3187  * This is called when the link goes down or if CMF mode is turned OFF.
3188  * It is also called when going offline or unloaded just before the
3189  * congestion info buffer is unregistered.
3190  **/
3191 void
3192 lpfc_cmf_stop(struct lpfc_hba *phba)
3193 {
3194 	int cpu;
3195 	struct lpfc_cgn_stat *cgs;
3196 
3197 	/* We only do something if CMF is enabled */
3198 	if (!phba->sli4_hba.pc_sli4_params.cmf)
3199 		return;
3200 
3201 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
3202 			"6221 Stop CMF / Cancel Timer\n");
3203 
3204 	/* Cancel the CMF timer */
3205 	hrtimer_cancel(&phba->cmf_stats_timer);
3206 	hrtimer_cancel(&phba->cmf_timer);
3207 
3208 	/* Zero CMF counters */
3209 	atomic_set(&phba->cmf_busy, 0);
3210 	for_each_present_cpu(cpu) {
3211 		cgs = per_cpu_ptr(phba->cmf_stat, cpu);
3212 		atomic64_set(&cgs->total_bytes, 0);
3213 		atomic64_set(&cgs->rcv_bytes, 0);
3214 		atomic_set(&cgs->rx_io_cnt, 0);
3215 		atomic64_set(&cgs->rx_latency, 0);
3216 	}
3217 	atomic_set(&phba->cmf_bw_wait, 0);
3218 
3219 	/* Resume any blocked IO - Queue unblock on workqueue */
3220 	queue_work(phba->wq, &phba->unblock_request_work);
3221 }
3222 
3223 static inline uint64_t
3224 lpfc_get_max_line_rate(struct lpfc_hba *phba)
3225 {
3226 	uint64_t rate = lpfc_sli_port_speed_get(phba);
3227 
3228 	return ((((unsigned long)rate) * 1024 * 1024) / 10);
3229 }
3230 
3231 void
3232 lpfc_cmf_signal_init(struct lpfc_hba *phba)
3233 {
3234 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
3235 			"6223 Signal CMF init\n");
3236 
3237 	/* Use the new fc_linkspeed to recalculate */
3238 	phba->cmf_interval_rate = LPFC_CMF_INTERVAL;
3239 	phba->cmf_max_line_rate = lpfc_get_max_line_rate(phba);
3240 	phba->cmf_link_byte_count = div_u64(phba->cmf_max_line_rate *
3241 					    phba->cmf_interval_rate, 1000);
3242 	phba->cmf_max_bytes_per_interval = phba->cmf_link_byte_count;
3243 
3244 	/* This is a signal to firmware to sync up CMF BW with link speed */
3245 	lpfc_issue_cmf_sync_wqe(phba, 0, 0);
3246 }
3247 
3248 /**
3249  * lpfc_cmf_start - Start CMF processing
3250  * @phba: pointer to lpfc hba data structure.
3251  *
3252  * This is called when the link comes up or if CMF mode is turned OFF
3253  * to Monitor or Managed.
3254  **/
3255 void
3256 lpfc_cmf_start(struct lpfc_hba *phba)
3257 {
3258 	struct lpfc_cgn_stat *cgs;
3259 	int cpu;
3260 
3261 	/* We only do something if CMF is enabled */
3262 	if (!phba->sli4_hba.pc_sli4_params.cmf ||
3263 	    phba->cmf_active_mode == LPFC_CFG_OFF)
3264 		return;
3265 
3266 	/* Reinitialize congestion buffer info */
3267 	lpfc_init_congestion_buf(phba);
3268 
3269 	atomic_set(&phba->cgn_fabric_warn_cnt, 0);
3270 	atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
3271 	atomic_set(&phba->cgn_sync_alarm_cnt, 0);
3272 	atomic_set(&phba->cgn_sync_warn_cnt, 0);
3273 
3274 	atomic_set(&phba->cmf_busy, 0);
3275 	for_each_present_cpu(cpu) {
3276 		cgs = per_cpu_ptr(phba->cmf_stat, cpu);
3277 		atomic64_set(&cgs->total_bytes, 0);
3278 		atomic64_set(&cgs->rcv_bytes, 0);
3279 		atomic_set(&cgs->rx_io_cnt, 0);
3280 		atomic64_set(&cgs->rx_latency, 0);
3281 	}
3282 	phba->cmf_latency.tv_sec = 0;
3283 	phba->cmf_latency.tv_nsec = 0;
3284 
3285 	lpfc_cmf_signal_init(phba);
3286 
3287 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
3288 			"6222 Start CMF / Timer\n");
3289 
3290 	phba->cmf_timer_cnt = 0;
3291 	hrtimer_start(&phba->cmf_timer,
3292 		      ktime_set(0, LPFC_CMF_INTERVAL * NSEC_PER_MSEC),
3293 		      HRTIMER_MODE_REL);
3294 	hrtimer_start(&phba->cmf_stats_timer,
3295 		      ktime_set(0, LPFC_SEC_MIN * NSEC_PER_SEC),
3296 		      HRTIMER_MODE_REL);
3297 	/* Setup for latency check in IO cmpl routines */
3298 	ktime_get_real_ts64(&phba->cmf_latency);
3299 
3300 	atomic_set(&phba->cmf_bw_wait, 0);
3301 	atomic_set(&phba->cmf_stop_io, 0);
3302 }
3303 
3304 /**
3305  * lpfc_stop_hba_timers - Stop all the timers associated with an HBA
3306  * @phba: pointer to lpfc hba data structure.
3307  *
3308  * This routine stops all the timers associated with a HBA. This function is
3309  * invoked before either putting a HBA offline or unloading the driver.
3310  **/
3311 void
3312 lpfc_stop_hba_timers(struct lpfc_hba *phba)
3313 {
3314 	if (phba->pport)
3315 		lpfc_stop_vport_timers(phba->pport);
3316 	cancel_delayed_work_sync(&phba->eq_delay_work);
3317 	cancel_delayed_work_sync(&phba->idle_stat_delay_work);
3318 	timer_delete_sync(&phba->sli.mbox_tmo);
3319 	timer_delete_sync(&phba->fabric_block_timer);
3320 	timer_delete_sync(&phba->eratt_poll);
3321 	timer_delete_sync(&phba->hb_tmofunc);
3322 	if (phba->sli_rev == LPFC_SLI_REV4) {
3323 		timer_delete_sync(&phba->rrq_tmr);
3324 		clear_bit(HBA_RRQ_ACTIVE, &phba->hba_flag);
3325 	}
3326 	clear_bit(HBA_HBEAT_INP, &phba->hba_flag);
3327 	clear_bit(HBA_HBEAT_TMO, &phba->hba_flag);
3328 
3329 	switch (phba->pci_dev_grp) {
3330 	case LPFC_PCI_DEV_LP:
3331 		/* Stop any LightPulse device specific driver timers */
3332 		timer_delete_sync(&phba->fcp_poll_timer);
3333 		break;
3334 	case LPFC_PCI_DEV_OC:
3335 		/* Stop any OneConnect device specific driver timers */
3336 		lpfc_sli4_stop_fcf_redisc_wait_timer(phba);
3337 		break;
3338 	default:
3339 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3340 				"0297 Invalid device group (x%x)\n",
3341 				phba->pci_dev_grp);
3342 		break;
3343 	}
3344 	return;
3345 }
3346 
3347 /**
3348  * lpfc_block_mgmt_io - Mark a HBA's management interface as blocked
3349  * @phba: pointer to lpfc hba data structure.
3350  * @mbx_action: flag for mailbox no wait action.
3351  *
3352  * This routine marks a HBA's management interface as blocked. Once the HBA's
3353  * management interface is marked as blocked, all the user space access to
3354  * the HBA, whether they are from sysfs interface or libdfc interface will
3355  * all be blocked. The HBA is set to block the management interface when the
3356  * driver prepares the HBA interface for online or offline.
3357  **/
3358 static void
3359 lpfc_block_mgmt_io(struct lpfc_hba *phba, int mbx_action)
3360 {
3361 	unsigned long iflag;
3362 	uint8_t actcmd = MBX_HEARTBEAT;
3363 	unsigned long timeout;
3364 
3365 	spin_lock_irqsave(&phba->hbalock, iflag);
3366 	phba->sli.sli_flag |= LPFC_BLOCK_MGMT_IO;
3367 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3368 	if (mbx_action == LPFC_MBX_NO_WAIT)
3369 		return;
3370 	timeout = secs_to_jiffies(LPFC_MBOX_TMO) + jiffies;
3371 	spin_lock_irqsave(&phba->hbalock, iflag);
3372 	if (phba->sli.mbox_active) {
3373 		actcmd = phba->sli.mbox_active->u.mb.mbxCommand;
3374 		/* Determine how long we might wait for the active mailbox
3375 		 * command to be gracefully completed by firmware.
3376 		 */
3377 		timeout = secs_to_jiffies(lpfc_mbox_tmo_val(phba,
3378 				phba->sli.mbox_active)) + jiffies;
3379 	}
3380 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3381 
3382 	/* Wait for the outstnading mailbox command to complete */
3383 	while (phba->sli.mbox_active) {
3384 		/* Check active mailbox complete status every 2ms */
3385 		msleep(2);
3386 		if (time_after(jiffies, timeout)) {
3387 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3388 					"2813 Mgmt IO is Blocked %x "
3389 					"- mbox cmd %x still active\n",
3390 					phba->sli.sli_flag, actcmd);
3391 			break;
3392 		}
3393 	}
3394 }
3395 
3396 /**
3397  * lpfc_sli4_node_rpi_restore - Recover assigned RPIs for active nodes.
3398  * @phba: pointer to lpfc hba data structure.
3399  *
3400  * Allocate RPIs for all active remote nodes. This is needed whenever
3401  * an SLI4 adapter is reset and the driver is not unloading. Its purpose
3402  * is to fixup the temporary rpi assignments.
3403  **/
3404 void
3405 lpfc_sli4_node_rpi_restore(struct lpfc_hba *phba)
3406 {
3407 	struct lpfc_nodelist  *ndlp, *next_ndlp;
3408 	struct lpfc_vport **vports;
3409 	int i, rpi;
3410 
3411 	if (phba->sli_rev != LPFC_SLI_REV4)
3412 		return;
3413 
3414 	vports = lpfc_create_vport_work_array(phba);
3415 	if (!vports)
3416 		return;
3417 
3418 	for (i = 0; i <= phba->max_vports && vports[i]; i++) {
3419 		if (test_bit(FC_UNLOADING, &vports[i]->load_flag))
3420 			continue;
3421 
3422 		list_for_each_entry_safe(ndlp, next_ndlp,
3423 					 &vports[i]->fc_nodes,
3424 					 nlp_listp) {
3425 			rpi = lpfc_sli4_alloc_rpi(phba);
3426 			if (rpi == LPFC_RPI_ALLOC_ERROR) {
3427 				lpfc_printf_vlog(ndlp->vport, KERN_INFO,
3428 						 LOG_NODE | LOG_DISCOVERY,
3429 						 "0099 RPI alloc error for "
3430 						 "ndlp x%px DID:x%06x "
3431 						 "flg:x%lx\n",
3432 						 ndlp, ndlp->nlp_DID,
3433 						 ndlp->nlp_flag);
3434 				continue;
3435 			}
3436 			ndlp->nlp_rpi = rpi;
3437 			lpfc_printf_vlog(ndlp->vport, KERN_INFO,
3438 					 LOG_NODE | LOG_DISCOVERY,
3439 					 "0009 Assign RPI x%x to ndlp x%px "
3440 					 "DID:x%06x flg:x%lx\n",
3441 					 ndlp->nlp_rpi, ndlp, ndlp->nlp_DID,
3442 					 ndlp->nlp_flag);
3443 		}
3444 	}
3445 	lpfc_destroy_vport_work_array(phba, vports);
3446 }
3447 
3448 /**
3449  * lpfc_create_expedite_pool - create expedite pool
3450  * @phba: pointer to lpfc hba data structure.
3451  *
3452  * This routine moves a batch of XRIs from lpfc_io_buf_list_put of HWQ 0
3453  * to expedite pool. Mark them as expedite.
3454  **/
3455 static void lpfc_create_expedite_pool(struct lpfc_hba *phba)
3456 {
3457 	struct lpfc_sli4_hdw_queue *qp;
3458 	struct lpfc_io_buf *lpfc_ncmd;
3459 	struct lpfc_io_buf *lpfc_ncmd_next;
3460 	struct lpfc_epd_pool *epd_pool;
3461 	unsigned long iflag;
3462 
3463 	epd_pool = &phba->epd_pool;
3464 	qp = &phba->sli4_hba.hdwq[0];
3465 
3466 	spin_lock_init(&epd_pool->lock);
3467 	spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3468 	spin_lock(&epd_pool->lock);
3469 	INIT_LIST_HEAD(&epd_pool->list);
3470 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3471 				 &qp->lpfc_io_buf_list_put, list) {
3472 		list_move_tail(&lpfc_ncmd->list, &epd_pool->list);
3473 		lpfc_ncmd->expedite = true;
3474 		qp->put_io_bufs--;
3475 		epd_pool->count++;
3476 		if (epd_pool->count >= XRI_BATCH)
3477 			break;
3478 	}
3479 	spin_unlock(&epd_pool->lock);
3480 	spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3481 }
3482 
3483 /**
3484  * lpfc_destroy_expedite_pool - destroy expedite pool
3485  * @phba: pointer to lpfc hba data structure.
3486  *
3487  * This routine returns XRIs from expedite pool to lpfc_io_buf_list_put
3488  * of HWQ 0. Clear the mark.
3489  **/
3490 static void lpfc_destroy_expedite_pool(struct lpfc_hba *phba)
3491 {
3492 	struct lpfc_sli4_hdw_queue *qp;
3493 	struct lpfc_io_buf *lpfc_ncmd;
3494 	struct lpfc_io_buf *lpfc_ncmd_next;
3495 	struct lpfc_epd_pool *epd_pool;
3496 	unsigned long iflag;
3497 
3498 	epd_pool = &phba->epd_pool;
3499 	qp = &phba->sli4_hba.hdwq[0];
3500 
3501 	spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3502 	spin_lock(&epd_pool->lock);
3503 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3504 				 &epd_pool->list, list) {
3505 		list_move_tail(&lpfc_ncmd->list,
3506 			       &qp->lpfc_io_buf_list_put);
3507 		lpfc_ncmd->flags = false;
3508 		qp->put_io_bufs++;
3509 		epd_pool->count--;
3510 	}
3511 	spin_unlock(&epd_pool->lock);
3512 	spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3513 }
3514 
3515 /**
3516  * lpfc_create_multixri_pools - create multi-XRI pools
3517  * @phba: pointer to lpfc hba data structure.
3518  *
3519  * This routine initialize public, private per HWQ. Then, move XRIs from
3520  * lpfc_io_buf_list_put to public pool. High and low watermark are also
3521  * Initialized.
3522  **/
3523 void lpfc_create_multixri_pools(struct lpfc_hba *phba)
3524 {
3525 	u32 i, j;
3526 	u32 hwq_count;
3527 	u32 count_per_hwq;
3528 	struct lpfc_io_buf *lpfc_ncmd;
3529 	struct lpfc_io_buf *lpfc_ncmd_next;
3530 	unsigned long iflag;
3531 	struct lpfc_sli4_hdw_queue *qp;
3532 	struct lpfc_multixri_pool *multixri_pool;
3533 	struct lpfc_pbl_pool *pbl_pool;
3534 	struct lpfc_pvt_pool *pvt_pool;
3535 
3536 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3537 			"1234 num_hdw_queue=%d num_present_cpu=%d common_xri_cnt=%d\n",
3538 			phba->cfg_hdw_queue, phba->sli4_hba.num_present_cpu,
3539 			phba->sli4_hba.io_xri_cnt);
3540 
3541 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
3542 		lpfc_create_expedite_pool(phba);
3543 
3544 	hwq_count = phba->cfg_hdw_queue;
3545 	count_per_hwq = phba->sli4_hba.io_xri_cnt / hwq_count;
3546 
3547 	for (i = 0; i < hwq_count; i++) {
3548 		multixri_pool = kzalloc(sizeof(*multixri_pool), GFP_KERNEL);
3549 
3550 		if (!multixri_pool) {
3551 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3552 					"1238 Failed to allocate memory for "
3553 					"multixri_pool\n");
3554 
3555 			if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
3556 				lpfc_destroy_expedite_pool(phba);
3557 
3558 			j = 0;
3559 			while (j < i) {
3560 				qp = &phba->sli4_hba.hdwq[j];
3561 				kfree(qp->p_multixri_pool);
3562 				j++;
3563 			}
3564 			phba->cfg_xri_rebalancing = 0;
3565 			return;
3566 		}
3567 
3568 		qp = &phba->sli4_hba.hdwq[i];
3569 		qp->p_multixri_pool = multixri_pool;
3570 
3571 		multixri_pool->xri_limit = count_per_hwq;
3572 		multixri_pool->rrb_next_hwqid = i;
3573 
3574 		/* Deal with public free xri pool */
3575 		pbl_pool = &multixri_pool->pbl_pool;
3576 		spin_lock_init(&pbl_pool->lock);
3577 		spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3578 		spin_lock(&pbl_pool->lock);
3579 		INIT_LIST_HEAD(&pbl_pool->list);
3580 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3581 					 &qp->lpfc_io_buf_list_put, list) {
3582 			list_move_tail(&lpfc_ncmd->list, &pbl_pool->list);
3583 			qp->put_io_bufs--;
3584 			pbl_pool->count++;
3585 		}
3586 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3587 				"1235 Moved %d buffers from PUT list over to pbl_pool[%d]\n",
3588 				pbl_pool->count, i);
3589 		spin_unlock(&pbl_pool->lock);
3590 		spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3591 
3592 		/* Deal with private free xri pool */
3593 		pvt_pool = &multixri_pool->pvt_pool;
3594 		pvt_pool->high_watermark = multixri_pool->xri_limit / 2;
3595 		pvt_pool->low_watermark = XRI_BATCH;
3596 		spin_lock_init(&pvt_pool->lock);
3597 		spin_lock_irqsave(&pvt_pool->lock, iflag);
3598 		INIT_LIST_HEAD(&pvt_pool->list);
3599 		pvt_pool->count = 0;
3600 		spin_unlock_irqrestore(&pvt_pool->lock, iflag);
3601 	}
3602 }
3603 
3604 /**
3605  * lpfc_destroy_multixri_pools - destroy multi-XRI pools
3606  * @phba: pointer to lpfc hba data structure.
3607  *
3608  * This routine returns XRIs from public/private to lpfc_io_buf_list_put.
3609  **/
3610 static void lpfc_destroy_multixri_pools(struct lpfc_hba *phba)
3611 {
3612 	u32 i;
3613 	u32 hwq_count;
3614 	struct lpfc_io_buf *lpfc_ncmd;
3615 	struct lpfc_io_buf *lpfc_ncmd_next;
3616 	unsigned long iflag;
3617 	struct lpfc_sli4_hdw_queue *qp;
3618 	struct lpfc_multixri_pool *multixri_pool;
3619 	struct lpfc_pbl_pool *pbl_pool;
3620 	struct lpfc_pvt_pool *pvt_pool;
3621 
3622 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
3623 		lpfc_destroy_expedite_pool(phba);
3624 
3625 	if (!test_bit(FC_UNLOADING, &phba->pport->load_flag))
3626 		lpfc_sli_flush_io_rings(phba);
3627 
3628 	hwq_count = phba->cfg_hdw_queue;
3629 
3630 	for (i = 0; i < hwq_count; i++) {
3631 		qp = &phba->sli4_hba.hdwq[i];
3632 		multixri_pool = qp->p_multixri_pool;
3633 		if (!multixri_pool)
3634 			continue;
3635 
3636 		qp->p_multixri_pool = NULL;
3637 
3638 		spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3639 
3640 		/* Deal with public free xri pool */
3641 		pbl_pool = &multixri_pool->pbl_pool;
3642 		spin_lock(&pbl_pool->lock);
3643 
3644 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3645 				"1236 Moving %d buffers from pbl_pool[%d] TO PUT list\n",
3646 				pbl_pool->count, i);
3647 
3648 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3649 					 &pbl_pool->list, list) {
3650 			list_move_tail(&lpfc_ncmd->list,
3651 				       &qp->lpfc_io_buf_list_put);
3652 			qp->put_io_bufs++;
3653 			pbl_pool->count--;
3654 		}
3655 
3656 		INIT_LIST_HEAD(&pbl_pool->list);
3657 		pbl_pool->count = 0;
3658 
3659 		spin_unlock(&pbl_pool->lock);
3660 
3661 		/* Deal with private free xri pool */
3662 		pvt_pool = &multixri_pool->pvt_pool;
3663 		spin_lock(&pvt_pool->lock);
3664 
3665 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3666 				"1237 Moving %d buffers from pvt_pool[%d] TO PUT list\n",
3667 				pvt_pool->count, i);
3668 
3669 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3670 					 &pvt_pool->list, list) {
3671 			list_move_tail(&lpfc_ncmd->list,
3672 				       &qp->lpfc_io_buf_list_put);
3673 			qp->put_io_bufs++;
3674 			pvt_pool->count--;
3675 		}
3676 
3677 		INIT_LIST_HEAD(&pvt_pool->list);
3678 		pvt_pool->count = 0;
3679 
3680 		spin_unlock(&pvt_pool->lock);
3681 		spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3682 
3683 		kfree(multixri_pool);
3684 	}
3685 }
3686 
3687 /**
3688  * lpfc_online - Initialize and bring a HBA online
3689  * @phba: pointer to lpfc hba data structure.
3690  *
3691  * This routine initializes the HBA and brings a HBA online. During this
3692  * process, the management interface is blocked to prevent user space access
3693  * to the HBA interfering with the driver initialization.
3694  *
3695  * Return codes
3696  *   0 - successful
3697  *   1 - failed
3698  **/
3699 int
3700 lpfc_online(struct lpfc_hba *phba)
3701 {
3702 	struct lpfc_vport *vport;
3703 	struct lpfc_vport **vports;
3704 	int i, error = 0;
3705 	bool vpis_cleared = false;
3706 
3707 	if (!phba)
3708 		return 0;
3709 	vport = phba->pport;
3710 
3711 	if (!test_bit(FC_OFFLINE_MODE, &vport->fc_flag))
3712 		return 0;
3713 
3714 	lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
3715 			"0458 Bring Adapter online\n");
3716 
3717 	lpfc_block_mgmt_io(phba, LPFC_MBX_WAIT);
3718 
3719 	if (phba->sli_rev == LPFC_SLI_REV4) {
3720 		if (lpfc_sli4_hba_setup(phba)) { /* Initialize SLI4 HBA */
3721 			lpfc_unblock_mgmt_io(phba);
3722 			return 1;
3723 		}
3724 		spin_lock_irq(&phba->hbalock);
3725 		if (!phba->sli4_hba.max_cfg_param.vpi_used)
3726 			vpis_cleared = true;
3727 		spin_unlock_irq(&phba->hbalock);
3728 
3729 		/* Reestablish the local initiator port.
3730 		 * The offline process destroyed the previous lport.
3731 		 */
3732 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME &&
3733 				!phba->nvmet_support) {
3734 			error = lpfc_nvme_create_localport(phba->pport);
3735 			if (error)
3736 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3737 					"6132 NVME restore reg failed "
3738 					"on nvmei error x%x\n", error);
3739 		}
3740 	} else {
3741 		lpfc_sli_queue_init(phba);
3742 		if (lpfc_sli_hba_setup(phba)) {	/* Initialize SLI2/SLI3 HBA */
3743 			lpfc_unblock_mgmt_io(phba);
3744 			return 1;
3745 		}
3746 	}
3747 
3748 	vports = lpfc_create_vport_work_array(phba);
3749 	if (vports != NULL) {
3750 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3751 			clear_bit(FC_OFFLINE_MODE, &vports[i]->fc_flag);
3752 			if (phba->sli3_options & LPFC_SLI3_NPIV_ENABLED)
3753 				set_bit(FC_VPORT_NEEDS_REG_VPI,
3754 					&vports[i]->fc_flag);
3755 			if (phba->sli_rev == LPFC_SLI_REV4) {
3756 				set_bit(FC_VPORT_NEEDS_INIT_VPI,
3757 					&vports[i]->fc_flag);
3758 				if ((vpis_cleared) &&
3759 				    (vports[i]->port_type !=
3760 					LPFC_PHYSICAL_PORT))
3761 					vports[i]->vpi = 0;
3762 			}
3763 		}
3764 	}
3765 	lpfc_destroy_vport_work_array(phba, vports);
3766 
3767 	if (phba->cfg_xri_rebalancing)
3768 		lpfc_create_multixri_pools(phba);
3769 
3770 	lpfc_cpuhp_add(phba);
3771 
3772 	lpfc_unblock_mgmt_io(phba);
3773 	return 0;
3774 }
3775 
3776 /**
3777  * lpfc_unblock_mgmt_io - Mark a HBA's management interface to be not blocked
3778  * @phba: pointer to lpfc hba data structure.
3779  *
3780  * This routine marks a HBA's management interface as not blocked. Once the
3781  * HBA's management interface is marked as not blocked, all the user space
3782  * access to the HBA, whether they are from sysfs interface or libdfc
3783  * interface will be allowed. The HBA is set to block the management interface
3784  * when the driver prepares the HBA interface for online or offline and then
3785  * set to unblock the management interface afterwards.
3786  **/
3787 void
3788 lpfc_unblock_mgmt_io(struct lpfc_hba * phba)
3789 {
3790 	unsigned long iflag;
3791 
3792 	spin_lock_irqsave(&phba->hbalock, iflag);
3793 	phba->sli.sli_flag &= ~LPFC_BLOCK_MGMT_IO;
3794 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3795 }
3796 
3797 /**
3798  * lpfc_offline_prep - Prepare a HBA to be brought offline
3799  * @phba: pointer to lpfc hba data structure.
3800  * @mbx_action: flag for mailbox shutdown action.
3801  *
3802  * This routine is invoked to prepare a HBA to be brought offline. It performs
3803  * unregistration login to all the nodes on all vports and flushes the mailbox
3804  * queue to make it ready to be brought offline.
3805  **/
3806 void
3807 lpfc_offline_prep(struct lpfc_hba *phba, int mbx_action)
3808 {
3809 	struct lpfc_vport *vport = phba->pport;
3810 	struct lpfc_nodelist  *ndlp, *next_ndlp;
3811 	struct lpfc_vport **vports;
3812 	struct Scsi_Host *shost;
3813 	int i;
3814 	int offline;
3815 	bool hba_pci_err;
3816 
3817 	if (test_bit(FC_OFFLINE_MODE, &vport->fc_flag))
3818 		return;
3819 
3820 	lpfc_block_mgmt_io(phba, mbx_action);
3821 
3822 	lpfc_linkdown(phba);
3823 
3824 	offline =  pci_channel_offline(phba->pcidev);
3825 	hba_pci_err = test_bit(HBA_PCI_ERR, &phba->bit_flags);
3826 
3827 	/* Issue an unreg_login to all nodes on all vports */
3828 	vports = lpfc_create_vport_work_array(phba);
3829 	if (vports != NULL) {
3830 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3831 			if (test_bit(FC_UNLOADING, &vports[i]->load_flag))
3832 				continue;
3833 			shost = lpfc_shost_from_vport(vports[i]);
3834 			spin_lock_irq(shost->host_lock);
3835 			vports[i]->vpi_state &= ~LPFC_VPI_REGISTERED;
3836 			spin_unlock_irq(shost->host_lock);
3837 			set_bit(FC_VPORT_NEEDS_REG_VPI, &vports[i]->fc_flag);
3838 			clear_bit(FC_VFI_REGISTERED, &vports[i]->fc_flag);
3839 
3840 			list_for_each_entry_safe(ndlp, next_ndlp,
3841 						 &vports[i]->fc_nodes,
3842 						 nlp_listp) {
3843 
3844 				clear_bit(NLP_NPR_ADISC, &ndlp->nlp_flag);
3845 				if (offline || hba_pci_err) {
3846 					clear_bit(NLP_UNREG_INP,
3847 						  &ndlp->nlp_flag);
3848 					clear_bit(NLP_RPI_REGISTERED,
3849 						  &ndlp->nlp_flag);
3850 				}
3851 
3852 				if (ndlp->nlp_type & NLP_FABRIC) {
3853 					lpfc_disc_state_machine(vports[i], ndlp,
3854 						NULL, NLP_EVT_DEVICE_RECOVERY);
3855 
3856 					/* Don't remove the node unless the node
3857 					 * has been unregistered with the
3858 					 * transport, and we're not in recovery
3859 					 * before dev_loss_tmo triggered.
3860 					 * Otherwise, let dev_loss take care of
3861 					 * the node.
3862 					 */
3863 					if (!test_bit(NLP_IN_RECOV_POST_DEV_LOSS,
3864 						      &ndlp->save_flags) &&
3865 					    !(ndlp->fc4_xpt_flags &
3866 					      (NVME_XPT_REGD | SCSI_XPT_REGD)))
3867 						lpfc_disc_state_machine
3868 							(vports[i], ndlp,
3869 							 NULL,
3870 							 NLP_EVT_DEVICE_RM);
3871 				}
3872 			}
3873 		}
3874 	}
3875 	lpfc_destroy_vport_work_array(phba, vports);
3876 
3877 	lpfc_sli_mbox_sys_shutdown(phba, mbx_action);
3878 
3879 	if (phba->wq)
3880 		flush_workqueue(phba->wq);
3881 }
3882 
3883 /**
3884  * lpfc_offline - Bring a HBA offline
3885  * @phba: pointer to lpfc hba data structure.
3886  *
3887  * This routine actually brings a HBA offline. It stops all the timers
3888  * associated with the HBA, brings down the SLI layer, and eventually
3889  * marks the HBA as in offline state for the upper layer protocol.
3890  **/
3891 void
3892 lpfc_offline(struct lpfc_hba *phba)
3893 {
3894 	struct Scsi_Host  *shost;
3895 	struct lpfc_vport **vports;
3896 	int i;
3897 
3898 	if (test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag))
3899 		return;
3900 
3901 	/* stop port and all timers associated with this hba */
3902 	lpfc_stop_port(phba);
3903 
3904 	/* Tear down the local and target port registrations.  The
3905 	 * nvme transports need to cleanup.
3906 	 */
3907 	lpfc_nvmet_destroy_targetport(phba);
3908 	lpfc_nvme_destroy_localport(phba->pport);
3909 
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 			lpfc_stop_vport_timers(vports[i]);
3914 	lpfc_destroy_vport_work_array(phba, vports);
3915 	lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
3916 			"0460 Bring Adapter offline\n");
3917 	/* Bring down the SLI Layer and cleanup.  The HBA is offline
3918 	   now.  */
3919 	lpfc_sli_hba_down(phba);
3920 	spin_lock_irq(&phba->hbalock);
3921 	phba->work_ha = 0;
3922 	spin_unlock_irq(&phba->hbalock);
3923 	vports = lpfc_create_vport_work_array(phba);
3924 	if (vports != NULL)
3925 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3926 			shost = lpfc_shost_from_vport(vports[i]);
3927 			spin_lock_irq(shost->host_lock);
3928 			vports[i]->work_port_events = 0;
3929 			spin_unlock_irq(shost->host_lock);
3930 			set_bit(FC_OFFLINE_MODE, &vports[i]->fc_flag);
3931 		}
3932 	lpfc_destroy_vport_work_array(phba, vports);
3933 	/* If OFFLINE flag is clear (i.e. unloading), cpuhp removal is handled
3934 	 * in hba_unset
3935 	 */
3936 	if (test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag))
3937 		__lpfc_cpuhp_remove(phba);
3938 
3939 	if (phba->cfg_xri_rebalancing)
3940 		lpfc_destroy_multixri_pools(phba);
3941 }
3942 
3943 /**
3944  * lpfc_scsi_free - Free all the SCSI buffers and IOCBs from driver lists
3945  * @phba: pointer to lpfc hba data structure.
3946  *
3947  * This routine is to free all the SCSI buffers and IOCBs from the driver
3948  * list back to kernel. It is called from lpfc_pci_remove_one to free
3949  * the internal resources before the device is removed from the system.
3950  **/
3951 static void
3952 lpfc_scsi_free(struct lpfc_hba *phba)
3953 {
3954 	struct lpfc_io_buf *sb, *sb_next;
3955 
3956 	if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP))
3957 		return;
3958 
3959 	spin_lock_irq(&phba->hbalock);
3960 
3961 	/* Release all the lpfc_scsi_bufs maintained by this host. */
3962 
3963 	spin_lock(&phba->scsi_buf_list_put_lock);
3964 	list_for_each_entry_safe(sb, sb_next, &phba->lpfc_scsi_buf_list_put,
3965 				 list) {
3966 		list_del(&sb->list);
3967 		dma_pool_free(phba->lpfc_sg_dma_buf_pool, sb->data,
3968 			      sb->dma_handle);
3969 		kfree(sb);
3970 		phba->total_scsi_bufs--;
3971 	}
3972 	spin_unlock(&phba->scsi_buf_list_put_lock);
3973 
3974 	spin_lock(&phba->scsi_buf_list_get_lock);
3975 	list_for_each_entry_safe(sb, sb_next, &phba->lpfc_scsi_buf_list_get,
3976 				 list) {
3977 		list_del(&sb->list);
3978 		dma_pool_free(phba->lpfc_sg_dma_buf_pool, sb->data,
3979 			      sb->dma_handle);
3980 		kfree(sb);
3981 		phba->total_scsi_bufs--;
3982 	}
3983 	spin_unlock(&phba->scsi_buf_list_get_lock);
3984 	spin_unlock_irq(&phba->hbalock);
3985 }
3986 
3987 /**
3988  * lpfc_io_free - Free all the IO buffers and IOCBs from driver lists
3989  * @phba: pointer to lpfc hba data structure.
3990  *
3991  * This routine is to free all the IO buffers and IOCBs from the driver
3992  * list back to kernel. It is called from lpfc_pci_remove_one to free
3993  * the internal resources before the device is removed from the system.
3994  **/
3995 void
3996 lpfc_io_free(struct lpfc_hba *phba)
3997 {
3998 	struct lpfc_io_buf *lpfc_ncmd, *lpfc_ncmd_next;
3999 	struct lpfc_sli4_hdw_queue *qp;
4000 	int idx;
4001 
4002 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
4003 		qp = &phba->sli4_hba.hdwq[idx];
4004 		/* Release all the lpfc_nvme_bufs maintained by this host. */
4005 		spin_lock(&qp->io_buf_list_put_lock);
4006 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
4007 					 &qp->lpfc_io_buf_list_put,
4008 					 list) {
4009 			list_del(&lpfc_ncmd->list);
4010 			qp->put_io_bufs--;
4011 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4012 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4013 			if (phba->cfg_xpsgl && !phba->nvmet_support)
4014 				lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
4015 			lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
4016 			kfree(lpfc_ncmd);
4017 			qp->total_io_bufs--;
4018 		}
4019 		spin_unlock(&qp->io_buf_list_put_lock);
4020 
4021 		spin_lock(&qp->io_buf_list_get_lock);
4022 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
4023 					 &qp->lpfc_io_buf_list_get,
4024 					 list) {
4025 			list_del(&lpfc_ncmd->list);
4026 			qp->get_io_bufs--;
4027 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4028 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4029 			if (phba->cfg_xpsgl && !phba->nvmet_support)
4030 				lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
4031 			lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
4032 			kfree(lpfc_ncmd);
4033 			qp->total_io_bufs--;
4034 		}
4035 		spin_unlock(&qp->io_buf_list_get_lock);
4036 	}
4037 }
4038 
4039 /**
4040  * lpfc_sli4_els_sgl_update - update ELS xri-sgl sizing and mapping
4041  * @phba: pointer to lpfc hba data structure.
4042  *
4043  * This routine first calculates the sizes of the current els and allocated
4044  * scsi sgl lists, and then goes through all sgls to updates the physical
4045  * XRIs assigned due to port function reset. During port initialization, the
4046  * current els and allocated scsi sgl lists are 0s.
4047  *
4048  * Return codes
4049  *   0 - successful (for now, it always returns 0)
4050  **/
4051 int
4052 lpfc_sli4_els_sgl_update(struct lpfc_hba *phba)
4053 {
4054 	struct lpfc_sglq *sglq_entry = NULL, *sglq_entry_next = NULL;
4055 	uint16_t i, lxri, xri_cnt, els_xri_cnt;
4056 	LIST_HEAD(els_sgl_list);
4057 	int rc;
4058 
4059 	/*
4060 	 * update on pci function's els xri-sgl list
4061 	 */
4062 	els_xri_cnt = lpfc_sli4_get_els_iocb_cnt(phba);
4063 
4064 	if (els_xri_cnt > phba->sli4_hba.els_xri_cnt) {
4065 		/* els xri-sgl expanded */
4066 		xri_cnt = els_xri_cnt - phba->sli4_hba.els_xri_cnt;
4067 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4068 				"3157 ELS xri-sgl count increased from "
4069 				"%d to %d\n", phba->sli4_hba.els_xri_cnt,
4070 				els_xri_cnt);
4071 		/* allocate the additional els sgls */
4072 		for (i = 0; i < xri_cnt; i++) {
4073 			sglq_entry = kzalloc(sizeof(struct lpfc_sglq),
4074 					     GFP_KERNEL);
4075 			if (sglq_entry == NULL) {
4076 				lpfc_printf_log(phba, KERN_ERR,
4077 						LOG_TRACE_EVENT,
4078 						"2562 Failure to allocate an "
4079 						"ELS sgl entry:%d\n", i);
4080 				rc = -ENOMEM;
4081 				goto out_free_mem;
4082 			}
4083 			sglq_entry->buff_type = GEN_BUFF_TYPE;
4084 			sglq_entry->virt = lpfc_mbuf_alloc(phba, 0,
4085 							   &sglq_entry->phys);
4086 			if (sglq_entry->virt == NULL) {
4087 				kfree(sglq_entry);
4088 				lpfc_printf_log(phba, KERN_ERR,
4089 						LOG_TRACE_EVENT,
4090 						"2563 Failure to allocate an "
4091 						"ELS mbuf:%d\n", i);
4092 				rc = -ENOMEM;
4093 				goto out_free_mem;
4094 			}
4095 			sglq_entry->sgl = sglq_entry->virt;
4096 			memset(sglq_entry->sgl, 0, LPFC_BPL_SIZE);
4097 			sglq_entry->state = SGL_FREED;
4098 			list_add_tail(&sglq_entry->list, &els_sgl_list);
4099 		}
4100 		spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
4101 		list_splice_init(&els_sgl_list,
4102 				 &phba->sli4_hba.lpfc_els_sgl_list);
4103 		spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
4104 	} else if (els_xri_cnt < phba->sli4_hba.els_xri_cnt) {
4105 		/* els xri-sgl shrinked */
4106 		xri_cnt = phba->sli4_hba.els_xri_cnt - els_xri_cnt;
4107 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4108 				"3158 ELS xri-sgl count decreased from "
4109 				"%d to %d\n", phba->sli4_hba.els_xri_cnt,
4110 				els_xri_cnt);
4111 		spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
4112 		list_splice_init(&phba->sli4_hba.lpfc_els_sgl_list,
4113 				 &els_sgl_list);
4114 		/* release extra els sgls from list */
4115 		for (i = 0; i < xri_cnt; i++) {
4116 			list_remove_head(&els_sgl_list,
4117 					 sglq_entry, struct lpfc_sglq, list);
4118 			if (sglq_entry) {
4119 				__lpfc_mbuf_free(phba, sglq_entry->virt,
4120 						 sglq_entry->phys);
4121 				kfree(sglq_entry);
4122 			}
4123 		}
4124 		list_splice_init(&els_sgl_list,
4125 				 &phba->sli4_hba.lpfc_els_sgl_list);
4126 		spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
4127 	} else
4128 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4129 				"3163 ELS xri-sgl count unchanged: %d\n",
4130 				els_xri_cnt);
4131 	phba->sli4_hba.els_xri_cnt = els_xri_cnt;
4132 
4133 	/* update xris to els sgls on the list */
4134 	sglq_entry = NULL;
4135 	sglq_entry_next = NULL;
4136 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
4137 				 &phba->sli4_hba.lpfc_els_sgl_list, list) {
4138 		lxri = lpfc_sli4_next_xritag(phba);
4139 		if (lxri == NO_XRI) {
4140 			lpfc_printf_log(phba, KERN_ERR,
4141 					LOG_TRACE_EVENT,
4142 					"2400 Failed to allocate xri for "
4143 					"ELS sgl\n");
4144 			rc = -ENOMEM;
4145 			goto out_free_mem;
4146 		}
4147 		sglq_entry->sli4_lxritag = lxri;
4148 		sglq_entry->sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4149 	}
4150 	return 0;
4151 
4152 out_free_mem:
4153 	lpfc_free_els_sgl_list(phba);
4154 	return rc;
4155 }
4156 
4157 /**
4158  * lpfc_sli4_nvmet_sgl_update - update xri-sgl sizing and mapping
4159  * @phba: pointer to lpfc hba data structure.
4160  *
4161  * This routine first calculates the sizes of the current els and allocated
4162  * scsi sgl lists, and then goes through all sgls to updates the physical
4163  * XRIs assigned due to port function reset. During port initialization, the
4164  * current els and allocated scsi sgl lists are 0s.
4165  *
4166  * Return codes
4167  *   0 - successful (for now, it always returns 0)
4168  **/
4169 int
4170 lpfc_sli4_nvmet_sgl_update(struct lpfc_hba *phba)
4171 {
4172 	struct lpfc_sglq *sglq_entry = NULL, *sglq_entry_next = NULL;
4173 	uint16_t i, lxri, xri_cnt, els_xri_cnt;
4174 	uint16_t nvmet_xri_cnt;
4175 	LIST_HEAD(nvmet_sgl_list);
4176 	int rc;
4177 
4178 	/*
4179 	 * update on pci function's nvmet xri-sgl list
4180 	 */
4181 	els_xri_cnt = lpfc_sli4_get_els_iocb_cnt(phba);
4182 
4183 	/* For NVMET, ALL remaining XRIs are dedicated for IO processing */
4184 	nvmet_xri_cnt = phba->sli4_hba.max_cfg_param.max_xri - els_xri_cnt;
4185 	if (nvmet_xri_cnt > phba->sli4_hba.nvmet_xri_cnt) {
4186 		/* els xri-sgl expanded */
4187 		xri_cnt = nvmet_xri_cnt - phba->sli4_hba.nvmet_xri_cnt;
4188 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4189 				"6302 NVMET xri-sgl cnt grew from %d to %d\n",
4190 				phba->sli4_hba.nvmet_xri_cnt, nvmet_xri_cnt);
4191 		/* allocate the additional nvmet sgls */
4192 		for (i = 0; i < xri_cnt; i++) {
4193 			sglq_entry = kzalloc(sizeof(struct lpfc_sglq),
4194 					     GFP_KERNEL);
4195 			if (sglq_entry == NULL) {
4196 				lpfc_printf_log(phba, KERN_ERR,
4197 						LOG_TRACE_EVENT,
4198 						"6303 Failure to allocate an "
4199 						"NVMET sgl entry:%d\n", i);
4200 				rc = -ENOMEM;
4201 				goto out_free_mem;
4202 			}
4203 			sglq_entry->buff_type = NVMET_BUFF_TYPE;
4204 			sglq_entry->virt = lpfc_nvmet_buf_alloc(phba, 0,
4205 							   &sglq_entry->phys);
4206 			if (sglq_entry->virt == NULL) {
4207 				kfree(sglq_entry);
4208 				lpfc_printf_log(phba, KERN_ERR,
4209 						LOG_TRACE_EVENT,
4210 						"6304 Failure to allocate an "
4211 						"NVMET buf:%d\n", i);
4212 				rc = -ENOMEM;
4213 				goto out_free_mem;
4214 			}
4215 			sglq_entry->sgl = sglq_entry->virt;
4216 			memset(sglq_entry->sgl, 0,
4217 			       phba->cfg_sg_dma_buf_size);
4218 			sglq_entry->state = SGL_FREED;
4219 			list_add_tail(&sglq_entry->list, &nvmet_sgl_list);
4220 		}
4221 		spin_lock_irq(&phba->hbalock);
4222 		spin_lock(&phba->sli4_hba.sgl_list_lock);
4223 		list_splice_init(&nvmet_sgl_list,
4224 				 &phba->sli4_hba.lpfc_nvmet_sgl_list);
4225 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
4226 		spin_unlock_irq(&phba->hbalock);
4227 	} else if (nvmet_xri_cnt < phba->sli4_hba.nvmet_xri_cnt) {
4228 		/* nvmet xri-sgl shrunk */
4229 		xri_cnt = phba->sli4_hba.nvmet_xri_cnt - nvmet_xri_cnt;
4230 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4231 				"6305 NVMET xri-sgl count decreased from "
4232 				"%d to %d\n", phba->sli4_hba.nvmet_xri_cnt,
4233 				nvmet_xri_cnt);
4234 		spin_lock_irq(&phba->hbalock);
4235 		spin_lock(&phba->sli4_hba.sgl_list_lock);
4236 		list_splice_init(&phba->sli4_hba.lpfc_nvmet_sgl_list,
4237 				 &nvmet_sgl_list);
4238 		/* release extra nvmet sgls from list */
4239 		for (i = 0; i < xri_cnt; i++) {
4240 			list_remove_head(&nvmet_sgl_list,
4241 					 sglq_entry, struct lpfc_sglq, list);
4242 			if (sglq_entry) {
4243 				lpfc_nvmet_buf_free(phba, sglq_entry->virt,
4244 						    sglq_entry->phys);
4245 				kfree(sglq_entry);
4246 			}
4247 		}
4248 		list_splice_init(&nvmet_sgl_list,
4249 				 &phba->sli4_hba.lpfc_nvmet_sgl_list);
4250 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
4251 		spin_unlock_irq(&phba->hbalock);
4252 	} else
4253 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4254 				"6306 NVMET xri-sgl count unchanged: %d\n",
4255 				nvmet_xri_cnt);
4256 	phba->sli4_hba.nvmet_xri_cnt = nvmet_xri_cnt;
4257 
4258 	/* update xris to nvmet sgls on the list */
4259 	sglq_entry = NULL;
4260 	sglq_entry_next = NULL;
4261 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
4262 				 &phba->sli4_hba.lpfc_nvmet_sgl_list, list) {
4263 		lxri = lpfc_sli4_next_xritag(phba);
4264 		if (lxri == NO_XRI) {
4265 			lpfc_printf_log(phba, KERN_ERR,
4266 					LOG_TRACE_EVENT,
4267 					"6307 Failed to allocate xri for "
4268 					"NVMET sgl\n");
4269 			rc = -ENOMEM;
4270 			goto out_free_mem;
4271 		}
4272 		sglq_entry->sli4_lxritag = lxri;
4273 		sglq_entry->sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4274 	}
4275 	return 0;
4276 
4277 out_free_mem:
4278 	lpfc_free_nvmet_sgl_list(phba);
4279 	return rc;
4280 }
4281 
4282 int
4283 lpfc_io_buf_flush(struct lpfc_hba *phba, struct list_head *cbuf)
4284 {
4285 	LIST_HEAD(blist);
4286 	struct lpfc_sli4_hdw_queue *qp;
4287 	struct lpfc_io_buf *lpfc_cmd;
4288 	struct lpfc_io_buf *iobufp, *prev_iobufp;
4289 	int idx, cnt, xri, inserted;
4290 
4291 	cnt = 0;
4292 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
4293 		qp = &phba->sli4_hba.hdwq[idx];
4294 		spin_lock_irq(&qp->io_buf_list_get_lock);
4295 		spin_lock(&qp->io_buf_list_put_lock);
4296 
4297 		/* Take everything off the get and put lists */
4298 		list_splice_init(&qp->lpfc_io_buf_list_get, &blist);
4299 		list_splice(&qp->lpfc_io_buf_list_put, &blist);
4300 		INIT_LIST_HEAD(&qp->lpfc_io_buf_list_get);
4301 		INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
4302 		cnt += qp->get_io_bufs + qp->put_io_bufs;
4303 		qp->get_io_bufs = 0;
4304 		qp->put_io_bufs = 0;
4305 		qp->total_io_bufs = 0;
4306 		spin_unlock(&qp->io_buf_list_put_lock);
4307 		spin_unlock_irq(&qp->io_buf_list_get_lock);
4308 	}
4309 
4310 	/*
4311 	 * Take IO buffers off blist and put on cbuf sorted by XRI.
4312 	 * This is because POST_SGL takes a sequential range of XRIs
4313 	 * to post to the firmware.
4314 	 */
4315 	for (idx = 0; idx < cnt; idx++) {
4316 		list_remove_head(&blist, lpfc_cmd, struct lpfc_io_buf, list);
4317 		if (!lpfc_cmd)
4318 			return cnt;
4319 		if (idx == 0) {
4320 			list_add_tail(&lpfc_cmd->list, cbuf);
4321 			continue;
4322 		}
4323 		xri = lpfc_cmd->cur_iocbq.sli4_xritag;
4324 		inserted = 0;
4325 		prev_iobufp = NULL;
4326 		list_for_each_entry(iobufp, cbuf, list) {
4327 			if (xri < iobufp->cur_iocbq.sli4_xritag) {
4328 				if (prev_iobufp)
4329 					list_add(&lpfc_cmd->list,
4330 						 &prev_iobufp->list);
4331 				else
4332 					list_add(&lpfc_cmd->list, cbuf);
4333 				inserted = 1;
4334 				break;
4335 			}
4336 			prev_iobufp = iobufp;
4337 		}
4338 		if (!inserted)
4339 			list_add_tail(&lpfc_cmd->list, cbuf);
4340 	}
4341 	return cnt;
4342 }
4343 
4344 int
4345 lpfc_io_buf_replenish(struct lpfc_hba *phba, struct list_head *cbuf)
4346 {
4347 	struct lpfc_sli4_hdw_queue *qp;
4348 	struct lpfc_io_buf *lpfc_cmd;
4349 	int idx, cnt;
4350 	unsigned long iflags;
4351 
4352 	qp = phba->sli4_hba.hdwq;
4353 	cnt = 0;
4354 	while (!list_empty(cbuf)) {
4355 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
4356 			list_remove_head(cbuf, lpfc_cmd,
4357 					 struct lpfc_io_buf, list);
4358 			if (!lpfc_cmd)
4359 				return cnt;
4360 			cnt++;
4361 			qp = &phba->sli4_hba.hdwq[idx];
4362 			lpfc_cmd->hdwq_no = idx;
4363 			lpfc_cmd->hdwq = qp;
4364 			lpfc_cmd->cur_iocbq.cmd_cmpl = NULL;
4365 			spin_lock_irqsave(&qp->io_buf_list_put_lock, iflags);
4366 			list_add_tail(&lpfc_cmd->list,
4367 				      &qp->lpfc_io_buf_list_put);
4368 			qp->put_io_bufs++;
4369 			qp->total_io_bufs++;
4370 			spin_unlock_irqrestore(&qp->io_buf_list_put_lock,
4371 					       iflags);
4372 		}
4373 	}
4374 	return cnt;
4375 }
4376 
4377 /**
4378  * lpfc_sli4_io_sgl_update - update xri-sgl sizing and mapping
4379  * @phba: pointer to lpfc hba data structure.
4380  *
4381  * This routine first calculates the sizes of the current els and allocated
4382  * scsi sgl lists, and then goes through all sgls to updates the physical
4383  * XRIs assigned due to port function reset. During port initialization, the
4384  * current els and allocated scsi sgl lists are 0s.
4385  *
4386  * Return codes
4387  *   0 - successful (for now, it always returns 0)
4388  **/
4389 int
4390 lpfc_sli4_io_sgl_update(struct lpfc_hba *phba)
4391 {
4392 	struct lpfc_io_buf *lpfc_ncmd = NULL, *lpfc_ncmd_next = NULL;
4393 	uint16_t i, lxri, els_xri_cnt;
4394 	uint16_t io_xri_cnt, io_xri_max;
4395 	LIST_HEAD(io_sgl_list);
4396 	int rc, cnt;
4397 
4398 	/*
4399 	 * update on pci function's allocated nvme xri-sgl list
4400 	 */
4401 
4402 	/* maximum number of xris available for nvme buffers */
4403 	els_xri_cnt = lpfc_sli4_get_els_iocb_cnt(phba);
4404 	io_xri_max = phba->sli4_hba.max_cfg_param.max_xri - els_xri_cnt;
4405 	phba->sli4_hba.io_xri_max = io_xri_max;
4406 
4407 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4408 			"6074 Current allocated XRI sgl count:%d, "
4409 			"maximum XRI count:%d els_xri_cnt:%d\n\n",
4410 			phba->sli4_hba.io_xri_cnt,
4411 			phba->sli4_hba.io_xri_max,
4412 			els_xri_cnt);
4413 
4414 	cnt = lpfc_io_buf_flush(phba, &io_sgl_list);
4415 
4416 	if (phba->sli4_hba.io_xri_cnt > phba->sli4_hba.io_xri_max) {
4417 		/* max nvme xri shrunk below the allocated nvme buffers */
4418 		io_xri_cnt = phba->sli4_hba.io_xri_cnt -
4419 					phba->sli4_hba.io_xri_max;
4420 		/* release the extra allocated nvme buffers */
4421 		for (i = 0; i < io_xri_cnt; i++) {
4422 			list_remove_head(&io_sgl_list, lpfc_ncmd,
4423 					 struct lpfc_io_buf, list);
4424 			if (lpfc_ncmd) {
4425 				dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4426 					      lpfc_ncmd->data,
4427 					      lpfc_ncmd->dma_handle);
4428 				kfree(lpfc_ncmd);
4429 			}
4430 		}
4431 		phba->sli4_hba.io_xri_cnt -= io_xri_cnt;
4432 	}
4433 
4434 	/* update xris associated to remaining allocated nvme buffers */
4435 	lpfc_ncmd = NULL;
4436 	lpfc_ncmd_next = NULL;
4437 	phba->sli4_hba.io_xri_cnt = cnt;
4438 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
4439 				 &io_sgl_list, list) {
4440 		lxri = lpfc_sli4_next_xritag(phba);
4441 		if (lxri == NO_XRI) {
4442 			lpfc_printf_log(phba, KERN_ERR,
4443 					LOG_TRACE_EVENT,
4444 					"6075 Failed to allocate xri for "
4445 					"nvme buffer\n");
4446 			rc = -ENOMEM;
4447 			goto out_free_mem;
4448 		}
4449 		lpfc_ncmd->cur_iocbq.sli4_lxritag = lxri;
4450 		lpfc_ncmd->cur_iocbq.sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4451 	}
4452 	cnt = lpfc_io_buf_replenish(phba, &io_sgl_list);
4453 	return 0;
4454 
4455 out_free_mem:
4456 	lpfc_io_free(phba);
4457 	return rc;
4458 }
4459 
4460 /**
4461  * lpfc_new_io_buf - IO buffer allocator for HBA with SLI4 IF spec
4462  * @phba: Pointer to lpfc hba data structure.
4463  * @num_to_alloc: The requested number of buffers to allocate.
4464  *
4465  * This routine allocates nvme buffers for device with SLI-4 interface spec,
4466  * the nvme buffer contains all the necessary information needed to initiate
4467  * an I/O. After allocating up to @num_to_allocate IO buffers and put
4468  * them on a list, it post them to the port by using SGL block post.
4469  *
4470  * Return codes:
4471  *   int - number of IO buffers that were allocated and posted.
4472  *   0 = failure, less than num_to_alloc is a partial failure.
4473  **/
4474 int
4475 lpfc_new_io_buf(struct lpfc_hba *phba, int num_to_alloc)
4476 {
4477 	struct lpfc_io_buf *lpfc_ncmd;
4478 	struct lpfc_iocbq *pwqeq;
4479 	uint16_t iotag, lxri = 0;
4480 	int bcnt, num_posted;
4481 	LIST_HEAD(prep_nblist);
4482 	LIST_HEAD(post_nblist);
4483 	LIST_HEAD(nvme_nblist);
4484 
4485 	phba->sli4_hba.io_xri_cnt = 0;
4486 	for (bcnt = 0; bcnt < num_to_alloc; bcnt++) {
4487 		lpfc_ncmd = kzalloc(sizeof(*lpfc_ncmd), GFP_KERNEL);
4488 		if (!lpfc_ncmd)
4489 			break;
4490 		/*
4491 		 * Get memory from the pci pool to map the virt space to
4492 		 * pci bus space for an I/O. The DMA buffer includes the
4493 		 * number of SGE's necessary to support the sg_tablesize.
4494 		 */
4495 		lpfc_ncmd->data = dma_pool_zalloc(phba->lpfc_sg_dma_buf_pool,
4496 						  GFP_KERNEL,
4497 						  &lpfc_ncmd->dma_handle);
4498 		if (!lpfc_ncmd->data) {
4499 			kfree(lpfc_ncmd);
4500 			break;
4501 		}
4502 
4503 		if (phba->cfg_xpsgl && !phba->nvmet_support) {
4504 			INIT_LIST_HEAD(&lpfc_ncmd->dma_sgl_xtra_list);
4505 		} else {
4506 			/*
4507 			 * 4K Page alignment is CRITICAL to BlockGuard, double
4508 			 * check to be sure.
4509 			 */
4510 			if ((phba->sli3_options & LPFC_SLI3_BG_ENABLED) &&
4511 			    (((unsigned long)(lpfc_ncmd->data) &
4512 			    (unsigned long)(SLI4_PAGE_SIZE - 1)) != 0)) {
4513 				lpfc_printf_log(phba, KERN_ERR,
4514 						LOG_TRACE_EVENT,
4515 						"3369 Memory alignment err: "
4516 						"addr=%lx\n",
4517 						(unsigned long)lpfc_ncmd->data);
4518 				dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4519 					      lpfc_ncmd->data,
4520 					      lpfc_ncmd->dma_handle);
4521 				kfree(lpfc_ncmd);
4522 				break;
4523 			}
4524 		}
4525 
4526 		INIT_LIST_HEAD(&lpfc_ncmd->dma_cmd_rsp_list);
4527 
4528 		lxri = lpfc_sli4_next_xritag(phba);
4529 		if (lxri == NO_XRI) {
4530 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4531 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4532 			kfree(lpfc_ncmd);
4533 			break;
4534 		}
4535 		pwqeq = &lpfc_ncmd->cur_iocbq;
4536 
4537 		/* Allocate iotag for lpfc_ncmd->cur_iocbq. */
4538 		iotag = lpfc_sli_next_iotag(phba, pwqeq);
4539 		if (iotag == 0) {
4540 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4541 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4542 			kfree(lpfc_ncmd);
4543 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4544 					"6121 Failed to allocate IOTAG for"
4545 					" XRI:0x%x\n", lxri);
4546 			lpfc_sli4_free_xri(phba, lxri);
4547 			break;
4548 		}
4549 		pwqeq->sli4_lxritag = lxri;
4550 		pwqeq->sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4551 
4552 		/* Initialize local short-hand pointers. */
4553 		lpfc_ncmd->dma_sgl = lpfc_ncmd->data;
4554 		lpfc_ncmd->dma_phys_sgl = lpfc_ncmd->dma_handle;
4555 		lpfc_ncmd->cur_iocbq.io_buf = lpfc_ncmd;
4556 		spin_lock_init(&lpfc_ncmd->buf_lock);
4557 
4558 		/* add the nvme buffer to a post list */
4559 		list_add_tail(&lpfc_ncmd->list, &post_nblist);
4560 		phba->sli4_hba.io_xri_cnt++;
4561 	}
4562 	lpfc_printf_log(phba, KERN_INFO, LOG_NVME,
4563 			"6114 Allocate %d out of %d requested new NVME "
4564 			"buffers of size x%zu bytes\n", bcnt, num_to_alloc,
4565 			sizeof(*lpfc_ncmd));
4566 
4567 
4568 	/* post the list of nvme buffer sgls to port if available */
4569 	if (!list_empty(&post_nblist))
4570 		num_posted = lpfc_sli4_post_io_sgl_list(
4571 				phba, &post_nblist, bcnt);
4572 	else
4573 		num_posted = 0;
4574 
4575 	return num_posted;
4576 }
4577 
4578 static uint64_t
4579 lpfc_get_wwpn(struct lpfc_hba *phba)
4580 {
4581 	uint64_t wwn;
4582 	int rc;
4583 	LPFC_MBOXQ_t *mboxq;
4584 	MAILBOX_t *mb;
4585 
4586 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
4587 						GFP_KERNEL);
4588 	if (!mboxq)
4589 		return (uint64_t)-1;
4590 
4591 	/* First get WWN of HBA instance */
4592 	lpfc_read_nv(phba, mboxq);
4593 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
4594 	if (rc != MBX_SUCCESS) {
4595 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4596 				"6019 Mailbox failed , mbxCmd x%x "
4597 				"READ_NV, mbxStatus x%x\n",
4598 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
4599 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
4600 		mempool_free(mboxq, phba->mbox_mem_pool);
4601 		return (uint64_t) -1;
4602 	}
4603 	mb = &mboxq->u.mb;
4604 	memcpy(&wwn, (char *)mb->un.varRDnvp.portname, sizeof(uint64_t));
4605 	/* wwn is WWPN of HBA instance */
4606 	mempool_free(mboxq, phba->mbox_mem_pool);
4607 	if (phba->sli_rev == LPFC_SLI_REV4)
4608 		return be64_to_cpu(wwn);
4609 	else
4610 		return rol64(wwn, 32);
4611 }
4612 
4613 static unsigned short lpfc_get_sg_tablesize(struct lpfc_hba *phba)
4614 {
4615 	if (phba->sli_rev == LPFC_SLI_REV4)
4616 		if (phba->cfg_xpsgl && !phba->nvmet_support)
4617 			return LPFC_MAX_SG_TABLESIZE;
4618 		else
4619 			return phba->cfg_scsi_seg_cnt;
4620 	else
4621 		return phba->cfg_sg_seg_cnt;
4622 }
4623 
4624 /**
4625  * lpfc_vmid_res_alloc - Allocates resources for VMID
4626  * @phba: pointer to lpfc hba data structure.
4627  * @vport: pointer to vport data structure
4628  *
4629  * This routine allocated the resources needed for the VMID.
4630  *
4631  * Return codes
4632  *	0 on Success
4633  *	Non-0 on Failure
4634  */
4635 static int
4636 lpfc_vmid_res_alloc(struct lpfc_hba *phba, struct lpfc_vport *vport)
4637 {
4638 	/* VMID feature is supported only on SLI4 */
4639 	if (phba->sli_rev == LPFC_SLI_REV3) {
4640 		phba->cfg_vmid_app_header = 0;
4641 		phba->cfg_vmid_priority_tagging = 0;
4642 	}
4643 
4644 	if (lpfc_is_vmid_enabled(phba)) {
4645 		vport->vmid =
4646 		    kcalloc(phba->cfg_max_vmid, sizeof(struct lpfc_vmid),
4647 			    GFP_KERNEL);
4648 		if (!vport->vmid)
4649 			return -ENOMEM;
4650 
4651 		rwlock_init(&vport->vmid_lock);
4652 
4653 		/* Set the VMID parameters for the vport */
4654 		vport->vmid_priority_tagging = phba->cfg_vmid_priority_tagging;
4655 		vport->vmid_inactivity_timeout =
4656 		    phba->cfg_vmid_inactivity_timeout;
4657 		vport->max_vmid = phba->cfg_max_vmid;
4658 		vport->cur_vmid_cnt = 0;
4659 
4660 		vport->vmid_priority_range = bitmap_zalloc
4661 			(LPFC_VMID_MAX_PRIORITY_RANGE, GFP_KERNEL);
4662 
4663 		if (!vport->vmid_priority_range) {
4664 			kfree(vport->vmid);
4665 			return -ENOMEM;
4666 		}
4667 
4668 		hash_init(vport->hash_table);
4669 	}
4670 	return 0;
4671 }
4672 
4673 /**
4674  * lpfc_create_port - Create an FC port
4675  * @phba: pointer to lpfc hba data structure.
4676  * @instance: a unique integer ID to this FC port.
4677  * @dev: pointer to the device data structure.
4678  *
4679  * This routine creates a FC port for the upper layer protocol. The FC port
4680  * can be created on top of either a physical port or a virtual port provided
4681  * by the HBA. This routine also allocates a SCSI host data structure (shost)
4682  * and associates the FC port created before adding the shost into the SCSI
4683  * layer.
4684  *
4685  * Return codes
4686  *   @vport - pointer to the virtual N_Port data structure.
4687  *   NULL - port create failed.
4688  **/
4689 struct lpfc_vport *
4690 lpfc_create_port(struct lpfc_hba *phba, int instance, struct device *dev)
4691 {
4692 	struct lpfc_vport *vport;
4693 	struct Scsi_Host  *shost = NULL;
4694 	struct scsi_host_template *template;
4695 	int error = 0;
4696 	int i;
4697 	uint64_t wwn;
4698 	bool use_no_reset_hba = false;
4699 	int rc;
4700 	u8 if_type;
4701 
4702 	if (lpfc_no_hba_reset_cnt) {
4703 		if (phba->sli_rev < LPFC_SLI_REV4 &&
4704 		    dev == &phba->pcidev->dev) {
4705 			/* Reset the port first */
4706 			lpfc_sli_brdrestart(phba);
4707 			rc = lpfc_sli_chipset_init(phba);
4708 			if (rc)
4709 				return NULL;
4710 		}
4711 		wwn = lpfc_get_wwpn(phba);
4712 	}
4713 
4714 	for (i = 0; i < lpfc_no_hba_reset_cnt; i++) {
4715 		if (wwn == lpfc_no_hba_reset[i]) {
4716 			lpfc_printf_log(phba, KERN_ERR,
4717 					LOG_TRACE_EVENT,
4718 					"6020 Setting use_no_reset port=%llx\n",
4719 					wwn);
4720 			use_no_reset_hba = true;
4721 			break;
4722 		}
4723 	}
4724 
4725 	/* Seed template for SCSI host registration */
4726 	if (dev == &phba->pcidev->dev) {
4727 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP) {
4728 			/* Seed physical port template */
4729 			template = &lpfc_template;
4730 
4731 			if (use_no_reset_hba)
4732 				/* template is for a no reset SCSI Host */
4733 				template->eh_host_reset_handler = NULL;
4734 
4735 			/* Seed updated value of sg_tablesize */
4736 			template->sg_tablesize = lpfc_get_sg_tablesize(phba);
4737 		} else {
4738 			/* NVMET is for physical port only */
4739 			template = &lpfc_template_nvme;
4740 		}
4741 	} else {
4742 		/* Seed vport template */
4743 		template = &lpfc_vport_template;
4744 
4745 		/* Seed updated value of sg_tablesize */
4746 		template->sg_tablesize = lpfc_get_sg_tablesize(phba);
4747 	}
4748 
4749 	shost = scsi_host_alloc(template, sizeof(struct lpfc_vport));
4750 	if (!shost)
4751 		goto out;
4752 
4753 	vport = (struct lpfc_vport *) shost->hostdata;
4754 	vport->phba = phba;
4755 	set_bit(FC_LOADING, &vport->load_flag);
4756 	set_bit(FC_VPORT_NEEDS_REG_VPI, &vport->fc_flag);
4757 	vport->fc_rscn_flush = 0;
4758 	atomic_set(&vport->fc_plogi_cnt, 0);
4759 	atomic_set(&vport->fc_adisc_cnt, 0);
4760 	atomic_set(&vport->fc_reglogin_cnt, 0);
4761 	atomic_set(&vport->fc_prli_cnt, 0);
4762 	atomic_set(&vport->fc_unmap_cnt, 0);
4763 	atomic_set(&vport->fc_map_cnt, 0);
4764 	atomic_set(&vport->fc_npr_cnt, 0);
4765 	atomic_set(&vport->fc_unused_cnt, 0);
4766 	lpfc_get_vport_cfgparam(vport);
4767 
4768 	/* Adjust value in vport */
4769 	vport->cfg_enable_fc4_type = phba->cfg_enable_fc4_type;
4770 
4771 	shost->unique_id = instance;
4772 	shost->max_id = LPFC_MAX_TARGET;
4773 	shost->max_lun = vport->cfg_max_luns;
4774 	shost->this_id = -1;
4775 
4776 	/* Set max_cmd_len applicable to ASIC support */
4777 	if (phba->sli_rev == LPFC_SLI_REV4) {
4778 		if_type = bf_get(lpfc_sli_intf_if_type,
4779 				 &phba->sli4_hba.sli_intf);
4780 		switch (if_type) {
4781 		case LPFC_SLI_INTF_IF_TYPE_2:
4782 			fallthrough;
4783 		case LPFC_SLI_INTF_IF_TYPE_6:
4784 			shost->max_cmd_len = LPFC_FCP_CDB_LEN_32;
4785 			break;
4786 		default:
4787 			shost->max_cmd_len = LPFC_FCP_CDB_LEN;
4788 			break;
4789 		}
4790 	} else {
4791 		shost->max_cmd_len = LPFC_FCP_CDB_LEN;
4792 	}
4793 
4794 	if (phba->sli_rev == LPFC_SLI_REV4) {
4795 		if (!phba->cfg_fcp_mq_threshold ||
4796 		    phba->cfg_fcp_mq_threshold > phba->cfg_hdw_queue)
4797 			phba->cfg_fcp_mq_threshold = phba->cfg_hdw_queue;
4798 
4799 		shost->nr_hw_queues = min_t(int, 2 * num_possible_nodes(),
4800 					    phba->cfg_fcp_mq_threshold);
4801 
4802 		shost->dma_boundary =
4803 			phba->sli4_hba.pc_sli4_params.sge_supp_len-1;
4804 	} else
4805 		/* SLI-3 has a limited number of hardware queues (3),
4806 		 * thus there is only one for FCP processing.
4807 		 */
4808 		shost->nr_hw_queues = 1;
4809 
4810 	/*
4811 	 * Set initial can_queue value since 0 is no longer supported and
4812 	 * scsi_add_host will fail. This will be adjusted later based on the
4813 	 * max xri value determined in hba setup.
4814 	 */
4815 	shost->can_queue = phba->cfg_hba_queue_depth - 10;
4816 	if (dev != &phba->pcidev->dev) {
4817 		shost->transportt = lpfc_vport_transport_template;
4818 		vport->port_type = LPFC_NPIV_PORT;
4819 	} else {
4820 		shost->transportt = lpfc_transport_template;
4821 		vport->port_type = LPFC_PHYSICAL_PORT;
4822 	}
4823 
4824 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP,
4825 			"9081 CreatePort TMPLATE type %x TBLsize %d "
4826 			"SEGcnt %d/%d\n",
4827 			vport->port_type, shost->sg_tablesize,
4828 			phba->cfg_scsi_seg_cnt, phba->cfg_sg_seg_cnt);
4829 
4830 	/* Allocate the resources for VMID */
4831 	rc = lpfc_vmid_res_alloc(phba, vport);
4832 
4833 	if (rc)
4834 		goto out_put_shost;
4835 
4836 	/* Initialize all internally managed lists. */
4837 	INIT_LIST_HEAD(&vport->fc_nodes);
4838 	spin_lock_init(&vport->fc_nodes_list_lock);
4839 	INIT_LIST_HEAD(&vport->rcv_buffer_list);
4840 	spin_lock_init(&vport->work_port_lock);
4841 
4842 	timer_setup(&vport->fc_disctmo, lpfc_disc_timeout, 0);
4843 
4844 	timer_setup(&vport->els_tmofunc, lpfc_els_timeout, 0);
4845 
4846 	timer_setup(&vport->delayed_disc_tmo, lpfc_delayed_disc_tmo, 0);
4847 
4848 	if (phba->sli3_options & LPFC_SLI3_BG_ENABLED)
4849 		lpfc_setup_bg(phba, shost);
4850 
4851 	error = scsi_add_host_with_dma(shost, dev, &phba->pcidev->dev);
4852 	if (error)
4853 		goto out_free_vmid;
4854 
4855 	spin_lock_irq(&phba->port_list_lock);
4856 	list_add_tail(&vport->listentry, &phba->port_list);
4857 	spin_unlock_irq(&phba->port_list_lock);
4858 	return vport;
4859 
4860 out_free_vmid:
4861 	kfree(vport->vmid);
4862 	bitmap_free(vport->vmid_priority_range);
4863 out_put_shost:
4864 	scsi_host_put(shost);
4865 out:
4866 	return NULL;
4867 }
4868 
4869 /**
4870  * destroy_port -  destroy an FC port
4871  * @vport: pointer to an lpfc virtual N_Port data structure.
4872  *
4873  * This routine destroys a FC port from the upper layer protocol. All the
4874  * resources associated with the port are released.
4875  **/
4876 void
4877 destroy_port(struct lpfc_vport *vport)
4878 {
4879 	struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
4880 	struct lpfc_hba  *phba = vport->phba;
4881 
4882 	lpfc_debugfs_terminate(vport);
4883 	fc_remove_host(shost);
4884 	scsi_remove_host(shost);
4885 
4886 	spin_lock_irq(&phba->port_list_lock);
4887 	list_del_init(&vport->listentry);
4888 	spin_unlock_irq(&phba->port_list_lock);
4889 
4890 	lpfc_cleanup(vport);
4891 	return;
4892 }
4893 
4894 /**
4895  * lpfc_get_instance - Get a unique integer ID
4896  *
4897  * This routine allocates a unique integer ID from lpfc_hba_index pool. It
4898  * uses the kernel idr facility to perform the task.
4899  *
4900  * Return codes:
4901  *   instance - a unique integer ID allocated as the new instance.
4902  *   -1 - lpfc get instance failed.
4903  **/
4904 int
4905 lpfc_get_instance(void)
4906 {
4907 	int ret;
4908 
4909 	ret = idr_alloc(&lpfc_hba_index, NULL, 0, 0, GFP_KERNEL);
4910 	return ret < 0 ? -1 : ret;
4911 }
4912 
4913 /**
4914  * lpfc_scan_finished - method for SCSI layer to detect whether scan is done
4915  * @shost: pointer to SCSI host data structure.
4916  * @time: elapsed time of the scan in jiffies.
4917  *
4918  * This routine is called by the SCSI layer with a SCSI host to determine
4919  * whether the scan host is finished.
4920  *
4921  * Note: there is no scan_start function as adapter initialization will have
4922  * asynchronously kicked off the link initialization.
4923  *
4924  * Return codes
4925  *   0 - SCSI host scan is not over yet.
4926  *   1 - SCSI host scan is over.
4927  **/
4928 int lpfc_scan_finished(struct Scsi_Host *shost, unsigned long time)
4929 {
4930 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
4931 	struct lpfc_hba   *phba = vport->phba;
4932 	int stat = 0;
4933 
4934 	spin_lock_irq(shost->host_lock);
4935 
4936 	if (test_bit(FC_UNLOADING, &vport->load_flag)) {
4937 		stat = 1;
4938 		goto finished;
4939 	}
4940 	if (time >= secs_to_jiffies(30)) {
4941 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4942 				"0461 Scanning longer than 30 "
4943 				"seconds.  Continuing initialization\n");
4944 		stat = 1;
4945 		goto finished;
4946 	}
4947 	if (time >= secs_to_jiffies(15) &&
4948 	    phba->link_state <= LPFC_LINK_DOWN) {
4949 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4950 				"0465 Link down longer than 15 "
4951 				"seconds.  Continuing initialization\n");
4952 		stat = 1;
4953 		goto finished;
4954 	}
4955 
4956 	if (vport->port_state != LPFC_VPORT_READY)
4957 		goto finished;
4958 	if (vport->num_disc_nodes || vport->fc_prli_sent)
4959 		goto finished;
4960 	if (!atomic_read(&vport->fc_map_cnt) &&
4961 	    time < secs_to_jiffies(2))
4962 		goto finished;
4963 	if ((phba->sli.sli_flag & LPFC_SLI_MBOX_ACTIVE) != 0)
4964 		goto finished;
4965 
4966 	stat = 1;
4967 
4968 finished:
4969 	spin_unlock_irq(shost->host_lock);
4970 	return stat;
4971 }
4972 
4973 static void lpfc_host_supported_speeds_set(struct Scsi_Host *shost)
4974 {
4975 	struct lpfc_vport *vport = (struct lpfc_vport *)shost->hostdata;
4976 	struct lpfc_hba   *phba = vport->phba;
4977 
4978 	fc_host_supported_speeds(shost) = 0;
4979 	/*
4980 	 * Avoid reporting supported link speed for FCoE as it can't be
4981 	 * controlled via FCoE.
4982 	 */
4983 	if (test_bit(HBA_FCOE_MODE, &phba->hba_flag))
4984 		return;
4985 
4986 	if (phba->lmt & LMT_256Gb)
4987 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_256GBIT;
4988 	if (phba->lmt & LMT_128Gb)
4989 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_128GBIT;
4990 	if (phba->lmt & LMT_64Gb)
4991 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_64GBIT;
4992 	if (phba->lmt & LMT_32Gb)
4993 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_32GBIT;
4994 	if (phba->lmt & LMT_16Gb)
4995 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_16GBIT;
4996 	if (phba->lmt & LMT_10Gb)
4997 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_10GBIT;
4998 	if (phba->lmt & LMT_8Gb)
4999 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_8GBIT;
5000 	if (phba->lmt & LMT_4Gb)
5001 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_4GBIT;
5002 	if (phba->lmt & LMT_2Gb)
5003 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_2GBIT;
5004 	if (phba->lmt & LMT_1Gb)
5005 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_1GBIT;
5006 }
5007 
5008 /**
5009  * lpfc_host_attrib_init - Initialize SCSI host attributes on a FC port
5010  * @shost: pointer to SCSI host data structure.
5011  *
5012  * This routine initializes a given SCSI host attributes on a FC port. The
5013  * SCSI host can be either on top of a physical port or a virtual port.
5014  **/
5015 void lpfc_host_attrib_init(struct Scsi_Host *shost)
5016 {
5017 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
5018 	struct lpfc_hba   *phba = vport->phba;
5019 	/*
5020 	 * Set fixed host attributes.  Must done after lpfc_sli_hba_setup().
5021 	 */
5022 
5023 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
5024 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
5025 	fc_host_supported_classes(shost) = FC_COS_CLASS3;
5026 
5027 	memset(fc_host_supported_fc4s(shost), 0,
5028 	       sizeof(fc_host_supported_fc4s(shost)));
5029 	fc_host_supported_fc4s(shost)[2] = 1;
5030 	fc_host_supported_fc4s(shost)[7] = 1;
5031 
5032 	lpfc_vport_symbolic_node_name(vport, fc_host_symbolic_name(shost),
5033 				 sizeof fc_host_symbolic_name(shost));
5034 
5035 	lpfc_host_supported_speeds_set(shost);
5036 
5037 	fc_host_maxframe_size(shost) =
5038 		(((uint32_t) vport->fc_sparam.cmn.bbRcvSizeMsb & 0x0F) << 8) |
5039 		(uint32_t) vport->fc_sparam.cmn.bbRcvSizeLsb;
5040 
5041 	fc_host_dev_loss_tmo(shost) = vport->cfg_devloss_tmo;
5042 
5043 	/* This value is also unchanging */
5044 	memset(fc_host_active_fc4s(shost), 0,
5045 	       sizeof(fc_host_active_fc4s(shost)));
5046 	fc_host_active_fc4s(shost)[2] = 1;
5047 	fc_host_active_fc4s(shost)[7] = 1;
5048 
5049 	fc_host_max_npiv_vports(shost) = phba->max_vpi;
5050 	clear_bit(FC_LOADING, &vport->load_flag);
5051 }
5052 
5053 /**
5054  * lpfc_stop_port_s3 - Stop SLI3 device port
5055  * @phba: pointer to lpfc hba data structure.
5056  *
5057  * This routine is invoked to stop an SLI3 device port, it stops the device
5058  * from generating interrupts and stops the device driver's timers for the
5059  * device.
5060  **/
5061 static void
5062 lpfc_stop_port_s3(struct lpfc_hba *phba)
5063 {
5064 	/* Clear all interrupt enable conditions */
5065 	writel(0, phba->HCregaddr);
5066 	readl(phba->HCregaddr); /* flush */
5067 	/* Clear all pending interrupts */
5068 	writel(0xffffffff, phba->HAregaddr);
5069 	readl(phba->HAregaddr); /* flush */
5070 
5071 	/* Reset some HBA SLI setup states */
5072 	lpfc_stop_hba_timers(phba);
5073 	phba->pport->work_port_events = 0;
5074 }
5075 
5076 /**
5077  * lpfc_stop_port_s4 - Stop SLI4 device port
5078  * @phba: pointer to lpfc hba data structure.
5079  *
5080  * This routine is invoked to stop an SLI4 device port, it stops the device
5081  * from generating interrupts and stops the device driver's timers for the
5082  * device.
5083  **/
5084 static void
5085 lpfc_stop_port_s4(struct lpfc_hba *phba)
5086 {
5087 	/* Reset some HBA SLI4 setup states */
5088 	lpfc_stop_hba_timers(phba);
5089 	if (phba->pport)
5090 		phba->pport->work_port_events = 0;
5091 	phba->sli4_hba.intr_enable = 0;
5092 }
5093 
5094 /**
5095  * lpfc_stop_port - Wrapper function for stopping hba port
5096  * @phba: Pointer to HBA context object.
5097  *
5098  * This routine wraps the actual SLI3 or SLI4 hba stop port routine from
5099  * the API jump table function pointer from the lpfc_hba struct.
5100  **/
5101 void
5102 lpfc_stop_port(struct lpfc_hba *phba)
5103 {
5104 	phba->lpfc_stop_port(phba);
5105 
5106 	if (phba->wq)
5107 		flush_workqueue(phba->wq);
5108 }
5109 
5110 /**
5111  * lpfc_fcf_redisc_wait_start_timer - Start fcf rediscover wait timer
5112  * @phba: Pointer to hba for which this call is being executed.
5113  *
5114  * This routine starts the timer waiting for the FCF rediscovery to complete.
5115  **/
5116 void
5117 lpfc_fcf_redisc_wait_start_timer(struct lpfc_hba *phba)
5118 {
5119 	unsigned long fcf_redisc_wait_tmo =
5120 		(jiffies + msecs_to_jiffies(LPFC_FCF_REDISCOVER_WAIT_TMO));
5121 	/* Start fcf rediscovery wait period timer */
5122 	mod_timer(&phba->fcf.redisc_wait, fcf_redisc_wait_tmo);
5123 	spin_lock_irq(&phba->hbalock);
5124 	/* Allow action to new fcf asynchronous event */
5125 	phba->fcf.fcf_flag &= ~(FCF_AVAILABLE | FCF_SCAN_DONE);
5126 	/* Mark the FCF rediscovery pending state */
5127 	phba->fcf.fcf_flag |= FCF_REDISC_PEND;
5128 	spin_unlock_irq(&phba->hbalock);
5129 }
5130 
5131 /**
5132  * lpfc_sli4_fcf_redisc_wait_tmo - FCF table rediscover wait timeout
5133  * @t: Timer context used to obtain the pointer to lpfc hba data structure.
5134  *
5135  * This routine is invoked when waiting for FCF table rediscover has been
5136  * timed out. If new FCF record(s) has (have) been discovered during the
5137  * wait period, a new FCF event shall be added to the FCOE async event
5138  * list, and then worker thread shall be waked up for processing from the
5139  * worker thread context.
5140  **/
5141 static void
5142 lpfc_sli4_fcf_redisc_wait_tmo(struct timer_list *t)
5143 {
5144 	struct lpfc_hba *phba = timer_container_of(phba, t, fcf.redisc_wait);
5145 
5146 	/* Don't send FCF rediscovery event if timer cancelled */
5147 	spin_lock_irq(&phba->hbalock);
5148 	if (!(phba->fcf.fcf_flag & FCF_REDISC_PEND)) {
5149 		spin_unlock_irq(&phba->hbalock);
5150 		return;
5151 	}
5152 	/* Clear FCF rediscovery timer pending flag */
5153 	phba->fcf.fcf_flag &= ~FCF_REDISC_PEND;
5154 	/* FCF rediscovery event to worker thread */
5155 	phba->fcf.fcf_flag |= FCF_REDISC_EVT;
5156 	spin_unlock_irq(&phba->hbalock);
5157 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
5158 			"2776 FCF rediscover quiescent timer expired\n");
5159 	/* wake up worker thread */
5160 	lpfc_worker_wake_up(phba);
5161 }
5162 
5163 /**
5164  * lpfc_vmid_poll - VMID timeout detection
5165  * @t: Timer context used to obtain the pointer to lpfc hba data structure.
5166  *
5167  * This routine is invoked when there is no I/O on by a VM for the specified
5168  * amount of time. When this situation is detected, the VMID has to be
5169  * deregistered from the switch and all the local resources freed. The VMID
5170  * will be reassigned to the VM once the I/O begins.
5171  **/
5172 static void
5173 lpfc_vmid_poll(struct timer_list *t)
5174 {
5175 	struct lpfc_hba *phba = timer_container_of(phba, t,
5176 						   inactive_vmid_poll);
5177 	u32 wake_up = 0;
5178 
5179 	/* check if there is a need to issue QFPA */
5180 	if (phba->pport->vmid_priority_tagging) {
5181 		wake_up = 1;
5182 		phba->pport->work_port_events |= WORKER_CHECK_VMID_ISSUE_QFPA;
5183 	}
5184 
5185 	/* Is the vmid inactivity timer enabled */
5186 	if (phba->pport->vmid_inactivity_timeout ||
5187 	    test_bit(FC_DEREGISTER_ALL_APP_ID, &phba->pport->load_flag)) {
5188 		wake_up = 1;
5189 		phba->pport->work_port_events |= WORKER_CHECK_INACTIVE_VMID;
5190 	}
5191 
5192 	if (wake_up)
5193 		lpfc_worker_wake_up(phba);
5194 
5195 	/* restart the timer for the next iteration */
5196 	mod_timer(&phba->inactive_vmid_poll,
5197 		  jiffies + secs_to_jiffies(LPFC_VMID_TIMER));
5198 }
5199 
5200 /**
5201  * lpfc_sli4_parse_latt_fault - Parse sli4 link-attention link fault code
5202  * @phba: pointer to lpfc hba data structure.
5203  * @acqe_link: pointer to the async link completion queue entry.
5204  *
5205  * This routine is to parse the SLI4 link-attention link fault code.
5206  **/
5207 static void
5208 lpfc_sli4_parse_latt_fault(struct lpfc_hba *phba,
5209 			   struct lpfc_acqe_link *acqe_link)
5210 {
5211 	switch (bf_get(lpfc_acqe_fc_la_att_type, acqe_link)) {
5212 	case LPFC_FC_LA_TYPE_LINK_DOWN:
5213 	case LPFC_FC_LA_TYPE_TRUNKING_EVENT:
5214 	case LPFC_FC_LA_TYPE_ACTIVATE_FAIL:
5215 	case LPFC_FC_LA_TYPE_LINK_RESET_PRTCL_EVT:
5216 		break;
5217 	default:
5218 		switch (bf_get(lpfc_acqe_link_fault, acqe_link)) {
5219 		case LPFC_ASYNC_LINK_FAULT_NONE:
5220 		case LPFC_ASYNC_LINK_FAULT_LOCAL:
5221 		case LPFC_ASYNC_LINK_FAULT_REMOTE:
5222 		case LPFC_ASYNC_LINK_FAULT_LR_LRR:
5223 			break;
5224 		default:
5225 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5226 					"0398 Unknown link fault code: x%x\n",
5227 					bf_get(lpfc_acqe_link_fault, acqe_link));
5228 			break;
5229 		}
5230 		break;
5231 	}
5232 }
5233 
5234 /**
5235  * lpfc_sli4_parse_latt_type - Parse sli4 link attention type
5236  * @phba: pointer to lpfc hba data structure.
5237  * @acqe_link: pointer to the async link completion queue entry.
5238  *
5239  * This routine is to parse the SLI4 link attention type and translate it
5240  * into the base driver's link attention type coding.
5241  *
5242  * Return: Link attention type in terms of base driver's coding.
5243  **/
5244 static uint8_t
5245 lpfc_sli4_parse_latt_type(struct lpfc_hba *phba,
5246 			  struct lpfc_acqe_link *acqe_link)
5247 {
5248 	uint8_t att_type;
5249 
5250 	switch (bf_get(lpfc_acqe_link_status, acqe_link)) {
5251 	case LPFC_ASYNC_LINK_STATUS_DOWN:
5252 	case LPFC_ASYNC_LINK_STATUS_LOGICAL_DOWN:
5253 		att_type = LPFC_ATT_LINK_DOWN;
5254 		break;
5255 	case LPFC_ASYNC_LINK_STATUS_UP:
5256 		/* Ignore physical link up events - wait for logical link up */
5257 		att_type = LPFC_ATT_RESERVED;
5258 		break;
5259 	case LPFC_ASYNC_LINK_STATUS_LOGICAL_UP:
5260 		att_type = LPFC_ATT_LINK_UP;
5261 		break;
5262 	default:
5263 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5264 				"0399 Invalid link attention type: x%x\n",
5265 				bf_get(lpfc_acqe_link_status, acqe_link));
5266 		att_type = LPFC_ATT_RESERVED;
5267 		break;
5268 	}
5269 	return att_type;
5270 }
5271 
5272 /**
5273  * lpfc_sli_port_speed_get - Get sli3 link speed code to link speed
5274  * @phba: pointer to lpfc hba data structure.
5275  *
5276  * This routine is to get an SLI3 FC port's link speed in Mbps.
5277  *
5278  * Return: link speed in terms of Mbps.
5279  **/
5280 uint32_t
5281 lpfc_sli_port_speed_get(struct lpfc_hba *phba)
5282 {
5283 	uint32_t link_speed;
5284 
5285 	if (!lpfc_is_link_up(phba))
5286 		return 0;
5287 
5288 	if (phba->sli_rev <= LPFC_SLI_REV3) {
5289 		switch (phba->fc_linkspeed) {
5290 		case LPFC_LINK_SPEED_1GHZ:
5291 			link_speed = 1000;
5292 			break;
5293 		case LPFC_LINK_SPEED_2GHZ:
5294 			link_speed = 2000;
5295 			break;
5296 		case LPFC_LINK_SPEED_4GHZ:
5297 			link_speed = 4000;
5298 			break;
5299 		case LPFC_LINK_SPEED_8GHZ:
5300 			link_speed = 8000;
5301 			break;
5302 		case LPFC_LINK_SPEED_10GHZ:
5303 			link_speed = 10000;
5304 			break;
5305 		case LPFC_LINK_SPEED_16GHZ:
5306 			link_speed = 16000;
5307 			break;
5308 		default:
5309 			link_speed = 0;
5310 		}
5311 	} else {
5312 		if (phba->sli4_hba.link_state.logical_speed)
5313 			link_speed =
5314 			      phba->sli4_hba.link_state.logical_speed;
5315 		else
5316 			link_speed = phba->sli4_hba.link_state.speed;
5317 	}
5318 	return link_speed;
5319 }
5320 
5321 /**
5322  * lpfc_sli4_port_speed_parse - Parse async evt link speed code to link speed
5323  * @phba: pointer to lpfc hba data structure.
5324  * @evt_code: asynchronous event code.
5325  * @speed_code: asynchronous event link speed code.
5326  *
5327  * This routine is to parse the giving SLI4 async event link speed code into
5328  * value of Mbps for the link speed.
5329  *
5330  * Return: link speed in terms of Mbps.
5331  **/
5332 static uint32_t
5333 lpfc_sli4_port_speed_parse(struct lpfc_hba *phba, uint32_t evt_code,
5334 			   uint8_t speed_code)
5335 {
5336 	uint32_t port_speed;
5337 
5338 	switch (evt_code) {
5339 	case LPFC_TRAILER_CODE_LINK:
5340 		switch (speed_code) {
5341 		case LPFC_ASYNC_LINK_SPEED_ZERO:
5342 			port_speed = 0;
5343 			break;
5344 		case LPFC_ASYNC_LINK_SPEED_10MBPS:
5345 			port_speed = 10;
5346 			break;
5347 		case LPFC_ASYNC_LINK_SPEED_100MBPS:
5348 			port_speed = 100;
5349 			break;
5350 		case LPFC_ASYNC_LINK_SPEED_1GBPS:
5351 			port_speed = 1000;
5352 			break;
5353 		case LPFC_ASYNC_LINK_SPEED_10GBPS:
5354 			port_speed = 10000;
5355 			break;
5356 		case LPFC_ASYNC_LINK_SPEED_20GBPS:
5357 			port_speed = 20000;
5358 			break;
5359 		case LPFC_ASYNC_LINK_SPEED_25GBPS:
5360 			port_speed = 25000;
5361 			break;
5362 		case LPFC_ASYNC_LINK_SPEED_40GBPS:
5363 			port_speed = 40000;
5364 			break;
5365 		case LPFC_ASYNC_LINK_SPEED_100GBPS:
5366 			port_speed = 100000;
5367 			break;
5368 		default:
5369 			port_speed = 0;
5370 		}
5371 		break;
5372 	case LPFC_TRAILER_CODE_FC:
5373 		switch (speed_code) {
5374 		case LPFC_FC_LA_SPEED_UNKNOWN:
5375 			port_speed = 0;
5376 			break;
5377 		case LPFC_FC_LA_SPEED_1G:
5378 			port_speed = 1000;
5379 			break;
5380 		case LPFC_FC_LA_SPEED_2G:
5381 			port_speed = 2000;
5382 			break;
5383 		case LPFC_FC_LA_SPEED_4G:
5384 			port_speed = 4000;
5385 			break;
5386 		case LPFC_FC_LA_SPEED_8G:
5387 			port_speed = 8000;
5388 			break;
5389 		case LPFC_FC_LA_SPEED_10G:
5390 			port_speed = 10000;
5391 			break;
5392 		case LPFC_FC_LA_SPEED_16G:
5393 			port_speed = 16000;
5394 			break;
5395 		case LPFC_FC_LA_SPEED_32G:
5396 			port_speed = 32000;
5397 			break;
5398 		case LPFC_FC_LA_SPEED_64G:
5399 			port_speed = 64000;
5400 			break;
5401 		case LPFC_FC_LA_SPEED_128G:
5402 			port_speed = 128000;
5403 			break;
5404 		case LPFC_FC_LA_SPEED_256G:
5405 			port_speed = 256000;
5406 			break;
5407 		default:
5408 			port_speed = 0;
5409 		}
5410 		break;
5411 	default:
5412 		port_speed = 0;
5413 	}
5414 	return port_speed;
5415 }
5416 
5417 /**
5418  * lpfc_sli4_async_link_evt - Process the asynchronous FCoE link event
5419  * @phba: pointer to lpfc hba data structure.
5420  * @acqe_link: pointer to the async link completion queue entry.
5421  *
5422  * This routine is to handle the SLI4 asynchronous FCoE link event.
5423  **/
5424 static void
5425 lpfc_sli4_async_link_evt(struct lpfc_hba *phba,
5426 			 struct lpfc_acqe_link *acqe_link)
5427 {
5428 	LPFC_MBOXQ_t *pmb;
5429 	MAILBOX_t *mb;
5430 	struct lpfc_mbx_read_top *la;
5431 	uint8_t att_type;
5432 	int rc;
5433 
5434 	att_type = lpfc_sli4_parse_latt_type(phba, acqe_link);
5435 	if (att_type != LPFC_ATT_LINK_DOWN && att_type != LPFC_ATT_LINK_UP)
5436 		return;
5437 	phba->fcoe_eventtag = acqe_link->event_tag;
5438 	pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5439 	if (!pmb) {
5440 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5441 				"0395 The mboxq allocation failed\n");
5442 		return;
5443 	}
5444 
5445 	rc = lpfc_mbox_rsrc_prep(phba, pmb);
5446 	if (rc) {
5447 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5448 				"0396 mailbox allocation failed\n");
5449 		goto out_free_pmb;
5450 	}
5451 
5452 	/* Cleanup any outstanding ELS commands */
5453 	lpfc_els_flush_all_cmd(phba);
5454 
5455 	/* Block ELS IOCBs until we have done process link event */
5456 	phba->sli4_hba.els_wq->pring->flag |= LPFC_STOP_IOCB_EVENT;
5457 
5458 	/* Update link event statistics */
5459 	phba->sli.slistat.link_event++;
5460 
5461 	/* Create lpfc_handle_latt mailbox command from link ACQE */
5462 	lpfc_read_topology(phba, pmb, pmb->ctx_buf);
5463 	pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
5464 	pmb->vport = phba->pport;
5465 
5466 	/* Keep the link status for extra SLI4 state machine reference */
5467 	phba->sli4_hba.link_state.speed =
5468 			lpfc_sli4_port_speed_parse(phba, LPFC_TRAILER_CODE_LINK,
5469 				bf_get(lpfc_acqe_link_speed, acqe_link));
5470 	phba->sli4_hba.link_state.duplex =
5471 				bf_get(lpfc_acqe_link_duplex, acqe_link);
5472 	phba->sli4_hba.link_state.status =
5473 				bf_get(lpfc_acqe_link_status, acqe_link);
5474 	phba->sli4_hba.link_state.type =
5475 				bf_get(lpfc_acqe_link_type, acqe_link);
5476 	phba->sli4_hba.link_state.number =
5477 				bf_get(lpfc_acqe_link_number, acqe_link);
5478 	phba->sli4_hba.link_state.fault =
5479 				bf_get(lpfc_acqe_link_fault, acqe_link);
5480 	phba->sli4_hba.link_state.logical_speed =
5481 			bf_get(lpfc_acqe_logical_link_speed, acqe_link) * 10;
5482 
5483 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5484 			"2900 Async FC/FCoE Link event - Speed:%dGBit "
5485 			"duplex:x%x LA Type:x%x Port Type:%d Port Number:%d "
5486 			"Logical speed:%dMbps Fault:%d\n",
5487 			phba->sli4_hba.link_state.speed,
5488 			phba->sli4_hba.link_state.topology,
5489 			phba->sli4_hba.link_state.status,
5490 			phba->sli4_hba.link_state.type,
5491 			phba->sli4_hba.link_state.number,
5492 			phba->sli4_hba.link_state.logical_speed,
5493 			phba->sli4_hba.link_state.fault);
5494 	/*
5495 	 * For FC Mode: issue the READ_TOPOLOGY mailbox command to fetch
5496 	 * topology info. Note: Optional for non FC-AL ports.
5497 	 */
5498 	if (!test_bit(HBA_FCOE_MODE, &phba->hba_flag)) {
5499 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
5500 		if (rc == MBX_NOT_FINISHED)
5501 			goto out_free_pmb;
5502 		return;
5503 	}
5504 	/*
5505 	 * For FCoE Mode: fill in all the topology information we need and call
5506 	 * the READ_TOPOLOGY completion routine to continue without actually
5507 	 * sending the READ_TOPOLOGY mailbox command to the port.
5508 	 */
5509 	/* Initialize completion status */
5510 	mb = &pmb->u.mb;
5511 	mb->mbxStatus = MBX_SUCCESS;
5512 
5513 	/* Parse port fault information field */
5514 	lpfc_sli4_parse_latt_fault(phba, acqe_link);
5515 
5516 	/* Parse and translate link attention fields */
5517 	la = (struct lpfc_mbx_read_top *) &pmb->u.mb.un.varReadTop;
5518 	la->eventTag = acqe_link->event_tag;
5519 	bf_set(lpfc_mbx_read_top_att_type, la, att_type);
5520 	bf_set(lpfc_mbx_read_top_link_spd, la,
5521 	       (bf_get(lpfc_acqe_link_speed, acqe_link)));
5522 
5523 	/* Fake the following irrelevant fields */
5524 	bf_set(lpfc_mbx_read_top_topology, la, LPFC_TOPOLOGY_PT_PT);
5525 	bf_set(lpfc_mbx_read_top_alpa_granted, la, 0);
5526 	bf_set(lpfc_mbx_read_top_il, la, 0);
5527 	bf_set(lpfc_mbx_read_top_pb, la, 0);
5528 	bf_set(lpfc_mbx_read_top_fa, la, 0);
5529 	bf_set(lpfc_mbx_read_top_mm, la, 0);
5530 
5531 	/* Invoke the lpfc_handle_latt mailbox command callback function */
5532 	lpfc_mbx_cmpl_read_topology(phba, pmb);
5533 
5534 	return;
5535 
5536 out_free_pmb:
5537 	lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
5538 }
5539 
5540 /**
5541  * lpfc_async_link_speed_to_read_top - Parse async evt link speed code to read
5542  * topology.
5543  * @phba: pointer to lpfc hba data structure.
5544  * @speed_code: asynchronous event link speed code.
5545  *
5546  * This routine is to parse the giving SLI4 async event link speed code into
5547  * value of Read topology link speed.
5548  *
5549  * Return: link speed in terms of Read topology.
5550  **/
5551 static uint8_t
5552 lpfc_async_link_speed_to_read_top(struct lpfc_hba *phba, uint8_t speed_code)
5553 {
5554 	uint8_t port_speed;
5555 
5556 	switch (speed_code) {
5557 	case LPFC_FC_LA_SPEED_1G:
5558 		port_speed = LPFC_LINK_SPEED_1GHZ;
5559 		break;
5560 	case LPFC_FC_LA_SPEED_2G:
5561 		port_speed = LPFC_LINK_SPEED_2GHZ;
5562 		break;
5563 	case LPFC_FC_LA_SPEED_4G:
5564 		port_speed = LPFC_LINK_SPEED_4GHZ;
5565 		break;
5566 	case LPFC_FC_LA_SPEED_8G:
5567 		port_speed = LPFC_LINK_SPEED_8GHZ;
5568 		break;
5569 	case LPFC_FC_LA_SPEED_16G:
5570 		port_speed = LPFC_LINK_SPEED_16GHZ;
5571 		break;
5572 	case LPFC_FC_LA_SPEED_32G:
5573 		port_speed = LPFC_LINK_SPEED_32GHZ;
5574 		break;
5575 	case LPFC_FC_LA_SPEED_64G:
5576 		port_speed = LPFC_LINK_SPEED_64GHZ;
5577 		break;
5578 	case LPFC_FC_LA_SPEED_128G:
5579 		port_speed = LPFC_LINK_SPEED_128GHZ;
5580 		break;
5581 	case LPFC_FC_LA_SPEED_256G:
5582 		port_speed = LPFC_LINK_SPEED_256GHZ;
5583 		break;
5584 	default:
5585 		port_speed = 0;
5586 		break;
5587 	}
5588 
5589 	return port_speed;
5590 }
5591 
5592 void
5593 lpfc_cgn_dump_rxmonitor(struct lpfc_hba *phba)
5594 {
5595 	if (!phba->rx_monitor) {
5596 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5597 				"4411 Rx Monitor Info is empty.\n");
5598 	} else {
5599 		lpfc_rx_monitor_report(phba, phba->rx_monitor, NULL, 0,
5600 				       LPFC_MAX_RXMONITOR_DUMP);
5601 	}
5602 }
5603 
5604 /**
5605  * lpfc_cgn_update_stat - Save data into congestion stats buffer
5606  * @phba: pointer to lpfc hba data structure.
5607  * @dtag: FPIN descriptor received
5608  *
5609  * Increment the FPIN received counter/time when it happens.
5610  */
5611 void
5612 lpfc_cgn_update_stat(struct lpfc_hba *phba, uint32_t dtag)
5613 {
5614 	struct lpfc_cgn_info *cp;
5615 	u32 value;
5616 
5617 	/* Make sure we have a congestion info buffer */
5618 	if (!phba->cgn_i)
5619 		return;
5620 	cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
5621 
5622 	/* Update congestion statistics */
5623 	switch (dtag) {
5624 	case ELS_DTAG_LNK_INTEGRITY:
5625 		le32_add_cpu(&cp->link_integ_notification, 1);
5626 		lpfc_cgn_update_tstamp(phba, &cp->stat_lnk);
5627 		break;
5628 	case ELS_DTAG_DELIVERY:
5629 		le32_add_cpu(&cp->delivery_notification, 1);
5630 		lpfc_cgn_update_tstamp(phba, &cp->stat_delivery);
5631 		break;
5632 	case ELS_DTAG_PEER_CONGEST:
5633 		le32_add_cpu(&cp->cgn_peer_notification, 1);
5634 		lpfc_cgn_update_tstamp(phba, &cp->stat_peer);
5635 		break;
5636 	case ELS_DTAG_CONGESTION:
5637 		le32_add_cpu(&cp->cgn_notification, 1);
5638 		lpfc_cgn_update_tstamp(phba, &cp->stat_fpin);
5639 	}
5640 	if (phba->cgn_fpin_frequency &&
5641 	    phba->cgn_fpin_frequency != LPFC_FPIN_INIT_FREQ) {
5642 		value = LPFC_CGN_TIMER_TO_MIN / phba->cgn_fpin_frequency;
5643 		cp->cgn_stat_npm = value;
5644 	}
5645 
5646 	value = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ,
5647 				    LPFC_CGN_CRC32_SEED);
5648 	cp->cgn_info_crc = cpu_to_le32(value);
5649 }
5650 
5651 /**
5652  * lpfc_cgn_update_tstamp - Update cmf timestamp
5653  * @phba: pointer to lpfc hba data structure.
5654  * @ts: structure to write the timestamp to.
5655  */
5656 void
5657 lpfc_cgn_update_tstamp(struct lpfc_hba *phba, struct lpfc_cgn_ts *ts)
5658 {
5659 	struct timespec64 cur_time;
5660 	struct tm tm_val;
5661 
5662 	ktime_get_real_ts64(&cur_time);
5663 	time64_to_tm(cur_time.tv_sec, 0, &tm_val);
5664 
5665 	ts->month = tm_val.tm_mon + 1;
5666 	ts->day	= tm_val.tm_mday;
5667 	ts->year = tm_val.tm_year - 100;
5668 	ts->hour = tm_val.tm_hour;
5669 	ts->minute = tm_val.tm_min;
5670 	ts->second = tm_val.tm_sec;
5671 
5672 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5673 			"2646 Updated CMF timestamp : "
5674 			"%u/%u/%u %u:%u:%u\n",
5675 			ts->day, ts->month,
5676 			ts->year, ts->hour,
5677 			ts->minute, ts->second);
5678 }
5679 
5680 /**
5681  * lpfc_cmf_stats_timer - Save data into registered congestion buffer
5682  * @timer: Timer cookie to access lpfc private data
5683  *
5684  * Save the congestion event data every minute.
5685  * On the hour collapse all the minute data into hour data. Every day
5686  * collapse all the hour data into daily data. Separate driver
5687  * and fabrc congestion event counters that will be saved out
5688  * to the registered congestion buffer every minute.
5689  */
5690 static enum hrtimer_restart
5691 lpfc_cmf_stats_timer(struct hrtimer *timer)
5692 {
5693 	struct lpfc_hba *phba;
5694 	struct lpfc_cgn_info *cp;
5695 	uint32_t i, index;
5696 	uint16_t value, mvalue;
5697 	uint64_t bps;
5698 	uint32_t mbps;
5699 	uint32_t dvalue, wvalue, lvalue, avalue;
5700 	uint64_t latsum;
5701 	__le16 *ptr;
5702 	__le32 *lptr;
5703 	__le16 *mptr;
5704 
5705 	phba = container_of(timer, struct lpfc_hba, cmf_stats_timer);
5706 	/* Make sure we have a congestion info buffer */
5707 	if (!phba->cgn_i)
5708 		return HRTIMER_NORESTART;
5709 	cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
5710 
5711 	phba->cgn_evt_timestamp = jiffies +
5712 			msecs_to_jiffies(LPFC_CGN_TIMER_TO_MIN);
5713 	phba->cgn_evt_minute++;
5714 
5715 	/* We should get to this point in the routine on 1 minute intervals */
5716 	lpfc_cgn_update_tstamp(phba, &cp->base_time);
5717 
5718 	if (phba->cgn_fpin_frequency &&
5719 	    phba->cgn_fpin_frequency != LPFC_FPIN_INIT_FREQ) {
5720 		value = LPFC_CGN_TIMER_TO_MIN / phba->cgn_fpin_frequency;
5721 		cp->cgn_stat_npm = value;
5722 	}
5723 
5724 	/* Read and clear the latency counters for this minute */
5725 	lvalue = atomic_read(&phba->cgn_latency_evt_cnt);
5726 	latsum = atomic64_read(&phba->cgn_latency_evt);
5727 	atomic_set(&phba->cgn_latency_evt_cnt, 0);
5728 	atomic64_set(&phba->cgn_latency_evt, 0);
5729 
5730 	/* We need to store MB/sec bandwidth in the congestion information.
5731 	 * block_cnt is count of 512 byte blocks for the entire minute,
5732 	 * bps will get bytes per sec before finally converting to MB/sec.
5733 	 */
5734 	bps = div_u64(phba->rx_block_cnt, LPFC_SEC_MIN) * 512;
5735 	phba->rx_block_cnt = 0;
5736 	mvalue = bps / (1024 * 1024); /* convert to MB/sec */
5737 
5738 	/* Every minute */
5739 	/* cgn parameters */
5740 	cp->cgn_info_mode = phba->cgn_p.cgn_param_mode;
5741 	cp->cgn_info_level0 = phba->cgn_p.cgn_param_level0;
5742 	cp->cgn_info_level1 = phba->cgn_p.cgn_param_level1;
5743 	cp->cgn_info_level2 = phba->cgn_p.cgn_param_level2;
5744 
5745 	/* Fill in default LUN qdepth */
5746 	value = (uint16_t)(phba->pport->cfg_lun_queue_depth);
5747 	cp->cgn_lunq = cpu_to_le16(value);
5748 
5749 	/* Record congestion buffer info - every minute
5750 	 * cgn_driver_evt_cnt (Driver events)
5751 	 * cgn_fabric_warn_cnt (Congestion Warnings)
5752 	 * cgn_latency_evt_cnt / cgn_latency_evt (IO Latency)
5753 	 * cgn_fabric_alarm_cnt (Congestion Alarms)
5754 	 */
5755 	index = ++cp->cgn_index_minute;
5756 	if (cp->cgn_index_minute == LPFC_MIN_HOUR) {
5757 		cp->cgn_index_minute = 0;
5758 		index = 0;
5759 	}
5760 
5761 	/* Get the number of driver events in this sample and reset counter */
5762 	dvalue = atomic_read(&phba->cgn_driver_evt_cnt);
5763 	atomic_set(&phba->cgn_driver_evt_cnt, 0);
5764 
5765 	/* Get the number of warning events - FPIN and Signal for this minute */
5766 	wvalue = 0;
5767 	if ((phba->cgn_reg_fpin & LPFC_CGN_FPIN_WARN) ||
5768 	    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY ||
5769 	    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM)
5770 		wvalue = atomic_read(&phba->cgn_fabric_warn_cnt);
5771 	atomic_set(&phba->cgn_fabric_warn_cnt, 0);
5772 
5773 	/* Get the number of alarm events - FPIN and Signal for this minute */
5774 	avalue = 0;
5775 	if ((phba->cgn_reg_fpin & LPFC_CGN_FPIN_ALARM) ||
5776 	    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM)
5777 		avalue = atomic_read(&phba->cgn_fabric_alarm_cnt);
5778 	atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
5779 
5780 	/* Collect the driver, warning, alarm and latency counts for this
5781 	 * minute into the driver congestion buffer.
5782 	 */
5783 	ptr = &cp->cgn_drvr_min[index];
5784 	value = (uint16_t)dvalue;
5785 	*ptr = cpu_to_le16(value);
5786 
5787 	ptr = &cp->cgn_warn_min[index];
5788 	value = (uint16_t)wvalue;
5789 	*ptr = cpu_to_le16(value);
5790 
5791 	ptr = &cp->cgn_alarm_min[index];
5792 	value = (uint16_t)avalue;
5793 	*ptr = cpu_to_le16(value);
5794 
5795 	lptr = &cp->cgn_latency_min[index];
5796 	if (lvalue) {
5797 		lvalue = (uint32_t)div_u64(latsum, lvalue);
5798 		*lptr = cpu_to_le32(lvalue);
5799 	} else {
5800 		*lptr = 0;
5801 	}
5802 
5803 	/* Collect the bandwidth value into the driver's congesion buffer. */
5804 	mptr = &cp->cgn_bw_min[index];
5805 	*mptr = cpu_to_le16(mvalue);
5806 
5807 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5808 			"2418 Congestion Info - minute (%d): %d %d %d %d %d\n",
5809 			index, dvalue, wvalue, *lptr, mvalue, avalue);
5810 
5811 	/* Every hour */
5812 	if ((phba->cgn_evt_minute % LPFC_MIN_HOUR) == 0) {
5813 		/* Record congestion buffer info - every hour
5814 		 * Collapse all minutes into an hour
5815 		 */
5816 		index = ++cp->cgn_index_hour;
5817 		if (cp->cgn_index_hour == LPFC_HOUR_DAY) {
5818 			cp->cgn_index_hour = 0;
5819 			index = 0;
5820 		}
5821 
5822 		dvalue = 0;
5823 		wvalue = 0;
5824 		lvalue = 0;
5825 		avalue = 0;
5826 		mvalue = 0;
5827 		mbps = 0;
5828 		for (i = 0; i < LPFC_MIN_HOUR; i++) {
5829 			dvalue += le16_to_cpu(cp->cgn_drvr_min[i]);
5830 			wvalue += le16_to_cpu(cp->cgn_warn_min[i]);
5831 			lvalue += le32_to_cpu(cp->cgn_latency_min[i]);
5832 			mbps += le16_to_cpu(cp->cgn_bw_min[i]);
5833 			avalue += le16_to_cpu(cp->cgn_alarm_min[i]);
5834 		}
5835 		if (lvalue)		/* Avg of latency averages */
5836 			lvalue /= LPFC_MIN_HOUR;
5837 		if (mbps)		/* Avg of Bandwidth averages */
5838 			mvalue = mbps / LPFC_MIN_HOUR;
5839 
5840 		lptr = &cp->cgn_drvr_hr[index];
5841 		*lptr = cpu_to_le32(dvalue);
5842 		lptr = &cp->cgn_warn_hr[index];
5843 		*lptr = cpu_to_le32(wvalue);
5844 		lptr = &cp->cgn_latency_hr[index];
5845 		*lptr = cpu_to_le32(lvalue);
5846 		mptr = &cp->cgn_bw_hr[index];
5847 		*mptr = cpu_to_le16(mvalue);
5848 		lptr = &cp->cgn_alarm_hr[index];
5849 		*lptr = cpu_to_le32(avalue);
5850 
5851 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5852 				"2419 Congestion Info - hour "
5853 				"(%d): %d %d %d %d %d\n",
5854 				index, dvalue, wvalue, lvalue, mvalue, avalue);
5855 	}
5856 
5857 	/* Every day */
5858 	if ((phba->cgn_evt_minute % LPFC_MIN_DAY) == 0) {
5859 		/* Record congestion buffer info - every hour
5860 		 * Collapse all hours into a day. Rotate days
5861 		 * after LPFC_MAX_CGN_DAYS.
5862 		 */
5863 		index = ++cp->cgn_index_day;
5864 		if (cp->cgn_index_day == LPFC_MAX_CGN_DAYS) {
5865 			cp->cgn_index_day = 0;
5866 			index = 0;
5867 		}
5868 
5869 		dvalue = 0;
5870 		wvalue = 0;
5871 		lvalue = 0;
5872 		mvalue = 0;
5873 		mbps = 0;
5874 		avalue = 0;
5875 		for (i = 0; i < LPFC_HOUR_DAY; i++) {
5876 			dvalue += le32_to_cpu(cp->cgn_drvr_hr[i]);
5877 			wvalue += le32_to_cpu(cp->cgn_warn_hr[i]);
5878 			lvalue += le32_to_cpu(cp->cgn_latency_hr[i]);
5879 			mbps += le16_to_cpu(cp->cgn_bw_hr[i]);
5880 			avalue += le32_to_cpu(cp->cgn_alarm_hr[i]);
5881 		}
5882 		if (lvalue)		/* Avg of latency averages */
5883 			lvalue /= LPFC_HOUR_DAY;
5884 		if (mbps)		/* Avg of Bandwidth averages */
5885 			mvalue = mbps / LPFC_HOUR_DAY;
5886 
5887 		lptr = &cp->cgn_drvr_day[index];
5888 		*lptr = cpu_to_le32(dvalue);
5889 		lptr = &cp->cgn_warn_day[index];
5890 		*lptr = cpu_to_le32(wvalue);
5891 		lptr = &cp->cgn_latency_day[index];
5892 		*lptr = cpu_to_le32(lvalue);
5893 		mptr = &cp->cgn_bw_day[index];
5894 		*mptr = cpu_to_le16(mvalue);
5895 		lptr = &cp->cgn_alarm_day[index];
5896 		*lptr = cpu_to_le32(avalue);
5897 
5898 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5899 				"2420 Congestion Info - daily (%d): "
5900 				"%d %d %d %d %d\n",
5901 				index, dvalue, wvalue, lvalue, mvalue, avalue);
5902 	}
5903 
5904 	/* Use the frequency found in the last rcv'ed FPIN */
5905 	value = phba->cgn_fpin_frequency;
5906 	cp->cgn_warn_freq = cpu_to_le16(value);
5907 	cp->cgn_alarm_freq = cpu_to_le16(value);
5908 
5909 	lvalue = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ,
5910 				     LPFC_CGN_CRC32_SEED);
5911 	cp->cgn_info_crc = cpu_to_le32(lvalue);
5912 
5913 	hrtimer_forward_now(timer, ktime_set(0, LPFC_SEC_MIN * NSEC_PER_SEC));
5914 
5915 	return HRTIMER_RESTART;
5916 }
5917 
5918 /**
5919  * lpfc_calc_cmf_latency - latency from start of rxate timer interval
5920  * @phba: The Hba for which this call is being executed.
5921  *
5922  * The routine calculates the latency from the beginning of the CMF timer
5923  * interval to the current point in time. It is called from IO completion
5924  * when we exceed our Bandwidth limitation for the time interval.
5925  */
5926 uint32_t
5927 lpfc_calc_cmf_latency(struct lpfc_hba *phba)
5928 {
5929 	struct timespec64 cmpl_time;
5930 	uint32_t msec = 0;
5931 
5932 	ktime_get_real_ts64(&cmpl_time);
5933 
5934 	/* This routine works on a ms granularity so sec and usec are
5935 	 * converted accordingly.
5936 	 */
5937 	if (cmpl_time.tv_sec == phba->cmf_latency.tv_sec) {
5938 		msec = (cmpl_time.tv_nsec - phba->cmf_latency.tv_nsec) /
5939 			NSEC_PER_MSEC;
5940 	} else {
5941 		if (cmpl_time.tv_nsec >= phba->cmf_latency.tv_nsec) {
5942 			msec = (cmpl_time.tv_sec -
5943 				phba->cmf_latency.tv_sec) * MSEC_PER_SEC;
5944 			msec += ((cmpl_time.tv_nsec -
5945 				  phba->cmf_latency.tv_nsec) / NSEC_PER_MSEC);
5946 		} else {
5947 			msec = (cmpl_time.tv_sec - phba->cmf_latency.tv_sec -
5948 				1) * MSEC_PER_SEC;
5949 			msec += (((NSEC_PER_SEC - phba->cmf_latency.tv_nsec) +
5950 				 cmpl_time.tv_nsec) / NSEC_PER_MSEC);
5951 		}
5952 	}
5953 	return msec;
5954 }
5955 
5956 /**
5957  * lpfc_cmf_timer -  This is the timer function for one congestion
5958  * rate interval.
5959  * @timer: Pointer to the high resolution timer that expired
5960  */
5961 static enum hrtimer_restart
5962 lpfc_cmf_timer(struct hrtimer *timer)
5963 {
5964 	struct lpfc_hba *phba = container_of(timer, struct lpfc_hba,
5965 					     cmf_timer);
5966 	struct rx_info_entry entry;
5967 	uint32_t io_cnt;
5968 	uint32_t busy, max_read;
5969 	uint64_t total, rcv, lat, mbpi, extra, cnt;
5970 	int timer_interval = LPFC_CMF_INTERVAL;
5971 	uint32_t ms;
5972 	struct lpfc_cgn_stat *cgs;
5973 	int cpu;
5974 
5975 	/* Only restart the timer if congestion mgmt is on */
5976 	if (phba->cmf_active_mode == LPFC_CFG_OFF ||
5977 	    !phba->cmf_latency.tv_sec) {
5978 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5979 				"6224 CMF timer exit: %d %lld\n",
5980 				phba->cmf_active_mode,
5981 				(uint64_t)phba->cmf_latency.tv_sec);
5982 		return HRTIMER_NORESTART;
5983 	}
5984 
5985 	/* If pport is not ready yet, just exit and wait for
5986 	 * the next timer cycle to hit.
5987 	 */
5988 	if (!phba->pport)
5989 		goto skip;
5990 
5991 	/* Do not block SCSI IO while in the timer routine since
5992 	 * total_bytes will be cleared
5993 	 */
5994 	atomic_set(&phba->cmf_stop_io, 1);
5995 
5996 	/* First we need to calculate the actual ms between
5997 	 * the last timer interrupt and this one. We ask for
5998 	 * LPFC_CMF_INTERVAL, however the actual time may
5999 	 * vary depending on system overhead.
6000 	 */
6001 	ms = lpfc_calc_cmf_latency(phba);
6002 
6003 
6004 	/* Immediately after we calculate the time since the last
6005 	 * timer interrupt, set the start time for the next
6006 	 * interrupt
6007 	 */
6008 	ktime_get_real_ts64(&phba->cmf_latency);
6009 
6010 	phba->cmf_link_byte_count =
6011 		div_u64(phba->cmf_max_line_rate * LPFC_CMF_INTERVAL, 1000);
6012 
6013 	/* Collect all the stats from the prior timer interval */
6014 	total = 0;
6015 	io_cnt = 0;
6016 	lat = 0;
6017 	rcv = 0;
6018 	for_each_present_cpu(cpu) {
6019 		cgs = per_cpu_ptr(phba->cmf_stat, cpu);
6020 		total += atomic64_xchg(&cgs->total_bytes, 0);
6021 		io_cnt += atomic_xchg(&cgs->rx_io_cnt, 0);
6022 		lat += atomic64_xchg(&cgs->rx_latency, 0);
6023 		rcv += atomic64_xchg(&cgs->rcv_bytes, 0);
6024 	}
6025 
6026 	/* Before we issue another CMF_SYNC_WQE, retrieve the BW
6027 	 * returned from the last CMF_SYNC_WQE issued, from
6028 	 * cmf_last_sync_bw. This will be the target BW for
6029 	 * this next timer interval.
6030 	 */
6031 	if (phba->cmf_active_mode == LPFC_CFG_MANAGED &&
6032 	    phba->link_state != LPFC_LINK_DOWN &&
6033 	    test_bit(HBA_SETUP, &phba->hba_flag)) {
6034 		mbpi = phba->cmf_last_sync_bw;
6035 		phba->cmf_last_sync_bw = 0;
6036 		extra = 0;
6037 
6038 		/* Calculate any extra bytes needed to account for the
6039 		 * timer accuracy. If we are less than LPFC_CMF_INTERVAL
6040 		 * calculate the adjustment needed for total to reflect
6041 		 * a full LPFC_CMF_INTERVAL.
6042 		 */
6043 		if (ms && ms < LPFC_CMF_INTERVAL) {
6044 			cnt = div_u64(total, ms); /* bytes per ms */
6045 			cnt *= LPFC_CMF_INTERVAL; /* what total should be */
6046 			extra = cnt - total;
6047 		}
6048 		lpfc_issue_cmf_sync_wqe(phba, LPFC_CMF_INTERVAL, total + extra);
6049 	} else {
6050 		/* For Monitor mode or link down we want mbpi
6051 		 * to be the full link speed
6052 		 */
6053 		mbpi = phba->cmf_link_byte_count;
6054 		extra = 0;
6055 	}
6056 	phba->cmf_timer_cnt++;
6057 
6058 	if (io_cnt) {
6059 		/* Update congestion info buffer latency in us */
6060 		atomic_add(io_cnt, &phba->cgn_latency_evt_cnt);
6061 		atomic64_add(lat, &phba->cgn_latency_evt);
6062 	}
6063 	busy = atomic_xchg(&phba->cmf_busy, 0);
6064 	max_read = atomic_xchg(&phba->rx_max_read_cnt, 0);
6065 
6066 	/* Calculate MBPI for the next timer interval */
6067 	if (mbpi) {
6068 		if (mbpi > phba->cmf_link_byte_count ||
6069 		    phba->cmf_active_mode == LPFC_CFG_MONITOR)
6070 			mbpi = phba->cmf_link_byte_count;
6071 
6072 		/* Change max_bytes_per_interval to what the prior
6073 		 * CMF_SYNC_WQE cmpl indicated.
6074 		 */
6075 		if (mbpi != phba->cmf_max_bytes_per_interval)
6076 			phba->cmf_max_bytes_per_interval = mbpi;
6077 	}
6078 
6079 	/* Save rxmonitor information for debug */
6080 	if (phba->rx_monitor) {
6081 		entry.total_bytes = total;
6082 		entry.cmf_bytes = total + extra;
6083 		entry.rcv_bytes = rcv;
6084 		entry.cmf_busy = busy;
6085 		entry.cmf_info = phba->cmf_active_info;
6086 		if (io_cnt) {
6087 			entry.avg_io_latency = div_u64(lat, io_cnt);
6088 			entry.avg_io_size = div_u64(rcv, io_cnt);
6089 		} else {
6090 			entry.avg_io_latency = 0;
6091 			entry.avg_io_size = 0;
6092 		}
6093 		entry.max_read_cnt = max_read;
6094 		entry.io_cnt = io_cnt;
6095 		entry.max_bytes_per_interval = mbpi;
6096 		if (phba->cmf_active_mode == LPFC_CFG_MANAGED)
6097 			entry.timer_utilization = phba->cmf_last_ts;
6098 		else
6099 			entry.timer_utilization = ms;
6100 		entry.timer_interval = ms;
6101 		phba->cmf_last_ts = 0;
6102 
6103 		lpfc_rx_monitor_record(phba->rx_monitor, &entry);
6104 	}
6105 
6106 	if (phba->cmf_active_mode == LPFC_CFG_MONITOR) {
6107 		/* If Monitor mode, check if we are oversubscribed
6108 		 * against the full line rate.
6109 		 */
6110 		if (mbpi && total > mbpi)
6111 			atomic_inc(&phba->cgn_driver_evt_cnt);
6112 	}
6113 	phba->rx_block_cnt += div_u64(rcv, 512);  /* save 512 byte block cnt */
6114 
6115 	/* Since total_bytes has already been zero'ed, its okay to unblock
6116 	 * after max_bytes_per_interval is setup.
6117 	 */
6118 	if (atomic_xchg(&phba->cmf_bw_wait, 0))
6119 		queue_work(phba->wq, &phba->unblock_request_work);
6120 
6121 	/* SCSI IO is now unblocked */
6122 	atomic_set(&phba->cmf_stop_io, 0);
6123 
6124 skip:
6125 	hrtimer_forward_now(timer,
6126 			    ktime_set(0, timer_interval * NSEC_PER_MSEC));
6127 	return HRTIMER_RESTART;
6128 }
6129 
6130 #define trunk_link_status(__idx)\
6131 	bf_get(lpfc_acqe_fc_la_trunk_config_port##__idx, acqe_fc) ?\
6132 	       ((phba->trunk_link.link##__idx.state == LPFC_LINK_UP) ?\
6133 		"Link up" : "Link down") : "NA"
6134 /* Did port __idx reported an error */
6135 #define trunk_port_fault(__idx)\
6136 	bf_get(lpfc_acqe_fc_la_trunk_config_port##__idx, acqe_fc) ?\
6137 	       (port_fault & (1 << __idx) ? "YES" : "NO") : "NA"
6138 
6139 static void
6140 lpfc_update_trunk_link_status(struct lpfc_hba *phba,
6141 			      struct lpfc_acqe_fc_la *acqe_fc)
6142 {
6143 	uint8_t port_fault = bf_get(lpfc_acqe_fc_la_trunk_linkmask, acqe_fc);
6144 	uint8_t err = bf_get(lpfc_acqe_fc_la_trunk_fault, acqe_fc);
6145 	u8 cnt = 0;
6146 
6147 	phba->sli4_hba.link_state.speed =
6148 		lpfc_sli4_port_speed_parse(phba, LPFC_TRAILER_CODE_FC,
6149 				bf_get(lpfc_acqe_fc_la_speed, acqe_fc));
6150 
6151 	phba->sli4_hba.link_state.logical_speed =
6152 				bf_get(lpfc_acqe_fc_la_llink_spd, acqe_fc) * 10;
6153 	/* We got FC link speed, convert to fc_linkspeed (READ_TOPOLOGY) */
6154 	phba->fc_linkspeed =
6155 		 lpfc_async_link_speed_to_read_top(
6156 				phba,
6157 				bf_get(lpfc_acqe_fc_la_speed, acqe_fc));
6158 
6159 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port0, acqe_fc)) {
6160 		phba->trunk_link.link0.state =
6161 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port0, acqe_fc)
6162 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
6163 		phba->trunk_link.link0.fault = port_fault & 0x1 ? err : 0;
6164 		cnt++;
6165 	}
6166 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port1, acqe_fc)) {
6167 		phba->trunk_link.link1.state =
6168 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port1, acqe_fc)
6169 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
6170 		phba->trunk_link.link1.fault = port_fault & 0x2 ? err : 0;
6171 		cnt++;
6172 	}
6173 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port2, acqe_fc)) {
6174 		phba->trunk_link.link2.state =
6175 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port2, acqe_fc)
6176 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
6177 		phba->trunk_link.link2.fault = port_fault & 0x4 ? err : 0;
6178 		cnt++;
6179 	}
6180 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port3, acqe_fc)) {
6181 		phba->trunk_link.link3.state =
6182 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port3, acqe_fc)
6183 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
6184 		phba->trunk_link.link3.fault = port_fault & 0x8 ? err : 0;
6185 		cnt++;
6186 	}
6187 
6188 	if (cnt)
6189 		phba->trunk_link.phy_lnk_speed =
6190 			phba->sli4_hba.link_state.logical_speed / (cnt * 1000);
6191 	else
6192 		phba->trunk_link.phy_lnk_speed = LPFC_LINK_SPEED_UNKNOWN;
6193 
6194 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6195 			"2910 Async FC Trunking Event - Speed:%d\n"
6196 			"\tLogical speed:%d "
6197 			"port0: %s port1: %s port2: %s port3: %s\n",
6198 			phba->sli4_hba.link_state.speed,
6199 			phba->sli4_hba.link_state.logical_speed,
6200 			trunk_link_status(0), trunk_link_status(1),
6201 			trunk_link_status(2), trunk_link_status(3));
6202 
6203 	if (phba->cmf_active_mode != LPFC_CFG_OFF)
6204 		lpfc_cmf_signal_init(phba);
6205 
6206 	if (port_fault)
6207 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6208 				"3202 trunk error:0x%x (%s) seen on port0:%s "
6209 				/*
6210 				 * SLI-4: We have only 0xA error codes
6211 				 * defined as of now. print an appropriate
6212 				 * message in case driver needs to be updated.
6213 				 */
6214 				"port1:%s port2:%s port3:%s\n", err, err > 0xA ?
6215 				"UNDEFINED. update driver." : trunk_errmsg[err],
6216 				trunk_port_fault(0), trunk_port_fault(1),
6217 				trunk_port_fault(2), trunk_port_fault(3));
6218 }
6219 
6220 
6221 /**
6222  * lpfc_sli4_async_fc_evt - Process the asynchronous FC link event
6223  * @phba: pointer to lpfc hba data structure.
6224  * @acqe_fc: pointer to the async fc completion queue entry.
6225  *
6226  * This routine is to handle the SLI4 asynchronous FC event. It will simply log
6227  * that the event was received and then issue a read_topology mailbox command so
6228  * that the rest of the driver will treat it the same as SLI3.
6229  **/
6230 static void
6231 lpfc_sli4_async_fc_evt(struct lpfc_hba *phba, struct lpfc_acqe_fc_la *acqe_fc)
6232 {
6233 	LPFC_MBOXQ_t *pmb;
6234 	MAILBOX_t *mb;
6235 	struct lpfc_mbx_read_top *la;
6236 	char *log_level;
6237 	int rc;
6238 
6239 	if (bf_get(lpfc_trailer_type, acqe_fc) !=
6240 	    LPFC_FC_LA_EVENT_TYPE_FC_LINK) {
6241 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6242 				"2895 Non FC link Event detected.(%d)\n",
6243 				bf_get(lpfc_trailer_type, acqe_fc));
6244 		return;
6245 	}
6246 
6247 	if (bf_get(lpfc_acqe_fc_la_att_type, acqe_fc) ==
6248 	    LPFC_FC_LA_TYPE_TRUNKING_EVENT) {
6249 		lpfc_update_trunk_link_status(phba, acqe_fc);
6250 		return;
6251 	}
6252 
6253 	/* Keep the link status for extra SLI4 state machine reference */
6254 	phba->sli4_hba.link_state.speed =
6255 			lpfc_sli4_port_speed_parse(phba, LPFC_TRAILER_CODE_FC,
6256 				bf_get(lpfc_acqe_fc_la_speed, acqe_fc));
6257 	phba->sli4_hba.link_state.duplex = LPFC_ASYNC_LINK_DUPLEX_FULL;
6258 	phba->sli4_hba.link_state.topology =
6259 				bf_get(lpfc_acqe_fc_la_topology, acqe_fc);
6260 	phba->sli4_hba.link_state.status =
6261 				bf_get(lpfc_acqe_fc_la_att_type, acqe_fc);
6262 	phba->sli4_hba.link_state.type =
6263 				bf_get(lpfc_acqe_fc_la_port_type, acqe_fc);
6264 	phba->sli4_hba.link_state.number =
6265 				bf_get(lpfc_acqe_fc_la_port_number, acqe_fc);
6266 	phba->sli4_hba.link_state.fault =
6267 				bf_get(lpfc_acqe_link_fault, acqe_fc);
6268 	phba->sli4_hba.link_state.link_status =
6269 				bf_get(lpfc_acqe_fc_la_link_status, acqe_fc);
6270 
6271 	/*
6272 	 * Only select attention types need logical speed modification to what
6273 	 * was previously set.
6274 	 */
6275 	if (phba->sli4_hba.link_state.status >= LPFC_FC_LA_TYPE_LINK_UP &&
6276 	    phba->sli4_hba.link_state.status < LPFC_FC_LA_TYPE_ACTIVATE_FAIL) {
6277 		if (bf_get(lpfc_acqe_fc_la_att_type, acqe_fc) ==
6278 		    LPFC_FC_LA_TYPE_LINK_DOWN)
6279 			phba->sli4_hba.link_state.logical_speed = 0;
6280 		else if (!phba->sli4_hba.conf_trunk)
6281 			phba->sli4_hba.link_state.logical_speed =
6282 				bf_get(lpfc_acqe_fc_la_llink_spd, acqe_fc) * 10;
6283 	}
6284 
6285 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6286 			"2896 Async FC event - Speed:%dGBaud Topology:x%x "
6287 			"LA Type:x%x Port Type:%d Port Number:%d Logical speed:"
6288 			"%dMbps Fault:x%x Link Status:x%x\n",
6289 			phba->sli4_hba.link_state.speed,
6290 			phba->sli4_hba.link_state.topology,
6291 			phba->sli4_hba.link_state.status,
6292 			phba->sli4_hba.link_state.type,
6293 			phba->sli4_hba.link_state.number,
6294 			phba->sli4_hba.link_state.logical_speed,
6295 			phba->sli4_hba.link_state.fault,
6296 			phba->sli4_hba.link_state.link_status);
6297 
6298 	/*
6299 	 * The following attention types are informational only, providing
6300 	 * further details about link status.  Overwrite the value of
6301 	 * link_state.status appropriately.  No further action is required.
6302 	 */
6303 	if (phba->sli4_hba.link_state.status >= LPFC_FC_LA_TYPE_ACTIVATE_FAIL) {
6304 		switch (phba->sli4_hba.link_state.status) {
6305 		case LPFC_FC_LA_TYPE_ACTIVATE_FAIL:
6306 			log_level = KERN_WARNING;
6307 			phba->sli4_hba.link_state.status =
6308 					LPFC_FC_LA_TYPE_LINK_DOWN;
6309 			break;
6310 		case LPFC_FC_LA_TYPE_LINK_RESET_PRTCL_EVT:
6311 			/*
6312 			 * During bb credit recovery establishment, receiving
6313 			 * this attention type is normal.  Link Up attention
6314 			 * type is expected to occur before this informational
6315 			 * attention type so keep the Link Up status.
6316 			 */
6317 			log_level = KERN_INFO;
6318 			phba->sli4_hba.link_state.status =
6319 					LPFC_FC_LA_TYPE_LINK_UP;
6320 			break;
6321 		default:
6322 			log_level = KERN_INFO;
6323 			break;
6324 		}
6325 		lpfc_log_msg(phba, log_level, LOG_SLI,
6326 			     "2992 Async FC event - Informational Link "
6327 			     "Attention Type x%x\n",
6328 			     bf_get(lpfc_acqe_fc_la_att_type, acqe_fc));
6329 		return;
6330 	}
6331 
6332 	pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6333 	if (!pmb) {
6334 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6335 				"2897 The mboxq allocation failed\n");
6336 		return;
6337 	}
6338 	rc = lpfc_mbox_rsrc_prep(phba, pmb);
6339 	if (rc) {
6340 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6341 				"2898 The mboxq prep failed\n");
6342 		goto out_free_pmb;
6343 	}
6344 
6345 	/* Cleanup any outstanding ELS commands */
6346 	lpfc_els_flush_all_cmd(phba);
6347 
6348 	/* Block ELS IOCBs until we have done process link event */
6349 	phba->sli4_hba.els_wq->pring->flag |= LPFC_STOP_IOCB_EVENT;
6350 
6351 	/* Update link event statistics */
6352 	phba->sli.slistat.link_event++;
6353 
6354 	/* Create lpfc_handle_latt mailbox command from link ACQE */
6355 	lpfc_read_topology(phba, pmb, pmb->ctx_buf);
6356 	pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
6357 	pmb->vport = phba->pport;
6358 
6359 	if (phba->sli4_hba.link_state.status != LPFC_FC_LA_TYPE_LINK_UP) {
6360 		phba->link_flag &= ~(LS_MDS_LINK_DOWN | LS_MDS_LOOPBACK);
6361 
6362 		switch (phba->sli4_hba.link_state.status) {
6363 		case LPFC_FC_LA_TYPE_MDS_LINK_DOWN:
6364 			phba->link_flag |= LS_MDS_LINK_DOWN;
6365 			break;
6366 		case LPFC_FC_LA_TYPE_MDS_LOOPBACK:
6367 			phba->link_flag |= LS_MDS_LOOPBACK;
6368 			break;
6369 		default:
6370 			break;
6371 		}
6372 
6373 		/* Initialize completion status */
6374 		mb = &pmb->u.mb;
6375 		mb->mbxStatus = MBX_SUCCESS;
6376 
6377 		/* Parse port fault information field */
6378 		lpfc_sli4_parse_latt_fault(phba, (void *)acqe_fc);
6379 
6380 		/* Parse and translate link attention fields */
6381 		la = (struct lpfc_mbx_read_top *)&pmb->u.mb.un.varReadTop;
6382 		la->eventTag = acqe_fc->event_tag;
6383 
6384 		if (phba->sli4_hba.link_state.status ==
6385 		    LPFC_FC_LA_TYPE_UNEXP_WWPN) {
6386 			bf_set(lpfc_mbx_read_top_att_type, la,
6387 			       LPFC_FC_LA_TYPE_UNEXP_WWPN);
6388 		} else {
6389 			bf_set(lpfc_mbx_read_top_att_type, la,
6390 			       LPFC_FC_LA_TYPE_LINK_DOWN);
6391 		}
6392 		/* Invoke the mailbox command callback function */
6393 		lpfc_mbx_cmpl_read_topology(phba, pmb);
6394 
6395 		return;
6396 	}
6397 
6398 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
6399 	if (rc == MBX_NOT_FINISHED)
6400 		goto out_free_pmb;
6401 	return;
6402 
6403 out_free_pmb:
6404 	lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
6405 }
6406 
6407 /**
6408  * lpfc_sli4_async_sli_evt - Process the asynchronous SLI link event
6409  * @phba: pointer to lpfc hba data structure.
6410  * @acqe_sli: pointer to the async SLI completion queue entry.
6411  *
6412  * This routine is to handle the SLI4 asynchronous SLI events.
6413  **/
6414 static void
6415 lpfc_sli4_async_sli_evt(struct lpfc_hba *phba, struct lpfc_acqe_sli *acqe_sli)
6416 {
6417 	char port_name;
6418 	char message[128];
6419 	uint8_t status;
6420 	uint8_t evt_type;
6421 	uint8_t operational = 0;
6422 	struct temp_event temp_event_data;
6423 	struct lpfc_acqe_misconfigured_event *misconfigured;
6424 	struct lpfc_acqe_cgn_signal *cgn_signal;
6425 	struct Scsi_Host  *shost;
6426 	struct lpfc_vport **vports;
6427 	int rc, i, cnt;
6428 
6429 	evt_type = bf_get(lpfc_trailer_type, acqe_sli);
6430 
6431 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6432 			"2901 Async SLI event - Type:%d, Event Data: x%08x "
6433 			"x%08x x%08x x%08x\n", evt_type,
6434 			acqe_sli->event_data1, acqe_sli->event_data2,
6435 			acqe_sli->event_data3, acqe_sli->trailer);
6436 
6437 	port_name = phba->Port[0];
6438 	if (port_name == 0x00)
6439 		port_name = '?'; /* get port name is empty */
6440 
6441 	switch (evt_type) {
6442 	case LPFC_SLI_EVENT_TYPE_OVER_TEMP:
6443 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
6444 		temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
6445 		temp_event_data.data = (uint32_t)acqe_sli->event_data1;
6446 
6447 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6448 				"3190 Over Temperature:%d Celsius- Port Name %c\n",
6449 				acqe_sli->event_data1, port_name);
6450 
6451 		phba->sfp_warning |= LPFC_TRANSGRESSION_HIGH_TEMPERATURE;
6452 		shost = lpfc_shost_from_vport(phba->pport);
6453 		fc_host_post_vendor_event(shost, fc_get_event_number(),
6454 					  sizeof(temp_event_data),
6455 					  (char *)&temp_event_data,
6456 					  SCSI_NL_VID_TYPE_PCI
6457 					  | PCI_VENDOR_ID_EMULEX);
6458 		break;
6459 	case LPFC_SLI_EVENT_TYPE_NORM_TEMP:
6460 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
6461 		temp_event_data.event_code = LPFC_NORMAL_TEMP;
6462 		temp_event_data.data = (uint32_t)acqe_sli->event_data1;
6463 
6464 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI | LOG_LDS_EVENT,
6465 				"3191 Normal Temperature:%d Celsius - Port Name %c\n",
6466 				acqe_sli->event_data1, port_name);
6467 
6468 		shost = lpfc_shost_from_vport(phba->pport);
6469 		fc_host_post_vendor_event(shost, fc_get_event_number(),
6470 					  sizeof(temp_event_data),
6471 					  (char *)&temp_event_data,
6472 					  SCSI_NL_VID_TYPE_PCI
6473 					  | PCI_VENDOR_ID_EMULEX);
6474 		break;
6475 	case LPFC_SLI_EVENT_TYPE_MISCONFIGURED:
6476 		misconfigured = (struct lpfc_acqe_misconfigured_event *)
6477 					&acqe_sli->event_data1;
6478 
6479 		/* fetch the status for this port */
6480 		switch (phba->sli4_hba.lnk_info.lnk_no) {
6481 		case LPFC_LINK_NUMBER_0:
6482 			status = bf_get(lpfc_sli_misconfigured_port0_state,
6483 					&misconfigured->theEvent);
6484 			operational = bf_get(lpfc_sli_misconfigured_port0_op,
6485 					&misconfigured->theEvent);
6486 			break;
6487 		case LPFC_LINK_NUMBER_1:
6488 			status = bf_get(lpfc_sli_misconfigured_port1_state,
6489 					&misconfigured->theEvent);
6490 			operational = bf_get(lpfc_sli_misconfigured_port1_op,
6491 					&misconfigured->theEvent);
6492 			break;
6493 		case LPFC_LINK_NUMBER_2:
6494 			status = bf_get(lpfc_sli_misconfigured_port2_state,
6495 					&misconfigured->theEvent);
6496 			operational = bf_get(lpfc_sli_misconfigured_port2_op,
6497 					&misconfigured->theEvent);
6498 			break;
6499 		case LPFC_LINK_NUMBER_3:
6500 			status = bf_get(lpfc_sli_misconfigured_port3_state,
6501 					&misconfigured->theEvent);
6502 			operational = bf_get(lpfc_sli_misconfigured_port3_op,
6503 					&misconfigured->theEvent);
6504 			break;
6505 		default:
6506 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6507 					"3296 "
6508 					"LPFC_SLI_EVENT_TYPE_MISCONFIGURED "
6509 					"event: Invalid link %d",
6510 					phba->sli4_hba.lnk_info.lnk_no);
6511 			return;
6512 		}
6513 
6514 		/* Skip if optic state unchanged */
6515 		if (phba->sli4_hba.lnk_info.optic_state == status)
6516 			return;
6517 
6518 		switch (status) {
6519 		case LPFC_SLI_EVENT_STATUS_VALID:
6520 			sprintf(message, "Physical Link is functional");
6521 			break;
6522 		case LPFC_SLI_EVENT_STATUS_NOT_PRESENT:
6523 			sprintf(message, "Optics faulted/incorrectly "
6524 				"installed/not installed - Reseat optics, "
6525 				"if issue not resolved, replace.");
6526 			break;
6527 		case LPFC_SLI_EVENT_STATUS_WRONG_TYPE:
6528 			sprintf(message,
6529 				"Optics of two types installed - Remove one "
6530 				"optic or install matching pair of optics.");
6531 			break;
6532 		case LPFC_SLI_EVENT_STATUS_UNSUPPORTED:
6533 			sprintf(message, "Incompatible optics - Replace with "
6534 				"compatible optics for card to function.");
6535 			break;
6536 		case LPFC_SLI_EVENT_STATUS_UNQUALIFIED:
6537 			sprintf(message, "Unqualified optics - Replace with "
6538 				"Avago optics for Warranty and Technical "
6539 				"Support - Link is%s operational",
6540 				(operational) ? " not" : "");
6541 			break;
6542 		case LPFC_SLI_EVENT_STATUS_UNCERTIFIED:
6543 			sprintf(message, "Uncertified optics - Replace with "
6544 				"Avago-certified optics to enable link "
6545 				"operation - Link is%s operational",
6546 				(operational) ? " not" : "");
6547 			break;
6548 		default:
6549 			/* firmware is reporting a status we don't know about */
6550 			sprintf(message, "Unknown event status x%02x", status);
6551 			break;
6552 		}
6553 
6554 		/* Issue READ_CONFIG mbox command to refresh supported speeds */
6555 		rc = lpfc_sli4_read_config(phba);
6556 		if (rc) {
6557 			phba->lmt = 0;
6558 			lpfc_printf_log(phba, KERN_ERR,
6559 					LOG_TRACE_EVENT,
6560 					"3194 Unable to retrieve supported "
6561 					"speeds, rc = 0x%x\n", rc);
6562 		}
6563 		rc = lpfc_sli4_refresh_params(phba);
6564 		if (rc) {
6565 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6566 					"3174 Unable to update pls support, "
6567 					"rc x%x\n", rc);
6568 		}
6569 		vports = lpfc_create_vport_work_array(phba);
6570 		if (vports != NULL) {
6571 			for (i = 0; i <= phba->max_vports && vports[i] != NULL;
6572 					i++) {
6573 				shost = lpfc_shost_from_vport(vports[i]);
6574 				lpfc_host_supported_speeds_set(shost);
6575 			}
6576 		}
6577 		lpfc_destroy_vport_work_array(phba, vports);
6578 
6579 		phba->sli4_hba.lnk_info.optic_state = status;
6580 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6581 				"3176 Port Name %c %s\n", port_name, message);
6582 		break;
6583 	case LPFC_SLI_EVENT_TYPE_REMOTE_DPORT:
6584 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6585 				"3192 Remote DPort Test Initiated - "
6586 				"Event Data1:x%08x Event Data2: x%08x\n",
6587 				acqe_sli->event_data1, acqe_sli->event_data2);
6588 		break;
6589 	case LPFC_SLI_EVENT_TYPE_PORT_PARAMS_CHG:
6590 		/* Call FW to obtain active parms */
6591 		lpfc_sli4_cgn_parm_chg_evt(phba);
6592 		break;
6593 	case LPFC_SLI_EVENT_TYPE_MISCONF_FAWWN:
6594 		/* Misconfigured WWN. Reports that the SLI Port is configured
6595 		 * to use FA-WWN, but the attached device doesn’t support it.
6596 		 * Event Data1 - N.A, Event Data2 - N.A
6597 		 * This event only happens on the physical port.
6598 		 */
6599 		lpfc_log_msg(phba, KERN_WARNING, LOG_SLI | LOG_DISCOVERY,
6600 			     "2699 Misconfigured FA-PWWN - Attached device "
6601 			     "does not support FA-PWWN\n");
6602 		phba->sli4_hba.fawwpn_flag &= ~LPFC_FAWWPN_FABRIC;
6603 		memset(phba->pport->fc_portname.u.wwn, 0,
6604 		       sizeof(struct lpfc_name));
6605 		break;
6606 	case LPFC_SLI_EVENT_TYPE_EEPROM_FAILURE:
6607 		/* EEPROM failure. No driver action is required */
6608 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6609 			     "2518 EEPROM failure - "
6610 			     "Event Data1: x%08x Event Data2: x%08x\n",
6611 			     acqe_sli->event_data1, acqe_sli->event_data2);
6612 		break;
6613 	case LPFC_SLI_EVENT_TYPE_CGN_SIGNAL:
6614 		if (phba->cmf_active_mode == LPFC_CFG_OFF)
6615 			break;
6616 		cgn_signal = (struct lpfc_acqe_cgn_signal *)
6617 					&acqe_sli->event_data1;
6618 		phba->cgn_acqe_cnt++;
6619 
6620 		cnt = bf_get(lpfc_warn_acqe, cgn_signal);
6621 		atomic64_add(cnt, &phba->cgn_acqe_stat.warn);
6622 		atomic64_add(cgn_signal->alarm_cnt, &phba->cgn_acqe_stat.alarm);
6623 
6624 		/* no threshold for CMF, even 1 signal will trigger an event */
6625 
6626 		/* Alarm overrides warning, so check that first */
6627 		if (cgn_signal->alarm_cnt) {
6628 			if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
6629 				/* Keep track of alarm cnt for CMF_SYNC_WQE */
6630 				atomic_add(cgn_signal->alarm_cnt,
6631 					   &phba->cgn_sync_alarm_cnt);
6632 			}
6633 		} else if (cnt) {
6634 			/* signal action needs to be taken */
6635 			if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY ||
6636 			    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
6637 				/* Keep track of warning cnt for CMF_SYNC_WQE */
6638 				atomic_add(cnt, &phba->cgn_sync_warn_cnt);
6639 			}
6640 		}
6641 		break;
6642 	case LPFC_SLI_EVENT_TYPE_RD_SIGNAL:
6643 		/* May be accompanied by a temperature event */
6644 		lpfc_printf_log(phba, KERN_INFO,
6645 				LOG_SLI | LOG_LINK_EVENT | LOG_LDS_EVENT,
6646 				"2902 Remote Degrade Signaling: x%08x x%08x "
6647 				"x%08x\n",
6648 				acqe_sli->event_data1, acqe_sli->event_data2,
6649 				acqe_sli->event_data3);
6650 		break;
6651 	case LPFC_SLI_EVENT_TYPE_RESET_CM_STATS:
6652 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
6653 				"2905 Reset CM statistics\n");
6654 		lpfc_sli4_async_cmstat_evt(phba);
6655 		break;
6656 	default:
6657 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6658 				"3193 Unrecognized SLI event, type: 0x%x",
6659 				evt_type);
6660 		break;
6661 	}
6662 }
6663 
6664 /**
6665  * lpfc_sli4_perform_vport_cvl - Perform clear virtual link on a vport
6666  * @vport: pointer to vport data structure.
6667  *
6668  * This routine is to perform Clear Virtual Link (CVL) on a vport in
6669  * response to a CVL event.
6670  *
6671  * Return the pointer to the ndlp with the vport if successful, otherwise
6672  * return NULL.
6673  **/
6674 static struct lpfc_nodelist *
6675 lpfc_sli4_perform_vport_cvl(struct lpfc_vport *vport)
6676 {
6677 	struct lpfc_nodelist *ndlp;
6678 	struct Scsi_Host *shost;
6679 	struct lpfc_hba *phba;
6680 
6681 	if (!vport)
6682 		return NULL;
6683 	phba = vport->phba;
6684 	if (!phba)
6685 		return NULL;
6686 	ndlp = lpfc_findnode_did(vport, Fabric_DID);
6687 	if (!ndlp) {
6688 		/* Cannot find existing Fabric ndlp, so allocate a new one */
6689 		ndlp = lpfc_nlp_init(vport, Fabric_DID);
6690 		if (!ndlp)
6691 			return NULL;
6692 		/* Set the node type */
6693 		ndlp->nlp_type |= NLP_FABRIC;
6694 		/* Put ndlp onto node list */
6695 		lpfc_enqueue_node(vport, ndlp);
6696 	}
6697 	if ((phba->pport->port_state < LPFC_FLOGI) &&
6698 		(phba->pport->port_state != LPFC_VPORT_FAILED))
6699 		return NULL;
6700 	/* If virtual link is not yet instantiated ignore CVL */
6701 	if ((vport != phba->pport) && (vport->port_state < LPFC_FDISC)
6702 		&& (vport->port_state != LPFC_VPORT_FAILED))
6703 		return NULL;
6704 	shost = lpfc_shost_from_vport(vport);
6705 	if (!shost)
6706 		return NULL;
6707 	lpfc_linkdown_port(vport);
6708 	lpfc_cleanup_pending_mbox(vport);
6709 	set_bit(FC_VPORT_CVL_RCVD, &vport->fc_flag);
6710 
6711 	return ndlp;
6712 }
6713 
6714 /**
6715  * lpfc_sli4_perform_all_vport_cvl - Perform clear virtual link on all vports
6716  * @phba: pointer to lpfc hba data structure.
6717  *
6718  * This routine is to perform Clear Virtual Link (CVL) on all vports in
6719  * response to a FCF dead event.
6720  **/
6721 static void
6722 lpfc_sli4_perform_all_vport_cvl(struct lpfc_hba *phba)
6723 {
6724 	struct lpfc_vport **vports;
6725 	int i;
6726 
6727 	vports = lpfc_create_vport_work_array(phba);
6728 	if (vports)
6729 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++)
6730 			lpfc_sli4_perform_vport_cvl(vports[i]);
6731 	lpfc_destroy_vport_work_array(phba, vports);
6732 }
6733 
6734 /**
6735  * lpfc_sli4_async_fip_evt - Process the asynchronous FCoE FIP event
6736  * @phba: pointer to lpfc hba data structure.
6737  * @acqe_fip: pointer to the async fcoe completion queue entry.
6738  *
6739  * This routine is to handle the SLI4 asynchronous fcoe event.
6740  **/
6741 static void
6742 lpfc_sli4_async_fip_evt(struct lpfc_hba *phba,
6743 			struct lpfc_acqe_fip *acqe_fip)
6744 {
6745 	uint8_t event_type = bf_get(lpfc_trailer_type, acqe_fip);
6746 	int rc;
6747 	struct lpfc_vport *vport;
6748 	struct lpfc_nodelist *ndlp;
6749 	int active_vlink_present;
6750 	struct lpfc_vport **vports;
6751 	int i;
6752 
6753 	phba->fc_eventTag = acqe_fip->event_tag;
6754 	phba->fcoe_eventtag = acqe_fip->event_tag;
6755 	switch (event_type) {
6756 	case LPFC_FIP_EVENT_TYPE_NEW_FCF:
6757 	case LPFC_FIP_EVENT_TYPE_FCF_PARAM_MOD:
6758 		if (event_type == LPFC_FIP_EVENT_TYPE_NEW_FCF)
6759 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6760 					"2546 New FCF event, evt_tag:x%x, "
6761 					"index:x%x\n",
6762 					acqe_fip->event_tag,
6763 					acqe_fip->index);
6764 		else
6765 			lpfc_printf_log(phba, KERN_WARNING, LOG_FIP |
6766 					LOG_DISCOVERY,
6767 					"2788 FCF param modified event, "
6768 					"evt_tag:x%x, index:x%x\n",
6769 					acqe_fip->event_tag,
6770 					acqe_fip->index);
6771 		if (phba->fcf.fcf_flag & FCF_DISCOVERY) {
6772 			/*
6773 			 * During period of FCF discovery, read the FCF
6774 			 * table record indexed by the event to update
6775 			 * FCF roundrobin failover eligible FCF bmask.
6776 			 */
6777 			lpfc_printf_log(phba, KERN_INFO, LOG_FIP |
6778 					LOG_DISCOVERY,
6779 					"2779 Read FCF (x%x) for updating "
6780 					"roundrobin FCF failover bmask\n",
6781 					acqe_fip->index);
6782 			rc = lpfc_sli4_read_fcf_rec(phba, acqe_fip->index);
6783 		}
6784 
6785 		/* If the FCF discovery is in progress, do nothing. */
6786 		if (test_bit(FCF_TS_INPROG, &phba->hba_flag))
6787 			break;
6788 		spin_lock_irq(&phba->hbalock);
6789 		/* If fast FCF failover rescan event is pending, do nothing */
6790 		if (phba->fcf.fcf_flag & (FCF_REDISC_EVT | FCF_REDISC_PEND)) {
6791 			spin_unlock_irq(&phba->hbalock);
6792 			break;
6793 		}
6794 
6795 		/* If the FCF has been in discovered state, do nothing. */
6796 		if (phba->fcf.fcf_flag & FCF_SCAN_DONE) {
6797 			spin_unlock_irq(&phba->hbalock);
6798 			break;
6799 		}
6800 		spin_unlock_irq(&phba->hbalock);
6801 
6802 		/* Otherwise, scan the entire FCF table and re-discover SAN */
6803 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
6804 				"2770 Start FCF table scan per async FCF "
6805 				"event, evt_tag:x%x, index:x%x\n",
6806 				acqe_fip->event_tag, acqe_fip->index);
6807 		rc = lpfc_sli4_fcf_scan_read_fcf_rec(phba,
6808 						     LPFC_FCOE_FCF_GET_FIRST);
6809 		if (rc)
6810 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6811 					"2547 Issue FCF scan read FCF mailbox "
6812 					"command failed (x%x)\n", rc);
6813 		break;
6814 
6815 	case LPFC_FIP_EVENT_TYPE_FCF_TABLE_FULL:
6816 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6817 				"2548 FCF Table full count 0x%x tag 0x%x\n",
6818 				bf_get(lpfc_acqe_fip_fcf_count, acqe_fip),
6819 				acqe_fip->event_tag);
6820 		break;
6821 
6822 	case LPFC_FIP_EVENT_TYPE_FCF_DEAD:
6823 		phba->fcoe_cvl_eventtag = acqe_fip->event_tag;
6824 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6825 				"2549 FCF (x%x) disconnected from network, "
6826 				 "tag:x%x\n", acqe_fip->index,
6827 				 acqe_fip->event_tag);
6828 		/*
6829 		 * If we are in the middle of FCF failover process, clear
6830 		 * the corresponding FCF bit in the roundrobin bitmap.
6831 		 */
6832 		spin_lock_irq(&phba->hbalock);
6833 		if ((phba->fcf.fcf_flag & FCF_DISCOVERY) &&
6834 		    (phba->fcf.current_rec.fcf_indx != acqe_fip->index)) {
6835 			spin_unlock_irq(&phba->hbalock);
6836 			/* Update FLOGI FCF failover eligible FCF bmask */
6837 			lpfc_sli4_fcf_rr_index_clear(phba, acqe_fip->index);
6838 			break;
6839 		}
6840 		spin_unlock_irq(&phba->hbalock);
6841 
6842 		/* If the event is not for currently used fcf do nothing */
6843 		if (phba->fcf.current_rec.fcf_indx != acqe_fip->index)
6844 			break;
6845 
6846 		/*
6847 		 * Otherwise, request the port to rediscover the entire FCF
6848 		 * table for a fast recovery from case that the current FCF
6849 		 * is no longer valid as we are not in the middle of FCF
6850 		 * failover process already.
6851 		 */
6852 		spin_lock_irq(&phba->hbalock);
6853 		/* Mark the fast failover process in progress */
6854 		phba->fcf.fcf_flag |= FCF_DEAD_DISC;
6855 		spin_unlock_irq(&phba->hbalock);
6856 
6857 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
6858 				"2771 Start FCF fast failover process due to "
6859 				"FCF DEAD event: evt_tag:x%x, fcf_index:x%x "
6860 				"\n", acqe_fip->event_tag, acqe_fip->index);
6861 		rc = lpfc_sli4_redisc_fcf_table(phba);
6862 		if (rc) {
6863 			lpfc_printf_log(phba, KERN_ERR, LOG_FIP |
6864 					LOG_TRACE_EVENT,
6865 					"2772 Issue FCF rediscover mailbox "
6866 					"command failed, fail through to FCF "
6867 					"dead event\n");
6868 			spin_lock_irq(&phba->hbalock);
6869 			phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
6870 			spin_unlock_irq(&phba->hbalock);
6871 			/*
6872 			 * Last resort will fail over by treating this
6873 			 * as a link down to FCF registration.
6874 			 */
6875 			lpfc_sli4_fcf_dead_failthrough(phba);
6876 		} else {
6877 			/* Reset FCF roundrobin bmask for new discovery */
6878 			lpfc_sli4_clear_fcf_rr_bmask(phba);
6879 			/*
6880 			 * Handling fast FCF failover to a DEAD FCF event is
6881 			 * considered equalivant to receiving CVL to all vports.
6882 			 */
6883 			lpfc_sli4_perform_all_vport_cvl(phba);
6884 		}
6885 		break;
6886 	case LPFC_FIP_EVENT_TYPE_CVL:
6887 		phba->fcoe_cvl_eventtag = acqe_fip->event_tag;
6888 		lpfc_printf_log(phba, KERN_ERR,
6889 				LOG_TRACE_EVENT,
6890 			"2718 Clear Virtual Link Received for VPI 0x%x"
6891 			" tag 0x%x\n", acqe_fip->index, acqe_fip->event_tag);
6892 
6893 		vport = lpfc_find_vport_by_vpid(phba,
6894 						acqe_fip->index);
6895 		ndlp = lpfc_sli4_perform_vport_cvl(vport);
6896 		if (!ndlp)
6897 			break;
6898 		active_vlink_present = 0;
6899 
6900 		vports = lpfc_create_vport_work_array(phba);
6901 		if (vports) {
6902 			for (i = 0; i <= phba->max_vports && vports[i] != NULL;
6903 					i++) {
6904 				if (!test_bit(FC_VPORT_CVL_RCVD,
6905 					      &vports[i]->fc_flag) &&
6906 				    vports[i]->port_state > LPFC_FDISC) {
6907 					active_vlink_present = 1;
6908 					break;
6909 				}
6910 			}
6911 			lpfc_destroy_vport_work_array(phba, vports);
6912 		}
6913 
6914 		/*
6915 		 * Don't re-instantiate if vport is marked for deletion.
6916 		 * If we are here first then vport_delete is going to wait
6917 		 * for discovery to complete.
6918 		 */
6919 		if (!test_bit(FC_UNLOADING, &vport->load_flag) &&
6920 		    active_vlink_present) {
6921 			/*
6922 			 * If there are other active VLinks present,
6923 			 * re-instantiate the Vlink using FDISC.
6924 			 */
6925 			mod_timer(&ndlp->nlp_delayfunc,
6926 				  jiffies + secs_to_jiffies(1));
6927 			set_bit(NLP_DELAY_TMO, &ndlp->nlp_flag);
6928 			ndlp->nlp_last_elscmd = ELS_CMD_FDISC;
6929 			vport->port_state = LPFC_FDISC;
6930 		} else {
6931 			/*
6932 			 * Otherwise, we request port to rediscover
6933 			 * the entire FCF table for a fast recovery
6934 			 * from possible case that the current FCF
6935 			 * is no longer valid if we are not already
6936 			 * in the FCF failover process.
6937 			 */
6938 			spin_lock_irq(&phba->hbalock);
6939 			if (phba->fcf.fcf_flag & FCF_DISCOVERY) {
6940 				spin_unlock_irq(&phba->hbalock);
6941 				break;
6942 			}
6943 			/* Mark the fast failover process in progress */
6944 			phba->fcf.fcf_flag |= FCF_ACVL_DISC;
6945 			spin_unlock_irq(&phba->hbalock);
6946 			lpfc_printf_log(phba, KERN_INFO, LOG_FIP |
6947 					LOG_DISCOVERY,
6948 					"2773 Start FCF failover per CVL, "
6949 					"evt_tag:x%x\n", acqe_fip->event_tag);
6950 			rc = lpfc_sli4_redisc_fcf_table(phba);
6951 			if (rc) {
6952 				lpfc_printf_log(phba, KERN_ERR, LOG_FIP |
6953 						LOG_TRACE_EVENT,
6954 						"2774 Issue FCF rediscover "
6955 						"mailbox command failed, "
6956 						"through to CVL event\n");
6957 				spin_lock_irq(&phba->hbalock);
6958 				phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
6959 				spin_unlock_irq(&phba->hbalock);
6960 				/*
6961 				 * Last resort will be re-try on the
6962 				 * the current registered FCF entry.
6963 				 */
6964 				lpfc_retry_pport_discovery(phba);
6965 			} else
6966 				/*
6967 				 * Reset FCF roundrobin bmask for new
6968 				 * discovery.
6969 				 */
6970 				lpfc_sli4_clear_fcf_rr_bmask(phba);
6971 		}
6972 		break;
6973 	default:
6974 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6975 				"0288 Unknown FCoE event type 0x%x event tag "
6976 				"0x%x\n", event_type, acqe_fip->event_tag);
6977 		break;
6978 	}
6979 }
6980 
6981 /**
6982  * lpfc_sli4_async_dcbx_evt - Process the asynchronous dcbx event
6983  * @phba: pointer to lpfc hba data structure.
6984  * @acqe_dcbx: pointer to the async dcbx completion queue entry.
6985  *
6986  * This routine is to handle the SLI4 asynchronous dcbx event.
6987  **/
6988 static void
6989 lpfc_sli4_async_dcbx_evt(struct lpfc_hba *phba,
6990 			 struct lpfc_acqe_dcbx *acqe_dcbx)
6991 {
6992 	phba->fc_eventTag = acqe_dcbx->event_tag;
6993 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6994 			"0290 The SLI4 DCBX asynchronous event is not "
6995 			"handled yet\n");
6996 }
6997 
6998 /**
6999  * lpfc_sli4_async_grp5_evt - Process the asynchronous group5 event
7000  * @phba: pointer to lpfc hba data structure.
7001  * @acqe_grp5: pointer to the async grp5 completion queue entry.
7002  *
7003  * This routine is to handle the SLI4 asynchronous grp5 event. A grp5 event
7004  * is an asynchronous notified of a logical link speed change.  The Port
7005  * reports the logical link speed in units of 10Mbps.
7006  **/
7007 static void
7008 lpfc_sli4_async_grp5_evt(struct lpfc_hba *phba,
7009 			 struct lpfc_acqe_grp5 *acqe_grp5)
7010 {
7011 	uint16_t prev_ll_spd;
7012 
7013 	phba->fc_eventTag = acqe_grp5->event_tag;
7014 	phba->fcoe_eventtag = acqe_grp5->event_tag;
7015 	prev_ll_spd = phba->sli4_hba.link_state.logical_speed;
7016 	phba->sli4_hba.link_state.logical_speed =
7017 		(bf_get(lpfc_acqe_grp5_llink_spd, acqe_grp5)) * 10;
7018 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
7019 			"2789 GRP5 Async Event: Updating logical link speed "
7020 			"from %dMbps to %dMbps\n", prev_ll_spd,
7021 			phba->sli4_hba.link_state.logical_speed);
7022 }
7023 
7024 /**
7025  * lpfc_sli4_async_cmstat_evt - Process the asynchronous cmstat event
7026  * @phba: pointer to lpfc hba data structure.
7027  *
7028  * This routine is to handle the SLI4 asynchronous cmstat event. A cmstat event
7029  * is an asynchronous notification of a request to reset CM stats.
7030  **/
7031 static void
7032 lpfc_sli4_async_cmstat_evt(struct lpfc_hba *phba)
7033 {
7034 	if (!phba->cgn_i)
7035 		return;
7036 	lpfc_init_congestion_stat(phba);
7037 }
7038 
7039 /**
7040  * lpfc_cgn_params_val - Validate FW congestion parameters.
7041  * @phba: pointer to lpfc hba data structure.
7042  * @p_cfg_param: pointer to FW provided congestion parameters.
7043  *
7044  * This routine validates the congestion parameters passed
7045  * by the FW to the driver via an ACQE event.
7046  **/
7047 static void
7048 lpfc_cgn_params_val(struct lpfc_hba *phba, struct lpfc_cgn_param *p_cfg_param)
7049 {
7050 	spin_lock_irq(&phba->hbalock);
7051 
7052 	if (!lpfc_rangecheck(p_cfg_param->cgn_param_mode, LPFC_CFG_OFF,
7053 			     LPFC_CFG_MONITOR)) {
7054 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT,
7055 				"6225 CMF mode param out of range: %d\n",
7056 				 p_cfg_param->cgn_param_mode);
7057 		p_cfg_param->cgn_param_mode = LPFC_CFG_OFF;
7058 	}
7059 
7060 	spin_unlock_irq(&phba->hbalock);
7061 }
7062 
7063 static const char * const lpfc_cmf_mode_to_str[] = {
7064 	"OFF",
7065 	"MANAGED",
7066 	"MONITOR",
7067 };
7068 
7069 /**
7070  * lpfc_cgn_params_parse - Process a FW cong parm change event
7071  * @phba: pointer to lpfc hba data structure.
7072  * @p_cgn_param: pointer to a data buffer with the FW cong params.
7073  * @len: the size of pdata in bytes.
7074  *
7075  * This routine validates the congestion management buffer signature
7076  * from the FW, validates the contents and makes corrections for
7077  * valid, in-range values.  If the signature magic is correct and
7078  * after parameter validation, the contents are copied to the driver's
7079  * @phba structure. If the magic is incorrect, an error message is
7080  * logged.
7081  **/
7082 static void
7083 lpfc_cgn_params_parse(struct lpfc_hba *phba,
7084 		      struct lpfc_cgn_param *p_cgn_param, uint32_t len)
7085 {
7086 	struct lpfc_cgn_info *cp;
7087 	uint32_t crc, oldmode;
7088 	char acr_string[4] = {0};
7089 
7090 	/* Make sure the FW has encoded the correct magic number to
7091 	 * validate the congestion parameter in FW memory.
7092 	 */
7093 	if (p_cgn_param->cgn_param_magic == LPFC_CFG_PARAM_MAGIC_NUM) {
7094 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT | LOG_INIT,
7095 				"4668 FW cgn parm buffer data: "
7096 				"magic 0x%x version %d mode %d "
7097 				"level0 %d level1 %d "
7098 				"level2 %d byte13 %d "
7099 				"byte14 %d byte15 %d "
7100 				"byte11 %d byte12 %d activeMode %d\n",
7101 				p_cgn_param->cgn_param_magic,
7102 				p_cgn_param->cgn_param_version,
7103 				p_cgn_param->cgn_param_mode,
7104 				p_cgn_param->cgn_param_level0,
7105 				p_cgn_param->cgn_param_level1,
7106 				p_cgn_param->cgn_param_level2,
7107 				p_cgn_param->byte13,
7108 				p_cgn_param->byte14,
7109 				p_cgn_param->byte15,
7110 				p_cgn_param->byte11,
7111 				p_cgn_param->byte12,
7112 				phba->cmf_active_mode);
7113 
7114 		oldmode = phba->cmf_active_mode;
7115 
7116 		/* Any parameters out of range are corrected to defaults
7117 		 * by this routine.  No need to fail.
7118 		 */
7119 		lpfc_cgn_params_val(phba, p_cgn_param);
7120 
7121 		/* Parameters are verified, move them into driver storage */
7122 		spin_lock_irq(&phba->hbalock);
7123 		memcpy(&phba->cgn_p, p_cgn_param,
7124 		       sizeof(struct lpfc_cgn_param));
7125 
7126 		/* Update parameters in congestion info buffer now */
7127 		if (phba->cgn_i) {
7128 			cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
7129 			cp->cgn_info_mode = phba->cgn_p.cgn_param_mode;
7130 			cp->cgn_info_level0 = phba->cgn_p.cgn_param_level0;
7131 			cp->cgn_info_level1 = phba->cgn_p.cgn_param_level1;
7132 			cp->cgn_info_level2 = phba->cgn_p.cgn_param_level2;
7133 			crc = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ,
7134 						  LPFC_CGN_CRC32_SEED);
7135 			cp->cgn_info_crc = cpu_to_le32(crc);
7136 		}
7137 		spin_unlock_irq(&phba->hbalock);
7138 
7139 		phba->cmf_active_mode = phba->cgn_p.cgn_param_mode;
7140 
7141 		switch (oldmode) {
7142 		case LPFC_CFG_OFF:
7143 			if (phba->cgn_p.cgn_param_mode != LPFC_CFG_OFF) {
7144 				/* Turning CMF on */
7145 				lpfc_cmf_start(phba);
7146 
7147 				if (phba->link_state >= LPFC_LINK_UP) {
7148 					phba->cgn_reg_fpin =
7149 						phba->cgn_init_reg_fpin;
7150 					phba->cgn_reg_signal =
7151 						phba->cgn_init_reg_signal;
7152 					lpfc_issue_els_edc(phba->pport, 0);
7153 				}
7154 			}
7155 			break;
7156 		case LPFC_CFG_MANAGED:
7157 			switch (phba->cgn_p.cgn_param_mode) {
7158 			case LPFC_CFG_OFF:
7159 				/* Turning CMF off */
7160 				lpfc_cmf_stop(phba);
7161 				if (phba->link_state >= LPFC_LINK_UP)
7162 					lpfc_issue_els_edc(phba->pport, 0);
7163 				break;
7164 			case LPFC_CFG_MONITOR:
7165 				phba->cmf_max_bytes_per_interval =
7166 					phba->cmf_link_byte_count;
7167 
7168 				/* Resume blocked IO - unblock on workqueue */
7169 				queue_work(phba->wq,
7170 					   &phba->unblock_request_work);
7171 				break;
7172 			}
7173 			break;
7174 		case LPFC_CFG_MONITOR:
7175 			switch (phba->cgn_p.cgn_param_mode) {
7176 			case LPFC_CFG_OFF:
7177 				/* Turning CMF off */
7178 				lpfc_cmf_stop(phba);
7179 				if (phba->link_state >= LPFC_LINK_UP)
7180 					lpfc_issue_els_edc(phba->pport, 0);
7181 				break;
7182 			case LPFC_CFG_MANAGED:
7183 				lpfc_cmf_signal_init(phba);
7184 				break;
7185 			}
7186 			break;
7187 		}
7188 		if (oldmode != LPFC_CFG_OFF ||
7189 		    oldmode != phba->cgn_p.cgn_param_mode) {
7190 			if (phba->cgn_p.cgn_param_mode == LPFC_CFG_MANAGED)
7191 				scnprintf(acr_string, sizeof(acr_string), "%u",
7192 					  phba->cgn_p.cgn_param_level0);
7193 			else
7194 				scnprintf(acr_string, sizeof(acr_string), "NA");
7195 
7196 			dev_info(&phba->pcidev->dev, "%d: "
7197 				 "4663 CMF: Mode %s acr %s\n",
7198 				 phba->brd_no,
7199 				 lpfc_cmf_mode_to_str
7200 				 [phba->cgn_p.cgn_param_mode],
7201 				 acr_string);
7202 		}
7203 	} else {
7204 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7205 				"4669 FW cgn parm buf wrong magic 0x%x "
7206 				"version %d\n", p_cgn_param->cgn_param_magic,
7207 				p_cgn_param->cgn_param_version);
7208 	}
7209 }
7210 
7211 /**
7212  * lpfc_sli4_cgn_params_read - Read and Validate FW congestion parameters.
7213  * @phba: pointer to lpfc hba data structure.
7214  *
7215  * This routine issues a read_object mailbox command to
7216  * get the congestion management parameters from the FW
7217  * parses it and updates the driver maintained values.
7218  *
7219  * Returns
7220  *  0     if the object was empty
7221  *  -Eval if an error was encountered
7222  *  Count if bytes were read from object
7223  **/
7224 int
7225 lpfc_sli4_cgn_params_read(struct lpfc_hba *phba)
7226 {
7227 	int ret = 0;
7228 	struct lpfc_cgn_param *p_cgn_param = NULL;
7229 	u32 *pdata = NULL;
7230 	u32 len = 0;
7231 
7232 	/* Find out if the FW has a new set of congestion parameters. */
7233 	len = sizeof(struct lpfc_cgn_param);
7234 	pdata = kzalloc(len, GFP_KERNEL);
7235 	if (!pdata)
7236 		return -ENOMEM;
7237 	ret = lpfc_read_object(phba, (char *)LPFC_PORT_CFG_NAME,
7238 			       pdata, len);
7239 
7240 	/* 0 means no data.  A negative means error.  A positive means
7241 	 * bytes were copied.
7242 	 */
7243 	if (!ret) {
7244 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7245 				"4670 CGN RD OBJ returns no data\n");
7246 		goto rd_obj_err;
7247 	} else if (ret < 0) {
7248 		/* Some error.  Just exit and return it to the caller.*/
7249 		goto rd_obj_err;
7250 	}
7251 
7252 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT | LOG_INIT,
7253 			"6234 READ CGN PARAMS Successful %d\n", len);
7254 
7255 	/* Parse data pointer over len and update the phba congestion
7256 	 * parameters with values passed back.  The receive rate values
7257 	 * may have been altered in FW, but take no action here.
7258 	 */
7259 	p_cgn_param = (struct lpfc_cgn_param *)pdata;
7260 	lpfc_cgn_params_parse(phba, p_cgn_param, len);
7261 
7262  rd_obj_err:
7263 	kfree(pdata);
7264 	return ret;
7265 }
7266 
7267 /**
7268  * lpfc_sli4_cgn_parm_chg_evt - Process a FW congestion param change event
7269  * @phba: pointer to lpfc hba data structure.
7270  *
7271  * The FW generated Async ACQE SLI event calls this routine when
7272  * the event type is an SLI Internal Port Event and the Event Code
7273  * indicates a change to the FW maintained congestion parameters.
7274  *
7275  * This routine executes a Read_Object mailbox call to obtain the
7276  * current congestion parameters maintained in FW and corrects
7277  * the driver's active congestion parameters.
7278  *
7279  * The acqe event is not passed because there is no further data
7280  * required.
7281  *
7282  * Returns nonzero error if event processing encountered an error.
7283  * Zero otherwise for success.
7284  **/
7285 static int
7286 lpfc_sli4_cgn_parm_chg_evt(struct lpfc_hba *phba)
7287 {
7288 	int ret = 0;
7289 
7290 	if (!phba->sli4_hba.pc_sli4_params.cmf) {
7291 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7292 				"4664 Cgn Evt when E2E off. Drop event\n");
7293 		return -EACCES;
7294 	}
7295 
7296 	/* If the event is claiming an empty object, it's ok.  A write
7297 	 * could have cleared it.  Only error is a negative return
7298 	 * status.
7299 	 */
7300 	ret = lpfc_sli4_cgn_params_read(phba);
7301 	if (ret < 0) {
7302 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7303 				"4667 Error reading Cgn Params (%d)\n",
7304 				ret);
7305 	} else if (!ret) {
7306 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7307 				"4673 CGN Event empty object.\n");
7308 	}
7309 	return ret;
7310 }
7311 
7312 /**
7313  * lpfc_sli4_async_event_proc - Process all the pending asynchronous event
7314  * @phba: pointer to lpfc hba data structure.
7315  *
7316  * This routine is invoked by the worker thread to process all the pending
7317  * SLI4 asynchronous events.
7318  **/
7319 void lpfc_sli4_async_event_proc(struct lpfc_hba *phba)
7320 {
7321 	struct lpfc_cq_event *cq_event;
7322 	unsigned long iflags;
7323 
7324 	/* First, declare the async event has been handled */
7325 	clear_bit(ASYNC_EVENT, &phba->hba_flag);
7326 
7327 	/* Now, handle all the async events */
7328 	spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
7329 	while (!list_empty(&phba->sli4_hba.sp_asynce_work_queue)) {
7330 		list_remove_head(&phba->sli4_hba.sp_asynce_work_queue,
7331 				 cq_event, struct lpfc_cq_event, list);
7332 		spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock,
7333 				       iflags);
7334 
7335 		/* Process the asynchronous event */
7336 		switch (bf_get(lpfc_trailer_code, &cq_event->cqe.mcqe_cmpl)) {
7337 		case LPFC_TRAILER_CODE_LINK:
7338 			lpfc_sli4_async_link_evt(phba,
7339 						 &cq_event->cqe.acqe_link);
7340 			break;
7341 		case LPFC_TRAILER_CODE_FCOE:
7342 			lpfc_sli4_async_fip_evt(phba, &cq_event->cqe.acqe_fip);
7343 			break;
7344 		case LPFC_TRAILER_CODE_DCBX:
7345 			lpfc_sli4_async_dcbx_evt(phba,
7346 						 &cq_event->cqe.acqe_dcbx);
7347 			break;
7348 		case LPFC_TRAILER_CODE_GRP5:
7349 			lpfc_sli4_async_grp5_evt(phba,
7350 						 &cq_event->cqe.acqe_grp5);
7351 			break;
7352 		case LPFC_TRAILER_CODE_FC:
7353 			lpfc_sli4_async_fc_evt(phba, &cq_event->cqe.acqe_fc);
7354 			break;
7355 		case LPFC_TRAILER_CODE_SLI:
7356 			lpfc_sli4_async_sli_evt(phba, &cq_event->cqe.acqe_sli);
7357 			break;
7358 		default:
7359 			lpfc_printf_log(phba, KERN_ERR,
7360 					LOG_TRACE_EVENT,
7361 					"1804 Invalid asynchronous event code: "
7362 					"x%x\n", bf_get(lpfc_trailer_code,
7363 					&cq_event->cqe.mcqe_cmpl));
7364 			break;
7365 		}
7366 
7367 		/* Free the completion event processed to the free pool */
7368 		lpfc_sli4_cq_event_release(phba, cq_event);
7369 		spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
7370 	}
7371 	spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock, iflags);
7372 }
7373 
7374 /**
7375  * lpfc_sli4_fcf_redisc_event_proc - Process fcf table rediscovery event
7376  * @phba: pointer to lpfc hba data structure.
7377  *
7378  * This routine is invoked by the worker thread to process FCF table
7379  * rediscovery pending completion event.
7380  **/
7381 void lpfc_sli4_fcf_redisc_event_proc(struct lpfc_hba *phba)
7382 {
7383 	int rc;
7384 
7385 	spin_lock_irq(&phba->hbalock);
7386 	/* Clear FCF rediscovery timeout event */
7387 	phba->fcf.fcf_flag &= ~FCF_REDISC_EVT;
7388 	/* Clear driver fast failover FCF record flag */
7389 	phba->fcf.failover_rec.flag = 0;
7390 	/* Set state for FCF fast failover */
7391 	phba->fcf.fcf_flag |= FCF_REDISC_FOV;
7392 	spin_unlock_irq(&phba->hbalock);
7393 
7394 	/* Scan FCF table from the first entry to re-discover SAN */
7395 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
7396 			"2777 Start post-quiescent FCF table scan\n");
7397 	rc = lpfc_sli4_fcf_scan_read_fcf_rec(phba, LPFC_FCOE_FCF_GET_FIRST);
7398 	if (rc)
7399 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7400 				"2747 Issue FCF scan read FCF mailbox "
7401 				"command failed 0x%x\n", rc);
7402 }
7403 
7404 /**
7405  * lpfc_api_table_setup - Set up per hba pci-device group func api jump table
7406  * @phba: pointer to lpfc hba data structure.
7407  * @dev_grp: The HBA PCI-Device group number.
7408  *
7409  * This routine is invoked to set up the per HBA PCI-Device group function
7410  * API jump table entries.
7411  *
7412  * Return: 0 if success, otherwise -ENODEV
7413  **/
7414 int
7415 lpfc_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
7416 {
7417 	int rc;
7418 
7419 	/* Set up lpfc PCI-device group */
7420 	phba->pci_dev_grp = dev_grp;
7421 
7422 	/* The LPFC_PCI_DEV_OC uses SLI4 */
7423 	if (dev_grp == LPFC_PCI_DEV_OC)
7424 		phba->sli_rev = LPFC_SLI_REV4;
7425 
7426 	/* Set up device INIT API function jump table */
7427 	rc = lpfc_init_api_table_setup(phba, dev_grp);
7428 	if (rc)
7429 		return -ENODEV;
7430 	/* Set up SCSI API function jump table */
7431 	rc = lpfc_scsi_api_table_setup(phba, dev_grp);
7432 	if (rc)
7433 		return -ENODEV;
7434 	/* Set up SLI API function jump table */
7435 	rc = lpfc_sli_api_table_setup(phba, dev_grp);
7436 	if (rc)
7437 		return -ENODEV;
7438 	/* Set up MBOX API function jump table */
7439 	rc = lpfc_mbox_api_table_setup(phba, dev_grp);
7440 	if (rc)
7441 		return -ENODEV;
7442 
7443 	return 0;
7444 }
7445 
7446 /**
7447  * lpfc_log_intr_mode - Log the active interrupt mode
7448  * @phba: pointer to lpfc hba data structure.
7449  * @intr_mode: active interrupt mode adopted.
7450  *
7451  * This routine it invoked to log the currently used active interrupt mode
7452  * to the device.
7453  **/
7454 static void lpfc_log_intr_mode(struct lpfc_hba *phba, uint32_t intr_mode)
7455 {
7456 	switch (intr_mode) {
7457 	case 0:
7458 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7459 				"0470 Enable INTx interrupt mode.\n");
7460 		break;
7461 	case 1:
7462 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7463 				"0481 Enabled MSI interrupt mode.\n");
7464 		break;
7465 	case 2:
7466 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7467 				"0480 Enabled MSI-X interrupt mode.\n");
7468 		break;
7469 	default:
7470 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7471 				"0482 Illegal interrupt mode.\n");
7472 		break;
7473 	}
7474 	return;
7475 }
7476 
7477 /**
7478  * lpfc_enable_pci_dev - Enable a generic PCI device.
7479  * @phba: pointer to lpfc hba data structure.
7480  *
7481  * This routine is invoked to enable the PCI device that is common to all
7482  * PCI devices.
7483  *
7484  * Return codes
7485  * 	0 - successful
7486  * 	other values - error
7487  **/
7488 static int
7489 lpfc_enable_pci_dev(struct lpfc_hba *phba)
7490 {
7491 	struct pci_dev *pdev;
7492 
7493 	/* Obtain PCI device reference */
7494 	if (!phba->pcidev)
7495 		goto out_error;
7496 	else
7497 		pdev = phba->pcidev;
7498 	/* Enable PCI device */
7499 	if (pci_enable_device_mem(pdev))
7500 		goto out_error;
7501 	/* Request PCI resource for the device */
7502 	if (pci_request_mem_regions(pdev, LPFC_DRIVER_NAME))
7503 		goto out_disable_device;
7504 	/* Set up device as PCI master and save state for EEH */
7505 	pci_set_master(pdev);
7506 	pci_try_set_mwi(pdev);
7507 	pci_save_state(pdev);
7508 
7509 	/* PCIe EEH recovery on powerpc platforms needs fundamental reset */
7510 	if (pci_is_pcie(pdev))
7511 		pdev->needs_freset = 1;
7512 
7513 	return 0;
7514 
7515 out_disable_device:
7516 	pci_disable_device(pdev);
7517 out_error:
7518 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7519 			"1401 Failed to enable pci device\n");
7520 	return -ENODEV;
7521 }
7522 
7523 /**
7524  * lpfc_disable_pci_dev - Disable a generic PCI device.
7525  * @phba: pointer to lpfc hba data structure.
7526  *
7527  * This routine is invoked to disable the PCI device that is common to all
7528  * PCI devices.
7529  **/
7530 static void
7531 lpfc_disable_pci_dev(struct lpfc_hba *phba)
7532 {
7533 	struct pci_dev *pdev;
7534 
7535 	/* Obtain PCI device reference */
7536 	if (!phba->pcidev)
7537 		return;
7538 	else
7539 		pdev = phba->pcidev;
7540 	/* Release PCI resource and disable PCI device */
7541 	pci_release_mem_regions(pdev);
7542 	pci_disable_device(pdev);
7543 
7544 	return;
7545 }
7546 
7547 /**
7548  * lpfc_reset_hba - Reset a hba
7549  * @phba: pointer to lpfc hba data structure.
7550  *
7551  * This routine is invoked to reset a hba device. It brings the HBA
7552  * offline, performs a board restart, and then brings the board back
7553  * online. The lpfc_offline calls lpfc_sli_hba_down which will clean up
7554  * on outstanding mailbox commands.
7555  **/
7556 void
7557 lpfc_reset_hba(struct lpfc_hba *phba)
7558 {
7559 	int rc = 0;
7560 
7561 	/* If resets are disabled then set error state and return. */
7562 	if (!phba->cfg_enable_hba_reset) {
7563 		phba->link_state = LPFC_HBA_ERROR;
7564 		return;
7565 	}
7566 
7567 	/* If not LPFC_SLI_ACTIVE, force all IO to be flushed */
7568 	if (phba->sli.sli_flag & LPFC_SLI_ACTIVE) {
7569 		lpfc_offline_prep(phba, LPFC_MBX_WAIT);
7570 	} else {
7571 		if (test_bit(MBX_TMO_ERR, &phba->bit_flags)) {
7572 			/* Perform a PCI function reset to start from clean */
7573 			rc = lpfc_pci_function_reset(phba);
7574 			lpfc_els_flush_all_cmd(phba);
7575 		}
7576 		lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
7577 		lpfc_sli_flush_io_rings(phba);
7578 	}
7579 	lpfc_offline(phba);
7580 	clear_bit(MBX_TMO_ERR, &phba->bit_flags);
7581 	if (unlikely(rc)) {
7582 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
7583 				"8888 PCI function reset failed rc %x\n",
7584 				rc);
7585 	} else {
7586 		lpfc_sli_brdrestart(phba);
7587 		lpfc_online(phba);
7588 		lpfc_unblock_mgmt_io(phba);
7589 	}
7590 }
7591 
7592 /**
7593  * lpfc_sli_sriov_nr_virtfn_get - Get the number of sr-iov virtual functions
7594  * @phba: pointer to lpfc hba data structure.
7595  *
7596  * This function enables the PCI SR-IOV virtual functions to a physical
7597  * function. It invokes the PCI SR-IOV api with the @nr_vfn provided to
7598  * enable the number of virtual functions to the physical function. As
7599  * not all devices support SR-IOV, the return code from the pci_enable_sriov()
7600  * API call does not considered as an error condition for most of the device.
7601  **/
7602 uint16_t
7603 lpfc_sli_sriov_nr_virtfn_get(struct lpfc_hba *phba)
7604 {
7605 	struct pci_dev *pdev = phba->pcidev;
7606 	uint16_t nr_virtfn;
7607 	int pos;
7608 
7609 	pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_SRIOV);
7610 	if (pos == 0)
7611 		return 0;
7612 
7613 	pci_read_config_word(pdev, pos + PCI_SRIOV_TOTAL_VF, &nr_virtfn);
7614 	return nr_virtfn;
7615 }
7616 
7617 /**
7618  * lpfc_sli_probe_sriov_nr_virtfn - Enable a number of sr-iov virtual functions
7619  * @phba: pointer to lpfc hba data structure.
7620  * @nr_vfn: number of virtual functions to be enabled.
7621  *
7622  * This function enables the PCI SR-IOV virtual functions to a physical
7623  * function. It invokes the PCI SR-IOV api with the @nr_vfn provided to
7624  * enable the number of virtual functions to the physical function. As
7625  * not all devices support SR-IOV, the return code from the pci_enable_sriov()
7626  * API call does not considered as an error condition for most of the device.
7627  **/
7628 int
7629 lpfc_sli_probe_sriov_nr_virtfn(struct lpfc_hba *phba, int nr_vfn)
7630 {
7631 	struct pci_dev *pdev = phba->pcidev;
7632 	uint16_t max_nr_vfn;
7633 	int rc;
7634 
7635 	max_nr_vfn = lpfc_sli_sriov_nr_virtfn_get(phba);
7636 	if (nr_vfn > max_nr_vfn) {
7637 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7638 				"3057 Requested vfs (%d) greater than "
7639 				"supported vfs (%d)", nr_vfn, max_nr_vfn);
7640 		return -EINVAL;
7641 	}
7642 
7643 	rc = pci_enable_sriov(pdev, nr_vfn);
7644 	if (rc) {
7645 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7646 				"2806 Failed to enable sriov on this device "
7647 				"with vfn number nr_vf:%d, rc:%d\n",
7648 				nr_vfn, rc);
7649 	} else
7650 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7651 				"2807 Successful enable sriov on this device "
7652 				"with vfn number nr_vf:%d\n", nr_vfn);
7653 	return rc;
7654 }
7655 
7656 static void
7657 lpfc_unblock_requests_work(struct work_struct *work)
7658 {
7659 	struct lpfc_hba *phba = container_of(work, struct lpfc_hba,
7660 					     unblock_request_work);
7661 
7662 	lpfc_unblock_requests(phba);
7663 }
7664 
7665 /**
7666  * lpfc_setup_driver_resource_phase1 - Phase1 etup driver internal resources.
7667  * @phba: pointer to lpfc hba data structure.
7668  *
7669  * This routine is invoked to set up the driver internal resources before the
7670  * device specific resource setup to support the HBA device it attached to.
7671  *
7672  * Return codes
7673  *	0 - successful
7674  *	other values - error
7675  **/
7676 static int
7677 lpfc_setup_driver_resource_phase1(struct lpfc_hba *phba)
7678 {
7679 	struct lpfc_sli *psli = &phba->sli;
7680 
7681 	/*
7682 	 * Driver resources common to all SLI revisions
7683 	 */
7684 	atomic_set(&phba->fast_event_count, 0);
7685 	atomic_set(&phba->dbg_log_idx, 0);
7686 	atomic_set(&phba->dbg_log_cnt, 0);
7687 	atomic_set(&phba->dbg_log_dmping, 0);
7688 	spin_lock_init(&phba->hbalock);
7689 
7690 	/* Initialize port_list spinlock */
7691 	spin_lock_init(&phba->port_list_lock);
7692 	INIT_LIST_HEAD(&phba->port_list);
7693 
7694 	INIT_LIST_HEAD(&phba->work_list);
7695 
7696 	/* Initialize the wait queue head for the kernel thread */
7697 	init_waitqueue_head(&phba->work_waitq);
7698 
7699 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7700 			"1403 Protocols supported %s %s %s\n",
7701 			((phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP) ?
7702 				"SCSI" : " "),
7703 			((phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) ?
7704 				"NVME" : " "),
7705 			(phba->nvmet_support ? "NVMET" : " "));
7706 
7707 	/* ras_fwlog state */
7708 	spin_lock_init(&phba->ras_fwlog_lock);
7709 
7710 	/* Initialize the IO buffer list used by driver for SLI3 SCSI */
7711 	spin_lock_init(&phba->scsi_buf_list_get_lock);
7712 	INIT_LIST_HEAD(&phba->lpfc_scsi_buf_list_get);
7713 	spin_lock_init(&phba->scsi_buf_list_put_lock);
7714 	INIT_LIST_HEAD(&phba->lpfc_scsi_buf_list_put);
7715 
7716 	/* Initialize the fabric iocb list */
7717 	INIT_LIST_HEAD(&phba->fabric_iocb_list);
7718 
7719 	/* Initialize list to save ELS buffers */
7720 	INIT_LIST_HEAD(&phba->elsbuf);
7721 
7722 	/* Initialize FCF connection rec list */
7723 	INIT_LIST_HEAD(&phba->fcf_conn_rec_list);
7724 
7725 	/* Initialize OAS configuration list */
7726 	spin_lock_init(&phba->devicelock);
7727 	INIT_LIST_HEAD(&phba->luns);
7728 
7729 	/* MBOX heartbeat timer */
7730 	timer_setup(&psli->mbox_tmo, lpfc_mbox_timeout, 0);
7731 	/* Fabric block timer */
7732 	timer_setup(&phba->fabric_block_timer, lpfc_fabric_block_timeout, 0);
7733 	/* EA polling mode timer */
7734 	timer_setup(&phba->eratt_poll, lpfc_poll_eratt, 0);
7735 	/* Heartbeat timer */
7736 	timer_setup(&phba->hb_tmofunc, lpfc_hb_timeout, 0);
7737 
7738 	INIT_DELAYED_WORK(&phba->eq_delay_work, lpfc_hb_eq_delay_work);
7739 
7740 	INIT_DELAYED_WORK(&phba->idle_stat_delay_work,
7741 			  lpfc_idle_stat_delay_work);
7742 	INIT_WORK(&phba->unblock_request_work, lpfc_unblock_requests_work);
7743 	return 0;
7744 }
7745 
7746 /**
7747  * lpfc_sli_driver_resource_setup - Setup driver internal resources for SLI3 dev
7748  * @phba: pointer to lpfc hba data structure.
7749  *
7750  * This routine is invoked to set up the driver internal resources specific to
7751  * support the SLI-3 HBA device it attached to.
7752  *
7753  * Return codes
7754  * 0 - successful
7755  * other values - error
7756  **/
7757 static int
7758 lpfc_sli_driver_resource_setup(struct lpfc_hba *phba)
7759 {
7760 	int rc, entry_sz;
7761 
7762 	/*
7763 	 * Initialize timers used by driver
7764 	 */
7765 
7766 	/* FCP polling mode timer */
7767 	timer_setup(&phba->fcp_poll_timer, lpfc_poll_timeout, 0);
7768 
7769 	/* Host attention work mask setup */
7770 	phba->work_ha_mask = (HA_ERATT | HA_MBATT | HA_LATT);
7771 	phba->work_ha_mask |= (HA_RXMASK << (LPFC_ELS_RING * 4));
7772 
7773 	/* Get all the module params for configuring this host */
7774 	lpfc_get_cfgparam(phba);
7775 	/* Set up phase-1 common device driver resources */
7776 
7777 	rc = lpfc_setup_driver_resource_phase1(phba);
7778 	if (rc)
7779 		return -ENODEV;
7780 
7781 	if (!phba->sli.sli3_ring)
7782 		phba->sli.sli3_ring = kcalloc(LPFC_SLI3_MAX_RING,
7783 					      sizeof(struct lpfc_sli_ring),
7784 					      GFP_KERNEL);
7785 	if (!phba->sli.sli3_ring)
7786 		return -ENOMEM;
7787 
7788 	/*
7789 	 * Since lpfc_sg_seg_cnt is module parameter, the sg_dma_buf_size
7790 	 * used to create the sg_dma_buf_pool must be dynamically calculated.
7791 	 */
7792 
7793 	if (phba->sli_rev == LPFC_SLI_REV4)
7794 		entry_sz = sizeof(struct sli4_sge);
7795 	else
7796 		entry_sz = sizeof(struct ulp_bde64);
7797 
7798 	/* There are going to be 2 reserved BDEs: 1 FCP cmnd + 1 FCP rsp */
7799 	if (phba->cfg_enable_bg) {
7800 		/*
7801 		 * The scsi_buf for a T10-DIF I/O will hold the FCP cmnd,
7802 		 * the FCP rsp, and a BDE for each. Sice we have no control
7803 		 * over how many protection data segments the SCSI Layer
7804 		 * will hand us (ie: there could be one for every block
7805 		 * in the IO), we just allocate enough BDEs to accomidate
7806 		 * our max amount and we need to limit lpfc_sg_seg_cnt to
7807 		 * minimize the risk of running out.
7808 		 */
7809 		phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd) +
7810 			sizeof(struct fcp_rsp) +
7811 			(LPFC_MAX_SG_SEG_CNT * entry_sz);
7812 
7813 		if (phba->cfg_sg_seg_cnt > LPFC_MAX_SG_SEG_CNT_DIF)
7814 			phba->cfg_sg_seg_cnt = LPFC_MAX_SG_SEG_CNT_DIF;
7815 
7816 		/* Total BDEs in BPL for scsi_sg_list and scsi_sg_prot_list */
7817 		phba->cfg_total_seg_cnt = LPFC_MAX_SG_SEG_CNT;
7818 	} else {
7819 		/*
7820 		 * The scsi_buf for a regular I/O will hold the FCP cmnd,
7821 		 * the FCP rsp, a BDE for each, and a BDE for up to
7822 		 * cfg_sg_seg_cnt data segments.
7823 		 */
7824 		phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd) +
7825 			sizeof(struct fcp_rsp) +
7826 			((phba->cfg_sg_seg_cnt + 2) * entry_sz);
7827 
7828 		/* Total BDEs in BPL for scsi_sg_list */
7829 		phba->cfg_total_seg_cnt = phba->cfg_sg_seg_cnt + 2;
7830 	}
7831 
7832 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP,
7833 			"9088 INIT sg_tablesize:%d dmabuf_size:%d total_bde:%d\n",
7834 			phba->cfg_sg_seg_cnt, phba->cfg_sg_dma_buf_size,
7835 			phba->cfg_total_seg_cnt);
7836 
7837 	phba->max_vpi = LPFC_MAX_VPI;
7838 	/* This will be set to correct value after config_port mbox */
7839 	phba->max_vports = 0;
7840 
7841 	/*
7842 	 * Initialize the SLI Layer to run with lpfc HBAs.
7843 	 */
7844 	lpfc_sli_setup(phba);
7845 	lpfc_sli_queue_init(phba);
7846 
7847 	/* Allocate device driver memory */
7848 	if (lpfc_mem_alloc(phba, BPL_ALIGN_SZ))
7849 		return -ENOMEM;
7850 
7851 	phba->lpfc_sg_dma_buf_pool =
7852 		dma_pool_create("lpfc_sg_dma_buf_pool",
7853 				&phba->pcidev->dev, phba->cfg_sg_dma_buf_size,
7854 				BPL_ALIGN_SZ, 0);
7855 
7856 	if (!phba->lpfc_sg_dma_buf_pool)
7857 		goto fail_free_mem;
7858 
7859 	phba->lpfc_cmd_rsp_buf_pool =
7860 			dma_pool_create("lpfc_cmd_rsp_buf_pool",
7861 					&phba->pcidev->dev,
7862 					sizeof(struct fcp_cmnd) +
7863 					sizeof(struct fcp_rsp),
7864 					BPL_ALIGN_SZ, 0);
7865 
7866 	if (!phba->lpfc_cmd_rsp_buf_pool)
7867 		goto fail_free_dma_buf_pool;
7868 
7869 	/*
7870 	 * Enable sr-iov virtual functions if supported and configured
7871 	 * through the module parameter.
7872 	 */
7873 	if (phba->cfg_sriov_nr_virtfn > 0) {
7874 		rc = lpfc_sli_probe_sriov_nr_virtfn(phba,
7875 						 phba->cfg_sriov_nr_virtfn);
7876 		if (rc) {
7877 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7878 					"2808 Requested number of SR-IOV "
7879 					"virtual functions (%d) is not "
7880 					"supported\n",
7881 					phba->cfg_sriov_nr_virtfn);
7882 			phba->cfg_sriov_nr_virtfn = 0;
7883 		}
7884 	}
7885 
7886 	return 0;
7887 
7888 fail_free_dma_buf_pool:
7889 	dma_pool_destroy(phba->lpfc_sg_dma_buf_pool);
7890 	phba->lpfc_sg_dma_buf_pool = NULL;
7891 fail_free_mem:
7892 	lpfc_mem_free(phba);
7893 	return -ENOMEM;
7894 }
7895 
7896 /**
7897  * lpfc_sli_driver_resource_unset - Unset drvr internal resources for SLI3 dev
7898  * @phba: pointer to lpfc hba data structure.
7899  *
7900  * This routine is invoked to unset the driver internal resources set up
7901  * specific for supporting the SLI-3 HBA device it attached to.
7902  **/
7903 static void
7904 lpfc_sli_driver_resource_unset(struct lpfc_hba *phba)
7905 {
7906 	/* Free device driver memory allocated */
7907 	lpfc_mem_free_all(phba);
7908 
7909 	return;
7910 }
7911 
7912 /**
7913  * lpfc_sli4_driver_resource_setup - Setup drvr internal resources for SLI4 dev
7914  * @phba: pointer to lpfc hba data structure.
7915  *
7916  * This routine is invoked to set up the driver internal resources specific to
7917  * support the SLI-4 HBA device it attached to.
7918  *
7919  * Return codes
7920  * 	0 - successful
7921  * 	other values - error
7922  **/
7923 static int
7924 lpfc_sli4_driver_resource_setup(struct lpfc_hba *phba)
7925 {
7926 	LPFC_MBOXQ_t *mboxq;
7927 	MAILBOX_t *mb;
7928 	int rc, i, max_buf_size;
7929 	int longs;
7930 	int extra;
7931 	uint64_t wwn;
7932 
7933 	phba->sli4_hba.num_present_cpu = lpfc_present_cpu;
7934 	phba->sli4_hba.num_possible_cpu = cpumask_last(cpu_possible_mask) + 1;
7935 	phba->sli4_hba.curr_disp_cpu = 0;
7936 
7937 	/* Get all the module params for configuring this host */
7938 	lpfc_get_cfgparam(phba);
7939 
7940 	/* Set up phase-1 common device driver resources */
7941 	rc = lpfc_setup_driver_resource_phase1(phba);
7942 	if (rc)
7943 		return -ENODEV;
7944 
7945 	/* Before proceed, wait for POST done and device ready */
7946 	rc = lpfc_sli4_post_status_check(phba);
7947 	if (rc)
7948 		return -ENODEV;
7949 
7950 	/* Allocate all driver workqueues here */
7951 
7952 	/* The lpfc_wq workqueue for deferred irq use */
7953 	phba->wq = alloc_workqueue("lpfc_wq", WQ_MEM_RECLAIM, 0);
7954 	if (!phba->wq)
7955 		return -ENOMEM;
7956 
7957 	/*
7958 	 * Initialize timers used by driver
7959 	 */
7960 
7961 	timer_setup(&phba->rrq_tmr, lpfc_rrq_timeout, 0);
7962 
7963 	/* FCF rediscover timer */
7964 	timer_setup(&phba->fcf.redisc_wait, lpfc_sli4_fcf_redisc_wait_tmo, 0);
7965 
7966 	/* CMF congestion timer */
7967 	hrtimer_setup(&phba->cmf_timer, lpfc_cmf_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
7968 	/* CMF 1 minute stats collection timer */
7969 	hrtimer_setup(&phba->cmf_stats_timer, lpfc_cmf_stats_timer, CLOCK_MONOTONIC,
7970 		      HRTIMER_MODE_REL);
7971 
7972 	/*
7973 	 * Control structure for handling external multi-buffer mailbox
7974 	 * command pass-through.
7975 	 */
7976 	memset((uint8_t *)&phba->mbox_ext_buf_ctx, 0,
7977 		sizeof(struct lpfc_mbox_ext_buf_ctx));
7978 	INIT_LIST_HEAD(&phba->mbox_ext_buf_ctx.ext_dmabuf_list);
7979 
7980 	phba->max_vpi = LPFC_MAX_VPI;
7981 
7982 	/* This will be set to correct value after the read_config mbox */
7983 	phba->max_vports = 0;
7984 
7985 	/* Program the default value of vlan_id and fc_map */
7986 	phba->valid_vlan = 0;
7987 	phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
7988 	phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
7989 	phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
7990 
7991 	/*
7992 	 * For SLI4, instead of using ring 0 (LPFC_FCP_RING) for FCP commands
7993 	 * we will associate a new ring, for each EQ/CQ/WQ tuple.
7994 	 * The WQ create will allocate the ring.
7995 	 */
7996 
7997 	/* Initialize buffer queue management fields */
7998 	INIT_LIST_HEAD(&phba->hbqs[LPFC_ELS_HBQ].hbq_buffer_list);
7999 	phba->hbqs[LPFC_ELS_HBQ].hbq_alloc_buffer = lpfc_sli4_rb_alloc;
8000 	phba->hbqs[LPFC_ELS_HBQ].hbq_free_buffer = lpfc_sli4_rb_free;
8001 
8002 	/* for VMID idle timeout if VMID is enabled */
8003 	if (lpfc_is_vmid_enabled(phba))
8004 		timer_setup(&phba->inactive_vmid_poll, lpfc_vmid_poll, 0);
8005 
8006 	/*
8007 	 * Initialize the SLI Layer to run with lpfc SLI4 HBAs.
8008 	 */
8009 	/* Initialize the Abort buffer list used by driver */
8010 	spin_lock_init(&phba->sli4_hba.abts_io_buf_list_lock);
8011 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_io_buf_list);
8012 
8013 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
8014 		/* Initialize the Abort nvme buffer list used by driver */
8015 		spin_lock_init(&phba->sli4_hba.abts_nvmet_buf_list_lock);
8016 		INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
8017 		INIT_LIST_HEAD(&phba->sli4_hba.lpfc_nvmet_io_wait_list);
8018 		spin_lock_init(&phba->sli4_hba.t_active_list_lock);
8019 		INIT_LIST_HEAD(&phba->sli4_hba.t_active_ctx_list);
8020 	}
8021 
8022 	/* This abort list used by worker thread */
8023 	spin_lock_init(&phba->sli4_hba.sgl_list_lock);
8024 	spin_lock_init(&phba->sli4_hba.nvmet_io_wait_lock);
8025 	spin_lock_init(&phba->sli4_hba.asynce_list_lock);
8026 	spin_lock_init(&phba->sli4_hba.els_xri_abrt_list_lock);
8027 
8028 	/*
8029 	 * Initialize driver internal slow-path work queues
8030 	 */
8031 
8032 	/* Driver internel slow-path CQ Event pool */
8033 	INIT_LIST_HEAD(&phba->sli4_hba.sp_cqe_event_pool);
8034 	/* Response IOCB work queue list */
8035 	INIT_LIST_HEAD(&phba->sli4_hba.sp_queue_event);
8036 	/* Asynchronous event CQ Event work queue list */
8037 	INIT_LIST_HEAD(&phba->sli4_hba.sp_asynce_work_queue);
8038 	/* Slow-path XRI aborted CQ Event work queue list */
8039 	INIT_LIST_HEAD(&phba->sli4_hba.sp_els_xri_aborted_work_queue);
8040 	/* Receive queue CQ Event work queue list */
8041 	INIT_LIST_HEAD(&phba->sli4_hba.sp_unsol_work_queue);
8042 
8043 	/* Initialize extent block lists. */
8044 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_rpi_blk_list);
8045 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_xri_blk_list);
8046 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_vfi_blk_list);
8047 	INIT_LIST_HEAD(&phba->lpfc_vpi_blk_list);
8048 
8049 	/* Initialize mboxq lists. If the early init routines fail
8050 	 * these lists need to be correctly initialized.
8051 	 */
8052 	INIT_LIST_HEAD(&phba->sli.mboxq);
8053 	INIT_LIST_HEAD(&phba->sli.mboxq_cmpl);
8054 
8055 	/* initialize optic_state to 0xFF */
8056 	phba->sli4_hba.lnk_info.optic_state = 0xff;
8057 
8058 	/* Allocate device driver memory */
8059 	rc = lpfc_mem_alloc(phba, SGL_ALIGN_SZ);
8060 	if (rc)
8061 		goto out_destroy_workqueue;
8062 
8063 	/* IF Type 2 ports get initialized now. */
8064 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) >=
8065 	    LPFC_SLI_INTF_IF_TYPE_2) {
8066 		rc = lpfc_pci_function_reset(phba);
8067 		if (unlikely(rc)) {
8068 			rc = -ENODEV;
8069 			goto out_free_mem;
8070 		}
8071 		phba->temp_sensor_support = 1;
8072 	}
8073 
8074 	/* Create the bootstrap mailbox command */
8075 	rc = lpfc_create_bootstrap_mbox(phba);
8076 	if (unlikely(rc))
8077 		goto out_free_mem;
8078 
8079 	/* Set up the host's endian order with the device. */
8080 	rc = lpfc_setup_endian_order(phba);
8081 	if (unlikely(rc))
8082 		goto out_free_bsmbx;
8083 
8084 	/* Set up the hba's configuration parameters. */
8085 	rc = lpfc_sli4_read_config(phba);
8086 	if (unlikely(rc))
8087 		goto out_free_bsmbx;
8088 
8089 	if (phba->sli4_hba.fawwpn_flag & LPFC_FAWWPN_CONFIG) {
8090 		/* Right now the link is down, if FA-PWWN is configured the
8091 		 * firmware will try FLOGI before the driver gets a link up.
8092 		 * If it fails, the driver should get a MISCONFIGURED async
8093 		 * event which will clear this flag. The only notification
8094 		 * the driver gets is if it fails, if it succeeds there is no
8095 		 * notification given. Assume success.
8096 		 */
8097 		phba->sli4_hba.fawwpn_flag |= LPFC_FAWWPN_FABRIC;
8098 	}
8099 
8100 	rc = lpfc_mem_alloc_active_rrq_pool_s4(phba);
8101 	if (unlikely(rc))
8102 		goto out_free_bsmbx;
8103 
8104 	/* IF Type 0 ports get initialized now. */
8105 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
8106 	    LPFC_SLI_INTF_IF_TYPE_0) {
8107 		rc = lpfc_pci_function_reset(phba);
8108 		if (unlikely(rc))
8109 			goto out_free_bsmbx;
8110 	}
8111 
8112 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
8113 						       GFP_KERNEL);
8114 	if (!mboxq) {
8115 		rc = -ENOMEM;
8116 		goto out_free_bsmbx;
8117 	}
8118 
8119 	/* Check for NVMET being configured */
8120 	phba->nvmet_support = 0;
8121 	if (lpfc_enable_nvmet_cnt) {
8122 
8123 		/* First get WWN of HBA instance */
8124 		lpfc_read_nv(phba, mboxq);
8125 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8126 		if (rc != MBX_SUCCESS) {
8127 			lpfc_printf_log(phba, KERN_ERR,
8128 					LOG_TRACE_EVENT,
8129 					"6016 Mailbox failed , mbxCmd x%x "
8130 					"READ_NV, mbxStatus x%x\n",
8131 					bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8132 					bf_get(lpfc_mqe_status, &mboxq->u.mqe));
8133 			mempool_free(mboxq, phba->mbox_mem_pool);
8134 			rc = -EIO;
8135 			goto out_free_bsmbx;
8136 		}
8137 		mb = &mboxq->u.mb;
8138 		memcpy(&wwn, (char *)mb->un.varRDnvp.nodename,
8139 		       sizeof(uint64_t));
8140 		wwn = cpu_to_be64(wwn);
8141 		phba->sli4_hba.wwnn.u.name = wwn;
8142 		memcpy(&wwn, (char *)mb->un.varRDnvp.portname,
8143 		       sizeof(uint64_t));
8144 		/* wwn is WWPN of HBA instance */
8145 		wwn = cpu_to_be64(wwn);
8146 		phba->sli4_hba.wwpn.u.name = wwn;
8147 
8148 		/* Check to see if it matches any module parameter */
8149 		for (i = 0; i < lpfc_enable_nvmet_cnt; i++) {
8150 			if (wwn == lpfc_enable_nvmet[i]) {
8151 #if (IS_ENABLED(CONFIG_NVME_TARGET_FC))
8152 				if (lpfc_nvmet_mem_alloc(phba))
8153 					break;
8154 
8155 				phba->nvmet_support = 1; /* a match */
8156 
8157 				lpfc_printf_log(phba, KERN_ERR,
8158 						LOG_TRACE_EVENT,
8159 						"6017 NVME Target %016llx\n",
8160 						wwn);
8161 #else
8162 				lpfc_printf_log(phba, KERN_ERR,
8163 						LOG_TRACE_EVENT,
8164 						"6021 Can't enable NVME Target."
8165 						" NVME_TARGET_FC infrastructure"
8166 						" is not in kernel\n");
8167 #endif
8168 				/* Not supported for NVMET */
8169 				phba->cfg_xri_rebalancing = 0;
8170 				if (phba->irq_chann_mode == NHT_MODE) {
8171 					phba->cfg_irq_chann =
8172 						phba->sli4_hba.num_present_cpu;
8173 					phba->cfg_hdw_queue =
8174 						phba->sli4_hba.num_present_cpu;
8175 					phba->irq_chann_mode = NORMAL_MODE;
8176 				}
8177 				break;
8178 			}
8179 		}
8180 	}
8181 
8182 	lpfc_nvme_mod_param_dep(phba);
8183 
8184 	/*
8185 	 * Get sli4 parameters that override parameters from Port capabilities.
8186 	 * If this call fails, it isn't critical unless the SLI4 parameters come
8187 	 * back in conflict.
8188 	 */
8189 	rc = lpfc_get_sli4_parameters(phba, mboxq);
8190 	if (rc) {
8191 		lpfc_log_msg(phba, KERN_WARNING, LOG_INIT,
8192 			     "2999 Could not get SLI4 parameters\n");
8193 		rc = -EIO;
8194 		mempool_free(mboxq, phba->mbox_mem_pool);
8195 		goto out_free_bsmbx;
8196 	}
8197 
8198 	/*
8199 	 * 1 for cmd, 1 for rsp, NVME adds an extra one
8200 	 * for boundary conditions in its max_sgl_segment template.
8201 	 */
8202 	extra = 2;
8203 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
8204 		extra++;
8205 
8206 	/*
8207 	 * It doesn't matter what family our adapter is in, we are
8208 	 * limited to 2 Pages, 512 SGEs, for our SGL.
8209 	 * There are going to be 2 reserved SGEs: 1 FCP cmnd + 1 FCP rsp
8210 	 */
8211 	max_buf_size = (2 * SLI4_PAGE_SIZE);
8212 
8213 	/*
8214 	 * Since lpfc_sg_seg_cnt is module param, the sg_dma_buf_size
8215 	 * used to create the sg_dma_buf_pool must be calculated.
8216 	 */
8217 	if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
8218 		/* Both cfg_enable_bg and cfg_external_dif code paths */
8219 
8220 		/*
8221 		 * The scsi_buf for a T10-DIF I/O holds the FCP cmnd,
8222 		 * the FCP rsp, and a SGE. Sice we have no control
8223 		 * over how many protection segments the SCSI Layer
8224 		 * will hand us (ie: there could be one for every block
8225 		 * in the IO), just allocate enough SGEs to accomidate
8226 		 * our max amount and we need to limit lpfc_sg_seg_cnt
8227 		 * to minimize the risk of running out.
8228 		 */
8229 		phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd32) +
8230 				sizeof(struct fcp_rsp) + max_buf_size;
8231 
8232 		/* Total SGEs for scsi_sg_list and scsi_sg_prot_list */
8233 		phba->cfg_total_seg_cnt = LPFC_MAX_SGL_SEG_CNT;
8234 
8235 		/*
8236 		 * If supporting DIF, reduce the seg count for scsi to
8237 		 * allow room for the DIF sges.
8238 		 */
8239 		if (phba->cfg_enable_bg &&
8240 		    phba->cfg_sg_seg_cnt > LPFC_MAX_BG_SLI4_SEG_CNT_DIF)
8241 			phba->cfg_scsi_seg_cnt = LPFC_MAX_BG_SLI4_SEG_CNT_DIF;
8242 		else
8243 			phba->cfg_scsi_seg_cnt = phba->cfg_sg_seg_cnt;
8244 
8245 	} else {
8246 		/*
8247 		 * The scsi_buf for a regular I/O holds the FCP cmnd,
8248 		 * the FCP rsp, a SGE for each, and a SGE for up to
8249 		 * cfg_sg_seg_cnt data segments.
8250 		 */
8251 		phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd32) +
8252 				sizeof(struct fcp_rsp) +
8253 				((phba->cfg_sg_seg_cnt + extra) *
8254 				sizeof(struct sli4_sge));
8255 
8256 		/* Total SGEs for scsi_sg_list */
8257 		phba->cfg_total_seg_cnt = phba->cfg_sg_seg_cnt + extra;
8258 		phba->cfg_scsi_seg_cnt = phba->cfg_sg_seg_cnt;
8259 
8260 		/*
8261 		 * NOTE: if (phba->cfg_sg_seg_cnt + extra) <= 256 we only
8262 		 * need to post 1 page for the SGL.
8263 		 */
8264 	}
8265 
8266 	if (phba->cfg_xpsgl && !phba->nvmet_support)
8267 		phba->cfg_sg_dma_buf_size = LPFC_DEFAULT_XPSGL_SIZE;
8268 	else if (phba->cfg_sg_dma_buf_size  <= LPFC_MIN_SG_SLI4_BUF_SZ)
8269 		phba->cfg_sg_dma_buf_size = LPFC_MIN_SG_SLI4_BUF_SZ;
8270 	else
8271 		phba->cfg_sg_dma_buf_size =
8272 				SLI4_PAGE_ALIGN(phba->cfg_sg_dma_buf_size);
8273 
8274 	phba->border_sge_num = phba->cfg_sg_dma_buf_size /
8275 			       sizeof(struct sli4_sge);
8276 
8277 	/* Limit to LPFC_MAX_NVME_SEG_CNT for NVME. */
8278 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
8279 		if (phba->cfg_sg_seg_cnt > LPFC_MAX_NVME_SEG_CNT) {
8280 			lpfc_printf_log(phba, KERN_INFO, LOG_NVME | LOG_INIT,
8281 					"6300 Reducing NVME sg segment "
8282 					"cnt to %d\n",
8283 					LPFC_MAX_NVME_SEG_CNT);
8284 			phba->cfg_nvme_seg_cnt = LPFC_MAX_NVME_SEG_CNT;
8285 		} else
8286 			phba->cfg_nvme_seg_cnt = phba->cfg_sg_seg_cnt;
8287 	}
8288 
8289 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP,
8290 			"9087 sg_seg_cnt:%d dmabuf_size:%d "
8291 			"total:%d scsi:%d nvme:%d\n",
8292 			phba->cfg_sg_seg_cnt, phba->cfg_sg_dma_buf_size,
8293 			phba->cfg_total_seg_cnt,  phba->cfg_scsi_seg_cnt,
8294 			phba->cfg_nvme_seg_cnt);
8295 
8296 	i = min(phba->cfg_sg_dma_buf_size, SLI4_PAGE_SIZE);
8297 
8298 	phba->lpfc_sg_dma_buf_pool =
8299 			dma_pool_create("lpfc_sg_dma_buf_pool",
8300 					&phba->pcidev->dev,
8301 					phba->cfg_sg_dma_buf_size,
8302 					i, 0);
8303 	if (!phba->lpfc_sg_dma_buf_pool) {
8304 		rc = -ENOMEM;
8305 		goto out_free_bsmbx;
8306 	}
8307 
8308 	phba->lpfc_cmd_rsp_buf_pool =
8309 			dma_pool_create("lpfc_cmd_rsp_buf_pool",
8310 					&phba->pcidev->dev,
8311 					sizeof(struct fcp_cmnd32) +
8312 					sizeof(struct fcp_rsp),
8313 					i, 0);
8314 	if (!phba->lpfc_cmd_rsp_buf_pool) {
8315 		rc = -ENOMEM;
8316 		goto out_free_sg_dma_buf;
8317 	}
8318 
8319 	mempool_free(mboxq, phba->mbox_mem_pool);
8320 
8321 	/* Verify OAS is supported */
8322 	lpfc_sli4_oas_verify(phba);
8323 
8324 	/* Verify RAS support on adapter */
8325 	lpfc_sli4_ras_init(phba);
8326 
8327 	/* Verify all the SLI4 queues */
8328 	rc = lpfc_sli4_queue_verify(phba);
8329 	if (rc)
8330 		goto out_free_cmd_rsp_buf;
8331 
8332 	/* Create driver internal CQE event pool */
8333 	rc = lpfc_sli4_cq_event_pool_create(phba);
8334 	if (rc)
8335 		goto out_free_cmd_rsp_buf;
8336 
8337 	/* Initialize sgl lists per host */
8338 	lpfc_init_sgl_list(phba);
8339 
8340 	/* Allocate and initialize active sgl array */
8341 	rc = lpfc_init_active_sgl_array(phba);
8342 	if (rc) {
8343 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8344 				"1430 Failed to initialize sgl list.\n");
8345 		goto out_destroy_cq_event_pool;
8346 	}
8347 	rc = lpfc_sli4_init_rpi_hdrs(phba);
8348 	if (rc) {
8349 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8350 				"1432 Failed to initialize rpi headers.\n");
8351 		goto out_free_active_sgl;
8352 	}
8353 
8354 	/* Allocate eligible FCF bmask memory for FCF roundrobin failover */
8355 	longs = (LPFC_SLI4_FCF_TBL_INDX_MAX + BITS_PER_LONG - 1)/BITS_PER_LONG;
8356 	phba->fcf.fcf_rr_bmask = kcalloc(longs, sizeof(unsigned long),
8357 					 GFP_KERNEL);
8358 	if (!phba->fcf.fcf_rr_bmask) {
8359 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8360 				"2759 Failed allocate memory for FCF round "
8361 				"robin failover bmask\n");
8362 		rc = -ENOMEM;
8363 		goto out_remove_rpi_hdrs;
8364 	}
8365 
8366 	phba->sli4_hba.hba_eq_hdl = kcalloc(phba->cfg_irq_chann,
8367 					    sizeof(struct lpfc_hba_eq_hdl),
8368 					    GFP_KERNEL);
8369 	if (!phba->sli4_hba.hba_eq_hdl) {
8370 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8371 				"2572 Failed allocate memory for "
8372 				"fast-path per-EQ handle array\n");
8373 		rc = -ENOMEM;
8374 		goto out_free_fcf_rr_bmask;
8375 	}
8376 
8377 	phba->sli4_hba.cpu_map = kcalloc(phba->sli4_hba.num_possible_cpu,
8378 					sizeof(struct lpfc_vector_map_info),
8379 					GFP_KERNEL);
8380 	if (!phba->sli4_hba.cpu_map) {
8381 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8382 				"3327 Failed allocate memory for msi-x "
8383 				"interrupt vector mapping\n");
8384 		rc = -ENOMEM;
8385 		goto out_free_hba_eq_hdl;
8386 	}
8387 
8388 	phba->sli4_hba.eq_info = alloc_percpu(struct lpfc_eq_intr_info);
8389 	if (!phba->sli4_hba.eq_info) {
8390 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8391 				"3321 Failed allocation for per_cpu stats\n");
8392 		rc = -ENOMEM;
8393 		goto out_free_hba_cpu_map;
8394 	}
8395 
8396 	phba->sli4_hba.idle_stat = kcalloc(phba->sli4_hba.num_possible_cpu,
8397 					   sizeof(*phba->sli4_hba.idle_stat),
8398 					   GFP_KERNEL);
8399 	if (!phba->sli4_hba.idle_stat) {
8400 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8401 				"3390 Failed allocation for idle_stat\n");
8402 		rc = -ENOMEM;
8403 		goto out_free_hba_eq_info;
8404 	}
8405 
8406 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
8407 	phba->sli4_hba.c_stat = alloc_percpu(struct lpfc_hdwq_stat);
8408 	if (!phba->sli4_hba.c_stat) {
8409 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8410 				"3332 Failed allocating per cpu hdwq stats\n");
8411 		rc = -ENOMEM;
8412 		goto out_free_hba_idle_stat;
8413 	}
8414 #endif
8415 
8416 	phba->cmf_stat = alloc_percpu(struct lpfc_cgn_stat);
8417 	if (!phba->cmf_stat) {
8418 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8419 				"3331 Failed allocating per cpu cgn stats\n");
8420 		rc = -ENOMEM;
8421 		goto out_free_hba_hdwq_info;
8422 	}
8423 
8424 	/*
8425 	 * Enable sr-iov virtual functions if supported and configured
8426 	 * through the module parameter.
8427 	 */
8428 	if (phba->cfg_sriov_nr_virtfn > 0) {
8429 		rc = lpfc_sli_probe_sriov_nr_virtfn(phba,
8430 						 phba->cfg_sriov_nr_virtfn);
8431 		if (rc) {
8432 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
8433 					"3020 Requested number of SR-IOV "
8434 					"virtual functions (%d) is not "
8435 					"supported\n",
8436 					phba->cfg_sriov_nr_virtfn);
8437 			phba->cfg_sriov_nr_virtfn = 0;
8438 		}
8439 	}
8440 
8441 	return 0;
8442 
8443 out_free_hba_hdwq_info:
8444 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
8445 	free_percpu(phba->sli4_hba.c_stat);
8446 out_free_hba_idle_stat:
8447 #endif
8448 	kfree(phba->sli4_hba.idle_stat);
8449 out_free_hba_eq_info:
8450 	free_percpu(phba->sli4_hba.eq_info);
8451 out_free_hba_cpu_map:
8452 	kfree(phba->sli4_hba.cpu_map);
8453 out_free_hba_eq_hdl:
8454 	kfree(phba->sli4_hba.hba_eq_hdl);
8455 out_free_fcf_rr_bmask:
8456 	kfree(phba->fcf.fcf_rr_bmask);
8457 out_remove_rpi_hdrs:
8458 	lpfc_sli4_remove_rpi_hdrs(phba);
8459 out_free_active_sgl:
8460 	lpfc_free_active_sgl(phba);
8461 out_destroy_cq_event_pool:
8462 	lpfc_sli4_cq_event_pool_destroy(phba);
8463 out_free_cmd_rsp_buf:
8464 	dma_pool_destroy(phba->lpfc_cmd_rsp_buf_pool);
8465 	phba->lpfc_cmd_rsp_buf_pool = NULL;
8466 out_free_sg_dma_buf:
8467 	dma_pool_destroy(phba->lpfc_sg_dma_buf_pool);
8468 	phba->lpfc_sg_dma_buf_pool = NULL;
8469 out_free_bsmbx:
8470 	lpfc_destroy_bootstrap_mbox(phba);
8471 out_free_mem:
8472 	lpfc_mem_free(phba);
8473 out_destroy_workqueue:
8474 	destroy_workqueue(phba->wq);
8475 	phba->wq = NULL;
8476 	return rc;
8477 }
8478 
8479 /**
8480  * lpfc_sli4_driver_resource_unset - Unset drvr internal resources for SLI4 dev
8481  * @phba: pointer to lpfc hba data structure.
8482  *
8483  * This routine is invoked to unset the driver internal resources set up
8484  * specific for supporting the SLI-4 HBA device it attached to.
8485  **/
8486 static void
8487 lpfc_sli4_driver_resource_unset(struct lpfc_hba *phba)
8488 {
8489 	struct lpfc_fcf_conn_entry *conn_entry, *next_conn_entry;
8490 
8491 	free_percpu(phba->sli4_hba.eq_info);
8492 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
8493 	free_percpu(phba->sli4_hba.c_stat);
8494 #endif
8495 	free_percpu(phba->cmf_stat);
8496 	kfree(phba->sli4_hba.idle_stat);
8497 
8498 	/* Free memory allocated for msi-x interrupt vector to CPU mapping */
8499 	kfree(phba->sli4_hba.cpu_map);
8500 	phba->sli4_hba.num_possible_cpu = 0;
8501 	phba->sli4_hba.num_present_cpu = 0;
8502 	phba->sli4_hba.curr_disp_cpu = 0;
8503 	cpumask_clear(&phba->sli4_hba.irq_aff_mask);
8504 
8505 	/* Free memory allocated for fast-path work queue handles */
8506 	kfree(phba->sli4_hba.hba_eq_hdl);
8507 
8508 	/* Free the allocated rpi headers. */
8509 	lpfc_sli4_remove_rpi_hdrs(phba);
8510 	lpfc_sli4_remove_rpis(phba);
8511 
8512 	/* Free eligible FCF index bmask */
8513 	kfree(phba->fcf.fcf_rr_bmask);
8514 
8515 	/* Free the ELS sgl list */
8516 	lpfc_free_active_sgl(phba);
8517 	lpfc_free_els_sgl_list(phba);
8518 	lpfc_free_nvmet_sgl_list(phba);
8519 
8520 	/* Free the completion queue EQ event pool */
8521 	lpfc_sli4_cq_event_release_all(phba);
8522 	lpfc_sli4_cq_event_pool_destroy(phba);
8523 
8524 	/* Release resource identifiers. */
8525 	lpfc_sli4_dealloc_resource_identifiers(phba);
8526 
8527 	/* Free the bsmbx region. */
8528 	lpfc_destroy_bootstrap_mbox(phba);
8529 
8530 	/* Free the SLI Layer memory with SLI4 HBAs */
8531 	lpfc_mem_free_all(phba);
8532 
8533 	/* Free the current connect table */
8534 	list_for_each_entry_safe(conn_entry, next_conn_entry,
8535 		&phba->fcf_conn_rec_list, list) {
8536 		list_del_init(&conn_entry->list);
8537 		kfree(conn_entry);
8538 	}
8539 
8540 	return;
8541 }
8542 
8543 /**
8544  * lpfc_init_api_table_setup - Set up init api function jump table
8545  * @phba: The hba struct for which this call is being executed.
8546  * @dev_grp: The HBA PCI-Device group number.
8547  *
8548  * This routine sets up the device INIT interface API function jump table
8549  * in @phba struct.
8550  *
8551  * Returns: 0 - success, -ENODEV - failure.
8552  **/
8553 int
8554 lpfc_init_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
8555 {
8556 	phba->lpfc_hba_init_link = lpfc_hba_init_link;
8557 	phba->lpfc_hba_down_link = lpfc_hba_down_link;
8558 	phba->lpfc_selective_reset = lpfc_selective_reset;
8559 	switch (dev_grp) {
8560 	case LPFC_PCI_DEV_LP:
8561 		phba->lpfc_hba_down_post = lpfc_hba_down_post_s3;
8562 		phba->lpfc_handle_eratt = lpfc_handle_eratt_s3;
8563 		phba->lpfc_stop_port = lpfc_stop_port_s3;
8564 		break;
8565 	case LPFC_PCI_DEV_OC:
8566 		phba->lpfc_hba_down_post = lpfc_hba_down_post_s4;
8567 		phba->lpfc_handle_eratt = lpfc_handle_eratt_s4;
8568 		phba->lpfc_stop_port = lpfc_stop_port_s4;
8569 		break;
8570 	default:
8571 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8572 				"1431 Invalid HBA PCI-device group: 0x%x\n",
8573 				dev_grp);
8574 		return -ENODEV;
8575 	}
8576 	return 0;
8577 }
8578 
8579 /**
8580  * lpfc_setup_driver_resource_phase2 - Phase2 setup driver internal resources.
8581  * @phba: pointer to lpfc hba data structure.
8582  *
8583  * This routine is invoked to set up the driver internal resources after the
8584  * device specific resource setup to support the HBA device it attached to.
8585  *
8586  * Return codes
8587  * 	0 - successful
8588  * 	other values - error
8589  **/
8590 static int
8591 lpfc_setup_driver_resource_phase2(struct lpfc_hba *phba)
8592 {
8593 	int error;
8594 
8595 	/* Startup the kernel thread for this host adapter. */
8596 	phba->worker_thread = kthread_run(lpfc_do_work, phba,
8597 					  "lpfc_worker_%d", phba->brd_no);
8598 	if (IS_ERR(phba->worker_thread)) {
8599 		error = PTR_ERR(phba->worker_thread);
8600 		return error;
8601 	}
8602 
8603 	return 0;
8604 }
8605 
8606 /**
8607  * lpfc_unset_driver_resource_phase2 - Phase2 unset driver internal resources.
8608  * @phba: pointer to lpfc hba data structure.
8609  *
8610  * This routine is invoked to unset the driver internal resources set up after
8611  * the device specific resource setup for supporting the HBA device it
8612  * attached to.
8613  **/
8614 static void
8615 lpfc_unset_driver_resource_phase2(struct lpfc_hba *phba)
8616 {
8617 	if (phba->wq) {
8618 		destroy_workqueue(phba->wq);
8619 		phba->wq = NULL;
8620 	}
8621 
8622 	/* Stop kernel worker thread */
8623 	if (phba->worker_thread)
8624 		kthread_stop(phba->worker_thread);
8625 }
8626 
8627 /**
8628  * lpfc_free_iocb_list - Free iocb list.
8629  * @phba: pointer to lpfc hba data structure.
8630  *
8631  * This routine is invoked to free the driver's IOCB list and memory.
8632  **/
8633 void
8634 lpfc_free_iocb_list(struct lpfc_hba *phba)
8635 {
8636 	struct lpfc_iocbq *iocbq_entry = NULL, *iocbq_next = NULL;
8637 
8638 	spin_lock_irq(&phba->hbalock);
8639 	list_for_each_entry_safe(iocbq_entry, iocbq_next,
8640 				 &phba->lpfc_iocb_list, list) {
8641 		list_del(&iocbq_entry->list);
8642 		kfree(iocbq_entry);
8643 		phba->total_iocbq_bufs--;
8644 	}
8645 	spin_unlock_irq(&phba->hbalock);
8646 
8647 	return;
8648 }
8649 
8650 /**
8651  * lpfc_init_iocb_list - Allocate and initialize iocb list.
8652  * @phba: pointer to lpfc hba data structure.
8653  * @iocb_count: number of requested iocbs
8654  *
8655  * This routine is invoked to allocate and initizlize the driver's IOCB
8656  * list and set up the IOCB tag array accordingly.
8657  *
8658  * Return codes
8659  *	0 - successful
8660  *	other values - error
8661  **/
8662 int
8663 lpfc_init_iocb_list(struct lpfc_hba *phba, int iocb_count)
8664 {
8665 	struct lpfc_iocbq *iocbq_entry = NULL;
8666 	uint16_t iotag;
8667 	int i;
8668 
8669 	/* Initialize and populate the iocb list per host.  */
8670 	INIT_LIST_HEAD(&phba->lpfc_iocb_list);
8671 	for (i = 0; i < iocb_count; i++) {
8672 		iocbq_entry = kzalloc(sizeof(struct lpfc_iocbq), GFP_KERNEL);
8673 		if (iocbq_entry == NULL) {
8674 			printk(KERN_ERR "%s: only allocated %d iocbs of "
8675 				"expected %d count. Unloading driver.\n",
8676 				__func__, i, iocb_count);
8677 			goto out_free_iocbq;
8678 		}
8679 
8680 		iotag = lpfc_sli_next_iotag(phba, iocbq_entry);
8681 		if (iotag == 0) {
8682 			kfree(iocbq_entry);
8683 			printk(KERN_ERR "%s: failed to allocate IOTAG. "
8684 				"Unloading driver.\n", __func__);
8685 			goto out_free_iocbq;
8686 		}
8687 		iocbq_entry->sli4_lxritag = NO_XRI;
8688 		iocbq_entry->sli4_xritag = NO_XRI;
8689 
8690 		spin_lock_irq(&phba->hbalock);
8691 		list_add(&iocbq_entry->list, &phba->lpfc_iocb_list);
8692 		phba->total_iocbq_bufs++;
8693 		spin_unlock_irq(&phba->hbalock);
8694 	}
8695 
8696 	return 0;
8697 
8698 out_free_iocbq:
8699 	lpfc_free_iocb_list(phba);
8700 
8701 	return -ENOMEM;
8702 }
8703 
8704 /**
8705  * lpfc_free_sgl_list - Free a given sgl list.
8706  * @phba: pointer to lpfc hba data structure.
8707  * @sglq_list: pointer to the head of sgl list.
8708  *
8709  * This routine is invoked to free a give sgl list and memory.
8710  **/
8711 void
8712 lpfc_free_sgl_list(struct lpfc_hba *phba, struct list_head *sglq_list)
8713 {
8714 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
8715 
8716 	list_for_each_entry_safe(sglq_entry, sglq_next, sglq_list, list) {
8717 		list_del(&sglq_entry->list);
8718 		lpfc_mbuf_free(phba, sglq_entry->virt, sglq_entry->phys);
8719 		kfree(sglq_entry);
8720 	}
8721 }
8722 
8723 /**
8724  * lpfc_free_els_sgl_list - Free els sgl list.
8725  * @phba: pointer to lpfc hba data structure.
8726  *
8727  * This routine is invoked to free the driver's els sgl list and memory.
8728  **/
8729 static void
8730 lpfc_free_els_sgl_list(struct lpfc_hba *phba)
8731 {
8732 	LIST_HEAD(sglq_list);
8733 
8734 	/* Retrieve all els sgls from driver list */
8735 	spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
8736 	list_splice_init(&phba->sli4_hba.lpfc_els_sgl_list, &sglq_list);
8737 	spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
8738 
8739 	/* Now free the sgl list */
8740 	lpfc_free_sgl_list(phba, &sglq_list);
8741 }
8742 
8743 /**
8744  * lpfc_free_nvmet_sgl_list - Free nvmet sgl list.
8745  * @phba: pointer to lpfc hba data structure.
8746  *
8747  * This routine is invoked to free the driver's nvmet sgl list and memory.
8748  **/
8749 static void
8750 lpfc_free_nvmet_sgl_list(struct lpfc_hba *phba)
8751 {
8752 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
8753 	LIST_HEAD(sglq_list);
8754 
8755 	/* Retrieve all nvmet sgls from driver list */
8756 	spin_lock_irq(&phba->hbalock);
8757 	spin_lock(&phba->sli4_hba.sgl_list_lock);
8758 	list_splice_init(&phba->sli4_hba.lpfc_nvmet_sgl_list, &sglq_list);
8759 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
8760 	spin_unlock_irq(&phba->hbalock);
8761 
8762 	/* Now free the sgl list */
8763 	list_for_each_entry_safe(sglq_entry, sglq_next, &sglq_list, list) {
8764 		list_del(&sglq_entry->list);
8765 		lpfc_nvmet_buf_free(phba, sglq_entry->virt, sglq_entry->phys);
8766 		kfree(sglq_entry);
8767 	}
8768 
8769 	/* Update the nvmet_xri_cnt to reflect no current sgls.
8770 	 * The next initialization cycle sets the count and allocates
8771 	 * the sgls over again.
8772 	 */
8773 	phba->sli4_hba.nvmet_xri_cnt = 0;
8774 }
8775 
8776 /**
8777  * lpfc_init_active_sgl_array - Allocate the buf to track active ELS XRIs.
8778  * @phba: pointer to lpfc hba data structure.
8779  *
8780  * This routine is invoked to allocate the driver's active sgl memory.
8781  * This array will hold the sglq_entry's for active IOs.
8782  **/
8783 static int
8784 lpfc_init_active_sgl_array(struct lpfc_hba *phba)
8785 {
8786 	int size;
8787 	size = sizeof(struct lpfc_sglq *);
8788 	size *= phba->sli4_hba.max_cfg_param.max_xri;
8789 
8790 	phba->sli4_hba.lpfc_sglq_active_list =
8791 		kzalloc(size, GFP_KERNEL);
8792 	if (!phba->sli4_hba.lpfc_sglq_active_list)
8793 		return -ENOMEM;
8794 	return 0;
8795 }
8796 
8797 /**
8798  * lpfc_free_active_sgl - Free the buf that tracks active ELS XRIs.
8799  * @phba: pointer to lpfc hba data structure.
8800  *
8801  * This routine is invoked to walk through the array of active sglq entries
8802  * and free all of the resources.
8803  * This is just a place holder for now.
8804  **/
8805 static void
8806 lpfc_free_active_sgl(struct lpfc_hba *phba)
8807 {
8808 	kfree(phba->sli4_hba.lpfc_sglq_active_list);
8809 }
8810 
8811 /**
8812  * lpfc_init_sgl_list - Allocate and initialize sgl list.
8813  * @phba: pointer to lpfc hba data structure.
8814  *
8815  * This routine is invoked to allocate and initizlize the driver's sgl
8816  * list and set up the sgl xritag tag array accordingly.
8817  *
8818  **/
8819 static void
8820 lpfc_init_sgl_list(struct lpfc_hba *phba)
8821 {
8822 	/* Initialize and populate the sglq list per host/VF. */
8823 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_els_sgl_list);
8824 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_els_sgl_list);
8825 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_nvmet_sgl_list);
8826 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
8827 
8828 	/* els xri-sgl book keeping */
8829 	phba->sli4_hba.els_xri_cnt = 0;
8830 
8831 	/* nvme xri-buffer book keeping */
8832 	phba->sli4_hba.io_xri_cnt = 0;
8833 }
8834 
8835 /**
8836  * lpfc_sli4_init_rpi_hdrs - Post the rpi header memory region to the port
8837  * @phba: pointer to lpfc hba data structure.
8838  *
8839  * This routine is invoked to post rpi header templates to the
8840  * port for those SLI4 ports that do not support extents.  This routine
8841  * posts a PAGE_SIZE memory region to the port to hold up to
8842  * PAGE_SIZE modulo 64 rpi context headers.  This is an initialization routine
8843  * and should be called only when interrupts are disabled.
8844  *
8845  * Return codes
8846  * 	0 - successful
8847  *	-ERROR - otherwise.
8848  **/
8849 int
8850 lpfc_sli4_init_rpi_hdrs(struct lpfc_hba *phba)
8851 {
8852 	int rc = 0;
8853 	struct lpfc_rpi_hdr *rpi_hdr;
8854 
8855 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_rpi_hdr_list);
8856 	if (!phba->sli4_hba.rpi_hdrs_in_use)
8857 		return rc;
8858 	if (phba->sli4_hba.extents_in_use)
8859 		return -EIO;
8860 
8861 	rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
8862 	if (!rpi_hdr) {
8863 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8864 				"0391 Error during rpi post operation\n");
8865 		lpfc_sli4_remove_rpis(phba);
8866 		rc = -ENODEV;
8867 	}
8868 
8869 	return rc;
8870 }
8871 
8872 /**
8873  * lpfc_sli4_create_rpi_hdr - Allocate an rpi header memory region
8874  * @phba: pointer to lpfc hba data structure.
8875  *
8876  * This routine is invoked to allocate a single 4KB memory region to
8877  * support rpis and stores them in the phba.  This single region
8878  * provides support for up to 64 rpis.  The region is used globally
8879  * by the device.
8880  *
8881  * Returns:
8882  *   A valid rpi hdr on success.
8883  *   A NULL pointer on any failure.
8884  **/
8885 struct lpfc_rpi_hdr *
8886 lpfc_sli4_create_rpi_hdr(struct lpfc_hba *phba)
8887 {
8888 	uint16_t rpi_limit, curr_rpi_range;
8889 	struct lpfc_dmabuf *dmabuf;
8890 	struct lpfc_rpi_hdr *rpi_hdr;
8891 
8892 	/*
8893 	 * If the SLI4 port supports extents, posting the rpi header isn't
8894 	 * required.  Set the expected maximum count and let the actual value
8895 	 * get set when extents are fully allocated.
8896 	 */
8897 	if (!phba->sli4_hba.rpi_hdrs_in_use)
8898 		return NULL;
8899 	if (phba->sli4_hba.extents_in_use)
8900 		return NULL;
8901 
8902 	/* The limit on the logical index is just the max_rpi count. */
8903 	rpi_limit = phba->sli4_hba.max_cfg_param.max_rpi;
8904 
8905 	spin_lock_irq(&phba->hbalock);
8906 	/*
8907 	 * Establish the starting RPI in this header block.  The starting
8908 	 * rpi is normalized to a zero base because the physical rpi is
8909 	 * port based.
8910 	 */
8911 	curr_rpi_range = phba->sli4_hba.next_rpi;
8912 	spin_unlock_irq(&phba->hbalock);
8913 
8914 	/* Reached full RPI range */
8915 	if (curr_rpi_range == rpi_limit)
8916 		return NULL;
8917 
8918 	/*
8919 	 * First allocate the protocol header region for the port.  The
8920 	 * port expects a 4KB DMA-mapped memory region that is 4K aligned.
8921 	 */
8922 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
8923 	if (!dmabuf)
8924 		return NULL;
8925 
8926 	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
8927 					  LPFC_HDR_TEMPLATE_SIZE,
8928 					  &dmabuf->phys, GFP_KERNEL);
8929 	if (!dmabuf->virt) {
8930 		rpi_hdr = NULL;
8931 		goto err_free_dmabuf;
8932 	}
8933 
8934 	if (!IS_ALIGNED(dmabuf->phys, LPFC_HDR_TEMPLATE_SIZE)) {
8935 		rpi_hdr = NULL;
8936 		goto err_free_coherent;
8937 	}
8938 
8939 	/* Save the rpi header data for cleanup later. */
8940 	rpi_hdr = kzalloc(sizeof(struct lpfc_rpi_hdr), GFP_KERNEL);
8941 	if (!rpi_hdr)
8942 		goto err_free_coherent;
8943 
8944 	rpi_hdr->dmabuf = dmabuf;
8945 	rpi_hdr->len = LPFC_HDR_TEMPLATE_SIZE;
8946 	rpi_hdr->page_count = 1;
8947 	spin_lock_irq(&phba->hbalock);
8948 
8949 	/* The rpi_hdr stores the logical index only. */
8950 	rpi_hdr->start_rpi = curr_rpi_range;
8951 	rpi_hdr->next_rpi = phba->sli4_hba.next_rpi + LPFC_RPI_HDR_COUNT;
8952 	list_add_tail(&rpi_hdr->list, &phba->sli4_hba.lpfc_rpi_hdr_list);
8953 
8954 	spin_unlock_irq(&phba->hbalock);
8955 	return rpi_hdr;
8956 
8957  err_free_coherent:
8958 	dma_free_coherent(&phba->pcidev->dev, LPFC_HDR_TEMPLATE_SIZE,
8959 			  dmabuf->virt, dmabuf->phys);
8960  err_free_dmabuf:
8961 	kfree(dmabuf);
8962 	return NULL;
8963 }
8964 
8965 /**
8966  * lpfc_sli4_remove_rpi_hdrs - Remove all rpi header memory regions
8967  * @phba: pointer to lpfc hba data structure.
8968  *
8969  * This routine is invoked to remove all memory resources allocated
8970  * to support rpis for SLI4 ports not supporting extents. This routine
8971  * presumes the caller has released all rpis consumed by fabric or port
8972  * logins and is prepared to have the header pages removed.
8973  **/
8974 void
8975 lpfc_sli4_remove_rpi_hdrs(struct lpfc_hba *phba)
8976 {
8977 	struct lpfc_rpi_hdr *rpi_hdr, *next_rpi_hdr;
8978 
8979 	if (!phba->sli4_hba.rpi_hdrs_in_use)
8980 		goto exit;
8981 
8982 	list_for_each_entry_safe(rpi_hdr, next_rpi_hdr,
8983 				 &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
8984 		list_del(&rpi_hdr->list);
8985 		dma_free_coherent(&phba->pcidev->dev, rpi_hdr->len,
8986 				  rpi_hdr->dmabuf->virt, rpi_hdr->dmabuf->phys);
8987 		kfree(rpi_hdr->dmabuf);
8988 		kfree(rpi_hdr);
8989 	}
8990  exit:
8991 	/* There are no rpis available to the port now. */
8992 	phba->sli4_hba.next_rpi = 0;
8993 }
8994 
8995 /**
8996  * lpfc_hba_alloc - Allocate driver hba data structure for a device.
8997  * @pdev: pointer to pci device data structure.
8998  *
8999  * This routine is invoked to allocate the driver hba data structure for an
9000  * HBA device. If the allocation is successful, the phba reference to the
9001  * PCI device data structure is set.
9002  *
9003  * Return codes
9004  *      pointer to @phba - successful
9005  *      NULL - error
9006  **/
9007 static struct lpfc_hba *
9008 lpfc_hba_alloc(struct pci_dev *pdev)
9009 {
9010 	struct lpfc_hba *phba;
9011 
9012 	/* Allocate memory for HBA structure */
9013 	phba = kzalloc(sizeof(struct lpfc_hba), GFP_KERNEL);
9014 	if (!phba) {
9015 		dev_err(&pdev->dev, "failed to allocate hba struct\n");
9016 		return NULL;
9017 	}
9018 
9019 	/* Set reference to PCI device in HBA structure */
9020 	phba->pcidev = pdev;
9021 
9022 	/* Assign an unused board number */
9023 	phba->brd_no = lpfc_get_instance();
9024 	if (phba->brd_no < 0) {
9025 		kfree(phba);
9026 		return NULL;
9027 	}
9028 	phba->eratt_poll_interval = LPFC_ERATT_POLL_INTERVAL;
9029 
9030 	spin_lock_init(&phba->ct_ev_lock);
9031 	INIT_LIST_HEAD(&phba->ct_ev_waiters);
9032 
9033 	return phba;
9034 }
9035 
9036 /**
9037  * lpfc_hba_free - Free driver hba data structure with a device.
9038  * @phba: pointer to lpfc hba data structure.
9039  *
9040  * This routine is invoked to free the driver hba data structure with an
9041  * HBA device.
9042  **/
9043 static void
9044 lpfc_hba_free(struct lpfc_hba *phba)
9045 {
9046 	if (phba->sli_rev == LPFC_SLI_REV4)
9047 		kfree(phba->sli4_hba.hdwq);
9048 
9049 	/* Release the driver assigned board number */
9050 	idr_remove(&lpfc_hba_index, phba->brd_no);
9051 
9052 	/* Free memory allocated with sli3 rings */
9053 	kfree(phba->sli.sli3_ring);
9054 	phba->sli.sli3_ring = NULL;
9055 
9056 	kfree(phba);
9057 	return;
9058 }
9059 
9060 /**
9061  * lpfc_setup_fdmi_mask - Setup initial FDMI mask for HBA and Port attributes
9062  * @vport: pointer to lpfc vport data structure.
9063  *
9064  * This routine is will setup initial FDMI attribute masks for
9065  * FDMI2 or SmartSAN depending on module parameters. The driver will attempt
9066  * to get these attributes first before falling back, the attribute
9067  * fallback hierarchy is SmartSAN -> FDMI2 -> FMDI1
9068  **/
9069 void
9070 lpfc_setup_fdmi_mask(struct lpfc_vport *vport)
9071 {
9072 	struct lpfc_hba *phba = vport->phba;
9073 
9074 	set_bit(FC_ALLOW_FDMI, &vport->load_flag);
9075 	if (phba->cfg_enable_SmartSAN ||
9076 	    phba->cfg_fdmi_on == LPFC_FDMI_SUPPORT) {
9077 		/* Setup appropriate attribute masks */
9078 		vport->fdmi_hba_mask = LPFC_FDMI2_HBA_ATTR;
9079 		if (phba->cfg_enable_SmartSAN)
9080 			vport->fdmi_port_mask = LPFC_FDMI2_SMART_ATTR;
9081 		else
9082 			vport->fdmi_port_mask = LPFC_FDMI2_PORT_ATTR;
9083 	}
9084 
9085 	lpfc_printf_log(phba, KERN_INFO, LOG_DISCOVERY,
9086 			"6077 Setup FDMI mask: hba x%x port x%x\n",
9087 			vport->fdmi_hba_mask, vport->fdmi_port_mask);
9088 }
9089 
9090 /**
9091  * lpfc_create_shost - Create hba physical port with associated scsi host.
9092  * @phba: pointer to lpfc hba data structure.
9093  *
9094  * This routine is invoked to create HBA physical port and associate a SCSI
9095  * host with it.
9096  *
9097  * Return codes
9098  *      0 - successful
9099  *      other values - error
9100  **/
9101 static int
9102 lpfc_create_shost(struct lpfc_hba *phba)
9103 {
9104 	struct lpfc_vport *vport;
9105 	struct Scsi_Host  *shost;
9106 
9107 	/* Initialize HBA FC structure */
9108 	phba->fc_edtov = FF_DEF_EDTOV;
9109 	phba->fc_ratov = FF_DEF_RATOV;
9110 	phba->fc_altov = FF_DEF_ALTOV;
9111 	phba->fc_arbtov = FF_DEF_ARBTOV;
9112 
9113 	atomic_set(&phba->sdev_cnt, 0);
9114 	vport = lpfc_create_port(phba, phba->brd_no, &phba->pcidev->dev);
9115 	if (!vport)
9116 		return -ENODEV;
9117 
9118 	shost = lpfc_shost_from_vport(vport);
9119 	phba->pport = vport;
9120 
9121 	if (phba->nvmet_support) {
9122 		/* Only 1 vport (pport) will support NVME target */
9123 		phba->targetport = NULL;
9124 		phba->cfg_enable_fc4_type = LPFC_ENABLE_NVME;
9125 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_NVME_DISC,
9126 				"6076 NVME Target Found\n");
9127 	}
9128 
9129 	lpfc_debugfs_initialize(vport);
9130 	/* Put reference to SCSI host to driver's device private data */
9131 	pci_set_drvdata(phba->pcidev, shost);
9132 
9133 	lpfc_setup_fdmi_mask(vport);
9134 
9135 	/*
9136 	 * At this point we are fully registered with PSA. In addition,
9137 	 * any initial discovery should be completed.
9138 	 */
9139 	return 0;
9140 }
9141 
9142 /**
9143  * lpfc_destroy_shost - Destroy hba physical port with associated scsi host.
9144  * @phba: pointer to lpfc hba data structure.
9145  *
9146  * This routine is invoked to destroy HBA physical port and the associated
9147  * SCSI host.
9148  **/
9149 static void
9150 lpfc_destroy_shost(struct lpfc_hba *phba)
9151 {
9152 	struct lpfc_vport *vport = phba->pport;
9153 
9154 	/* Destroy physical port that associated with the SCSI host */
9155 	destroy_port(vport);
9156 
9157 	return;
9158 }
9159 
9160 /**
9161  * lpfc_setup_bg - Setup Block guard structures and debug areas.
9162  * @phba: pointer to lpfc hba data structure.
9163  * @shost: the shost to be used to detect Block guard settings.
9164  *
9165  * This routine sets up the local Block guard protocol settings for @shost.
9166  * This routine also allocates memory for debugging bg buffers.
9167  **/
9168 static void
9169 lpfc_setup_bg(struct lpfc_hba *phba, struct Scsi_Host *shost)
9170 {
9171 	uint32_t old_mask;
9172 	uint32_t old_guard;
9173 
9174 	if (phba->cfg_prot_mask && phba->cfg_prot_guard) {
9175 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9176 				"1478 Registering BlockGuard with the "
9177 				"SCSI layer\n");
9178 
9179 		old_mask = phba->cfg_prot_mask;
9180 		old_guard = phba->cfg_prot_guard;
9181 
9182 		/* Only allow supported values */
9183 		phba->cfg_prot_mask &= (SHOST_DIF_TYPE1_PROTECTION |
9184 			SHOST_DIX_TYPE0_PROTECTION |
9185 			SHOST_DIX_TYPE1_PROTECTION);
9186 		phba->cfg_prot_guard &= (SHOST_DIX_GUARD_IP |
9187 					 SHOST_DIX_GUARD_CRC);
9188 
9189 		/* DIF Type 1 protection for profiles AST1/C1 is end to end */
9190 		if (phba->cfg_prot_mask == SHOST_DIX_TYPE1_PROTECTION)
9191 			phba->cfg_prot_mask |= SHOST_DIF_TYPE1_PROTECTION;
9192 
9193 		if (phba->cfg_prot_mask && phba->cfg_prot_guard) {
9194 			if ((old_mask != phba->cfg_prot_mask) ||
9195 				(old_guard != phba->cfg_prot_guard))
9196 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9197 					"1475 Registering BlockGuard with the "
9198 					"SCSI layer: mask %d  guard %d\n",
9199 					phba->cfg_prot_mask,
9200 					phba->cfg_prot_guard);
9201 
9202 			scsi_host_set_prot(shost, phba->cfg_prot_mask);
9203 			scsi_host_set_guard(shost, phba->cfg_prot_guard);
9204 		} else
9205 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9206 				"1479 Not Registering BlockGuard with the SCSI "
9207 				"layer, Bad protection parameters: %d %d\n",
9208 				old_mask, old_guard);
9209 	}
9210 }
9211 
9212 /**
9213  * lpfc_post_init_setup - Perform necessary device post initialization setup.
9214  * @phba: pointer to lpfc hba data structure.
9215  *
9216  * This routine is invoked to perform all the necessary post initialization
9217  * setup for the device.
9218  **/
9219 static void
9220 lpfc_post_init_setup(struct lpfc_hba *phba)
9221 {
9222 	struct Scsi_Host  *shost;
9223 	struct lpfc_adapter_event_header adapter_event;
9224 
9225 	/* Get the default values for Model Name and Description */
9226 	lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
9227 
9228 	/*
9229 	 * hba setup may have changed the hba_queue_depth so we need to
9230 	 * adjust the value of can_queue.
9231 	 */
9232 	shost = pci_get_drvdata(phba->pcidev);
9233 	shost->can_queue = phba->cfg_hba_queue_depth - 10;
9234 
9235 	lpfc_host_attrib_init(shost);
9236 
9237 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
9238 		spin_lock_irq(shost->host_lock);
9239 		lpfc_poll_start_timer(phba);
9240 		spin_unlock_irq(shost->host_lock);
9241 	}
9242 
9243 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9244 			"0428 Perform SCSI scan\n");
9245 	/* Send board arrival event to upper layer */
9246 	adapter_event.event_type = FC_REG_ADAPTER_EVENT;
9247 	adapter_event.subcategory = LPFC_EVENT_ARRIVAL;
9248 	fc_host_post_vendor_event(shost, fc_get_event_number(),
9249 				  sizeof(adapter_event),
9250 				  (char *) &adapter_event,
9251 				  LPFC_NL_VENDOR_ID);
9252 	return;
9253 }
9254 
9255 /**
9256  * lpfc_sli_pci_mem_setup - Setup SLI3 HBA PCI memory space.
9257  * @phba: pointer to lpfc hba data structure.
9258  *
9259  * This routine is invoked to set up the PCI device memory space for device
9260  * with SLI-3 interface spec.
9261  *
9262  * Return codes
9263  * 	0 - successful
9264  * 	other values - error
9265  **/
9266 static int
9267 lpfc_sli_pci_mem_setup(struct lpfc_hba *phba)
9268 {
9269 	struct pci_dev *pdev = phba->pcidev;
9270 	unsigned long bar0map_len, bar2map_len;
9271 	int i, hbq_count;
9272 	void *ptr;
9273 	int error;
9274 
9275 	if (!pdev)
9276 		return -ENODEV;
9277 
9278 	/* Set the device DMA mask size */
9279 	error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
9280 	if (error)
9281 		error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32));
9282 	if (error)
9283 		return error;
9284 	error = -ENODEV;
9285 
9286 	/* Get the bus address of Bar0 and Bar2 and the number of bytes
9287 	 * required by each mapping.
9288 	 */
9289 	phba->pci_bar0_map = pci_resource_start(pdev, 0);
9290 	bar0map_len = pci_resource_len(pdev, 0);
9291 
9292 	phba->pci_bar2_map = pci_resource_start(pdev, 2);
9293 	bar2map_len = pci_resource_len(pdev, 2);
9294 
9295 	/* Map HBA SLIM to a kernel virtual address. */
9296 	phba->slim_memmap_p = ioremap(phba->pci_bar0_map, bar0map_len);
9297 	if (!phba->slim_memmap_p) {
9298 		dev_printk(KERN_ERR, &pdev->dev,
9299 			   "ioremap failed for SLIM memory.\n");
9300 		goto out;
9301 	}
9302 
9303 	/* Map HBA Control Registers to a kernel virtual address. */
9304 	phba->ctrl_regs_memmap_p = ioremap(phba->pci_bar2_map, bar2map_len);
9305 	if (!phba->ctrl_regs_memmap_p) {
9306 		dev_printk(KERN_ERR, &pdev->dev,
9307 			   "ioremap failed for HBA control registers.\n");
9308 		goto out_iounmap_slim;
9309 	}
9310 
9311 	/* Allocate memory for SLI-2 structures */
9312 	phba->slim2p.virt = dma_alloc_coherent(&pdev->dev, SLI2_SLIM_SIZE,
9313 					       &phba->slim2p.phys, GFP_KERNEL);
9314 	if (!phba->slim2p.virt)
9315 		goto out_iounmap;
9316 
9317 	phba->mbox = phba->slim2p.virt + offsetof(struct lpfc_sli2_slim, mbx);
9318 	phba->mbox_ext = (phba->slim2p.virt +
9319 		offsetof(struct lpfc_sli2_slim, mbx_ext_words));
9320 	phba->pcb = (phba->slim2p.virt + offsetof(struct lpfc_sli2_slim, pcb));
9321 	phba->IOCBs = (phba->slim2p.virt +
9322 		       offsetof(struct lpfc_sli2_slim, IOCBs));
9323 
9324 	phba->hbqslimp.virt = dma_alloc_coherent(&pdev->dev,
9325 						 lpfc_sli_hbq_size(),
9326 						 &phba->hbqslimp.phys,
9327 						 GFP_KERNEL);
9328 	if (!phba->hbqslimp.virt)
9329 		goto out_free_slim;
9330 
9331 	hbq_count = lpfc_sli_hbq_count();
9332 	ptr = phba->hbqslimp.virt;
9333 	for (i = 0; i < hbq_count; ++i) {
9334 		phba->hbqs[i].hbq_virt = ptr;
9335 		INIT_LIST_HEAD(&phba->hbqs[i].hbq_buffer_list);
9336 		ptr += (lpfc_hbq_defs[i]->entry_count *
9337 			sizeof(struct lpfc_hbq_entry));
9338 	}
9339 	phba->hbqs[LPFC_ELS_HBQ].hbq_alloc_buffer = lpfc_els_hbq_alloc;
9340 	phba->hbqs[LPFC_ELS_HBQ].hbq_free_buffer = lpfc_els_hbq_free;
9341 
9342 	memset(phba->hbqslimp.virt, 0, lpfc_sli_hbq_size());
9343 
9344 	phba->MBslimaddr = phba->slim_memmap_p;
9345 	phba->HAregaddr = phba->ctrl_regs_memmap_p + HA_REG_OFFSET;
9346 	phba->CAregaddr = phba->ctrl_regs_memmap_p + CA_REG_OFFSET;
9347 	phba->HSregaddr = phba->ctrl_regs_memmap_p + HS_REG_OFFSET;
9348 	phba->HCregaddr = phba->ctrl_regs_memmap_p + HC_REG_OFFSET;
9349 
9350 	return 0;
9351 
9352 out_free_slim:
9353 	dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
9354 			  phba->slim2p.virt, phba->slim2p.phys);
9355 out_iounmap:
9356 	iounmap(phba->ctrl_regs_memmap_p);
9357 out_iounmap_slim:
9358 	iounmap(phba->slim_memmap_p);
9359 out:
9360 	return error;
9361 }
9362 
9363 /**
9364  * lpfc_sli_pci_mem_unset - Unset SLI3 HBA PCI memory space.
9365  * @phba: pointer to lpfc hba data structure.
9366  *
9367  * This routine is invoked to unset the PCI device memory space for device
9368  * with SLI-3 interface spec.
9369  **/
9370 static void
9371 lpfc_sli_pci_mem_unset(struct lpfc_hba *phba)
9372 {
9373 	struct pci_dev *pdev;
9374 
9375 	/* Obtain PCI device reference */
9376 	if (!phba->pcidev)
9377 		return;
9378 	else
9379 		pdev = phba->pcidev;
9380 
9381 	/* Free coherent DMA memory allocated */
9382 	dma_free_coherent(&pdev->dev, lpfc_sli_hbq_size(),
9383 			  phba->hbqslimp.virt, phba->hbqslimp.phys);
9384 	dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
9385 			  phba->slim2p.virt, phba->slim2p.phys);
9386 
9387 	/* I/O memory unmap */
9388 	iounmap(phba->ctrl_regs_memmap_p);
9389 	iounmap(phba->slim_memmap_p);
9390 
9391 	return;
9392 }
9393 
9394 /**
9395  * lpfc_sli4_post_status_check - Wait for SLI4 POST done and check status
9396  * @phba: pointer to lpfc hba data structure.
9397  *
9398  * This routine is invoked to wait for SLI4 device Power On Self Test (POST)
9399  * done and check status.
9400  *
9401  * Return 0 if successful, otherwise -ENODEV.
9402  **/
9403 int
9404 lpfc_sli4_post_status_check(struct lpfc_hba *phba)
9405 {
9406 	struct lpfc_register portsmphr_reg, uerrlo_reg, uerrhi_reg;
9407 	struct lpfc_register reg_data;
9408 	int i, port_error = 0;
9409 	uint32_t if_type;
9410 
9411 	memset(&portsmphr_reg, 0, sizeof(portsmphr_reg));
9412 	memset(&reg_data, 0, sizeof(reg_data));
9413 	if (!phba->sli4_hba.PSMPHRregaddr)
9414 		return -ENODEV;
9415 
9416 	/* Wait up to 30 seconds for the SLI Port POST done and ready */
9417 	for (i = 0; i < 3000; i++) {
9418 		if (lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
9419 			&portsmphr_reg.word0) ||
9420 			(bf_get(lpfc_port_smphr_perr, &portsmphr_reg))) {
9421 			/* Port has a fatal POST error, break out */
9422 			port_error = -ENODEV;
9423 			break;
9424 		}
9425 		if (LPFC_POST_STAGE_PORT_READY ==
9426 		    bf_get(lpfc_port_smphr_port_status, &portsmphr_reg))
9427 			break;
9428 		msleep(10);
9429 	}
9430 
9431 	/*
9432 	 * If there was a port error during POST, then don't proceed with
9433 	 * other register reads as the data may not be valid.  Just exit.
9434 	 */
9435 	if (port_error) {
9436 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9437 			"1408 Port Failed POST - portsmphr=0x%x, "
9438 			"perr=x%x, sfi=x%x, nip=x%x, ipc=x%x, scr1=x%x, "
9439 			"scr2=x%x, hscratch=x%x, pstatus=x%x\n",
9440 			portsmphr_reg.word0,
9441 			bf_get(lpfc_port_smphr_perr, &portsmphr_reg),
9442 			bf_get(lpfc_port_smphr_sfi, &portsmphr_reg),
9443 			bf_get(lpfc_port_smphr_nip, &portsmphr_reg),
9444 			bf_get(lpfc_port_smphr_ipc, &portsmphr_reg),
9445 			bf_get(lpfc_port_smphr_scr1, &portsmphr_reg),
9446 			bf_get(lpfc_port_smphr_scr2, &portsmphr_reg),
9447 			bf_get(lpfc_port_smphr_host_scratch, &portsmphr_reg),
9448 			bf_get(lpfc_port_smphr_port_status, &portsmphr_reg));
9449 	} else {
9450 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9451 				"2534 Device Info: SLIFamily=0x%x, "
9452 				"SLIRev=0x%x, IFType=0x%x, SLIHint_1=0x%x, "
9453 				"SLIHint_2=0x%x, FT=0x%x\n",
9454 				bf_get(lpfc_sli_intf_sli_family,
9455 				       &phba->sli4_hba.sli_intf),
9456 				bf_get(lpfc_sli_intf_slirev,
9457 				       &phba->sli4_hba.sli_intf),
9458 				bf_get(lpfc_sli_intf_if_type,
9459 				       &phba->sli4_hba.sli_intf),
9460 				bf_get(lpfc_sli_intf_sli_hint1,
9461 				       &phba->sli4_hba.sli_intf),
9462 				bf_get(lpfc_sli_intf_sli_hint2,
9463 				       &phba->sli4_hba.sli_intf),
9464 				bf_get(lpfc_sli_intf_func_type,
9465 				       &phba->sli4_hba.sli_intf));
9466 		/*
9467 		 * Check for other Port errors during the initialization
9468 		 * process.  Fail the load if the port did not come up
9469 		 * correctly.
9470 		 */
9471 		if_type = bf_get(lpfc_sli_intf_if_type,
9472 				 &phba->sli4_hba.sli_intf);
9473 		switch (if_type) {
9474 		case LPFC_SLI_INTF_IF_TYPE_0:
9475 			phba->sli4_hba.ue_mask_lo =
9476 			      readl(phba->sli4_hba.u.if_type0.UEMASKLOregaddr);
9477 			phba->sli4_hba.ue_mask_hi =
9478 			      readl(phba->sli4_hba.u.if_type0.UEMASKHIregaddr);
9479 			uerrlo_reg.word0 =
9480 			      readl(phba->sli4_hba.u.if_type0.UERRLOregaddr);
9481 			uerrhi_reg.word0 =
9482 				readl(phba->sli4_hba.u.if_type0.UERRHIregaddr);
9483 			if ((~phba->sli4_hba.ue_mask_lo & uerrlo_reg.word0) ||
9484 			    (~phba->sli4_hba.ue_mask_hi & uerrhi_reg.word0)) {
9485 				lpfc_printf_log(phba, KERN_ERR,
9486 						LOG_TRACE_EVENT,
9487 						"1422 Unrecoverable Error "
9488 						"Detected during POST "
9489 						"uerr_lo_reg=0x%x, "
9490 						"uerr_hi_reg=0x%x, "
9491 						"ue_mask_lo_reg=0x%x, "
9492 						"ue_mask_hi_reg=0x%x\n",
9493 						uerrlo_reg.word0,
9494 						uerrhi_reg.word0,
9495 						phba->sli4_hba.ue_mask_lo,
9496 						phba->sli4_hba.ue_mask_hi);
9497 				port_error = -ENODEV;
9498 			}
9499 			break;
9500 		case LPFC_SLI_INTF_IF_TYPE_2:
9501 		case LPFC_SLI_INTF_IF_TYPE_6:
9502 			/* Final checks.  The port status should be clean. */
9503 			if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
9504 				&reg_data.word0) ||
9505 				lpfc_sli4_unrecoverable_port(&reg_data)) {
9506 				phba->work_status[0] =
9507 					readl(phba->sli4_hba.u.if_type2.
9508 					      ERR1regaddr);
9509 				phba->work_status[1] =
9510 					readl(phba->sli4_hba.u.if_type2.
9511 					      ERR2regaddr);
9512 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9513 					"2888 Unrecoverable port error "
9514 					"following POST: port status reg "
9515 					"0x%x, port_smphr reg 0x%x, "
9516 					"error 1=0x%x, error 2=0x%x\n",
9517 					reg_data.word0,
9518 					portsmphr_reg.word0,
9519 					phba->work_status[0],
9520 					phba->work_status[1]);
9521 				port_error = -ENODEV;
9522 				break;
9523 			}
9524 
9525 			if (lpfc_pldv_detect &&
9526 			    bf_get(lpfc_sli_intf_sli_family,
9527 				   &phba->sli4_hba.sli_intf) ==
9528 					LPFC_SLI_INTF_FAMILY_G6)
9529 				pci_write_config_byte(phba->pcidev,
9530 						      LPFC_SLI_INTF, CFG_PLD);
9531 			break;
9532 		case LPFC_SLI_INTF_IF_TYPE_1:
9533 		default:
9534 			break;
9535 		}
9536 	}
9537 	return port_error;
9538 }
9539 
9540 /**
9541  * lpfc_sli4_bar0_register_memmap - Set up SLI4 BAR0 register memory map.
9542  * @phba: pointer to lpfc hba data structure.
9543  * @if_type:  The SLI4 interface type getting configured.
9544  *
9545  * This routine is invoked to set up SLI4 BAR0 PCI config space register
9546  * memory map.
9547  **/
9548 static void
9549 lpfc_sli4_bar0_register_memmap(struct lpfc_hba *phba, uint32_t if_type)
9550 {
9551 	switch (if_type) {
9552 	case LPFC_SLI_INTF_IF_TYPE_0:
9553 		phba->sli4_hba.u.if_type0.UERRLOregaddr =
9554 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UERR_STATUS_LO;
9555 		phba->sli4_hba.u.if_type0.UERRHIregaddr =
9556 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UERR_STATUS_HI;
9557 		phba->sli4_hba.u.if_type0.UEMASKLOregaddr =
9558 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UE_MASK_LO;
9559 		phba->sli4_hba.u.if_type0.UEMASKHIregaddr =
9560 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UE_MASK_HI;
9561 		phba->sli4_hba.SLIINTFregaddr =
9562 			phba->sli4_hba.conf_regs_memmap_p + LPFC_SLI_INTF;
9563 		break;
9564 	case LPFC_SLI_INTF_IF_TYPE_2:
9565 		phba->sli4_hba.u.if_type2.EQDregaddr =
9566 			phba->sli4_hba.conf_regs_memmap_p +
9567 						LPFC_CTL_PORT_EQ_DELAY_OFFSET;
9568 		phba->sli4_hba.u.if_type2.ERR1regaddr =
9569 			phba->sli4_hba.conf_regs_memmap_p +
9570 						LPFC_CTL_PORT_ER1_OFFSET;
9571 		phba->sli4_hba.u.if_type2.ERR2regaddr =
9572 			phba->sli4_hba.conf_regs_memmap_p +
9573 						LPFC_CTL_PORT_ER2_OFFSET;
9574 		phba->sli4_hba.u.if_type2.CTRLregaddr =
9575 			phba->sli4_hba.conf_regs_memmap_p +
9576 						LPFC_CTL_PORT_CTL_OFFSET;
9577 		phba->sli4_hba.u.if_type2.STATUSregaddr =
9578 			phba->sli4_hba.conf_regs_memmap_p +
9579 						LPFC_CTL_PORT_STA_OFFSET;
9580 		phba->sli4_hba.SLIINTFregaddr =
9581 			phba->sli4_hba.conf_regs_memmap_p + LPFC_SLI_INTF;
9582 		phba->sli4_hba.PSMPHRregaddr =
9583 			phba->sli4_hba.conf_regs_memmap_p +
9584 						LPFC_CTL_PORT_SEM_OFFSET;
9585 		phba->sli4_hba.RQDBregaddr =
9586 			phba->sli4_hba.conf_regs_memmap_p +
9587 						LPFC_ULP0_RQ_DOORBELL;
9588 		phba->sli4_hba.WQDBregaddr =
9589 			phba->sli4_hba.conf_regs_memmap_p +
9590 						LPFC_ULP0_WQ_DOORBELL;
9591 		phba->sli4_hba.CQDBregaddr =
9592 			phba->sli4_hba.conf_regs_memmap_p + LPFC_EQCQ_DOORBELL;
9593 		phba->sli4_hba.EQDBregaddr = phba->sli4_hba.CQDBregaddr;
9594 		phba->sli4_hba.MQDBregaddr =
9595 			phba->sli4_hba.conf_regs_memmap_p + LPFC_MQ_DOORBELL;
9596 		phba->sli4_hba.BMBXregaddr =
9597 			phba->sli4_hba.conf_regs_memmap_p + LPFC_BMBX;
9598 		break;
9599 	case LPFC_SLI_INTF_IF_TYPE_6:
9600 		phba->sli4_hba.u.if_type2.EQDregaddr =
9601 			phba->sli4_hba.conf_regs_memmap_p +
9602 						LPFC_CTL_PORT_EQ_DELAY_OFFSET;
9603 		phba->sli4_hba.u.if_type2.ERR1regaddr =
9604 			phba->sli4_hba.conf_regs_memmap_p +
9605 						LPFC_CTL_PORT_ER1_OFFSET;
9606 		phba->sli4_hba.u.if_type2.ERR2regaddr =
9607 			phba->sli4_hba.conf_regs_memmap_p +
9608 						LPFC_CTL_PORT_ER2_OFFSET;
9609 		phba->sli4_hba.u.if_type2.CTRLregaddr =
9610 			phba->sli4_hba.conf_regs_memmap_p +
9611 						LPFC_CTL_PORT_CTL_OFFSET;
9612 		phba->sli4_hba.u.if_type2.STATUSregaddr =
9613 			phba->sli4_hba.conf_regs_memmap_p +
9614 						LPFC_CTL_PORT_STA_OFFSET;
9615 		phba->sli4_hba.PSMPHRregaddr =
9616 			phba->sli4_hba.conf_regs_memmap_p +
9617 						LPFC_CTL_PORT_SEM_OFFSET;
9618 		phba->sli4_hba.BMBXregaddr =
9619 			phba->sli4_hba.conf_regs_memmap_p + LPFC_BMBX;
9620 		break;
9621 	case LPFC_SLI_INTF_IF_TYPE_1:
9622 	default:
9623 		dev_printk(KERN_ERR, &phba->pcidev->dev,
9624 			   "FATAL - unsupported SLI4 interface type - %d\n",
9625 			   if_type);
9626 		break;
9627 	}
9628 }
9629 
9630 /**
9631  * lpfc_sli4_bar1_register_memmap - Set up SLI4 BAR1 register memory map.
9632  * @phba: pointer to lpfc hba data structure.
9633  * @if_type: sli if type to operate on.
9634  *
9635  * This routine is invoked to set up SLI4 BAR1 register memory map.
9636  **/
9637 static void
9638 lpfc_sli4_bar1_register_memmap(struct lpfc_hba *phba, uint32_t if_type)
9639 {
9640 	switch (if_type) {
9641 	case LPFC_SLI_INTF_IF_TYPE_0:
9642 		phba->sli4_hba.PSMPHRregaddr =
9643 			phba->sli4_hba.ctrl_regs_memmap_p +
9644 			LPFC_SLIPORT_IF0_SMPHR;
9645 		phba->sli4_hba.ISRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
9646 			LPFC_HST_ISR0;
9647 		phba->sli4_hba.IMRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
9648 			LPFC_HST_IMR0;
9649 		phba->sli4_hba.ISCRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
9650 			LPFC_HST_ISCR0;
9651 		break;
9652 	case LPFC_SLI_INTF_IF_TYPE_6:
9653 		phba->sli4_hba.RQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9654 			LPFC_IF6_RQ_DOORBELL;
9655 		phba->sli4_hba.WQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9656 			LPFC_IF6_WQ_DOORBELL;
9657 		phba->sli4_hba.CQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9658 			LPFC_IF6_CQ_DOORBELL;
9659 		phba->sli4_hba.EQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9660 			LPFC_IF6_EQ_DOORBELL;
9661 		phba->sli4_hba.MQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9662 			LPFC_IF6_MQ_DOORBELL;
9663 		break;
9664 	case LPFC_SLI_INTF_IF_TYPE_2:
9665 	case LPFC_SLI_INTF_IF_TYPE_1:
9666 	default:
9667 		dev_err(&phba->pcidev->dev,
9668 			   "FATAL - unsupported SLI4 interface type - %d\n",
9669 			   if_type);
9670 		break;
9671 	}
9672 }
9673 
9674 /**
9675  * lpfc_sli4_bar2_register_memmap - Set up SLI4 BAR2 register memory map.
9676  * @phba: pointer to lpfc hba data structure.
9677  * @vf: virtual function number
9678  *
9679  * This routine is invoked to set up SLI4 BAR2 doorbell register memory map
9680  * based on the given viftual function number, @vf.
9681  *
9682  * Return 0 if successful, otherwise -ENODEV.
9683  **/
9684 static int
9685 lpfc_sli4_bar2_register_memmap(struct lpfc_hba *phba, uint32_t vf)
9686 {
9687 	if (vf > LPFC_VIR_FUNC_MAX)
9688 		return -ENODEV;
9689 
9690 	phba->sli4_hba.RQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9691 				vf * LPFC_VFR_PAGE_SIZE +
9692 					LPFC_ULP0_RQ_DOORBELL);
9693 	phba->sli4_hba.WQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9694 				vf * LPFC_VFR_PAGE_SIZE +
9695 					LPFC_ULP0_WQ_DOORBELL);
9696 	phba->sli4_hba.CQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9697 				vf * LPFC_VFR_PAGE_SIZE +
9698 					LPFC_EQCQ_DOORBELL);
9699 	phba->sli4_hba.EQDBregaddr = phba->sli4_hba.CQDBregaddr;
9700 	phba->sli4_hba.MQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9701 				vf * LPFC_VFR_PAGE_SIZE + LPFC_MQ_DOORBELL);
9702 	phba->sli4_hba.BMBXregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9703 				vf * LPFC_VFR_PAGE_SIZE + LPFC_BMBX);
9704 	return 0;
9705 }
9706 
9707 /**
9708  * lpfc_create_bootstrap_mbox - Create the bootstrap mailbox
9709  * @phba: pointer to lpfc hba data structure.
9710  *
9711  * This routine is invoked to create the bootstrap mailbox
9712  * region consistent with the SLI-4 interface spec.  This
9713  * routine allocates all memory necessary to communicate
9714  * mailbox commands to the port and sets up all alignment
9715  * needs.  No locks are expected to be held when calling
9716  * this routine.
9717  *
9718  * Return codes
9719  * 	0 - successful
9720  * 	-ENOMEM - could not allocated memory.
9721  **/
9722 static int
9723 lpfc_create_bootstrap_mbox(struct lpfc_hba *phba)
9724 {
9725 	uint32_t bmbx_size;
9726 	struct lpfc_dmabuf *dmabuf;
9727 	struct dma_address *dma_address;
9728 	uint32_t pa_addr;
9729 	uint64_t phys_addr;
9730 
9731 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
9732 	if (!dmabuf)
9733 		return -ENOMEM;
9734 
9735 	/*
9736 	 * The bootstrap mailbox region is comprised of 2 parts
9737 	 * plus an alignment restriction of 16 bytes.
9738 	 */
9739 	bmbx_size = sizeof(struct lpfc_bmbx_create) + (LPFC_ALIGN_16_BYTE - 1);
9740 	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev, bmbx_size,
9741 					  &dmabuf->phys, GFP_KERNEL);
9742 	if (!dmabuf->virt) {
9743 		kfree(dmabuf);
9744 		return -ENOMEM;
9745 	}
9746 
9747 	/*
9748 	 * Initialize the bootstrap mailbox pointers now so that the register
9749 	 * operations are simple later.  The mailbox dma address is required
9750 	 * to be 16-byte aligned.  Also align the virtual memory as each
9751 	 * maibox is copied into the bmbx mailbox region before issuing the
9752 	 * command to the port.
9753 	 */
9754 	phba->sli4_hba.bmbx.dmabuf = dmabuf;
9755 	phba->sli4_hba.bmbx.bmbx_size = bmbx_size;
9756 
9757 	phba->sli4_hba.bmbx.avirt = PTR_ALIGN(dmabuf->virt,
9758 					      LPFC_ALIGN_16_BYTE);
9759 	phba->sli4_hba.bmbx.aphys = ALIGN(dmabuf->phys,
9760 					      LPFC_ALIGN_16_BYTE);
9761 
9762 	/*
9763 	 * Set the high and low physical addresses now.  The SLI4 alignment
9764 	 * requirement is 16 bytes and the mailbox is posted to the port
9765 	 * as two 30-bit addresses.  The other data is a bit marking whether
9766 	 * the 30-bit address is the high or low address.
9767 	 * Upcast bmbx aphys to 64bits so shift instruction compiles
9768 	 * clean on 32 bit machines.
9769 	 */
9770 	dma_address = &phba->sli4_hba.bmbx.dma_address;
9771 	phys_addr = (uint64_t)phba->sli4_hba.bmbx.aphys;
9772 	pa_addr = (uint32_t) ((phys_addr >> 34) & 0x3fffffff);
9773 	dma_address->addr_hi = (uint32_t) ((pa_addr << 2) |
9774 					   LPFC_BMBX_BIT1_ADDR_HI);
9775 
9776 	pa_addr = (uint32_t) ((phba->sli4_hba.bmbx.aphys >> 4) & 0x3fffffff);
9777 	dma_address->addr_lo = (uint32_t) ((pa_addr << 2) |
9778 					   LPFC_BMBX_BIT1_ADDR_LO);
9779 	return 0;
9780 }
9781 
9782 /**
9783  * lpfc_destroy_bootstrap_mbox - Destroy all bootstrap mailbox resources
9784  * @phba: pointer to lpfc hba data structure.
9785  *
9786  * This routine is invoked to teardown the bootstrap mailbox
9787  * region and release all host resources. This routine requires
9788  * the caller to ensure all mailbox commands recovered, no
9789  * additional mailbox comands are sent, and interrupts are disabled
9790  * before calling this routine.
9791  *
9792  **/
9793 static void
9794 lpfc_destroy_bootstrap_mbox(struct lpfc_hba *phba)
9795 {
9796 	dma_free_coherent(&phba->pcidev->dev,
9797 			  phba->sli4_hba.bmbx.bmbx_size,
9798 			  phba->sli4_hba.bmbx.dmabuf->virt,
9799 			  phba->sli4_hba.bmbx.dmabuf->phys);
9800 
9801 	kfree(phba->sli4_hba.bmbx.dmabuf);
9802 	memset(&phba->sli4_hba.bmbx, 0, sizeof(struct lpfc_bmbx));
9803 }
9804 
9805 static const char * const lpfc_topo_to_str[] = {
9806 	"Loop then P2P",
9807 	"Loopback",
9808 	"P2P Only",
9809 	"Unsupported",
9810 	"Loop Only",
9811 	"Unsupported",
9812 	"P2P then Loop",
9813 };
9814 
9815 #define	LINK_FLAGS_DEF	0x0
9816 #define	LINK_FLAGS_P2P	0x1
9817 #define	LINK_FLAGS_LOOP	0x2
9818 /**
9819  * lpfc_map_topology - Map the topology read from READ_CONFIG
9820  * @phba: pointer to lpfc hba data structure.
9821  * @rd_config: pointer to read config data
9822  *
9823  * This routine is invoked to map the topology values as read
9824  * from the read config mailbox command. If the persistent
9825  * topology feature is supported, the firmware will provide the
9826  * saved topology information to be used in INIT_LINK
9827  **/
9828 static void
9829 lpfc_map_topology(struct lpfc_hba *phba, struct lpfc_mbx_read_config *rd_config)
9830 {
9831 	u8 ptv, tf, pt;
9832 
9833 	ptv = bf_get(lpfc_mbx_rd_conf_ptv, rd_config);
9834 	tf = bf_get(lpfc_mbx_rd_conf_tf, rd_config);
9835 	pt = bf_get(lpfc_mbx_rd_conf_pt, rd_config);
9836 
9837 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9838 			"2027 Read Config Data : ptv:0x%x, tf:0x%x pt:0x%x",
9839 			 ptv, tf, pt);
9840 	if (!ptv) {
9841 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9842 				"2019 FW does not support persistent topology "
9843 				"Using driver parameter defined value [%s]",
9844 				lpfc_topo_to_str[phba->cfg_topology]);
9845 		return;
9846 	}
9847 	/* FW supports persistent topology - override module parameter value */
9848 	set_bit(HBA_PERSISTENT_TOPO, &phba->hba_flag);
9849 
9850 	/* if ASIC_GEN_NUM >= 0xC) */
9851 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
9852 		    LPFC_SLI_INTF_IF_TYPE_6) ||
9853 	    (bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf) ==
9854 		    LPFC_SLI_INTF_FAMILY_G6)) {
9855 		if (!tf)
9856 			phba->cfg_topology = ((pt == LINK_FLAGS_LOOP)
9857 					? FLAGS_TOPOLOGY_MODE_LOOP
9858 					: FLAGS_TOPOLOGY_MODE_PT_PT);
9859 		else
9860 			clear_bit(HBA_PERSISTENT_TOPO, &phba->hba_flag);
9861 	} else { /* G5 */
9862 		if (tf)
9863 			/* If topology failover set - pt is '0' or '1' */
9864 			phba->cfg_topology = (pt ? FLAGS_TOPOLOGY_MODE_PT_LOOP :
9865 					      FLAGS_TOPOLOGY_MODE_LOOP_PT);
9866 		else
9867 			phba->cfg_topology = ((pt == LINK_FLAGS_P2P)
9868 					? FLAGS_TOPOLOGY_MODE_PT_PT
9869 					: FLAGS_TOPOLOGY_MODE_LOOP);
9870 	}
9871 	if (test_bit(HBA_PERSISTENT_TOPO, &phba->hba_flag))
9872 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9873 				"2020 Using persistent topology value [%s]",
9874 				lpfc_topo_to_str[phba->cfg_topology]);
9875 	else
9876 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9877 				"2021 Invalid topology values from FW "
9878 				"Using driver parameter defined value [%s]",
9879 				lpfc_topo_to_str[phba->cfg_topology]);
9880 }
9881 
9882 /**
9883  * lpfc_sli4_read_config - Get the config parameters.
9884  * @phba: pointer to lpfc hba data structure.
9885  *
9886  * This routine is invoked to read the configuration parameters from the HBA.
9887  * The configuration parameters are used to set the base and maximum values
9888  * for RPI's XRI's VPI's VFI's and FCFIs. These values also affect the resource
9889  * allocation for the port.
9890  *
9891  * Return codes
9892  * 	0 - successful
9893  * 	-ENOMEM - No available memory
9894  *      -EIO - The mailbox failed to complete successfully.
9895  **/
9896 int
9897 lpfc_sli4_read_config(struct lpfc_hba *phba)
9898 {
9899 	LPFC_MBOXQ_t *pmb;
9900 	struct lpfc_mbx_read_config *rd_config;
9901 	union  lpfc_sli4_cfg_shdr *shdr;
9902 	uint32_t shdr_status, shdr_add_status;
9903 	struct lpfc_mbx_get_func_cfg *get_func_cfg;
9904 	struct lpfc_rsrc_desc_fcfcoe *desc;
9905 	char *pdesc_0;
9906 	uint16_t forced_link_speed;
9907 	uint32_t if_type, qmin, fawwpn;
9908 	int length, i, rc = 0, rc2;
9909 
9910 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
9911 	if (!pmb) {
9912 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9913 				"2011 Unable to allocate memory for issuing "
9914 				"SLI_CONFIG_SPECIAL mailbox command\n");
9915 		return -ENOMEM;
9916 	}
9917 
9918 	lpfc_read_config(phba, pmb);
9919 
9920 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
9921 	if (rc != MBX_SUCCESS) {
9922 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9923 				"2012 Mailbox failed , mbxCmd x%x "
9924 				"READ_CONFIG, mbxStatus x%x\n",
9925 				bf_get(lpfc_mqe_command, &pmb->u.mqe),
9926 				bf_get(lpfc_mqe_status, &pmb->u.mqe));
9927 		rc = -EIO;
9928 	} else {
9929 		rd_config = &pmb->u.mqe.un.rd_config;
9930 		if (bf_get(lpfc_mbx_rd_conf_lnk_ldv, rd_config)) {
9931 			phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL;
9932 			phba->sli4_hba.lnk_info.lnk_tp =
9933 				bf_get(lpfc_mbx_rd_conf_lnk_type, rd_config);
9934 			phba->sli4_hba.lnk_info.lnk_no =
9935 				bf_get(lpfc_mbx_rd_conf_lnk_numb, rd_config);
9936 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9937 					"3081 lnk_type:%d, lnk_numb:%d\n",
9938 					phba->sli4_hba.lnk_info.lnk_tp,
9939 					phba->sli4_hba.lnk_info.lnk_no);
9940 		} else
9941 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9942 					"3082 Mailbox (x%x) returned ldv:x0\n",
9943 					bf_get(lpfc_mqe_command, &pmb->u.mqe));
9944 		if (bf_get(lpfc_mbx_rd_conf_bbscn_def, rd_config)) {
9945 			phba->bbcredit_support = 1;
9946 			phba->sli4_hba.bbscn_params.word0 = rd_config->word8;
9947 		}
9948 
9949 		fawwpn = bf_get(lpfc_mbx_rd_conf_fawwpn, rd_config);
9950 
9951 		if (fawwpn) {
9952 			lpfc_printf_log(phba, KERN_INFO,
9953 					LOG_INIT | LOG_DISCOVERY,
9954 					"2702 READ_CONFIG: FA-PWWN is "
9955 					"configured on\n");
9956 			phba->sli4_hba.fawwpn_flag |= LPFC_FAWWPN_CONFIG;
9957 		} else {
9958 			/* Clear FW configured flag, preserve driver flag */
9959 			phba->sli4_hba.fawwpn_flag &= ~LPFC_FAWWPN_CONFIG;
9960 		}
9961 
9962 		phba->sli4_hba.conf_trunk =
9963 			bf_get(lpfc_mbx_rd_conf_trunk, rd_config);
9964 		phba->sli4_hba.extents_in_use =
9965 			bf_get(lpfc_mbx_rd_conf_extnts_inuse, rd_config);
9966 
9967 		phba->sli4_hba.max_cfg_param.max_xri =
9968 			bf_get(lpfc_mbx_rd_conf_xri_count, rd_config);
9969 		/* Reduce resource usage in kdump environment */
9970 		if (is_kdump_kernel() &&
9971 		    phba->sli4_hba.max_cfg_param.max_xri > 512)
9972 			phba->sli4_hba.max_cfg_param.max_xri = 512;
9973 		phba->sli4_hba.max_cfg_param.xri_base =
9974 			bf_get(lpfc_mbx_rd_conf_xri_base, rd_config);
9975 		phba->sli4_hba.max_cfg_param.max_vpi =
9976 			bf_get(lpfc_mbx_rd_conf_vpi_count, rd_config);
9977 		/* Limit the max we support */
9978 		if (phba->sli4_hba.max_cfg_param.max_vpi > LPFC_MAX_VPORTS)
9979 			phba->sli4_hba.max_cfg_param.max_vpi = LPFC_MAX_VPORTS;
9980 		phba->sli4_hba.max_cfg_param.vpi_base =
9981 			bf_get(lpfc_mbx_rd_conf_vpi_base, rd_config);
9982 		phba->sli4_hba.max_cfg_param.max_rpi =
9983 			bf_get(lpfc_mbx_rd_conf_rpi_count, rd_config);
9984 		phba->sli4_hba.max_cfg_param.rpi_base =
9985 			bf_get(lpfc_mbx_rd_conf_rpi_base, rd_config);
9986 		phba->sli4_hba.max_cfg_param.max_vfi =
9987 			bf_get(lpfc_mbx_rd_conf_vfi_count, rd_config);
9988 		phba->sli4_hba.max_cfg_param.vfi_base =
9989 			bf_get(lpfc_mbx_rd_conf_vfi_base, rd_config);
9990 		phba->sli4_hba.max_cfg_param.max_fcfi =
9991 			bf_get(lpfc_mbx_rd_conf_fcfi_count, rd_config);
9992 		phba->sli4_hba.max_cfg_param.max_eq =
9993 			bf_get(lpfc_mbx_rd_conf_eq_count, rd_config);
9994 		phba->sli4_hba.max_cfg_param.max_rq =
9995 			bf_get(lpfc_mbx_rd_conf_rq_count, rd_config);
9996 		phba->sli4_hba.max_cfg_param.max_wq =
9997 			bf_get(lpfc_mbx_rd_conf_wq_count, rd_config);
9998 		phba->sli4_hba.max_cfg_param.max_cq =
9999 			bf_get(lpfc_mbx_rd_conf_cq_count, rd_config);
10000 		phba->lmt = bf_get(lpfc_mbx_rd_conf_lmt, rd_config);
10001 		phba->sli4_hba.next_xri = phba->sli4_hba.max_cfg_param.xri_base;
10002 		phba->vpi_base = phba->sli4_hba.max_cfg_param.vpi_base;
10003 		phba->vfi_base = phba->sli4_hba.max_cfg_param.vfi_base;
10004 		phba->max_vpi = (phba->sli4_hba.max_cfg_param.max_vpi > 0) ?
10005 				(phba->sli4_hba.max_cfg_param.max_vpi - 1) : 0;
10006 		phba->max_vports = phba->max_vpi;
10007 
10008 		/* Next decide on FPIN or Signal E2E CGN support
10009 		 * For congestion alarms and warnings valid combination are:
10010 		 * 1. FPIN alarms / FPIN warnings
10011 		 * 2. Signal alarms / Signal warnings
10012 		 * 3. FPIN alarms / Signal warnings
10013 		 * 4. Signal alarms / FPIN warnings
10014 		 *
10015 		 * Initialize the adapter frequency to 100 mSecs
10016 		 */
10017 		phba->cgn_reg_fpin = LPFC_CGN_FPIN_BOTH;
10018 		phba->cgn_reg_signal = EDC_CG_SIG_NOTSUPPORTED;
10019 		phba->cgn_sig_freq = lpfc_fabric_cgn_frequency;
10020 
10021 		if (lpfc_use_cgn_signal) {
10022 			if (bf_get(lpfc_mbx_rd_conf_wcs, rd_config)) {
10023 				phba->cgn_reg_signal = EDC_CG_SIG_WARN_ONLY;
10024 				phba->cgn_reg_fpin &= ~LPFC_CGN_FPIN_WARN;
10025 			}
10026 			if (bf_get(lpfc_mbx_rd_conf_acs, rd_config)) {
10027 				/* MUST support both alarm and warning
10028 				 * because EDC does not support alarm alone.
10029 				 */
10030 				if (phba->cgn_reg_signal !=
10031 				    EDC_CG_SIG_WARN_ONLY) {
10032 					/* Must support both or none */
10033 					phba->cgn_reg_fpin = LPFC_CGN_FPIN_BOTH;
10034 					phba->cgn_reg_signal =
10035 						EDC_CG_SIG_NOTSUPPORTED;
10036 				} else {
10037 					phba->cgn_reg_signal =
10038 						EDC_CG_SIG_WARN_ALARM;
10039 					phba->cgn_reg_fpin =
10040 						LPFC_CGN_FPIN_NONE;
10041 				}
10042 			}
10043 		}
10044 
10045 		/* Set the congestion initial signal and fpin values. */
10046 		phba->cgn_init_reg_fpin = phba->cgn_reg_fpin;
10047 		phba->cgn_init_reg_signal = phba->cgn_reg_signal;
10048 
10049 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
10050 				"6446 READ_CONFIG reg_sig x%x reg_fpin:x%x\n",
10051 				phba->cgn_reg_signal, phba->cgn_reg_fpin);
10052 
10053 		lpfc_map_topology(phba, rd_config);
10054 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10055 				"2003 cfg params Extents? %d "
10056 				"XRI(B:%d M:%d), "
10057 				"VPI(B:%d M:%d) "
10058 				"VFI(B:%d M:%d) "
10059 				"RPI(B:%d M:%d) "
10060 				"FCFI:%d EQ:%d CQ:%d WQ:%d RQ:%d lmt:x%x\n",
10061 				phba->sli4_hba.extents_in_use,
10062 				phba->sli4_hba.max_cfg_param.xri_base,
10063 				phba->sli4_hba.max_cfg_param.max_xri,
10064 				phba->sli4_hba.max_cfg_param.vpi_base,
10065 				phba->sli4_hba.max_cfg_param.max_vpi,
10066 				phba->sli4_hba.max_cfg_param.vfi_base,
10067 				phba->sli4_hba.max_cfg_param.max_vfi,
10068 				phba->sli4_hba.max_cfg_param.rpi_base,
10069 				phba->sli4_hba.max_cfg_param.max_rpi,
10070 				phba->sli4_hba.max_cfg_param.max_fcfi,
10071 				phba->sli4_hba.max_cfg_param.max_eq,
10072 				phba->sli4_hba.max_cfg_param.max_cq,
10073 				phba->sli4_hba.max_cfg_param.max_wq,
10074 				phba->sli4_hba.max_cfg_param.max_rq,
10075 				phba->lmt);
10076 
10077 		/*
10078 		 * Calculate queue resources based on how
10079 		 * many WQ/CQ/EQs are available.
10080 		 */
10081 		qmin = phba->sli4_hba.max_cfg_param.max_wq;
10082 		if (phba->sli4_hba.max_cfg_param.max_cq < qmin)
10083 			qmin = phba->sli4_hba.max_cfg_param.max_cq;
10084 		/*
10085 		 * Reserve 4 (ELS, NVME LS, MBOX, plus one extra) and
10086 		 * the remainder can be used for NVME / FCP.
10087 		 */
10088 		qmin -= 4;
10089 		if (phba->sli4_hba.max_cfg_param.max_eq < qmin)
10090 			qmin = phba->sli4_hba.max_cfg_param.max_eq;
10091 
10092 		/* Check to see if there is enough for default cfg */
10093 		if ((phba->cfg_irq_chann > qmin) ||
10094 		    (phba->cfg_hdw_queue > qmin)) {
10095 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10096 					"2005 Reducing Queues - "
10097 					"FW resource limitation: "
10098 					"WQ %d CQ %d EQ %d: min %d: "
10099 					"IRQ %d HDWQ %d\n",
10100 					phba->sli4_hba.max_cfg_param.max_wq,
10101 					phba->sli4_hba.max_cfg_param.max_cq,
10102 					phba->sli4_hba.max_cfg_param.max_eq,
10103 					qmin, phba->cfg_irq_chann,
10104 					phba->cfg_hdw_queue);
10105 
10106 			if (phba->cfg_irq_chann > qmin)
10107 				phba->cfg_irq_chann = qmin;
10108 			if (phba->cfg_hdw_queue > qmin)
10109 				phba->cfg_hdw_queue = qmin;
10110 		}
10111 	}
10112 
10113 	if (rc)
10114 		goto read_cfg_out;
10115 
10116 	/* Update link speed if forced link speed is supported */
10117 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
10118 	if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
10119 		forced_link_speed =
10120 			bf_get(lpfc_mbx_rd_conf_link_speed, rd_config);
10121 		if (forced_link_speed) {
10122 			set_bit(HBA_FORCED_LINK_SPEED, &phba->hba_flag);
10123 
10124 			switch (forced_link_speed) {
10125 			case LINK_SPEED_1G:
10126 				phba->cfg_link_speed =
10127 					LPFC_USER_LINK_SPEED_1G;
10128 				break;
10129 			case LINK_SPEED_2G:
10130 				phba->cfg_link_speed =
10131 					LPFC_USER_LINK_SPEED_2G;
10132 				break;
10133 			case LINK_SPEED_4G:
10134 				phba->cfg_link_speed =
10135 					LPFC_USER_LINK_SPEED_4G;
10136 				break;
10137 			case LINK_SPEED_8G:
10138 				phba->cfg_link_speed =
10139 					LPFC_USER_LINK_SPEED_8G;
10140 				break;
10141 			case LINK_SPEED_10G:
10142 				phba->cfg_link_speed =
10143 					LPFC_USER_LINK_SPEED_10G;
10144 				break;
10145 			case LINK_SPEED_16G:
10146 				phba->cfg_link_speed =
10147 					LPFC_USER_LINK_SPEED_16G;
10148 				break;
10149 			case LINK_SPEED_32G:
10150 				phba->cfg_link_speed =
10151 					LPFC_USER_LINK_SPEED_32G;
10152 				break;
10153 			case LINK_SPEED_64G:
10154 				phba->cfg_link_speed =
10155 					LPFC_USER_LINK_SPEED_64G;
10156 				break;
10157 			case 0xffff:
10158 				phba->cfg_link_speed =
10159 					LPFC_USER_LINK_SPEED_AUTO;
10160 				break;
10161 			default:
10162 				lpfc_printf_log(phba, KERN_ERR,
10163 						LOG_TRACE_EVENT,
10164 						"0047 Unrecognized link "
10165 						"speed : %d\n",
10166 						forced_link_speed);
10167 				phba->cfg_link_speed =
10168 					LPFC_USER_LINK_SPEED_AUTO;
10169 			}
10170 		}
10171 	}
10172 
10173 	/* Reset the DFT_HBA_Q_DEPTH to the max xri  */
10174 	length = phba->sli4_hba.max_cfg_param.max_xri -
10175 			lpfc_sli4_get_els_iocb_cnt(phba);
10176 	if (phba->cfg_hba_queue_depth > length) {
10177 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
10178 				"3361 HBA queue depth changed from %d to %d\n",
10179 				phba->cfg_hba_queue_depth, length);
10180 		phba->cfg_hba_queue_depth = length;
10181 	}
10182 
10183 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) <
10184 	    LPFC_SLI_INTF_IF_TYPE_2)
10185 		goto read_cfg_out;
10186 
10187 	/* get the pf# and vf# for SLI4 if_type 2 port */
10188 	length = (sizeof(struct lpfc_mbx_get_func_cfg) -
10189 		  sizeof(struct lpfc_sli4_cfg_mhdr));
10190 	lpfc_sli4_config(phba, pmb, LPFC_MBOX_SUBSYSTEM_COMMON,
10191 			 LPFC_MBOX_OPCODE_GET_FUNCTION_CONFIG,
10192 			 length, LPFC_SLI4_MBX_EMBED);
10193 
10194 	rc2 = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
10195 	shdr = (union lpfc_sli4_cfg_shdr *)
10196 				&pmb->u.mqe.un.sli4_config.header.cfg_shdr;
10197 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
10198 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
10199 	if (rc2 || shdr_status || shdr_add_status) {
10200 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10201 				"3026 Mailbox failed , mbxCmd x%x "
10202 				"GET_FUNCTION_CONFIG, mbxStatus x%x\n",
10203 				bf_get(lpfc_mqe_command, &pmb->u.mqe),
10204 				bf_get(lpfc_mqe_status, &pmb->u.mqe));
10205 		goto read_cfg_out;
10206 	}
10207 
10208 	/* search for fc_fcoe resrouce descriptor */
10209 	get_func_cfg = &pmb->u.mqe.un.get_func_cfg;
10210 
10211 	pdesc_0 = (char *)&get_func_cfg->func_cfg.desc[0];
10212 	desc = (struct lpfc_rsrc_desc_fcfcoe *)pdesc_0;
10213 	length = bf_get(lpfc_rsrc_desc_fcfcoe_length, desc);
10214 	if (length == LPFC_RSRC_DESC_TYPE_FCFCOE_V0_RSVD)
10215 		length = LPFC_RSRC_DESC_TYPE_FCFCOE_V0_LENGTH;
10216 	else if (length != LPFC_RSRC_DESC_TYPE_FCFCOE_V1_LENGTH)
10217 		goto read_cfg_out;
10218 
10219 	for (i = 0; i < LPFC_RSRC_DESC_MAX_NUM; i++) {
10220 		desc = (struct lpfc_rsrc_desc_fcfcoe *)(pdesc_0 + length * i);
10221 		if (LPFC_RSRC_DESC_TYPE_FCFCOE ==
10222 		    bf_get(lpfc_rsrc_desc_fcfcoe_type, desc)) {
10223 			phba->sli4_hba.iov.pf_number =
10224 				bf_get(lpfc_rsrc_desc_fcfcoe_pfnum, desc);
10225 			phba->sli4_hba.iov.vf_number =
10226 				bf_get(lpfc_rsrc_desc_fcfcoe_vfnum, desc);
10227 			break;
10228 		}
10229 	}
10230 
10231 	if (i < LPFC_RSRC_DESC_MAX_NUM)
10232 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10233 				"3027 GET_FUNCTION_CONFIG: pf_number:%d, "
10234 				"vf_number:%d\n", phba->sli4_hba.iov.pf_number,
10235 				phba->sli4_hba.iov.vf_number);
10236 	else
10237 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10238 				"3028 GET_FUNCTION_CONFIG: failed to find "
10239 				"Resource Descriptor:x%x\n",
10240 				LPFC_RSRC_DESC_TYPE_FCFCOE);
10241 
10242 read_cfg_out:
10243 	mempool_free(pmb, phba->mbox_mem_pool);
10244 	return rc;
10245 }
10246 
10247 /**
10248  * lpfc_setup_endian_order - Write endian order to an SLI4 if_type 0 port.
10249  * @phba: pointer to lpfc hba data structure.
10250  *
10251  * This routine is invoked to setup the port-side endian order when
10252  * the port if_type is 0.  This routine has no function for other
10253  * if_types.
10254  *
10255  * Return codes
10256  * 	0 - successful
10257  * 	-ENOMEM - No available memory
10258  *      -EIO - The mailbox failed to complete successfully.
10259  **/
10260 static int
10261 lpfc_setup_endian_order(struct lpfc_hba *phba)
10262 {
10263 	LPFC_MBOXQ_t *mboxq;
10264 	uint32_t if_type, rc = 0;
10265 	uint32_t endian_mb_data[2] = {HOST_ENDIAN_LOW_WORD0,
10266 				      HOST_ENDIAN_HIGH_WORD1};
10267 
10268 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
10269 	switch (if_type) {
10270 	case LPFC_SLI_INTF_IF_TYPE_0:
10271 		mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
10272 						       GFP_KERNEL);
10273 		if (!mboxq) {
10274 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10275 					"0492 Unable to allocate memory for "
10276 					"issuing SLI_CONFIG_SPECIAL mailbox "
10277 					"command\n");
10278 			return -ENOMEM;
10279 		}
10280 
10281 		/*
10282 		 * The SLI4_CONFIG_SPECIAL mailbox command requires the first
10283 		 * two words to contain special data values and no other data.
10284 		 */
10285 		memset(mboxq, 0, sizeof(LPFC_MBOXQ_t));
10286 		memcpy(&mboxq->u.mqe, &endian_mb_data, sizeof(endian_mb_data));
10287 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
10288 		if (rc != MBX_SUCCESS) {
10289 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10290 					"0493 SLI_CONFIG_SPECIAL mailbox "
10291 					"failed with status x%x\n",
10292 					rc);
10293 			rc = -EIO;
10294 		}
10295 		mempool_free(mboxq, phba->mbox_mem_pool);
10296 		break;
10297 	case LPFC_SLI_INTF_IF_TYPE_6:
10298 	case LPFC_SLI_INTF_IF_TYPE_2:
10299 	case LPFC_SLI_INTF_IF_TYPE_1:
10300 	default:
10301 		break;
10302 	}
10303 	return rc;
10304 }
10305 
10306 /**
10307  * lpfc_sli4_queue_verify - Verify and update EQ counts
10308  * @phba: pointer to lpfc hba data structure.
10309  *
10310  * This routine is invoked to check the user settable queue counts for EQs.
10311  * After this routine is called the counts will be set to valid values that
10312  * adhere to the constraints of the system's interrupt vectors and the port's
10313  * queue resources.
10314  *
10315  * Return codes
10316  *      0 - successful
10317  *      -ENOMEM - No available memory
10318  **/
10319 static int
10320 lpfc_sli4_queue_verify(struct lpfc_hba *phba)
10321 {
10322 	/*
10323 	 * Sanity check for configured queue parameters against the run-time
10324 	 * device parameters
10325 	 */
10326 
10327 	if (phba->nvmet_support) {
10328 		if (phba->cfg_hdw_queue < phba->cfg_nvmet_mrq)
10329 			phba->cfg_nvmet_mrq = phba->cfg_hdw_queue;
10330 		if (phba->cfg_nvmet_mrq > LPFC_NVMET_MRQ_MAX)
10331 			phba->cfg_nvmet_mrq = LPFC_NVMET_MRQ_MAX;
10332 	}
10333 
10334 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10335 			"2574 IO channels: hdwQ %d IRQ %d MRQ: %d\n",
10336 			phba->cfg_hdw_queue, phba->cfg_irq_chann,
10337 			phba->cfg_nvmet_mrq);
10338 
10339 	/* Get EQ depth from module parameter, fake the default for now */
10340 	phba->sli4_hba.eq_esize = LPFC_EQE_SIZE_4B;
10341 	phba->sli4_hba.eq_ecount = LPFC_EQE_DEF_COUNT;
10342 
10343 	/* Get CQ depth from module parameter, fake the default for now */
10344 	phba->sli4_hba.cq_esize = LPFC_CQE_SIZE;
10345 	phba->sli4_hba.cq_ecount = LPFC_CQE_DEF_COUNT;
10346 	return 0;
10347 }
10348 
10349 static int
10350 lpfc_alloc_io_wq_cq(struct lpfc_hba *phba, int idx)
10351 {
10352 	struct lpfc_queue *qdesc;
10353 	u32 wqesize;
10354 	int cpu;
10355 
10356 	cpu = lpfc_find_cpu_handle(phba, idx, LPFC_FIND_BY_HDWQ);
10357 	/* Create Fast Path IO CQs */
10358 	if (phba->enab_exp_wqcq_pages)
10359 		/* Increase the CQ size when WQEs contain an embedded cdb */
10360 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_EXPANDED_PAGE_SIZE,
10361 					      phba->sli4_hba.cq_esize,
10362 					      LPFC_CQE_EXP_COUNT, cpu);
10363 
10364 	else
10365 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10366 					      phba->sli4_hba.cq_esize,
10367 					      phba->sli4_hba.cq_ecount, cpu);
10368 	if (!qdesc) {
10369 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10370 				"0499 Failed allocate fast-path IO CQ (%d)\n",
10371 				idx);
10372 		return 1;
10373 	}
10374 	qdesc->qe_valid = 1;
10375 	qdesc->hdwq = idx;
10376 	qdesc->chann = cpu;
10377 	phba->sli4_hba.hdwq[idx].io_cq = qdesc;
10378 
10379 	/* Create Fast Path IO WQs */
10380 	if (phba->enab_exp_wqcq_pages) {
10381 		/* Increase the WQ size when WQEs contain an embedded cdb */
10382 		wqesize = (phba->fcp_embed_io) ?
10383 			LPFC_WQE128_SIZE : phba->sli4_hba.wq_esize;
10384 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_EXPANDED_PAGE_SIZE,
10385 					      wqesize,
10386 					      LPFC_WQE_EXP_COUNT, cpu);
10387 	} else
10388 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10389 					      phba->sli4_hba.wq_esize,
10390 					      phba->sli4_hba.wq_ecount, cpu);
10391 
10392 	if (!qdesc) {
10393 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10394 				"0503 Failed allocate fast-path IO WQ (%d)\n",
10395 				idx);
10396 		return 1;
10397 	}
10398 	qdesc->hdwq = idx;
10399 	qdesc->chann = cpu;
10400 	phba->sli4_hba.hdwq[idx].io_wq = qdesc;
10401 	list_add_tail(&qdesc->wq_list, &phba->sli4_hba.lpfc_wq_list);
10402 	return 0;
10403 }
10404 
10405 /**
10406  * lpfc_sli4_queue_create - Create all the SLI4 queues
10407  * @phba: pointer to lpfc hba data structure.
10408  *
10409  * This routine is invoked to allocate all the SLI4 queues for the FCoE HBA
10410  * operation. For each SLI4 queue type, the parameters such as queue entry
10411  * count (queue depth) shall be taken from the module parameter. For now,
10412  * we just use some constant number as place holder.
10413  *
10414  * Return codes
10415  *      0 - successful
10416  *      -ENOMEM - No availble memory
10417  *      -EIO - The mailbox failed to complete successfully.
10418  **/
10419 int
10420 lpfc_sli4_queue_create(struct lpfc_hba *phba)
10421 {
10422 	struct lpfc_queue *qdesc;
10423 	int idx, cpu, eqcpu;
10424 	struct lpfc_sli4_hdw_queue *qp;
10425 	struct lpfc_vector_map_info *cpup;
10426 	struct lpfc_vector_map_info *eqcpup;
10427 	struct lpfc_eq_intr_info *eqi;
10428 	u32 wqesize;
10429 
10430 	/*
10431 	 * Create HBA Record arrays.
10432 	 * Both NVME and FCP will share that same vectors / EQs
10433 	 */
10434 	phba->sli4_hba.mq_esize = LPFC_MQE_SIZE;
10435 	phba->sli4_hba.mq_ecount = LPFC_MQE_DEF_COUNT;
10436 	phba->sli4_hba.wq_esize = LPFC_WQE_SIZE;
10437 	phba->sli4_hba.wq_ecount = LPFC_WQE_DEF_COUNT;
10438 	phba->sli4_hba.rq_esize = LPFC_RQE_SIZE;
10439 	phba->sli4_hba.rq_ecount = LPFC_RQE_DEF_COUNT;
10440 	phba->sli4_hba.eq_esize = LPFC_EQE_SIZE_4B;
10441 	phba->sli4_hba.eq_ecount = LPFC_EQE_DEF_COUNT;
10442 	phba->sli4_hba.cq_esize = LPFC_CQE_SIZE;
10443 	phba->sli4_hba.cq_ecount = LPFC_CQE_DEF_COUNT;
10444 
10445 	if (!phba->sli4_hba.hdwq) {
10446 		phba->sli4_hba.hdwq = kcalloc(
10447 			phba->cfg_hdw_queue, sizeof(struct lpfc_sli4_hdw_queue),
10448 			GFP_KERNEL);
10449 		if (!phba->sli4_hba.hdwq) {
10450 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10451 					"6427 Failed allocate memory for "
10452 					"fast-path Hardware Queue array\n");
10453 			goto out_error;
10454 		}
10455 		/* Prepare hardware queues to take IO buffers */
10456 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10457 			qp = &phba->sli4_hba.hdwq[idx];
10458 			spin_lock_init(&qp->io_buf_list_get_lock);
10459 			spin_lock_init(&qp->io_buf_list_put_lock);
10460 			INIT_LIST_HEAD(&qp->lpfc_io_buf_list_get);
10461 			INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
10462 			qp->get_io_bufs = 0;
10463 			qp->put_io_bufs = 0;
10464 			qp->total_io_bufs = 0;
10465 			spin_lock_init(&qp->abts_io_buf_list_lock);
10466 			INIT_LIST_HEAD(&qp->lpfc_abts_io_buf_list);
10467 			qp->abts_scsi_io_bufs = 0;
10468 			qp->abts_nvme_io_bufs = 0;
10469 			INIT_LIST_HEAD(&qp->sgl_list);
10470 			INIT_LIST_HEAD(&qp->cmd_rsp_buf_list);
10471 			spin_lock_init(&qp->hdwq_lock);
10472 		}
10473 	}
10474 
10475 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
10476 		if (phba->nvmet_support) {
10477 			phba->sli4_hba.nvmet_cqset = kcalloc(
10478 					phba->cfg_nvmet_mrq,
10479 					sizeof(struct lpfc_queue *),
10480 					GFP_KERNEL);
10481 			if (!phba->sli4_hba.nvmet_cqset) {
10482 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10483 					"3121 Fail allocate memory for "
10484 					"fast-path CQ set array\n");
10485 				goto out_error;
10486 			}
10487 			phba->sli4_hba.nvmet_mrq_hdr = kcalloc(
10488 					phba->cfg_nvmet_mrq,
10489 					sizeof(struct lpfc_queue *),
10490 					GFP_KERNEL);
10491 			if (!phba->sli4_hba.nvmet_mrq_hdr) {
10492 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10493 					"3122 Fail allocate memory for "
10494 					"fast-path RQ set hdr array\n");
10495 				goto out_error;
10496 			}
10497 			phba->sli4_hba.nvmet_mrq_data = kcalloc(
10498 					phba->cfg_nvmet_mrq,
10499 					sizeof(struct lpfc_queue *),
10500 					GFP_KERNEL);
10501 			if (!phba->sli4_hba.nvmet_mrq_data) {
10502 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10503 					"3124 Fail allocate memory for "
10504 					"fast-path RQ set data array\n");
10505 				goto out_error;
10506 			}
10507 		}
10508 	}
10509 
10510 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_wq_list);
10511 
10512 	/* Create HBA Event Queues (EQs) */
10513 	for_each_present_cpu(cpu) {
10514 		/* We only want to create 1 EQ per vector, even though
10515 		 * multiple CPUs might be using that vector. so only
10516 		 * selects the CPUs that are LPFC_CPU_FIRST_IRQ.
10517 		 */
10518 		cpup = &phba->sli4_hba.cpu_map[cpu];
10519 		if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
10520 			continue;
10521 
10522 		/* Get a ptr to the Hardware Queue associated with this CPU */
10523 		qp = &phba->sli4_hba.hdwq[cpup->hdwq];
10524 
10525 		/* Allocate an EQ */
10526 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10527 					      phba->sli4_hba.eq_esize,
10528 					      phba->sli4_hba.eq_ecount, cpu);
10529 		if (!qdesc) {
10530 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10531 					"0497 Failed allocate EQ (%d)\n",
10532 					cpup->hdwq);
10533 			goto out_error;
10534 		}
10535 		qdesc->qe_valid = 1;
10536 		qdesc->hdwq = cpup->hdwq;
10537 		qdesc->chann = cpu; /* First CPU this EQ is affinitized to */
10538 		qdesc->last_cpu = qdesc->chann;
10539 
10540 		/* Save the allocated EQ in the Hardware Queue */
10541 		qp->hba_eq = qdesc;
10542 
10543 		eqi = per_cpu_ptr(phba->sli4_hba.eq_info, qdesc->last_cpu);
10544 		list_add(&qdesc->cpu_list, &eqi->list);
10545 	}
10546 
10547 	/* Now we need to populate the other Hardware Queues, that share
10548 	 * an IRQ vector, with the associated EQ ptr.
10549 	 */
10550 	for_each_present_cpu(cpu) {
10551 		cpup = &phba->sli4_hba.cpu_map[cpu];
10552 
10553 		/* Check for EQ already allocated in previous loop */
10554 		if (cpup->flag & LPFC_CPU_FIRST_IRQ)
10555 			continue;
10556 
10557 		/* Check for multiple CPUs per hdwq */
10558 		qp = &phba->sli4_hba.hdwq[cpup->hdwq];
10559 		if (qp->hba_eq)
10560 			continue;
10561 
10562 		/* We need to share an EQ for this hdwq */
10563 		eqcpu = lpfc_find_cpu_handle(phba, cpup->eq, LPFC_FIND_BY_EQ);
10564 		eqcpup = &phba->sli4_hba.cpu_map[eqcpu];
10565 		qp->hba_eq = phba->sli4_hba.hdwq[eqcpup->hdwq].hba_eq;
10566 	}
10567 
10568 	/* Allocate IO Path SLI4 CQ/WQs */
10569 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10570 		if (lpfc_alloc_io_wq_cq(phba, idx))
10571 			goto out_error;
10572 	}
10573 
10574 	if (phba->nvmet_support) {
10575 		for (idx = 0; idx < phba->cfg_nvmet_mrq; idx++) {
10576 			cpu = lpfc_find_cpu_handle(phba, idx,
10577 						   LPFC_FIND_BY_HDWQ);
10578 			qdesc = lpfc_sli4_queue_alloc(phba,
10579 						      LPFC_DEFAULT_PAGE_SIZE,
10580 						      phba->sli4_hba.cq_esize,
10581 						      phba->sli4_hba.cq_ecount,
10582 						      cpu);
10583 			if (!qdesc) {
10584 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10585 						"3142 Failed allocate NVME "
10586 						"CQ Set (%d)\n", idx);
10587 				goto out_error;
10588 			}
10589 			qdesc->qe_valid = 1;
10590 			qdesc->hdwq = idx;
10591 			qdesc->chann = cpu;
10592 			phba->sli4_hba.nvmet_cqset[idx] = qdesc;
10593 		}
10594 	}
10595 
10596 	/*
10597 	 * Create Slow Path Completion Queues (CQs)
10598 	 */
10599 
10600 	cpu = lpfc_find_cpu_handle(phba, 0, LPFC_FIND_BY_EQ);
10601 	/* Create slow-path Mailbox Command Complete Queue */
10602 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10603 				      phba->sli4_hba.cq_esize,
10604 				      phba->sli4_hba.cq_ecount, cpu);
10605 	if (!qdesc) {
10606 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10607 				"0500 Failed allocate slow-path mailbox CQ\n");
10608 		goto out_error;
10609 	}
10610 	qdesc->qe_valid = 1;
10611 	phba->sli4_hba.mbx_cq = qdesc;
10612 
10613 	/* Create slow-path ELS Complete Queue */
10614 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10615 				      phba->sli4_hba.cq_esize,
10616 				      phba->sli4_hba.cq_ecount, cpu);
10617 	if (!qdesc) {
10618 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10619 				"0501 Failed allocate slow-path ELS CQ\n");
10620 		goto out_error;
10621 	}
10622 	qdesc->qe_valid = 1;
10623 	qdesc->chann = cpu;
10624 	phba->sli4_hba.els_cq = qdesc;
10625 
10626 
10627 	/*
10628 	 * Create Slow Path Work Queues (WQs)
10629 	 */
10630 
10631 	/* Create Mailbox Command Queue */
10632 
10633 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10634 				      phba->sli4_hba.mq_esize,
10635 				      phba->sli4_hba.mq_ecount, cpu);
10636 	if (!qdesc) {
10637 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10638 				"0505 Failed allocate slow-path MQ\n");
10639 		goto out_error;
10640 	}
10641 	qdesc->chann = cpu;
10642 	phba->sli4_hba.mbx_wq = qdesc;
10643 
10644 	/*
10645 	 * Create ELS Work Queues
10646 	 */
10647 
10648 	/*
10649 	 * Create slow-path ELS Work Queue.
10650 	 * Increase the ELS WQ size when WQEs contain an embedded cdb
10651 	 */
10652 	wqesize = (phba->fcp_embed_io) ?
10653 			LPFC_WQE128_SIZE : phba->sli4_hba.wq_esize;
10654 
10655 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10656 				      wqesize,
10657 				      phba->sli4_hba.wq_ecount, cpu);
10658 	if (!qdesc) {
10659 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10660 				"0504 Failed allocate slow-path ELS WQ\n");
10661 		goto out_error;
10662 	}
10663 	qdesc->chann = cpu;
10664 	phba->sli4_hba.els_wq = qdesc;
10665 	list_add_tail(&qdesc->wq_list, &phba->sli4_hba.lpfc_wq_list);
10666 
10667 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
10668 		/* Create NVME LS Complete Queue */
10669 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10670 					      phba->sli4_hba.cq_esize,
10671 					      phba->sli4_hba.cq_ecount, cpu);
10672 		if (!qdesc) {
10673 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10674 					"6079 Failed allocate NVME LS CQ\n");
10675 			goto out_error;
10676 		}
10677 		qdesc->chann = cpu;
10678 		qdesc->qe_valid = 1;
10679 		phba->sli4_hba.nvmels_cq = qdesc;
10680 
10681 		/* Create NVME LS Work Queue */
10682 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10683 					      phba->sli4_hba.wq_esize,
10684 					      phba->sli4_hba.wq_ecount, cpu);
10685 		if (!qdesc) {
10686 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10687 					"6080 Failed allocate NVME LS WQ\n");
10688 			goto out_error;
10689 		}
10690 		qdesc->chann = cpu;
10691 		phba->sli4_hba.nvmels_wq = qdesc;
10692 		list_add_tail(&qdesc->wq_list, &phba->sli4_hba.lpfc_wq_list);
10693 	}
10694 
10695 	/*
10696 	 * Create Receive Queue (RQ)
10697 	 */
10698 
10699 	/* Create Receive Queue for header */
10700 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10701 				      phba->sli4_hba.rq_esize,
10702 				      phba->sli4_hba.rq_ecount, cpu);
10703 	if (!qdesc) {
10704 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10705 				"0506 Failed allocate receive HRQ\n");
10706 		goto out_error;
10707 	}
10708 	phba->sli4_hba.hdr_rq = qdesc;
10709 
10710 	/* Create Receive Queue for data */
10711 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10712 				      phba->sli4_hba.rq_esize,
10713 				      phba->sli4_hba.rq_ecount, cpu);
10714 	if (!qdesc) {
10715 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10716 				"0507 Failed allocate receive DRQ\n");
10717 		goto out_error;
10718 	}
10719 	phba->sli4_hba.dat_rq = qdesc;
10720 
10721 	if ((phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) &&
10722 	    phba->nvmet_support) {
10723 		for (idx = 0; idx < phba->cfg_nvmet_mrq; idx++) {
10724 			cpu = lpfc_find_cpu_handle(phba, idx,
10725 						   LPFC_FIND_BY_HDWQ);
10726 			/* Create NVMET Receive Queue for header */
10727 			qdesc = lpfc_sli4_queue_alloc(phba,
10728 						      LPFC_DEFAULT_PAGE_SIZE,
10729 						      phba->sli4_hba.rq_esize,
10730 						      LPFC_NVMET_RQE_DEF_COUNT,
10731 						      cpu);
10732 			if (!qdesc) {
10733 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10734 						"3146 Failed allocate "
10735 						"receive HRQ\n");
10736 				goto out_error;
10737 			}
10738 			qdesc->hdwq = idx;
10739 			phba->sli4_hba.nvmet_mrq_hdr[idx] = qdesc;
10740 
10741 			/* Only needed for header of RQ pair */
10742 			qdesc->rqbp = kzalloc_node(sizeof(*qdesc->rqbp),
10743 						   GFP_KERNEL,
10744 						   cpu_to_node(cpu));
10745 			if (qdesc->rqbp == NULL) {
10746 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10747 						"6131 Failed allocate "
10748 						"Header RQBP\n");
10749 				goto out_error;
10750 			}
10751 
10752 			/* Put list in known state in case driver load fails. */
10753 			INIT_LIST_HEAD(&qdesc->rqbp->rqb_buffer_list);
10754 
10755 			/* Create NVMET Receive Queue for data */
10756 			qdesc = lpfc_sli4_queue_alloc(phba,
10757 						      LPFC_DEFAULT_PAGE_SIZE,
10758 						      phba->sli4_hba.rq_esize,
10759 						      LPFC_NVMET_RQE_DEF_COUNT,
10760 						      cpu);
10761 			if (!qdesc) {
10762 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10763 						"3156 Failed allocate "
10764 						"receive DRQ\n");
10765 				goto out_error;
10766 			}
10767 			qdesc->hdwq = idx;
10768 			phba->sli4_hba.nvmet_mrq_data[idx] = qdesc;
10769 		}
10770 	}
10771 
10772 	/* Clear NVME stats */
10773 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
10774 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10775 			memset(&phba->sli4_hba.hdwq[idx].nvme_cstat, 0,
10776 			       sizeof(phba->sli4_hba.hdwq[idx].nvme_cstat));
10777 		}
10778 	}
10779 
10780 	/* Clear SCSI stats */
10781 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP) {
10782 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10783 			memset(&phba->sli4_hba.hdwq[idx].scsi_cstat, 0,
10784 			       sizeof(phba->sli4_hba.hdwq[idx].scsi_cstat));
10785 		}
10786 	}
10787 
10788 	return 0;
10789 
10790 out_error:
10791 	lpfc_sli4_queue_destroy(phba);
10792 	return -ENOMEM;
10793 }
10794 
10795 static inline void
10796 __lpfc_sli4_release_queue(struct lpfc_queue **qp)
10797 {
10798 	if (*qp != NULL) {
10799 		lpfc_sli4_queue_free(*qp);
10800 		*qp = NULL;
10801 	}
10802 }
10803 
10804 static inline void
10805 lpfc_sli4_release_queues(struct lpfc_queue ***qs, int max)
10806 {
10807 	int idx;
10808 
10809 	if (*qs == NULL)
10810 		return;
10811 
10812 	for (idx = 0; idx < max; idx++)
10813 		__lpfc_sli4_release_queue(&(*qs)[idx]);
10814 
10815 	kfree(*qs);
10816 	*qs = NULL;
10817 }
10818 
10819 static inline void
10820 lpfc_sli4_release_hdwq(struct lpfc_hba *phba)
10821 {
10822 	struct lpfc_sli4_hdw_queue *hdwq;
10823 	struct lpfc_queue *eq;
10824 	uint32_t idx;
10825 
10826 	hdwq = phba->sli4_hba.hdwq;
10827 
10828 	/* Loop thru all Hardware Queues */
10829 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10830 		/* Free the CQ/WQ corresponding to the Hardware Queue */
10831 		lpfc_sli4_queue_free(hdwq[idx].io_cq);
10832 		lpfc_sli4_queue_free(hdwq[idx].io_wq);
10833 		hdwq[idx].hba_eq = NULL;
10834 		hdwq[idx].io_cq = NULL;
10835 		hdwq[idx].io_wq = NULL;
10836 		if (phba->cfg_xpsgl && !phba->nvmet_support)
10837 			lpfc_free_sgl_per_hdwq(phba, &hdwq[idx]);
10838 		lpfc_free_cmd_rsp_buf_per_hdwq(phba, &hdwq[idx]);
10839 	}
10840 	/* Loop thru all IRQ vectors */
10841 	for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
10842 		/* Free the EQ corresponding to the IRQ vector */
10843 		eq = phba->sli4_hba.hba_eq_hdl[idx].eq;
10844 		lpfc_sli4_queue_free(eq);
10845 		phba->sli4_hba.hba_eq_hdl[idx].eq = NULL;
10846 	}
10847 }
10848 
10849 /**
10850  * lpfc_sli4_queue_destroy - Destroy all the SLI4 queues
10851  * @phba: pointer to lpfc hba data structure.
10852  *
10853  * This routine is invoked to release all the SLI4 queues with the FCoE HBA
10854  * operation.
10855  *
10856  * Return codes
10857  *      0 - successful
10858  *      -ENOMEM - No available memory
10859  *      -EIO - The mailbox failed to complete successfully.
10860  **/
10861 void
10862 lpfc_sli4_queue_destroy(struct lpfc_hba *phba)
10863 {
10864 	/*
10865 	 * Set FREE_INIT before beginning to free the queues.
10866 	 * Wait until the users of queues to acknowledge to
10867 	 * release queues by clearing FREE_WAIT.
10868 	 */
10869 	spin_lock_irq(&phba->hbalock);
10870 	phba->sli.sli_flag |= LPFC_QUEUE_FREE_INIT;
10871 	while (phba->sli.sli_flag & LPFC_QUEUE_FREE_WAIT) {
10872 		spin_unlock_irq(&phba->hbalock);
10873 		msleep(20);
10874 		spin_lock_irq(&phba->hbalock);
10875 	}
10876 	spin_unlock_irq(&phba->hbalock);
10877 
10878 	lpfc_sli4_cleanup_poll_list(phba);
10879 
10880 	/* Release HBA eqs */
10881 	if (phba->sli4_hba.hdwq)
10882 		lpfc_sli4_release_hdwq(phba);
10883 
10884 	if (phba->nvmet_support) {
10885 		lpfc_sli4_release_queues(&phba->sli4_hba.nvmet_cqset,
10886 					 phba->cfg_nvmet_mrq);
10887 
10888 		lpfc_sli4_release_queues(&phba->sli4_hba.nvmet_mrq_hdr,
10889 					 phba->cfg_nvmet_mrq);
10890 		lpfc_sli4_release_queues(&phba->sli4_hba.nvmet_mrq_data,
10891 					 phba->cfg_nvmet_mrq);
10892 	}
10893 
10894 	/* Release mailbox command work queue */
10895 	__lpfc_sli4_release_queue(&phba->sli4_hba.mbx_wq);
10896 
10897 	/* Release ELS work queue */
10898 	__lpfc_sli4_release_queue(&phba->sli4_hba.els_wq);
10899 
10900 	/* Release ELS work queue */
10901 	__lpfc_sli4_release_queue(&phba->sli4_hba.nvmels_wq);
10902 
10903 	/* Release unsolicited receive queue */
10904 	__lpfc_sli4_release_queue(&phba->sli4_hba.hdr_rq);
10905 	__lpfc_sli4_release_queue(&phba->sli4_hba.dat_rq);
10906 
10907 	/* Release ELS complete queue */
10908 	__lpfc_sli4_release_queue(&phba->sli4_hba.els_cq);
10909 
10910 	/* Release NVME LS complete queue */
10911 	__lpfc_sli4_release_queue(&phba->sli4_hba.nvmels_cq);
10912 
10913 	/* Release mailbox command complete queue */
10914 	__lpfc_sli4_release_queue(&phba->sli4_hba.mbx_cq);
10915 
10916 	/* Everything on this list has been freed */
10917 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_wq_list);
10918 
10919 	/* Done with freeing the queues */
10920 	spin_lock_irq(&phba->hbalock);
10921 	phba->sli.sli_flag &= ~LPFC_QUEUE_FREE_INIT;
10922 	spin_unlock_irq(&phba->hbalock);
10923 }
10924 
10925 int
10926 lpfc_free_rq_buffer(struct lpfc_hba *phba, struct lpfc_queue *rq)
10927 {
10928 	struct lpfc_rqb *rqbp;
10929 	struct lpfc_dmabuf *h_buf;
10930 	struct rqb_dmabuf *rqb_buffer;
10931 
10932 	rqbp = rq->rqbp;
10933 	while (!list_empty(&rqbp->rqb_buffer_list)) {
10934 		list_remove_head(&rqbp->rqb_buffer_list, h_buf,
10935 				 struct lpfc_dmabuf, list);
10936 
10937 		rqb_buffer = container_of(h_buf, struct rqb_dmabuf, hbuf);
10938 		(rqbp->rqb_free_buffer)(phba, rqb_buffer);
10939 		rqbp->buffer_count--;
10940 	}
10941 	return 1;
10942 }
10943 
10944 static int
10945 lpfc_create_wq_cq(struct lpfc_hba *phba, struct lpfc_queue *eq,
10946 	struct lpfc_queue *cq, struct lpfc_queue *wq, uint16_t *cq_map,
10947 	int qidx, uint32_t qtype)
10948 {
10949 	struct lpfc_sli_ring *pring;
10950 	int rc;
10951 
10952 	if (!eq || !cq || !wq) {
10953 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10954 			"6085 Fast-path %s (%d) not allocated\n",
10955 			((eq) ? ((cq) ? "WQ" : "CQ") : "EQ"), qidx);
10956 		return -ENOMEM;
10957 	}
10958 
10959 	/* create the Cq first */
10960 	rc = lpfc_cq_create(phba, cq, eq,
10961 			(qtype == LPFC_MBOX) ? LPFC_MCQ : LPFC_WCQ, qtype);
10962 	if (rc) {
10963 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10964 				"6086 Failed setup of CQ (%d), rc = 0x%x\n",
10965 				qidx, (uint32_t)rc);
10966 		return rc;
10967 	}
10968 
10969 	if (qtype != LPFC_MBOX) {
10970 		/* Setup cq_map for fast lookup */
10971 		if (cq_map)
10972 			*cq_map = cq->queue_id;
10973 
10974 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
10975 			"6087 CQ setup: cq[%d]-id=%d, parent eq[%d]-id=%d\n",
10976 			qidx, cq->queue_id, qidx, eq->queue_id);
10977 
10978 		/* create the wq */
10979 		rc = lpfc_wq_create(phba, wq, cq, qtype);
10980 		if (rc) {
10981 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10982 				"4618 Fail setup fastpath WQ (%d), rc = 0x%x\n",
10983 				qidx, (uint32_t)rc);
10984 			/* no need to tear down cq - caller will do so */
10985 			return rc;
10986 		}
10987 
10988 		/* Bind this CQ/WQ to the NVME ring */
10989 		pring = wq->pring;
10990 		pring->sli.sli4.wqp = (void *)wq;
10991 		cq->pring = pring;
10992 
10993 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
10994 			"2593 WQ setup: wq[%d]-id=%d assoc=%d, cq[%d]-id=%d\n",
10995 			qidx, wq->queue_id, wq->assoc_qid, qidx, cq->queue_id);
10996 	} else {
10997 		rc = lpfc_mq_create(phba, wq, cq, LPFC_MBOX);
10998 		if (rc) {
10999 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11000 					"0539 Failed setup of slow-path MQ: "
11001 					"rc = 0x%x\n", rc);
11002 			/* no need to tear down cq - caller will do so */
11003 			return rc;
11004 		}
11005 
11006 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11007 			"2589 MBX MQ setup: wq-id=%d, parent cq-id=%d\n",
11008 			phba->sli4_hba.mbx_wq->queue_id,
11009 			phba->sli4_hba.mbx_cq->queue_id);
11010 	}
11011 
11012 	return 0;
11013 }
11014 
11015 /**
11016  * lpfc_setup_cq_lookup - Setup the CQ lookup table
11017  * @phba: pointer to lpfc hba data structure.
11018  *
11019  * This routine will populate the cq_lookup table by all
11020  * available CQ queue_id's.
11021  **/
11022 static void
11023 lpfc_setup_cq_lookup(struct lpfc_hba *phba)
11024 {
11025 	struct lpfc_queue *eq, *childq;
11026 	int qidx;
11027 
11028 	memset(phba->sli4_hba.cq_lookup, 0,
11029 	       (sizeof(struct lpfc_queue *) * (phba->sli4_hba.cq_max + 1)));
11030 	/* Loop thru all IRQ vectors */
11031 	for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
11032 		/* Get the EQ corresponding to the IRQ vector */
11033 		eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
11034 		if (!eq)
11035 			continue;
11036 		/* Loop through all CQs associated with that EQ */
11037 		list_for_each_entry(childq, &eq->child_list, list) {
11038 			if (childq->queue_id > phba->sli4_hba.cq_max)
11039 				continue;
11040 			if (childq->subtype == LPFC_IO)
11041 				phba->sli4_hba.cq_lookup[childq->queue_id] =
11042 					childq;
11043 		}
11044 	}
11045 }
11046 
11047 /**
11048  * lpfc_sli4_queue_setup - Set up all the SLI4 queues
11049  * @phba: pointer to lpfc hba data structure.
11050  *
11051  * This routine is invoked to set up all the SLI4 queues for the FCoE HBA
11052  * operation.
11053  *
11054  * Return codes
11055  *      0 - successful
11056  *      -ENOMEM - No available memory
11057  *      -EIO - The mailbox failed to complete successfully.
11058  **/
11059 int
11060 lpfc_sli4_queue_setup(struct lpfc_hba *phba)
11061 {
11062 	uint32_t shdr_status, shdr_add_status;
11063 	union lpfc_sli4_cfg_shdr *shdr;
11064 	struct lpfc_vector_map_info *cpup;
11065 	struct lpfc_sli4_hdw_queue *qp;
11066 	LPFC_MBOXQ_t *mboxq;
11067 	int qidx, cpu;
11068 	uint32_t length, usdelay;
11069 	int rc = -ENOMEM;
11070 
11071 	/* Check for dual-ULP support */
11072 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
11073 	if (!mboxq) {
11074 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11075 				"3249 Unable to allocate memory for "
11076 				"QUERY_FW_CFG mailbox command\n");
11077 		return -ENOMEM;
11078 	}
11079 	length = (sizeof(struct lpfc_mbx_query_fw_config) -
11080 		  sizeof(struct lpfc_sli4_cfg_mhdr));
11081 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
11082 			 LPFC_MBOX_OPCODE_QUERY_FW_CFG,
11083 			 length, LPFC_SLI4_MBX_EMBED);
11084 
11085 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
11086 
11087 	shdr = (union lpfc_sli4_cfg_shdr *)
11088 			&mboxq->u.mqe.un.sli4_config.header.cfg_shdr;
11089 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
11090 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
11091 	if (shdr_status || shdr_add_status || rc) {
11092 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11093 				"3250 QUERY_FW_CFG mailbox failed with status "
11094 				"x%x add_status x%x, mbx status x%x\n",
11095 				shdr_status, shdr_add_status, rc);
11096 		mempool_free(mboxq, phba->mbox_mem_pool);
11097 		rc = -ENXIO;
11098 		goto out_error;
11099 	}
11100 
11101 	phba->sli4_hba.fw_func_mode =
11102 			mboxq->u.mqe.un.query_fw_cfg.rsp.function_mode;
11103 	phba->sli4_hba.physical_port =
11104 			mboxq->u.mqe.un.query_fw_cfg.rsp.physical_port;
11105 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11106 			"3251 QUERY_FW_CFG: func_mode:x%x\n",
11107 			phba->sli4_hba.fw_func_mode);
11108 
11109 	mempool_free(mboxq, phba->mbox_mem_pool);
11110 
11111 	/*
11112 	 * Set up HBA Event Queues (EQs)
11113 	 */
11114 	qp = phba->sli4_hba.hdwq;
11115 
11116 	/* Set up HBA event queue */
11117 	if (!qp) {
11118 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11119 				"3147 Fast-path EQs not allocated\n");
11120 		rc = -ENOMEM;
11121 		goto out_error;
11122 	}
11123 
11124 	/* Loop thru all IRQ vectors */
11125 	for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
11126 		/* Create HBA Event Queues (EQs) in order */
11127 		for_each_present_cpu(cpu) {
11128 			cpup = &phba->sli4_hba.cpu_map[cpu];
11129 
11130 			/* Look for the CPU thats using that vector with
11131 			 * LPFC_CPU_FIRST_IRQ set.
11132 			 */
11133 			if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
11134 				continue;
11135 			if (qidx != cpup->eq)
11136 				continue;
11137 
11138 			/* Create an EQ for that vector */
11139 			rc = lpfc_eq_create(phba, qp[cpup->hdwq].hba_eq,
11140 					    phba->cfg_fcp_imax);
11141 			if (rc) {
11142 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11143 						"0523 Failed setup of fast-path"
11144 						" EQ (%d), rc = 0x%x\n",
11145 						cpup->eq, (uint32_t)rc);
11146 				goto out_destroy;
11147 			}
11148 
11149 			/* Save the EQ for that vector in the hba_eq_hdl */
11150 			phba->sli4_hba.hba_eq_hdl[cpup->eq].eq =
11151 				qp[cpup->hdwq].hba_eq;
11152 
11153 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11154 					"2584 HBA EQ setup: queue[%d]-id=%d\n",
11155 					cpup->eq,
11156 					qp[cpup->hdwq].hba_eq->queue_id);
11157 		}
11158 	}
11159 
11160 	/* Loop thru all Hardware Queues */
11161 	for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
11162 		cpu = lpfc_find_cpu_handle(phba, qidx, LPFC_FIND_BY_HDWQ);
11163 		cpup = &phba->sli4_hba.cpu_map[cpu];
11164 
11165 		/* Create the CQ/WQ corresponding to the Hardware Queue */
11166 		rc = lpfc_create_wq_cq(phba,
11167 				       phba->sli4_hba.hdwq[cpup->hdwq].hba_eq,
11168 				       qp[qidx].io_cq,
11169 				       qp[qidx].io_wq,
11170 				       &phba->sli4_hba.hdwq[qidx].io_cq_map,
11171 				       qidx,
11172 				       LPFC_IO);
11173 		if (rc) {
11174 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11175 					"0535 Failed to setup fastpath "
11176 					"IO WQ/CQ (%d), rc = 0x%x\n",
11177 					qidx, (uint32_t)rc);
11178 			goto out_destroy;
11179 		}
11180 	}
11181 
11182 	/*
11183 	 * Set up Slow Path Complete Queues (CQs)
11184 	 */
11185 
11186 	/* Set up slow-path MBOX CQ/MQ */
11187 
11188 	if (!phba->sli4_hba.mbx_cq || !phba->sli4_hba.mbx_wq) {
11189 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11190 				"0528 %s not allocated\n",
11191 				phba->sli4_hba.mbx_cq ?
11192 				"Mailbox WQ" : "Mailbox CQ");
11193 		rc = -ENOMEM;
11194 		goto out_destroy;
11195 	}
11196 
11197 	rc = lpfc_create_wq_cq(phba, qp[0].hba_eq,
11198 			       phba->sli4_hba.mbx_cq,
11199 			       phba->sli4_hba.mbx_wq,
11200 			       NULL, 0, LPFC_MBOX);
11201 	if (rc) {
11202 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11203 			"0529 Failed setup of mailbox WQ/CQ: rc = 0x%x\n",
11204 			(uint32_t)rc);
11205 		goto out_destroy;
11206 	}
11207 	if (phba->nvmet_support) {
11208 		if (!phba->sli4_hba.nvmet_cqset) {
11209 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11210 					"3165 Fast-path NVME CQ Set "
11211 					"array not allocated\n");
11212 			rc = -ENOMEM;
11213 			goto out_destroy;
11214 		}
11215 		if (phba->cfg_nvmet_mrq > 1) {
11216 			rc = lpfc_cq_create_set(phba,
11217 					phba->sli4_hba.nvmet_cqset,
11218 					qp,
11219 					LPFC_WCQ, LPFC_NVMET);
11220 			if (rc) {
11221 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11222 						"3164 Failed setup of NVME CQ "
11223 						"Set, rc = 0x%x\n",
11224 						(uint32_t)rc);
11225 				goto out_destroy;
11226 			}
11227 		} else {
11228 			/* Set up NVMET Receive Complete Queue */
11229 			rc = lpfc_cq_create(phba, phba->sli4_hba.nvmet_cqset[0],
11230 					    qp[0].hba_eq,
11231 					    LPFC_WCQ, LPFC_NVMET);
11232 			if (rc) {
11233 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11234 						"6089 Failed setup NVMET CQ: "
11235 						"rc = 0x%x\n", (uint32_t)rc);
11236 				goto out_destroy;
11237 			}
11238 			phba->sli4_hba.nvmet_cqset[0]->chann = 0;
11239 
11240 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11241 					"6090 NVMET CQ setup: cq-id=%d, "
11242 					"parent eq-id=%d\n",
11243 					phba->sli4_hba.nvmet_cqset[0]->queue_id,
11244 					qp[0].hba_eq->queue_id);
11245 		}
11246 	}
11247 
11248 	/* Set up slow-path ELS WQ/CQ */
11249 	if (!phba->sli4_hba.els_cq || !phba->sli4_hba.els_wq) {
11250 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11251 				"0530 ELS %s not allocated\n",
11252 				phba->sli4_hba.els_cq ? "WQ" : "CQ");
11253 		rc = -ENOMEM;
11254 		goto out_destroy;
11255 	}
11256 	rc = lpfc_create_wq_cq(phba, qp[0].hba_eq,
11257 			       phba->sli4_hba.els_cq,
11258 			       phba->sli4_hba.els_wq,
11259 			       NULL, 0, LPFC_ELS);
11260 	if (rc) {
11261 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11262 				"0525 Failed setup of ELS WQ/CQ: rc = 0x%x\n",
11263 				(uint32_t)rc);
11264 		goto out_destroy;
11265 	}
11266 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11267 			"2590 ELS WQ setup: wq-id=%d, parent cq-id=%d\n",
11268 			phba->sli4_hba.els_wq->queue_id,
11269 			phba->sli4_hba.els_cq->queue_id);
11270 
11271 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
11272 		/* Set up NVME LS Complete Queue */
11273 		if (!phba->sli4_hba.nvmels_cq || !phba->sli4_hba.nvmels_wq) {
11274 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11275 					"6091 LS %s not allocated\n",
11276 					phba->sli4_hba.nvmels_cq ? "WQ" : "CQ");
11277 			rc = -ENOMEM;
11278 			goto out_destroy;
11279 		}
11280 		rc = lpfc_create_wq_cq(phba, qp[0].hba_eq,
11281 				       phba->sli4_hba.nvmels_cq,
11282 				       phba->sli4_hba.nvmels_wq,
11283 				       NULL, 0, LPFC_NVME_LS);
11284 		if (rc) {
11285 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11286 					"0526 Failed setup of NVVME LS WQ/CQ: "
11287 					"rc = 0x%x\n", (uint32_t)rc);
11288 			goto out_destroy;
11289 		}
11290 
11291 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11292 				"6096 ELS WQ setup: wq-id=%d, "
11293 				"parent cq-id=%d\n",
11294 				phba->sli4_hba.nvmels_wq->queue_id,
11295 				phba->sli4_hba.nvmels_cq->queue_id);
11296 	}
11297 
11298 	/*
11299 	 * Create NVMET Receive Queue (RQ)
11300 	 */
11301 	if (phba->nvmet_support) {
11302 		if ((!phba->sli4_hba.nvmet_cqset) ||
11303 		    (!phba->sli4_hba.nvmet_mrq_hdr) ||
11304 		    (!phba->sli4_hba.nvmet_mrq_data)) {
11305 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11306 					"6130 MRQ CQ Queues not "
11307 					"allocated\n");
11308 			rc = -ENOMEM;
11309 			goto out_destroy;
11310 		}
11311 		if (phba->cfg_nvmet_mrq > 1) {
11312 			rc = lpfc_mrq_create(phba,
11313 					     phba->sli4_hba.nvmet_mrq_hdr,
11314 					     phba->sli4_hba.nvmet_mrq_data,
11315 					     phba->sli4_hba.nvmet_cqset,
11316 					     LPFC_NVMET);
11317 			if (rc) {
11318 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11319 						"6098 Failed setup of NVMET "
11320 						"MRQ: rc = 0x%x\n",
11321 						(uint32_t)rc);
11322 				goto out_destroy;
11323 			}
11324 
11325 		} else {
11326 			rc = lpfc_rq_create(phba,
11327 					    phba->sli4_hba.nvmet_mrq_hdr[0],
11328 					    phba->sli4_hba.nvmet_mrq_data[0],
11329 					    phba->sli4_hba.nvmet_cqset[0],
11330 					    LPFC_NVMET);
11331 			if (rc) {
11332 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11333 						"6057 Failed setup of NVMET "
11334 						"Receive Queue: rc = 0x%x\n",
11335 						(uint32_t)rc);
11336 				goto out_destroy;
11337 			}
11338 
11339 			lpfc_printf_log(
11340 				phba, KERN_INFO, LOG_INIT,
11341 				"6099 NVMET RQ setup: hdr-rq-id=%d, "
11342 				"dat-rq-id=%d parent cq-id=%d\n",
11343 				phba->sli4_hba.nvmet_mrq_hdr[0]->queue_id,
11344 				phba->sli4_hba.nvmet_mrq_data[0]->queue_id,
11345 				phba->sli4_hba.nvmet_cqset[0]->queue_id);
11346 
11347 		}
11348 	}
11349 
11350 	if (!phba->sli4_hba.hdr_rq || !phba->sli4_hba.dat_rq) {
11351 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11352 				"0540 Receive Queue not allocated\n");
11353 		rc = -ENOMEM;
11354 		goto out_destroy;
11355 	}
11356 
11357 	rc = lpfc_rq_create(phba, phba->sli4_hba.hdr_rq, phba->sli4_hba.dat_rq,
11358 			    phba->sli4_hba.els_cq, LPFC_USOL);
11359 	if (rc) {
11360 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11361 				"0541 Failed setup of Receive Queue: "
11362 				"rc = 0x%x\n", (uint32_t)rc);
11363 		goto out_destroy;
11364 	}
11365 
11366 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11367 			"2592 USL RQ setup: hdr-rq-id=%d, dat-rq-id=%d "
11368 			"parent cq-id=%d\n",
11369 			phba->sli4_hba.hdr_rq->queue_id,
11370 			phba->sli4_hba.dat_rq->queue_id,
11371 			phba->sli4_hba.els_cq->queue_id);
11372 
11373 	if (phba->cfg_fcp_imax)
11374 		usdelay = LPFC_SEC_TO_USEC / phba->cfg_fcp_imax;
11375 	else
11376 		usdelay = 0;
11377 
11378 	for (qidx = 0; qidx < phba->cfg_irq_chann;
11379 	     qidx += LPFC_MAX_EQ_DELAY_EQID_CNT)
11380 		lpfc_modify_hba_eq_delay(phba, qidx, LPFC_MAX_EQ_DELAY_EQID_CNT,
11381 					 usdelay);
11382 
11383 	if (phba->sli4_hba.cq_max) {
11384 		kfree(phba->sli4_hba.cq_lookup);
11385 		phba->sli4_hba.cq_lookup = kcalloc((phba->sli4_hba.cq_max + 1),
11386 			sizeof(struct lpfc_queue *), GFP_KERNEL);
11387 		if (!phba->sli4_hba.cq_lookup) {
11388 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11389 					"0549 Failed setup of CQ Lookup table: "
11390 					"size 0x%x\n", phba->sli4_hba.cq_max);
11391 			rc = -ENOMEM;
11392 			goto out_destroy;
11393 		}
11394 		lpfc_setup_cq_lookup(phba);
11395 	}
11396 	return 0;
11397 
11398 out_destroy:
11399 	lpfc_sli4_queue_unset(phba);
11400 out_error:
11401 	return rc;
11402 }
11403 
11404 /**
11405  * lpfc_sli4_queue_unset - Unset all the SLI4 queues
11406  * @phba: pointer to lpfc hba data structure.
11407  *
11408  * This routine is invoked to unset all the SLI4 queues with the FCoE HBA
11409  * operation.
11410  *
11411  * Return codes
11412  *      0 - successful
11413  *      -ENOMEM - No available memory
11414  *      -EIO - The mailbox failed to complete successfully.
11415  **/
11416 void
11417 lpfc_sli4_queue_unset(struct lpfc_hba *phba)
11418 {
11419 	struct lpfc_sli4_hdw_queue *qp;
11420 	struct lpfc_queue *eq;
11421 	int qidx;
11422 
11423 	/* Unset mailbox command work queue */
11424 	if (phba->sli4_hba.mbx_wq)
11425 		lpfc_mq_destroy(phba, phba->sli4_hba.mbx_wq);
11426 
11427 	/* Unset NVME LS work queue */
11428 	if (phba->sli4_hba.nvmels_wq)
11429 		lpfc_wq_destroy(phba, phba->sli4_hba.nvmels_wq);
11430 
11431 	/* Unset ELS work queue */
11432 	if (phba->sli4_hba.els_wq)
11433 		lpfc_wq_destroy(phba, phba->sli4_hba.els_wq);
11434 
11435 	/* Unset unsolicited receive queue */
11436 	if (phba->sli4_hba.hdr_rq)
11437 		lpfc_rq_destroy(phba, phba->sli4_hba.hdr_rq,
11438 				phba->sli4_hba.dat_rq);
11439 
11440 	/* Unset mailbox command complete queue */
11441 	if (phba->sli4_hba.mbx_cq)
11442 		lpfc_cq_destroy(phba, phba->sli4_hba.mbx_cq);
11443 
11444 	/* Unset ELS complete queue */
11445 	if (phba->sli4_hba.els_cq)
11446 		lpfc_cq_destroy(phba, phba->sli4_hba.els_cq);
11447 
11448 	/* Unset NVME LS complete queue */
11449 	if (phba->sli4_hba.nvmels_cq)
11450 		lpfc_cq_destroy(phba, phba->sli4_hba.nvmels_cq);
11451 
11452 	if (phba->nvmet_support) {
11453 		/* Unset NVMET MRQ queue */
11454 		if (phba->sli4_hba.nvmet_mrq_hdr) {
11455 			for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++)
11456 				lpfc_rq_destroy(
11457 					phba,
11458 					phba->sli4_hba.nvmet_mrq_hdr[qidx],
11459 					phba->sli4_hba.nvmet_mrq_data[qidx]);
11460 		}
11461 
11462 		/* Unset NVMET CQ Set complete queue */
11463 		if (phba->sli4_hba.nvmet_cqset) {
11464 			for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++)
11465 				lpfc_cq_destroy(
11466 					phba, phba->sli4_hba.nvmet_cqset[qidx]);
11467 		}
11468 	}
11469 
11470 	/* Unset fast-path SLI4 queues */
11471 	if (phba->sli4_hba.hdwq) {
11472 		/* Loop thru all Hardware Queues */
11473 		for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
11474 			/* Destroy the CQ/WQ corresponding to Hardware Queue */
11475 			qp = &phba->sli4_hba.hdwq[qidx];
11476 			lpfc_wq_destroy(phba, qp->io_wq);
11477 			lpfc_cq_destroy(phba, qp->io_cq);
11478 		}
11479 		/* Loop thru all IRQ vectors */
11480 		for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
11481 			/* Destroy the EQ corresponding to the IRQ vector */
11482 			eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
11483 			lpfc_eq_destroy(phba, eq);
11484 		}
11485 	}
11486 
11487 	kfree(phba->sli4_hba.cq_lookup);
11488 	phba->sli4_hba.cq_lookup = NULL;
11489 	phba->sli4_hba.cq_max = 0;
11490 }
11491 
11492 /**
11493  * lpfc_sli4_cq_event_pool_create - Create completion-queue event free pool
11494  * @phba: pointer to lpfc hba data structure.
11495  *
11496  * This routine is invoked to allocate and set up a pool of completion queue
11497  * events. The body of the completion queue event is a completion queue entry
11498  * CQE. For now, this pool is used for the interrupt service routine to queue
11499  * the following HBA completion queue events for the worker thread to process:
11500  *   - Mailbox asynchronous events
11501  *   - Receive queue completion unsolicited events
11502  * Later, this can be used for all the slow-path events.
11503  *
11504  * Return codes
11505  *      0 - successful
11506  *      -ENOMEM - No available memory
11507  **/
11508 static int
11509 lpfc_sli4_cq_event_pool_create(struct lpfc_hba *phba)
11510 {
11511 	struct lpfc_cq_event *cq_event;
11512 	int i;
11513 
11514 	for (i = 0; i < (4 * phba->sli4_hba.cq_ecount); i++) {
11515 		cq_event = kmalloc(sizeof(struct lpfc_cq_event), GFP_KERNEL);
11516 		if (!cq_event)
11517 			goto out_pool_create_fail;
11518 		list_add_tail(&cq_event->list,
11519 			      &phba->sli4_hba.sp_cqe_event_pool);
11520 	}
11521 	return 0;
11522 
11523 out_pool_create_fail:
11524 	lpfc_sli4_cq_event_pool_destroy(phba);
11525 	return -ENOMEM;
11526 }
11527 
11528 /**
11529  * lpfc_sli4_cq_event_pool_destroy - Free completion-queue event free pool
11530  * @phba: pointer to lpfc hba data structure.
11531  *
11532  * This routine is invoked to free the pool of completion queue events at
11533  * driver unload time. Note that, it is the responsibility of the driver
11534  * cleanup routine to free all the outstanding completion-queue events
11535  * allocated from this pool back into the pool before invoking this routine
11536  * to destroy the pool.
11537  **/
11538 static void
11539 lpfc_sli4_cq_event_pool_destroy(struct lpfc_hba *phba)
11540 {
11541 	struct lpfc_cq_event *cq_event, *next_cq_event;
11542 
11543 	list_for_each_entry_safe(cq_event, next_cq_event,
11544 				 &phba->sli4_hba.sp_cqe_event_pool, list) {
11545 		list_del(&cq_event->list);
11546 		kfree(cq_event);
11547 	}
11548 }
11549 
11550 /**
11551  * __lpfc_sli4_cq_event_alloc - Allocate a completion-queue event from free pool
11552  * @phba: pointer to lpfc hba data structure.
11553  *
11554  * This routine is the lock free version of the API invoked to allocate a
11555  * completion-queue event from the free pool.
11556  *
11557  * Return: Pointer to the newly allocated completion-queue event if successful
11558  *         NULL otherwise.
11559  **/
11560 struct lpfc_cq_event *
11561 __lpfc_sli4_cq_event_alloc(struct lpfc_hba *phba)
11562 {
11563 	struct lpfc_cq_event *cq_event = NULL;
11564 
11565 	list_remove_head(&phba->sli4_hba.sp_cqe_event_pool, cq_event,
11566 			 struct lpfc_cq_event, list);
11567 	return cq_event;
11568 }
11569 
11570 /**
11571  * lpfc_sli4_cq_event_alloc - Allocate a completion-queue event from free pool
11572  * @phba: pointer to lpfc hba data structure.
11573  *
11574  * This routine is the lock version of the API invoked to allocate a
11575  * completion-queue event from the free pool.
11576  *
11577  * Return: Pointer to the newly allocated completion-queue event if successful
11578  *         NULL otherwise.
11579  **/
11580 struct lpfc_cq_event *
11581 lpfc_sli4_cq_event_alloc(struct lpfc_hba *phba)
11582 {
11583 	struct lpfc_cq_event *cq_event;
11584 	unsigned long iflags;
11585 
11586 	spin_lock_irqsave(&phba->hbalock, iflags);
11587 	cq_event = __lpfc_sli4_cq_event_alloc(phba);
11588 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11589 	return cq_event;
11590 }
11591 
11592 /**
11593  * __lpfc_sli4_cq_event_release - Release a completion-queue event to free pool
11594  * @phba: pointer to lpfc hba data structure.
11595  * @cq_event: pointer to the completion queue event to be freed.
11596  *
11597  * This routine is the lock free version of the API invoked to release a
11598  * completion-queue event back into the free pool.
11599  **/
11600 void
11601 __lpfc_sli4_cq_event_release(struct lpfc_hba *phba,
11602 			     struct lpfc_cq_event *cq_event)
11603 {
11604 	list_add_tail(&cq_event->list, &phba->sli4_hba.sp_cqe_event_pool);
11605 }
11606 
11607 /**
11608  * lpfc_sli4_cq_event_release - Release a completion-queue event to free pool
11609  * @phba: pointer to lpfc hba data structure.
11610  * @cq_event: pointer to the completion queue event to be freed.
11611  *
11612  * This routine is the lock version of the API invoked to release a
11613  * completion-queue event back into the free pool.
11614  **/
11615 void
11616 lpfc_sli4_cq_event_release(struct lpfc_hba *phba,
11617 			   struct lpfc_cq_event *cq_event)
11618 {
11619 	unsigned long iflags;
11620 	spin_lock_irqsave(&phba->hbalock, iflags);
11621 	__lpfc_sli4_cq_event_release(phba, cq_event);
11622 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11623 }
11624 
11625 /**
11626  * lpfc_sli4_cq_event_release_all - Release all cq events to the free pool
11627  * @phba: pointer to lpfc hba data structure.
11628  *
11629  * This routine is to free all the pending completion-queue events to the
11630  * back into the free pool for device reset.
11631  **/
11632 static void
11633 lpfc_sli4_cq_event_release_all(struct lpfc_hba *phba)
11634 {
11635 	LIST_HEAD(cq_event_list);
11636 	struct lpfc_cq_event *cq_event;
11637 	unsigned long iflags;
11638 
11639 	/* Retrieve all the pending WCQEs from pending WCQE lists */
11640 
11641 	/* Pending ELS XRI abort events */
11642 	spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
11643 	list_splice_init(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
11644 			 &cq_event_list);
11645 	spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
11646 
11647 	/* Pending asynnc events */
11648 	spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
11649 	list_splice_init(&phba->sli4_hba.sp_asynce_work_queue,
11650 			 &cq_event_list);
11651 	spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock, iflags);
11652 
11653 	while (!list_empty(&cq_event_list)) {
11654 		list_remove_head(&cq_event_list, cq_event,
11655 				 struct lpfc_cq_event, list);
11656 		lpfc_sli4_cq_event_release(phba, cq_event);
11657 	}
11658 }
11659 
11660 /**
11661  * lpfc_pci_function_reset - Reset pci function.
11662  * @phba: pointer to lpfc hba data structure.
11663  *
11664  * This routine is invoked to request a PCI function reset. It will destroys
11665  * all resources assigned to the PCI function which originates this request.
11666  *
11667  * Return codes
11668  *      0 - successful
11669  *      -ENOMEM - No available memory
11670  *      -EIO - The mailbox failed to complete successfully.
11671  **/
11672 int
11673 lpfc_pci_function_reset(struct lpfc_hba *phba)
11674 {
11675 	LPFC_MBOXQ_t *mboxq;
11676 	uint32_t rc = 0, if_type;
11677 	uint32_t shdr_status, shdr_add_status;
11678 	uint32_t rdy_chk;
11679 	uint32_t port_reset = 0;
11680 	union lpfc_sli4_cfg_shdr *shdr;
11681 	struct lpfc_register reg_data;
11682 	uint16_t devid;
11683 
11684 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
11685 	switch (if_type) {
11686 	case LPFC_SLI_INTF_IF_TYPE_0:
11687 		mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
11688 						       GFP_KERNEL);
11689 		if (!mboxq) {
11690 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11691 					"0494 Unable to allocate memory for "
11692 					"issuing SLI_FUNCTION_RESET mailbox "
11693 					"command\n");
11694 			return -ENOMEM;
11695 		}
11696 
11697 		/* Setup PCI function reset mailbox-ioctl command */
11698 		lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
11699 				 LPFC_MBOX_OPCODE_FUNCTION_RESET, 0,
11700 				 LPFC_SLI4_MBX_EMBED);
11701 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
11702 		shdr = (union lpfc_sli4_cfg_shdr *)
11703 			&mboxq->u.mqe.un.sli4_config.header.cfg_shdr;
11704 		shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
11705 		shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
11706 					 &shdr->response);
11707 		mempool_free(mboxq, phba->mbox_mem_pool);
11708 		if (shdr_status || shdr_add_status || rc) {
11709 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11710 					"0495 SLI_FUNCTION_RESET mailbox "
11711 					"failed with status x%x add_status x%x,"
11712 					" mbx status x%x\n",
11713 					shdr_status, shdr_add_status, rc);
11714 			rc = -ENXIO;
11715 		}
11716 		break;
11717 	case LPFC_SLI_INTF_IF_TYPE_2:
11718 	case LPFC_SLI_INTF_IF_TYPE_6:
11719 wait:
11720 		/*
11721 		 * Poll the Port Status Register and wait for RDY for
11722 		 * up to 30 seconds. If the port doesn't respond, treat
11723 		 * it as an error.
11724 		 */
11725 		for (rdy_chk = 0; rdy_chk < 1500; rdy_chk++) {
11726 			if (lpfc_readl(phba->sli4_hba.u.if_type2.
11727 				STATUSregaddr, &reg_data.word0)) {
11728 				rc = -ENODEV;
11729 				goto out;
11730 			}
11731 			if (bf_get(lpfc_sliport_status_rdy, &reg_data))
11732 				break;
11733 			msleep(20);
11734 		}
11735 
11736 		if (!bf_get(lpfc_sliport_status_rdy, &reg_data)) {
11737 			phba->work_status[0] = readl(
11738 				phba->sli4_hba.u.if_type2.ERR1regaddr);
11739 			phba->work_status[1] = readl(
11740 				phba->sli4_hba.u.if_type2.ERR2regaddr);
11741 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11742 					"2890 Port not ready, port status reg "
11743 					"0x%x error 1=0x%x, error 2=0x%x\n",
11744 					reg_data.word0,
11745 					phba->work_status[0],
11746 					phba->work_status[1]);
11747 			rc = -ENODEV;
11748 			goto out;
11749 		}
11750 
11751 		if (bf_get(lpfc_sliport_status_pldv, &reg_data))
11752 			lpfc_pldv_detect = true;
11753 
11754 		if (!port_reset) {
11755 			/*
11756 			 * Reset the port now
11757 			 */
11758 			reg_data.word0 = 0;
11759 			bf_set(lpfc_sliport_ctrl_end, &reg_data,
11760 			       LPFC_SLIPORT_LITTLE_ENDIAN);
11761 			bf_set(lpfc_sliport_ctrl_ip, &reg_data,
11762 			       LPFC_SLIPORT_INIT_PORT);
11763 			writel(reg_data.word0, phba->sli4_hba.u.if_type2.
11764 			       CTRLregaddr);
11765 			/* flush */
11766 			pci_read_config_word(phba->pcidev,
11767 					     PCI_DEVICE_ID, &devid);
11768 
11769 			port_reset = 1;
11770 			msleep(20);
11771 			goto wait;
11772 		} else if (bf_get(lpfc_sliport_status_rn, &reg_data)) {
11773 			rc = -ENODEV;
11774 			goto out;
11775 		}
11776 		break;
11777 
11778 	case LPFC_SLI_INTF_IF_TYPE_1:
11779 	default:
11780 		break;
11781 	}
11782 
11783 out:
11784 	/* Catch the not-ready port failure after a port reset. */
11785 	if (rc) {
11786 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11787 				"3317 HBA not functional: IP Reset Failed "
11788 				"try: echo fw_reset > board_mode\n");
11789 		rc = -ENODEV;
11790 	}
11791 
11792 	return rc;
11793 }
11794 
11795 /**
11796  * lpfc_sli4_pci_mem_setup - Setup SLI4 HBA PCI memory space.
11797  * @phba: pointer to lpfc hba data structure.
11798  *
11799  * This routine is invoked to set up the PCI device memory space for device
11800  * with SLI-4 interface spec.
11801  *
11802  * Return codes
11803  * 	0 - successful
11804  * 	other values - error
11805  **/
11806 static int
11807 lpfc_sli4_pci_mem_setup(struct lpfc_hba *phba)
11808 {
11809 	struct pci_dev *pdev = phba->pcidev;
11810 	unsigned long bar0map_len, bar1map_len, bar2map_len;
11811 	int error;
11812 	uint32_t if_type;
11813 
11814 	if (!pdev)
11815 		return -ENODEV;
11816 
11817 	/* Set the device DMA mask size */
11818 	error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
11819 	if (error)
11820 		error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32));
11821 	if (error)
11822 		return error;
11823 
11824 	/*
11825 	 * The BARs and register set definitions and offset locations are
11826 	 * dependent on the if_type.
11827 	 */
11828 	if (pci_read_config_dword(pdev, LPFC_SLI_INTF,
11829 				  &phba->sli4_hba.sli_intf.word0)) {
11830 		return -ENODEV;
11831 	}
11832 
11833 	/* There is no SLI3 failback for SLI4 devices. */
11834 	if (bf_get(lpfc_sli_intf_valid, &phba->sli4_hba.sli_intf) !=
11835 	    LPFC_SLI_INTF_VALID) {
11836 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11837 				"2894 SLI_INTF reg contents invalid "
11838 				"sli_intf reg 0x%x\n",
11839 				phba->sli4_hba.sli_intf.word0);
11840 		return -ENODEV;
11841 	}
11842 
11843 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
11844 	/*
11845 	 * Get the bus address of SLI4 device Bar regions and the
11846 	 * number of bytes required by each mapping. The mapping of the
11847 	 * particular PCI BARs regions is dependent on the type of
11848 	 * SLI4 device.
11849 	 */
11850 	if (pci_resource_start(pdev, PCI_64BIT_BAR0)) {
11851 		phba->pci_bar0_map = pci_resource_start(pdev, PCI_64BIT_BAR0);
11852 		bar0map_len = pci_resource_len(pdev, PCI_64BIT_BAR0);
11853 
11854 		/*
11855 		 * Map SLI4 PCI Config Space Register base to a kernel virtual
11856 		 * addr
11857 		 */
11858 		phba->sli4_hba.conf_regs_memmap_p =
11859 			ioremap(phba->pci_bar0_map, bar0map_len);
11860 		if (!phba->sli4_hba.conf_regs_memmap_p) {
11861 			dev_printk(KERN_ERR, &pdev->dev,
11862 				   "ioremap failed for SLI4 PCI config "
11863 				   "registers.\n");
11864 			return -ENODEV;
11865 		}
11866 		phba->pci_bar0_memmap_p = phba->sli4_hba.conf_regs_memmap_p;
11867 		/* Set up BAR0 PCI config space register memory map */
11868 		lpfc_sli4_bar0_register_memmap(phba, if_type);
11869 	} else {
11870 		phba->pci_bar0_map = pci_resource_start(pdev, 1);
11871 		bar0map_len = pci_resource_len(pdev, 1);
11872 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
11873 			dev_printk(KERN_ERR, &pdev->dev,
11874 			   "FATAL - No BAR0 mapping for SLI4, if_type 2\n");
11875 			return -ENODEV;
11876 		}
11877 		phba->sli4_hba.conf_regs_memmap_p =
11878 				ioremap(phba->pci_bar0_map, bar0map_len);
11879 		if (!phba->sli4_hba.conf_regs_memmap_p) {
11880 			dev_printk(KERN_ERR, &pdev->dev,
11881 				"ioremap failed for SLI4 PCI config "
11882 				"registers.\n");
11883 			return -ENODEV;
11884 		}
11885 		lpfc_sli4_bar0_register_memmap(phba, if_type);
11886 	}
11887 
11888 	if (if_type == LPFC_SLI_INTF_IF_TYPE_0) {
11889 		if (pci_resource_start(pdev, PCI_64BIT_BAR2)) {
11890 			/*
11891 			 * Map SLI4 if type 0 HBA Control Register base to a
11892 			 * kernel virtual address and setup the registers.
11893 			 */
11894 			phba->pci_bar1_map = pci_resource_start(pdev,
11895 								PCI_64BIT_BAR2);
11896 			bar1map_len = pci_resource_len(pdev, PCI_64BIT_BAR2);
11897 			phba->sli4_hba.ctrl_regs_memmap_p =
11898 					ioremap(phba->pci_bar1_map,
11899 						bar1map_len);
11900 			if (!phba->sli4_hba.ctrl_regs_memmap_p) {
11901 				dev_err(&pdev->dev,
11902 					   "ioremap failed for SLI4 HBA "
11903 					    "control registers.\n");
11904 				error = -ENOMEM;
11905 				goto out_iounmap_conf;
11906 			}
11907 			phba->pci_bar2_memmap_p =
11908 					 phba->sli4_hba.ctrl_regs_memmap_p;
11909 			lpfc_sli4_bar1_register_memmap(phba, if_type);
11910 		} else {
11911 			error = -ENOMEM;
11912 			goto out_iounmap_conf;
11913 		}
11914 	}
11915 
11916 	if ((if_type == LPFC_SLI_INTF_IF_TYPE_6) &&
11917 	    (pci_resource_start(pdev, PCI_64BIT_BAR2))) {
11918 		/*
11919 		 * Map SLI4 if type 6 HBA Doorbell Register base to a kernel
11920 		 * virtual address and setup the registers.
11921 		 */
11922 		phba->pci_bar1_map = pci_resource_start(pdev, PCI_64BIT_BAR2);
11923 		bar1map_len = pci_resource_len(pdev, PCI_64BIT_BAR2);
11924 		phba->sli4_hba.drbl_regs_memmap_p =
11925 				ioremap(phba->pci_bar1_map, bar1map_len);
11926 		if (!phba->sli4_hba.drbl_regs_memmap_p) {
11927 			dev_err(&pdev->dev,
11928 			   "ioremap failed for SLI4 HBA doorbell registers.\n");
11929 			error = -ENOMEM;
11930 			goto out_iounmap_conf;
11931 		}
11932 		phba->pci_bar2_memmap_p = phba->sli4_hba.drbl_regs_memmap_p;
11933 		lpfc_sli4_bar1_register_memmap(phba, if_type);
11934 	}
11935 
11936 	if (if_type == LPFC_SLI_INTF_IF_TYPE_0) {
11937 		if (pci_resource_start(pdev, PCI_64BIT_BAR4)) {
11938 			/*
11939 			 * Map SLI4 if type 0 HBA Doorbell Register base to
11940 			 * a kernel virtual address and setup the registers.
11941 			 */
11942 			phba->pci_bar2_map = pci_resource_start(pdev,
11943 								PCI_64BIT_BAR4);
11944 			bar2map_len = pci_resource_len(pdev, PCI_64BIT_BAR4);
11945 			phba->sli4_hba.drbl_regs_memmap_p =
11946 					ioremap(phba->pci_bar2_map,
11947 						bar2map_len);
11948 			if (!phba->sli4_hba.drbl_regs_memmap_p) {
11949 				dev_err(&pdev->dev,
11950 					   "ioremap failed for SLI4 HBA"
11951 					   " doorbell registers.\n");
11952 				error = -ENOMEM;
11953 				goto out_iounmap_ctrl;
11954 			}
11955 			phba->pci_bar4_memmap_p =
11956 					phba->sli4_hba.drbl_regs_memmap_p;
11957 			error = lpfc_sli4_bar2_register_memmap(phba, LPFC_VF0);
11958 			if (error)
11959 				goto out_iounmap_all;
11960 		} else {
11961 			error = -ENOMEM;
11962 			goto out_iounmap_ctrl;
11963 		}
11964 	}
11965 
11966 	if (if_type == LPFC_SLI_INTF_IF_TYPE_6 &&
11967 	    pci_resource_start(pdev, PCI_64BIT_BAR4)) {
11968 		/*
11969 		 * Map SLI4 if type 6 HBA DPP Register base to a kernel
11970 		 * virtual address and setup the registers.
11971 		 */
11972 		phba->pci_bar2_map = pci_resource_start(pdev, PCI_64BIT_BAR4);
11973 		bar2map_len = pci_resource_len(pdev, PCI_64BIT_BAR4);
11974 		phba->sli4_hba.dpp_regs_memmap_p =
11975 				ioremap(phba->pci_bar2_map, bar2map_len);
11976 		if (!phba->sli4_hba.dpp_regs_memmap_p) {
11977 			dev_err(&pdev->dev,
11978 			   "ioremap failed for SLI4 HBA dpp registers.\n");
11979 			error = -ENOMEM;
11980 			goto out_iounmap_all;
11981 		}
11982 		phba->pci_bar4_memmap_p = phba->sli4_hba.dpp_regs_memmap_p;
11983 	}
11984 
11985 	/* Set up the EQ/CQ register handeling functions now */
11986 	switch (if_type) {
11987 	case LPFC_SLI_INTF_IF_TYPE_0:
11988 	case LPFC_SLI_INTF_IF_TYPE_2:
11989 		phba->sli4_hba.sli4_eq_clr_intr = lpfc_sli4_eq_clr_intr;
11990 		phba->sli4_hba.sli4_write_eq_db = lpfc_sli4_write_eq_db;
11991 		phba->sli4_hba.sli4_write_cq_db = lpfc_sli4_write_cq_db;
11992 		break;
11993 	case LPFC_SLI_INTF_IF_TYPE_6:
11994 		phba->sli4_hba.sli4_eq_clr_intr = lpfc_sli4_if6_eq_clr_intr;
11995 		phba->sli4_hba.sli4_write_eq_db = lpfc_sli4_if6_write_eq_db;
11996 		phba->sli4_hba.sli4_write_cq_db = lpfc_sli4_if6_write_cq_db;
11997 		break;
11998 	default:
11999 		break;
12000 	}
12001 
12002 	return 0;
12003 
12004 out_iounmap_all:
12005 	if (phba->sli4_hba.drbl_regs_memmap_p)
12006 		iounmap(phba->sli4_hba.drbl_regs_memmap_p);
12007 out_iounmap_ctrl:
12008 	if (phba->sli4_hba.ctrl_regs_memmap_p)
12009 		iounmap(phba->sli4_hba.ctrl_regs_memmap_p);
12010 out_iounmap_conf:
12011 	iounmap(phba->sli4_hba.conf_regs_memmap_p);
12012 
12013 	return error;
12014 }
12015 
12016 /**
12017  * lpfc_sli4_pci_mem_unset - Unset SLI4 HBA PCI memory space.
12018  * @phba: pointer to lpfc hba data structure.
12019  *
12020  * This routine is invoked to unset the PCI device memory space for device
12021  * with SLI-4 interface spec.
12022  **/
12023 static void
12024 lpfc_sli4_pci_mem_unset(struct lpfc_hba *phba)
12025 {
12026 	uint32_t if_type;
12027 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
12028 
12029 	switch (if_type) {
12030 	case LPFC_SLI_INTF_IF_TYPE_0:
12031 		iounmap(phba->sli4_hba.drbl_regs_memmap_p);
12032 		iounmap(phba->sli4_hba.ctrl_regs_memmap_p);
12033 		iounmap(phba->sli4_hba.conf_regs_memmap_p);
12034 		break;
12035 	case LPFC_SLI_INTF_IF_TYPE_2:
12036 		iounmap(phba->sli4_hba.conf_regs_memmap_p);
12037 		break;
12038 	case LPFC_SLI_INTF_IF_TYPE_6:
12039 		iounmap(phba->sli4_hba.drbl_regs_memmap_p);
12040 		iounmap(phba->sli4_hba.conf_regs_memmap_p);
12041 		if (phba->sli4_hba.dpp_regs_memmap_p)
12042 			iounmap(phba->sli4_hba.dpp_regs_memmap_p);
12043 		break;
12044 	case LPFC_SLI_INTF_IF_TYPE_1:
12045 		break;
12046 	default:
12047 		dev_printk(KERN_ERR, &phba->pcidev->dev,
12048 			   "FATAL - unsupported SLI4 interface type - %d\n",
12049 			   if_type);
12050 		break;
12051 	}
12052 }
12053 
12054 /**
12055  * lpfc_sli_enable_msix - Enable MSI-X interrupt mode on SLI-3 device
12056  * @phba: pointer to lpfc hba data structure.
12057  *
12058  * This routine is invoked to enable the MSI-X interrupt vectors to device
12059  * with SLI-3 interface specs.
12060  *
12061  * Return codes
12062  *   0 - successful
12063  *   other values - error
12064  **/
12065 static int
12066 lpfc_sli_enable_msix(struct lpfc_hba *phba)
12067 {
12068 	int rc;
12069 	LPFC_MBOXQ_t *pmb;
12070 
12071 	/* Set up MSI-X multi-message vectors */
12072 	rc = pci_alloc_irq_vectors(phba->pcidev,
12073 			LPFC_MSIX_VECTORS, LPFC_MSIX_VECTORS, PCI_IRQ_MSIX);
12074 	if (rc < 0) {
12075 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12076 				"0420 PCI enable MSI-X failed (%d)\n", rc);
12077 		goto vec_fail_out;
12078 	}
12079 
12080 	/*
12081 	 * Assign MSI-X vectors to interrupt handlers
12082 	 */
12083 
12084 	/* vector-0 is associated to slow-path handler */
12085 	rc = request_irq(pci_irq_vector(phba->pcidev, 0),
12086 			 &lpfc_sli_sp_intr_handler, 0,
12087 			 LPFC_SP_DRIVER_HANDLER_NAME, phba);
12088 	if (rc) {
12089 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
12090 				"0421 MSI-X slow-path request_irq failed "
12091 				"(%d)\n", rc);
12092 		goto msi_fail_out;
12093 	}
12094 
12095 	/* vector-1 is associated to fast-path handler */
12096 	rc = request_irq(pci_irq_vector(phba->pcidev, 1),
12097 			 &lpfc_sli_fp_intr_handler, 0,
12098 			 LPFC_FP_DRIVER_HANDLER_NAME, phba);
12099 
12100 	if (rc) {
12101 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
12102 				"0429 MSI-X fast-path request_irq failed "
12103 				"(%d)\n", rc);
12104 		goto irq_fail_out;
12105 	}
12106 
12107 	/*
12108 	 * Configure HBA MSI-X attention conditions to messages
12109 	 */
12110 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
12111 
12112 	if (!pmb) {
12113 		rc = -ENOMEM;
12114 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12115 				"0474 Unable to allocate memory for issuing "
12116 				"MBOX_CONFIG_MSI command\n");
12117 		goto mem_fail_out;
12118 	}
12119 	rc = lpfc_config_msi(phba, pmb);
12120 	if (rc)
12121 		goto mbx_fail_out;
12122 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
12123 	if (rc != MBX_SUCCESS) {
12124 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX,
12125 				"0351 Config MSI mailbox command failed, "
12126 				"mbxCmd x%x, mbxStatus x%x\n",
12127 				pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus);
12128 		goto mbx_fail_out;
12129 	}
12130 
12131 	/* Free memory allocated for mailbox command */
12132 	mempool_free(pmb, phba->mbox_mem_pool);
12133 	return rc;
12134 
12135 mbx_fail_out:
12136 	/* Free memory allocated for mailbox command */
12137 	mempool_free(pmb, phba->mbox_mem_pool);
12138 
12139 mem_fail_out:
12140 	/* free the irq already requested */
12141 	free_irq(pci_irq_vector(phba->pcidev, 1), phba);
12142 
12143 irq_fail_out:
12144 	/* free the irq already requested */
12145 	free_irq(pci_irq_vector(phba->pcidev, 0), phba);
12146 
12147 msi_fail_out:
12148 	/* Unconfigure MSI-X capability structure */
12149 	pci_free_irq_vectors(phba->pcidev);
12150 
12151 vec_fail_out:
12152 	return rc;
12153 }
12154 
12155 /**
12156  * lpfc_sli_enable_msi - Enable MSI interrupt mode on SLI-3 device.
12157  * @phba: pointer to lpfc hba data structure.
12158  *
12159  * This routine is invoked to enable the MSI interrupt mode to device with
12160  * SLI-3 interface spec. The kernel function pci_enable_msi() is called to
12161  * enable the MSI vector. The device driver is responsible for calling the
12162  * request_irq() to register MSI vector with a interrupt the handler, which
12163  * is done in this function.
12164  *
12165  * Return codes
12166  * 	0 - successful
12167  * 	other values - error
12168  */
12169 static int
12170 lpfc_sli_enable_msi(struct lpfc_hba *phba)
12171 {
12172 	int rc;
12173 
12174 	rc = pci_enable_msi(phba->pcidev);
12175 	if (!rc)
12176 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12177 				"0012 PCI enable MSI mode success.\n");
12178 	else {
12179 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12180 				"0471 PCI enable MSI mode failed (%d)\n", rc);
12181 		return rc;
12182 	}
12183 
12184 	rc = request_irq(phba->pcidev->irq, lpfc_sli_intr_handler,
12185 			 0, LPFC_DRIVER_NAME, phba);
12186 	if (rc) {
12187 		pci_disable_msi(phba->pcidev);
12188 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
12189 				"0478 MSI request_irq failed (%d)\n", rc);
12190 	}
12191 	return rc;
12192 }
12193 
12194 /**
12195  * lpfc_sli_enable_intr - Enable device interrupt to SLI-3 device.
12196  * @phba: pointer to lpfc hba data structure.
12197  * @cfg_mode: Interrupt configuration mode (INTx, MSI or MSI-X).
12198  *
12199  * This routine is invoked to enable device interrupt and associate driver's
12200  * interrupt handler(s) to interrupt vector(s) to device with SLI-3 interface
12201  * spec. Depends on the interrupt mode configured to the driver, the driver
12202  * will try to fallback from the configured interrupt mode to an interrupt
12203  * mode which is supported by the platform, kernel, and device in the order
12204  * of:
12205  * MSI-X -> MSI -> IRQ.
12206  *
12207  * Return codes
12208  *   0 - successful
12209  *   other values - error
12210  **/
12211 static uint32_t
12212 lpfc_sli_enable_intr(struct lpfc_hba *phba, uint32_t cfg_mode)
12213 {
12214 	uint32_t intr_mode = LPFC_INTR_ERROR;
12215 	int retval;
12216 
12217 	/* Need to issue conf_port mbox cmd before conf_msi mbox cmd */
12218 	retval = lpfc_sli_config_port(phba, LPFC_SLI_REV3);
12219 	if (retval)
12220 		return intr_mode;
12221 	clear_bit(HBA_NEEDS_CFG_PORT, &phba->hba_flag);
12222 
12223 	if (cfg_mode == 2) {
12224 		/* Now, try to enable MSI-X interrupt mode */
12225 		retval = lpfc_sli_enable_msix(phba);
12226 		if (!retval) {
12227 			/* Indicate initialization to MSI-X mode */
12228 			phba->intr_type = MSIX;
12229 			intr_mode = 2;
12230 		}
12231 	}
12232 
12233 	/* Fallback to MSI if MSI-X initialization failed */
12234 	if (cfg_mode >= 1 && phba->intr_type == NONE) {
12235 		retval = lpfc_sli_enable_msi(phba);
12236 		if (!retval) {
12237 			/* Indicate initialization to MSI mode */
12238 			phba->intr_type = MSI;
12239 			intr_mode = 1;
12240 		}
12241 	}
12242 
12243 	/* Fallback to INTx if both MSI-X/MSI initalization failed */
12244 	if (phba->intr_type == NONE) {
12245 		retval = request_irq(phba->pcidev->irq, lpfc_sli_intr_handler,
12246 				     IRQF_SHARED, LPFC_DRIVER_NAME, phba);
12247 		if (!retval) {
12248 			/* Indicate initialization to INTx mode */
12249 			phba->intr_type = INTx;
12250 			intr_mode = 0;
12251 		}
12252 	}
12253 	return intr_mode;
12254 }
12255 
12256 /**
12257  * lpfc_sli_disable_intr - Disable device interrupt to SLI-3 device.
12258  * @phba: pointer to lpfc hba data structure.
12259  *
12260  * This routine is invoked to disable device interrupt and disassociate the
12261  * driver's interrupt handler(s) from interrupt vector(s) to device with
12262  * SLI-3 interface spec. Depending on the interrupt mode, the driver will
12263  * release the interrupt vector(s) for the message signaled interrupt.
12264  **/
12265 static void
12266 lpfc_sli_disable_intr(struct lpfc_hba *phba)
12267 {
12268 	int nr_irqs, i;
12269 
12270 	if (phba->intr_type == MSIX)
12271 		nr_irqs = LPFC_MSIX_VECTORS;
12272 	else
12273 		nr_irqs = 1;
12274 
12275 	for (i = 0; i < nr_irqs; i++)
12276 		free_irq(pci_irq_vector(phba->pcidev, i), phba);
12277 	pci_free_irq_vectors(phba->pcidev);
12278 
12279 	/* Reset interrupt management states */
12280 	phba->intr_type = NONE;
12281 	phba->sli.slistat.sli_intr = 0;
12282 }
12283 
12284 /**
12285  * lpfc_find_cpu_handle - Find the CPU that corresponds to the specified Queue
12286  * @phba: pointer to lpfc hba data structure.
12287  * @id: EQ vector index or Hardware Queue index
12288  * @match: LPFC_FIND_BY_EQ = match by EQ
12289  *         LPFC_FIND_BY_HDWQ = match by Hardware Queue
12290  * Return the CPU that matches the selection criteria
12291  */
12292 static uint16_t
12293 lpfc_find_cpu_handle(struct lpfc_hba *phba, uint16_t id, int match)
12294 {
12295 	struct lpfc_vector_map_info *cpup;
12296 	int cpu;
12297 
12298 	/* Loop through all CPUs */
12299 	for_each_present_cpu(cpu) {
12300 		cpup = &phba->sli4_hba.cpu_map[cpu];
12301 
12302 		/* If we are matching by EQ, there may be multiple CPUs using
12303 		 * using the same vector, so select the one with
12304 		 * LPFC_CPU_FIRST_IRQ set.
12305 		 */
12306 		if ((match == LPFC_FIND_BY_EQ) &&
12307 		    (cpup->flag & LPFC_CPU_FIRST_IRQ) &&
12308 		    (cpup->eq == id))
12309 			return cpu;
12310 
12311 		/* If matching by HDWQ, select the first CPU that matches */
12312 		if ((match == LPFC_FIND_BY_HDWQ) && (cpup->hdwq == id))
12313 			return cpu;
12314 	}
12315 	return 0;
12316 }
12317 
12318 #ifdef CONFIG_X86
12319 /**
12320  * lpfc_find_hyper - Determine if the CPU map entry is hyper-threaded
12321  * @phba: pointer to lpfc hba data structure.
12322  * @cpu: CPU map index
12323  * @phys_id: CPU package physical id
12324  * @core_id: CPU core id
12325  */
12326 static int
12327 lpfc_find_hyper(struct lpfc_hba *phba, int cpu,
12328 		uint16_t phys_id, uint16_t core_id)
12329 {
12330 	struct lpfc_vector_map_info *cpup;
12331 	int idx;
12332 
12333 	for_each_present_cpu(idx) {
12334 		cpup = &phba->sli4_hba.cpu_map[idx];
12335 		/* Does the cpup match the one we are looking for */
12336 		if ((cpup->phys_id == phys_id) &&
12337 		    (cpup->core_id == core_id) &&
12338 		    (cpu != idx))
12339 			return 1;
12340 	}
12341 	return 0;
12342 }
12343 #endif
12344 
12345 /*
12346  * lpfc_assign_eq_map_info - Assigns eq for vector_map structure
12347  * @phba: pointer to lpfc hba data structure.
12348  * @eqidx: index for eq and irq vector
12349  * @flag: flags to set for vector_map structure
12350  * @cpu: cpu used to index vector_map structure
12351  *
12352  * The routine assigns eq info into vector_map structure
12353  */
12354 static inline void
12355 lpfc_assign_eq_map_info(struct lpfc_hba *phba, uint16_t eqidx, uint16_t flag,
12356 			unsigned int cpu)
12357 {
12358 	struct lpfc_vector_map_info *cpup = &phba->sli4_hba.cpu_map[cpu];
12359 	struct lpfc_hba_eq_hdl *eqhdl = lpfc_get_eq_hdl(eqidx);
12360 
12361 	cpup->eq = eqidx;
12362 	cpup->flag |= flag;
12363 
12364 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12365 			"3336 Set Affinity: CPU %d irq %d eq %d flag x%x\n",
12366 			cpu, eqhdl->irq, cpup->eq, cpup->flag);
12367 }
12368 
12369 /**
12370  * lpfc_cpu_map_array_init - Initialize cpu_map structure
12371  * @phba: pointer to lpfc hba data structure.
12372  *
12373  * The routine initializes the cpu_map array structure
12374  */
12375 static void
12376 lpfc_cpu_map_array_init(struct lpfc_hba *phba)
12377 {
12378 	struct lpfc_vector_map_info *cpup;
12379 	struct lpfc_eq_intr_info *eqi;
12380 	int cpu;
12381 
12382 	for_each_possible_cpu(cpu) {
12383 		cpup = &phba->sli4_hba.cpu_map[cpu];
12384 		cpup->phys_id = LPFC_VECTOR_MAP_EMPTY;
12385 		cpup->core_id = LPFC_VECTOR_MAP_EMPTY;
12386 		cpup->hdwq = LPFC_VECTOR_MAP_EMPTY;
12387 		cpup->eq = LPFC_VECTOR_MAP_EMPTY;
12388 		cpup->flag = 0;
12389 		eqi = per_cpu_ptr(phba->sli4_hba.eq_info, cpu);
12390 		INIT_LIST_HEAD(&eqi->list);
12391 		eqi->icnt = 0;
12392 	}
12393 }
12394 
12395 /**
12396  * lpfc_hba_eq_hdl_array_init - Initialize hba_eq_hdl structure
12397  * @phba: pointer to lpfc hba data structure.
12398  *
12399  * The routine initializes the hba_eq_hdl array structure
12400  */
12401 static void
12402 lpfc_hba_eq_hdl_array_init(struct lpfc_hba *phba)
12403 {
12404 	struct lpfc_hba_eq_hdl *eqhdl;
12405 	int i;
12406 
12407 	for (i = 0; i < phba->cfg_irq_chann; i++) {
12408 		eqhdl = lpfc_get_eq_hdl(i);
12409 		eqhdl->irq = LPFC_IRQ_EMPTY;
12410 		eqhdl->phba = phba;
12411 	}
12412 }
12413 
12414 /**
12415  * lpfc_cpu_affinity_check - Check vector CPU affinity mappings
12416  * @phba: pointer to lpfc hba data structure.
12417  * @vectors: number of msix vectors allocated.
12418  *
12419  * The routine will figure out the CPU affinity assignment for every
12420  * MSI-X vector allocated for the HBA.
12421  * In addition, the CPU to IO channel mapping will be calculated
12422  * and the phba->sli4_hba.cpu_map array will reflect this.
12423  */
12424 static void
12425 lpfc_cpu_affinity_check(struct lpfc_hba *phba, int vectors)
12426 {
12427 	int i, cpu, idx, next_idx, new_cpu, start_cpu, first_cpu;
12428 	int max_phys_id, min_phys_id;
12429 	int max_core_id, min_core_id;
12430 	struct lpfc_vector_map_info *cpup;
12431 	struct lpfc_vector_map_info *new_cpup;
12432 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
12433 	struct lpfc_hdwq_stat *c_stat;
12434 #endif
12435 
12436 	max_phys_id = 0;
12437 	min_phys_id = LPFC_VECTOR_MAP_EMPTY;
12438 	max_core_id = 0;
12439 	min_core_id = LPFC_VECTOR_MAP_EMPTY;
12440 
12441 	/* Update CPU map with physical id and core id of each CPU */
12442 	for_each_present_cpu(cpu) {
12443 		cpup = &phba->sli4_hba.cpu_map[cpu];
12444 #ifdef CONFIG_X86
12445 		cpup->phys_id = topology_physical_package_id(cpu);
12446 		cpup->core_id = topology_core_id(cpu);
12447 		if (lpfc_find_hyper(phba, cpu, cpup->phys_id, cpup->core_id))
12448 			cpup->flag |= LPFC_CPU_MAP_HYPER;
12449 #else
12450 		/* No distinction between CPUs for other platforms */
12451 		cpup->phys_id = 0;
12452 		cpup->core_id = cpu;
12453 #endif
12454 
12455 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12456 				"3328 CPU %d physid %d coreid %d flag x%x\n",
12457 				cpu, cpup->phys_id, cpup->core_id, cpup->flag);
12458 
12459 		if (cpup->phys_id > max_phys_id)
12460 			max_phys_id = cpup->phys_id;
12461 		if (cpup->phys_id < min_phys_id)
12462 			min_phys_id = cpup->phys_id;
12463 
12464 		if (cpup->core_id > max_core_id)
12465 			max_core_id = cpup->core_id;
12466 		if (cpup->core_id < min_core_id)
12467 			min_core_id = cpup->core_id;
12468 	}
12469 
12470 	/* After looking at each irq vector assigned to this pcidev, its
12471 	 * possible to see that not ALL CPUs have been accounted for.
12472 	 * Next we will set any unassigned (unaffinitized) cpu map
12473 	 * entries to a IRQ on the same phys_id.
12474 	 */
12475 	first_cpu = cpumask_first(cpu_present_mask);
12476 	start_cpu = first_cpu;
12477 
12478 	for_each_present_cpu(cpu) {
12479 		cpup = &phba->sli4_hba.cpu_map[cpu];
12480 
12481 		/* Is this CPU entry unassigned */
12482 		if (cpup->eq == LPFC_VECTOR_MAP_EMPTY) {
12483 			/* Mark CPU as IRQ not assigned by the kernel */
12484 			cpup->flag |= LPFC_CPU_MAP_UNASSIGN;
12485 
12486 			/* If so, find a new_cpup that is on the SAME
12487 			 * phys_id as cpup. start_cpu will start where we
12488 			 * left off so all unassigned entries don't get assgined
12489 			 * the IRQ of the first entry.
12490 			 */
12491 			new_cpu = start_cpu;
12492 			for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12493 				new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12494 				if (!(new_cpup->flag & LPFC_CPU_MAP_UNASSIGN) &&
12495 				    (new_cpup->eq != LPFC_VECTOR_MAP_EMPTY) &&
12496 				    (new_cpup->phys_id == cpup->phys_id))
12497 					goto found_same;
12498 				new_cpu = lpfc_next_present_cpu(new_cpu);
12499 			}
12500 			/* At this point, we leave the CPU as unassigned */
12501 			continue;
12502 found_same:
12503 			/* We found a matching phys_id, so copy the IRQ info */
12504 			cpup->eq = new_cpup->eq;
12505 
12506 			/* Bump start_cpu to the next slot to minmize the
12507 			 * chance of having multiple unassigned CPU entries
12508 			 * selecting the same IRQ.
12509 			 */
12510 			start_cpu = lpfc_next_present_cpu(new_cpu);
12511 
12512 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12513 					"3337 Set Affinity: CPU %d "
12514 					"eq %d from peer cpu %d same "
12515 					"phys_id (%d)\n",
12516 					cpu, cpup->eq, new_cpu,
12517 					cpup->phys_id);
12518 		}
12519 	}
12520 
12521 	/* Set any unassigned cpu map entries to a IRQ on any phys_id */
12522 	start_cpu = first_cpu;
12523 
12524 	for_each_present_cpu(cpu) {
12525 		cpup = &phba->sli4_hba.cpu_map[cpu];
12526 
12527 		/* Is this entry unassigned */
12528 		if (cpup->eq == LPFC_VECTOR_MAP_EMPTY) {
12529 			/* Mark it as IRQ not assigned by the kernel */
12530 			cpup->flag |= LPFC_CPU_MAP_UNASSIGN;
12531 
12532 			/* If so, find a new_cpup thats on ANY phys_id
12533 			 * as the cpup. start_cpu will start where we
12534 			 * left off so all unassigned entries don't get
12535 			 * assigned the IRQ of the first entry.
12536 			 */
12537 			new_cpu = start_cpu;
12538 			for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12539 				new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12540 				if (!(new_cpup->flag & LPFC_CPU_MAP_UNASSIGN) &&
12541 				    (new_cpup->eq != LPFC_VECTOR_MAP_EMPTY))
12542 					goto found_any;
12543 				new_cpu = lpfc_next_present_cpu(new_cpu);
12544 			}
12545 			/* We should never leave an entry unassigned */
12546 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12547 					"3339 Set Affinity: CPU %d "
12548 					"eq %d UNASSIGNED\n",
12549 					cpup->hdwq, cpup->eq);
12550 			continue;
12551 found_any:
12552 			/* We found an available entry, copy the IRQ info */
12553 			cpup->eq = new_cpup->eq;
12554 
12555 			/* Bump start_cpu to the next slot to minmize the
12556 			 * chance of having multiple unassigned CPU entries
12557 			 * selecting the same IRQ.
12558 			 */
12559 			start_cpu = lpfc_next_present_cpu(new_cpu);
12560 
12561 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12562 					"3338 Set Affinity: CPU %d "
12563 					"eq %d from peer cpu %d (%d/%d)\n",
12564 					cpu, cpup->eq, new_cpu,
12565 					new_cpup->phys_id, new_cpup->core_id);
12566 		}
12567 	}
12568 
12569 	/* Assign hdwq indices that are unique across all cpus in the map
12570 	 * that are also FIRST_CPUs.
12571 	 */
12572 	idx = 0;
12573 	for_each_present_cpu(cpu) {
12574 		cpup = &phba->sli4_hba.cpu_map[cpu];
12575 
12576 		/* Only FIRST IRQs get a hdwq index assignment. */
12577 		if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
12578 			continue;
12579 
12580 		/* 1 to 1, the first LPFC_CPU_FIRST_IRQ cpus to a unique hdwq */
12581 		cpup->hdwq = idx;
12582 		idx++;
12583 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12584 				"3333 Set Affinity: CPU %d (phys %d core %d): "
12585 				"hdwq %d eq %d flg x%x\n",
12586 				cpu, cpup->phys_id, cpup->core_id,
12587 				cpup->hdwq, cpup->eq, cpup->flag);
12588 	}
12589 	/* Associate a hdwq with each cpu_map entry
12590 	 * This will be 1 to 1 - hdwq to cpu, unless there are less
12591 	 * hardware queues then CPUs. For that case we will just round-robin
12592 	 * the available hardware queues as they get assigned to CPUs.
12593 	 * The next_idx is the idx from the FIRST_CPU loop above to account
12594 	 * for irq_chann < hdwq.  The idx is used for round-robin assignments
12595 	 * and needs to start at 0.
12596 	 */
12597 	next_idx = idx;
12598 	start_cpu = 0;
12599 	idx = 0;
12600 	for_each_present_cpu(cpu) {
12601 		cpup = &phba->sli4_hba.cpu_map[cpu];
12602 
12603 		/* FIRST cpus are already mapped. */
12604 		if (cpup->flag & LPFC_CPU_FIRST_IRQ)
12605 			continue;
12606 
12607 		/* If the cfg_irq_chann < cfg_hdw_queue, set the hdwq
12608 		 * of the unassigned cpus to the next idx so that all
12609 		 * hdw queues are fully utilized.
12610 		 */
12611 		if (next_idx < phba->cfg_hdw_queue) {
12612 			cpup->hdwq = next_idx;
12613 			next_idx++;
12614 			continue;
12615 		}
12616 
12617 		/* Not a First CPU and all hdw_queues are used.  Reuse a
12618 		 * Hardware Queue for another CPU, so be smart about it
12619 		 * and pick one that has its IRQ/EQ mapped to the same phys_id
12620 		 * (CPU package) and core_id.
12621 		 */
12622 		new_cpu = start_cpu;
12623 		for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12624 			new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12625 			if (new_cpup->hdwq != LPFC_VECTOR_MAP_EMPTY &&
12626 			    new_cpup->phys_id == cpup->phys_id &&
12627 			    new_cpup->core_id == cpup->core_id) {
12628 				goto found_hdwq;
12629 			}
12630 			new_cpu = lpfc_next_present_cpu(new_cpu);
12631 		}
12632 
12633 		/* If we can't match both phys_id and core_id,
12634 		 * settle for just a phys_id match.
12635 		 */
12636 		new_cpu = start_cpu;
12637 		for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12638 			new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12639 			if (new_cpup->hdwq != LPFC_VECTOR_MAP_EMPTY &&
12640 			    new_cpup->phys_id == cpup->phys_id)
12641 				goto found_hdwq;
12642 			new_cpu = lpfc_next_present_cpu(new_cpu);
12643 		}
12644 
12645 		/* Otherwise just round robin on cfg_hdw_queue */
12646 		cpup->hdwq = idx % phba->cfg_hdw_queue;
12647 		idx++;
12648 		goto logit;
12649  found_hdwq:
12650 		/* We found an available entry, copy the IRQ info */
12651 		start_cpu = lpfc_next_present_cpu(new_cpu);
12652 		cpup->hdwq = new_cpup->hdwq;
12653  logit:
12654 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12655 				"3335 Set Affinity: CPU %d (phys %d core %d): "
12656 				"hdwq %d eq %d flg x%x\n",
12657 				cpu, cpup->phys_id, cpup->core_id,
12658 				cpup->hdwq, cpup->eq, cpup->flag);
12659 	}
12660 
12661 	/*
12662 	 * Initialize the cpu_map slots for not-present cpus in case
12663 	 * a cpu is hot-added. Perform a simple hdwq round robin assignment.
12664 	 */
12665 	idx = 0;
12666 	for_each_possible_cpu(cpu) {
12667 		cpup = &phba->sli4_hba.cpu_map[cpu];
12668 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
12669 		c_stat = per_cpu_ptr(phba->sli4_hba.c_stat, cpu);
12670 		c_stat->hdwq_no = cpup->hdwq;
12671 #endif
12672 		if (cpup->hdwq != LPFC_VECTOR_MAP_EMPTY)
12673 			continue;
12674 
12675 		cpup->hdwq = idx++ % phba->cfg_hdw_queue;
12676 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
12677 		c_stat->hdwq_no = cpup->hdwq;
12678 #endif
12679 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12680 				"3340 Set Affinity: not present "
12681 				"CPU %d hdwq %d\n",
12682 				cpu, cpup->hdwq);
12683 	}
12684 
12685 	/* The cpu_map array will be used later during initialization
12686 	 * when EQ / CQ / WQs are allocated and configured.
12687 	 */
12688 	return;
12689 }
12690 
12691 /**
12692  * lpfc_cpuhp_get_eq
12693  *
12694  * @phba:   pointer to lpfc hba data structure.
12695  * @cpu:    cpu going offline
12696  * @eqlist: eq list to append to
12697  */
12698 static int
12699 lpfc_cpuhp_get_eq(struct lpfc_hba *phba, unsigned int cpu,
12700 		  struct list_head *eqlist)
12701 {
12702 	const struct cpumask *maskp;
12703 	struct lpfc_queue *eq;
12704 	struct cpumask *tmp;
12705 	u16 idx;
12706 
12707 	tmp = kzalloc(cpumask_size(), GFP_KERNEL);
12708 	if (!tmp)
12709 		return -ENOMEM;
12710 
12711 	for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
12712 		maskp = pci_irq_get_affinity(phba->pcidev, idx);
12713 		if (!maskp)
12714 			continue;
12715 		/*
12716 		 * if irq is not affinitized to the cpu going
12717 		 * then we don't need to poll the eq attached
12718 		 * to it.
12719 		 */
12720 		if (!cpumask_and(tmp, maskp, cpumask_of(cpu)))
12721 			continue;
12722 		/* get the cpus that are online and are affini-
12723 		 * tized to this irq vector.  If the count is
12724 		 * more than 1 then cpuhp is not going to shut-
12725 		 * down this vector.  Since this cpu has not
12726 		 * gone offline yet, we need >1.
12727 		 */
12728 		cpumask_and(tmp, maskp, cpu_online_mask);
12729 		if (cpumask_weight(tmp) > 1)
12730 			continue;
12731 
12732 		/* Now that we have an irq to shutdown, get the eq
12733 		 * mapped to this irq.  Note: multiple hdwq's in
12734 		 * the software can share an eq, but eventually
12735 		 * only eq will be mapped to this vector
12736 		 */
12737 		eq = phba->sli4_hba.hba_eq_hdl[idx].eq;
12738 		list_add(&eq->_poll_list, eqlist);
12739 	}
12740 	kfree(tmp);
12741 	return 0;
12742 }
12743 
12744 static void __lpfc_cpuhp_remove(struct lpfc_hba *phba)
12745 {
12746 	if (phba->sli_rev != LPFC_SLI_REV4)
12747 		return;
12748 
12749 	cpuhp_state_remove_instance_nocalls(lpfc_cpuhp_state,
12750 					    &phba->cpuhp);
12751 	/*
12752 	 * unregistering the instance doesn't stop the polling
12753 	 * timer. Wait for the poll timer to retire.
12754 	 */
12755 	synchronize_rcu();
12756 	timer_delete_sync(&phba->cpuhp_poll_timer);
12757 }
12758 
12759 static void lpfc_cpuhp_remove(struct lpfc_hba *phba)
12760 {
12761 	if (phba->pport &&
12762 	    test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag))
12763 		return;
12764 
12765 	__lpfc_cpuhp_remove(phba);
12766 }
12767 
12768 static void lpfc_cpuhp_add(struct lpfc_hba *phba)
12769 {
12770 	if (phba->sli_rev != LPFC_SLI_REV4)
12771 		return;
12772 
12773 	rcu_read_lock();
12774 
12775 	if (!list_empty(&phba->poll_list))
12776 		mod_timer(&phba->cpuhp_poll_timer,
12777 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
12778 
12779 	rcu_read_unlock();
12780 
12781 	cpuhp_state_add_instance_nocalls(lpfc_cpuhp_state,
12782 					 &phba->cpuhp);
12783 }
12784 
12785 static int __lpfc_cpuhp_checks(struct lpfc_hba *phba, int *retval)
12786 {
12787 	if (test_bit(FC_UNLOADING, &phba->pport->load_flag)) {
12788 		*retval = -EAGAIN;
12789 		return true;
12790 	}
12791 
12792 	if (phba->sli_rev != LPFC_SLI_REV4) {
12793 		*retval = 0;
12794 		return true;
12795 	}
12796 
12797 	/* proceed with the hotplug */
12798 	return false;
12799 }
12800 
12801 /**
12802  * lpfc_irq_set_aff - set IRQ affinity
12803  * @eqhdl: EQ handle
12804  * @cpu: cpu to set affinity
12805  *
12806  **/
12807 static inline void
12808 lpfc_irq_set_aff(struct lpfc_hba_eq_hdl *eqhdl, unsigned int cpu)
12809 {
12810 	cpumask_clear(&eqhdl->aff_mask);
12811 	cpumask_set_cpu(cpu, &eqhdl->aff_mask);
12812 	irq_set_status_flags(eqhdl->irq, IRQ_NO_BALANCING);
12813 	irq_set_affinity(eqhdl->irq, &eqhdl->aff_mask);
12814 }
12815 
12816 /**
12817  * lpfc_irq_clear_aff - clear IRQ affinity
12818  * @eqhdl: EQ handle
12819  *
12820  **/
12821 static inline void
12822 lpfc_irq_clear_aff(struct lpfc_hba_eq_hdl *eqhdl)
12823 {
12824 	cpumask_clear(&eqhdl->aff_mask);
12825 	irq_clear_status_flags(eqhdl->irq, IRQ_NO_BALANCING);
12826 }
12827 
12828 /**
12829  * lpfc_irq_rebalance - rebalances IRQ affinity according to cpuhp event
12830  * @phba: pointer to HBA context object.
12831  * @cpu: cpu going offline/online
12832  * @offline: true, cpu is going offline. false, cpu is coming online.
12833  *
12834  * If cpu is going offline, we'll try our best effort to find the next
12835  * online cpu on the phba's original_mask and migrate all offlining IRQ
12836  * affinities.
12837  *
12838  * If cpu is coming online, reaffinitize the IRQ back to the onlining cpu.
12839  *
12840  * Note: Call only if NUMA or NHT mode is enabled, otherwise rely on
12841  *	 PCI_IRQ_AFFINITY to auto-manage IRQ affinity.
12842  *
12843  **/
12844 static void
12845 lpfc_irq_rebalance(struct lpfc_hba *phba, unsigned int cpu, bool offline)
12846 {
12847 	struct lpfc_vector_map_info *cpup;
12848 	struct cpumask *aff_mask;
12849 	unsigned int cpu_select, cpu_next, idx;
12850 	const struct cpumask *orig_mask;
12851 
12852 	if (phba->irq_chann_mode == NORMAL_MODE)
12853 		return;
12854 
12855 	orig_mask = &phba->sli4_hba.irq_aff_mask;
12856 
12857 	if (!cpumask_test_cpu(cpu, orig_mask))
12858 		return;
12859 
12860 	cpup = &phba->sli4_hba.cpu_map[cpu];
12861 
12862 	if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
12863 		return;
12864 
12865 	if (offline) {
12866 		/* Find next online CPU on original mask */
12867 		cpu_next = cpumask_next_wrap(cpu, orig_mask);
12868 		cpu_select = lpfc_next_online_cpu(orig_mask, cpu_next);
12869 
12870 		/* Found a valid CPU */
12871 		if ((cpu_select < nr_cpu_ids) && (cpu_select != cpu)) {
12872 			/* Go through each eqhdl and ensure offlining
12873 			 * cpu aff_mask is migrated
12874 			 */
12875 			for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
12876 				aff_mask = lpfc_get_aff_mask(idx);
12877 
12878 				/* Migrate affinity */
12879 				if (cpumask_test_cpu(cpu, aff_mask))
12880 					lpfc_irq_set_aff(lpfc_get_eq_hdl(idx),
12881 							 cpu_select);
12882 			}
12883 		} else {
12884 			/* Rely on irqbalance if no online CPUs left on NUMA */
12885 			for (idx = 0; idx < phba->cfg_irq_chann; idx++)
12886 				lpfc_irq_clear_aff(lpfc_get_eq_hdl(idx));
12887 		}
12888 	} else {
12889 		/* Migrate affinity back to this CPU */
12890 		lpfc_irq_set_aff(lpfc_get_eq_hdl(cpup->eq), cpu);
12891 	}
12892 }
12893 
12894 static int lpfc_cpu_offline(unsigned int cpu, struct hlist_node *node)
12895 {
12896 	struct lpfc_hba *phba = hlist_entry_safe(node, struct lpfc_hba, cpuhp);
12897 	struct lpfc_queue *eq, *next;
12898 	LIST_HEAD(eqlist);
12899 	int retval;
12900 
12901 	if (!phba) {
12902 		WARN_ONCE(!phba, "cpu: %u. phba:NULL", raw_smp_processor_id());
12903 		return 0;
12904 	}
12905 
12906 	if (__lpfc_cpuhp_checks(phba, &retval))
12907 		return retval;
12908 
12909 	lpfc_irq_rebalance(phba, cpu, true);
12910 
12911 	retval = lpfc_cpuhp_get_eq(phba, cpu, &eqlist);
12912 	if (retval)
12913 		return retval;
12914 
12915 	/* start polling on these eq's */
12916 	list_for_each_entry_safe(eq, next, &eqlist, _poll_list) {
12917 		list_del_init(&eq->_poll_list);
12918 		lpfc_sli4_start_polling(eq);
12919 	}
12920 
12921 	return 0;
12922 }
12923 
12924 static int lpfc_cpu_online(unsigned int cpu, struct hlist_node *node)
12925 {
12926 	struct lpfc_hba *phba = hlist_entry_safe(node, struct lpfc_hba, cpuhp);
12927 	struct lpfc_queue *eq, *next;
12928 	unsigned int n;
12929 	int retval;
12930 
12931 	if (!phba) {
12932 		WARN_ONCE(!phba, "cpu: %u. phba:NULL", raw_smp_processor_id());
12933 		return 0;
12934 	}
12935 
12936 	if (__lpfc_cpuhp_checks(phba, &retval))
12937 		return retval;
12938 
12939 	lpfc_irq_rebalance(phba, cpu, false);
12940 
12941 	list_for_each_entry_safe(eq, next, &phba->poll_list, _poll_list) {
12942 		n = lpfc_find_cpu_handle(phba, eq->hdwq, LPFC_FIND_BY_HDWQ);
12943 		if (n == cpu)
12944 			lpfc_sli4_stop_polling(eq);
12945 	}
12946 
12947 	return 0;
12948 }
12949 
12950 /**
12951  * lpfc_sli4_enable_msix - Enable MSI-X interrupt mode to SLI-4 device
12952  * @phba: pointer to lpfc hba data structure.
12953  *
12954  * This routine is invoked to enable the MSI-X interrupt vectors to device
12955  * with SLI-4 interface spec.  It also allocates MSI-X vectors and maps them
12956  * to cpus on the system.
12957  *
12958  * When cfg_irq_numa is enabled, the adapter will only allocate vectors for
12959  * the number of cpus on the same numa node as this adapter.  The vectors are
12960  * allocated without requesting OS affinity mapping.  A vector will be
12961  * allocated and assigned to each online and offline cpu.  If the cpu is
12962  * online, then affinity will be set to that cpu.  If the cpu is offline, then
12963  * affinity will be set to the nearest peer cpu within the numa node that is
12964  * online.  If there are no online cpus within the numa node, affinity is not
12965  * assigned and the OS may do as it pleases. Note: cpu vector affinity mapping
12966  * is consistent with the way cpu online/offline is handled when cfg_irq_numa is
12967  * configured.
12968  *
12969  * If numa mode is not enabled and there is more than 1 vector allocated, then
12970  * the driver relies on the managed irq interface where the OS assigns vector to
12971  * cpu affinity.  The driver will then use that affinity mapping to setup its
12972  * cpu mapping table.
12973  *
12974  * Return codes
12975  * 0 - successful
12976  * other values - error
12977  **/
12978 static int
12979 lpfc_sli4_enable_msix(struct lpfc_hba *phba)
12980 {
12981 	int vectors, rc, index;
12982 	char *name;
12983 	const struct cpumask *aff_mask = NULL;
12984 	unsigned int cpu = 0, cpu_cnt = 0, cpu_select = nr_cpu_ids;
12985 	struct lpfc_vector_map_info *cpup;
12986 	struct lpfc_hba_eq_hdl *eqhdl;
12987 	const struct cpumask *maskp;
12988 	unsigned int flags = PCI_IRQ_MSIX;
12989 
12990 	/* Set up MSI-X multi-message vectors */
12991 	vectors = phba->cfg_irq_chann;
12992 
12993 	if (phba->irq_chann_mode != NORMAL_MODE)
12994 		aff_mask = &phba->sli4_hba.irq_aff_mask;
12995 
12996 	if (aff_mask) {
12997 		cpu_cnt = cpumask_weight(aff_mask);
12998 		vectors = min(phba->cfg_irq_chann, cpu_cnt);
12999 
13000 		/* cpu: iterates over aff_mask including offline or online
13001 		 * cpu_select: iterates over online aff_mask to set affinity
13002 		 */
13003 		cpu = cpumask_first(aff_mask);
13004 		cpu_select = lpfc_next_online_cpu(aff_mask, cpu);
13005 	} else {
13006 		flags |= PCI_IRQ_AFFINITY;
13007 	}
13008 
13009 	rc = pci_alloc_irq_vectors(phba->pcidev, 1, vectors, flags);
13010 	if (rc < 0) {
13011 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13012 				"0484 PCI enable MSI-X failed (%d)\n", rc);
13013 		goto vec_fail_out;
13014 	}
13015 	vectors = rc;
13016 
13017 	/* Assign MSI-X vectors to interrupt handlers */
13018 	for (index = 0; index < vectors; index++) {
13019 		eqhdl = lpfc_get_eq_hdl(index);
13020 		name = eqhdl->handler_name;
13021 		memset(name, 0, LPFC_SLI4_HANDLER_NAME_SZ);
13022 		snprintf(name, LPFC_SLI4_HANDLER_NAME_SZ,
13023 			 LPFC_DRIVER_HANDLER_NAME"%d", index);
13024 
13025 		eqhdl->idx = index;
13026 		rc = pci_irq_vector(phba->pcidev, index);
13027 		if (rc < 0) {
13028 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13029 					"0489 MSI-X fast-path (%d) "
13030 					"pci_irq_vec failed (%d)\n", index, rc);
13031 			goto cfg_fail_out;
13032 		}
13033 		eqhdl->irq = rc;
13034 
13035 		rc = request_threaded_irq(eqhdl->irq,
13036 					  &lpfc_sli4_hba_intr_handler,
13037 					  &lpfc_sli4_hba_intr_handler_th,
13038 					  0, name, eqhdl);
13039 		if (rc) {
13040 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13041 					"0486 MSI-X fast-path (%d) "
13042 					"request_irq failed (%d)\n", index, rc);
13043 			goto cfg_fail_out;
13044 		}
13045 
13046 		if (aff_mask) {
13047 			/* If found a neighboring online cpu, set affinity */
13048 			if (cpu_select < nr_cpu_ids)
13049 				lpfc_irq_set_aff(eqhdl, cpu_select);
13050 
13051 			/* Assign EQ to cpu_map */
13052 			lpfc_assign_eq_map_info(phba, index,
13053 						LPFC_CPU_FIRST_IRQ,
13054 						cpu);
13055 
13056 			/* Iterate to next offline or online cpu in aff_mask */
13057 			cpu = cpumask_next(cpu, aff_mask);
13058 
13059 			/* Find next online cpu in aff_mask to set affinity */
13060 			cpu_select = lpfc_next_online_cpu(aff_mask, cpu);
13061 		} else if (vectors == 1) {
13062 			cpu = cpumask_first(cpu_present_mask);
13063 			lpfc_assign_eq_map_info(phba, index, LPFC_CPU_FIRST_IRQ,
13064 						cpu);
13065 		} else {
13066 			maskp = pci_irq_get_affinity(phba->pcidev, index);
13067 
13068 			/* Loop through all CPUs associated with vector index */
13069 			for_each_cpu_and(cpu, maskp, cpu_present_mask) {
13070 				cpup = &phba->sli4_hba.cpu_map[cpu];
13071 
13072 				/* If this is the first CPU thats assigned to
13073 				 * this vector, set LPFC_CPU_FIRST_IRQ.
13074 				 *
13075 				 * With certain platforms its possible that irq
13076 				 * vectors are affinitized to all the cpu's.
13077 				 * This can result in each cpu_map.eq to be set
13078 				 * to the last vector, resulting in overwrite
13079 				 * of all the previous cpu_map.eq.  Ensure that
13080 				 * each vector receives a place in cpu_map.
13081 				 * Later call to lpfc_cpu_affinity_check will
13082 				 * ensure we are nicely balanced out.
13083 				 */
13084 				if (cpup->eq != LPFC_VECTOR_MAP_EMPTY)
13085 					continue;
13086 				lpfc_assign_eq_map_info(phba, index,
13087 							LPFC_CPU_FIRST_IRQ,
13088 							cpu);
13089 				break;
13090 			}
13091 		}
13092 	}
13093 
13094 	if (vectors != phba->cfg_irq_chann) {
13095 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13096 				"3238 Reducing IO channels to match number of "
13097 				"MSI-X vectors, requested %d got %d\n",
13098 				phba->cfg_irq_chann, vectors);
13099 		if (phba->cfg_irq_chann > vectors)
13100 			phba->cfg_irq_chann = vectors;
13101 	}
13102 
13103 	return rc;
13104 
13105 cfg_fail_out:
13106 	/* free the irq already requested */
13107 	for (--index; index >= 0; index--) {
13108 		eqhdl = lpfc_get_eq_hdl(index);
13109 		lpfc_irq_clear_aff(eqhdl);
13110 		free_irq(eqhdl->irq, eqhdl);
13111 	}
13112 
13113 	/* Unconfigure MSI-X capability structure */
13114 	pci_free_irq_vectors(phba->pcidev);
13115 
13116 vec_fail_out:
13117 	return rc;
13118 }
13119 
13120 /**
13121  * lpfc_sli4_enable_msi - Enable MSI interrupt mode to SLI-4 device
13122  * @phba: pointer to lpfc hba data structure.
13123  *
13124  * This routine is invoked to enable the MSI interrupt mode to device with
13125  * SLI-4 interface spec. The kernel function pci_alloc_irq_vectors() is
13126  * called to enable the MSI vector. The device driver is responsible for
13127  * calling the request_irq() to register MSI vector with a interrupt the
13128  * handler, which is done in this function.
13129  *
13130  * Return codes
13131  * 	0 - successful
13132  * 	other values - error
13133  **/
13134 static int
13135 lpfc_sli4_enable_msi(struct lpfc_hba *phba)
13136 {
13137 	int rc, index;
13138 	unsigned int cpu;
13139 	struct lpfc_hba_eq_hdl *eqhdl;
13140 
13141 	rc = pci_alloc_irq_vectors(phba->pcidev, 1, 1,
13142 				   PCI_IRQ_MSI | PCI_IRQ_AFFINITY);
13143 	if (rc > 0)
13144 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13145 				"0487 PCI enable MSI mode success.\n");
13146 	else {
13147 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13148 				"0488 PCI enable MSI mode failed (%d)\n", rc);
13149 		return rc ? rc : -1;
13150 	}
13151 
13152 	rc = request_irq(phba->pcidev->irq, lpfc_sli4_intr_handler,
13153 			 0, LPFC_DRIVER_NAME, phba);
13154 	if (rc) {
13155 		pci_free_irq_vectors(phba->pcidev);
13156 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13157 				"0490 MSI request_irq failed (%d)\n", rc);
13158 		return rc;
13159 	}
13160 
13161 	eqhdl = lpfc_get_eq_hdl(0);
13162 	rc = pci_irq_vector(phba->pcidev, 0);
13163 	if (rc < 0) {
13164 		free_irq(phba->pcidev->irq, phba);
13165 		pci_free_irq_vectors(phba->pcidev);
13166 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13167 				"0496 MSI pci_irq_vec failed (%d)\n", rc);
13168 		return rc;
13169 	}
13170 	eqhdl->irq = rc;
13171 
13172 	cpu = cpumask_first(cpu_present_mask);
13173 	lpfc_assign_eq_map_info(phba, 0, LPFC_CPU_FIRST_IRQ, cpu);
13174 
13175 	for (index = 0; index < phba->cfg_irq_chann; index++) {
13176 		eqhdl = lpfc_get_eq_hdl(index);
13177 		eqhdl->idx = index;
13178 	}
13179 
13180 	return 0;
13181 }
13182 
13183 /**
13184  * lpfc_sli4_enable_intr - Enable device interrupt to SLI-4 device
13185  * @phba: pointer to lpfc hba data structure.
13186  * @cfg_mode: Interrupt configuration mode (INTx, MSI or MSI-X).
13187  *
13188  * This routine is invoked to enable device interrupt and associate driver's
13189  * interrupt handler(s) to interrupt vector(s) to device with SLI-4
13190  * interface spec. Depends on the interrupt mode configured to the driver,
13191  * the driver will try to fallback from the configured interrupt mode to an
13192  * interrupt mode which is supported by the platform, kernel, and device in
13193  * the order of:
13194  * MSI-X -> MSI -> IRQ.
13195  *
13196  * Return codes
13197  *	Interrupt mode (2, 1, 0) - successful
13198  *	LPFC_INTR_ERROR - error
13199  **/
13200 static uint32_t
13201 lpfc_sli4_enable_intr(struct lpfc_hba *phba, uint32_t cfg_mode)
13202 {
13203 	uint32_t intr_mode = LPFC_INTR_ERROR;
13204 	int retval, idx;
13205 
13206 	if (cfg_mode == 2) {
13207 		/* Preparation before conf_msi mbox cmd */
13208 		retval = 0;
13209 		if (!retval) {
13210 			/* Now, try to enable MSI-X interrupt mode */
13211 			retval = lpfc_sli4_enable_msix(phba);
13212 			if (!retval) {
13213 				/* Indicate initialization to MSI-X mode */
13214 				phba->intr_type = MSIX;
13215 				intr_mode = 2;
13216 			}
13217 		}
13218 	}
13219 
13220 	/* Fallback to MSI if MSI-X initialization failed */
13221 	if (cfg_mode >= 1 && phba->intr_type == NONE) {
13222 		retval = lpfc_sli4_enable_msi(phba);
13223 		if (!retval) {
13224 			/* Indicate initialization to MSI mode */
13225 			phba->intr_type = MSI;
13226 			intr_mode = 1;
13227 		}
13228 	}
13229 
13230 	/* Fallback to INTx if both MSI-X/MSI initalization failed */
13231 	if (phba->intr_type == NONE) {
13232 		retval = request_irq(phba->pcidev->irq, lpfc_sli4_intr_handler,
13233 				     IRQF_SHARED, LPFC_DRIVER_NAME, phba);
13234 		if (!retval) {
13235 			struct lpfc_hba_eq_hdl *eqhdl;
13236 			unsigned int cpu;
13237 
13238 			/* Indicate initialization to INTx mode */
13239 			phba->intr_type = INTx;
13240 			intr_mode = 0;
13241 
13242 			eqhdl = lpfc_get_eq_hdl(0);
13243 			retval = pci_irq_vector(phba->pcidev, 0);
13244 			if (retval < 0) {
13245 				free_irq(phba->pcidev->irq, phba);
13246 				lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13247 					"0502 INTR pci_irq_vec failed (%d)\n",
13248 					 retval);
13249 				return LPFC_INTR_ERROR;
13250 			}
13251 			eqhdl->irq = retval;
13252 
13253 			cpu = cpumask_first(cpu_present_mask);
13254 			lpfc_assign_eq_map_info(phba, 0, LPFC_CPU_FIRST_IRQ,
13255 						cpu);
13256 			for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
13257 				eqhdl = lpfc_get_eq_hdl(idx);
13258 				eqhdl->idx = idx;
13259 			}
13260 		}
13261 	}
13262 	return intr_mode;
13263 }
13264 
13265 /**
13266  * lpfc_sli4_disable_intr - Disable device interrupt to SLI-4 device
13267  * @phba: pointer to lpfc hba data structure.
13268  *
13269  * This routine is invoked to disable device interrupt and disassociate
13270  * the driver's interrupt handler(s) from interrupt vector(s) to device
13271  * with SLI-4 interface spec. Depending on the interrupt mode, the driver
13272  * will release the interrupt vector(s) for the message signaled interrupt.
13273  **/
13274 static void
13275 lpfc_sli4_disable_intr(struct lpfc_hba *phba)
13276 {
13277 	/* Disable the currently initialized interrupt mode */
13278 	if (phba->intr_type == MSIX) {
13279 		int index;
13280 		struct lpfc_hba_eq_hdl *eqhdl;
13281 
13282 		/* Free up MSI-X multi-message vectors */
13283 		for (index = 0; index < phba->cfg_irq_chann; index++) {
13284 			eqhdl = lpfc_get_eq_hdl(index);
13285 			lpfc_irq_clear_aff(eqhdl);
13286 			free_irq(eqhdl->irq, eqhdl);
13287 		}
13288 	} else {
13289 		free_irq(phba->pcidev->irq, phba);
13290 	}
13291 
13292 	pci_free_irq_vectors(phba->pcidev);
13293 
13294 	/* Reset interrupt management states */
13295 	phba->intr_type = NONE;
13296 	phba->sli.slistat.sli_intr = 0;
13297 }
13298 
13299 /**
13300  * lpfc_unset_hba - Unset SLI3 hba device initialization
13301  * @phba: pointer to lpfc hba data structure.
13302  *
13303  * This routine is invoked to unset the HBA device initialization steps to
13304  * a device with SLI-3 interface spec.
13305  **/
13306 static void
13307 lpfc_unset_hba(struct lpfc_hba *phba)
13308 {
13309 	set_bit(FC_UNLOADING, &phba->pport->load_flag);
13310 
13311 	kfree(phba->vpi_bmask);
13312 	kfree(phba->vpi_ids);
13313 
13314 	lpfc_stop_hba_timers(phba);
13315 
13316 	phba->pport->work_port_events = 0;
13317 
13318 	lpfc_sli_hba_down(phba);
13319 
13320 	lpfc_sli_brdrestart(phba);
13321 
13322 	lpfc_sli_disable_intr(phba);
13323 
13324 	return;
13325 }
13326 
13327 /**
13328  * lpfc_sli4_xri_exchange_busy_wait - Wait for device XRI exchange busy
13329  * @phba: Pointer to HBA context object.
13330  *
13331  * This function is called in the SLI4 code path to wait for completion
13332  * of device's XRIs exchange busy. It will check the XRI exchange busy
13333  * on outstanding FCP and ELS I/Os every 10ms for up to 10 seconds; after
13334  * that, it will check the XRI exchange busy on outstanding FCP and ELS
13335  * I/Os every 30 seconds, log error message, and wait forever. Only when
13336  * all XRI exchange busy complete, the driver unload shall proceed with
13337  * invoking the function reset ioctl mailbox command to the CNA and the
13338  * the rest of the driver unload resource release.
13339  **/
13340 static void
13341 lpfc_sli4_xri_exchange_busy_wait(struct lpfc_hba *phba)
13342 {
13343 	struct lpfc_sli4_hdw_queue *qp;
13344 	int idx, ccnt;
13345 	int wait_time = 0;
13346 	int io_xri_cmpl = 1;
13347 	int nvmet_xri_cmpl = 1;
13348 	int els_xri_cmpl = list_empty(&phba->sli4_hba.lpfc_abts_els_sgl_list);
13349 
13350 	/* Driver just aborted IOs during the hba_unset process.  Pause
13351 	 * here to give the HBA time to complete the IO and get entries
13352 	 * into the abts lists.
13353 	 */
13354 	msleep(LPFC_XRI_EXCH_BUSY_WAIT_T1 * 5);
13355 
13356 	/* Wait for NVME pending IO to flush back to transport. */
13357 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
13358 		lpfc_nvme_wait_for_io_drain(phba);
13359 
13360 	ccnt = 0;
13361 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
13362 		qp = &phba->sli4_hba.hdwq[idx];
13363 		io_xri_cmpl = list_empty(&qp->lpfc_abts_io_buf_list);
13364 		if (!io_xri_cmpl) /* if list is NOT empty */
13365 			ccnt++;
13366 	}
13367 	if (ccnt)
13368 		io_xri_cmpl = 0;
13369 
13370 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13371 		nvmet_xri_cmpl =
13372 			list_empty(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
13373 	}
13374 
13375 	while (!els_xri_cmpl || !io_xri_cmpl || !nvmet_xri_cmpl) {
13376 		if (wait_time > LPFC_XRI_EXCH_BUSY_WAIT_TMO) {
13377 			if (!nvmet_xri_cmpl)
13378 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13379 						"6424 NVMET XRI exchange busy "
13380 						"wait time: %d seconds.\n",
13381 						wait_time/1000);
13382 			if (!io_xri_cmpl)
13383 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13384 						"6100 IO XRI exchange busy "
13385 						"wait time: %d seconds.\n",
13386 						wait_time/1000);
13387 			if (!els_xri_cmpl)
13388 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13389 						"2878 ELS XRI exchange busy "
13390 						"wait time: %d seconds.\n",
13391 						wait_time/1000);
13392 			msleep(LPFC_XRI_EXCH_BUSY_WAIT_T2);
13393 			wait_time += LPFC_XRI_EXCH_BUSY_WAIT_T2;
13394 		} else {
13395 			msleep(LPFC_XRI_EXCH_BUSY_WAIT_T1);
13396 			wait_time += LPFC_XRI_EXCH_BUSY_WAIT_T1;
13397 		}
13398 
13399 		ccnt = 0;
13400 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
13401 			qp = &phba->sli4_hba.hdwq[idx];
13402 			io_xri_cmpl = list_empty(
13403 			    &qp->lpfc_abts_io_buf_list);
13404 			if (!io_xri_cmpl) /* if list is NOT empty */
13405 				ccnt++;
13406 		}
13407 		if (ccnt)
13408 			io_xri_cmpl = 0;
13409 
13410 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13411 			nvmet_xri_cmpl = list_empty(
13412 				&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
13413 		}
13414 		els_xri_cmpl =
13415 			list_empty(&phba->sli4_hba.lpfc_abts_els_sgl_list);
13416 
13417 	}
13418 }
13419 
13420 /**
13421  * lpfc_sli4_hba_unset - Unset the fcoe hba
13422  * @phba: Pointer to HBA context object.
13423  *
13424  * This function is called in the SLI4 code path to reset the HBA's FCoE
13425  * function. The caller is not required to hold any lock. This routine
13426  * issues PCI function reset mailbox command to reset the FCoE function.
13427  * At the end of the function, it calls lpfc_hba_down_post function to
13428  * free any pending commands.
13429  **/
13430 static void
13431 lpfc_sli4_hba_unset(struct lpfc_hba *phba)
13432 {
13433 	int wait_cnt = 0;
13434 	LPFC_MBOXQ_t *mboxq;
13435 	struct pci_dev *pdev = phba->pcidev;
13436 
13437 	lpfc_stop_hba_timers(phba);
13438 	hrtimer_cancel(&phba->cmf_stats_timer);
13439 	hrtimer_cancel(&phba->cmf_timer);
13440 
13441 	if (phba->pport)
13442 		phba->sli4_hba.intr_enable = 0;
13443 
13444 	/*
13445 	 * Gracefully wait out the potential current outstanding asynchronous
13446 	 * mailbox command.
13447 	 */
13448 
13449 	/* First, block any pending async mailbox command from posted */
13450 	spin_lock_irq(&phba->hbalock);
13451 	phba->sli.sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
13452 	spin_unlock_irq(&phba->hbalock);
13453 	/* Now, trying to wait it out if we can */
13454 	while (phba->sli.sli_flag & LPFC_SLI_MBOX_ACTIVE) {
13455 		msleep(10);
13456 		if (++wait_cnt > LPFC_ACTIVE_MBOX_WAIT_CNT)
13457 			break;
13458 	}
13459 	/* Forcefully release the outstanding mailbox command if timed out */
13460 	if (phba->sli.sli_flag & LPFC_SLI_MBOX_ACTIVE) {
13461 		spin_lock_irq(&phba->hbalock);
13462 		mboxq = phba->sli.mbox_active;
13463 		mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
13464 		__lpfc_mbox_cmpl_put(phba, mboxq);
13465 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
13466 		phba->sli.mbox_active = NULL;
13467 		spin_unlock_irq(&phba->hbalock);
13468 	}
13469 
13470 	/* Abort all iocbs associated with the hba */
13471 	lpfc_sli_hba_iocb_abort(phba);
13472 
13473 	if (!pci_channel_offline(phba->pcidev))
13474 		/* Wait for completion of device XRI exchange busy */
13475 		lpfc_sli4_xri_exchange_busy_wait(phba);
13476 
13477 	/* per-phba callback de-registration for hotplug event */
13478 	if (phba->pport)
13479 		lpfc_cpuhp_remove(phba);
13480 
13481 	/* Disable PCI subsystem interrupt */
13482 	lpfc_sli4_disable_intr(phba);
13483 
13484 	/* Disable SR-IOV if enabled */
13485 	if (phba->cfg_sriov_nr_virtfn)
13486 		pci_disable_sriov(pdev);
13487 
13488 	/* Stop kthread signal shall trigger work_done one more time */
13489 	kthread_stop(phba->worker_thread);
13490 
13491 	/* Disable FW logging to host memory */
13492 	lpfc_ras_stop_fwlog(phba);
13493 
13494 	lpfc_sli4_queue_unset(phba);
13495 
13496 	/* Reset SLI4 HBA FCoE function */
13497 	lpfc_pci_function_reset(phba);
13498 
13499 	/* release all queue allocated resources. */
13500 	lpfc_sli4_queue_destroy(phba);
13501 
13502 	/* Free RAS DMA memory */
13503 	if (phba->ras_fwlog.ras_enabled)
13504 		lpfc_sli4_ras_dma_free(phba);
13505 
13506 	/* Stop the SLI4 device port */
13507 	if (phba->pport)
13508 		phba->pport->work_port_events = 0;
13509 }
13510 
13511 static uint32_t
13512 lpfc_cgn_crc32(uint32_t crc, u8 byte)
13513 {
13514 	uint32_t msb = 0;
13515 	uint32_t bit;
13516 
13517 	for (bit = 0; bit < 8; bit++) {
13518 		msb = (crc >> 31) & 1;
13519 		crc <<= 1;
13520 
13521 		if (msb ^ (byte & 1)) {
13522 			crc ^= LPFC_CGN_CRC32_MAGIC_NUMBER;
13523 			crc |= 1;
13524 		}
13525 		byte >>= 1;
13526 	}
13527 	return crc;
13528 }
13529 
13530 static uint32_t
13531 lpfc_cgn_reverse_bits(uint32_t wd)
13532 {
13533 	uint32_t result = 0;
13534 	uint32_t i;
13535 
13536 	for (i = 0; i < 32; i++) {
13537 		result <<= 1;
13538 		result |= (1 & (wd >> i));
13539 	}
13540 	return result;
13541 }
13542 
13543 /*
13544  * The routine corresponds with the algorithm the HBA firmware
13545  * uses to validate the data integrity.
13546  */
13547 uint32_t
13548 lpfc_cgn_calc_crc32(void *ptr, uint32_t byteLen, uint32_t crc)
13549 {
13550 	uint32_t  i;
13551 	uint32_t result;
13552 	uint8_t  *data = (uint8_t *)ptr;
13553 
13554 	for (i = 0; i < byteLen; ++i)
13555 		crc = lpfc_cgn_crc32(crc, data[i]);
13556 
13557 	result = ~lpfc_cgn_reverse_bits(crc);
13558 	return result;
13559 }
13560 
13561 void
13562 lpfc_init_congestion_buf(struct lpfc_hba *phba)
13563 {
13564 	struct lpfc_cgn_info *cp;
13565 	uint16_t size;
13566 	uint32_t crc;
13567 
13568 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
13569 			"6235 INIT Congestion Buffer %p\n", phba->cgn_i);
13570 
13571 	if (!phba->cgn_i)
13572 		return;
13573 	cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
13574 
13575 	atomic_set(&phba->cgn_fabric_warn_cnt, 0);
13576 	atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
13577 	atomic_set(&phba->cgn_sync_alarm_cnt, 0);
13578 	atomic_set(&phba->cgn_sync_warn_cnt, 0);
13579 
13580 	atomic_set(&phba->cgn_driver_evt_cnt, 0);
13581 	atomic_set(&phba->cgn_latency_evt_cnt, 0);
13582 	atomic64_set(&phba->cgn_latency_evt, 0);
13583 	phba->cgn_evt_minute = 0;
13584 
13585 	memset(cp, 0xff, offsetof(struct lpfc_cgn_info, cgn_stat));
13586 	cp->cgn_info_size = cpu_to_le16(LPFC_CGN_INFO_SZ);
13587 	cp->cgn_info_version = LPFC_CGN_INFO_V4;
13588 
13589 	/* cgn parameters */
13590 	cp->cgn_info_mode = phba->cgn_p.cgn_param_mode;
13591 	cp->cgn_info_level0 = phba->cgn_p.cgn_param_level0;
13592 	cp->cgn_info_level1 = phba->cgn_p.cgn_param_level1;
13593 	cp->cgn_info_level2 = phba->cgn_p.cgn_param_level2;
13594 
13595 	lpfc_cgn_update_tstamp(phba, &cp->base_time);
13596 
13597 	/* Fill in default LUN qdepth */
13598 	if (phba->pport) {
13599 		size = (uint16_t)(phba->pport->cfg_lun_queue_depth);
13600 		cp->cgn_lunq = cpu_to_le16(size);
13601 	}
13602 
13603 	/* last used Index initialized to 0xff already */
13604 
13605 	cp->cgn_warn_freq = cpu_to_le16(LPFC_FPIN_INIT_FREQ);
13606 	cp->cgn_alarm_freq = cpu_to_le16(LPFC_FPIN_INIT_FREQ);
13607 	crc = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ, LPFC_CGN_CRC32_SEED);
13608 	cp->cgn_info_crc = cpu_to_le32(crc);
13609 
13610 	phba->cgn_evt_timestamp = jiffies +
13611 		msecs_to_jiffies(LPFC_CGN_TIMER_TO_MIN);
13612 }
13613 
13614 void
13615 lpfc_init_congestion_stat(struct lpfc_hba *phba)
13616 {
13617 	struct lpfc_cgn_info *cp;
13618 	uint32_t crc;
13619 
13620 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
13621 			"6236 INIT Congestion Stat %p\n", phba->cgn_i);
13622 
13623 	if (!phba->cgn_i)
13624 		return;
13625 
13626 	cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
13627 	memset(&cp->cgn_stat, 0, sizeof(cp->cgn_stat));
13628 
13629 	lpfc_cgn_update_tstamp(phba, &cp->stat_start);
13630 	crc = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ, LPFC_CGN_CRC32_SEED);
13631 	cp->cgn_info_crc = cpu_to_le32(crc);
13632 }
13633 
13634 /**
13635  * __lpfc_reg_congestion_buf - register congestion info buffer with HBA
13636  * @phba: Pointer to hba context object.
13637  * @reg: flag to determine register or unregister.
13638  */
13639 static int
13640 __lpfc_reg_congestion_buf(struct lpfc_hba *phba, int reg)
13641 {
13642 	struct lpfc_mbx_reg_congestion_buf *reg_congestion_buf;
13643 	union  lpfc_sli4_cfg_shdr *shdr;
13644 	uint32_t shdr_status, shdr_add_status;
13645 	LPFC_MBOXQ_t *mboxq;
13646 	int length, rc;
13647 
13648 	if (!phba->cgn_i)
13649 		return -ENXIO;
13650 
13651 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
13652 	if (!mboxq) {
13653 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX,
13654 				"2641 REG_CONGESTION_BUF mbox allocation fail: "
13655 				"HBA state x%x reg %d\n",
13656 				phba->pport->port_state, reg);
13657 		return -ENOMEM;
13658 	}
13659 
13660 	length = (sizeof(struct lpfc_mbx_reg_congestion_buf) -
13661 		sizeof(struct lpfc_sli4_cfg_mhdr));
13662 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
13663 			 LPFC_MBOX_OPCODE_REG_CONGESTION_BUF, length,
13664 			 LPFC_SLI4_MBX_EMBED);
13665 	reg_congestion_buf = &mboxq->u.mqe.un.reg_congestion_buf;
13666 	bf_set(lpfc_mbx_reg_cgn_buf_type, reg_congestion_buf, 1);
13667 	if (reg > 0)
13668 		bf_set(lpfc_mbx_reg_cgn_buf_cnt, reg_congestion_buf, 1);
13669 	else
13670 		bf_set(lpfc_mbx_reg_cgn_buf_cnt, reg_congestion_buf, 0);
13671 	reg_congestion_buf->length = sizeof(struct lpfc_cgn_info);
13672 	reg_congestion_buf->addr_lo =
13673 		putPaddrLow(phba->cgn_i->phys);
13674 	reg_congestion_buf->addr_hi =
13675 		putPaddrHigh(phba->cgn_i->phys);
13676 
13677 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
13678 	shdr = (union lpfc_sli4_cfg_shdr *)
13679 		&mboxq->u.mqe.un.sli4_config.header.cfg_shdr;
13680 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13681 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
13682 				 &shdr->response);
13683 	mempool_free(mboxq, phba->mbox_mem_pool);
13684 	if (shdr_status || shdr_add_status || rc) {
13685 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13686 				"2642 REG_CONGESTION_BUF mailbox "
13687 				"failed with status x%x add_status x%x,"
13688 				" mbx status x%x reg %d\n",
13689 				shdr_status, shdr_add_status, rc, reg);
13690 		return -ENXIO;
13691 	}
13692 	return 0;
13693 }
13694 
13695 int
13696 lpfc_unreg_congestion_buf(struct lpfc_hba *phba)
13697 {
13698 	lpfc_cmf_stop(phba);
13699 	return __lpfc_reg_congestion_buf(phba, 0);
13700 }
13701 
13702 int
13703 lpfc_reg_congestion_buf(struct lpfc_hba *phba)
13704 {
13705 	return __lpfc_reg_congestion_buf(phba, 1);
13706 }
13707 
13708 /**
13709  * lpfc_get_sli4_parameters - Get the SLI4 Config PARAMETERS.
13710  * @phba: Pointer to HBA context object.
13711  * @mboxq: Pointer to the mailboxq memory for the mailbox command response.
13712  *
13713  * This function is called in the SLI4 code path to read the port's
13714  * sli4 capabilities.
13715  *
13716  * This function may be be called from any context that can block-wait
13717  * for the completion.  The expectation is that this routine is called
13718  * typically from probe_one or from the online routine.
13719  **/
13720 int
13721 lpfc_get_sli4_parameters(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
13722 {
13723 	int rc;
13724 	struct lpfc_mqe *mqe = &mboxq->u.mqe;
13725 	struct lpfc_pc_sli4_params *sli4_params;
13726 	uint32_t mbox_tmo;
13727 	int length;
13728 	bool exp_wqcq_pages = true;
13729 	struct lpfc_sli4_parameters *mbx_sli4_parameters;
13730 
13731 	/*
13732 	 * By default, the driver assumes the SLI4 port requires RPI
13733 	 * header postings.  The SLI4_PARAM response will correct this
13734 	 * assumption.
13735 	 */
13736 	phba->sli4_hba.rpi_hdrs_in_use = 1;
13737 
13738 	/* Read the port's SLI4 Config Parameters */
13739 	length = (sizeof(struct lpfc_mbx_get_sli4_parameters) -
13740 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13741 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
13742 			 LPFC_MBOX_OPCODE_GET_SLI4_PARAMETERS,
13743 			 length, LPFC_SLI4_MBX_EMBED);
13744 	if (!phba->sli4_hba.intr_enable)
13745 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
13746 	else {
13747 		mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
13748 		rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
13749 	}
13750 	if (unlikely(rc))
13751 		return rc;
13752 	sli4_params = &phba->sli4_hba.pc_sli4_params;
13753 	mbx_sli4_parameters = &mqe->un.get_sli4_parameters.sli4_parameters;
13754 	sli4_params->if_type = bf_get(cfg_if_type, mbx_sli4_parameters);
13755 	sli4_params->sli_rev = bf_get(cfg_sli_rev, mbx_sli4_parameters);
13756 	sli4_params->sli_family = bf_get(cfg_sli_family, mbx_sli4_parameters);
13757 	sli4_params->featurelevel_1 = bf_get(cfg_sli_hint_1,
13758 					     mbx_sli4_parameters);
13759 	sli4_params->featurelevel_2 = bf_get(cfg_sli_hint_2,
13760 					     mbx_sli4_parameters);
13761 	if (bf_get(cfg_phwq, mbx_sli4_parameters))
13762 		phba->sli3_options |= LPFC_SLI4_PHWQ_ENABLED;
13763 	else
13764 		phba->sli3_options &= ~LPFC_SLI4_PHWQ_ENABLED;
13765 	sli4_params->sge_supp_len = mbx_sli4_parameters->sge_supp_len;
13766 	sli4_params->loopbk_scope = bf_get(cfg_loopbk_scope,
13767 					   mbx_sli4_parameters);
13768 	sli4_params->oas_supported = bf_get(cfg_oas, mbx_sli4_parameters);
13769 	sli4_params->cqv = bf_get(cfg_cqv, mbx_sli4_parameters);
13770 	sli4_params->mqv = bf_get(cfg_mqv, mbx_sli4_parameters);
13771 	sli4_params->wqv = bf_get(cfg_wqv, mbx_sli4_parameters);
13772 	sli4_params->rqv = bf_get(cfg_rqv, mbx_sli4_parameters);
13773 	sli4_params->eqav = bf_get(cfg_eqav, mbx_sli4_parameters);
13774 	sli4_params->cqav = bf_get(cfg_cqav, mbx_sli4_parameters);
13775 	sli4_params->wqsize = bf_get(cfg_wqsize, mbx_sli4_parameters);
13776 	sli4_params->bv1s = bf_get(cfg_bv1s, mbx_sli4_parameters);
13777 	sli4_params->pls = bf_get(cfg_pvl, mbx_sli4_parameters);
13778 	sli4_params->sgl_pages_max = bf_get(cfg_sgl_page_cnt,
13779 					    mbx_sli4_parameters);
13780 	sli4_params->wqpcnt = bf_get(cfg_wqpcnt, mbx_sli4_parameters);
13781 	sli4_params->sgl_pp_align = bf_get(cfg_sgl_pp_align,
13782 					   mbx_sli4_parameters);
13783 	phba->sli4_hba.extents_in_use = bf_get(cfg_ext, mbx_sli4_parameters);
13784 	phba->sli4_hba.rpi_hdrs_in_use = bf_get(cfg_hdrr, mbx_sli4_parameters);
13785 	sli4_params->mi_cap = bf_get(cfg_mi_ver, mbx_sli4_parameters);
13786 
13787 	/* Check for Extended Pre-Registered SGL support */
13788 	phba->cfg_xpsgl = bf_get(cfg_xpsgl, mbx_sli4_parameters);
13789 
13790 	/* Check for firmware nvme support */
13791 	rc = (bf_get(cfg_nvme, mbx_sli4_parameters) &&
13792 		     bf_get(cfg_xib, mbx_sli4_parameters));
13793 
13794 	if (rc) {
13795 		/* Save this to indicate the Firmware supports NVME */
13796 		sli4_params->nvme = 1;
13797 
13798 		/* Firmware NVME support, check driver FC4 NVME support */
13799 		if (phba->cfg_enable_fc4_type == LPFC_ENABLE_FCP) {
13800 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_NVME,
13801 					"6133 Disabling NVME support: "
13802 					"FC4 type not supported: x%x\n",
13803 					phba->cfg_enable_fc4_type);
13804 			goto fcponly;
13805 		}
13806 	} else {
13807 		/* No firmware NVME support, check driver FC4 NVME support */
13808 		sli4_params->nvme = 0;
13809 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13810 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_NVME,
13811 					"6101 Disabling NVME support: Not "
13812 					"supported by firmware (%d %d) x%x\n",
13813 					bf_get(cfg_nvme, mbx_sli4_parameters),
13814 					bf_get(cfg_xib, mbx_sli4_parameters),
13815 					phba->cfg_enable_fc4_type);
13816 fcponly:
13817 			phba->nvmet_support = 0;
13818 			phba->cfg_nvmet_mrq = 0;
13819 			phba->cfg_nvme_seg_cnt = 0;
13820 
13821 			/* If no FC4 type support, move to just SCSI support */
13822 			if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP))
13823 				return -ENODEV;
13824 			phba->cfg_enable_fc4_type = LPFC_ENABLE_FCP;
13825 		}
13826 	}
13827 
13828 	/* If the NVME FC4 type is enabled, scale the sg_seg_cnt to
13829 	 * accommodate 512K and 1M IOs in a single nvme buf.
13830 	 */
13831 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
13832 		phba->cfg_sg_seg_cnt = LPFC_MAX_NVME_SEG_CNT;
13833 
13834 	/* Enable embedded Payload BDE if support is indicated */
13835 	if (bf_get(cfg_pbde, mbx_sli4_parameters))
13836 		phba->cfg_enable_pbde = 1;
13837 	else
13838 		phba->cfg_enable_pbde = 0;
13839 
13840 	/*
13841 	 * To support Suppress Response feature we must satisfy 3 conditions.
13842 	 * lpfc_suppress_rsp module parameter must be set (default).
13843 	 * In SLI4-Parameters Descriptor:
13844 	 * Extended Inline Buffers (XIB) must be supported.
13845 	 * Suppress Response IU Not Supported (SRIUNS) must NOT be supported
13846 	 * (double negative).
13847 	 */
13848 	if (phba->cfg_suppress_rsp && bf_get(cfg_xib, mbx_sli4_parameters) &&
13849 	    !(bf_get(cfg_nosr, mbx_sli4_parameters)))
13850 		phba->sli.sli_flag |= LPFC_SLI_SUPPRESS_RSP;
13851 	else
13852 		phba->cfg_suppress_rsp = 0;
13853 
13854 	if (bf_get(cfg_eqdr, mbx_sli4_parameters))
13855 		phba->sli.sli_flag |= LPFC_SLI_USE_EQDR;
13856 
13857 	/* Make sure that sge_supp_len can be handled by the driver */
13858 	if (sli4_params->sge_supp_len > LPFC_MAX_SGE_SIZE)
13859 		sli4_params->sge_supp_len = LPFC_MAX_SGE_SIZE;
13860 
13861 	dma_set_max_seg_size(&phba->pcidev->dev, sli4_params->sge_supp_len);
13862 
13863 	/*
13864 	 * Check whether the adapter supports an embedded copy of the
13865 	 * FCP CMD IU within the WQE for FCP_Ixxx commands. In order
13866 	 * to use this option, 128-byte WQEs must be used.
13867 	 */
13868 	if (bf_get(cfg_ext_embed_cb, mbx_sli4_parameters))
13869 		phba->fcp_embed_io = 1;
13870 	else
13871 		phba->fcp_embed_io = 0;
13872 
13873 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_NVME,
13874 			"6422 XIB %d PBDE %d: FCP %d NVME %d %d %d\n",
13875 			bf_get(cfg_xib, mbx_sli4_parameters),
13876 			phba->cfg_enable_pbde,
13877 			phba->fcp_embed_io, sli4_params->nvme,
13878 			phba->cfg_nvme_embed_cmd, phba->cfg_suppress_rsp);
13879 
13880 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
13881 	    LPFC_SLI_INTF_IF_TYPE_2) &&
13882 	    (bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf) ==
13883 		 LPFC_SLI_INTF_FAMILY_LNCR_A0))
13884 		exp_wqcq_pages = false;
13885 
13886 	if ((bf_get(cfg_cqpsize, mbx_sli4_parameters) & LPFC_CQ_16K_PAGE_SZ) &&
13887 	    (bf_get(cfg_wqpsize, mbx_sli4_parameters) & LPFC_WQ_16K_PAGE_SZ) &&
13888 	    exp_wqcq_pages &&
13889 	    (sli4_params->wqsize & LPFC_WQ_SZ128_SUPPORT))
13890 		phba->enab_exp_wqcq_pages = 1;
13891 	else
13892 		phba->enab_exp_wqcq_pages = 0;
13893 	/*
13894 	 * Check if the SLI port supports MDS Diagnostics
13895 	 */
13896 	if (bf_get(cfg_mds_diags, mbx_sli4_parameters))
13897 		phba->mds_diags_support = 1;
13898 	else
13899 		phba->mds_diags_support = 0;
13900 
13901 	/*
13902 	 * Check if the SLI port supports NSLER
13903 	 */
13904 	if (bf_get(cfg_nsler, mbx_sli4_parameters))
13905 		phba->nsler = 1;
13906 	else
13907 		phba->nsler = 0;
13908 
13909 	return 0;
13910 }
13911 
13912 /**
13913  * lpfc_pci_probe_one_s3 - PCI probe func to reg SLI-3 device to PCI subsystem.
13914  * @pdev: pointer to PCI device
13915  * @pid: pointer to PCI device identifier
13916  *
13917  * This routine is to be called to attach a device with SLI-3 interface spec
13918  * to the PCI subsystem. When an Emulex HBA with SLI-3 interface spec is
13919  * presented on PCI bus, the kernel PCI subsystem looks at PCI device-specific
13920  * information of the device and driver to see if the driver state that it can
13921  * support this kind of device. If the match is successful, the driver core
13922  * invokes this routine. If this routine determines it can claim the HBA, it
13923  * does all the initialization that it needs to do to handle the HBA properly.
13924  *
13925  * Return code
13926  * 	0 - driver can claim the device
13927  * 	negative value - driver can not claim the device
13928  **/
13929 static int
13930 lpfc_pci_probe_one_s3(struct pci_dev *pdev, const struct pci_device_id *pid)
13931 {
13932 	struct lpfc_hba   *phba;
13933 	struct lpfc_vport *vport = NULL;
13934 	struct Scsi_Host  *shost = NULL;
13935 	int error;
13936 	uint32_t cfg_mode, intr_mode;
13937 
13938 	/* Allocate memory for HBA structure */
13939 	phba = lpfc_hba_alloc(pdev);
13940 	if (!phba)
13941 		return -ENOMEM;
13942 
13943 	/* Perform generic PCI device enabling operation */
13944 	error = lpfc_enable_pci_dev(phba);
13945 	if (error)
13946 		goto out_free_phba;
13947 
13948 	/* Set up SLI API function jump table for PCI-device group-0 HBAs */
13949 	error = lpfc_api_table_setup(phba, LPFC_PCI_DEV_LP);
13950 	if (error)
13951 		goto out_disable_pci_dev;
13952 
13953 	/* Set up SLI-3 specific device PCI memory space */
13954 	error = lpfc_sli_pci_mem_setup(phba);
13955 	if (error) {
13956 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13957 				"1402 Failed to set up pci memory space.\n");
13958 		goto out_disable_pci_dev;
13959 	}
13960 
13961 	/* Set up SLI-3 specific device driver resources */
13962 	error = lpfc_sli_driver_resource_setup(phba);
13963 	if (error) {
13964 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13965 				"1404 Failed to set up driver resource.\n");
13966 		goto out_unset_pci_mem_s3;
13967 	}
13968 
13969 	/* Initialize and populate the iocb list per host */
13970 
13971 	error = lpfc_init_iocb_list(phba, LPFC_IOCB_LIST_CNT);
13972 	if (error) {
13973 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13974 				"1405 Failed to initialize iocb list.\n");
13975 		goto out_unset_driver_resource_s3;
13976 	}
13977 
13978 	/* Set up common device driver resources */
13979 	error = lpfc_setup_driver_resource_phase2(phba);
13980 	if (error) {
13981 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13982 				"1406 Failed to set up driver resource.\n");
13983 		goto out_free_iocb_list;
13984 	}
13985 
13986 	/* Get the default values for Model Name and Description */
13987 	lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
13988 
13989 	/* Create SCSI host to the physical port */
13990 	error = lpfc_create_shost(phba);
13991 	if (error) {
13992 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13993 				"1407 Failed to create scsi host.\n");
13994 		goto out_unset_driver_resource;
13995 	}
13996 
13997 	/* Configure sysfs attributes */
13998 	vport = phba->pport;
13999 	error = lpfc_alloc_sysfs_attr(vport);
14000 	if (error) {
14001 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14002 				"1476 Failed to allocate sysfs attr\n");
14003 		goto out_destroy_shost;
14004 	}
14005 
14006 	shost = lpfc_shost_from_vport(vport); /* save shost for error cleanup */
14007 	/* Now, trying to enable interrupt and bring up the device */
14008 	cfg_mode = phba->cfg_use_msi;
14009 	while (true) {
14010 		/* Put device to a known state before enabling interrupt */
14011 		lpfc_stop_port(phba);
14012 		/* Configure and enable interrupt */
14013 		intr_mode = lpfc_sli_enable_intr(phba, cfg_mode);
14014 		if (intr_mode == LPFC_INTR_ERROR) {
14015 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14016 					"0431 Failed to enable interrupt.\n");
14017 			error = -ENODEV;
14018 			goto out_free_sysfs_attr;
14019 		}
14020 		/* SLI-3 HBA setup */
14021 		if (lpfc_sli_hba_setup(phba)) {
14022 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14023 					"1477 Failed to set up hba\n");
14024 			error = -ENODEV;
14025 			goto out_remove_device;
14026 		}
14027 
14028 		/* Wait 50ms for the interrupts of previous mailbox commands */
14029 		msleep(50);
14030 		/* Check active interrupts on message signaled interrupts */
14031 		if (intr_mode == 0 ||
14032 		    phba->sli.slistat.sli_intr > LPFC_MSIX_VECTORS) {
14033 			/* Log the current active interrupt mode */
14034 			phba->intr_mode = intr_mode;
14035 			lpfc_log_intr_mode(phba, intr_mode);
14036 			break;
14037 		} else {
14038 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
14039 					"0447 Configure interrupt mode (%d) "
14040 					"failed active interrupt test.\n",
14041 					intr_mode);
14042 			/* Disable the current interrupt mode */
14043 			lpfc_sli_disable_intr(phba);
14044 			/* Try next level of interrupt mode */
14045 			cfg_mode = --intr_mode;
14046 		}
14047 	}
14048 
14049 	/* Perform post initialization setup */
14050 	lpfc_post_init_setup(phba);
14051 
14052 	/* Check if there are static vports to be created. */
14053 	lpfc_create_static_vport(phba);
14054 
14055 	return 0;
14056 
14057 out_remove_device:
14058 	lpfc_unset_hba(phba);
14059 out_free_sysfs_attr:
14060 	lpfc_free_sysfs_attr(vport);
14061 out_destroy_shost:
14062 	lpfc_destroy_shost(phba);
14063 out_unset_driver_resource:
14064 	lpfc_unset_driver_resource_phase2(phba);
14065 out_free_iocb_list:
14066 	lpfc_free_iocb_list(phba);
14067 out_unset_driver_resource_s3:
14068 	lpfc_sli_driver_resource_unset(phba);
14069 out_unset_pci_mem_s3:
14070 	lpfc_sli_pci_mem_unset(phba);
14071 out_disable_pci_dev:
14072 	lpfc_disable_pci_dev(phba);
14073 	if (shost)
14074 		scsi_host_put(shost);
14075 out_free_phba:
14076 	lpfc_hba_free(phba);
14077 	return error;
14078 }
14079 
14080 /**
14081  * lpfc_pci_remove_one_s3 - PCI func to unreg SLI-3 device from PCI subsystem.
14082  * @pdev: pointer to PCI device
14083  *
14084  * This routine is to be called to disattach a device with SLI-3 interface
14085  * spec from PCI subsystem. When an Emulex HBA with SLI-3 interface spec is
14086  * removed from PCI bus, it performs all the necessary cleanup for the HBA
14087  * device to be removed from the PCI subsystem properly.
14088  **/
14089 static void
14090 lpfc_pci_remove_one_s3(struct pci_dev *pdev)
14091 {
14092 	struct Scsi_Host  *shost = pci_get_drvdata(pdev);
14093 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
14094 	struct lpfc_vport **vports;
14095 	struct lpfc_hba   *phba = vport->phba;
14096 	int i;
14097 
14098 	set_bit(FC_UNLOADING, &vport->load_flag);
14099 
14100 	lpfc_free_sysfs_attr(vport);
14101 
14102 	/* Release all the vports against this physical port */
14103 	vports = lpfc_create_vport_work_array(phba);
14104 	if (vports != NULL)
14105 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
14106 			if (vports[i]->port_type == LPFC_PHYSICAL_PORT)
14107 				continue;
14108 			fc_vport_terminate(vports[i]->fc_vport);
14109 		}
14110 	lpfc_destroy_vport_work_array(phba, vports);
14111 
14112 	/* Remove FC host with the physical port */
14113 	fc_remove_host(shost);
14114 	scsi_remove_host(shost);
14115 
14116 	/* Clean up all nodes, mailboxes and IOs. */
14117 	lpfc_cleanup(vport);
14118 
14119 	/*
14120 	 * Bring down the SLI Layer. This step disable all interrupts,
14121 	 * clears the rings, discards all mailbox commands, and resets
14122 	 * the HBA.
14123 	 */
14124 
14125 	/* HBA interrupt will be disabled after this call */
14126 	lpfc_sli_hba_down(phba);
14127 	/* Stop kthread signal shall trigger work_done one more time */
14128 	kthread_stop(phba->worker_thread);
14129 	/* Final cleanup of txcmplq and reset the HBA */
14130 	lpfc_sli_brdrestart(phba);
14131 
14132 	kfree(phba->vpi_bmask);
14133 	kfree(phba->vpi_ids);
14134 
14135 	lpfc_stop_hba_timers(phba);
14136 	spin_lock_irq(&phba->port_list_lock);
14137 	list_del_init(&vport->listentry);
14138 	spin_unlock_irq(&phba->port_list_lock);
14139 
14140 	lpfc_debugfs_terminate(vport);
14141 
14142 	/* Disable SR-IOV if enabled */
14143 	if (phba->cfg_sriov_nr_virtfn)
14144 		pci_disable_sriov(pdev);
14145 
14146 	/* Disable interrupt */
14147 	lpfc_sli_disable_intr(phba);
14148 
14149 	scsi_host_put(shost);
14150 
14151 	/*
14152 	 * Call scsi_free before mem_free since scsi bufs are released to their
14153 	 * corresponding pools here.
14154 	 */
14155 	lpfc_scsi_free(phba);
14156 	lpfc_free_iocb_list(phba);
14157 
14158 	lpfc_mem_free_all(phba);
14159 
14160 	dma_free_coherent(&pdev->dev, lpfc_sli_hbq_size(),
14161 			  phba->hbqslimp.virt, phba->hbqslimp.phys);
14162 
14163 	/* Free resources associated with SLI2 interface */
14164 	dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
14165 			  phba->slim2p.virt, phba->slim2p.phys);
14166 
14167 	/* unmap adapter SLIM and Control Registers */
14168 	iounmap(phba->ctrl_regs_memmap_p);
14169 	iounmap(phba->slim_memmap_p);
14170 
14171 	lpfc_hba_free(phba);
14172 
14173 	pci_release_mem_regions(pdev);
14174 	pci_disable_device(pdev);
14175 }
14176 
14177 /**
14178  * lpfc_pci_suspend_one_s3 - PCI func to suspend SLI-3 device for power mgmnt
14179  * @dev_d: pointer to device
14180  *
14181  * This routine is to be called from the kernel's PCI subsystem to support
14182  * system Power Management (PM) to device with SLI-3 interface spec. When
14183  * PM invokes this method, it quiesces the device by stopping the driver's
14184  * worker thread for the device, turning off device's interrupt and DMA,
14185  * and bring the device offline. Note that as the driver implements the
14186  * minimum PM requirements to a power-aware driver's PM support for the
14187  * suspend/resume -- all the possible PM messages (SUSPEND, HIBERNATE, FREEZE)
14188  * to the suspend() method call will be treated as SUSPEND and the driver will
14189  * fully reinitialize its device during resume() method call, the driver will
14190  * set device to PCI_D3hot state in PCI config space instead of setting it
14191  * according to the @msg provided by the PM.
14192  *
14193  * Return code
14194  * 	0 - driver suspended the device
14195  * 	Error otherwise
14196  **/
14197 static int __maybe_unused
14198 lpfc_pci_suspend_one_s3(struct device *dev_d)
14199 {
14200 	struct Scsi_Host *shost = dev_get_drvdata(dev_d);
14201 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14202 
14203 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
14204 			"0473 PCI device Power Management suspend.\n");
14205 
14206 	/* Bring down the device */
14207 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
14208 	lpfc_offline(phba);
14209 	kthread_stop(phba->worker_thread);
14210 
14211 	/* Disable interrupt from device */
14212 	lpfc_sli_disable_intr(phba);
14213 
14214 	return 0;
14215 }
14216 
14217 /**
14218  * lpfc_pci_resume_one_s3 - PCI func to resume SLI-3 device for power mgmnt
14219  * @dev_d: pointer to device
14220  *
14221  * This routine is to be called from the kernel's PCI subsystem to support
14222  * system Power Management (PM) to device with SLI-3 interface spec. When PM
14223  * invokes this method, it restores the device's PCI config space state and
14224  * fully reinitializes the device and brings it online. Note that as the
14225  * driver implements the minimum PM requirements to a power-aware driver's
14226  * PM for suspend/resume -- all the possible PM messages (SUSPEND, HIBERNATE,
14227  * FREEZE) to the suspend() method call will be treated as SUSPEND and the
14228  * driver will fully reinitialize its device during resume() method call,
14229  * the device will be set to PCI_D0 directly in PCI config space before
14230  * restoring the state.
14231  *
14232  * Return code
14233  * 	0 - driver suspended the device
14234  * 	Error otherwise
14235  **/
14236 static int __maybe_unused
14237 lpfc_pci_resume_one_s3(struct device *dev_d)
14238 {
14239 	struct Scsi_Host *shost = dev_get_drvdata(dev_d);
14240 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14241 	uint32_t intr_mode;
14242 	int error;
14243 
14244 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
14245 			"0452 PCI device Power Management resume.\n");
14246 
14247 	/* Startup the kernel thread for this host adapter. */
14248 	phba->worker_thread = kthread_run(lpfc_do_work, phba,
14249 					"lpfc_worker_%d", phba->brd_no);
14250 	if (IS_ERR(phba->worker_thread)) {
14251 		error = PTR_ERR(phba->worker_thread);
14252 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14253 				"0434 PM resume failed to start worker "
14254 				"thread: error=x%x.\n", error);
14255 		return error;
14256 	}
14257 
14258 	/* Init cpu_map array */
14259 	lpfc_cpu_map_array_init(phba);
14260 	/* Init hba_eq_hdl array */
14261 	lpfc_hba_eq_hdl_array_init(phba);
14262 	/* Configure and enable interrupt */
14263 	intr_mode = lpfc_sli_enable_intr(phba, phba->intr_mode);
14264 	if (intr_mode == LPFC_INTR_ERROR) {
14265 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14266 				"0430 PM resume Failed to enable interrupt\n");
14267 		return -EIO;
14268 	} else
14269 		phba->intr_mode = intr_mode;
14270 
14271 	/* Restart HBA and bring it online */
14272 	lpfc_sli_brdrestart(phba);
14273 	lpfc_online(phba);
14274 
14275 	/* Log the current active interrupt mode */
14276 	lpfc_log_intr_mode(phba, phba->intr_mode);
14277 
14278 	return 0;
14279 }
14280 
14281 /**
14282  * lpfc_sli_prep_dev_for_recover - Prepare SLI3 device for pci slot recover
14283  * @phba: pointer to lpfc hba data structure.
14284  *
14285  * This routine is called to prepare the SLI3 device for PCI slot recover. It
14286  * aborts all the outstanding SCSI I/Os to the pci device.
14287  **/
14288 static void
14289 lpfc_sli_prep_dev_for_recover(struct lpfc_hba *phba)
14290 {
14291 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14292 			"2723 PCI channel I/O abort preparing for recovery\n");
14293 
14294 	/*
14295 	 * There may be errored I/Os through HBA, abort all I/Os on txcmplq
14296 	 * and let the SCSI mid-layer to retry them to recover.
14297 	 */
14298 	lpfc_sli_abort_fcp_rings(phba);
14299 }
14300 
14301 /**
14302  * lpfc_sli_prep_dev_for_reset - Prepare SLI3 device for pci slot reset
14303  * @phba: pointer to lpfc hba data structure.
14304  *
14305  * This routine is called to prepare the SLI3 device for PCI slot reset. It
14306  * disables the device interrupt and pci device, and aborts the internal FCP
14307  * pending I/Os.
14308  **/
14309 static void
14310 lpfc_sli_prep_dev_for_reset(struct lpfc_hba *phba)
14311 {
14312 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14313 			"2710 PCI channel disable preparing for reset\n");
14314 
14315 	/* Block any management I/Os to the device */
14316 	lpfc_block_mgmt_io(phba, LPFC_MBX_WAIT);
14317 
14318 	/* Block all SCSI devices' I/Os on the host */
14319 	lpfc_scsi_dev_block(phba);
14320 
14321 	/* Flush all driver's outstanding SCSI I/Os as we are to reset */
14322 	lpfc_sli_flush_io_rings(phba);
14323 
14324 	/* stop all timers */
14325 	lpfc_stop_hba_timers(phba);
14326 
14327 	/* Disable interrupt and pci device */
14328 	lpfc_sli_disable_intr(phba);
14329 	pci_disable_device(phba->pcidev);
14330 }
14331 
14332 /**
14333  * lpfc_sli_prep_dev_for_perm_failure - Prepare SLI3 dev for pci slot disable
14334  * @phba: pointer to lpfc hba data structure.
14335  *
14336  * This routine is called to prepare the SLI3 device for PCI slot permanently
14337  * disabling. It blocks the SCSI transport layer traffic and flushes the FCP
14338  * pending I/Os.
14339  **/
14340 static void
14341 lpfc_sli_prep_dev_for_perm_failure(struct lpfc_hba *phba)
14342 {
14343 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14344 			"2711 PCI channel permanent disable for failure\n");
14345 	/* Block all SCSI devices' I/Os on the host */
14346 	lpfc_scsi_dev_block(phba);
14347 	lpfc_sli4_prep_dev_for_reset(phba);
14348 
14349 	/* stop all timers */
14350 	lpfc_stop_hba_timers(phba);
14351 
14352 	/* Clean up all driver's outstanding SCSI I/Os */
14353 	lpfc_sli_flush_io_rings(phba);
14354 }
14355 
14356 /**
14357  * lpfc_io_error_detected_s3 - Method for handling SLI-3 device PCI I/O error
14358  * @pdev: pointer to PCI device.
14359  * @state: the current PCI connection state.
14360  *
14361  * This routine is called from the PCI subsystem for I/O error handling to
14362  * device with SLI-3 interface spec. This function is called by the PCI
14363  * subsystem after a PCI bus error affecting this device has been detected.
14364  * When this function is invoked, it will need to stop all the I/Os and
14365  * interrupt(s) to the device. Once that is done, it will return
14366  * PCI_ERS_RESULT_NEED_RESET for the PCI subsystem to perform proper recovery
14367  * as desired.
14368  *
14369  * Return codes
14370  * 	PCI_ERS_RESULT_CAN_RECOVER - can be recovered with reset_link
14371  * 	PCI_ERS_RESULT_NEED_RESET - need to reset before recovery
14372  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
14373  **/
14374 static pci_ers_result_t
14375 lpfc_io_error_detected_s3(struct pci_dev *pdev, pci_channel_state_t state)
14376 {
14377 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
14378 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14379 
14380 	switch (state) {
14381 	case pci_channel_io_normal:
14382 		/* Non-fatal error, prepare for recovery */
14383 		lpfc_sli_prep_dev_for_recover(phba);
14384 		return PCI_ERS_RESULT_CAN_RECOVER;
14385 	case pci_channel_io_frozen:
14386 		/* Fatal error, prepare for slot reset */
14387 		lpfc_sli_prep_dev_for_reset(phba);
14388 		return PCI_ERS_RESULT_NEED_RESET;
14389 	case pci_channel_io_perm_failure:
14390 		/* Permanent failure, prepare for device down */
14391 		lpfc_sli_prep_dev_for_perm_failure(phba);
14392 		return PCI_ERS_RESULT_DISCONNECT;
14393 	default:
14394 		/* Unknown state, prepare and request slot reset */
14395 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14396 				"0472 Unknown PCI error state: x%x\n", state);
14397 		lpfc_sli_prep_dev_for_reset(phba);
14398 		return PCI_ERS_RESULT_NEED_RESET;
14399 	}
14400 }
14401 
14402 /**
14403  * lpfc_io_slot_reset_s3 - Method for restarting PCI SLI-3 device from scratch.
14404  * @pdev: pointer to PCI device.
14405  *
14406  * This routine is called from the PCI subsystem for error handling to
14407  * device with SLI-3 interface spec. This is called after PCI bus has been
14408  * reset to restart the PCI card from scratch, as if from a cold-boot.
14409  * During the PCI subsystem error recovery, after driver returns
14410  * PCI_ERS_RESULT_NEED_RESET, the PCI subsystem will perform proper error
14411  * recovery and then call this routine before calling the .resume method
14412  * to recover the device. This function will initialize the HBA device,
14413  * enable the interrupt, but it will just put the HBA to offline state
14414  * without passing any I/O traffic.
14415  *
14416  * Return codes
14417  * 	PCI_ERS_RESULT_RECOVERED - the device has been recovered
14418  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
14419  */
14420 static pci_ers_result_t
14421 lpfc_io_slot_reset_s3(struct pci_dev *pdev)
14422 {
14423 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
14424 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14425 	struct lpfc_sli *psli = &phba->sli;
14426 	uint32_t intr_mode;
14427 
14428 	dev_printk(KERN_INFO, &pdev->dev, "recovering from a slot reset.\n");
14429 	if (pci_enable_device_mem(pdev)) {
14430 		printk(KERN_ERR "lpfc: Cannot re-enable "
14431 			"PCI device after reset.\n");
14432 		return PCI_ERS_RESULT_DISCONNECT;
14433 	}
14434 
14435 	pci_restore_state(pdev);
14436 
14437 	/*
14438 	 * As the new kernel behavior of pci_restore_state() API call clears
14439 	 * device saved_state flag, need to save the restored state again.
14440 	 */
14441 	pci_save_state(pdev);
14442 
14443 	if (pdev->is_busmaster)
14444 		pci_set_master(pdev);
14445 
14446 	spin_lock_irq(&phba->hbalock);
14447 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
14448 	spin_unlock_irq(&phba->hbalock);
14449 
14450 	/* Configure and enable interrupt */
14451 	intr_mode = lpfc_sli_enable_intr(phba, phba->intr_mode);
14452 	if (intr_mode == LPFC_INTR_ERROR) {
14453 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14454 				"0427 Cannot re-enable interrupt after "
14455 				"slot reset.\n");
14456 		return PCI_ERS_RESULT_DISCONNECT;
14457 	} else
14458 		phba->intr_mode = intr_mode;
14459 
14460 	/* Take device offline, it will perform cleanup */
14461 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
14462 	lpfc_offline(phba);
14463 	lpfc_sli_brdrestart(phba);
14464 
14465 	/* Log the current active interrupt mode */
14466 	lpfc_log_intr_mode(phba, phba->intr_mode);
14467 
14468 	return PCI_ERS_RESULT_RECOVERED;
14469 }
14470 
14471 /**
14472  * lpfc_io_resume_s3 - Method for resuming PCI I/O operation on SLI-3 device.
14473  * @pdev: pointer to PCI device
14474  *
14475  * This routine is called from the PCI subsystem for error handling to device
14476  * with SLI-3 interface spec. It is called when kernel error recovery tells
14477  * the lpfc driver that it is ok to resume normal PCI operation after PCI bus
14478  * error recovery. After this call, traffic can start to flow from this device
14479  * again.
14480  */
14481 static void
14482 lpfc_io_resume_s3(struct pci_dev *pdev)
14483 {
14484 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
14485 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14486 
14487 	/* Bring device online, it will be no-op for non-fatal error resume */
14488 	lpfc_online(phba);
14489 }
14490 
14491 /**
14492  * lpfc_sli4_get_els_iocb_cnt - Calculate the # of ELS IOCBs to reserve
14493  * @phba: pointer to lpfc hba data structure.
14494  *
14495  * returns the number of ELS/CT IOCBs to reserve
14496  **/
14497 int
14498 lpfc_sli4_get_els_iocb_cnt(struct lpfc_hba *phba)
14499 {
14500 	int max_xri = phba->sli4_hba.max_cfg_param.max_xri;
14501 
14502 	if (phba->sli_rev == LPFC_SLI_REV4) {
14503 		if (max_xri <= 100)
14504 			return 10;
14505 		else if (max_xri <= 256)
14506 			return 25;
14507 		else if (max_xri <= 512)
14508 			return 50;
14509 		else if (max_xri <= 1024)
14510 			return 100;
14511 		else if (max_xri <= 1536)
14512 			return 150;
14513 		else if (max_xri <= 2048)
14514 			return 200;
14515 		else
14516 			return 250;
14517 	} else
14518 		return 0;
14519 }
14520 
14521 /**
14522  * lpfc_sli4_get_iocb_cnt - Calculate the # of total IOCBs to reserve
14523  * @phba: pointer to lpfc hba data structure.
14524  *
14525  * returns the number of ELS/CT + NVMET IOCBs to reserve
14526  **/
14527 int
14528 lpfc_sli4_get_iocb_cnt(struct lpfc_hba *phba)
14529 {
14530 	int max_xri = lpfc_sli4_get_els_iocb_cnt(phba);
14531 
14532 	if (phba->nvmet_support)
14533 		max_xri += LPFC_NVMET_BUF_POST;
14534 	return max_xri;
14535 }
14536 
14537 
14538 static int
14539 lpfc_log_write_firmware_error(struct lpfc_hba *phba, uint32_t offset,
14540 	uint32_t magic_number, uint32_t ftype, uint32_t fid, uint32_t fsize,
14541 	const struct firmware *fw)
14542 {
14543 	int rc;
14544 	u8 sli_family;
14545 
14546 	sli_family = bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf);
14547 	/* Three cases:  (1) FW was not supported on the detected adapter.
14548 	 * (2) FW update has been locked out administratively.
14549 	 * (3) Some other error during FW update.
14550 	 * In each case, an unmaskable message is written to the console
14551 	 * for admin diagnosis.
14552 	 */
14553 	if (offset == ADD_STATUS_FW_NOT_SUPPORTED ||
14554 	    (sli_family == LPFC_SLI_INTF_FAMILY_G6 &&
14555 	     magic_number != MAGIC_NUMBER_G6) ||
14556 	    (sli_family == LPFC_SLI_INTF_FAMILY_G7 &&
14557 	     magic_number != MAGIC_NUMBER_G7) ||
14558 	    (sli_family == LPFC_SLI_INTF_FAMILY_G7P &&
14559 	     magic_number != MAGIC_NUMBER_G7P)) {
14560 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14561 				"3030 This firmware version is not supported on"
14562 				" this HBA model. Device:%x Magic:%x Type:%x "
14563 				"ID:%x Size %d %zd\n",
14564 				phba->pcidev->device, magic_number, ftype, fid,
14565 				fsize, fw->size);
14566 		rc = -EINVAL;
14567 	} else if (offset == ADD_STATUS_FW_DOWNLOAD_HW_DISABLED) {
14568 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14569 				"3021 Firmware downloads have been prohibited "
14570 				"by a system configuration setting on "
14571 				"Device:%x Magic:%x Type:%x ID:%x Size %d "
14572 				"%zd\n",
14573 				phba->pcidev->device, magic_number, ftype, fid,
14574 				fsize, fw->size);
14575 		rc = -EACCES;
14576 	} else {
14577 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14578 				"3022 FW Download failed. Add Status x%x "
14579 				"Device:%x Magic:%x Type:%x ID:%x Size %d "
14580 				"%zd\n",
14581 				offset, phba->pcidev->device, magic_number,
14582 				ftype, fid, fsize, fw->size);
14583 		rc = -EIO;
14584 	}
14585 	return rc;
14586 }
14587 
14588 /**
14589  * lpfc_write_firmware - attempt to write a firmware image to the port
14590  * @fw: pointer to firmware image returned from request_firmware.
14591  * @context: pointer to firmware image returned from request_firmware.
14592  *
14593  **/
14594 static void
14595 lpfc_write_firmware(const struct firmware *fw, void *context)
14596 {
14597 	struct lpfc_hba *phba = (struct lpfc_hba *)context;
14598 	char fwrev[FW_REV_STR_SIZE];
14599 	struct lpfc_grp_hdr *image;
14600 	struct list_head dma_buffer_list;
14601 	int i, rc = 0;
14602 	struct lpfc_dmabuf *dmabuf, *next;
14603 	uint32_t offset = 0, temp_offset = 0;
14604 	uint32_t magic_number, ftype, fid, fsize;
14605 
14606 	/* It can be null in no-wait mode, sanity check */
14607 	if (!fw) {
14608 		rc = -ENXIO;
14609 		goto out;
14610 	}
14611 	image = (struct lpfc_grp_hdr *)fw->data;
14612 
14613 	magic_number = be32_to_cpu(image->magic_number);
14614 	ftype = bf_get_be32(lpfc_grp_hdr_file_type, image);
14615 	fid = bf_get_be32(lpfc_grp_hdr_id, image);
14616 	fsize = be32_to_cpu(image->size);
14617 
14618 	INIT_LIST_HEAD(&dma_buffer_list);
14619 	lpfc_decode_firmware_rev(phba, fwrev, 1);
14620 	if (strncmp(fwrev, image->revision, strnlen(image->revision, 16))) {
14621 		lpfc_log_msg(phba, KERN_NOTICE, LOG_INIT | LOG_SLI,
14622 			     "3023 Updating Firmware, Current Version:%s "
14623 			     "New Version:%s\n",
14624 			     fwrev, image->revision);
14625 		for (i = 0; i < LPFC_MBX_WR_CONFIG_MAX_BDE; i++) {
14626 			dmabuf = kzalloc(sizeof(struct lpfc_dmabuf),
14627 					 GFP_KERNEL);
14628 			if (!dmabuf) {
14629 				rc = -ENOMEM;
14630 				goto release_out;
14631 			}
14632 			dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
14633 							  SLI4_PAGE_SIZE,
14634 							  &dmabuf->phys,
14635 							  GFP_KERNEL);
14636 			if (!dmabuf->virt) {
14637 				kfree(dmabuf);
14638 				rc = -ENOMEM;
14639 				goto release_out;
14640 			}
14641 			list_add_tail(&dmabuf->list, &dma_buffer_list);
14642 		}
14643 		while (offset < fw->size) {
14644 			temp_offset = offset;
14645 			list_for_each_entry(dmabuf, &dma_buffer_list, list) {
14646 				if (temp_offset + SLI4_PAGE_SIZE > fw->size) {
14647 					memcpy(dmabuf->virt,
14648 					       fw->data + temp_offset,
14649 					       fw->size - temp_offset);
14650 					temp_offset = fw->size;
14651 					break;
14652 				}
14653 				memcpy(dmabuf->virt, fw->data + temp_offset,
14654 				       SLI4_PAGE_SIZE);
14655 				temp_offset += SLI4_PAGE_SIZE;
14656 			}
14657 			rc = lpfc_wr_object(phba, &dma_buffer_list,
14658 				    (fw->size - offset), &offset);
14659 			if (rc) {
14660 				rc = lpfc_log_write_firmware_error(phba, offset,
14661 								   magic_number,
14662 								   ftype,
14663 								   fid,
14664 								   fsize,
14665 								   fw);
14666 				goto release_out;
14667 			}
14668 		}
14669 		rc = offset;
14670 	} else
14671 		lpfc_log_msg(phba, KERN_NOTICE, LOG_INIT | LOG_SLI,
14672 			     "3029 Skipped Firmware update, Current "
14673 			     "Version:%s New Version:%s\n",
14674 			     fwrev, image->revision);
14675 
14676 release_out:
14677 	list_for_each_entry_safe(dmabuf, next, &dma_buffer_list, list) {
14678 		list_del(&dmabuf->list);
14679 		dma_free_coherent(&phba->pcidev->dev, SLI4_PAGE_SIZE,
14680 				  dmabuf->virt, dmabuf->phys);
14681 		kfree(dmabuf);
14682 	}
14683 	release_firmware(fw);
14684 out:
14685 	if (rc < 0)
14686 		lpfc_log_msg(phba, KERN_ERR, LOG_INIT | LOG_SLI,
14687 			     "3062 Firmware update error, status %d.\n", rc);
14688 	else
14689 		lpfc_log_msg(phba, KERN_NOTICE, LOG_INIT | LOG_SLI,
14690 			     "3024 Firmware update success: size %d.\n", rc);
14691 }
14692 
14693 /**
14694  * lpfc_sli4_request_firmware_update - Request linux generic firmware upgrade
14695  * @phba: pointer to lpfc hba data structure.
14696  * @fw_upgrade: which firmware to update.
14697  *
14698  * This routine is called to perform Linux generic firmware upgrade on device
14699  * that supports such feature.
14700  **/
14701 int
14702 lpfc_sli4_request_firmware_update(struct lpfc_hba *phba, uint8_t fw_upgrade)
14703 {
14704 	char file_name[ELX_FW_NAME_SIZE] = {0};
14705 	int ret;
14706 	const struct firmware *fw;
14707 
14708 	/* Only supported on SLI4 interface type 2 for now */
14709 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) <
14710 	    LPFC_SLI_INTF_IF_TYPE_2)
14711 		return -EPERM;
14712 
14713 	scnprintf(file_name, sizeof(file_name), "%s.grp", phba->ModelName);
14714 
14715 	if (fw_upgrade == INT_FW_UPGRADE) {
14716 		ret = request_firmware_nowait(THIS_MODULE, FW_ACTION_UEVENT,
14717 					file_name, &phba->pcidev->dev,
14718 					GFP_KERNEL, (void *)phba,
14719 					lpfc_write_firmware);
14720 	} else if (fw_upgrade == RUN_FW_UPGRADE) {
14721 		ret = request_firmware(&fw, file_name, &phba->pcidev->dev);
14722 		if (!ret)
14723 			lpfc_write_firmware(fw, (void *)phba);
14724 	} else {
14725 		ret = -EINVAL;
14726 	}
14727 
14728 	return ret;
14729 }
14730 
14731 /**
14732  * lpfc_pci_probe_one_s4 - PCI probe func to reg SLI-4 device to PCI subsys
14733  * @pdev: pointer to PCI device
14734  * @pid: pointer to PCI device identifier
14735  *
14736  * This routine is called from the kernel's PCI subsystem to device with
14737  * SLI-4 interface spec. When an Emulex HBA with SLI-4 interface spec is
14738  * presented on PCI bus, the kernel PCI subsystem looks at PCI device-specific
14739  * information of the device and driver to see if the driver state that it
14740  * can support this kind of device. If the match is successful, the driver
14741  * core invokes this routine. If this routine determines it can claim the HBA,
14742  * it does all the initialization that it needs to do to handle the HBA
14743  * properly.
14744  *
14745  * Return code
14746  * 	0 - driver can claim the device
14747  * 	negative value - driver can not claim the device
14748  **/
14749 static int
14750 lpfc_pci_probe_one_s4(struct pci_dev *pdev, const struct pci_device_id *pid)
14751 {
14752 	struct lpfc_hba   *phba;
14753 	struct lpfc_vport *vport = NULL;
14754 	struct Scsi_Host  *shost = NULL;
14755 	int error;
14756 	uint32_t cfg_mode, intr_mode;
14757 
14758 	/* Allocate memory for HBA structure */
14759 	phba = lpfc_hba_alloc(pdev);
14760 	if (!phba)
14761 		return -ENOMEM;
14762 
14763 	INIT_LIST_HEAD(&phba->poll_list);
14764 
14765 	/* Perform generic PCI device enabling operation */
14766 	error = lpfc_enable_pci_dev(phba);
14767 	if (error)
14768 		goto out_free_phba;
14769 
14770 	/* Set up SLI API function jump table for PCI-device group-1 HBAs */
14771 	error = lpfc_api_table_setup(phba, LPFC_PCI_DEV_OC);
14772 	if (error)
14773 		goto out_disable_pci_dev;
14774 
14775 	/* Set up SLI-4 specific device PCI memory space */
14776 	error = lpfc_sli4_pci_mem_setup(phba);
14777 	if (error) {
14778 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14779 				"1410 Failed to set up pci memory space.\n");
14780 		goto out_disable_pci_dev;
14781 	}
14782 
14783 	/* Set up SLI-4 Specific device driver resources */
14784 	error = lpfc_sli4_driver_resource_setup(phba);
14785 	if (error) {
14786 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14787 				"1412 Failed to set up driver resource.\n");
14788 		goto out_unset_pci_mem_s4;
14789 	}
14790 
14791 	spin_lock_init(&phba->rrq_list_lock);
14792 	INIT_LIST_HEAD(&phba->active_rrq_list);
14793 	INIT_LIST_HEAD(&phba->fcf.fcf_pri_list);
14794 
14795 	/* Set up common device driver resources */
14796 	error = lpfc_setup_driver_resource_phase2(phba);
14797 	if (error) {
14798 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14799 				"1414 Failed to set up driver resource.\n");
14800 		goto out_unset_driver_resource_s4;
14801 	}
14802 
14803 	/* Get the default values for Model Name and Description */
14804 	lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
14805 
14806 	/* Now, trying to enable interrupt and bring up the device */
14807 	cfg_mode = phba->cfg_use_msi;
14808 
14809 	/* Put device to a known state before enabling interrupt */
14810 	phba->pport = NULL;
14811 	lpfc_stop_port(phba);
14812 
14813 	/* Init cpu_map array */
14814 	lpfc_cpu_map_array_init(phba);
14815 
14816 	/* Init hba_eq_hdl array */
14817 	lpfc_hba_eq_hdl_array_init(phba);
14818 
14819 	/* Configure and enable interrupt */
14820 	intr_mode = lpfc_sli4_enable_intr(phba, cfg_mode);
14821 	if (intr_mode == LPFC_INTR_ERROR) {
14822 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14823 				"0426 Failed to enable interrupt.\n");
14824 		error = -ENODEV;
14825 		goto out_unset_driver_resource;
14826 	}
14827 	/* Default to single EQ for non-MSI-X */
14828 	if (phba->intr_type != MSIX) {
14829 		phba->cfg_irq_chann = 1;
14830 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
14831 			if (phba->nvmet_support)
14832 				phba->cfg_nvmet_mrq = 1;
14833 		}
14834 	}
14835 	lpfc_cpu_affinity_check(phba, phba->cfg_irq_chann);
14836 
14837 	/* Create SCSI host to the physical port */
14838 	error = lpfc_create_shost(phba);
14839 	if (error) {
14840 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14841 				"1415 Failed to create scsi host.\n");
14842 		goto out_disable_intr;
14843 	}
14844 	vport = phba->pport;
14845 	shost = lpfc_shost_from_vport(vport); /* save shost for error cleanup */
14846 
14847 	/* Configure sysfs attributes */
14848 	error = lpfc_alloc_sysfs_attr(vport);
14849 	if (error) {
14850 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14851 				"1416 Failed to allocate sysfs attr\n");
14852 		goto out_destroy_shost;
14853 	}
14854 
14855 	/* Set up SLI-4 HBA */
14856 	if (lpfc_sli4_hba_setup(phba)) {
14857 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14858 				"1421 Failed to set up hba\n");
14859 		error = -ENODEV;
14860 		goto out_free_sysfs_attr;
14861 	}
14862 
14863 	/* Log the current active interrupt mode */
14864 	phba->intr_mode = intr_mode;
14865 	lpfc_log_intr_mode(phba, intr_mode);
14866 
14867 	/* Perform post initialization setup */
14868 	lpfc_post_init_setup(phba);
14869 
14870 	/* NVME support in FW earlier in the driver load corrects the
14871 	 * FC4 type making a check for nvme_support unnecessary.
14872 	 */
14873 	if (phba->nvmet_support == 0) {
14874 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
14875 			/* Create NVME binding with nvme_fc_transport. This
14876 			 * ensures the vport is initialized.  If the localport
14877 			 * create fails, it should not unload the driver to
14878 			 * support field issues.
14879 			 */
14880 			error = lpfc_nvme_create_localport(vport);
14881 			if (error) {
14882 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14883 						"6004 NVME registration "
14884 						"failed, error x%x\n",
14885 						error);
14886 			}
14887 		}
14888 	}
14889 
14890 	/* check for firmware upgrade or downgrade */
14891 	if (phba->cfg_request_firmware_upgrade)
14892 		lpfc_sli4_request_firmware_update(phba, INT_FW_UPGRADE);
14893 
14894 	/* Check if there are static vports to be created. */
14895 	lpfc_create_static_vport(phba);
14896 
14897 	timer_setup(&phba->cpuhp_poll_timer, lpfc_sli4_poll_hbtimer, 0);
14898 	cpuhp_state_add_instance_nocalls(lpfc_cpuhp_state, &phba->cpuhp);
14899 
14900 	return 0;
14901 
14902 out_free_sysfs_attr:
14903 	lpfc_free_sysfs_attr(vport);
14904 out_destroy_shost:
14905 	lpfc_destroy_shost(phba);
14906 out_disable_intr:
14907 	lpfc_sli4_disable_intr(phba);
14908 out_unset_driver_resource:
14909 	lpfc_unset_driver_resource_phase2(phba);
14910 out_unset_driver_resource_s4:
14911 	lpfc_sli4_driver_resource_unset(phba);
14912 out_unset_pci_mem_s4:
14913 	lpfc_sli4_pci_mem_unset(phba);
14914 out_disable_pci_dev:
14915 	lpfc_disable_pci_dev(phba);
14916 	if (shost)
14917 		scsi_host_put(shost);
14918 out_free_phba:
14919 	lpfc_hba_free(phba);
14920 	return error;
14921 }
14922 
14923 /**
14924  * lpfc_pci_remove_one_s4 - PCI func to unreg SLI-4 device from PCI subsystem
14925  * @pdev: pointer to PCI device
14926  *
14927  * This routine is called from the kernel's PCI subsystem to device with
14928  * SLI-4 interface spec. When an Emulex HBA with SLI-4 interface spec is
14929  * removed from PCI bus, it performs all the necessary cleanup for the HBA
14930  * device to be removed from the PCI subsystem properly.
14931  **/
14932 static void
14933 lpfc_pci_remove_one_s4(struct pci_dev *pdev)
14934 {
14935 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
14936 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
14937 	struct lpfc_vport **vports;
14938 	struct lpfc_hba *phba = vport->phba;
14939 	int i;
14940 
14941 	/* Mark the device unloading flag */
14942 	set_bit(FC_UNLOADING, &vport->load_flag);
14943 	if (phba->cgn_i)
14944 		lpfc_unreg_congestion_buf(phba);
14945 
14946 	lpfc_free_sysfs_attr(vport);
14947 
14948 	/* Release all the vports against this physical port */
14949 	vports = lpfc_create_vport_work_array(phba);
14950 	if (vports != NULL)
14951 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
14952 			if (vports[i]->port_type == LPFC_PHYSICAL_PORT)
14953 				continue;
14954 			fc_vport_terminate(vports[i]->fc_vport);
14955 		}
14956 	lpfc_destroy_vport_work_array(phba, vports);
14957 
14958 	/* Remove FC host with the physical port */
14959 	fc_remove_host(shost);
14960 	scsi_remove_host(shost);
14961 
14962 	/* Perform ndlp cleanup on the physical port.  The nvme and nvmet
14963 	 * localports are destroyed after to cleanup all transport memory.
14964 	 */
14965 	lpfc_cleanup(vport);
14966 	lpfc_nvmet_destroy_targetport(phba);
14967 	lpfc_nvme_destroy_localport(vport);
14968 
14969 	/* De-allocate multi-XRI pools */
14970 	if (phba->cfg_xri_rebalancing)
14971 		lpfc_destroy_multixri_pools(phba);
14972 
14973 	/*
14974 	 * Bring down the SLI Layer. This step disables all interrupts,
14975 	 * clears the rings, discards all mailbox commands, and resets
14976 	 * the HBA FCoE function.
14977 	 */
14978 	lpfc_debugfs_terminate(vport);
14979 
14980 	lpfc_stop_hba_timers(phba);
14981 	spin_lock_irq(&phba->port_list_lock);
14982 	list_del_init(&vport->listentry);
14983 	spin_unlock_irq(&phba->port_list_lock);
14984 
14985 	/* Perform scsi free before driver resource_unset since scsi
14986 	 * buffers are released to their corresponding pools here.
14987 	 */
14988 	lpfc_io_free(phba);
14989 	lpfc_free_iocb_list(phba);
14990 	lpfc_sli4_hba_unset(phba);
14991 
14992 	lpfc_unset_driver_resource_phase2(phba);
14993 	lpfc_sli4_driver_resource_unset(phba);
14994 
14995 	/* Unmap adapter Control and Doorbell registers */
14996 	lpfc_sli4_pci_mem_unset(phba);
14997 
14998 	/* Release PCI resources and disable device's PCI function */
14999 	scsi_host_put(shost);
15000 	lpfc_disable_pci_dev(phba);
15001 
15002 	/* Finally, free the driver's device data structure */
15003 	lpfc_hba_free(phba);
15004 
15005 	return;
15006 }
15007 
15008 /**
15009  * lpfc_pci_suspend_one_s4 - PCI func to suspend SLI-4 device for power mgmnt
15010  * @dev_d: pointer to device
15011  *
15012  * This routine is called from the kernel's PCI subsystem to support system
15013  * Power Management (PM) to device with SLI-4 interface spec. When PM invokes
15014  * this method, it quiesces the device by stopping the driver's worker
15015  * thread for the device, turning off device's interrupt and DMA, and bring
15016  * the device offline. Note that as the driver implements the minimum PM
15017  * requirements to a power-aware driver's PM support for suspend/resume -- all
15018  * the possible PM messages (SUSPEND, HIBERNATE, FREEZE) to the suspend()
15019  * method call will be treated as SUSPEND and the driver will fully
15020  * reinitialize its device during resume() method call, the driver will set
15021  * device to PCI_D3hot state in PCI config space instead of setting it
15022  * according to the @msg provided by the PM.
15023  *
15024  * Return code
15025  * 	0 - driver suspended the device
15026  * 	Error otherwise
15027  **/
15028 static int __maybe_unused
15029 lpfc_pci_suspend_one_s4(struct device *dev_d)
15030 {
15031 	struct Scsi_Host *shost = dev_get_drvdata(dev_d);
15032 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15033 
15034 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
15035 			"2843 PCI device Power Management suspend.\n");
15036 
15037 	/* Bring down the device */
15038 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
15039 	lpfc_offline(phba);
15040 	kthread_stop(phba->worker_thread);
15041 
15042 	/* Disable interrupt from device */
15043 	lpfc_sli4_disable_intr(phba);
15044 	lpfc_sli4_queue_destroy(phba);
15045 
15046 	return 0;
15047 }
15048 
15049 /**
15050  * lpfc_pci_resume_one_s4 - PCI func to resume SLI-4 device for power mgmnt
15051  * @dev_d: pointer to device
15052  *
15053  * This routine is called from the kernel's PCI subsystem to support system
15054  * Power Management (PM) to device with SLI-4 interface spac. When PM invokes
15055  * this method, it restores the device's PCI config space state and fully
15056  * reinitializes the device and brings it online. Note that as the driver
15057  * implements the minimum PM requirements to a power-aware driver's PM for
15058  * suspend/resume -- all the possible PM messages (SUSPEND, HIBERNATE, FREEZE)
15059  * to the suspend() method call will be treated as SUSPEND and the driver
15060  * will fully reinitialize its device during resume() method call, the device
15061  * will be set to PCI_D0 directly in PCI config space before restoring the
15062  * state.
15063  *
15064  * Return code
15065  * 	0 - driver suspended the device
15066  * 	Error otherwise
15067  **/
15068 static int __maybe_unused
15069 lpfc_pci_resume_one_s4(struct device *dev_d)
15070 {
15071 	struct Scsi_Host *shost = dev_get_drvdata(dev_d);
15072 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15073 	uint32_t intr_mode;
15074 	int error;
15075 
15076 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
15077 			"0292 PCI device Power Management resume.\n");
15078 
15079 	 /* Startup the kernel thread for this host adapter. */
15080 	phba->worker_thread = kthread_run(lpfc_do_work, phba,
15081 					"lpfc_worker_%d", phba->brd_no);
15082 	if (IS_ERR(phba->worker_thread)) {
15083 		error = PTR_ERR(phba->worker_thread);
15084 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15085 				"0293 PM resume failed to start worker "
15086 				"thread: error=x%x.\n", error);
15087 		return error;
15088 	}
15089 
15090 	/* Configure and enable interrupt */
15091 	intr_mode = lpfc_sli4_enable_intr(phba, phba->intr_mode);
15092 	if (intr_mode == LPFC_INTR_ERROR) {
15093 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15094 				"0294 PM resume Failed to enable interrupt\n");
15095 		return -EIO;
15096 	} else
15097 		phba->intr_mode = intr_mode;
15098 
15099 	/* Restart HBA and bring it online */
15100 	lpfc_sli_brdrestart(phba);
15101 	lpfc_online(phba);
15102 
15103 	/* Log the current active interrupt mode */
15104 	lpfc_log_intr_mode(phba, phba->intr_mode);
15105 
15106 	return 0;
15107 }
15108 
15109 /**
15110  * lpfc_sli4_prep_dev_for_recover - Prepare SLI4 device for pci slot recover
15111  * @phba: pointer to lpfc hba data structure.
15112  *
15113  * This routine is called to prepare the SLI4 device for PCI slot recover. It
15114  * aborts all the outstanding SCSI I/Os to the pci device.
15115  **/
15116 static void
15117 lpfc_sli4_prep_dev_for_recover(struct lpfc_hba *phba)
15118 {
15119 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15120 			"2828 PCI channel I/O abort preparing for recovery\n");
15121 	/*
15122 	 * There may be errored I/Os through HBA, abort all I/Os on txcmplq
15123 	 * and let the SCSI mid-layer to retry them to recover.
15124 	 */
15125 	lpfc_sli_abort_fcp_rings(phba);
15126 }
15127 
15128 /**
15129  * lpfc_sli4_prep_dev_for_reset - Prepare SLI4 device for pci slot reset
15130  * @phba: pointer to lpfc hba data structure.
15131  *
15132  * This routine is called to prepare the SLI4 device for PCI slot reset. It
15133  * disables the device interrupt and pci device, and aborts the internal FCP
15134  * pending I/Os.
15135  **/
15136 static void
15137 lpfc_sli4_prep_dev_for_reset(struct lpfc_hba *phba)
15138 {
15139 	int offline =  pci_channel_offline(phba->pcidev);
15140 
15141 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15142 			"2826 PCI channel disable preparing for reset offline"
15143 			" %d\n", offline);
15144 
15145 	/* Block any management I/Os to the device */
15146 	lpfc_block_mgmt_io(phba, LPFC_MBX_NO_WAIT);
15147 
15148 
15149 	/* HBA_PCI_ERR was set in io_error_detect */
15150 	lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
15151 	/* Flush all driver's outstanding I/Os as we are to reset */
15152 	lpfc_sli_flush_io_rings(phba);
15153 	lpfc_offline(phba);
15154 
15155 	/* stop all timers */
15156 	lpfc_stop_hba_timers(phba);
15157 
15158 	lpfc_sli4_queue_destroy(phba);
15159 	/* Disable interrupt and pci device */
15160 	lpfc_sli4_disable_intr(phba);
15161 	pci_disable_device(phba->pcidev);
15162 }
15163 
15164 /**
15165  * lpfc_sli4_prep_dev_for_perm_failure - Prepare SLI4 dev for pci slot disable
15166  * @phba: pointer to lpfc hba data structure.
15167  *
15168  * This routine is called to prepare the SLI4 device for PCI slot permanently
15169  * disabling. It blocks the SCSI transport layer traffic and flushes the FCP
15170  * pending I/Os.
15171  **/
15172 static void
15173 lpfc_sli4_prep_dev_for_perm_failure(struct lpfc_hba *phba)
15174 {
15175 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15176 			"2827 PCI channel permanent disable for failure\n");
15177 
15178 	/* Block all SCSI devices' I/Os on the host */
15179 	lpfc_scsi_dev_block(phba);
15180 
15181 	/* stop all timers */
15182 	lpfc_stop_hba_timers(phba);
15183 
15184 	/* Clean up all driver's outstanding I/Os */
15185 	lpfc_sli_flush_io_rings(phba);
15186 }
15187 
15188 /**
15189  * lpfc_io_error_detected_s4 - Method for handling PCI I/O error to SLI-4 device
15190  * @pdev: pointer to PCI device.
15191  * @state: the current PCI connection state.
15192  *
15193  * This routine is called from the PCI subsystem for error handling to device
15194  * with SLI-4 interface spec. This function is called by the PCI subsystem
15195  * after a PCI bus error affecting this device has been detected. When this
15196  * function is invoked, it will need to stop all the I/Os and interrupt(s)
15197  * to the device. Once that is done, it will return PCI_ERS_RESULT_NEED_RESET
15198  * for the PCI subsystem to perform proper recovery as desired.
15199  *
15200  * Return codes
15201  * 	PCI_ERS_RESULT_NEED_RESET - need to reset before recovery
15202  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15203  **/
15204 static pci_ers_result_t
15205 lpfc_io_error_detected_s4(struct pci_dev *pdev, pci_channel_state_t state)
15206 {
15207 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15208 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15209 	bool hba_pci_err;
15210 
15211 	switch (state) {
15212 	case pci_channel_io_normal:
15213 		/* Non-fatal error, prepare for recovery */
15214 		lpfc_sli4_prep_dev_for_recover(phba);
15215 		return PCI_ERS_RESULT_CAN_RECOVER;
15216 	case pci_channel_io_frozen:
15217 		hba_pci_err = test_and_set_bit(HBA_PCI_ERR, &phba->bit_flags);
15218 		/* Fatal error, prepare for slot reset */
15219 		if (!hba_pci_err)
15220 			lpfc_sli4_prep_dev_for_reset(phba);
15221 		else
15222 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15223 					"2832  Already handling PCI error "
15224 					"state: x%x\n", state);
15225 		return PCI_ERS_RESULT_NEED_RESET;
15226 	case pci_channel_io_perm_failure:
15227 		set_bit(HBA_PCI_ERR, &phba->bit_flags);
15228 		/* Permanent failure, prepare for device down */
15229 		lpfc_sli4_prep_dev_for_perm_failure(phba);
15230 		return PCI_ERS_RESULT_DISCONNECT;
15231 	default:
15232 		hba_pci_err = test_and_set_bit(HBA_PCI_ERR, &phba->bit_flags);
15233 		if (!hba_pci_err)
15234 			lpfc_sli4_prep_dev_for_reset(phba);
15235 		/* Unknown state, prepare and request slot reset */
15236 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15237 				"2825 Unknown PCI error state: x%x\n", state);
15238 		lpfc_sli4_prep_dev_for_reset(phba);
15239 		return PCI_ERS_RESULT_NEED_RESET;
15240 	}
15241 }
15242 
15243 /**
15244  * lpfc_io_slot_reset_s4 - Method for restart PCI SLI-4 device from scratch
15245  * @pdev: pointer to PCI device.
15246  *
15247  * This routine is called from the PCI subsystem for error handling to device
15248  * with SLI-4 interface spec. It is called after PCI bus has been reset to
15249  * restart the PCI card from scratch, as if from a cold-boot. During the
15250  * PCI subsystem error recovery, after the driver returns
15251  * PCI_ERS_RESULT_NEED_RESET, the PCI subsystem will perform proper error
15252  * recovery and then call this routine before calling the .resume method to
15253  * recover the device. This function will initialize the HBA device, enable
15254  * the interrupt, but it will just put the HBA to offline state without
15255  * passing any I/O traffic.
15256  *
15257  * Return codes
15258  * 	PCI_ERS_RESULT_RECOVERED - the device has been recovered
15259  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15260  */
15261 static pci_ers_result_t
15262 lpfc_io_slot_reset_s4(struct pci_dev *pdev)
15263 {
15264 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15265 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15266 	struct lpfc_sli *psli = &phba->sli;
15267 	uint32_t intr_mode;
15268 	bool hba_pci_err;
15269 
15270 	dev_printk(KERN_INFO, &pdev->dev, "recovering from a slot reset.\n");
15271 	if (pci_enable_device_mem(pdev)) {
15272 		printk(KERN_ERR "lpfc: Cannot re-enable "
15273 		       "PCI device after reset.\n");
15274 		return PCI_ERS_RESULT_DISCONNECT;
15275 	}
15276 
15277 	pci_restore_state(pdev);
15278 
15279 	hba_pci_err = test_and_clear_bit(HBA_PCI_ERR, &phba->bit_flags);
15280 	if (!hba_pci_err)
15281 		dev_info(&pdev->dev,
15282 			 "hba_pci_err was not set, recovering slot reset.\n");
15283 	/*
15284 	 * As the new kernel behavior of pci_restore_state() API call clears
15285 	 * device saved_state flag, need to save the restored state again.
15286 	 */
15287 	pci_save_state(pdev);
15288 
15289 	if (pdev->is_busmaster)
15290 		pci_set_master(pdev);
15291 
15292 	spin_lock_irq(&phba->hbalock);
15293 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
15294 	spin_unlock_irq(&phba->hbalock);
15295 
15296 	/* Init cpu_map array */
15297 	lpfc_cpu_map_array_init(phba);
15298 	/* Configure and enable interrupt */
15299 	intr_mode = lpfc_sli4_enable_intr(phba, phba->intr_mode);
15300 	if (intr_mode == LPFC_INTR_ERROR) {
15301 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15302 				"2824 Cannot re-enable interrupt after "
15303 				"slot reset.\n");
15304 		return PCI_ERS_RESULT_DISCONNECT;
15305 	} else
15306 		phba->intr_mode = intr_mode;
15307 	lpfc_cpu_affinity_check(phba, phba->cfg_irq_chann);
15308 
15309 	/* Log the current active interrupt mode */
15310 	lpfc_log_intr_mode(phba, phba->intr_mode);
15311 
15312 	return PCI_ERS_RESULT_RECOVERED;
15313 }
15314 
15315 /**
15316  * lpfc_io_resume_s4 - Method for resuming PCI I/O operation to SLI-4 device
15317  * @pdev: pointer to PCI device
15318  *
15319  * This routine is called from the PCI subsystem for error handling to device
15320  * with SLI-4 interface spec. It is called when kernel error recovery tells
15321  * the lpfc driver that it is ok to resume normal PCI operation after PCI bus
15322  * error recovery. After this call, traffic can start to flow from this device
15323  * again.
15324  **/
15325 static void
15326 lpfc_io_resume_s4(struct pci_dev *pdev)
15327 {
15328 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15329 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15330 
15331 	/*
15332 	 * In case of slot reset, as function reset is performed through
15333 	 * mailbox command which needs DMA to be enabled, this operation
15334 	 * has to be moved to the io resume phase. Taking device offline
15335 	 * will perform the necessary cleanup.
15336 	 */
15337 	if (!(phba->sli.sli_flag & LPFC_SLI_ACTIVE)) {
15338 		/* Perform device reset */
15339 		lpfc_sli_brdrestart(phba);
15340 		/* Bring the device back online */
15341 		lpfc_online(phba);
15342 	}
15343 }
15344 
15345 /**
15346  * lpfc_pci_probe_one - lpfc PCI probe func to reg dev to PCI subsystem
15347  * @pdev: pointer to PCI device
15348  * @pid: pointer to PCI device identifier
15349  *
15350  * This routine is to be registered to the kernel's PCI subsystem. When an
15351  * Emulex HBA device is presented on PCI bus, the kernel PCI subsystem looks
15352  * at PCI device-specific information of the device and driver to see if the
15353  * driver state that it can support this kind of device. If the match is
15354  * successful, the driver core invokes this routine. This routine dispatches
15355  * the action to the proper SLI-3 or SLI-4 device probing routine, which will
15356  * do all the initialization that it needs to do to handle the HBA device
15357  * properly.
15358  *
15359  * Return code
15360  * 	0 - driver can claim the device
15361  * 	negative value - driver can not claim the device
15362  **/
15363 static int
15364 lpfc_pci_probe_one(struct pci_dev *pdev, const struct pci_device_id *pid)
15365 {
15366 	int rc;
15367 	struct lpfc_sli_intf intf;
15368 
15369 	if (pci_read_config_dword(pdev, LPFC_SLI_INTF, &intf.word0))
15370 		return -ENODEV;
15371 
15372 	if ((bf_get(lpfc_sli_intf_valid, &intf) == LPFC_SLI_INTF_VALID) &&
15373 	    (bf_get(lpfc_sli_intf_slirev, &intf) == LPFC_SLI_INTF_REV_SLI4))
15374 		rc = lpfc_pci_probe_one_s4(pdev, pid);
15375 	else
15376 		rc = lpfc_pci_probe_one_s3(pdev, pid);
15377 
15378 	return rc;
15379 }
15380 
15381 /**
15382  * lpfc_pci_remove_one - lpfc PCI func to unreg dev from PCI subsystem
15383  * @pdev: pointer to PCI device
15384  *
15385  * This routine is to be registered to the kernel's PCI subsystem. When an
15386  * Emulex HBA is removed from PCI bus, the driver core invokes this routine.
15387  * This routine dispatches the action to the proper SLI-3 or SLI-4 device
15388  * remove routine, which will perform all the necessary cleanup for the
15389  * device to be removed from the PCI subsystem properly.
15390  **/
15391 static void
15392 lpfc_pci_remove_one(struct pci_dev *pdev)
15393 {
15394 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15395 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15396 
15397 	switch (phba->pci_dev_grp) {
15398 	case LPFC_PCI_DEV_LP:
15399 		lpfc_pci_remove_one_s3(pdev);
15400 		break;
15401 	case LPFC_PCI_DEV_OC:
15402 		lpfc_pci_remove_one_s4(pdev);
15403 		break;
15404 	default:
15405 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15406 				"1424 Invalid PCI device group: 0x%x\n",
15407 				phba->pci_dev_grp);
15408 		break;
15409 	}
15410 	return;
15411 }
15412 
15413 /**
15414  * lpfc_pci_suspend_one - lpfc PCI func to suspend dev for power management
15415  * @dev: pointer to device
15416  *
15417  * This routine is to be registered to the kernel's PCI subsystem to support
15418  * system Power Management (PM). When PM invokes this method, it dispatches
15419  * the action to the proper SLI-3 or SLI-4 device suspend routine, which will
15420  * suspend the device.
15421  *
15422  * Return code
15423  * 	0 - driver suspended the device
15424  * 	Error otherwise
15425  **/
15426 static int __maybe_unused
15427 lpfc_pci_suspend_one(struct device *dev)
15428 {
15429 	struct Scsi_Host *shost = dev_get_drvdata(dev);
15430 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15431 	int rc = -ENODEV;
15432 
15433 	switch (phba->pci_dev_grp) {
15434 	case LPFC_PCI_DEV_LP:
15435 		rc = lpfc_pci_suspend_one_s3(dev);
15436 		break;
15437 	case LPFC_PCI_DEV_OC:
15438 		rc = lpfc_pci_suspend_one_s4(dev);
15439 		break;
15440 	default:
15441 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15442 				"1425 Invalid PCI device group: 0x%x\n",
15443 				phba->pci_dev_grp);
15444 		break;
15445 	}
15446 	return rc;
15447 }
15448 
15449 /**
15450  * lpfc_pci_resume_one - lpfc PCI func to resume dev for power management
15451  * @dev: pointer to device
15452  *
15453  * This routine is to be registered to the kernel's PCI subsystem to support
15454  * system Power Management (PM). When PM invokes this method, it dispatches
15455  * the action to the proper SLI-3 or SLI-4 device resume routine, which will
15456  * resume the device.
15457  *
15458  * Return code
15459  * 	0 - driver suspended the device
15460  * 	Error otherwise
15461  **/
15462 static int __maybe_unused
15463 lpfc_pci_resume_one(struct device *dev)
15464 {
15465 	struct Scsi_Host *shost = dev_get_drvdata(dev);
15466 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15467 	int rc = -ENODEV;
15468 
15469 	switch (phba->pci_dev_grp) {
15470 	case LPFC_PCI_DEV_LP:
15471 		rc = lpfc_pci_resume_one_s3(dev);
15472 		break;
15473 	case LPFC_PCI_DEV_OC:
15474 		rc = lpfc_pci_resume_one_s4(dev);
15475 		break;
15476 	default:
15477 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15478 				"1426 Invalid PCI device group: 0x%x\n",
15479 				phba->pci_dev_grp);
15480 		break;
15481 	}
15482 	return rc;
15483 }
15484 
15485 /**
15486  * lpfc_io_error_detected - lpfc method for handling PCI I/O error
15487  * @pdev: pointer to PCI device.
15488  * @state: the current PCI connection state.
15489  *
15490  * This routine is registered to the PCI subsystem for error handling. This
15491  * function is called by the PCI subsystem after a PCI bus error affecting
15492  * this device has been detected. When this routine is invoked, it dispatches
15493  * the action to the proper SLI-3 or SLI-4 device error detected handling
15494  * routine, which will perform the proper error detected operation.
15495  *
15496  * Return codes
15497  * 	PCI_ERS_RESULT_NEED_RESET - need to reset before recovery
15498  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15499  **/
15500 static pci_ers_result_t
15501 lpfc_io_error_detected(struct pci_dev *pdev, pci_channel_state_t state)
15502 {
15503 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15504 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15505 	pci_ers_result_t rc = PCI_ERS_RESULT_DISCONNECT;
15506 
15507 	if (phba->link_state == LPFC_HBA_ERROR &&
15508 	    test_bit(HBA_IOQ_FLUSH, &phba->hba_flag))
15509 		return PCI_ERS_RESULT_NEED_RESET;
15510 
15511 	switch (phba->pci_dev_grp) {
15512 	case LPFC_PCI_DEV_LP:
15513 		rc = lpfc_io_error_detected_s3(pdev, state);
15514 		break;
15515 	case LPFC_PCI_DEV_OC:
15516 		rc = lpfc_io_error_detected_s4(pdev, state);
15517 		break;
15518 	default:
15519 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15520 				"1427 Invalid PCI device group: 0x%x\n",
15521 				phba->pci_dev_grp);
15522 		break;
15523 	}
15524 	return rc;
15525 }
15526 
15527 /**
15528  * lpfc_io_slot_reset - lpfc method for restart PCI dev from scratch
15529  * @pdev: pointer to PCI device.
15530  *
15531  * This routine is registered to the PCI subsystem for error handling. This
15532  * function is called after PCI bus has been reset to restart the PCI card
15533  * from scratch, as if from a cold-boot. When this routine is invoked, it
15534  * dispatches the action to the proper SLI-3 or SLI-4 device reset handling
15535  * routine, which will perform the proper device reset.
15536  *
15537  * Return codes
15538  * 	PCI_ERS_RESULT_RECOVERED - the device has been recovered
15539  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15540  **/
15541 static pci_ers_result_t
15542 lpfc_io_slot_reset(struct pci_dev *pdev)
15543 {
15544 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15545 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15546 	pci_ers_result_t rc = PCI_ERS_RESULT_DISCONNECT;
15547 
15548 	switch (phba->pci_dev_grp) {
15549 	case LPFC_PCI_DEV_LP:
15550 		rc = lpfc_io_slot_reset_s3(pdev);
15551 		break;
15552 	case LPFC_PCI_DEV_OC:
15553 		rc = lpfc_io_slot_reset_s4(pdev);
15554 		break;
15555 	default:
15556 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15557 				"1428 Invalid PCI device group: 0x%x\n",
15558 				phba->pci_dev_grp);
15559 		break;
15560 	}
15561 	return rc;
15562 }
15563 
15564 /**
15565  * lpfc_io_resume - lpfc method for resuming PCI I/O operation
15566  * @pdev: pointer to PCI device
15567  *
15568  * This routine is registered to the PCI subsystem for error handling. It
15569  * is called when kernel error recovery tells the lpfc driver that it is
15570  * OK to resume normal PCI operation after PCI bus error recovery. When
15571  * this routine is invoked, it dispatches the action to the proper SLI-3
15572  * or SLI-4 device io_resume routine, which will resume the device operation.
15573  **/
15574 static void
15575 lpfc_io_resume(struct pci_dev *pdev)
15576 {
15577 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15578 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15579 
15580 	switch (phba->pci_dev_grp) {
15581 	case LPFC_PCI_DEV_LP:
15582 		lpfc_io_resume_s3(pdev);
15583 		break;
15584 	case LPFC_PCI_DEV_OC:
15585 		lpfc_io_resume_s4(pdev);
15586 		break;
15587 	default:
15588 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15589 				"1429 Invalid PCI device group: 0x%x\n",
15590 				phba->pci_dev_grp);
15591 		break;
15592 	}
15593 	return;
15594 }
15595 
15596 /**
15597  * lpfc_sli4_oas_verify - Verify OAS is supported by this adapter
15598  * @phba: pointer to lpfc hba data structure.
15599  *
15600  * This routine checks to see if OAS is supported for this adapter. If
15601  * supported, the configure Flash Optimized Fabric flag is set.  Otherwise,
15602  * the enable oas flag is cleared and the pool created for OAS device data
15603  * is destroyed.
15604  *
15605  **/
15606 static void
15607 lpfc_sli4_oas_verify(struct lpfc_hba *phba)
15608 {
15609 
15610 	if (!phba->cfg_EnableXLane)
15611 		return;
15612 
15613 	if (phba->sli4_hba.pc_sli4_params.oas_supported) {
15614 		phba->cfg_fof = 1;
15615 	} else {
15616 		phba->cfg_fof = 0;
15617 		mempool_destroy(phba->device_data_mem_pool);
15618 		phba->device_data_mem_pool = NULL;
15619 	}
15620 
15621 	return;
15622 }
15623 
15624 /**
15625  * lpfc_sli4_ras_init - Verify RAS-FW log is supported by this adapter
15626  * @phba: pointer to lpfc hba data structure.
15627  *
15628  * This routine checks to see if RAS is supported by the adapter. Check the
15629  * function through which RAS support enablement is to be done.
15630  **/
15631 void
15632 lpfc_sli4_ras_init(struct lpfc_hba *phba)
15633 {
15634 	/* if ASIC_GEN_NUM >= 0xC) */
15635 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
15636 		    LPFC_SLI_INTF_IF_TYPE_6) ||
15637 	    (bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf) ==
15638 		    LPFC_SLI_INTF_FAMILY_G6)) {
15639 		phba->ras_fwlog.ras_hwsupport = true;
15640 		if (phba->cfg_ras_fwlog_func == PCI_FUNC(phba->pcidev->devfn) &&
15641 		    phba->cfg_ras_fwlog_buffsize)
15642 			phba->ras_fwlog.ras_enabled = true;
15643 		else
15644 			phba->ras_fwlog.ras_enabled = false;
15645 	} else {
15646 		phba->ras_fwlog.ras_hwsupport = false;
15647 	}
15648 }
15649 
15650 
15651 MODULE_DEVICE_TABLE(pci, lpfc_id_table);
15652 
15653 static const struct pci_error_handlers lpfc_err_handler = {
15654 	.error_detected = lpfc_io_error_detected,
15655 	.slot_reset = lpfc_io_slot_reset,
15656 	.resume = lpfc_io_resume,
15657 };
15658 
15659 static SIMPLE_DEV_PM_OPS(lpfc_pci_pm_ops_one,
15660 			 lpfc_pci_suspend_one,
15661 			 lpfc_pci_resume_one);
15662 
15663 static struct pci_driver lpfc_driver = {
15664 	.name		= LPFC_DRIVER_NAME,
15665 	.id_table	= lpfc_id_table,
15666 	.probe		= lpfc_pci_probe_one,
15667 	.remove		= lpfc_pci_remove_one,
15668 	.shutdown	= lpfc_pci_remove_one,
15669 	.driver.pm	= &lpfc_pci_pm_ops_one,
15670 	.err_handler    = &lpfc_err_handler,
15671 };
15672 
15673 static const struct file_operations lpfc_mgmt_fop = {
15674 	.owner = THIS_MODULE,
15675 };
15676 
15677 static struct miscdevice lpfc_mgmt_dev = {
15678 	.minor = MISC_DYNAMIC_MINOR,
15679 	.name = "lpfcmgmt",
15680 	.fops = &lpfc_mgmt_fop,
15681 };
15682 
15683 /**
15684  * lpfc_init - lpfc module initialization routine
15685  *
15686  * This routine is to be invoked when the lpfc module is loaded into the
15687  * kernel. The special kernel macro module_init() is used to indicate the
15688  * role of this routine to the kernel as lpfc module entry point.
15689  *
15690  * Return codes
15691  *   0 - successful
15692  *   -ENOMEM - FC attach transport failed
15693  *   all others - failed
15694  */
15695 static int __init
15696 lpfc_init(void)
15697 {
15698 	int error = 0;
15699 
15700 	pr_info(LPFC_MODULE_DESC "\n");
15701 	pr_info(LPFC_COPYRIGHT "\n");
15702 
15703 	error = misc_register(&lpfc_mgmt_dev);
15704 	if (error)
15705 		printk(KERN_ERR "Could not register lpfcmgmt device, "
15706 			"misc_register returned with status %d", error);
15707 
15708 	error = -ENOMEM;
15709 	lpfc_transport_functions.vport_create = lpfc_vport_create;
15710 	lpfc_transport_functions.vport_delete = lpfc_vport_delete;
15711 	lpfc_transport_template =
15712 				fc_attach_transport(&lpfc_transport_functions);
15713 	if (lpfc_transport_template == NULL)
15714 		goto unregister;
15715 	lpfc_vport_transport_template =
15716 		fc_attach_transport(&lpfc_vport_transport_functions);
15717 	if (lpfc_vport_transport_template == NULL) {
15718 		fc_release_transport(lpfc_transport_template);
15719 		goto unregister;
15720 	}
15721 	lpfc_wqe_cmd_template();
15722 	lpfc_nvmet_cmd_template();
15723 
15724 	/* Initialize in case vector mapping is needed */
15725 	lpfc_present_cpu = num_present_cpus();
15726 
15727 	lpfc_pldv_detect = false;
15728 
15729 	error = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN,
15730 					"lpfc/sli4:online",
15731 					lpfc_cpu_online, lpfc_cpu_offline);
15732 	if (error < 0)
15733 		goto cpuhp_failure;
15734 	lpfc_cpuhp_state = error;
15735 
15736 	error = pci_register_driver(&lpfc_driver);
15737 	if (error)
15738 		goto unwind;
15739 
15740 	return error;
15741 
15742 unwind:
15743 	cpuhp_remove_multi_state(lpfc_cpuhp_state);
15744 cpuhp_failure:
15745 	fc_release_transport(lpfc_transport_template);
15746 	fc_release_transport(lpfc_vport_transport_template);
15747 unregister:
15748 	misc_deregister(&lpfc_mgmt_dev);
15749 
15750 	return error;
15751 }
15752 
15753 void lpfc_dmp_dbg(struct lpfc_hba *phba)
15754 {
15755 	unsigned int start_idx;
15756 	unsigned int dbg_cnt;
15757 	unsigned int temp_idx;
15758 	int i;
15759 	int j = 0;
15760 	unsigned long rem_nsec;
15761 
15762 	if (atomic_cmpxchg(&phba->dbg_log_dmping, 0, 1) != 0)
15763 		return;
15764 
15765 	start_idx = (unsigned int)atomic_read(&phba->dbg_log_idx) % DBG_LOG_SZ;
15766 	dbg_cnt = (unsigned int)atomic_read(&phba->dbg_log_cnt);
15767 	if (!dbg_cnt)
15768 		goto out;
15769 	temp_idx = start_idx;
15770 	if (dbg_cnt >= DBG_LOG_SZ) {
15771 		dbg_cnt = DBG_LOG_SZ;
15772 		temp_idx -= 1;
15773 	} else {
15774 		if ((start_idx + dbg_cnt) > (DBG_LOG_SZ - 1)) {
15775 			temp_idx = (start_idx + dbg_cnt) % DBG_LOG_SZ;
15776 		} else {
15777 			if (start_idx < dbg_cnt)
15778 				start_idx = DBG_LOG_SZ - (dbg_cnt - start_idx);
15779 			else
15780 				start_idx -= dbg_cnt;
15781 		}
15782 	}
15783 	dev_info(&phba->pcidev->dev, "start %d end %d cnt %d\n",
15784 		 start_idx, temp_idx, dbg_cnt);
15785 
15786 	for (i = 0; i < dbg_cnt; i++) {
15787 		if ((start_idx + i) < DBG_LOG_SZ)
15788 			temp_idx = (start_idx + i) % DBG_LOG_SZ;
15789 		else
15790 			temp_idx = j++;
15791 		rem_nsec = do_div(phba->dbg_log[temp_idx].t_ns, NSEC_PER_SEC);
15792 		dev_info(&phba->pcidev->dev, "%d: [%5lu.%06lu] %s",
15793 			 temp_idx,
15794 			 (unsigned long)phba->dbg_log[temp_idx].t_ns,
15795 			 rem_nsec / 1000,
15796 			 phba->dbg_log[temp_idx].log);
15797 	}
15798 out:
15799 	atomic_set(&phba->dbg_log_cnt, 0);
15800 	atomic_set(&phba->dbg_log_dmping, 0);
15801 }
15802 
15803 __printf(2, 3)
15804 void lpfc_dbg_print(struct lpfc_hba *phba, const char *fmt, ...)
15805 {
15806 	unsigned int idx;
15807 	va_list args;
15808 	int dbg_dmping = atomic_read(&phba->dbg_log_dmping);
15809 	struct va_format vaf;
15810 
15811 
15812 	va_start(args, fmt);
15813 	if (unlikely(dbg_dmping)) {
15814 		vaf.fmt = fmt;
15815 		vaf.va = &args;
15816 		dev_info(&phba->pcidev->dev, "%pV", &vaf);
15817 		va_end(args);
15818 		return;
15819 	}
15820 	idx = (unsigned int)atomic_fetch_add(1, &phba->dbg_log_idx) %
15821 		DBG_LOG_SZ;
15822 
15823 	atomic_inc(&phba->dbg_log_cnt);
15824 
15825 	vscnprintf(phba->dbg_log[idx].log,
15826 		   sizeof(phba->dbg_log[idx].log), fmt, args);
15827 	va_end(args);
15828 
15829 	phba->dbg_log[idx].t_ns = local_clock();
15830 }
15831 
15832 /**
15833  * lpfc_exit - lpfc module removal routine
15834  *
15835  * This routine is invoked when the lpfc module is removed from the kernel.
15836  * The special kernel macro module_exit() is used to indicate the role of
15837  * this routine to the kernel as lpfc module exit point.
15838  */
15839 static void __exit
15840 lpfc_exit(void)
15841 {
15842 	misc_deregister(&lpfc_mgmt_dev);
15843 	pci_unregister_driver(&lpfc_driver);
15844 	cpuhp_remove_multi_state(lpfc_cpuhp_state);
15845 	fc_release_transport(lpfc_transport_template);
15846 	fc_release_transport(lpfc_vport_transport_template);
15847 	idr_destroy(&lpfc_hba_index);
15848 }
15849 
15850 module_init(lpfc_init);
15851 module_exit(lpfc_exit);
15852 MODULE_LICENSE("GPL");
15853 MODULE_DESCRIPTION(LPFC_MODULE_DESC);
15854 MODULE_AUTHOR("Broadcom");
15855 MODULE_VERSION("0:" LPFC_DRIVER_VERSION);
15856