xref: /openbmc/linux/drivers/scsi/lpfc/lpfc_init.c (revision dff03381)
1 /*******************************************************************
2  * This file is part of the Emulex Linux Device Driver for         *
3  * Fibre Channel Host Bus Adapters.                                *
4  * Copyright (C) 2017-2022 Broadcom. All Rights Reserved. The term *
5  * “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.  *
6  * Copyright (C) 2004-2016 Emulex.  All rights reserved.           *
7  * EMULEX and SLI are trademarks of Emulex.                        *
8  * www.broadcom.com                                                *
9  * Portions Copyright (C) 2004-2005 Christoph Hellwig              *
10  *                                                                 *
11  * This program is free software; you can redistribute it and/or   *
12  * modify it under the terms of version 2 of the GNU General       *
13  * Public License as published by the Free Software Foundation.    *
14  * This program is distributed in the hope that it will be useful. *
15  * ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND          *
16  * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,  *
17  * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE      *
18  * DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD *
19  * TO BE LEGALLY INVALID.  See the GNU General Public License for  *
20  * more details, a copy of which can be found in the file COPYING  *
21  * included with this package.                                     *
22  *******************************************************************/
23 
24 #include <linux/blkdev.h>
25 #include <linux/delay.h>
26 #include <linux/dma-mapping.h>
27 #include <linux/idr.h>
28 #include <linux/interrupt.h>
29 #include <linux/module.h>
30 #include <linux/kthread.h>
31 #include <linux/pci.h>
32 #include <linux/spinlock.h>
33 #include <linux/ctype.h>
34 #include <linux/aer.h>
35 #include <linux/slab.h>
36 #include <linux/firmware.h>
37 #include <linux/miscdevice.h>
38 #include <linux/percpu.h>
39 #include <linux/msi.h>
40 #include <linux/irq.h>
41 #include <linux/bitops.h>
42 #include <linux/crash_dump.h>
43 #include <linux/cpu.h>
44 #include <linux/cpuhotplug.h>
45 
46 #include <scsi/scsi.h>
47 #include <scsi/scsi_device.h>
48 #include <scsi/scsi_host.h>
49 #include <scsi/scsi_transport_fc.h>
50 #include <scsi/scsi_tcq.h>
51 #include <scsi/fc/fc_fs.h>
52 
53 #include "lpfc_hw4.h"
54 #include "lpfc_hw.h"
55 #include "lpfc_sli.h"
56 #include "lpfc_sli4.h"
57 #include "lpfc_nl.h"
58 #include "lpfc_disc.h"
59 #include "lpfc.h"
60 #include "lpfc_scsi.h"
61 #include "lpfc_nvme.h"
62 #include "lpfc_logmsg.h"
63 #include "lpfc_crtn.h"
64 #include "lpfc_vport.h"
65 #include "lpfc_version.h"
66 #include "lpfc_ids.h"
67 
68 static enum cpuhp_state lpfc_cpuhp_state;
69 /* Used when mapping IRQ vectors in a driver centric manner */
70 static uint32_t lpfc_present_cpu;
71 static bool lpfc_pldv_detect;
72 
73 static void __lpfc_cpuhp_remove(struct lpfc_hba *phba);
74 static void lpfc_cpuhp_remove(struct lpfc_hba *phba);
75 static void lpfc_cpuhp_add(struct lpfc_hba *phba);
76 static void lpfc_get_hba_model_desc(struct lpfc_hba *, uint8_t *, uint8_t *);
77 static int lpfc_post_rcv_buf(struct lpfc_hba *);
78 static int lpfc_sli4_queue_verify(struct lpfc_hba *);
79 static int lpfc_create_bootstrap_mbox(struct lpfc_hba *);
80 static int lpfc_setup_endian_order(struct lpfc_hba *);
81 static void lpfc_destroy_bootstrap_mbox(struct lpfc_hba *);
82 static void lpfc_free_els_sgl_list(struct lpfc_hba *);
83 static void lpfc_free_nvmet_sgl_list(struct lpfc_hba *);
84 static void lpfc_init_sgl_list(struct lpfc_hba *);
85 static int lpfc_init_active_sgl_array(struct lpfc_hba *);
86 static void lpfc_free_active_sgl(struct lpfc_hba *);
87 static int lpfc_hba_down_post_s3(struct lpfc_hba *phba);
88 static int lpfc_hba_down_post_s4(struct lpfc_hba *phba);
89 static int lpfc_sli4_cq_event_pool_create(struct lpfc_hba *);
90 static void lpfc_sli4_cq_event_pool_destroy(struct lpfc_hba *);
91 static void lpfc_sli4_cq_event_release_all(struct lpfc_hba *);
92 static void lpfc_sli4_disable_intr(struct lpfc_hba *);
93 static uint32_t lpfc_sli4_enable_intr(struct lpfc_hba *, uint32_t);
94 static void lpfc_sli4_oas_verify(struct lpfc_hba *phba);
95 static uint16_t lpfc_find_cpu_handle(struct lpfc_hba *, uint16_t, int);
96 static void lpfc_setup_bg(struct lpfc_hba *, struct Scsi_Host *);
97 static int lpfc_sli4_cgn_parm_chg_evt(struct lpfc_hba *);
98 static void lpfc_sli4_prep_dev_for_reset(struct lpfc_hba *phba);
99 
100 static struct scsi_transport_template *lpfc_transport_template = NULL;
101 static struct scsi_transport_template *lpfc_vport_transport_template = NULL;
102 static DEFINE_IDR(lpfc_hba_index);
103 #define LPFC_NVMET_BUF_POST 254
104 static int lpfc_vmid_res_alloc(struct lpfc_hba *phba, struct lpfc_vport *vport);
105 
106 /**
107  * lpfc_config_port_prep - Perform lpfc initialization prior to config port
108  * @phba: pointer to lpfc hba data structure.
109  *
110  * This routine will do LPFC initialization prior to issuing the CONFIG_PORT
111  * mailbox command. It retrieves the revision information from the HBA and
112  * collects the Vital Product Data (VPD) about the HBA for preparing the
113  * configuration of the HBA.
114  *
115  * Return codes:
116  *   0 - success.
117  *   -ERESTART - requests the SLI layer to reset the HBA and try again.
118  *   Any other value - indicates an error.
119  **/
120 int
121 lpfc_config_port_prep(struct lpfc_hba *phba)
122 {
123 	lpfc_vpd_t *vp = &phba->vpd;
124 	int i = 0, rc;
125 	LPFC_MBOXQ_t *pmb;
126 	MAILBOX_t *mb;
127 	char *lpfc_vpd_data = NULL;
128 	uint16_t offset = 0;
129 	static char licensed[56] =
130 		    "key unlock for use with gnu public licensed code only\0";
131 	static int init_key = 1;
132 
133 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
134 	if (!pmb) {
135 		phba->link_state = LPFC_HBA_ERROR;
136 		return -ENOMEM;
137 	}
138 
139 	mb = &pmb->u.mb;
140 	phba->link_state = LPFC_INIT_MBX_CMDS;
141 
142 	if (lpfc_is_LC_HBA(phba->pcidev->device)) {
143 		if (init_key) {
144 			uint32_t *ptext = (uint32_t *) licensed;
145 
146 			for (i = 0; i < 56; i += sizeof (uint32_t), ptext++)
147 				*ptext = cpu_to_be32(*ptext);
148 			init_key = 0;
149 		}
150 
151 		lpfc_read_nv(phba, pmb);
152 		memset((char*)mb->un.varRDnvp.rsvd3, 0,
153 			sizeof (mb->un.varRDnvp.rsvd3));
154 		memcpy((char*)mb->un.varRDnvp.rsvd3, licensed,
155 			 sizeof (licensed));
156 
157 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
158 
159 		if (rc != MBX_SUCCESS) {
160 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
161 					"0324 Config Port initialization "
162 					"error, mbxCmd x%x READ_NVPARM, "
163 					"mbxStatus x%x\n",
164 					mb->mbxCommand, mb->mbxStatus);
165 			mempool_free(pmb, phba->mbox_mem_pool);
166 			return -ERESTART;
167 		}
168 		memcpy(phba->wwnn, (char *)mb->un.varRDnvp.nodename,
169 		       sizeof(phba->wwnn));
170 		memcpy(phba->wwpn, (char *)mb->un.varRDnvp.portname,
171 		       sizeof(phba->wwpn));
172 	}
173 
174 	/*
175 	 * Clear all option bits except LPFC_SLI3_BG_ENABLED,
176 	 * which was already set in lpfc_get_cfgparam()
177 	 */
178 	phba->sli3_options &= (uint32_t)LPFC_SLI3_BG_ENABLED;
179 
180 	/* Setup and issue mailbox READ REV command */
181 	lpfc_read_rev(phba, pmb);
182 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
183 	if (rc != MBX_SUCCESS) {
184 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
185 				"0439 Adapter failed to init, mbxCmd x%x "
186 				"READ_REV, mbxStatus x%x\n",
187 				mb->mbxCommand, mb->mbxStatus);
188 		mempool_free( pmb, phba->mbox_mem_pool);
189 		return -ERESTART;
190 	}
191 
192 
193 	/*
194 	 * The value of rr must be 1 since the driver set the cv field to 1.
195 	 * This setting requires the FW to set all revision fields.
196 	 */
197 	if (mb->un.varRdRev.rr == 0) {
198 		vp->rev.rBit = 0;
199 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
200 				"0440 Adapter failed to init, READ_REV has "
201 				"missing revision information.\n");
202 		mempool_free(pmb, phba->mbox_mem_pool);
203 		return -ERESTART;
204 	}
205 
206 	if (phba->sli_rev == 3 && !mb->un.varRdRev.v3rsp) {
207 		mempool_free(pmb, phba->mbox_mem_pool);
208 		return -EINVAL;
209 	}
210 
211 	/* Save information as VPD data */
212 	vp->rev.rBit = 1;
213 	memcpy(&vp->sli3Feat, &mb->un.varRdRev.sli3Feat, sizeof(uint32_t));
214 	vp->rev.sli1FwRev = mb->un.varRdRev.sli1FwRev;
215 	memcpy(vp->rev.sli1FwName, (char*) mb->un.varRdRev.sli1FwName, 16);
216 	vp->rev.sli2FwRev = mb->un.varRdRev.sli2FwRev;
217 	memcpy(vp->rev.sli2FwName, (char *) mb->un.varRdRev.sli2FwName, 16);
218 	vp->rev.biuRev = mb->un.varRdRev.biuRev;
219 	vp->rev.smRev = mb->un.varRdRev.smRev;
220 	vp->rev.smFwRev = mb->un.varRdRev.un.smFwRev;
221 	vp->rev.endecRev = mb->un.varRdRev.endecRev;
222 	vp->rev.fcphHigh = mb->un.varRdRev.fcphHigh;
223 	vp->rev.fcphLow = mb->un.varRdRev.fcphLow;
224 	vp->rev.feaLevelHigh = mb->un.varRdRev.feaLevelHigh;
225 	vp->rev.feaLevelLow = mb->un.varRdRev.feaLevelLow;
226 	vp->rev.postKernRev = mb->un.varRdRev.postKernRev;
227 	vp->rev.opFwRev = mb->un.varRdRev.opFwRev;
228 
229 	/* If the sli feature level is less then 9, we must
230 	 * tear down all RPIs and VPIs on link down if NPIV
231 	 * is enabled.
232 	 */
233 	if (vp->rev.feaLevelHigh < 9)
234 		phba->sli3_options |= LPFC_SLI3_VPORT_TEARDOWN;
235 
236 	if (lpfc_is_LC_HBA(phba->pcidev->device))
237 		memcpy(phba->RandomData, (char *)&mb->un.varWords[24],
238 						sizeof (phba->RandomData));
239 
240 	/* Get adapter VPD information */
241 	lpfc_vpd_data = kmalloc(DMP_VPD_SIZE, GFP_KERNEL);
242 	if (!lpfc_vpd_data)
243 		goto out_free_mbox;
244 	do {
245 		lpfc_dump_mem(phba, pmb, offset, DMP_REGION_VPD);
246 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
247 
248 		if (rc != MBX_SUCCESS) {
249 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
250 					"0441 VPD not present on adapter, "
251 					"mbxCmd x%x DUMP VPD, mbxStatus x%x\n",
252 					mb->mbxCommand, mb->mbxStatus);
253 			mb->un.varDmp.word_cnt = 0;
254 		}
255 		/* dump mem may return a zero when finished or we got a
256 		 * mailbox error, either way we are done.
257 		 */
258 		if (mb->un.varDmp.word_cnt == 0)
259 			break;
260 
261 		if (mb->un.varDmp.word_cnt > DMP_VPD_SIZE - offset)
262 			mb->un.varDmp.word_cnt = DMP_VPD_SIZE - offset;
263 		lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
264 				      lpfc_vpd_data + offset,
265 				      mb->un.varDmp.word_cnt);
266 		offset += mb->un.varDmp.word_cnt;
267 	} while (mb->un.varDmp.word_cnt && offset < DMP_VPD_SIZE);
268 
269 	lpfc_parse_vpd(phba, lpfc_vpd_data, offset);
270 
271 	kfree(lpfc_vpd_data);
272 out_free_mbox:
273 	mempool_free(pmb, phba->mbox_mem_pool);
274 	return 0;
275 }
276 
277 /**
278  * lpfc_config_async_cmpl - Completion handler for config async event mbox cmd
279  * @phba: pointer to lpfc hba data structure.
280  * @pmboxq: pointer to the driver internal queue element for mailbox command.
281  *
282  * This is the completion handler for driver's configuring asynchronous event
283  * mailbox command to the device. If the mailbox command returns successfully,
284  * it will set internal async event support flag to 1; otherwise, it will
285  * set internal async event support flag to 0.
286  **/
287 static void
288 lpfc_config_async_cmpl(struct lpfc_hba * phba, LPFC_MBOXQ_t * pmboxq)
289 {
290 	if (pmboxq->u.mb.mbxStatus == MBX_SUCCESS)
291 		phba->temp_sensor_support = 1;
292 	else
293 		phba->temp_sensor_support = 0;
294 	mempool_free(pmboxq, phba->mbox_mem_pool);
295 	return;
296 }
297 
298 /**
299  * lpfc_dump_wakeup_param_cmpl - dump memory mailbox command completion handler
300  * @phba: pointer to lpfc hba data structure.
301  * @pmboxq: pointer to the driver internal queue element for mailbox command.
302  *
303  * This is the completion handler for dump mailbox command for getting
304  * wake up parameters. When this command complete, the response contain
305  * Option rom version of the HBA. This function translate the version number
306  * into a human readable string and store it in OptionROMVersion.
307  **/
308 static void
309 lpfc_dump_wakeup_param_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
310 {
311 	struct prog_id *prg;
312 	uint32_t prog_id_word;
313 	char dist = ' ';
314 	/* character array used for decoding dist type. */
315 	char dist_char[] = "nabx";
316 
317 	if (pmboxq->u.mb.mbxStatus != MBX_SUCCESS) {
318 		mempool_free(pmboxq, phba->mbox_mem_pool);
319 		return;
320 	}
321 
322 	prg = (struct prog_id *) &prog_id_word;
323 
324 	/* word 7 contain option rom version */
325 	prog_id_word = pmboxq->u.mb.un.varWords[7];
326 
327 	/* Decode the Option rom version word to a readable string */
328 	if (prg->dist < 4)
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 = (struct lpfc_dmabuf *)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 	phba->hba_flag &= ~HBA_ERATT_HANDLED;
571 
572 	/* Enable appropriate host interrupts */
573 	if (lpfc_readl(phba->HCregaddr, &status)) {
574 		spin_unlock_irq(&phba->hbalock);
575 		return -EIO;
576 	}
577 	status |= HC_MBINT_ENA | HC_ERINT_ENA | HC_LAINT_ENA;
578 	if (psli->num_rings > 0)
579 		status |= HC_R0INT_ENA;
580 	if (psli->num_rings > 1)
581 		status |= HC_R1INT_ENA;
582 	if (psli->num_rings > 2)
583 		status |= HC_R2INT_ENA;
584 	if (psli->num_rings > 3)
585 		status |= HC_R3INT_ENA;
586 
587 	if ((phba->cfg_poll & ENABLE_FCP_RING_POLLING) &&
588 	    (phba->cfg_poll & DISABLE_FCP_RING_INT))
589 		status &= ~(HC_R0INT_ENA);
590 
591 	writel(status, phba->HCregaddr);
592 	readl(phba->HCregaddr); /* flush */
593 	spin_unlock_irq(&phba->hbalock);
594 
595 	/* Set up ring-0 (ELS) timer */
596 	timeout = phba->fc_ratov * 2;
597 	mod_timer(&vport->els_tmofunc,
598 		  jiffies + msecs_to_jiffies(1000 * timeout));
599 	/* Set up heart beat (HB) timer */
600 	mod_timer(&phba->hb_tmofunc,
601 		  jiffies + msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
602 	phba->hba_flag &= ~(HBA_HBEAT_INP | HBA_HBEAT_TMO);
603 	phba->last_completion_time = jiffies;
604 	/* Set up error attention (ERATT) polling timer */
605 	mod_timer(&phba->eratt_poll,
606 		  jiffies + msecs_to_jiffies(1000 * phba->eratt_poll_interval));
607 
608 	if (phba->hba_flag & LINK_DISABLED) {
609 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
610 				"2598 Adapter Link is disabled.\n");
611 		lpfc_down_link(phba, pmb);
612 		pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
613 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
614 		if ((rc != MBX_SUCCESS) && (rc != MBX_BUSY)) {
615 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
616 					"2599 Adapter failed to issue DOWN_LINK"
617 					" mbox command rc 0x%x\n", rc);
618 
619 			mempool_free(pmb, phba->mbox_mem_pool);
620 			return -EIO;
621 		}
622 	} else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
623 		mempool_free(pmb, phba->mbox_mem_pool);
624 		rc = phba->lpfc_hba_init_link(phba, MBX_NOWAIT);
625 		if (rc)
626 			return rc;
627 	}
628 	/* MBOX buffer will be freed in mbox compl */
629 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
630 	if (!pmb) {
631 		phba->link_state = LPFC_HBA_ERROR;
632 		return -ENOMEM;
633 	}
634 
635 	lpfc_config_async(phba, pmb, LPFC_ELS_RING);
636 	pmb->mbox_cmpl = lpfc_config_async_cmpl;
637 	pmb->vport = phba->pport;
638 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
639 
640 	if ((rc != MBX_BUSY) && (rc != MBX_SUCCESS)) {
641 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
642 				"0456 Adapter failed to issue "
643 				"ASYNCEVT_ENABLE mbox status x%x\n",
644 				rc);
645 		mempool_free(pmb, phba->mbox_mem_pool);
646 	}
647 
648 	/* Get Option rom version */
649 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
650 	if (!pmb) {
651 		phba->link_state = LPFC_HBA_ERROR;
652 		return -ENOMEM;
653 	}
654 
655 	lpfc_dump_wakeup_param(phba, pmb);
656 	pmb->mbox_cmpl = lpfc_dump_wakeup_param_cmpl;
657 	pmb->vport = phba->pport;
658 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
659 
660 	if ((rc != MBX_BUSY) && (rc != MBX_SUCCESS)) {
661 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
662 				"0435 Adapter failed "
663 				"to get Option ROM version status x%x\n", rc);
664 		mempool_free(pmb, phba->mbox_mem_pool);
665 	}
666 
667 	return 0;
668 }
669 
670 /**
671  * lpfc_sli4_refresh_params - update driver copy of params.
672  * @phba: Pointer to HBA context object.
673  *
674  * This is called to refresh driver copy of dynamic fields from the
675  * common_get_sli4_parameters descriptor.
676  **/
677 int
678 lpfc_sli4_refresh_params(struct lpfc_hba *phba)
679 {
680 	LPFC_MBOXQ_t *mboxq;
681 	struct lpfc_mqe *mqe;
682 	struct lpfc_sli4_parameters *mbx_sli4_parameters;
683 	int length, rc;
684 
685 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
686 	if (!mboxq)
687 		return -ENOMEM;
688 
689 	mqe = &mboxq->u.mqe;
690 	/* Read the port's SLI4 Config Parameters */
691 	length = (sizeof(struct lpfc_mbx_get_sli4_parameters) -
692 		  sizeof(struct lpfc_sli4_cfg_mhdr));
693 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
694 			 LPFC_MBOX_OPCODE_GET_SLI4_PARAMETERS,
695 			 length, LPFC_SLI4_MBX_EMBED);
696 
697 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
698 	if (unlikely(rc)) {
699 		mempool_free(mboxq, phba->mbox_mem_pool);
700 		return rc;
701 	}
702 	mbx_sli4_parameters = &mqe->un.get_sli4_parameters.sli4_parameters;
703 
704 	/* Are we forcing MI off via module parameter? */
705 	if (phba->cfg_enable_mi)
706 		phba->sli4_hba.pc_sli4_params.mi_ver =
707 			bf_get(cfg_mi_ver, mbx_sli4_parameters);
708 	else
709 		phba->sli4_hba.pc_sli4_params.mi_ver = 0;
710 
711 	phba->sli4_hba.pc_sli4_params.cmf =
712 			bf_get(cfg_cmf, mbx_sli4_parameters);
713 	phba->sli4_hba.pc_sli4_params.pls =
714 			bf_get(cfg_pvl, mbx_sli4_parameters);
715 
716 	mempool_free(mboxq, phba->mbox_mem_pool);
717 	return rc;
718 }
719 
720 /**
721  * lpfc_hba_init_link - Initialize the FC link
722  * @phba: pointer to lpfc hba data structure.
723  * @flag: mailbox command issue mode - either MBX_POLL or MBX_NOWAIT
724  *
725  * This routine will issue the INIT_LINK mailbox command call.
726  * It is available to other drivers through the lpfc_hba data
727  * structure for use as a delayed link up mechanism with the
728  * module parameter lpfc_suppress_link_up.
729  *
730  * Return code
731  *		0 - success
732  *		Any other value - error
733  **/
734 static int
735 lpfc_hba_init_link(struct lpfc_hba *phba, uint32_t flag)
736 {
737 	return lpfc_hba_init_link_fc_topology(phba, phba->cfg_topology, flag);
738 }
739 
740 /**
741  * lpfc_hba_init_link_fc_topology - Initialize FC link with desired topology
742  * @phba: pointer to lpfc hba data structure.
743  * @fc_topology: desired fc topology.
744  * @flag: mailbox command issue mode - either MBX_POLL or MBX_NOWAIT
745  *
746  * This routine will issue the INIT_LINK mailbox command call.
747  * It is available to other drivers through the lpfc_hba data
748  * structure for use as a delayed link up mechanism with the
749  * module parameter lpfc_suppress_link_up.
750  *
751  * Return code
752  *              0 - success
753  *              Any other value - error
754  **/
755 int
756 lpfc_hba_init_link_fc_topology(struct lpfc_hba *phba, uint32_t fc_topology,
757 			       uint32_t flag)
758 {
759 	struct lpfc_vport *vport = phba->pport;
760 	LPFC_MBOXQ_t *pmb;
761 	MAILBOX_t *mb;
762 	int rc;
763 
764 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
765 	if (!pmb) {
766 		phba->link_state = LPFC_HBA_ERROR;
767 		return -ENOMEM;
768 	}
769 	mb = &pmb->u.mb;
770 	pmb->vport = vport;
771 
772 	if ((phba->cfg_link_speed > LPFC_USER_LINK_SPEED_MAX) ||
773 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_1G) &&
774 	     !(phba->lmt & LMT_1Gb)) ||
775 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_2G) &&
776 	     !(phba->lmt & LMT_2Gb)) ||
777 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_4G) &&
778 	     !(phba->lmt & LMT_4Gb)) ||
779 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_8G) &&
780 	     !(phba->lmt & LMT_8Gb)) ||
781 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_10G) &&
782 	     !(phba->lmt & LMT_10Gb)) ||
783 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_16G) &&
784 	     !(phba->lmt & LMT_16Gb)) ||
785 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_32G) &&
786 	     !(phba->lmt & LMT_32Gb)) ||
787 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_64G) &&
788 	     !(phba->lmt & LMT_64Gb))) {
789 		/* Reset link speed to auto */
790 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
791 				"1302 Invalid speed for this board:%d "
792 				"Reset link speed to auto.\n",
793 				phba->cfg_link_speed);
794 			phba->cfg_link_speed = LPFC_USER_LINK_SPEED_AUTO;
795 	}
796 	lpfc_init_link(phba, pmb, fc_topology, phba->cfg_link_speed);
797 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
798 	if (phba->sli_rev < LPFC_SLI_REV4)
799 		lpfc_set_loopback_flag(phba);
800 	rc = lpfc_sli_issue_mbox(phba, pmb, flag);
801 	if ((rc != MBX_BUSY) && (rc != MBX_SUCCESS)) {
802 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
803 				"0498 Adapter failed to init, mbxCmd x%x "
804 				"INIT_LINK, mbxStatus x%x\n",
805 				mb->mbxCommand, mb->mbxStatus);
806 		if (phba->sli_rev <= LPFC_SLI_REV3) {
807 			/* Clear all interrupt enable conditions */
808 			writel(0, phba->HCregaddr);
809 			readl(phba->HCregaddr); /* flush */
810 			/* Clear all pending interrupts */
811 			writel(0xffffffff, phba->HAregaddr);
812 			readl(phba->HAregaddr); /* flush */
813 		}
814 		phba->link_state = LPFC_HBA_ERROR;
815 		if (rc != MBX_BUSY || flag == MBX_POLL)
816 			mempool_free(pmb, phba->mbox_mem_pool);
817 		return -EIO;
818 	}
819 	phba->cfg_suppress_link_up = LPFC_INITIALIZE_LINK;
820 	if (flag == MBX_POLL)
821 		mempool_free(pmb, phba->mbox_mem_pool);
822 
823 	return 0;
824 }
825 
826 /**
827  * lpfc_hba_down_link - this routine downs the FC link
828  * @phba: pointer to lpfc hba data structure.
829  * @flag: mailbox command issue mode - either MBX_POLL or MBX_NOWAIT
830  *
831  * This routine will issue the DOWN_LINK mailbox command call.
832  * It is available to other drivers through the lpfc_hba data
833  * structure for use to stop the link.
834  *
835  * Return code
836  *		0 - success
837  *		Any other value - error
838  **/
839 static int
840 lpfc_hba_down_link(struct lpfc_hba *phba, uint32_t flag)
841 {
842 	LPFC_MBOXQ_t *pmb;
843 	int rc;
844 
845 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
846 	if (!pmb) {
847 		phba->link_state = LPFC_HBA_ERROR;
848 		return -ENOMEM;
849 	}
850 
851 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
852 			"0491 Adapter Link is disabled.\n");
853 	lpfc_down_link(phba, pmb);
854 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
855 	rc = lpfc_sli_issue_mbox(phba, pmb, flag);
856 	if ((rc != MBX_SUCCESS) && (rc != MBX_BUSY)) {
857 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
858 				"2522 Adapter failed to issue DOWN_LINK"
859 				" mbox command rc 0x%x\n", rc);
860 
861 		mempool_free(pmb, phba->mbox_mem_pool);
862 		return -EIO;
863 	}
864 	if (flag == MBX_POLL)
865 		mempool_free(pmb, phba->mbox_mem_pool);
866 
867 	return 0;
868 }
869 
870 /**
871  * lpfc_hba_down_prep - Perform lpfc uninitialization prior to HBA reset
872  * @phba: pointer to lpfc HBA data structure.
873  *
874  * This routine will do LPFC uninitialization before the HBA is reset when
875  * bringing down the SLI Layer.
876  *
877  * Return codes
878  *   0 - success.
879  *   Any other value - error.
880  **/
881 int
882 lpfc_hba_down_prep(struct lpfc_hba *phba)
883 {
884 	struct lpfc_vport **vports;
885 	int i;
886 
887 	if (phba->sli_rev <= LPFC_SLI_REV3) {
888 		/* Disable interrupts */
889 		writel(0, phba->HCregaddr);
890 		readl(phba->HCregaddr); /* flush */
891 	}
892 
893 	if (phba->pport->load_flag & FC_UNLOADING)
894 		lpfc_cleanup_discovery_resources(phba->pport);
895 	else {
896 		vports = lpfc_create_vport_work_array(phba);
897 		if (vports != NULL)
898 			for (i = 0; i <= phba->max_vports &&
899 				vports[i] != NULL; i++)
900 				lpfc_cleanup_discovery_resources(vports[i]);
901 		lpfc_destroy_vport_work_array(phba, vports);
902 	}
903 	return 0;
904 }
905 
906 /**
907  * lpfc_sli4_free_sp_events - Cleanup sp_queue_events to free
908  * rspiocb which got deferred
909  *
910  * @phba: pointer to lpfc HBA data structure.
911  *
912  * This routine will cleanup completed slow path events after HBA is reset
913  * when bringing down the SLI Layer.
914  *
915  *
916  * Return codes
917  *   void.
918  **/
919 static void
920 lpfc_sli4_free_sp_events(struct lpfc_hba *phba)
921 {
922 	struct lpfc_iocbq *rspiocbq;
923 	struct hbq_dmabuf *dmabuf;
924 	struct lpfc_cq_event *cq_event;
925 
926 	spin_lock_irq(&phba->hbalock);
927 	phba->hba_flag &= ~HBA_SP_QUEUE_EVT;
928 	spin_unlock_irq(&phba->hbalock);
929 
930 	while (!list_empty(&phba->sli4_hba.sp_queue_event)) {
931 		/* Get the response iocb from the head of work queue */
932 		spin_lock_irq(&phba->hbalock);
933 		list_remove_head(&phba->sli4_hba.sp_queue_event,
934 				 cq_event, struct lpfc_cq_event, list);
935 		spin_unlock_irq(&phba->hbalock);
936 
937 		switch (bf_get(lpfc_wcqe_c_code, &cq_event->cqe.wcqe_cmpl)) {
938 		case CQE_CODE_COMPL_WQE:
939 			rspiocbq = container_of(cq_event, struct lpfc_iocbq,
940 						 cq_event);
941 			lpfc_sli_release_iocbq(phba, rspiocbq);
942 			break;
943 		case CQE_CODE_RECEIVE:
944 		case CQE_CODE_RECEIVE_V1:
945 			dmabuf = container_of(cq_event, struct hbq_dmabuf,
946 					      cq_event);
947 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
948 		}
949 	}
950 }
951 
952 /**
953  * lpfc_hba_free_post_buf - Perform lpfc uninitialization after HBA reset
954  * @phba: pointer to lpfc HBA data structure.
955  *
956  * This routine will cleanup posted ELS buffers after the HBA is reset
957  * when bringing down the SLI Layer.
958  *
959  *
960  * Return codes
961  *   void.
962  **/
963 static void
964 lpfc_hba_free_post_buf(struct lpfc_hba *phba)
965 {
966 	struct lpfc_sli *psli = &phba->sli;
967 	struct lpfc_sli_ring *pring;
968 	struct lpfc_dmabuf *mp, *next_mp;
969 	LIST_HEAD(buflist);
970 	int count;
971 
972 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)
973 		lpfc_sli_hbqbuf_free_all(phba);
974 	else {
975 		/* Cleanup preposted buffers on the ELS ring */
976 		pring = &psli->sli3_ring[LPFC_ELS_RING];
977 		spin_lock_irq(&phba->hbalock);
978 		list_splice_init(&pring->postbufq, &buflist);
979 		spin_unlock_irq(&phba->hbalock);
980 
981 		count = 0;
982 		list_for_each_entry_safe(mp, next_mp, &buflist, list) {
983 			list_del(&mp->list);
984 			count++;
985 			lpfc_mbuf_free(phba, mp->virt, mp->phys);
986 			kfree(mp);
987 		}
988 
989 		spin_lock_irq(&phba->hbalock);
990 		pring->postbufq_cnt -= count;
991 		spin_unlock_irq(&phba->hbalock);
992 	}
993 }
994 
995 /**
996  * lpfc_hba_clean_txcmplq - Perform lpfc uninitialization after HBA reset
997  * @phba: pointer to lpfc HBA data structure.
998  *
999  * This routine will cleanup the txcmplq after the HBA is reset when bringing
1000  * down the SLI Layer.
1001  *
1002  * Return codes
1003  *   void
1004  **/
1005 static void
1006 lpfc_hba_clean_txcmplq(struct lpfc_hba *phba)
1007 {
1008 	struct lpfc_sli *psli = &phba->sli;
1009 	struct lpfc_queue *qp = NULL;
1010 	struct lpfc_sli_ring *pring;
1011 	LIST_HEAD(completions);
1012 	int i;
1013 	struct lpfc_iocbq *piocb, *next_iocb;
1014 
1015 	if (phba->sli_rev != LPFC_SLI_REV4) {
1016 		for (i = 0; i < psli->num_rings; i++) {
1017 			pring = &psli->sli3_ring[i];
1018 			spin_lock_irq(&phba->hbalock);
1019 			/* At this point in time the HBA is either reset or DOA
1020 			 * Nothing should be on txcmplq as it will
1021 			 * NEVER complete.
1022 			 */
1023 			list_splice_init(&pring->txcmplq, &completions);
1024 			pring->txcmplq_cnt = 0;
1025 			spin_unlock_irq(&phba->hbalock);
1026 
1027 			lpfc_sli_abort_iocb_ring(phba, pring);
1028 		}
1029 		/* Cancel all the IOCBs from the completions list */
1030 		lpfc_sli_cancel_iocbs(phba, &completions,
1031 				      IOSTAT_LOCAL_REJECT, IOERR_SLI_ABORTED);
1032 		return;
1033 	}
1034 	list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
1035 		pring = qp->pring;
1036 		if (!pring)
1037 			continue;
1038 		spin_lock_irq(&pring->ring_lock);
1039 		list_for_each_entry_safe(piocb, next_iocb,
1040 					 &pring->txcmplq, list)
1041 			piocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
1042 		list_splice_init(&pring->txcmplq, &completions);
1043 		pring->txcmplq_cnt = 0;
1044 		spin_unlock_irq(&pring->ring_lock);
1045 		lpfc_sli_abort_iocb_ring(phba, pring);
1046 	}
1047 	/* Cancel all the IOCBs from the completions list */
1048 	lpfc_sli_cancel_iocbs(phba, &completions,
1049 			      IOSTAT_LOCAL_REJECT, IOERR_SLI_ABORTED);
1050 }
1051 
1052 /**
1053  * lpfc_hba_down_post_s3 - Perform lpfc uninitialization after HBA reset
1054  * @phba: pointer to lpfc HBA data structure.
1055  *
1056  * This routine will do uninitialization after the HBA is reset when bring
1057  * down the SLI Layer.
1058  *
1059  * Return codes
1060  *   0 - success.
1061  *   Any other value - error.
1062  **/
1063 static int
1064 lpfc_hba_down_post_s3(struct lpfc_hba *phba)
1065 {
1066 	lpfc_hba_free_post_buf(phba);
1067 	lpfc_hba_clean_txcmplq(phba);
1068 	return 0;
1069 }
1070 
1071 /**
1072  * lpfc_hba_down_post_s4 - Perform lpfc uninitialization after HBA reset
1073  * @phba: pointer to lpfc HBA data structure.
1074  *
1075  * This routine will do uninitialization after the HBA is reset when bring
1076  * down the SLI Layer.
1077  *
1078  * Return codes
1079  *   0 - success.
1080  *   Any other value - error.
1081  **/
1082 static int
1083 lpfc_hba_down_post_s4(struct lpfc_hba *phba)
1084 {
1085 	struct lpfc_io_buf *psb, *psb_next;
1086 	struct lpfc_async_xchg_ctx *ctxp, *ctxp_next;
1087 	struct lpfc_sli4_hdw_queue *qp;
1088 	LIST_HEAD(aborts);
1089 	LIST_HEAD(nvme_aborts);
1090 	LIST_HEAD(nvmet_aborts);
1091 	struct lpfc_sglq *sglq_entry = NULL;
1092 	int cnt, idx;
1093 
1094 
1095 	lpfc_sli_hbqbuf_free_all(phba);
1096 	lpfc_hba_clean_txcmplq(phba);
1097 
1098 	/* At this point in time the HBA is either reset or DOA. Either
1099 	 * way, nothing should be on lpfc_abts_els_sgl_list, it needs to be
1100 	 * on the lpfc_els_sgl_list so that it can either be freed if the
1101 	 * driver is unloading or reposted if the driver is restarting
1102 	 * the port.
1103 	 */
1104 
1105 	/* sgl_list_lock required because worker thread uses this
1106 	 * list.
1107 	 */
1108 	spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
1109 	list_for_each_entry(sglq_entry,
1110 		&phba->sli4_hba.lpfc_abts_els_sgl_list, list)
1111 		sglq_entry->state = SGL_FREED;
1112 
1113 	list_splice_init(&phba->sli4_hba.lpfc_abts_els_sgl_list,
1114 			&phba->sli4_hba.lpfc_els_sgl_list);
1115 
1116 
1117 	spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
1118 
1119 	/* abts_xxxx_buf_list_lock required because worker thread uses this
1120 	 * list.
1121 	 */
1122 	spin_lock_irq(&phba->hbalock);
1123 	cnt = 0;
1124 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
1125 		qp = &phba->sli4_hba.hdwq[idx];
1126 
1127 		spin_lock(&qp->abts_io_buf_list_lock);
1128 		list_splice_init(&qp->lpfc_abts_io_buf_list,
1129 				 &aborts);
1130 
1131 		list_for_each_entry_safe(psb, psb_next, &aborts, list) {
1132 			psb->pCmd = NULL;
1133 			psb->status = IOSTAT_SUCCESS;
1134 			cnt++;
1135 		}
1136 		spin_lock(&qp->io_buf_list_put_lock);
1137 		list_splice_init(&aborts, &qp->lpfc_io_buf_list_put);
1138 		qp->put_io_bufs += qp->abts_scsi_io_bufs;
1139 		qp->put_io_bufs += qp->abts_nvme_io_bufs;
1140 		qp->abts_scsi_io_bufs = 0;
1141 		qp->abts_nvme_io_bufs = 0;
1142 		spin_unlock(&qp->io_buf_list_put_lock);
1143 		spin_unlock(&qp->abts_io_buf_list_lock);
1144 	}
1145 	spin_unlock_irq(&phba->hbalock);
1146 
1147 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
1148 		spin_lock_irq(&phba->sli4_hba.abts_nvmet_buf_list_lock);
1149 		list_splice_init(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list,
1150 				 &nvmet_aborts);
1151 		spin_unlock_irq(&phba->sli4_hba.abts_nvmet_buf_list_lock);
1152 		list_for_each_entry_safe(ctxp, ctxp_next, &nvmet_aborts, list) {
1153 			ctxp->flag &= ~(LPFC_NVME_XBUSY | LPFC_NVME_ABORT_OP);
1154 			lpfc_nvmet_ctxbuf_post(phba, ctxp->ctxbuf);
1155 		}
1156 	}
1157 
1158 	lpfc_sli4_free_sp_events(phba);
1159 	return cnt;
1160 }
1161 
1162 /**
1163  * lpfc_hba_down_post - Wrapper func for hba down post routine
1164  * @phba: pointer to lpfc HBA data structure.
1165  *
1166  * This routine wraps the actual SLI3 or SLI4 routine for performing
1167  * uninitialization after the HBA is reset when bring down the SLI Layer.
1168  *
1169  * Return codes
1170  *   0 - success.
1171  *   Any other value - error.
1172  **/
1173 int
1174 lpfc_hba_down_post(struct lpfc_hba *phba)
1175 {
1176 	return (*phba->lpfc_hba_down_post)(phba);
1177 }
1178 
1179 /**
1180  * lpfc_hb_timeout - The HBA-timer timeout handler
1181  * @t: timer context used to obtain the pointer to lpfc hba data structure.
1182  *
1183  * This is the HBA-timer timeout handler registered to the lpfc driver. When
1184  * this timer fires, a HBA timeout event shall be posted to the lpfc driver
1185  * work-port-events bitmap and the worker thread is notified. This timeout
1186  * event will be used by the worker thread to invoke the actual timeout
1187  * handler routine, lpfc_hb_timeout_handler. Any periodical operations will
1188  * be performed in the timeout handler and the HBA timeout event bit shall
1189  * be cleared by the worker thread after it has taken the event bitmap out.
1190  **/
1191 static void
1192 lpfc_hb_timeout(struct timer_list *t)
1193 {
1194 	struct lpfc_hba *phba;
1195 	uint32_t tmo_posted;
1196 	unsigned long iflag;
1197 
1198 	phba = from_timer(phba, t, hb_tmofunc);
1199 
1200 	/* Check for heart beat timeout conditions */
1201 	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
1202 	tmo_posted = phba->pport->work_port_events & WORKER_HB_TMO;
1203 	if (!tmo_posted)
1204 		phba->pport->work_port_events |= WORKER_HB_TMO;
1205 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
1206 
1207 	/* Tell the worker thread there is work to do */
1208 	if (!tmo_posted)
1209 		lpfc_worker_wake_up(phba);
1210 	return;
1211 }
1212 
1213 /**
1214  * lpfc_rrq_timeout - The RRQ-timer timeout handler
1215  * @t: timer context used to obtain the pointer to lpfc hba data structure.
1216  *
1217  * This is the RRQ-timer timeout handler registered to the lpfc driver. When
1218  * this timer fires, a RRQ timeout event shall be posted to the lpfc driver
1219  * work-port-events bitmap and the worker thread is notified. This timeout
1220  * event will be used by the worker thread to invoke the actual timeout
1221  * handler routine, lpfc_rrq_handler. Any periodical operations will
1222  * be performed in the timeout handler and the RRQ timeout event bit shall
1223  * be cleared by the worker thread after it has taken the event bitmap out.
1224  **/
1225 static void
1226 lpfc_rrq_timeout(struct timer_list *t)
1227 {
1228 	struct lpfc_hba *phba;
1229 	unsigned long iflag;
1230 
1231 	phba = from_timer(phba, t, rrq_tmr);
1232 	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
1233 	if (!(phba->pport->load_flag & FC_UNLOADING))
1234 		phba->hba_flag |= HBA_RRQ_ACTIVE;
1235 	else
1236 		phba->hba_flag &= ~HBA_RRQ_ACTIVE;
1237 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
1238 
1239 	if (!(phba->pport->load_flag & FC_UNLOADING))
1240 		lpfc_worker_wake_up(phba);
1241 }
1242 
1243 /**
1244  * lpfc_hb_mbox_cmpl - The lpfc heart-beat mailbox command callback function
1245  * @phba: pointer to lpfc hba data structure.
1246  * @pmboxq: pointer to the driver internal queue element for mailbox command.
1247  *
1248  * This is the callback function to the lpfc heart-beat mailbox command.
1249  * If configured, the lpfc driver issues the heart-beat mailbox command to
1250  * the HBA every LPFC_HB_MBOX_INTERVAL (current 5) seconds. At the time the
1251  * heart-beat mailbox command is issued, the driver shall set up heart-beat
1252  * timeout timer to LPFC_HB_MBOX_TIMEOUT (current 30) seconds and marks
1253  * heart-beat outstanding state. Once the mailbox command comes back and
1254  * no error conditions detected, the heart-beat mailbox command timer is
1255  * reset to LPFC_HB_MBOX_INTERVAL seconds and the heart-beat outstanding
1256  * state is cleared for the next heart-beat. If the timer expired with the
1257  * heart-beat outstanding state set, the driver will put the HBA offline.
1258  **/
1259 static void
1260 lpfc_hb_mbox_cmpl(struct lpfc_hba * phba, LPFC_MBOXQ_t * pmboxq)
1261 {
1262 	unsigned long drvr_flag;
1263 
1264 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
1265 	phba->hba_flag &= ~(HBA_HBEAT_INP | HBA_HBEAT_TMO);
1266 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
1267 
1268 	/* Check and reset heart-beat timer if necessary */
1269 	mempool_free(pmboxq, phba->mbox_mem_pool);
1270 	if (!(phba->pport->fc_flag & FC_OFFLINE_MODE) &&
1271 		!(phba->link_state == LPFC_HBA_ERROR) &&
1272 		!(phba->pport->load_flag & FC_UNLOADING))
1273 		mod_timer(&phba->hb_tmofunc,
1274 			  jiffies +
1275 			  msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
1276 	return;
1277 }
1278 
1279 /*
1280  * lpfc_idle_stat_delay_work - idle_stat tracking
1281  *
1282  * This routine tracks per-cq idle_stat and determines polling decisions.
1283  *
1284  * Return codes:
1285  *   None
1286  **/
1287 static void
1288 lpfc_idle_stat_delay_work(struct work_struct *work)
1289 {
1290 	struct lpfc_hba *phba = container_of(to_delayed_work(work),
1291 					     struct lpfc_hba,
1292 					     idle_stat_delay_work);
1293 	struct lpfc_queue *cq;
1294 	struct lpfc_sli4_hdw_queue *hdwq;
1295 	struct lpfc_idle_stat *idle_stat;
1296 	u32 i, idle_percent;
1297 	u64 wall, wall_idle, diff_wall, diff_idle, busy_time;
1298 
1299 	if (phba->pport->load_flag & FC_UNLOADING)
1300 		return;
1301 
1302 	if (phba->link_state == LPFC_HBA_ERROR ||
1303 	    phba->pport->fc_flag & FC_OFFLINE_MODE ||
1304 	    phba->cmf_active_mode != LPFC_CFG_OFF)
1305 		goto requeue;
1306 
1307 	for_each_present_cpu(i) {
1308 		hdwq = &phba->sli4_hba.hdwq[phba->sli4_hba.cpu_map[i].hdwq];
1309 		cq = hdwq->io_cq;
1310 
1311 		/* Skip if we've already handled this cq's primary CPU */
1312 		if (cq->chann != i)
1313 			continue;
1314 
1315 		idle_stat = &phba->sli4_hba.idle_stat[i];
1316 
1317 		/* get_cpu_idle_time returns values as running counters. Thus,
1318 		 * to know the amount for this period, the prior counter values
1319 		 * need to be subtracted from the current counter values.
1320 		 * From there, the idle time stat can be calculated as a
1321 		 * percentage of 100 - the sum of the other consumption times.
1322 		 */
1323 		wall_idle = get_cpu_idle_time(i, &wall, 1);
1324 		diff_idle = wall_idle - idle_stat->prev_idle;
1325 		diff_wall = wall - idle_stat->prev_wall;
1326 
1327 		if (diff_wall <= diff_idle)
1328 			busy_time = 0;
1329 		else
1330 			busy_time = diff_wall - diff_idle;
1331 
1332 		idle_percent = div64_u64(100 * busy_time, diff_wall);
1333 		idle_percent = 100 - idle_percent;
1334 
1335 		if (idle_percent < 15)
1336 			cq->poll_mode = LPFC_QUEUE_WORK;
1337 		else
1338 			cq->poll_mode = LPFC_IRQ_POLL;
1339 
1340 		idle_stat->prev_idle = wall_idle;
1341 		idle_stat->prev_wall = wall;
1342 	}
1343 
1344 requeue:
1345 	schedule_delayed_work(&phba->idle_stat_delay_work,
1346 			      msecs_to_jiffies(LPFC_IDLE_STAT_DELAY));
1347 }
1348 
1349 static void
1350 lpfc_hb_eq_delay_work(struct work_struct *work)
1351 {
1352 	struct lpfc_hba *phba = container_of(to_delayed_work(work),
1353 					     struct lpfc_hba, eq_delay_work);
1354 	struct lpfc_eq_intr_info *eqi, *eqi_new;
1355 	struct lpfc_queue *eq, *eq_next;
1356 	unsigned char *ena_delay = NULL;
1357 	uint32_t usdelay;
1358 	int i;
1359 
1360 	if (!phba->cfg_auto_imax || phba->pport->load_flag & FC_UNLOADING)
1361 		return;
1362 
1363 	if (phba->link_state == LPFC_HBA_ERROR ||
1364 	    phba->pport->fc_flag & FC_OFFLINE_MODE)
1365 		goto requeue;
1366 
1367 	ena_delay = kcalloc(phba->sli4_hba.num_possible_cpu, sizeof(*ena_delay),
1368 			    GFP_KERNEL);
1369 	if (!ena_delay)
1370 		goto requeue;
1371 
1372 	for (i = 0; i < phba->cfg_irq_chann; i++) {
1373 		/* Get the EQ corresponding to the IRQ vector */
1374 		eq = phba->sli4_hba.hba_eq_hdl[i].eq;
1375 		if (!eq)
1376 			continue;
1377 		if (eq->q_mode || eq->q_flag & HBA_EQ_DELAY_CHK) {
1378 			eq->q_flag &= ~HBA_EQ_DELAY_CHK;
1379 			ena_delay[eq->last_cpu] = 1;
1380 		}
1381 	}
1382 
1383 	for_each_present_cpu(i) {
1384 		eqi = per_cpu_ptr(phba->sli4_hba.eq_info, i);
1385 		if (ena_delay[i]) {
1386 			usdelay = (eqi->icnt >> 10) * LPFC_EQ_DELAY_STEP;
1387 			if (usdelay > LPFC_MAX_AUTO_EQ_DELAY)
1388 				usdelay = LPFC_MAX_AUTO_EQ_DELAY;
1389 		} else {
1390 			usdelay = 0;
1391 		}
1392 
1393 		eqi->icnt = 0;
1394 
1395 		list_for_each_entry_safe(eq, eq_next, &eqi->list, cpu_list) {
1396 			if (unlikely(eq->last_cpu != i)) {
1397 				eqi_new = per_cpu_ptr(phba->sli4_hba.eq_info,
1398 						      eq->last_cpu);
1399 				list_move_tail(&eq->cpu_list, &eqi_new->list);
1400 				continue;
1401 			}
1402 			if (usdelay != eq->q_mode)
1403 				lpfc_modify_hba_eq_delay(phba, eq->hdwq, 1,
1404 							 usdelay);
1405 		}
1406 	}
1407 
1408 	kfree(ena_delay);
1409 
1410 requeue:
1411 	queue_delayed_work(phba->wq, &phba->eq_delay_work,
1412 			   msecs_to_jiffies(LPFC_EQ_DELAY_MSECS));
1413 }
1414 
1415 /**
1416  * lpfc_hb_mxp_handler - Multi-XRI pools handler to adjust XRI distribution
1417  * @phba: pointer to lpfc hba data structure.
1418  *
1419  * For each heartbeat, this routine does some heuristic methods to adjust
1420  * XRI distribution. The goal is to fully utilize free XRIs.
1421  **/
1422 static void lpfc_hb_mxp_handler(struct lpfc_hba *phba)
1423 {
1424 	u32 i;
1425 	u32 hwq_count;
1426 
1427 	hwq_count = phba->cfg_hdw_queue;
1428 	for (i = 0; i < hwq_count; i++) {
1429 		/* Adjust XRIs in private pool */
1430 		lpfc_adjust_pvt_pool_count(phba, i);
1431 
1432 		/* Adjust high watermark */
1433 		lpfc_adjust_high_watermark(phba, i);
1434 
1435 #ifdef LPFC_MXP_STAT
1436 		/* Snapshot pbl, pvt and busy count */
1437 		lpfc_snapshot_mxp(phba, i);
1438 #endif
1439 	}
1440 }
1441 
1442 /**
1443  * lpfc_issue_hb_mbox - Issues heart-beat mailbox command
1444  * @phba: pointer to lpfc hba data structure.
1445  *
1446  * If a HB mbox is not already in progrees, this routine will allocate
1447  * a LPFC_MBOXQ_t, populate it with a MBX_HEARTBEAT (0x31) command,
1448  * and issue it. The HBA_HBEAT_INP flag means the command is in progress.
1449  **/
1450 int
1451 lpfc_issue_hb_mbox(struct lpfc_hba *phba)
1452 {
1453 	LPFC_MBOXQ_t *pmboxq;
1454 	int retval;
1455 
1456 	/* Is a Heartbeat mbox already in progress */
1457 	if (phba->hba_flag & HBA_HBEAT_INP)
1458 		return 0;
1459 
1460 	pmboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
1461 	if (!pmboxq)
1462 		return -ENOMEM;
1463 
1464 	lpfc_heart_beat(phba, pmboxq);
1465 	pmboxq->mbox_cmpl = lpfc_hb_mbox_cmpl;
1466 	pmboxq->vport = phba->pport;
1467 	retval = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
1468 
1469 	if (retval != MBX_BUSY && retval != MBX_SUCCESS) {
1470 		mempool_free(pmboxq, phba->mbox_mem_pool);
1471 		return -ENXIO;
1472 	}
1473 	phba->hba_flag |= HBA_HBEAT_INP;
1474 
1475 	return 0;
1476 }
1477 
1478 /**
1479  * lpfc_issue_hb_tmo - Signals heartbeat timer to issue mbox command
1480  * @phba: pointer to lpfc hba data structure.
1481  *
1482  * The heartbeat timer (every 5 sec) will fire. If the HBA_HBEAT_TMO
1483  * flag is set, it will force a MBX_HEARTBEAT mbox command, regardless
1484  * of the value of lpfc_enable_hba_heartbeat.
1485  * If lpfc_enable_hba_heartbeat is set, the timeout routine will always
1486  * try to issue a MBX_HEARTBEAT mbox command.
1487  **/
1488 void
1489 lpfc_issue_hb_tmo(struct lpfc_hba *phba)
1490 {
1491 	if (phba->cfg_enable_hba_heartbeat)
1492 		return;
1493 	phba->hba_flag |= HBA_HBEAT_TMO;
1494 }
1495 
1496 /**
1497  * lpfc_hb_timeout_handler - The HBA-timer timeout handler
1498  * @phba: pointer to lpfc hba data structure.
1499  *
1500  * This is the actual HBA-timer timeout handler to be invoked by the worker
1501  * thread whenever the HBA timer fired and HBA-timeout event posted. This
1502  * handler performs any periodic operations needed for the device. If such
1503  * periodic event has already been attended to either in the interrupt handler
1504  * or by processing slow-ring or fast-ring events within the HBA-timer
1505  * timeout window (LPFC_HB_MBOX_INTERVAL), this handler just simply resets
1506  * the timer for the next timeout period. If lpfc heart-beat mailbox command
1507  * is configured and there is no heart-beat mailbox command outstanding, a
1508  * heart-beat mailbox is issued and timer set properly. Otherwise, if there
1509  * has been a heart-beat mailbox command outstanding, the HBA shall be put
1510  * to offline.
1511  **/
1512 void
1513 lpfc_hb_timeout_handler(struct lpfc_hba *phba)
1514 {
1515 	struct lpfc_vport **vports;
1516 	struct lpfc_dmabuf *buf_ptr;
1517 	int retval = 0;
1518 	int i, tmo;
1519 	struct lpfc_sli *psli = &phba->sli;
1520 	LIST_HEAD(completions);
1521 
1522 	if (phba->cfg_xri_rebalancing) {
1523 		/* Multi-XRI pools handler */
1524 		lpfc_hb_mxp_handler(phba);
1525 	}
1526 
1527 	vports = lpfc_create_vport_work_array(phba);
1528 	if (vports != NULL)
1529 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
1530 			lpfc_rcv_seq_check_edtov(vports[i]);
1531 			lpfc_fdmi_change_check(vports[i]);
1532 		}
1533 	lpfc_destroy_vport_work_array(phba, vports);
1534 
1535 	if ((phba->link_state == LPFC_HBA_ERROR) ||
1536 		(phba->pport->load_flag & FC_UNLOADING) ||
1537 		(phba->pport->fc_flag & FC_OFFLINE_MODE))
1538 		return;
1539 
1540 	if (phba->elsbuf_cnt &&
1541 		(phba->elsbuf_cnt == phba->elsbuf_prev_cnt)) {
1542 		spin_lock_irq(&phba->hbalock);
1543 		list_splice_init(&phba->elsbuf, &completions);
1544 		phba->elsbuf_cnt = 0;
1545 		phba->elsbuf_prev_cnt = 0;
1546 		spin_unlock_irq(&phba->hbalock);
1547 
1548 		while (!list_empty(&completions)) {
1549 			list_remove_head(&completions, buf_ptr,
1550 				struct lpfc_dmabuf, list);
1551 			lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
1552 			kfree(buf_ptr);
1553 		}
1554 	}
1555 	phba->elsbuf_prev_cnt = phba->elsbuf_cnt;
1556 
1557 	/* If there is no heart beat outstanding, issue a heartbeat command */
1558 	if (phba->cfg_enable_hba_heartbeat) {
1559 		/* If IOs are completing, no need to issue a MBX_HEARTBEAT */
1560 		spin_lock_irq(&phba->pport->work_port_lock);
1561 		if (time_after(phba->last_completion_time +
1562 				msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL),
1563 				jiffies)) {
1564 			spin_unlock_irq(&phba->pport->work_port_lock);
1565 			if (phba->hba_flag & HBA_HBEAT_INP)
1566 				tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1567 			else
1568 				tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1569 			goto out;
1570 		}
1571 		spin_unlock_irq(&phba->pport->work_port_lock);
1572 
1573 		/* Check if a MBX_HEARTBEAT is already in progress */
1574 		if (phba->hba_flag & HBA_HBEAT_INP) {
1575 			/*
1576 			 * If heart beat timeout called with HBA_HBEAT_INP set
1577 			 * we need to give the hb mailbox cmd a chance to
1578 			 * complete or TMO.
1579 			 */
1580 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
1581 				"0459 Adapter heartbeat still outstanding: "
1582 				"last compl time was %d ms.\n",
1583 				jiffies_to_msecs(jiffies
1584 					 - phba->last_completion_time));
1585 			tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1586 		} else {
1587 			if ((!(psli->sli_flag & LPFC_SLI_MBOX_ACTIVE)) &&
1588 				(list_empty(&psli->mboxq))) {
1589 
1590 				retval = lpfc_issue_hb_mbox(phba);
1591 				if (retval) {
1592 					tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1593 					goto out;
1594 				}
1595 				phba->skipped_hb = 0;
1596 			} else if (time_before_eq(phba->last_completion_time,
1597 					phba->skipped_hb)) {
1598 				lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
1599 					"2857 Last completion time not "
1600 					" updated in %d ms\n",
1601 					jiffies_to_msecs(jiffies
1602 						 - phba->last_completion_time));
1603 			} else
1604 				phba->skipped_hb = jiffies;
1605 
1606 			tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1607 			goto out;
1608 		}
1609 	} else {
1610 		/* Check to see if we want to force a MBX_HEARTBEAT */
1611 		if (phba->hba_flag & HBA_HBEAT_TMO) {
1612 			retval = lpfc_issue_hb_mbox(phba);
1613 			if (retval)
1614 				tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1615 			else
1616 				tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1617 			goto out;
1618 		}
1619 		tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1620 	}
1621 out:
1622 	mod_timer(&phba->hb_tmofunc, jiffies + msecs_to_jiffies(tmo));
1623 }
1624 
1625 /**
1626  * lpfc_offline_eratt - Bring lpfc offline on hardware error attention
1627  * @phba: pointer to lpfc hba data structure.
1628  *
1629  * This routine is called to bring the HBA offline when HBA hardware error
1630  * other than Port Error 6 has been detected.
1631  **/
1632 static void
1633 lpfc_offline_eratt(struct lpfc_hba *phba)
1634 {
1635 	struct lpfc_sli   *psli = &phba->sli;
1636 
1637 	spin_lock_irq(&phba->hbalock);
1638 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1639 	spin_unlock_irq(&phba->hbalock);
1640 	lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
1641 
1642 	lpfc_offline(phba);
1643 	lpfc_reset_barrier(phba);
1644 	spin_lock_irq(&phba->hbalock);
1645 	lpfc_sli_brdreset(phba);
1646 	spin_unlock_irq(&phba->hbalock);
1647 	lpfc_hba_down_post(phba);
1648 	lpfc_sli_brdready(phba, HS_MBRDY);
1649 	lpfc_unblock_mgmt_io(phba);
1650 	phba->link_state = LPFC_HBA_ERROR;
1651 	return;
1652 }
1653 
1654 /**
1655  * lpfc_sli4_offline_eratt - Bring lpfc offline on SLI4 hardware error attention
1656  * @phba: pointer to lpfc hba data structure.
1657  *
1658  * This routine is called to bring a SLI4 HBA offline when HBA hardware error
1659  * other than Port Error 6 has been detected.
1660  **/
1661 void
1662 lpfc_sli4_offline_eratt(struct lpfc_hba *phba)
1663 {
1664 	spin_lock_irq(&phba->hbalock);
1665 	if (phba->link_state == LPFC_HBA_ERROR &&
1666 		test_bit(HBA_PCI_ERR, &phba->bit_flags)) {
1667 		spin_unlock_irq(&phba->hbalock);
1668 		return;
1669 	}
1670 	phba->link_state = LPFC_HBA_ERROR;
1671 	spin_unlock_irq(&phba->hbalock);
1672 
1673 	lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
1674 	lpfc_sli_flush_io_rings(phba);
1675 	lpfc_offline(phba);
1676 	lpfc_hba_down_post(phba);
1677 	lpfc_unblock_mgmt_io(phba);
1678 }
1679 
1680 /**
1681  * lpfc_handle_deferred_eratt - The HBA hardware deferred error handler
1682  * @phba: pointer to lpfc hba data structure.
1683  *
1684  * This routine is invoked to handle the deferred HBA hardware error
1685  * conditions. This type of error is indicated by HBA by setting ER1
1686  * and another ER bit in the host status register. The driver will
1687  * wait until the ER1 bit clears before handling the error condition.
1688  **/
1689 static void
1690 lpfc_handle_deferred_eratt(struct lpfc_hba *phba)
1691 {
1692 	uint32_t old_host_status = phba->work_hs;
1693 	struct lpfc_sli *psli = &phba->sli;
1694 
1695 	/* If the pci channel is offline, ignore possible errors,
1696 	 * since we cannot communicate with the pci card anyway.
1697 	 */
1698 	if (pci_channel_offline(phba->pcidev)) {
1699 		spin_lock_irq(&phba->hbalock);
1700 		phba->hba_flag &= ~DEFER_ERATT;
1701 		spin_unlock_irq(&phba->hbalock);
1702 		return;
1703 	}
1704 
1705 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1706 			"0479 Deferred Adapter Hardware Error "
1707 			"Data: x%x x%x x%x\n",
1708 			phba->work_hs, phba->work_status[0],
1709 			phba->work_status[1]);
1710 
1711 	spin_lock_irq(&phba->hbalock);
1712 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1713 	spin_unlock_irq(&phba->hbalock);
1714 
1715 
1716 	/*
1717 	 * Firmware stops when it triggred erratt. That could cause the I/Os
1718 	 * dropped by the firmware. Error iocb (I/O) on txcmplq and let the
1719 	 * SCSI layer retry it after re-establishing link.
1720 	 */
1721 	lpfc_sli_abort_fcp_rings(phba);
1722 
1723 	/*
1724 	 * There was a firmware error. Take the hba offline and then
1725 	 * attempt to restart it.
1726 	 */
1727 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
1728 	lpfc_offline(phba);
1729 
1730 	/* Wait for the ER1 bit to clear.*/
1731 	while (phba->work_hs & HS_FFER1) {
1732 		msleep(100);
1733 		if (lpfc_readl(phba->HSregaddr, &phba->work_hs)) {
1734 			phba->work_hs = UNPLUG_ERR ;
1735 			break;
1736 		}
1737 		/* If driver is unloading let the worker thread continue */
1738 		if (phba->pport->load_flag & FC_UNLOADING) {
1739 			phba->work_hs = 0;
1740 			break;
1741 		}
1742 	}
1743 
1744 	/*
1745 	 * This is to ptrotect against a race condition in which
1746 	 * first write to the host attention register clear the
1747 	 * host status register.
1748 	 */
1749 	if ((!phba->work_hs) && (!(phba->pport->load_flag & FC_UNLOADING)))
1750 		phba->work_hs = old_host_status & ~HS_FFER1;
1751 
1752 	spin_lock_irq(&phba->hbalock);
1753 	phba->hba_flag &= ~DEFER_ERATT;
1754 	spin_unlock_irq(&phba->hbalock);
1755 	phba->work_status[0] = readl(phba->MBslimaddr + 0xa8);
1756 	phba->work_status[1] = readl(phba->MBslimaddr + 0xac);
1757 }
1758 
1759 static void
1760 lpfc_board_errevt_to_mgmt(struct lpfc_hba *phba)
1761 {
1762 	struct lpfc_board_event_header board_event;
1763 	struct Scsi_Host *shost;
1764 
1765 	board_event.event_type = FC_REG_BOARD_EVENT;
1766 	board_event.subcategory = LPFC_EVENT_PORTINTERR;
1767 	shost = lpfc_shost_from_vport(phba->pport);
1768 	fc_host_post_vendor_event(shost, fc_get_event_number(),
1769 				  sizeof(board_event),
1770 				  (char *) &board_event,
1771 				  LPFC_NL_VENDOR_ID);
1772 }
1773 
1774 /**
1775  * lpfc_handle_eratt_s3 - The SLI3 HBA hardware error handler
1776  * @phba: pointer to lpfc hba data structure.
1777  *
1778  * This routine is invoked to handle the following HBA hardware error
1779  * conditions:
1780  * 1 - HBA error attention interrupt
1781  * 2 - DMA ring index out of range
1782  * 3 - Mailbox command came back as unknown
1783  **/
1784 static void
1785 lpfc_handle_eratt_s3(struct lpfc_hba *phba)
1786 {
1787 	struct lpfc_vport *vport = phba->pport;
1788 	struct lpfc_sli   *psli = &phba->sli;
1789 	uint32_t event_data;
1790 	unsigned long temperature;
1791 	struct temp_event temp_event_data;
1792 	struct Scsi_Host  *shost;
1793 
1794 	/* If the pci channel is offline, ignore possible errors,
1795 	 * since we cannot communicate with the pci card anyway.
1796 	 */
1797 	if (pci_channel_offline(phba->pcidev)) {
1798 		spin_lock_irq(&phba->hbalock);
1799 		phba->hba_flag &= ~DEFER_ERATT;
1800 		spin_unlock_irq(&phba->hbalock);
1801 		return;
1802 	}
1803 
1804 	/* If resets are disabled then leave the HBA alone and return */
1805 	if (!phba->cfg_enable_hba_reset)
1806 		return;
1807 
1808 	/* Send an internal error event to mgmt application */
1809 	lpfc_board_errevt_to_mgmt(phba);
1810 
1811 	if (phba->hba_flag & DEFER_ERATT)
1812 		lpfc_handle_deferred_eratt(phba);
1813 
1814 	if ((phba->work_hs & HS_FFER6) || (phba->work_hs & HS_FFER8)) {
1815 		if (phba->work_hs & HS_FFER6)
1816 			/* Re-establishing Link */
1817 			lpfc_printf_log(phba, KERN_INFO, LOG_LINK_EVENT,
1818 					"1301 Re-establishing Link "
1819 					"Data: x%x x%x x%x\n",
1820 					phba->work_hs, phba->work_status[0],
1821 					phba->work_status[1]);
1822 		if (phba->work_hs & HS_FFER8)
1823 			/* Device Zeroization */
1824 			lpfc_printf_log(phba, KERN_INFO, LOG_LINK_EVENT,
1825 					"2861 Host Authentication device "
1826 					"zeroization Data:x%x x%x x%x\n",
1827 					phba->work_hs, phba->work_status[0],
1828 					phba->work_status[1]);
1829 
1830 		spin_lock_irq(&phba->hbalock);
1831 		psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1832 		spin_unlock_irq(&phba->hbalock);
1833 
1834 		/*
1835 		* Firmware stops when it triggled erratt with HS_FFER6.
1836 		* That could cause the I/Os dropped by the firmware.
1837 		* Error iocb (I/O) on txcmplq and let the SCSI layer
1838 		* retry it after re-establishing link.
1839 		*/
1840 		lpfc_sli_abort_fcp_rings(phba);
1841 
1842 		/*
1843 		 * There was a firmware error.  Take the hba offline and then
1844 		 * attempt to restart it.
1845 		 */
1846 		lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
1847 		lpfc_offline(phba);
1848 		lpfc_sli_brdrestart(phba);
1849 		if (lpfc_online(phba) == 0) {	/* Initialize the HBA */
1850 			lpfc_unblock_mgmt_io(phba);
1851 			return;
1852 		}
1853 		lpfc_unblock_mgmt_io(phba);
1854 	} else if (phba->work_hs & HS_CRIT_TEMP) {
1855 		temperature = readl(phba->MBslimaddr + TEMPERATURE_OFFSET);
1856 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
1857 		temp_event_data.event_code = LPFC_CRIT_TEMP;
1858 		temp_event_data.data = (uint32_t)temperature;
1859 
1860 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1861 				"0406 Adapter maximum temperature exceeded "
1862 				"(%ld), taking this port offline "
1863 				"Data: x%x x%x x%x\n",
1864 				temperature, phba->work_hs,
1865 				phba->work_status[0], phba->work_status[1]);
1866 
1867 		shost = lpfc_shost_from_vport(phba->pport);
1868 		fc_host_post_vendor_event(shost, fc_get_event_number(),
1869 					  sizeof(temp_event_data),
1870 					  (char *) &temp_event_data,
1871 					  SCSI_NL_VID_TYPE_PCI
1872 					  | PCI_VENDOR_ID_EMULEX);
1873 
1874 		spin_lock_irq(&phba->hbalock);
1875 		phba->over_temp_state = HBA_OVER_TEMP;
1876 		spin_unlock_irq(&phba->hbalock);
1877 		lpfc_offline_eratt(phba);
1878 
1879 	} else {
1880 		/* The if clause above forces this code path when the status
1881 		 * failure is a value other than FFER6. Do not call the offline
1882 		 * twice. This is the adapter hardware error path.
1883 		 */
1884 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1885 				"0457 Adapter Hardware Error "
1886 				"Data: x%x x%x x%x\n",
1887 				phba->work_hs,
1888 				phba->work_status[0], phba->work_status[1]);
1889 
1890 		event_data = FC_REG_DUMP_EVENT;
1891 		shost = lpfc_shost_from_vport(vport);
1892 		fc_host_post_vendor_event(shost, fc_get_event_number(),
1893 				sizeof(event_data), (char *) &event_data,
1894 				SCSI_NL_VID_TYPE_PCI | PCI_VENDOR_ID_EMULEX);
1895 
1896 		lpfc_offline_eratt(phba);
1897 	}
1898 	return;
1899 }
1900 
1901 /**
1902  * lpfc_sli4_port_sta_fn_reset - The SLI4 function reset due to port status reg
1903  * @phba: pointer to lpfc hba data structure.
1904  * @mbx_action: flag for mailbox shutdown action.
1905  * @en_rn_msg: send reset/port recovery message.
1906  * This routine is invoked to perform an SLI4 port PCI function reset in
1907  * response to port status register polling attention. It waits for port
1908  * status register (ERR, RDY, RN) bits before proceeding with function reset.
1909  * During this process, interrupt vectors are freed and later requested
1910  * for handling possible port resource change.
1911  **/
1912 static int
1913 lpfc_sli4_port_sta_fn_reset(struct lpfc_hba *phba, int mbx_action,
1914 			    bool en_rn_msg)
1915 {
1916 	int rc;
1917 	uint32_t intr_mode;
1918 	LPFC_MBOXQ_t *mboxq;
1919 
1920 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) >=
1921 	    LPFC_SLI_INTF_IF_TYPE_2) {
1922 		/*
1923 		 * On error status condition, driver need to wait for port
1924 		 * ready before performing reset.
1925 		 */
1926 		rc = lpfc_sli4_pdev_status_reg_wait(phba);
1927 		if (rc)
1928 			return rc;
1929 	}
1930 
1931 	/* need reset: attempt for port recovery */
1932 	if (en_rn_msg)
1933 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
1934 				"2887 Reset Needed: Attempting Port "
1935 				"Recovery...\n");
1936 
1937 	/* If we are no wait, the HBA has been reset and is not
1938 	 * functional, thus we should clear
1939 	 * (LPFC_SLI_ACTIVE | LPFC_SLI_MBOX_ACTIVE) flags.
1940 	 */
1941 	if (mbx_action == LPFC_MBX_NO_WAIT) {
1942 		spin_lock_irq(&phba->hbalock);
1943 		phba->sli.sli_flag &= ~LPFC_SLI_ACTIVE;
1944 		if (phba->sli.mbox_active) {
1945 			mboxq = phba->sli.mbox_active;
1946 			mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
1947 			__lpfc_mbox_cmpl_put(phba, mboxq);
1948 			phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
1949 			phba->sli.mbox_active = NULL;
1950 		}
1951 		spin_unlock_irq(&phba->hbalock);
1952 	}
1953 
1954 	lpfc_offline_prep(phba, mbx_action);
1955 	lpfc_sli_flush_io_rings(phba);
1956 	lpfc_offline(phba);
1957 	/* release interrupt for possible resource change */
1958 	lpfc_sli4_disable_intr(phba);
1959 	rc = lpfc_sli_brdrestart(phba);
1960 	if (rc) {
1961 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1962 				"6309 Failed to restart board\n");
1963 		return rc;
1964 	}
1965 	/* request and enable interrupt */
1966 	intr_mode = lpfc_sli4_enable_intr(phba, phba->intr_mode);
1967 	if (intr_mode == LPFC_INTR_ERROR) {
1968 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1969 				"3175 Failed to enable interrupt\n");
1970 		return -EIO;
1971 	}
1972 	phba->intr_mode = intr_mode;
1973 	rc = lpfc_online(phba);
1974 	if (rc == 0)
1975 		lpfc_unblock_mgmt_io(phba);
1976 
1977 	return rc;
1978 }
1979 
1980 /**
1981  * lpfc_handle_eratt_s4 - The SLI4 HBA hardware error handler
1982  * @phba: pointer to lpfc hba data structure.
1983  *
1984  * This routine is invoked to handle the SLI4 HBA hardware error attention
1985  * conditions.
1986  **/
1987 static void
1988 lpfc_handle_eratt_s4(struct lpfc_hba *phba)
1989 {
1990 	struct lpfc_vport *vport = phba->pport;
1991 	uint32_t event_data;
1992 	struct Scsi_Host *shost;
1993 	uint32_t if_type;
1994 	struct lpfc_register portstat_reg = {0};
1995 	uint32_t reg_err1, reg_err2;
1996 	uint32_t uerrlo_reg, uemasklo_reg;
1997 	uint32_t smphr_port_status = 0, pci_rd_rc1, pci_rd_rc2;
1998 	bool en_rn_msg = true;
1999 	struct temp_event temp_event_data;
2000 	struct lpfc_register portsmphr_reg;
2001 	int rc, i;
2002 
2003 	/* If the pci channel is offline, ignore possible errors, since
2004 	 * we cannot communicate with the pci card anyway.
2005 	 */
2006 	if (pci_channel_offline(phba->pcidev)) {
2007 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2008 				"3166 pci channel is offline\n");
2009 		lpfc_sli_flush_io_rings(phba);
2010 		return;
2011 	}
2012 
2013 	memset(&portsmphr_reg, 0, sizeof(portsmphr_reg));
2014 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
2015 	switch (if_type) {
2016 	case LPFC_SLI_INTF_IF_TYPE_0:
2017 		pci_rd_rc1 = lpfc_readl(
2018 				phba->sli4_hba.u.if_type0.UERRLOregaddr,
2019 				&uerrlo_reg);
2020 		pci_rd_rc2 = lpfc_readl(
2021 				phba->sli4_hba.u.if_type0.UEMASKLOregaddr,
2022 				&uemasklo_reg);
2023 		/* consider PCI bus read error as pci_channel_offline */
2024 		if (pci_rd_rc1 == -EIO && pci_rd_rc2 == -EIO)
2025 			return;
2026 		if (!(phba->hba_flag & HBA_RECOVERABLE_UE)) {
2027 			lpfc_sli4_offline_eratt(phba);
2028 			return;
2029 		}
2030 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2031 				"7623 Checking UE recoverable");
2032 
2033 		for (i = 0; i < phba->sli4_hba.ue_to_sr / 1000; i++) {
2034 			if (lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
2035 				       &portsmphr_reg.word0))
2036 				continue;
2037 
2038 			smphr_port_status = bf_get(lpfc_port_smphr_port_status,
2039 						   &portsmphr_reg);
2040 			if ((smphr_port_status & LPFC_PORT_SEM_MASK) ==
2041 			    LPFC_PORT_SEM_UE_RECOVERABLE)
2042 				break;
2043 			/*Sleep for 1Sec, before checking SEMAPHORE */
2044 			msleep(1000);
2045 		}
2046 
2047 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2048 				"4827 smphr_port_status x%x : Waited %dSec",
2049 				smphr_port_status, i);
2050 
2051 		/* Recoverable UE, reset the HBA device */
2052 		if ((smphr_port_status & LPFC_PORT_SEM_MASK) ==
2053 		    LPFC_PORT_SEM_UE_RECOVERABLE) {
2054 			for (i = 0; i < 20; i++) {
2055 				msleep(1000);
2056 				if (!lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
2057 				    &portsmphr_reg.word0) &&
2058 				    (LPFC_POST_STAGE_PORT_READY ==
2059 				     bf_get(lpfc_port_smphr_port_status,
2060 				     &portsmphr_reg))) {
2061 					rc = lpfc_sli4_port_sta_fn_reset(phba,
2062 						LPFC_MBX_NO_WAIT, en_rn_msg);
2063 					if (rc == 0)
2064 						return;
2065 					lpfc_printf_log(phba, KERN_ERR,
2066 						LOG_TRACE_EVENT,
2067 						"4215 Failed to recover UE");
2068 					break;
2069 				}
2070 			}
2071 		}
2072 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2073 				"7624 Firmware not ready: Failing UE recovery,"
2074 				" waited %dSec", i);
2075 		phba->link_state = LPFC_HBA_ERROR;
2076 		break;
2077 
2078 	case LPFC_SLI_INTF_IF_TYPE_2:
2079 	case LPFC_SLI_INTF_IF_TYPE_6:
2080 		pci_rd_rc1 = lpfc_readl(
2081 				phba->sli4_hba.u.if_type2.STATUSregaddr,
2082 				&portstat_reg.word0);
2083 		/* consider PCI bus read error as pci_channel_offline */
2084 		if (pci_rd_rc1 == -EIO) {
2085 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2086 				"3151 PCI bus read access failure: x%x\n",
2087 				readl(phba->sli4_hba.u.if_type2.STATUSregaddr));
2088 			lpfc_sli4_offline_eratt(phba);
2089 			return;
2090 		}
2091 		reg_err1 = readl(phba->sli4_hba.u.if_type2.ERR1regaddr);
2092 		reg_err2 = readl(phba->sli4_hba.u.if_type2.ERR2regaddr);
2093 		if (bf_get(lpfc_sliport_status_oti, &portstat_reg)) {
2094 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2095 					"2889 Port Overtemperature event, "
2096 					"taking port offline Data: x%x x%x\n",
2097 					reg_err1, reg_err2);
2098 
2099 			phba->sfp_alarm |= LPFC_TRANSGRESSION_HIGH_TEMPERATURE;
2100 			temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
2101 			temp_event_data.event_code = LPFC_CRIT_TEMP;
2102 			temp_event_data.data = 0xFFFFFFFF;
2103 
2104 			shost = lpfc_shost_from_vport(phba->pport);
2105 			fc_host_post_vendor_event(shost, fc_get_event_number(),
2106 						  sizeof(temp_event_data),
2107 						  (char *)&temp_event_data,
2108 						  SCSI_NL_VID_TYPE_PCI
2109 						  | PCI_VENDOR_ID_EMULEX);
2110 
2111 			spin_lock_irq(&phba->hbalock);
2112 			phba->over_temp_state = HBA_OVER_TEMP;
2113 			spin_unlock_irq(&phba->hbalock);
2114 			lpfc_sli4_offline_eratt(phba);
2115 			return;
2116 		}
2117 		if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2118 		    reg_err2 == SLIPORT_ERR2_REG_FW_RESTART) {
2119 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2120 					"3143 Port Down: Firmware Update "
2121 					"Detected\n");
2122 			en_rn_msg = false;
2123 		} else if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2124 			 reg_err2 == SLIPORT_ERR2_REG_FORCED_DUMP)
2125 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2126 					"3144 Port Down: Debug Dump\n");
2127 		else if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2128 			 reg_err2 == SLIPORT_ERR2_REG_FUNC_PROVISON)
2129 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2130 					"3145 Port Down: Provisioning\n");
2131 
2132 		/* If resets are disabled then leave the HBA alone and return */
2133 		if (!phba->cfg_enable_hba_reset)
2134 			return;
2135 
2136 		/* Check port status register for function reset */
2137 		rc = lpfc_sli4_port_sta_fn_reset(phba, LPFC_MBX_NO_WAIT,
2138 				en_rn_msg);
2139 		if (rc == 0) {
2140 			/* don't report event on forced debug dump */
2141 			if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2142 			    reg_err2 == SLIPORT_ERR2_REG_FORCED_DUMP)
2143 				return;
2144 			else
2145 				break;
2146 		}
2147 		/* fall through for not able to recover */
2148 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2149 				"3152 Unrecoverable error\n");
2150 		phba->link_state = LPFC_HBA_ERROR;
2151 		break;
2152 	case LPFC_SLI_INTF_IF_TYPE_1:
2153 	default:
2154 		break;
2155 	}
2156 	lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
2157 			"3123 Report dump event to upper layer\n");
2158 	/* Send an internal error event to mgmt application */
2159 	lpfc_board_errevt_to_mgmt(phba);
2160 
2161 	event_data = FC_REG_DUMP_EVENT;
2162 	shost = lpfc_shost_from_vport(vport);
2163 	fc_host_post_vendor_event(shost, fc_get_event_number(),
2164 				  sizeof(event_data), (char *) &event_data,
2165 				  SCSI_NL_VID_TYPE_PCI | PCI_VENDOR_ID_EMULEX);
2166 }
2167 
2168 /**
2169  * lpfc_handle_eratt - Wrapper func for handling hba error attention
2170  * @phba: pointer to lpfc HBA data structure.
2171  *
2172  * This routine wraps the actual SLI3 or SLI4 hba error attention handling
2173  * routine from the API jump table function pointer from the lpfc_hba struct.
2174  *
2175  * Return codes
2176  *   0 - success.
2177  *   Any other value - error.
2178  **/
2179 void
2180 lpfc_handle_eratt(struct lpfc_hba *phba)
2181 {
2182 	(*phba->lpfc_handle_eratt)(phba);
2183 }
2184 
2185 /**
2186  * lpfc_handle_latt - The HBA link event handler
2187  * @phba: pointer to lpfc hba data structure.
2188  *
2189  * This routine is invoked from the worker thread to handle a HBA host
2190  * attention link event. SLI3 only.
2191  **/
2192 void
2193 lpfc_handle_latt(struct lpfc_hba *phba)
2194 {
2195 	struct lpfc_vport *vport = phba->pport;
2196 	struct lpfc_sli   *psli = &phba->sli;
2197 	LPFC_MBOXQ_t *pmb;
2198 	volatile uint32_t control;
2199 	int rc = 0;
2200 
2201 	pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
2202 	if (!pmb) {
2203 		rc = 1;
2204 		goto lpfc_handle_latt_err_exit;
2205 	}
2206 
2207 	rc = lpfc_mbox_rsrc_prep(phba, pmb);
2208 	if (rc) {
2209 		rc = 2;
2210 		mempool_free(pmb, phba->mbox_mem_pool);
2211 		goto lpfc_handle_latt_err_exit;
2212 	}
2213 
2214 	/* Cleanup any outstanding ELS commands */
2215 	lpfc_els_flush_all_cmd(phba);
2216 	psli->slistat.link_event++;
2217 	lpfc_read_topology(phba, pmb, (struct lpfc_dmabuf *)pmb->ctx_buf);
2218 	pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
2219 	pmb->vport = vport;
2220 	/* Block ELS IOCBs until we have processed this mbox command */
2221 	phba->sli.sli3_ring[LPFC_ELS_RING].flag |= LPFC_STOP_IOCB_EVENT;
2222 	rc = lpfc_sli_issue_mbox (phba, pmb, MBX_NOWAIT);
2223 	if (rc == MBX_NOT_FINISHED) {
2224 		rc = 4;
2225 		goto lpfc_handle_latt_free_mbuf;
2226 	}
2227 
2228 	/* Clear Link Attention in HA REG */
2229 	spin_lock_irq(&phba->hbalock);
2230 	writel(HA_LATT, phba->HAregaddr);
2231 	readl(phba->HAregaddr); /* flush */
2232 	spin_unlock_irq(&phba->hbalock);
2233 
2234 	return;
2235 
2236 lpfc_handle_latt_free_mbuf:
2237 	phba->sli.sli3_ring[LPFC_ELS_RING].flag &= ~LPFC_STOP_IOCB_EVENT;
2238 	lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
2239 lpfc_handle_latt_err_exit:
2240 	/* Enable Link attention interrupts */
2241 	spin_lock_irq(&phba->hbalock);
2242 	psli->sli_flag |= LPFC_PROCESS_LA;
2243 	control = readl(phba->HCregaddr);
2244 	control |= HC_LAINT_ENA;
2245 	writel(control, phba->HCregaddr);
2246 	readl(phba->HCregaddr); /* flush */
2247 
2248 	/* Clear Link Attention in HA REG */
2249 	writel(HA_LATT, phba->HAregaddr);
2250 	readl(phba->HAregaddr); /* flush */
2251 	spin_unlock_irq(&phba->hbalock);
2252 	lpfc_linkdown(phba);
2253 	phba->link_state = LPFC_HBA_ERROR;
2254 
2255 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2256 			"0300 LATT: Cannot issue READ_LA: Data:%d\n", rc);
2257 
2258 	return;
2259 }
2260 
2261 /**
2262  * lpfc_parse_vpd - Parse VPD (Vital Product Data)
2263  * @phba: pointer to lpfc hba data structure.
2264  * @vpd: pointer to the vital product data.
2265  * @len: length of the vital product data in bytes.
2266  *
2267  * This routine parses the Vital Product Data (VPD). The VPD is treated as
2268  * an array of characters. In this routine, the ModelName, ProgramType, and
2269  * ModelDesc, etc. fields of the phba data structure will be populated.
2270  *
2271  * Return codes
2272  *   0 - pointer to the VPD passed in is NULL
2273  *   1 - success
2274  **/
2275 int
2276 lpfc_parse_vpd(struct lpfc_hba *phba, uint8_t *vpd, int len)
2277 {
2278 	uint8_t lenlo, lenhi;
2279 	int Length;
2280 	int i, j;
2281 	int finished = 0;
2282 	int index = 0;
2283 
2284 	if (!vpd)
2285 		return 0;
2286 
2287 	/* Vital Product */
2288 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
2289 			"0455 Vital Product Data: x%x x%x x%x x%x\n",
2290 			(uint32_t) vpd[0], (uint32_t) vpd[1], (uint32_t) vpd[2],
2291 			(uint32_t) vpd[3]);
2292 	while (!finished && (index < (len - 4))) {
2293 		switch (vpd[index]) {
2294 		case 0x82:
2295 		case 0x91:
2296 			index += 1;
2297 			lenlo = vpd[index];
2298 			index += 1;
2299 			lenhi = vpd[index];
2300 			index += 1;
2301 			i = ((((unsigned short)lenhi) << 8) + lenlo);
2302 			index += i;
2303 			break;
2304 		case 0x90:
2305 			index += 1;
2306 			lenlo = vpd[index];
2307 			index += 1;
2308 			lenhi = vpd[index];
2309 			index += 1;
2310 			Length = ((((unsigned short)lenhi) << 8) + lenlo);
2311 			if (Length > len - index)
2312 				Length = len - index;
2313 			while (Length > 0) {
2314 			/* Look for Serial Number */
2315 			if ((vpd[index] == 'S') && (vpd[index+1] == 'N')) {
2316 				index += 2;
2317 				i = vpd[index];
2318 				index += 1;
2319 				j = 0;
2320 				Length -= (3+i);
2321 				while(i--) {
2322 					phba->SerialNumber[j++] = vpd[index++];
2323 					if (j == 31)
2324 						break;
2325 				}
2326 				phba->SerialNumber[j] = 0;
2327 				continue;
2328 			}
2329 			else if ((vpd[index] == 'V') && (vpd[index+1] == '1')) {
2330 				phba->vpd_flag |= VPD_MODEL_DESC;
2331 				index += 2;
2332 				i = vpd[index];
2333 				index += 1;
2334 				j = 0;
2335 				Length -= (3+i);
2336 				while(i--) {
2337 					phba->ModelDesc[j++] = vpd[index++];
2338 					if (j == 255)
2339 						break;
2340 				}
2341 				phba->ModelDesc[j] = 0;
2342 				continue;
2343 			}
2344 			else if ((vpd[index] == 'V') && (vpd[index+1] == '2')) {
2345 				phba->vpd_flag |= VPD_MODEL_NAME;
2346 				index += 2;
2347 				i = vpd[index];
2348 				index += 1;
2349 				j = 0;
2350 				Length -= (3+i);
2351 				while(i--) {
2352 					phba->ModelName[j++] = vpd[index++];
2353 					if (j == 79)
2354 						break;
2355 				}
2356 				phba->ModelName[j] = 0;
2357 				continue;
2358 			}
2359 			else if ((vpd[index] == 'V') && (vpd[index+1] == '3')) {
2360 				phba->vpd_flag |= VPD_PROGRAM_TYPE;
2361 				index += 2;
2362 				i = vpd[index];
2363 				index += 1;
2364 				j = 0;
2365 				Length -= (3+i);
2366 				while(i--) {
2367 					phba->ProgramType[j++] = vpd[index++];
2368 					if (j == 255)
2369 						break;
2370 				}
2371 				phba->ProgramType[j] = 0;
2372 				continue;
2373 			}
2374 			else if ((vpd[index] == 'V') && (vpd[index+1] == '4')) {
2375 				phba->vpd_flag |= VPD_PORT;
2376 				index += 2;
2377 				i = vpd[index];
2378 				index += 1;
2379 				j = 0;
2380 				Length -= (3+i);
2381 				while(i--) {
2382 					if ((phba->sli_rev == LPFC_SLI_REV4) &&
2383 					    (phba->sli4_hba.pport_name_sta ==
2384 					     LPFC_SLI4_PPNAME_GET)) {
2385 						j++;
2386 						index++;
2387 					} else
2388 						phba->Port[j++] = vpd[index++];
2389 					if (j == 19)
2390 						break;
2391 				}
2392 				if ((phba->sli_rev != LPFC_SLI_REV4) ||
2393 				    (phba->sli4_hba.pport_name_sta ==
2394 				     LPFC_SLI4_PPNAME_NON))
2395 					phba->Port[j] = 0;
2396 				continue;
2397 			}
2398 			else {
2399 				index += 2;
2400 				i = vpd[index];
2401 				index += 1;
2402 				index += i;
2403 				Length -= (3 + i);
2404 			}
2405 		}
2406 		finished = 0;
2407 		break;
2408 		case 0x78:
2409 			finished = 1;
2410 			break;
2411 		default:
2412 			index ++;
2413 			break;
2414 		}
2415 	}
2416 
2417 	return(1);
2418 }
2419 
2420 /**
2421  * lpfc_get_atto_model_desc - Retrieve ATTO HBA device model name and description
2422  * @phba: pointer to lpfc hba data structure.
2423  * @mdp: pointer to the data structure to hold the derived model name.
2424  * @descp: pointer to the data structure to hold the derived description.
2425  *
2426  * This routine retrieves HBA's description based on its registered PCI device
2427  * ID. The @descp passed into this function points to an array of 256 chars. It
2428  * shall be returned with the model name, maximum speed, and the host bus type.
2429  * The @mdp passed into this function points to an array of 80 chars. When the
2430  * function returns, the @mdp will be filled with the model name.
2431  **/
2432 static void
2433 lpfc_get_atto_model_desc(struct lpfc_hba *phba, uint8_t *mdp, uint8_t *descp)
2434 {
2435 	uint16_t sub_dev_id = phba->pcidev->subsystem_device;
2436 	char *model = "<Unknown>";
2437 	int tbolt = 0;
2438 
2439 	switch (sub_dev_id) {
2440 	case PCI_DEVICE_ID_CLRY_161E:
2441 		model = "161E";
2442 		break;
2443 	case PCI_DEVICE_ID_CLRY_162E:
2444 		model = "162E";
2445 		break;
2446 	case PCI_DEVICE_ID_CLRY_164E:
2447 		model = "164E";
2448 		break;
2449 	case PCI_DEVICE_ID_CLRY_161P:
2450 		model = "161P";
2451 		break;
2452 	case PCI_DEVICE_ID_CLRY_162P:
2453 		model = "162P";
2454 		break;
2455 	case PCI_DEVICE_ID_CLRY_164P:
2456 		model = "164P";
2457 		break;
2458 	case PCI_DEVICE_ID_CLRY_321E:
2459 		model = "321E";
2460 		break;
2461 	case PCI_DEVICE_ID_CLRY_322E:
2462 		model = "322E";
2463 		break;
2464 	case PCI_DEVICE_ID_CLRY_324E:
2465 		model = "324E";
2466 		break;
2467 	case PCI_DEVICE_ID_CLRY_321P:
2468 		model = "321P";
2469 		break;
2470 	case PCI_DEVICE_ID_CLRY_322P:
2471 		model = "322P";
2472 		break;
2473 	case PCI_DEVICE_ID_CLRY_324P:
2474 		model = "324P";
2475 		break;
2476 	case PCI_DEVICE_ID_TLFC_2XX2:
2477 		model = "2XX2";
2478 		tbolt = 1;
2479 		break;
2480 	case PCI_DEVICE_ID_TLFC_3162:
2481 		model = "3162";
2482 		tbolt = 1;
2483 		break;
2484 	case PCI_DEVICE_ID_TLFC_3322:
2485 		model = "3322";
2486 		tbolt = 1;
2487 		break;
2488 	default:
2489 		model = "Unknown";
2490 		break;
2491 	}
2492 
2493 	if (mdp && mdp[0] == '\0')
2494 		snprintf(mdp, 79, "%s", model);
2495 
2496 	if (descp && descp[0] == '\0')
2497 		snprintf(descp, 255,
2498 			 "ATTO %s%s, Fibre Channel Adapter Initiator, Port %s",
2499 			 (tbolt) ? "ThunderLink FC " : "Celerity FC-",
2500 			 model,
2501 			 phba->Port);
2502 }
2503 
2504 /**
2505  * lpfc_get_hba_model_desc - Retrieve HBA device model name and description
2506  * @phba: pointer to lpfc hba data structure.
2507  * @mdp: pointer to the data structure to hold the derived model name.
2508  * @descp: pointer to the data structure to hold the derived description.
2509  *
2510  * This routine retrieves HBA's description based on its registered PCI device
2511  * ID. The @descp passed into this function points to an array of 256 chars. It
2512  * shall be returned with the model name, maximum speed, and the host bus type.
2513  * The @mdp passed into this function points to an array of 80 chars. When the
2514  * function returns, the @mdp will be filled with the model name.
2515  **/
2516 static void
2517 lpfc_get_hba_model_desc(struct lpfc_hba *phba, uint8_t *mdp, uint8_t *descp)
2518 {
2519 	lpfc_vpd_t *vp;
2520 	uint16_t dev_id = phba->pcidev->device;
2521 	int max_speed;
2522 	int GE = 0;
2523 	int oneConnect = 0; /* default is not a oneConnect */
2524 	struct {
2525 		char *name;
2526 		char *bus;
2527 		char *function;
2528 	} m = {"<Unknown>", "", ""};
2529 
2530 	if (mdp && mdp[0] != '\0'
2531 		&& descp && descp[0] != '\0')
2532 		return;
2533 
2534 	if (phba->pcidev->vendor == PCI_VENDOR_ID_ATTO) {
2535 		lpfc_get_atto_model_desc(phba, mdp, descp);
2536 		return;
2537 	}
2538 
2539 	if (phba->lmt & LMT_64Gb)
2540 		max_speed = 64;
2541 	else if (phba->lmt & LMT_32Gb)
2542 		max_speed = 32;
2543 	else if (phba->lmt & LMT_16Gb)
2544 		max_speed = 16;
2545 	else if (phba->lmt & LMT_10Gb)
2546 		max_speed = 10;
2547 	else if (phba->lmt & LMT_8Gb)
2548 		max_speed = 8;
2549 	else if (phba->lmt & LMT_4Gb)
2550 		max_speed = 4;
2551 	else if (phba->lmt & LMT_2Gb)
2552 		max_speed = 2;
2553 	else if (phba->lmt & LMT_1Gb)
2554 		max_speed = 1;
2555 	else
2556 		max_speed = 0;
2557 
2558 	vp = &phba->vpd;
2559 
2560 	switch (dev_id) {
2561 	case PCI_DEVICE_ID_FIREFLY:
2562 		m = (typeof(m)){"LP6000", "PCI",
2563 				"Obsolete, Unsupported Fibre Channel Adapter"};
2564 		break;
2565 	case PCI_DEVICE_ID_SUPERFLY:
2566 		if (vp->rev.biuRev >= 1 && vp->rev.biuRev <= 3)
2567 			m = (typeof(m)){"LP7000", "PCI", ""};
2568 		else
2569 			m = (typeof(m)){"LP7000E", "PCI", ""};
2570 		m.function = "Obsolete, Unsupported Fibre Channel Adapter";
2571 		break;
2572 	case PCI_DEVICE_ID_DRAGONFLY:
2573 		m = (typeof(m)){"LP8000", "PCI",
2574 				"Obsolete, Unsupported Fibre Channel Adapter"};
2575 		break;
2576 	case PCI_DEVICE_ID_CENTAUR:
2577 		if (FC_JEDEC_ID(vp->rev.biuRev) == CENTAUR_2G_JEDEC_ID)
2578 			m = (typeof(m)){"LP9002", "PCI", ""};
2579 		else
2580 			m = (typeof(m)){"LP9000", "PCI", ""};
2581 		m.function = "Obsolete, Unsupported Fibre Channel Adapter";
2582 		break;
2583 	case PCI_DEVICE_ID_RFLY:
2584 		m = (typeof(m)){"LP952", "PCI",
2585 				"Obsolete, Unsupported Fibre Channel Adapter"};
2586 		break;
2587 	case PCI_DEVICE_ID_PEGASUS:
2588 		m = (typeof(m)){"LP9802", "PCI-X",
2589 				"Obsolete, Unsupported Fibre Channel Adapter"};
2590 		break;
2591 	case PCI_DEVICE_ID_THOR:
2592 		m = (typeof(m)){"LP10000", "PCI-X",
2593 				"Obsolete, Unsupported Fibre Channel Adapter"};
2594 		break;
2595 	case PCI_DEVICE_ID_VIPER:
2596 		m = (typeof(m)){"LPX1000",  "PCI-X",
2597 				"Obsolete, Unsupported Fibre Channel Adapter"};
2598 		break;
2599 	case PCI_DEVICE_ID_PFLY:
2600 		m = (typeof(m)){"LP982", "PCI-X",
2601 				"Obsolete, Unsupported Fibre Channel Adapter"};
2602 		break;
2603 	case PCI_DEVICE_ID_TFLY:
2604 		m = (typeof(m)){"LP1050", "PCI-X",
2605 				"Obsolete, Unsupported Fibre Channel Adapter"};
2606 		break;
2607 	case PCI_DEVICE_ID_HELIOS:
2608 		m = (typeof(m)){"LP11000", "PCI-X2",
2609 				"Obsolete, Unsupported Fibre Channel Adapter"};
2610 		break;
2611 	case PCI_DEVICE_ID_HELIOS_SCSP:
2612 		m = (typeof(m)){"LP11000-SP", "PCI-X2",
2613 				"Obsolete, Unsupported Fibre Channel Adapter"};
2614 		break;
2615 	case PCI_DEVICE_ID_HELIOS_DCSP:
2616 		m = (typeof(m)){"LP11002-SP",  "PCI-X2",
2617 				"Obsolete, Unsupported Fibre Channel Adapter"};
2618 		break;
2619 	case PCI_DEVICE_ID_NEPTUNE:
2620 		m = (typeof(m)){"LPe1000", "PCIe",
2621 				"Obsolete, Unsupported Fibre Channel Adapter"};
2622 		break;
2623 	case PCI_DEVICE_ID_NEPTUNE_SCSP:
2624 		m = (typeof(m)){"LPe1000-SP", "PCIe",
2625 				"Obsolete, Unsupported Fibre Channel Adapter"};
2626 		break;
2627 	case PCI_DEVICE_ID_NEPTUNE_DCSP:
2628 		m = (typeof(m)){"LPe1002-SP", "PCIe",
2629 				"Obsolete, Unsupported Fibre Channel Adapter"};
2630 		break;
2631 	case PCI_DEVICE_ID_BMID:
2632 		m = (typeof(m)){"LP1150", "PCI-X2", "Fibre Channel Adapter"};
2633 		break;
2634 	case PCI_DEVICE_ID_BSMB:
2635 		m = (typeof(m)){"LP111", "PCI-X2",
2636 				"Obsolete, Unsupported Fibre Channel Adapter"};
2637 		break;
2638 	case PCI_DEVICE_ID_ZEPHYR:
2639 		m = (typeof(m)){"LPe11000", "PCIe", "Fibre Channel Adapter"};
2640 		break;
2641 	case PCI_DEVICE_ID_ZEPHYR_SCSP:
2642 		m = (typeof(m)){"LPe11000", "PCIe", "Fibre Channel Adapter"};
2643 		break;
2644 	case PCI_DEVICE_ID_ZEPHYR_DCSP:
2645 		m = (typeof(m)){"LP2105", "PCIe", "FCoE Adapter"};
2646 		GE = 1;
2647 		break;
2648 	case PCI_DEVICE_ID_ZMID:
2649 		m = (typeof(m)){"LPe1150", "PCIe", "Fibre Channel Adapter"};
2650 		break;
2651 	case PCI_DEVICE_ID_ZSMB:
2652 		m = (typeof(m)){"LPe111", "PCIe", "Fibre Channel Adapter"};
2653 		break;
2654 	case PCI_DEVICE_ID_LP101:
2655 		m = (typeof(m)){"LP101", "PCI-X",
2656 				"Obsolete, Unsupported Fibre Channel Adapter"};
2657 		break;
2658 	case PCI_DEVICE_ID_LP10000S:
2659 		m = (typeof(m)){"LP10000-S", "PCI",
2660 				"Obsolete, Unsupported Fibre Channel Adapter"};
2661 		break;
2662 	case PCI_DEVICE_ID_LP11000S:
2663 		m = (typeof(m)){"LP11000-S", "PCI-X2",
2664 				"Obsolete, Unsupported Fibre Channel Adapter"};
2665 		break;
2666 	case PCI_DEVICE_ID_LPE11000S:
2667 		m = (typeof(m)){"LPe11000-S", "PCIe",
2668 				"Obsolete, Unsupported Fibre Channel Adapter"};
2669 		break;
2670 	case PCI_DEVICE_ID_SAT:
2671 		m = (typeof(m)){"LPe12000", "PCIe", "Fibre Channel Adapter"};
2672 		break;
2673 	case PCI_DEVICE_ID_SAT_MID:
2674 		m = (typeof(m)){"LPe1250", "PCIe", "Fibre Channel Adapter"};
2675 		break;
2676 	case PCI_DEVICE_ID_SAT_SMB:
2677 		m = (typeof(m)){"LPe121", "PCIe", "Fibre Channel Adapter"};
2678 		break;
2679 	case PCI_DEVICE_ID_SAT_DCSP:
2680 		m = (typeof(m)){"LPe12002-SP", "PCIe", "Fibre Channel Adapter"};
2681 		break;
2682 	case PCI_DEVICE_ID_SAT_SCSP:
2683 		m = (typeof(m)){"LPe12000-SP", "PCIe", "Fibre Channel Adapter"};
2684 		break;
2685 	case PCI_DEVICE_ID_SAT_S:
2686 		m = (typeof(m)){"LPe12000-S", "PCIe", "Fibre Channel Adapter"};
2687 		break;
2688 	case PCI_DEVICE_ID_PROTEUS_VF:
2689 		m = (typeof(m)){"LPev12000", "PCIe IOV",
2690 				"Obsolete, Unsupported Fibre Channel Adapter"};
2691 		break;
2692 	case PCI_DEVICE_ID_PROTEUS_PF:
2693 		m = (typeof(m)){"LPev12000", "PCIe IOV",
2694 				"Obsolete, Unsupported Fibre Channel Adapter"};
2695 		break;
2696 	case PCI_DEVICE_ID_PROTEUS_S:
2697 		m = (typeof(m)){"LPemv12002-S", "PCIe IOV",
2698 				"Obsolete, Unsupported Fibre Channel Adapter"};
2699 		break;
2700 	case PCI_DEVICE_ID_TIGERSHARK:
2701 		oneConnect = 1;
2702 		m = (typeof(m)){"OCe10100", "PCIe", "FCoE"};
2703 		break;
2704 	case PCI_DEVICE_ID_TOMCAT:
2705 		oneConnect = 1;
2706 		m = (typeof(m)){"OCe11100", "PCIe", "FCoE"};
2707 		break;
2708 	case PCI_DEVICE_ID_FALCON:
2709 		m = (typeof(m)){"LPSe12002-ML1-E", "PCIe",
2710 				"EmulexSecure Fibre"};
2711 		break;
2712 	case PCI_DEVICE_ID_BALIUS:
2713 		m = (typeof(m)){"LPVe12002", "PCIe Shared I/O",
2714 				"Obsolete, Unsupported Fibre Channel Adapter"};
2715 		break;
2716 	case PCI_DEVICE_ID_LANCER_FC:
2717 		m = (typeof(m)){"LPe16000", "PCIe", "Fibre Channel Adapter"};
2718 		break;
2719 	case PCI_DEVICE_ID_LANCER_FC_VF:
2720 		m = (typeof(m)){"LPe16000", "PCIe",
2721 				"Obsolete, Unsupported Fibre Channel Adapter"};
2722 		break;
2723 	case PCI_DEVICE_ID_LANCER_FCOE:
2724 		oneConnect = 1;
2725 		m = (typeof(m)){"OCe15100", "PCIe", "FCoE"};
2726 		break;
2727 	case PCI_DEVICE_ID_LANCER_FCOE_VF:
2728 		oneConnect = 1;
2729 		m = (typeof(m)){"OCe15100", "PCIe",
2730 				"Obsolete, Unsupported FCoE"};
2731 		break;
2732 	case PCI_DEVICE_ID_LANCER_G6_FC:
2733 		m = (typeof(m)){"LPe32000", "PCIe", "Fibre Channel Adapter"};
2734 		break;
2735 	case PCI_DEVICE_ID_LANCER_G7_FC:
2736 		m = (typeof(m)){"LPe36000", "PCIe", "Fibre Channel Adapter"};
2737 		break;
2738 	case PCI_DEVICE_ID_LANCER_G7P_FC:
2739 		m = (typeof(m)){"LPe38000", "PCIe", "Fibre Channel Adapter"};
2740 		break;
2741 	case PCI_DEVICE_ID_SKYHAWK:
2742 	case PCI_DEVICE_ID_SKYHAWK_VF:
2743 		oneConnect = 1;
2744 		m = (typeof(m)){"OCe14000", "PCIe", "FCoE"};
2745 		break;
2746 	default:
2747 		m = (typeof(m)){"Unknown", "", ""};
2748 		break;
2749 	}
2750 
2751 	if (mdp && mdp[0] == '\0')
2752 		snprintf(mdp, 79,"%s", m.name);
2753 	/*
2754 	 * oneConnect hba requires special processing, they are all initiators
2755 	 * and we put the port number on the end
2756 	 */
2757 	if (descp && descp[0] == '\0') {
2758 		if (oneConnect)
2759 			snprintf(descp, 255,
2760 				"Emulex OneConnect %s, %s Initiator %s",
2761 				m.name, m.function,
2762 				phba->Port);
2763 		else if (max_speed == 0)
2764 			snprintf(descp, 255,
2765 				"Emulex %s %s %s",
2766 				m.name, m.bus, m.function);
2767 		else
2768 			snprintf(descp, 255,
2769 				"Emulex %s %d%s %s %s",
2770 				m.name, max_speed, (GE) ? "GE" : "Gb",
2771 				m.bus, m.function);
2772 	}
2773 }
2774 
2775 /**
2776  * lpfc_sli3_post_buffer - Post IOCB(s) with DMA buffer descriptor(s) to a IOCB ring
2777  * @phba: pointer to lpfc hba data structure.
2778  * @pring: pointer to a IOCB ring.
2779  * @cnt: the number of IOCBs to be posted to the IOCB ring.
2780  *
2781  * This routine posts a given number of IOCBs with the associated DMA buffer
2782  * descriptors specified by the cnt argument to the given IOCB ring.
2783  *
2784  * Return codes
2785  *   The number of IOCBs NOT able to be posted to the IOCB ring.
2786  **/
2787 int
2788 lpfc_sli3_post_buffer(struct lpfc_hba *phba, struct lpfc_sli_ring *pring, int cnt)
2789 {
2790 	IOCB_t *icmd;
2791 	struct lpfc_iocbq *iocb;
2792 	struct lpfc_dmabuf *mp1, *mp2;
2793 
2794 	cnt += pring->missbufcnt;
2795 
2796 	/* While there are buffers to post */
2797 	while (cnt > 0) {
2798 		/* Allocate buffer for  command iocb */
2799 		iocb = lpfc_sli_get_iocbq(phba);
2800 		if (iocb == NULL) {
2801 			pring->missbufcnt = cnt;
2802 			return cnt;
2803 		}
2804 		icmd = &iocb->iocb;
2805 
2806 		/* 2 buffers can be posted per command */
2807 		/* Allocate buffer to post */
2808 		mp1 = kmalloc(sizeof (struct lpfc_dmabuf), GFP_KERNEL);
2809 		if (mp1)
2810 		    mp1->virt = lpfc_mbuf_alloc(phba, MEM_PRI, &mp1->phys);
2811 		if (!mp1 || !mp1->virt) {
2812 			kfree(mp1);
2813 			lpfc_sli_release_iocbq(phba, iocb);
2814 			pring->missbufcnt = cnt;
2815 			return cnt;
2816 		}
2817 
2818 		INIT_LIST_HEAD(&mp1->list);
2819 		/* Allocate buffer to post */
2820 		if (cnt > 1) {
2821 			mp2 = kmalloc(sizeof (struct lpfc_dmabuf), GFP_KERNEL);
2822 			if (mp2)
2823 				mp2->virt = lpfc_mbuf_alloc(phba, MEM_PRI,
2824 							    &mp2->phys);
2825 			if (!mp2 || !mp2->virt) {
2826 				kfree(mp2);
2827 				lpfc_mbuf_free(phba, mp1->virt, mp1->phys);
2828 				kfree(mp1);
2829 				lpfc_sli_release_iocbq(phba, iocb);
2830 				pring->missbufcnt = cnt;
2831 				return cnt;
2832 			}
2833 
2834 			INIT_LIST_HEAD(&mp2->list);
2835 		} else {
2836 			mp2 = NULL;
2837 		}
2838 
2839 		icmd->un.cont64[0].addrHigh = putPaddrHigh(mp1->phys);
2840 		icmd->un.cont64[0].addrLow = putPaddrLow(mp1->phys);
2841 		icmd->un.cont64[0].tus.f.bdeSize = FCELSSIZE;
2842 		icmd->ulpBdeCount = 1;
2843 		cnt--;
2844 		if (mp2) {
2845 			icmd->un.cont64[1].addrHigh = putPaddrHigh(mp2->phys);
2846 			icmd->un.cont64[1].addrLow = putPaddrLow(mp2->phys);
2847 			icmd->un.cont64[1].tus.f.bdeSize = FCELSSIZE;
2848 			cnt--;
2849 			icmd->ulpBdeCount = 2;
2850 		}
2851 
2852 		icmd->ulpCommand = CMD_QUE_RING_BUF64_CN;
2853 		icmd->ulpLe = 1;
2854 
2855 		if (lpfc_sli_issue_iocb(phba, pring->ringno, iocb, 0) ==
2856 		    IOCB_ERROR) {
2857 			lpfc_mbuf_free(phba, mp1->virt, mp1->phys);
2858 			kfree(mp1);
2859 			cnt++;
2860 			if (mp2) {
2861 				lpfc_mbuf_free(phba, mp2->virt, mp2->phys);
2862 				kfree(mp2);
2863 				cnt++;
2864 			}
2865 			lpfc_sli_release_iocbq(phba, iocb);
2866 			pring->missbufcnt = cnt;
2867 			return cnt;
2868 		}
2869 		lpfc_sli_ringpostbuf_put(phba, pring, mp1);
2870 		if (mp2)
2871 			lpfc_sli_ringpostbuf_put(phba, pring, mp2);
2872 	}
2873 	pring->missbufcnt = 0;
2874 	return 0;
2875 }
2876 
2877 /**
2878  * lpfc_post_rcv_buf - Post the initial receive IOCB buffers to ELS ring
2879  * @phba: pointer to lpfc hba data structure.
2880  *
2881  * This routine posts initial receive IOCB buffers to the ELS ring. The
2882  * current number of initial IOCB buffers specified by LPFC_BUF_RING0 is
2883  * set to 64 IOCBs. SLI3 only.
2884  *
2885  * Return codes
2886  *   0 - success (currently always success)
2887  **/
2888 static int
2889 lpfc_post_rcv_buf(struct lpfc_hba *phba)
2890 {
2891 	struct lpfc_sli *psli = &phba->sli;
2892 
2893 	/* Ring 0, ELS / CT buffers */
2894 	lpfc_sli3_post_buffer(phba, &psli->sli3_ring[LPFC_ELS_RING], LPFC_BUF_RING0);
2895 	/* Ring 2 - FCP no buffers needed */
2896 
2897 	return 0;
2898 }
2899 
2900 #define S(N,V) (((V)<<(N))|((V)>>(32-(N))))
2901 
2902 /**
2903  * lpfc_sha_init - Set up initial array of hash table entries
2904  * @HashResultPointer: pointer to an array as hash table.
2905  *
2906  * This routine sets up the initial values to the array of hash table entries
2907  * for the LC HBAs.
2908  **/
2909 static void
2910 lpfc_sha_init(uint32_t * HashResultPointer)
2911 {
2912 	HashResultPointer[0] = 0x67452301;
2913 	HashResultPointer[1] = 0xEFCDAB89;
2914 	HashResultPointer[2] = 0x98BADCFE;
2915 	HashResultPointer[3] = 0x10325476;
2916 	HashResultPointer[4] = 0xC3D2E1F0;
2917 }
2918 
2919 /**
2920  * lpfc_sha_iterate - Iterate initial hash table with the working hash table
2921  * @HashResultPointer: pointer to an initial/result hash table.
2922  * @HashWorkingPointer: pointer to an working hash table.
2923  *
2924  * This routine iterates an initial hash table pointed by @HashResultPointer
2925  * with the values from the working hash table pointeed by @HashWorkingPointer.
2926  * The results are putting back to the initial hash table, returned through
2927  * the @HashResultPointer as the result hash table.
2928  **/
2929 static void
2930 lpfc_sha_iterate(uint32_t * HashResultPointer, uint32_t * HashWorkingPointer)
2931 {
2932 	int t;
2933 	uint32_t TEMP;
2934 	uint32_t A, B, C, D, E;
2935 	t = 16;
2936 	do {
2937 		HashWorkingPointer[t] =
2938 		    S(1,
2939 		      HashWorkingPointer[t - 3] ^ HashWorkingPointer[t -
2940 								     8] ^
2941 		      HashWorkingPointer[t - 14] ^ HashWorkingPointer[t - 16]);
2942 	} while (++t <= 79);
2943 	t = 0;
2944 	A = HashResultPointer[0];
2945 	B = HashResultPointer[1];
2946 	C = HashResultPointer[2];
2947 	D = HashResultPointer[3];
2948 	E = HashResultPointer[4];
2949 
2950 	do {
2951 		if (t < 20) {
2952 			TEMP = ((B & C) | ((~B) & D)) + 0x5A827999;
2953 		} else if (t < 40) {
2954 			TEMP = (B ^ C ^ D) + 0x6ED9EBA1;
2955 		} else if (t < 60) {
2956 			TEMP = ((B & C) | (B & D) | (C & D)) + 0x8F1BBCDC;
2957 		} else {
2958 			TEMP = (B ^ C ^ D) + 0xCA62C1D6;
2959 		}
2960 		TEMP += S(5, A) + E + HashWorkingPointer[t];
2961 		E = D;
2962 		D = C;
2963 		C = S(30, B);
2964 		B = A;
2965 		A = TEMP;
2966 	} while (++t <= 79);
2967 
2968 	HashResultPointer[0] += A;
2969 	HashResultPointer[1] += B;
2970 	HashResultPointer[2] += C;
2971 	HashResultPointer[3] += D;
2972 	HashResultPointer[4] += E;
2973 
2974 }
2975 
2976 /**
2977  * lpfc_challenge_key - Create challenge key based on WWPN of the HBA
2978  * @RandomChallenge: pointer to the entry of host challenge random number array.
2979  * @HashWorking: pointer to the entry of the working hash array.
2980  *
2981  * This routine calculates the working hash array referred by @HashWorking
2982  * from the challenge random numbers associated with the host, referred by
2983  * @RandomChallenge. The result is put into the entry of the working hash
2984  * array and returned by reference through @HashWorking.
2985  **/
2986 static void
2987 lpfc_challenge_key(uint32_t * RandomChallenge, uint32_t * HashWorking)
2988 {
2989 	*HashWorking = (*RandomChallenge ^ *HashWorking);
2990 }
2991 
2992 /**
2993  * lpfc_hba_init - Perform special handling for LC HBA initialization
2994  * @phba: pointer to lpfc hba data structure.
2995  * @hbainit: pointer to an array of unsigned 32-bit integers.
2996  *
2997  * This routine performs the special handling for LC HBA initialization.
2998  **/
2999 void
3000 lpfc_hba_init(struct lpfc_hba *phba, uint32_t *hbainit)
3001 {
3002 	int t;
3003 	uint32_t *HashWorking;
3004 	uint32_t *pwwnn = (uint32_t *) phba->wwnn;
3005 
3006 	HashWorking = kcalloc(80, sizeof(uint32_t), GFP_KERNEL);
3007 	if (!HashWorking)
3008 		return;
3009 
3010 	HashWorking[0] = HashWorking[78] = *pwwnn++;
3011 	HashWorking[1] = HashWorking[79] = *pwwnn;
3012 
3013 	for (t = 0; t < 7; t++)
3014 		lpfc_challenge_key(phba->RandomData + t, HashWorking + t);
3015 
3016 	lpfc_sha_init(hbainit);
3017 	lpfc_sha_iterate(hbainit, HashWorking);
3018 	kfree(HashWorking);
3019 }
3020 
3021 /**
3022  * lpfc_cleanup - Performs vport cleanups before deleting a vport
3023  * @vport: pointer to a virtual N_Port data structure.
3024  *
3025  * This routine performs the necessary cleanups before deleting the @vport.
3026  * It invokes the discovery state machine to perform necessary state
3027  * transitions and to release the ndlps associated with the @vport. Note,
3028  * the physical port is treated as @vport 0.
3029  **/
3030 void
3031 lpfc_cleanup(struct lpfc_vport *vport)
3032 {
3033 	struct lpfc_hba   *phba = vport->phba;
3034 	struct lpfc_nodelist *ndlp, *next_ndlp;
3035 	int i = 0;
3036 
3037 	if (phba->link_state > LPFC_LINK_DOWN)
3038 		lpfc_port_link_failure(vport);
3039 
3040 	/* Clean up VMID resources */
3041 	if (lpfc_is_vmid_enabled(phba))
3042 		lpfc_vmid_vport_cleanup(vport);
3043 
3044 	list_for_each_entry_safe(ndlp, next_ndlp, &vport->fc_nodes, nlp_listp) {
3045 		if (vport->port_type != LPFC_PHYSICAL_PORT &&
3046 		    ndlp->nlp_DID == Fabric_DID) {
3047 			/* Just free up ndlp with Fabric_DID for vports */
3048 			lpfc_nlp_put(ndlp);
3049 			continue;
3050 		}
3051 
3052 		if (ndlp->nlp_DID == Fabric_Cntl_DID &&
3053 		    ndlp->nlp_state == NLP_STE_UNUSED_NODE) {
3054 			lpfc_nlp_put(ndlp);
3055 			continue;
3056 		}
3057 
3058 		/* Fabric Ports not in UNMAPPED state are cleaned up in the
3059 		 * DEVICE_RM event.
3060 		 */
3061 		if (ndlp->nlp_type & NLP_FABRIC &&
3062 		    ndlp->nlp_state == NLP_STE_UNMAPPED_NODE)
3063 			lpfc_disc_state_machine(vport, ndlp, NULL,
3064 					NLP_EVT_DEVICE_RECOVERY);
3065 
3066 		if (!(ndlp->fc4_xpt_flags & (NVME_XPT_REGD|SCSI_XPT_REGD)))
3067 			lpfc_disc_state_machine(vport, ndlp, NULL,
3068 					NLP_EVT_DEVICE_RM);
3069 	}
3070 
3071 	/* This is a special case flush to return all
3072 	 * IOs before entering this loop. There are
3073 	 * two points in the code where a flush is
3074 	 * avoided if the FC_UNLOADING flag is set.
3075 	 * one is in the multipool destroy,
3076 	 * (this prevents a crash) and the other is
3077 	 * in the nvme abort handler, ( also prevents
3078 	 * a crash). Both of these exceptions are
3079 	 * cases where the slot is still accessible.
3080 	 * The flush here is only when the pci slot
3081 	 * is offline.
3082 	 */
3083 	if (vport->load_flag & FC_UNLOADING &&
3084 	    pci_channel_offline(phba->pcidev))
3085 		lpfc_sli_flush_io_rings(vport->phba);
3086 
3087 	/* At this point, ALL ndlp's should be gone
3088 	 * because of the previous NLP_EVT_DEVICE_RM.
3089 	 * Lets wait for this to happen, if needed.
3090 	 */
3091 	while (!list_empty(&vport->fc_nodes)) {
3092 		if (i++ > 3000) {
3093 			lpfc_printf_vlog(vport, KERN_ERR,
3094 					 LOG_TRACE_EVENT,
3095 				"0233 Nodelist not empty\n");
3096 			list_for_each_entry_safe(ndlp, next_ndlp,
3097 						&vport->fc_nodes, nlp_listp) {
3098 				lpfc_printf_vlog(ndlp->vport, KERN_ERR,
3099 						 LOG_DISCOVERY,
3100 						 "0282 did:x%x ndlp:x%px "
3101 						 "refcnt:%d xflags x%x nflag x%x\n",
3102 						 ndlp->nlp_DID, (void *)ndlp,
3103 						 kref_read(&ndlp->kref),
3104 						 ndlp->fc4_xpt_flags,
3105 						 ndlp->nlp_flag);
3106 			}
3107 			break;
3108 		}
3109 
3110 		/* Wait for any activity on ndlps to settle */
3111 		msleep(10);
3112 	}
3113 	lpfc_cleanup_vports_rrqs(vport, NULL);
3114 }
3115 
3116 /**
3117  * lpfc_stop_vport_timers - Stop all the timers associated with a vport
3118  * @vport: pointer to a virtual N_Port data structure.
3119  *
3120  * This routine stops all the timers associated with a @vport. This function
3121  * is invoked before disabling or deleting a @vport. Note that the physical
3122  * port is treated as @vport 0.
3123  **/
3124 void
3125 lpfc_stop_vport_timers(struct lpfc_vport *vport)
3126 {
3127 	del_timer_sync(&vport->els_tmofunc);
3128 	del_timer_sync(&vport->delayed_disc_tmo);
3129 	lpfc_can_disctmo(vport);
3130 	return;
3131 }
3132 
3133 /**
3134  * __lpfc_sli4_stop_fcf_redisc_wait_timer - Stop FCF rediscovery wait timer
3135  * @phba: pointer to lpfc hba data structure.
3136  *
3137  * This routine stops the SLI4 FCF rediscover wait timer if it's on. The
3138  * caller of this routine should already hold the host lock.
3139  **/
3140 void
3141 __lpfc_sli4_stop_fcf_redisc_wait_timer(struct lpfc_hba *phba)
3142 {
3143 	/* Clear pending FCF rediscovery wait flag */
3144 	phba->fcf.fcf_flag &= ~FCF_REDISC_PEND;
3145 
3146 	/* Now, try to stop the timer */
3147 	del_timer(&phba->fcf.redisc_wait);
3148 }
3149 
3150 /**
3151  * lpfc_sli4_stop_fcf_redisc_wait_timer - Stop FCF rediscovery wait timer
3152  * @phba: pointer to lpfc hba data structure.
3153  *
3154  * This routine stops the SLI4 FCF rediscover wait timer if it's on. It
3155  * checks whether the FCF rediscovery wait timer is pending with the host
3156  * lock held before proceeding with disabling the timer and clearing the
3157  * wait timer pendig flag.
3158  **/
3159 void
3160 lpfc_sli4_stop_fcf_redisc_wait_timer(struct lpfc_hba *phba)
3161 {
3162 	spin_lock_irq(&phba->hbalock);
3163 	if (!(phba->fcf.fcf_flag & FCF_REDISC_PEND)) {
3164 		/* FCF rediscovery timer already fired or stopped */
3165 		spin_unlock_irq(&phba->hbalock);
3166 		return;
3167 	}
3168 	__lpfc_sli4_stop_fcf_redisc_wait_timer(phba);
3169 	/* Clear failover in progress flags */
3170 	phba->fcf.fcf_flag &= ~(FCF_DEAD_DISC | FCF_ACVL_DISC);
3171 	spin_unlock_irq(&phba->hbalock);
3172 }
3173 
3174 /**
3175  * lpfc_cmf_stop - Stop CMF processing
3176  * @phba: pointer to lpfc hba data structure.
3177  *
3178  * This is called when the link goes down or if CMF mode is turned OFF.
3179  * It is also called when going offline or unloaded just before the
3180  * congestion info buffer is unregistered.
3181  **/
3182 void
3183 lpfc_cmf_stop(struct lpfc_hba *phba)
3184 {
3185 	int cpu;
3186 	struct lpfc_cgn_stat *cgs;
3187 
3188 	/* We only do something if CMF is enabled */
3189 	if (!phba->sli4_hba.pc_sli4_params.cmf)
3190 		return;
3191 
3192 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
3193 			"6221 Stop CMF / Cancel Timer\n");
3194 
3195 	/* Cancel the CMF timer */
3196 	hrtimer_cancel(&phba->cmf_timer);
3197 
3198 	/* Zero CMF counters */
3199 	atomic_set(&phba->cmf_busy, 0);
3200 	for_each_present_cpu(cpu) {
3201 		cgs = per_cpu_ptr(phba->cmf_stat, cpu);
3202 		atomic64_set(&cgs->total_bytes, 0);
3203 		atomic64_set(&cgs->rcv_bytes, 0);
3204 		atomic_set(&cgs->rx_io_cnt, 0);
3205 		atomic64_set(&cgs->rx_latency, 0);
3206 	}
3207 	atomic_set(&phba->cmf_bw_wait, 0);
3208 
3209 	/* Resume any blocked IO - Queue unblock on workqueue */
3210 	queue_work(phba->wq, &phba->unblock_request_work);
3211 }
3212 
3213 static inline uint64_t
3214 lpfc_get_max_line_rate(struct lpfc_hba *phba)
3215 {
3216 	uint64_t rate = lpfc_sli_port_speed_get(phba);
3217 
3218 	return ((((unsigned long)rate) * 1024 * 1024) / 10);
3219 }
3220 
3221 void
3222 lpfc_cmf_signal_init(struct lpfc_hba *phba)
3223 {
3224 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
3225 			"6223 Signal CMF init\n");
3226 
3227 	/* Use the new fc_linkspeed to recalculate */
3228 	phba->cmf_interval_rate = LPFC_CMF_INTERVAL;
3229 	phba->cmf_max_line_rate = lpfc_get_max_line_rate(phba);
3230 	phba->cmf_link_byte_count = div_u64(phba->cmf_max_line_rate *
3231 					    phba->cmf_interval_rate, 1000);
3232 	phba->cmf_max_bytes_per_interval = phba->cmf_link_byte_count;
3233 
3234 	/* This is a signal to firmware to sync up CMF BW with link speed */
3235 	lpfc_issue_cmf_sync_wqe(phba, 0, 0);
3236 }
3237 
3238 /**
3239  * lpfc_cmf_start - Start CMF processing
3240  * @phba: pointer to lpfc hba data structure.
3241  *
3242  * This is called when the link comes up or if CMF mode is turned OFF
3243  * to Monitor or Managed.
3244  **/
3245 void
3246 lpfc_cmf_start(struct lpfc_hba *phba)
3247 {
3248 	struct lpfc_cgn_stat *cgs;
3249 	int cpu;
3250 
3251 	/* We only do something if CMF is enabled */
3252 	if (!phba->sli4_hba.pc_sli4_params.cmf ||
3253 	    phba->cmf_active_mode == LPFC_CFG_OFF)
3254 		return;
3255 
3256 	/* Reinitialize congestion buffer info */
3257 	lpfc_init_congestion_buf(phba);
3258 
3259 	atomic_set(&phba->cgn_fabric_warn_cnt, 0);
3260 	atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
3261 	atomic_set(&phba->cgn_sync_alarm_cnt, 0);
3262 	atomic_set(&phba->cgn_sync_warn_cnt, 0);
3263 
3264 	atomic_set(&phba->cmf_busy, 0);
3265 	for_each_present_cpu(cpu) {
3266 		cgs = per_cpu_ptr(phba->cmf_stat, cpu);
3267 		atomic64_set(&cgs->total_bytes, 0);
3268 		atomic64_set(&cgs->rcv_bytes, 0);
3269 		atomic_set(&cgs->rx_io_cnt, 0);
3270 		atomic64_set(&cgs->rx_latency, 0);
3271 	}
3272 	phba->cmf_latency.tv_sec = 0;
3273 	phba->cmf_latency.tv_nsec = 0;
3274 
3275 	lpfc_cmf_signal_init(phba);
3276 
3277 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
3278 			"6222 Start CMF / Timer\n");
3279 
3280 	phba->cmf_timer_cnt = 0;
3281 	hrtimer_start(&phba->cmf_timer,
3282 		      ktime_set(0, LPFC_CMF_INTERVAL * 1000000),
3283 		      HRTIMER_MODE_REL);
3284 	/* Setup for latency check in IO cmpl routines */
3285 	ktime_get_real_ts64(&phba->cmf_latency);
3286 
3287 	atomic_set(&phba->cmf_bw_wait, 0);
3288 	atomic_set(&phba->cmf_stop_io, 0);
3289 }
3290 
3291 /**
3292  * lpfc_stop_hba_timers - Stop all the timers associated with an HBA
3293  * @phba: pointer to lpfc hba data structure.
3294  *
3295  * This routine stops all the timers associated with a HBA. This function is
3296  * invoked before either putting a HBA offline or unloading the driver.
3297  **/
3298 void
3299 lpfc_stop_hba_timers(struct lpfc_hba *phba)
3300 {
3301 	if (phba->pport)
3302 		lpfc_stop_vport_timers(phba->pport);
3303 	cancel_delayed_work_sync(&phba->eq_delay_work);
3304 	cancel_delayed_work_sync(&phba->idle_stat_delay_work);
3305 	del_timer_sync(&phba->sli.mbox_tmo);
3306 	del_timer_sync(&phba->fabric_block_timer);
3307 	del_timer_sync(&phba->eratt_poll);
3308 	del_timer_sync(&phba->hb_tmofunc);
3309 	if (phba->sli_rev == LPFC_SLI_REV4) {
3310 		del_timer_sync(&phba->rrq_tmr);
3311 		phba->hba_flag &= ~HBA_RRQ_ACTIVE;
3312 	}
3313 	phba->hba_flag &= ~(HBA_HBEAT_INP | HBA_HBEAT_TMO);
3314 
3315 	switch (phba->pci_dev_grp) {
3316 	case LPFC_PCI_DEV_LP:
3317 		/* Stop any LightPulse device specific driver timers */
3318 		del_timer_sync(&phba->fcp_poll_timer);
3319 		break;
3320 	case LPFC_PCI_DEV_OC:
3321 		/* Stop any OneConnect device specific driver timers */
3322 		lpfc_sli4_stop_fcf_redisc_wait_timer(phba);
3323 		break;
3324 	default:
3325 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3326 				"0297 Invalid device group (x%x)\n",
3327 				phba->pci_dev_grp);
3328 		break;
3329 	}
3330 	return;
3331 }
3332 
3333 /**
3334  * lpfc_block_mgmt_io - Mark a HBA's management interface as blocked
3335  * @phba: pointer to lpfc hba data structure.
3336  * @mbx_action: flag for mailbox no wait action.
3337  *
3338  * This routine marks a HBA's management interface as blocked. Once the HBA's
3339  * management interface is marked as blocked, all the user space access to
3340  * the HBA, whether they are from sysfs interface or libdfc interface will
3341  * all be blocked. The HBA is set to block the management interface when the
3342  * driver prepares the HBA interface for online or offline.
3343  **/
3344 static void
3345 lpfc_block_mgmt_io(struct lpfc_hba *phba, int mbx_action)
3346 {
3347 	unsigned long iflag;
3348 	uint8_t actcmd = MBX_HEARTBEAT;
3349 	unsigned long timeout;
3350 
3351 	spin_lock_irqsave(&phba->hbalock, iflag);
3352 	phba->sli.sli_flag |= LPFC_BLOCK_MGMT_IO;
3353 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3354 	if (mbx_action == LPFC_MBX_NO_WAIT)
3355 		return;
3356 	timeout = msecs_to_jiffies(LPFC_MBOX_TMO * 1000) + jiffies;
3357 	spin_lock_irqsave(&phba->hbalock, iflag);
3358 	if (phba->sli.mbox_active) {
3359 		actcmd = phba->sli.mbox_active->u.mb.mbxCommand;
3360 		/* Determine how long we might wait for the active mailbox
3361 		 * command to be gracefully completed by firmware.
3362 		 */
3363 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
3364 				phba->sli.mbox_active) * 1000) + jiffies;
3365 	}
3366 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3367 
3368 	/* Wait for the outstnading mailbox command to complete */
3369 	while (phba->sli.mbox_active) {
3370 		/* Check active mailbox complete status every 2ms */
3371 		msleep(2);
3372 		if (time_after(jiffies, timeout)) {
3373 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3374 					"2813 Mgmt IO is Blocked %x "
3375 					"- mbox cmd %x still active\n",
3376 					phba->sli.sli_flag, actcmd);
3377 			break;
3378 		}
3379 	}
3380 }
3381 
3382 /**
3383  * lpfc_sli4_node_prep - Assign RPIs for active nodes.
3384  * @phba: pointer to lpfc hba data structure.
3385  *
3386  * Allocate RPIs for all active remote nodes. This is needed whenever
3387  * an SLI4 adapter is reset and the driver is not unloading. Its purpose
3388  * is to fixup the temporary rpi assignments.
3389  **/
3390 void
3391 lpfc_sli4_node_prep(struct lpfc_hba *phba)
3392 {
3393 	struct lpfc_nodelist  *ndlp, *next_ndlp;
3394 	struct lpfc_vport **vports;
3395 	int i, rpi;
3396 
3397 	if (phba->sli_rev != LPFC_SLI_REV4)
3398 		return;
3399 
3400 	vports = lpfc_create_vport_work_array(phba);
3401 	if (vports == NULL)
3402 		return;
3403 
3404 	for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3405 		if (vports[i]->load_flag & FC_UNLOADING)
3406 			continue;
3407 
3408 		list_for_each_entry_safe(ndlp, next_ndlp,
3409 					 &vports[i]->fc_nodes,
3410 					 nlp_listp) {
3411 			rpi = lpfc_sli4_alloc_rpi(phba);
3412 			if (rpi == LPFC_RPI_ALLOC_ERROR) {
3413 				/* TODO print log? */
3414 				continue;
3415 			}
3416 			ndlp->nlp_rpi = rpi;
3417 			lpfc_printf_vlog(ndlp->vport, KERN_INFO,
3418 					 LOG_NODE | LOG_DISCOVERY,
3419 					 "0009 Assign RPI x%x to ndlp x%px "
3420 					 "DID:x%06x flg:x%x\n",
3421 					 ndlp->nlp_rpi, ndlp, ndlp->nlp_DID,
3422 					 ndlp->nlp_flag);
3423 		}
3424 	}
3425 	lpfc_destroy_vport_work_array(phba, vports);
3426 }
3427 
3428 /**
3429  * lpfc_create_expedite_pool - create expedite pool
3430  * @phba: pointer to lpfc hba data structure.
3431  *
3432  * This routine moves a batch of XRIs from lpfc_io_buf_list_put of HWQ 0
3433  * to expedite pool. Mark them as expedite.
3434  **/
3435 static void lpfc_create_expedite_pool(struct lpfc_hba *phba)
3436 {
3437 	struct lpfc_sli4_hdw_queue *qp;
3438 	struct lpfc_io_buf *lpfc_ncmd;
3439 	struct lpfc_io_buf *lpfc_ncmd_next;
3440 	struct lpfc_epd_pool *epd_pool;
3441 	unsigned long iflag;
3442 
3443 	epd_pool = &phba->epd_pool;
3444 	qp = &phba->sli4_hba.hdwq[0];
3445 
3446 	spin_lock_init(&epd_pool->lock);
3447 	spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3448 	spin_lock(&epd_pool->lock);
3449 	INIT_LIST_HEAD(&epd_pool->list);
3450 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3451 				 &qp->lpfc_io_buf_list_put, list) {
3452 		list_move_tail(&lpfc_ncmd->list, &epd_pool->list);
3453 		lpfc_ncmd->expedite = true;
3454 		qp->put_io_bufs--;
3455 		epd_pool->count++;
3456 		if (epd_pool->count >= XRI_BATCH)
3457 			break;
3458 	}
3459 	spin_unlock(&epd_pool->lock);
3460 	spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3461 }
3462 
3463 /**
3464  * lpfc_destroy_expedite_pool - destroy expedite pool
3465  * @phba: pointer to lpfc hba data structure.
3466  *
3467  * This routine returns XRIs from expedite pool to lpfc_io_buf_list_put
3468  * of HWQ 0. Clear the mark.
3469  **/
3470 static void lpfc_destroy_expedite_pool(struct lpfc_hba *phba)
3471 {
3472 	struct lpfc_sli4_hdw_queue *qp;
3473 	struct lpfc_io_buf *lpfc_ncmd;
3474 	struct lpfc_io_buf *lpfc_ncmd_next;
3475 	struct lpfc_epd_pool *epd_pool;
3476 	unsigned long iflag;
3477 
3478 	epd_pool = &phba->epd_pool;
3479 	qp = &phba->sli4_hba.hdwq[0];
3480 
3481 	spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3482 	spin_lock(&epd_pool->lock);
3483 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3484 				 &epd_pool->list, list) {
3485 		list_move_tail(&lpfc_ncmd->list,
3486 			       &qp->lpfc_io_buf_list_put);
3487 		lpfc_ncmd->flags = false;
3488 		qp->put_io_bufs++;
3489 		epd_pool->count--;
3490 	}
3491 	spin_unlock(&epd_pool->lock);
3492 	spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3493 }
3494 
3495 /**
3496  * lpfc_create_multixri_pools - create multi-XRI pools
3497  * @phba: pointer to lpfc hba data structure.
3498  *
3499  * This routine initialize public, private per HWQ. Then, move XRIs from
3500  * lpfc_io_buf_list_put to public pool. High and low watermark are also
3501  * Initialized.
3502  **/
3503 void lpfc_create_multixri_pools(struct lpfc_hba *phba)
3504 {
3505 	u32 i, j;
3506 	u32 hwq_count;
3507 	u32 count_per_hwq;
3508 	struct lpfc_io_buf *lpfc_ncmd;
3509 	struct lpfc_io_buf *lpfc_ncmd_next;
3510 	unsigned long iflag;
3511 	struct lpfc_sli4_hdw_queue *qp;
3512 	struct lpfc_multixri_pool *multixri_pool;
3513 	struct lpfc_pbl_pool *pbl_pool;
3514 	struct lpfc_pvt_pool *pvt_pool;
3515 
3516 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3517 			"1234 num_hdw_queue=%d num_present_cpu=%d common_xri_cnt=%d\n",
3518 			phba->cfg_hdw_queue, phba->sli4_hba.num_present_cpu,
3519 			phba->sli4_hba.io_xri_cnt);
3520 
3521 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
3522 		lpfc_create_expedite_pool(phba);
3523 
3524 	hwq_count = phba->cfg_hdw_queue;
3525 	count_per_hwq = phba->sli4_hba.io_xri_cnt / hwq_count;
3526 
3527 	for (i = 0; i < hwq_count; i++) {
3528 		multixri_pool = kzalloc(sizeof(*multixri_pool), GFP_KERNEL);
3529 
3530 		if (!multixri_pool) {
3531 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3532 					"1238 Failed to allocate memory for "
3533 					"multixri_pool\n");
3534 
3535 			if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
3536 				lpfc_destroy_expedite_pool(phba);
3537 
3538 			j = 0;
3539 			while (j < i) {
3540 				qp = &phba->sli4_hba.hdwq[j];
3541 				kfree(qp->p_multixri_pool);
3542 				j++;
3543 			}
3544 			phba->cfg_xri_rebalancing = 0;
3545 			return;
3546 		}
3547 
3548 		qp = &phba->sli4_hba.hdwq[i];
3549 		qp->p_multixri_pool = multixri_pool;
3550 
3551 		multixri_pool->xri_limit = count_per_hwq;
3552 		multixri_pool->rrb_next_hwqid = i;
3553 
3554 		/* Deal with public free xri pool */
3555 		pbl_pool = &multixri_pool->pbl_pool;
3556 		spin_lock_init(&pbl_pool->lock);
3557 		spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3558 		spin_lock(&pbl_pool->lock);
3559 		INIT_LIST_HEAD(&pbl_pool->list);
3560 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3561 					 &qp->lpfc_io_buf_list_put, list) {
3562 			list_move_tail(&lpfc_ncmd->list, &pbl_pool->list);
3563 			qp->put_io_bufs--;
3564 			pbl_pool->count++;
3565 		}
3566 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3567 				"1235 Moved %d buffers from PUT list over to pbl_pool[%d]\n",
3568 				pbl_pool->count, i);
3569 		spin_unlock(&pbl_pool->lock);
3570 		spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3571 
3572 		/* Deal with private free xri pool */
3573 		pvt_pool = &multixri_pool->pvt_pool;
3574 		pvt_pool->high_watermark = multixri_pool->xri_limit / 2;
3575 		pvt_pool->low_watermark = XRI_BATCH;
3576 		spin_lock_init(&pvt_pool->lock);
3577 		spin_lock_irqsave(&pvt_pool->lock, iflag);
3578 		INIT_LIST_HEAD(&pvt_pool->list);
3579 		pvt_pool->count = 0;
3580 		spin_unlock_irqrestore(&pvt_pool->lock, iflag);
3581 	}
3582 }
3583 
3584 /**
3585  * lpfc_destroy_multixri_pools - destroy multi-XRI pools
3586  * @phba: pointer to lpfc hba data structure.
3587  *
3588  * This routine returns XRIs from public/private to lpfc_io_buf_list_put.
3589  **/
3590 static void lpfc_destroy_multixri_pools(struct lpfc_hba *phba)
3591 {
3592 	u32 i;
3593 	u32 hwq_count;
3594 	struct lpfc_io_buf *lpfc_ncmd;
3595 	struct lpfc_io_buf *lpfc_ncmd_next;
3596 	unsigned long iflag;
3597 	struct lpfc_sli4_hdw_queue *qp;
3598 	struct lpfc_multixri_pool *multixri_pool;
3599 	struct lpfc_pbl_pool *pbl_pool;
3600 	struct lpfc_pvt_pool *pvt_pool;
3601 
3602 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
3603 		lpfc_destroy_expedite_pool(phba);
3604 
3605 	if (!(phba->pport->load_flag & FC_UNLOADING))
3606 		lpfc_sli_flush_io_rings(phba);
3607 
3608 	hwq_count = phba->cfg_hdw_queue;
3609 
3610 	for (i = 0; i < hwq_count; i++) {
3611 		qp = &phba->sli4_hba.hdwq[i];
3612 		multixri_pool = qp->p_multixri_pool;
3613 		if (!multixri_pool)
3614 			continue;
3615 
3616 		qp->p_multixri_pool = NULL;
3617 
3618 		spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3619 
3620 		/* Deal with public free xri pool */
3621 		pbl_pool = &multixri_pool->pbl_pool;
3622 		spin_lock(&pbl_pool->lock);
3623 
3624 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3625 				"1236 Moving %d buffers from pbl_pool[%d] TO PUT list\n",
3626 				pbl_pool->count, i);
3627 
3628 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3629 					 &pbl_pool->list, list) {
3630 			list_move_tail(&lpfc_ncmd->list,
3631 				       &qp->lpfc_io_buf_list_put);
3632 			qp->put_io_bufs++;
3633 			pbl_pool->count--;
3634 		}
3635 
3636 		INIT_LIST_HEAD(&pbl_pool->list);
3637 		pbl_pool->count = 0;
3638 
3639 		spin_unlock(&pbl_pool->lock);
3640 
3641 		/* Deal with private free xri pool */
3642 		pvt_pool = &multixri_pool->pvt_pool;
3643 		spin_lock(&pvt_pool->lock);
3644 
3645 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3646 				"1237 Moving %d buffers from pvt_pool[%d] TO PUT list\n",
3647 				pvt_pool->count, i);
3648 
3649 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3650 					 &pvt_pool->list, list) {
3651 			list_move_tail(&lpfc_ncmd->list,
3652 				       &qp->lpfc_io_buf_list_put);
3653 			qp->put_io_bufs++;
3654 			pvt_pool->count--;
3655 		}
3656 
3657 		INIT_LIST_HEAD(&pvt_pool->list);
3658 		pvt_pool->count = 0;
3659 
3660 		spin_unlock(&pvt_pool->lock);
3661 		spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3662 
3663 		kfree(multixri_pool);
3664 	}
3665 }
3666 
3667 /**
3668  * lpfc_online - Initialize and bring a HBA online
3669  * @phba: pointer to lpfc hba data structure.
3670  *
3671  * This routine initializes the HBA and brings a HBA online. During this
3672  * process, the management interface is blocked to prevent user space access
3673  * to the HBA interfering with the driver initialization.
3674  *
3675  * Return codes
3676  *   0 - successful
3677  *   1 - failed
3678  **/
3679 int
3680 lpfc_online(struct lpfc_hba *phba)
3681 {
3682 	struct lpfc_vport *vport;
3683 	struct lpfc_vport **vports;
3684 	int i, error = 0;
3685 	bool vpis_cleared = false;
3686 
3687 	if (!phba)
3688 		return 0;
3689 	vport = phba->pport;
3690 
3691 	if (!(vport->fc_flag & FC_OFFLINE_MODE))
3692 		return 0;
3693 
3694 	lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
3695 			"0458 Bring Adapter online\n");
3696 
3697 	lpfc_block_mgmt_io(phba, LPFC_MBX_WAIT);
3698 
3699 	if (phba->sli_rev == LPFC_SLI_REV4) {
3700 		if (lpfc_sli4_hba_setup(phba)) { /* Initialize SLI4 HBA */
3701 			lpfc_unblock_mgmt_io(phba);
3702 			return 1;
3703 		}
3704 		spin_lock_irq(&phba->hbalock);
3705 		if (!phba->sli4_hba.max_cfg_param.vpi_used)
3706 			vpis_cleared = true;
3707 		spin_unlock_irq(&phba->hbalock);
3708 
3709 		/* Reestablish the local initiator port.
3710 		 * The offline process destroyed the previous lport.
3711 		 */
3712 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME &&
3713 				!phba->nvmet_support) {
3714 			error = lpfc_nvme_create_localport(phba->pport);
3715 			if (error)
3716 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3717 					"6132 NVME restore reg failed "
3718 					"on nvmei error x%x\n", error);
3719 		}
3720 	} else {
3721 		lpfc_sli_queue_init(phba);
3722 		if (lpfc_sli_hba_setup(phba)) {	/* Initialize SLI2/SLI3 HBA */
3723 			lpfc_unblock_mgmt_io(phba);
3724 			return 1;
3725 		}
3726 	}
3727 
3728 	vports = lpfc_create_vport_work_array(phba);
3729 	if (vports != NULL) {
3730 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3731 			struct Scsi_Host *shost;
3732 			shost = lpfc_shost_from_vport(vports[i]);
3733 			spin_lock_irq(shost->host_lock);
3734 			vports[i]->fc_flag &= ~FC_OFFLINE_MODE;
3735 			if (phba->sli3_options & LPFC_SLI3_NPIV_ENABLED)
3736 				vports[i]->fc_flag |= FC_VPORT_NEEDS_REG_VPI;
3737 			if (phba->sli_rev == LPFC_SLI_REV4) {
3738 				vports[i]->fc_flag |= FC_VPORT_NEEDS_INIT_VPI;
3739 				if ((vpis_cleared) &&
3740 				    (vports[i]->port_type !=
3741 					LPFC_PHYSICAL_PORT))
3742 					vports[i]->vpi = 0;
3743 			}
3744 			spin_unlock_irq(shost->host_lock);
3745 		}
3746 	}
3747 	lpfc_destroy_vport_work_array(phba, vports);
3748 
3749 	if (phba->cfg_xri_rebalancing)
3750 		lpfc_create_multixri_pools(phba);
3751 
3752 	lpfc_cpuhp_add(phba);
3753 
3754 	lpfc_unblock_mgmt_io(phba);
3755 	return 0;
3756 }
3757 
3758 /**
3759  * lpfc_unblock_mgmt_io - Mark a HBA's management interface to be not blocked
3760  * @phba: pointer to lpfc hba data structure.
3761  *
3762  * This routine marks a HBA's management interface as not blocked. Once the
3763  * HBA's management interface is marked as not blocked, all the user space
3764  * access to the HBA, whether they are from sysfs interface or libdfc
3765  * interface will be allowed. The HBA is set to block the management interface
3766  * when the driver prepares the HBA interface for online or offline and then
3767  * set to unblock the management interface afterwards.
3768  **/
3769 void
3770 lpfc_unblock_mgmt_io(struct lpfc_hba * phba)
3771 {
3772 	unsigned long iflag;
3773 
3774 	spin_lock_irqsave(&phba->hbalock, iflag);
3775 	phba->sli.sli_flag &= ~LPFC_BLOCK_MGMT_IO;
3776 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3777 }
3778 
3779 /**
3780  * lpfc_offline_prep - Prepare a HBA to be brought offline
3781  * @phba: pointer to lpfc hba data structure.
3782  * @mbx_action: flag for mailbox shutdown action.
3783  *
3784  * This routine is invoked to prepare a HBA to be brought offline. It performs
3785  * unregistration login to all the nodes on all vports and flushes the mailbox
3786  * queue to make it ready to be brought offline.
3787  **/
3788 void
3789 lpfc_offline_prep(struct lpfc_hba *phba, int mbx_action)
3790 {
3791 	struct lpfc_vport *vport = phba->pport;
3792 	struct lpfc_nodelist  *ndlp, *next_ndlp;
3793 	struct lpfc_vport **vports;
3794 	struct Scsi_Host *shost;
3795 	int i;
3796 	int offline;
3797 	bool hba_pci_err;
3798 
3799 	if (vport->fc_flag & FC_OFFLINE_MODE)
3800 		return;
3801 
3802 	lpfc_block_mgmt_io(phba, mbx_action);
3803 
3804 	lpfc_linkdown(phba);
3805 
3806 	offline =  pci_channel_offline(phba->pcidev);
3807 	hba_pci_err = test_bit(HBA_PCI_ERR, &phba->bit_flags);
3808 
3809 	/* Issue an unreg_login to all nodes on all vports */
3810 	vports = lpfc_create_vport_work_array(phba);
3811 	if (vports != NULL) {
3812 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3813 			if (vports[i]->load_flag & FC_UNLOADING)
3814 				continue;
3815 			shost = lpfc_shost_from_vport(vports[i]);
3816 			spin_lock_irq(shost->host_lock);
3817 			vports[i]->vpi_state &= ~LPFC_VPI_REGISTERED;
3818 			vports[i]->fc_flag |= FC_VPORT_NEEDS_REG_VPI;
3819 			vports[i]->fc_flag &= ~FC_VFI_REGISTERED;
3820 			spin_unlock_irq(shost->host_lock);
3821 
3822 			shost =	lpfc_shost_from_vport(vports[i]);
3823 			list_for_each_entry_safe(ndlp, next_ndlp,
3824 						 &vports[i]->fc_nodes,
3825 						 nlp_listp) {
3826 
3827 				spin_lock_irq(&ndlp->lock);
3828 				ndlp->nlp_flag &= ~NLP_NPR_ADISC;
3829 				spin_unlock_irq(&ndlp->lock);
3830 
3831 				if (offline || hba_pci_err) {
3832 					spin_lock_irq(&ndlp->lock);
3833 					ndlp->nlp_flag &= ~(NLP_UNREG_INP |
3834 							    NLP_RPI_REGISTERED);
3835 					spin_unlock_irq(&ndlp->lock);
3836 					if (phba->sli_rev == LPFC_SLI_REV4)
3837 						lpfc_sli_rpi_release(vports[i],
3838 								     ndlp);
3839 				} else {
3840 					lpfc_unreg_rpi(vports[i], ndlp);
3841 				}
3842 				/*
3843 				 * Whenever an SLI4 port goes offline, free the
3844 				 * RPI. Get a new RPI when the adapter port
3845 				 * comes back online.
3846 				 */
3847 				if (phba->sli_rev == LPFC_SLI_REV4) {
3848 					lpfc_printf_vlog(vports[i], KERN_INFO,
3849 						 LOG_NODE | LOG_DISCOVERY,
3850 						 "0011 Free RPI x%x on "
3851 						 "ndlp: x%px did x%x\n",
3852 						 ndlp->nlp_rpi, ndlp,
3853 						 ndlp->nlp_DID);
3854 					lpfc_sli4_free_rpi(phba, ndlp->nlp_rpi);
3855 					ndlp->nlp_rpi = LPFC_RPI_ALLOC_ERROR;
3856 				}
3857 
3858 				if (ndlp->nlp_type & NLP_FABRIC) {
3859 					lpfc_disc_state_machine(vports[i], ndlp,
3860 						NULL, NLP_EVT_DEVICE_RECOVERY);
3861 
3862 					/* Don't remove the node unless the node
3863 					 * has been unregistered with the
3864 					 * transport, and we're not in recovery
3865 					 * before dev_loss_tmo triggered.
3866 					 * Otherwise, let dev_loss take care of
3867 					 * the node.
3868 					 */
3869 					if (!(ndlp->save_flags &
3870 					      NLP_IN_RECOV_POST_DEV_LOSS) &&
3871 					    !(ndlp->fc4_xpt_flags &
3872 					      (NVME_XPT_REGD | SCSI_XPT_REGD)))
3873 						lpfc_disc_state_machine
3874 							(vports[i], ndlp,
3875 							 NULL,
3876 							 NLP_EVT_DEVICE_RM);
3877 				}
3878 			}
3879 		}
3880 	}
3881 	lpfc_destroy_vport_work_array(phba, vports);
3882 
3883 	lpfc_sli_mbox_sys_shutdown(phba, mbx_action);
3884 
3885 	if (phba->wq)
3886 		flush_workqueue(phba->wq);
3887 }
3888 
3889 /**
3890  * lpfc_offline - Bring a HBA offline
3891  * @phba: pointer to lpfc hba data structure.
3892  *
3893  * This routine actually brings a HBA offline. It stops all the timers
3894  * associated with the HBA, brings down the SLI layer, and eventually
3895  * marks the HBA as in offline state for the upper layer protocol.
3896  **/
3897 void
3898 lpfc_offline(struct lpfc_hba *phba)
3899 {
3900 	struct Scsi_Host  *shost;
3901 	struct lpfc_vport **vports;
3902 	int i;
3903 
3904 	if (phba->pport->fc_flag & FC_OFFLINE_MODE)
3905 		return;
3906 
3907 	/* stop port and all timers associated with this hba */
3908 	lpfc_stop_port(phba);
3909 
3910 	/* Tear down the local and target port registrations.  The
3911 	 * nvme transports need to cleanup.
3912 	 */
3913 	lpfc_nvmet_destroy_targetport(phba);
3914 	lpfc_nvme_destroy_localport(phba->pport);
3915 
3916 	vports = lpfc_create_vport_work_array(phba);
3917 	if (vports != NULL)
3918 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++)
3919 			lpfc_stop_vport_timers(vports[i]);
3920 	lpfc_destroy_vport_work_array(phba, vports);
3921 	lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
3922 			"0460 Bring Adapter offline\n");
3923 	/* Bring down the SLI Layer and cleanup.  The HBA is offline
3924 	   now.  */
3925 	lpfc_sli_hba_down(phba);
3926 	spin_lock_irq(&phba->hbalock);
3927 	phba->work_ha = 0;
3928 	spin_unlock_irq(&phba->hbalock);
3929 	vports = lpfc_create_vport_work_array(phba);
3930 	if (vports != NULL)
3931 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3932 			shost = lpfc_shost_from_vport(vports[i]);
3933 			spin_lock_irq(shost->host_lock);
3934 			vports[i]->work_port_events = 0;
3935 			vports[i]->fc_flag |= FC_OFFLINE_MODE;
3936 			spin_unlock_irq(shost->host_lock);
3937 		}
3938 	lpfc_destroy_vport_work_array(phba, vports);
3939 	/* If OFFLINE flag is clear (i.e. unloading), cpuhp removal is handled
3940 	 * in hba_unset
3941 	 */
3942 	if (phba->pport->fc_flag & FC_OFFLINE_MODE)
3943 		__lpfc_cpuhp_remove(phba);
3944 
3945 	if (phba->cfg_xri_rebalancing)
3946 		lpfc_destroy_multixri_pools(phba);
3947 }
3948 
3949 /**
3950  * lpfc_scsi_free - Free all the SCSI buffers and IOCBs from driver lists
3951  * @phba: pointer to lpfc hba data structure.
3952  *
3953  * This routine is to free all the SCSI buffers and IOCBs from the driver
3954  * list back to kernel. It is called from lpfc_pci_remove_one to free
3955  * the internal resources before the device is removed from the system.
3956  **/
3957 static void
3958 lpfc_scsi_free(struct lpfc_hba *phba)
3959 {
3960 	struct lpfc_io_buf *sb, *sb_next;
3961 
3962 	if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP))
3963 		return;
3964 
3965 	spin_lock_irq(&phba->hbalock);
3966 
3967 	/* Release all the lpfc_scsi_bufs maintained by this host. */
3968 
3969 	spin_lock(&phba->scsi_buf_list_put_lock);
3970 	list_for_each_entry_safe(sb, sb_next, &phba->lpfc_scsi_buf_list_put,
3971 				 list) {
3972 		list_del(&sb->list);
3973 		dma_pool_free(phba->lpfc_sg_dma_buf_pool, sb->data,
3974 			      sb->dma_handle);
3975 		kfree(sb);
3976 		phba->total_scsi_bufs--;
3977 	}
3978 	spin_unlock(&phba->scsi_buf_list_put_lock);
3979 
3980 	spin_lock(&phba->scsi_buf_list_get_lock);
3981 	list_for_each_entry_safe(sb, sb_next, &phba->lpfc_scsi_buf_list_get,
3982 				 list) {
3983 		list_del(&sb->list);
3984 		dma_pool_free(phba->lpfc_sg_dma_buf_pool, sb->data,
3985 			      sb->dma_handle);
3986 		kfree(sb);
3987 		phba->total_scsi_bufs--;
3988 	}
3989 	spin_unlock(&phba->scsi_buf_list_get_lock);
3990 	spin_unlock_irq(&phba->hbalock);
3991 }
3992 
3993 /**
3994  * lpfc_io_free - Free all the IO buffers and IOCBs from driver lists
3995  * @phba: pointer to lpfc hba data structure.
3996  *
3997  * This routine is to free all the IO buffers and IOCBs from the driver
3998  * list back to kernel. It is called from lpfc_pci_remove_one to free
3999  * the internal resources before the device is removed from the system.
4000  **/
4001 void
4002 lpfc_io_free(struct lpfc_hba *phba)
4003 {
4004 	struct lpfc_io_buf *lpfc_ncmd, *lpfc_ncmd_next;
4005 	struct lpfc_sli4_hdw_queue *qp;
4006 	int idx;
4007 
4008 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
4009 		qp = &phba->sli4_hba.hdwq[idx];
4010 		/* Release all the lpfc_nvme_bufs maintained by this host. */
4011 		spin_lock(&qp->io_buf_list_put_lock);
4012 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
4013 					 &qp->lpfc_io_buf_list_put,
4014 					 list) {
4015 			list_del(&lpfc_ncmd->list);
4016 			qp->put_io_bufs--;
4017 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4018 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4019 			if (phba->cfg_xpsgl && !phba->nvmet_support)
4020 				lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
4021 			lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
4022 			kfree(lpfc_ncmd);
4023 			qp->total_io_bufs--;
4024 		}
4025 		spin_unlock(&qp->io_buf_list_put_lock);
4026 
4027 		spin_lock(&qp->io_buf_list_get_lock);
4028 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
4029 					 &qp->lpfc_io_buf_list_get,
4030 					 list) {
4031 			list_del(&lpfc_ncmd->list);
4032 			qp->get_io_bufs--;
4033 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4034 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4035 			if (phba->cfg_xpsgl && !phba->nvmet_support)
4036 				lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
4037 			lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
4038 			kfree(lpfc_ncmd);
4039 			qp->total_io_bufs--;
4040 		}
4041 		spin_unlock(&qp->io_buf_list_get_lock);
4042 	}
4043 }
4044 
4045 /**
4046  * lpfc_sli4_els_sgl_update - update ELS xri-sgl sizing and mapping
4047  * @phba: pointer to lpfc hba data structure.
4048  *
4049  * This routine first calculates the sizes of the current els and allocated
4050  * scsi sgl lists, and then goes through all sgls to updates the physical
4051  * XRIs assigned due to port function reset. During port initialization, the
4052  * current els and allocated scsi sgl lists are 0s.
4053  *
4054  * Return codes
4055  *   0 - successful (for now, it always returns 0)
4056  **/
4057 int
4058 lpfc_sli4_els_sgl_update(struct lpfc_hba *phba)
4059 {
4060 	struct lpfc_sglq *sglq_entry = NULL, *sglq_entry_next = NULL;
4061 	uint16_t i, lxri, xri_cnt, els_xri_cnt;
4062 	LIST_HEAD(els_sgl_list);
4063 	int rc;
4064 
4065 	/*
4066 	 * update on pci function's els xri-sgl list
4067 	 */
4068 	els_xri_cnt = lpfc_sli4_get_els_iocb_cnt(phba);
4069 
4070 	if (els_xri_cnt > phba->sli4_hba.els_xri_cnt) {
4071 		/* els xri-sgl expanded */
4072 		xri_cnt = els_xri_cnt - phba->sli4_hba.els_xri_cnt;
4073 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4074 				"3157 ELS xri-sgl count increased from "
4075 				"%d to %d\n", phba->sli4_hba.els_xri_cnt,
4076 				els_xri_cnt);
4077 		/* allocate the additional els sgls */
4078 		for (i = 0; i < xri_cnt; i++) {
4079 			sglq_entry = kzalloc(sizeof(struct lpfc_sglq),
4080 					     GFP_KERNEL);
4081 			if (sglq_entry == NULL) {
4082 				lpfc_printf_log(phba, KERN_ERR,
4083 						LOG_TRACE_EVENT,
4084 						"2562 Failure to allocate an "
4085 						"ELS sgl entry:%d\n", i);
4086 				rc = -ENOMEM;
4087 				goto out_free_mem;
4088 			}
4089 			sglq_entry->buff_type = GEN_BUFF_TYPE;
4090 			sglq_entry->virt = lpfc_mbuf_alloc(phba, 0,
4091 							   &sglq_entry->phys);
4092 			if (sglq_entry->virt == NULL) {
4093 				kfree(sglq_entry);
4094 				lpfc_printf_log(phba, KERN_ERR,
4095 						LOG_TRACE_EVENT,
4096 						"2563 Failure to allocate an "
4097 						"ELS mbuf:%d\n", i);
4098 				rc = -ENOMEM;
4099 				goto out_free_mem;
4100 			}
4101 			sglq_entry->sgl = sglq_entry->virt;
4102 			memset(sglq_entry->sgl, 0, LPFC_BPL_SIZE);
4103 			sglq_entry->state = SGL_FREED;
4104 			list_add_tail(&sglq_entry->list, &els_sgl_list);
4105 		}
4106 		spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
4107 		list_splice_init(&els_sgl_list,
4108 				 &phba->sli4_hba.lpfc_els_sgl_list);
4109 		spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
4110 	} else if (els_xri_cnt < phba->sli4_hba.els_xri_cnt) {
4111 		/* els xri-sgl shrinked */
4112 		xri_cnt = phba->sli4_hba.els_xri_cnt - els_xri_cnt;
4113 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4114 				"3158 ELS xri-sgl count decreased from "
4115 				"%d to %d\n", phba->sli4_hba.els_xri_cnt,
4116 				els_xri_cnt);
4117 		spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
4118 		list_splice_init(&phba->sli4_hba.lpfc_els_sgl_list,
4119 				 &els_sgl_list);
4120 		/* release extra els sgls from list */
4121 		for (i = 0; i < xri_cnt; i++) {
4122 			list_remove_head(&els_sgl_list,
4123 					 sglq_entry, struct lpfc_sglq, list);
4124 			if (sglq_entry) {
4125 				__lpfc_mbuf_free(phba, sglq_entry->virt,
4126 						 sglq_entry->phys);
4127 				kfree(sglq_entry);
4128 			}
4129 		}
4130 		list_splice_init(&els_sgl_list,
4131 				 &phba->sli4_hba.lpfc_els_sgl_list);
4132 		spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
4133 	} else
4134 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4135 				"3163 ELS xri-sgl count unchanged: %d\n",
4136 				els_xri_cnt);
4137 	phba->sli4_hba.els_xri_cnt = els_xri_cnt;
4138 
4139 	/* update xris to els sgls on the list */
4140 	sglq_entry = NULL;
4141 	sglq_entry_next = NULL;
4142 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
4143 				 &phba->sli4_hba.lpfc_els_sgl_list, list) {
4144 		lxri = lpfc_sli4_next_xritag(phba);
4145 		if (lxri == NO_XRI) {
4146 			lpfc_printf_log(phba, KERN_ERR,
4147 					LOG_TRACE_EVENT,
4148 					"2400 Failed to allocate xri for "
4149 					"ELS sgl\n");
4150 			rc = -ENOMEM;
4151 			goto out_free_mem;
4152 		}
4153 		sglq_entry->sli4_lxritag = lxri;
4154 		sglq_entry->sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4155 	}
4156 	return 0;
4157 
4158 out_free_mem:
4159 	lpfc_free_els_sgl_list(phba);
4160 	return rc;
4161 }
4162 
4163 /**
4164  * lpfc_sli4_nvmet_sgl_update - update xri-sgl sizing and mapping
4165  * @phba: pointer to lpfc hba data structure.
4166  *
4167  * This routine first calculates the sizes of the current els and allocated
4168  * scsi sgl lists, and then goes through all sgls to updates the physical
4169  * XRIs assigned due to port function reset. During port initialization, the
4170  * current els and allocated scsi sgl lists are 0s.
4171  *
4172  * Return codes
4173  *   0 - successful (for now, it always returns 0)
4174  **/
4175 int
4176 lpfc_sli4_nvmet_sgl_update(struct lpfc_hba *phba)
4177 {
4178 	struct lpfc_sglq *sglq_entry = NULL, *sglq_entry_next = NULL;
4179 	uint16_t i, lxri, xri_cnt, els_xri_cnt;
4180 	uint16_t nvmet_xri_cnt;
4181 	LIST_HEAD(nvmet_sgl_list);
4182 	int rc;
4183 
4184 	/*
4185 	 * update on pci function's nvmet xri-sgl list
4186 	 */
4187 	els_xri_cnt = lpfc_sli4_get_els_iocb_cnt(phba);
4188 
4189 	/* For NVMET, ALL remaining XRIs are dedicated for IO processing */
4190 	nvmet_xri_cnt = phba->sli4_hba.max_cfg_param.max_xri - els_xri_cnt;
4191 	if (nvmet_xri_cnt > phba->sli4_hba.nvmet_xri_cnt) {
4192 		/* els xri-sgl expanded */
4193 		xri_cnt = nvmet_xri_cnt - phba->sli4_hba.nvmet_xri_cnt;
4194 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4195 				"6302 NVMET xri-sgl cnt grew from %d to %d\n",
4196 				phba->sli4_hba.nvmet_xri_cnt, nvmet_xri_cnt);
4197 		/* allocate the additional nvmet sgls */
4198 		for (i = 0; i < xri_cnt; i++) {
4199 			sglq_entry = kzalloc(sizeof(struct lpfc_sglq),
4200 					     GFP_KERNEL);
4201 			if (sglq_entry == NULL) {
4202 				lpfc_printf_log(phba, KERN_ERR,
4203 						LOG_TRACE_EVENT,
4204 						"6303 Failure to allocate an "
4205 						"NVMET sgl entry:%d\n", i);
4206 				rc = -ENOMEM;
4207 				goto out_free_mem;
4208 			}
4209 			sglq_entry->buff_type = NVMET_BUFF_TYPE;
4210 			sglq_entry->virt = lpfc_nvmet_buf_alloc(phba, 0,
4211 							   &sglq_entry->phys);
4212 			if (sglq_entry->virt == NULL) {
4213 				kfree(sglq_entry);
4214 				lpfc_printf_log(phba, KERN_ERR,
4215 						LOG_TRACE_EVENT,
4216 						"6304 Failure to allocate an "
4217 						"NVMET buf:%d\n", i);
4218 				rc = -ENOMEM;
4219 				goto out_free_mem;
4220 			}
4221 			sglq_entry->sgl = sglq_entry->virt;
4222 			memset(sglq_entry->sgl, 0,
4223 			       phba->cfg_sg_dma_buf_size);
4224 			sglq_entry->state = SGL_FREED;
4225 			list_add_tail(&sglq_entry->list, &nvmet_sgl_list);
4226 		}
4227 		spin_lock_irq(&phba->hbalock);
4228 		spin_lock(&phba->sli4_hba.sgl_list_lock);
4229 		list_splice_init(&nvmet_sgl_list,
4230 				 &phba->sli4_hba.lpfc_nvmet_sgl_list);
4231 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
4232 		spin_unlock_irq(&phba->hbalock);
4233 	} else if (nvmet_xri_cnt < phba->sli4_hba.nvmet_xri_cnt) {
4234 		/* nvmet xri-sgl shrunk */
4235 		xri_cnt = phba->sli4_hba.nvmet_xri_cnt - nvmet_xri_cnt;
4236 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4237 				"6305 NVMET xri-sgl count decreased from "
4238 				"%d to %d\n", phba->sli4_hba.nvmet_xri_cnt,
4239 				nvmet_xri_cnt);
4240 		spin_lock_irq(&phba->hbalock);
4241 		spin_lock(&phba->sli4_hba.sgl_list_lock);
4242 		list_splice_init(&phba->sli4_hba.lpfc_nvmet_sgl_list,
4243 				 &nvmet_sgl_list);
4244 		/* release extra nvmet sgls from list */
4245 		for (i = 0; i < xri_cnt; i++) {
4246 			list_remove_head(&nvmet_sgl_list,
4247 					 sglq_entry, struct lpfc_sglq, list);
4248 			if (sglq_entry) {
4249 				lpfc_nvmet_buf_free(phba, sglq_entry->virt,
4250 						    sglq_entry->phys);
4251 				kfree(sglq_entry);
4252 			}
4253 		}
4254 		list_splice_init(&nvmet_sgl_list,
4255 				 &phba->sli4_hba.lpfc_nvmet_sgl_list);
4256 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
4257 		spin_unlock_irq(&phba->hbalock);
4258 	} else
4259 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4260 				"6306 NVMET xri-sgl count unchanged: %d\n",
4261 				nvmet_xri_cnt);
4262 	phba->sli4_hba.nvmet_xri_cnt = nvmet_xri_cnt;
4263 
4264 	/* update xris to nvmet sgls on the list */
4265 	sglq_entry = NULL;
4266 	sglq_entry_next = NULL;
4267 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
4268 				 &phba->sli4_hba.lpfc_nvmet_sgl_list, list) {
4269 		lxri = lpfc_sli4_next_xritag(phba);
4270 		if (lxri == NO_XRI) {
4271 			lpfc_printf_log(phba, KERN_ERR,
4272 					LOG_TRACE_EVENT,
4273 					"6307 Failed to allocate xri for "
4274 					"NVMET sgl\n");
4275 			rc = -ENOMEM;
4276 			goto out_free_mem;
4277 		}
4278 		sglq_entry->sli4_lxritag = lxri;
4279 		sglq_entry->sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4280 	}
4281 	return 0;
4282 
4283 out_free_mem:
4284 	lpfc_free_nvmet_sgl_list(phba);
4285 	return rc;
4286 }
4287 
4288 int
4289 lpfc_io_buf_flush(struct lpfc_hba *phba, struct list_head *cbuf)
4290 {
4291 	LIST_HEAD(blist);
4292 	struct lpfc_sli4_hdw_queue *qp;
4293 	struct lpfc_io_buf *lpfc_cmd;
4294 	struct lpfc_io_buf *iobufp, *prev_iobufp;
4295 	int idx, cnt, xri, inserted;
4296 
4297 	cnt = 0;
4298 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
4299 		qp = &phba->sli4_hba.hdwq[idx];
4300 		spin_lock_irq(&qp->io_buf_list_get_lock);
4301 		spin_lock(&qp->io_buf_list_put_lock);
4302 
4303 		/* Take everything off the get and put lists */
4304 		list_splice_init(&qp->lpfc_io_buf_list_get, &blist);
4305 		list_splice(&qp->lpfc_io_buf_list_put, &blist);
4306 		INIT_LIST_HEAD(&qp->lpfc_io_buf_list_get);
4307 		INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
4308 		cnt += qp->get_io_bufs + qp->put_io_bufs;
4309 		qp->get_io_bufs = 0;
4310 		qp->put_io_bufs = 0;
4311 		qp->total_io_bufs = 0;
4312 		spin_unlock(&qp->io_buf_list_put_lock);
4313 		spin_unlock_irq(&qp->io_buf_list_get_lock);
4314 	}
4315 
4316 	/*
4317 	 * Take IO buffers off blist and put on cbuf sorted by XRI.
4318 	 * This is because POST_SGL takes a sequential range of XRIs
4319 	 * to post to the firmware.
4320 	 */
4321 	for (idx = 0; idx < cnt; idx++) {
4322 		list_remove_head(&blist, lpfc_cmd, struct lpfc_io_buf, list);
4323 		if (!lpfc_cmd)
4324 			return cnt;
4325 		if (idx == 0) {
4326 			list_add_tail(&lpfc_cmd->list, cbuf);
4327 			continue;
4328 		}
4329 		xri = lpfc_cmd->cur_iocbq.sli4_xritag;
4330 		inserted = 0;
4331 		prev_iobufp = NULL;
4332 		list_for_each_entry(iobufp, cbuf, list) {
4333 			if (xri < iobufp->cur_iocbq.sli4_xritag) {
4334 				if (prev_iobufp)
4335 					list_add(&lpfc_cmd->list,
4336 						 &prev_iobufp->list);
4337 				else
4338 					list_add(&lpfc_cmd->list, cbuf);
4339 				inserted = 1;
4340 				break;
4341 			}
4342 			prev_iobufp = iobufp;
4343 		}
4344 		if (!inserted)
4345 			list_add_tail(&lpfc_cmd->list, cbuf);
4346 	}
4347 	return cnt;
4348 }
4349 
4350 int
4351 lpfc_io_buf_replenish(struct lpfc_hba *phba, struct list_head *cbuf)
4352 {
4353 	struct lpfc_sli4_hdw_queue *qp;
4354 	struct lpfc_io_buf *lpfc_cmd;
4355 	int idx, cnt;
4356 
4357 	qp = phba->sli4_hba.hdwq;
4358 	cnt = 0;
4359 	while (!list_empty(cbuf)) {
4360 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
4361 			list_remove_head(cbuf, lpfc_cmd,
4362 					 struct lpfc_io_buf, list);
4363 			if (!lpfc_cmd)
4364 				return cnt;
4365 			cnt++;
4366 			qp = &phba->sli4_hba.hdwq[idx];
4367 			lpfc_cmd->hdwq_no = idx;
4368 			lpfc_cmd->hdwq = qp;
4369 			lpfc_cmd->cur_iocbq.cmd_cmpl = NULL;
4370 			spin_lock(&qp->io_buf_list_put_lock);
4371 			list_add_tail(&lpfc_cmd->list,
4372 				      &qp->lpfc_io_buf_list_put);
4373 			qp->put_io_bufs++;
4374 			qp->total_io_bufs++;
4375 			spin_unlock(&qp->io_buf_list_put_lock);
4376 		}
4377 	}
4378 	return cnt;
4379 }
4380 
4381 /**
4382  * lpfc_sli4_io_sgl_update - update xri-sgl sizing and mapping
4383  * @phba: pointer to lpfc hba data structure.
4384  *
4385  * This routine first calculates the sizes of the current els and allocated
4386  * scsi sgl lists, and then goes through all sgls to updates the physical
4387  * XRIs assigned due to port function reset. During port initialization, the
4388  * current els and allocated scsi sgl lists are 0s.
4389  *
4390  * Return codes
4391  *   0 - successful (for now, it always returns 0)
4392  **/
4393 int
4394 lpfc_sli4_io_sgl_update(struct lpfc_hba *phba)
4395 {
4396 	struct lpfc_io_buf *lpfc_ncmd = NULL, *lpfc_ncmd_next = NULL;
4397 	uint16_t i, lxri, els_xri_cnt;
4398 	uint16_t io_xri_cnt, io_xri_max;
4399 	LIST_HEAD(io_sgl_list);
4400 	int rc, cnt;
4401 
4402 	/*
4403 	 * update on pci function's allocated nvme xri-sgl list
4404 	 */
4405 
4406 	/* maximum number of xris available for nvme buffers */
4407 	els_xri_cnt = lpfc_sli4_get_els_iocb_cnt(phba);
4408 	io_xri_max = phba->sli4_hba.max_cfg_param.max_xri - els_xri_cnt;
4409 	phba->sli4_hba.io_xri_max = io_xri_max;
4410 
4411 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4412 			"6074 Current allocated XRI sgl count:%d, "
4413 			"maximum XRI count:%d els_xri_cnt:%d\n\n",
4414 			phba->sli4_hba.io_xri_cnt,
4415 			phba->sli4_hba.io_xri_max,
4416 			els_xri_cnt);
4417 
4418 	cnt = lpfc_io_buf_flush(phba, &io_sgl_list);
4419 
4420 	if (phba->sli4_hba.io_xri_cnt > phba->sli4_hba.io_xri_max) {
4421 		/* max nvme xri shrunk below the allocated nvme buffers */
4422 		io_xri_cnt = phba->sli4_hba.io_xri_cnt -
4423 					phba->sli4_hba.io_xri_max;
4424 		/* release the extra allocated nvme buffers */
4425 		for (i = 0; i < io_xri_cnt; i++) {
4426 			list_remove_head(&io_sgl_list, lpfc_ncmd,
4427 					 struct lpfc_io_buf, list);
4428 			if (lpfc_ncmd) {
4429 				dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4430 					      lpfc_ncmd->data,
4431 					      lpfc_ncmd->dma_handle);
4432 				kfree(lpfc_ncmd);
4433 			}
4434 		}
4435 		phba->sli4_hba.io_xri_cnt -= io_xri_cnt;
4436 	}
4437 
4438 	/* update xris associated to remaining allocated nvme buffers */
4439 	lpfc_ncmd = NULL;
4440 	lpfc_ncmd_next = NULL;
4441 	phba->sli4_hba.io_xri_cnt = cnt;
4442 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
4443 				 &io_sgl_list, list) {
4444 		lxri = lpfc_sli4_next_xritag(phba);
4445 		if (lxri == NO_XRI) {
4446 			lpfc_printf_log(phba, KERN_ERR,
4447 					LOG_TRACE_EVENT,
4448 					"6075 Failed to allocate xri for "
4449 					"nvme buffer\n");
4450 			rc = -ENOMEM;
4451 			goto out_free_mem;
4452 		}
4453 		lpfc_ncmd->cur_iocbq.sli4_lxritag = lxri;
4454 		lpfc_ncmd->cur_iocbq.sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4455 	}
4456 	cnt = lpfc_io_buf_replenish(phba, &io_sgl_list);
4457 	return 0;
4458 
4459 out_free_mem:
4460 	lpfc_io_free(phba);
4461 	return rc;
4462 }
4463 
4464 /**
4465  * lpfc_new_io_buf - IO buffer allocator for HBA with SLI4 IF spec
4466  * @phba: Pointer to lpfc hba data structure.
4467  * @num_to_alloc: The requested number of buffers to allocate.
4468  *
4469  * This routine allocates nvme buffers for device with SLI-4 interface spec,
4470  * the nvme buffer contains all the necessary information needed to initiate
4471  * an I/O. After allocating up to @num_to_allocate IO buffers and put
4472  * them on a list, it post them to the port by using SGL block post.
4473  *
4474  * Return codes:
4475  *   int - number of IO buffers that were allocated and posted.
4476  *   0 = failure, less than num_to_alloc is a partial failure.
4477  **/
4478 int
4479 lpfc_new_io_buf(struct lpfc_hba *phba, int num_to_alloc)
4480 {
4481 	struct lpfc_io_buf *lpfc_ncmd;
4482 	struct lpfc_iocbq *pwqeq;
4483 	uint16_t iotag, lxri = 0;
4484 	int bcnt, num_posted;
4485 	LIST_HEAD(prep_nblist);
4486 	LIST_HEAD(post_nblist);
4487 	LIST_HEAD(nvme_nblist);
4488 
4489 	phba->sli4_hba.io_xri_cnt = 0;
4490 	for (bcnt = 0; bcnt < num_to_alloc; bcnt++) {
4491 		lpfc_ncmd = kzalloc(sizeof(*lpfc_ncmd), GFP_KERNEL);
4492 		if (!lpfc_ncmd)
4493 			break;
4494 		/*
4495 		 * Get memory from the pci pool to map the virt space to
4496 		 * pci bus space for an I/O. The DMA buffer includes the
4497 		 * number of SGE's necessary to support the sg_tablesize.
4498 		 */
4499 		lpfc_ncmd->data = dma_pool_zalloc(phba->lpfc_sg_dma_buf_pool,
4500 						  GFP_KERNEL,
4501 						  &lpfc_ncmd->dma_handle);
4502 		if (!lpfc_ncmd->data) {
4503 			kfree(lpfc_ncmd);
4504 			break;
4505 		}
4506 
4507 		if (phba->cfg_xpsgl && !phba->nvmet_support) {
4508 			INIT_LIST_HEAD(&lpfc_ncmd->dma_sgl_xtra_list);
4509 		} else {
4510 			/*
4511 			 * 4K Page alignment is CRITICAL to BlockGuard, double
4512 			 * check to be sure.
4513 			 */
4514 			if ((phba->sli3_options & LPFC_SLI3_BG_ENABLED) &&
4515 			    (((unsigned long)(lpfc_ncmd->data) &
4516 			    (unsigned long)(SLI4_PAGE_SIZE - 1)) != 0)) {
4517 				lpfc_printf_log(phba, KERN_ERR,
4518 						LOG_TRACE_EVENT,
4519 						"3369 Memory alignment err: "
4520 						"addr=%lx\n",
4521 						(unsigned long)lpfc_ncmd->data);
4522 				dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4523 					      lpfc_ncmd->data,
4524 					      lpfc_ncmd->dma_handle);
4525 				kfree(lpfc_ncmd);
4526 				break;
4527 			}
4528 		}
4529 
4530 		INIT_LIST_HEAD(&lpfc_ncmd->dma_cmd_rsp_list);
4531 
4532 		lxri = lpfc_sli4_next_xritag(phba);
4533 		if (lxri == NO_XRI) {
4534 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4535 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4536 			kfree(lpfc_ncmd);
4537 			break;
4538 		}
4539 		pwqeq = &lpfc_ncmd->cur_iocbq;
4540 
4541 		/* Allocate iotag for lpfc_ncmd->cur_iocbq. */
4542 		iotag = lpfc_sli_next_iotag(phba, pwqeq);
4543 		if (iotag == 0) {
4544 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4545 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4546 			kfree(lpfc_ncmd);
4547 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4548 					"6121 Failed to allocate IOTAG for"
4549 					" XRI:0x%x\n", lxri);
4550 			lpfc_sli4_free_xri(phba, lxri);
4551 			break;
4552 		}
4553 		pwqeq->sli4_lxritag = lxri;
4554 		pwqeq->sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4555 
4556 		/* Initialize local short-hand pointers. */
4557 		lpfc_ncmd->dma_sgl = lpfc_ncmd->data;
4558 		lpfc_ncmd->dma_phys_sgl = lpfc_ncmd->dma_handle;
4559 		lpfc_ncmd->cur_iocbq.io_buf = lpfc_ncmd;
4560 		spin_lock_init(&lpfc_ncmd->buf_lock);
4561 
4562 		/* add the nvme buffer to a post list */
4563 		list_add_tail(&lpfc_ncmd->list, &post_nblist);
4564 		phba->sli4_hba.io_xri_cnt++;
4565 	}
4566 	lpfc_printf_log(phba, KERN_INFO, LOG_NVME,
4567 			"6114 Allocate %d out of %d requested new NVME "
4568 			"buffers of size x%zu bytes\n", bcnt, num_to_alloc,
4569 			sizeof(*lpfc_ncmd));
4570 
4571 
4572 	/* post the list of nvme buffer sgls to port if available */
4573 	if (!list_empty(&post_nblist))
4574 		num_posted = lpfc_sli4_post_io_sgl_list(
4575 				phba, &post_nblist, bcnt);
4576 	else
4577 		num_posted = 0;
4578 
4579 	return num_posted;
4580 }
4581 
4582 static uint64_t
4583 lpfc_get_wwpn(struct lpfc_hba *phba)
4584 {
4585 	uint64_t wwn;
4586 	int rc;
4587 	LPFC_MBOXQ_t *mboxq;
4588 	MAILBOX_t *mb;
4589 
4590 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
4591 						GFP_KERNEL);
4592 	if (!mboxq)
4593 		return (uint64_t)-1;
4594 
4595 	/* First get WWN of HBA instance */
4596 	lpfc_read_nv(phba, mboxq);
4597 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
4598 	if (rc != MBX_SUCCESS) {
4599 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4600 				"6019 Mailbox failed , mbxCmd x%x "
4601 				"READ_NV, mbxStatus x%x\n",
4602 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
4603 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
4604 		mempool_free(mboxq, phba->mbox_mem_pool);
4605 		return (uint64_t) -1;
4606 	}
4607 	mb = &mboxq->u.mb;
4608 	memcpy(&wwn, (char *)mb->un.varRDnvp.portname, sizeof(uint64_t));
4609 	/* wwn is WWPN of HBA instance */
4610 	mempool_free(mboxq, phba->mbox_mem_pool);
4611 	if (phba->sli_rev == LPFC_SLI_REV4)
4612 		return be64_to_cpu(wwn);
4613 	else
4614 		return rol64(wwn, 32);
4615 }
4616 
4617 /**
4618  * lpfc_vmid_res_alloc - Allocates resources for VMID
4619  * @phba: pointer to lpfc hba data structure.
4620  * @vport: pointer to vport data structure
4621  *
4622  * This routine allocated the resources needed for the VMID.
4623  *
4624  * Return codes
4625  *	0 on Success
4626  *	Non-0 on Failure
4627  */
4628 static int
4629 lpfc_vmid_res_alloc(struct lpfc_hba *phba, struct lpfc_vport *vport)
4630 {
4631 	/* VMID feature is supported only on SLI4 */
4632 	if (phba->sli_rev == LPFC_SLI_REV3) {
4633 		phba->cfg_vmid_app_header = 0;
4634 		phba->cfg_vmid_priority_tagging = 0;
4635 	}
4636 
4637 	if (lpfc_is_vmid_enabled(phba)) {
4638 		vport->vmid =
4639 		    kcalloc(phba->cfg_max_vmid, sizeof(struct lpfc_vmid),
4640 			    GFP_KERNEL);
4641 		if (!vport->vmid)
4642 			return -ENOMEM;
4643 
4644 		rwlock_init(&vport->vmid_lock);
4645 
4646 		/* Set the VMID parameters for the vport */
4647 		vport->vmid_priority_tagging = phba->cfg_vmid_priority_tagging;
4648 		vport->vmid_inactivity_timeout =
4649 		    phba->cfg_vmid_inactivity_timeout;
4650 		vport->max_vmid = phba->cfg_max_vmid;
4651 		vport->cur_vmid_cnt = 0;
4652 
4653 		vport->vmid_priority_range = bitmap_zalloc
4654 			(LPFC_VMID_MAX_PRIORITY_RANGE, GFP_KERNEL);
4655 
4656 		if (!vport->vmid_priority_range) {
4657 			kfree(vport->vmid);
4658 			return -ENOMEM;
4659 		}
4660 
4661 		hash_init(vport->hash_table);
4662 	}
4663 	return 0;
4664 }
4665 
4666 /**
4667  * lpfc_create_port - Create an FC port
4668  * @phba: pointer to lpfc hba data structure.
4669  * @instance: a unique integer ID to this FC port.
4670  * @dev: pointer to the device data structure.
4671  *
4672  * This routine creates a FC port for the upper layer protocol. The FC port
4673  * can be created on top of either a physical port or a virtual port provided
4674  * by the HBA. This routine also allocates a SCSI host data structure (shost)
4675  * and associates the FC port created before adding the shost into the SCSI
4676  * layer.
4677  *
4678  * Return codes
4679  *   @vport - pointer to the virtual N_Port data structure.
4680  *   NULL - port create failed.
4681  **/
4682 struct lpfc_vport *
4683 lpfc_create_port(struct lpfc_hba *phba, int instance, struct device *dev)
4684 {
4685 	struct lpfc_vport *vport;
4686 	struct Scsi_Host  *shost = NULL;
4687 	struct scsi_host_template *template;
4688 	int error = 0;
4689 	int i;
4690 	uint64_t wwn;
4691 	bool use_no_reset_hba = false;
4692 	int rc;
4693 
4694 	if (lpfc_no_hba_reset_cnt) {
4695 		if (phba->sli_rev < LPFC_SLI_REV4 &&
4696 		    dev == &phba->pcidev->dev) {
4697 			/* Reset the port first */
4698 			lpfc_sli_brdrestart(phba);
4699 			rc = lpfc_sli_chipset_init(phba);
4700 			if (rc)
4701 				return NULL;
4702 		}
4703 		wwn = lpfc_get_wwpn(phba);
4704 	}
4705 
4706 	for (i = 0; i < lpfc_no_hba_reset_cnt; i++) {
4707 		if (wwn == lpfc_no_hba_reset[i]) {
4708 			lpfc_printf_log(phba, KERN_ERR,
4709 					LOG_TRACE_EVENT,
4710 					"6020 Setting use_no_reset port=%llx\n",
4711 					wwn);
4712 			use_no_reset_hba = true;
4713 			break;
4714 		}
4715 	}
4716 
4717 	/* Seed template for SCSI host registration */
4718 	if (dev == &phba->pcidev->dev) {
4719 		template = &phba->port_template;
4720 
4721 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP) {
4722 			/* Seed physical port template */
4723 			memcpy(template, &lpfc_template, sizeof(*template));
4724 
4725 			if (use_no_reset_hba)
4726 				/* template is for a no reset SCSI Host */
4727 				template->eh_host_reset_handler = NULL;
4728 
4729 			/* Template for all vports this physical port creates */
4730 			memcpy(&phba->vport_template, &lpfc_template,
4731 			       sizeof(*template));
4732 			phba->vport_template.shost_groups = lpfc_vport_groups;
4733 			phba->vport_template.eh_bus_reset_handler = NULL;
4734 			phba->vport_template.eh_host_reset_handler = NULL;
4735 			phba->vport_template.vendor_id = 0;
4736 
4737 			/* Initialize the host templates with updated value */
4738 			if (phba->sli_rev == LPFC_SLI_REV4) {
4739 				template->sg_tablesize = phba->cfg_scsi_seg_cnt;
4740 				phba->vport_template.sg_tablesize =
4741 					phba->cfg_scsi_seg_cnt;
4742 			} else {
4743 				template->sg_tablesize = phba->cfg_sg_seg_cnt;
4744 				phba->vport_template.sg_tablesize =
4745 					phba->cfg_sg_seg_cnt;
4746 			}
4747 
4748 		} else {
4749 			/* NVMET is for physical port only */
4750 			memcpy(template, &lpfc_template_nvme,
4751 			       sizeof(*template));
4752 		}
4753 	} else {
4754 		template = &phba->vport_template;
4755 	}
4756 
4757 	shost = scsi_host_alloc(template, sizeof(struct lpfc_vport));
4758 	if (!shost)
4759 		goto out;
4760 
4761 	vport = (struct lpfc_vport *) shost->hostdata;
4762 	vport->phba = phba;
4763 	vport->load_flag |= FC_LOADING;
4764 	vport->fc_flag |= FC_VPORT_NEEDS_REG_VPI;
4765 	vport->fc_rscn_flush = 0;
4766 	lpfc_get_vport_cfgparam(vport);
4767 
4768 	/* Adjust value in vport */
4769 	vport->cfg_enable_fc4_type = phba->cfg_enable_fc4_type;
4770 
4771 	shost->unique_id = instance;
4772 	shost->max_id = LPFC_MAX_TARGET;
4773 	shost->max_lun = vport->cfg_max_luns;
4774 	shost->this_id = -1;
4775 	shost->max_cmd_len = 16;
4776 
4777 	if (phba->sli_rev == LPFC_SLI_REV4) {
4778 		if (!phba->cfg_fcp_mq_threshold ||
4779 		    phba->cfg_fcp_mq_threshold > phba->cfg_hdw_queue)
4780 			phba->cfg_fcp_mq_threshold = phba->cfg_hdw_queue;
4781 
4782 		shost->nr_hw_queues = min_t(int, 2 * num_possible_nodes(),
4783 					    phba->cfg_fcp_mq_threshold);
4784 
4785 		shost->dma_boundary =
4786 			phba->sli4_hba.pc_sli4_params.sge_supp_len-1;
4787 
4788 		if (phba->cfg_xpsgl && !phba->nvmet_support)
4789 			shost->sg_tablesize = LPFC_MAX_SG_TABLESIZE;
4790 		else
4791 			shost->sg_tablesize = phba->cfg_scsi_seg_cnt;
4792 	} else
4793 		/* SLI-3 has a limited number of hardware queues (3),
4794 		 * thus there is only one for FCP processing.
4795 		 */
4796 		shost->nr_hw_queues = 1;
4797 
4798 	/*
4799 	 * Set initial can_queue value since 0 is no longer supported and
4800 	 * scsi_add_host will fail. This will be adjusted later based on the
4801 	 * max xri value determined in hba setup.
4802 	 */
4803 	shost->can_queue = phba->cfg_hba_queue_depth - 10;
4804 	if (dev != &phba->pcidev->dev) {
4805 		shost->transportt = lpfc_vport_transport_template;
4806 		vport->port_type = LPFC_NPIV_PORT;
4807 	} else {
4808 		shost->transportt = lpfc_transport_template;
4809 		vport->port_type = LPFC_PHYSICAL_PORT;
4810 	}
4811 
4812 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP,
4813 			"9081 CreatePort TMPLATE type %x TBLsize %d "
4814 			"SEGcnt %d/%d\n",
4815 			vport->port_type, shost->sg_tablesize,
4816 			phba->cfg_scsi_seg_cnt, phba->cfg_sg_seg_cnt);
4817 
4818 	/* Allocate the resources for VMID */
4819 	rc = lpfc_vmid_res_alloc(phba, vport);
4820 
4821 	if (rc)
4822 		goto out;
4823 
4824 	/* Initialize all internally managed lists. */
4825 	INIT_LIST_HEAD(&vport->fc_nodes);
4826 	INIT_LIST_HEAD(&vport->rcv_buffer_list);
4827 	spin_lock_init(&vport->work_port_lock);
4828 
4829 	timer_setup(&vport->fc_disctmo, lpfc_disc_timeout, 0);
4830 
4831 	timer_setup(&vport->els_tmofunc, lpfc_els_timeout, 0);
4832 
4833 	timer_setup(&vport->delayed_disc_tmo, lpfc_delayed_disc_tmo, 0);
4834 
4835 	if (phba->sli3_options & LPFC_SLI3_BG_ENABLED)
4836 		lpfc_setup_bg(phba, shost);
4837 
4838 	error = scsi_add_host_with_dma(shost, dev, &phba->pcidev->dev);
4839 	if (error)
4840 		goto out_put_shost;
4841 
4842 	spin_lock_irq(&phba->port_list_lock);
4843 	list_add_tail(&vport->listentry, &phba->port_list);
4844 	spin_unlock_irq(&phba->port_list_lock);
4845 	return vport;
4846 
4847 out_put_shost:
4848 	kfree(vport->vmid);
4849 	bitmap_free(vport->vmid_priority_range);
4850 	scsi_host_put(shost);
4851 out:
4852 	return NULL;
4853 }
4854 
4855 /**
4856  * destroy_port -  destroy an FC port
4857  * @vport: pointer to an lpfc virtual N_Port data structure.
4858  *
4859  * This routine destroys a FC port from the upper layer protocol. All the
4860  * resources associated with the port are released.
4861  **/
4862 void
4863 destroy_port(struct lpfc_vport *vport)
4864 {
4865 	struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
4866 	struct lpfc_hba  *phba = vport->phba;
4867 
4868 	lpfc_debugfs_terminate(vport);
4869 	fc_remove_host(shost);
4870 	scsi_remove_host(shost);
4871 
4872 	spin_lock_irq(&phba->port_list_lock);
4873 	list_del_init(&vport->listentry);
4874 	spin_unlock_irq(&phba->port_list_lock);
4875 
4876 	lpfc_cleanup(vport);
4877 	return;
4878 }
4879 
4880 /**
4881  * lpfc_get_instance - Get a unique integer ID
4882  *
4883  * This routine allocates a unique integer ID from lpfc_hba_index pool. It
4884  * uses the kernel idr facility to perform the task.
4885  *
4886  * Return codes:
4887  *   instance - a unique integer ID allocated as the new instance.
4888  *   -1 - lpfc get instance failed.
4889  **/
4890 int
4891 lpfc_get_instance(void)
4892 {
4893 	int ret;
4894 
4895 	ret = idr_alloc(&lpfc_hba_index, NULL, 0, 0, GFP_KERNEL);
4896 	return ret < 0 ? -1 : ret;
4897 }
4898 
4899 /**
4900  * lpfc_scan_finished - method for SCSI layer to detect whether scan is done
4901  * @shost: pointer to SCSI host data structure.
4902  * @time: elapsed time of the scan in jiffies.
4903  *
4904  * This routine is called by the SCSI layer with a SCSI host to determine
4905  * whether the scan host is finished.
4906  *
4907  * Note: there is no scan_start function as adapter initialization will have
4908  * asynchronously kicked off the link initialization.
4909  *
4910  * Return codes
4911  *   0 - SCSI host scan is not over yet.
4912  *   1 - SCSI host scan is over.
4913  **/
4914 int lpfc_scan_finished(struct Scsi_Host *shost, unsigned long time)
4915 {
4916 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
4917 	struct lpfc_hba   *phba = vport->phba;
4918 	int stat = 0;
4919 
4920 	spin_lock_irq(shost->host_lock);
4921 
4922 	if (vport->load_flag & FC_UNLOADING) {
4923 		stat = 1;
4924 		goto finished;
4925 	}
4926 	if (time >= msecs_to_jiffies(30 * 1000)) {
4927 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4928 				"0461 Scanning longer than 30 "
4929 				"seconds.  Continuing initialization\n");
4930 		stat = 1;
4931 		goto finished;
4932 	}
4933 	if (time >= msecs_to_jiffies(15 * 1000) &&
4934 	    phba->link_state <= LPFC_LINK_DOWN) {
4935 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4936 				"0465 Link down longer than 15 "
4937 				"seconds.  Continuing initialization\n");
4938 		stat = 1;
4939 		goto finished;
4940 	}
4941 
4942 	if (vport->port_state != LPFC_VPORT_READY)
4943 		goto finished;
4944 	if (vport->num_disc_nodes || vport->fc_prli_sent)
4945 		goto finished;
4946 	if (vport->fc_map_cnt == 0 && time < msecs_to_jiffies(2 * 1000))
4947 		goto finished;
4948 	if ((phba->sli.sli_flag & LPFC_SLI_MBOX_ACTIVE) != 0)
4949 		goto finished;
4950 
4951 	stat = 1;
4952 
4953 finished:
4954 	spin_unlock_irq(shost->host_lock);
4955 	return stat;
4956 }
4957 
4958 static void lpfc_host_supported_speeds_set(struct Scsi_Host *shost)
4959 {
4960 	struct lpfc_vport *vport = (struct lpfc_vport *)shost->hostdata;
4961 	struct lpfc_hba   *phba = vport->phba;
4962 
4963 	fc_host_supported_speeds(shost) = 0;
4964 	/*
4965 	 * Avoid reporting supported link speed for FCoE as it can't be
4966 	 * controlled via FCoE.
4967 	 */
4968 	if (phba->hba_flag & HBA_FCOE_MODE)
4969 		return;
4970 
4971 	if (phba->lmt & LMT_256Gb)
4972 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_256GBIT;
4973 	if (phba->lmt & LMT_128Gb)
4974 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_128GBIT;
4975 	if (phba->lmt & LMT_64Gb)
4976 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_64GBIT;
4977 	if (phba->lmt & LMT_32Gb)
4978 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_32GBIT;
4979 	if (phba->lmt & LMT_16Gb)
4980 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_16GBIT;
4981 	if (phba->lmt & LMT_10Gb)
4982 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_10GBIT;
4983 	if (phba->lmt & LMT_8Gb)
4984 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_8GBIT;
4985 	if (phba->lmt & LMT_4Gb)
4986 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_4GBIT;
4987 	if (phba->lmt & LMT_2Gb)
4988 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_2GBIT;
4989 	if (phba->lmt & LMT_1Gb)
4990 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_1GBIT;
4991 }
4992 
4993 /**
4994  * lpfc_host_attrib_init - Initialize SCSI host attributes on a FC port
4995  * @shost: pointer to SCSI host data structure.
4996  *
4997  * This routine initializes a given SCSI host attributes on a FC port. The
4998  * SCSI host can be either on top of a physical port or a virtual port.
4999  **/
5000 void lpfc_host_attrib_init(struct Scsi_Host *shost)
5001 {
5002 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
5003 	struct lpfc_hba   *phba = vport->phba;
5004 	/*
5005 	 * Set fixed host attributes.  Must done after lpfc_sli_hba_setup().
5006 	 */
5007 
5008 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
5009 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
5010 	fc_host_supported_classes(shost) = FC_COS_CLASS3;
5011 
5012 	memset(fc_host_supported_fc4s(shost), 0,
5013 	       sizeof(fc_host_supported_fc4s(shost)));
5014 	fc_host_supported_fc4s(shost)[2] = 1;
5015 	fc_host_supported_fc4s(shost)[7] = 1;
5016 
5017 	lpfc_vport_symbolic_node_name(vport, fc_host_symbolic_name(shost),
5018 				 sizeof fc_host_symbolic_name(shost));
5019 
5020 	lpfc_host_supported_speeds_set(shost);
5021 
5022 	fc_host_maxframe_size(shost) =
5023 		(((uint32_t) vport->fc_sparam.cmn.bbRcvSizeMsb & 0x0F) << 8) |
5024 		(uint32_t) vport->fc_sparam.cmn.bbRcvSizeLsb;
5025 
5026 	fc_host_dev_loss_tmo(shost) = vport->cfg_devloss_tmo;
5027 
5028 	/* This value is also unchanging */
5029 	memset(fc_host_active_fc4s(shost), 0,
5030 	       sizeof(fc_host_active_fc4s(shost)));
5031 	fc_host_active_fc4s(shost)[2] = 1;
5032 	fc_host_active_fc4s(shost)[7] = 1;
5033 
5034 	fc_host_max_npiv_vports(shost) = phba->max_vpi;
5035 	spin_lock_irq(shost->host_lock);
5036 	vport->load_flag &= ~FC_LOADING;
5037 	spin_unlock_irq(shost->host_lock);
5038 }
5039 
5040 /**
5041  * lpfc_stop_port_s3 - Stop SLI3 device port
5042  * @phba: pointer to lpfc hba data structure.
5043  *
5044  * This routine is invoked to stop an SLI3 device port, it stops the device
5045  * from generating interrupts and stops the device driver's timers for the
5046  * device.
5047  **/
5048 static void
5049 lpfc_stop_port_s3(struct lpfc_hba *phba)
5050 {
5051 	/* Clear all interrupt enable conditions */
5052 	writel(0, phba->HCregaddr);
5053 	readl(phba->HCregaddr); /* flush */
5054 	/* Clear all pending interrupts */
5055 	writel(0xffffffff, phba->HAregaddr);
5056 	readl(phba->HAregaddr); /* flush */
5057 
5058 	/* Reset some HBA SLI setup states */
5059 	lpfc_stop_hba_timers(phba);
5060 	phba->pport->work_port_events = 0;
5061 }
5062 
5063 /**
5064  * lpfc_stop_port_s4 - Stop SLI4 device port
5065  * @phba: pointer to lpfc hba data structure.
5066  *
5067  * This routine is invoked to stop an SLI4 device port, it stops the device
5068  * from generating interrupts and stops the device driver's timers for the
5069  * device.
5070  **/
5071 static void
5072 lpfc_stop_port_s4(struct lpfc_hba *phba)
5073 {
5074 	/* Reset some HBA SLI4 setup states */
5075 	lpfc_stop_hba_timers(phba);
5076 	if (phba->pport)
5077 		phba->pport->work_port_events = 0;
5078 	phba->sli4_hba.intr_enable = 0;
5079 }
5080 
5081 /**
5082  * lpfc_stop_port - Wrapper function for stopping hba port
5083  * @phba: Pointer to HBA context object.
5084  *
5085  * This routine wraps the actual SLI3 or SLI4 hba stop port routine from
5086  * the API jump table function pointer from the lpfc_hba struct.
5087  **/
5088 void
5089 lpfc_stop_port(struct lpfc_hba *phba)
5090 {
5091 	phba->lpfc_stop_port(phba);
5092 
5093 	if (phba->wq)
5094 		flush_workqueue(phba->wq);
5095 }
5096 
5097 /**
5098  * lpfc_fcf_redisc_wait_start_timer - Start fcf rediscover wait timer
5099  * @phba: Pointer to hba for which this call is being executed.
5100  *
5101  * This routine starts the timer waiting for the FCF rediscovery to complete.
5102  **/
5103 void
5104 lpfc_fcf_redisc_wait_start_timer(struct lpfc_hba *phba)
5105 {
5106 	unsigned long fcf_redisc_wait_tmo =
5107 		(jiffies + msecs_to_jiffies(LPFC_FCF_REDISCOVER_WAIT_TMO));
5108 	/* Start fcf rediscovery wait period timer */
5109 	mod_timer(&phba->fcf.redisc_wait, fcf_redisc_wait_tmo);
5110 	spin_lock_irq(&phba->hbalock);
5111 	/* Allow action to new fcf asynchronous event */
5112 	phba->fcf.fcf_flag &= ~(FCF_AVAILABLE | FCF_SCAN_DONE);
5113 	/* Mark the FCF rediscovery pending state */
5114 	phba->fcf.fcf_flag |= FCF_REDISC_PEND;
5115 	spin_unlock_irq(&phba->hbalock);
5116 }
5117 
5118 /**
5119  * lpfc_sli4_fcf_redisc_wait_tmo - FCF table rediscover wait timeout
5120  * @t: Timer context used to obtain the pointer to lpfc hba data structure.
5121  *
5122  * This routine is invoked when waiting for FCF table rediscover has been
5123  * timed out. If new FCF record(s) has (have) been discovered during the
5124  * wait period, a new FCF event shall be added to the FCOE async event
5125  * list, and then worker thread shall be waked up for processing from the
5126  * worker thread context.
5127  **/
5128 static void
5129 lpfc_sli4_fcf_redisc_wait_tmo(struct timer_list *t)
5130 {
5131 	struct lpfc_hba *phba = from_timer(phba, t, fcf.redisc_wait);
5132 
5133 	/* Don't send FCF rediscovery event if timer cancelled */
5134 	spin_lock_irq(&phba->hbalock);
5135 	if (!(phba->fcf.fcf_flag & FCF_REDISC_PEND)) {
5136 		spin_unlock_irq(&phba->hbalock);
5137 		return;
5138 	}
5139 	/* Clear FCF rediscovery timer pending flag */
5140 	phba->fcf.fcf_flag &= ~FCF_REDISC_PEND;
5141 	/* FCF rediscovery event to worker thread */
5142 	phba->fcf.fcf_flag |= FCF_REDISC_EVT;
5143 	spin_unlock_irq(&phba->hbalock);
5144 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
5145 			"2776 FCF rediscover quiescent timer expired\n");
5146 	/* wake up worker thread */
5147 	lpfc_worker_wake_up(phba);
5148 }
5149 
5150 /**
5151  * lpfc_vmid_poll - VMID timeout detection
5152  * @t: Timer context used to obtain the pointer to lpfc hba data structure.
5153  *
5154  * This routine is invoked when there is no I/O on by a VM for the specified
5155  * amount of time. When this situation is detected, the VMID has to be
5156  * deregistered from the switch and all the local resources freed. The VMID
5157  * will be reassigned to the VM once the I/O begins.
5158  **/
5159 static void
5160 lpfc_vmid_poll(struct timer_list *t)
5161 {
5162 	struct lpfc_hba *phba = from_timer(phba, t, inactive_vmid_poll);
5163 	u32 wake_up = 0;
5164 
5165 	/* check if there is a need to issue QFPA */
5166 	if (phba->pport->vmid_priority_tagging) {
5167 		wake_up = 1;
5168 		phba->pport->work_port_events |= WORKER_CHECK_VMID_ISSUE_QFPA;
5169 	}
5170 
5171 	/* Is the vmid inactivity timer enabled */
5172 	if (phba->pport->vmid_inactivity_timeout ||
5173 	    phba->pport->load_flag & FC_DEREGISTER_ALL_APP_ID) {
5174 		wake_up = 1;
5175 		phba->pport->work_port_events |= WORKER_CHECK_INACTIVE_VMID;
5176 	}
5177 
5178 	if (wake_up)
5179 		lpfc_worker_wake_up(phba);
5180 
5181 	/* restart the timer for the next iteration */
5182 	mod_timer(&phba->inactive_vmid_poll, jiffies + msecs_to_jiffies(1000 *
5183 							LPFC_VMID_TIMER));
5184 }
5185 
5186 /**
5187  * lpfc_sli4_parse_latt_fault - Parse sli4 link-attention link fault code
5188  * @phba: pointer to lpfc hba data structure.
5189  * @acqe_link: pointer to the async link completion queue entry.
5190  *
5191  * This routine is to parse the SLI4 link-attention link fault code.
5192  **/
5193 static void
5194 lpfc_sli4_parse_latt_fault(struct lpfc_hba *phba,
5195 			   struct lpfc_acqe_link *acqe_link)
5196 {
5197 	switch (bf_get(lpfc_acqe_link_fault, acqe_link)) {
5198 	case LPFC_ASYNC_LINK_FAULT_NONE:
5199 	case LPFC_ASYNC_LINK_FAULT_LOCAL:
5200 	case LPFC_ASYNC_LINK_FAULT_REMOTE:
5201 	case LPFC_ASYNC_LINK_FAULT_LR_LRR:
5202 		break;
5203 	default:
5204 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5205 				"0398 Unknown link fault code: x%x\n",
5206 				bf_get(lpfc_acqe_link_fault, acqe_link));
5207 		break;
5208 	}
5209 }
5210 
5211 /**
5212  * lpfc_sli4_parse_latt_type - Parse sli4 link attention type
5213  * @phba: pointer to lpfc hba data structure.
5214  * @acqe_link: pointer to the async link completion queue entry.
5215  *
5216  * This routine is to parse the SLI4 link attention type and translate it
5217  * into the base driver's link attention type coding.
5218  *
5219  * Return: Link attention type in terms of base driver's coding.
5220  **/
5221 static uint8_t
5222 lpfc_sli4_parse_latt_type(struct lpfc_hba *phba,
5223 			  struct lpfc_acqe_link *acqe_link)
5224 {
5225 	uint8_t att_type;
5226 
5227 	switch (bf_get(lpfc_acqe_link_status, acqe_link)) {
5228 	case LPFC_ASYNC_LINK_STATUS_DOWN:
5229 	case LPFC_ASYNC_LINK_STATUS_LOGICAL_DOWN:
5230 		att_type = LPFC_ATT_LINK_DOWN;
5231 		break;
5232 	case LPFC_ASYNC_LINK_STATUS_UP:
5233 		/* Ignore physical link up events - wait for logical link up */
5234 		att_type = LPFC_ATT_RESERVED;
5235 		break;
5236 	case LPFC_ASYNC_LINK_STATUS_LOGICAL_UP:
5237 		att_type = LPFC_ATT_LINK_UP;
5238 		break;
5239 	default:
5240 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5241 				"0399 Invalid link attention type: x%x\n",
5242 				bf_get(lpfc_acqe_link_status, acqe_link));
5243 		att_type = LPFC_ATT_RESERVED;
5244 		break;
5245 	}
5246 	return att_type;
5247 }
5248 
5249 /**
5250  * lpfc_sli_port_speed_get - Get sli3 link speed code to link speed
5251  * @phba: pointer to lpfc hba data structure.
5252  *
5253  * This routine is to get an SLI3 FC port's link speed in Mbps.
5254  *
5255  * Return: link speed in terms of Mbps.
5256  **/
5257 uint32_t
5258 lpfc_sli_port_speed_get(struct lpfc_hba *phba)
5259 {
5260 	uint32_t link_speed;
5261 
5262 	if (!lpfc_is_link_up(phba))
5263 		return 0;
5264 
5265 	if (phba->sli_rev <= LPFC_SLI_REV3) {
5266 		switch (phba->fc_linkspeed) {
5267 		case LPFC_LINK_SPEED_1GHZ:
5268 			link_speed = 1000;
5269 			break;
5270 		case LPFC_LINK_SPEED_2GHZ:
5271 			link_speed = 2000;
5272 			break;
5273 		case LPFC_LINK_SPEED_4GHZ:
5274 			link_speed = 4000;
5275 			break;
5276 		case LPFC_LINK_SPEED_8GHZ:
5277 			link_speed = 8000;
5278 			break;
5279 		case LPFC_LINK_SPEED_10GHZ:
5280 			link_speed = 10000;
5281 			break;
5282 		case LPFC_LINK_SPEED_16GHZ:
5283 			link_speed = 16000;
5284 			break;
5285 		default:
5286 			link_speed = 0;
5287 		}
5288 	} else {
5289 		if (phba->sli4_hba.link_state.logical_speed)
5290 			link_speed =
5291 			      phba->sli4_hba.link_state.logical_speed;
5292 		else
5293 			link_speed = phba->sli4_hba.link_state.speed;
5294 	}
5295 	return link_speed;
5296 }
5297 
5298 /**
5299  * lpfc_sli4_port_speed_parse - Parse async evt link speed code to link speed
5300  * @phba: pointer to lpfc hba data structure.
5301  * @evt_code: asynchronous event code.
5302  * @speed_code: asynchronous event link speed code.
5303  *
5304  * This routine is to parse the giving SLI4 async event link speed code into
5305  * value of Mbps for the link speed.
5306  *
5307  * Return: link speed in terms of Mbps.
5308  **/
5309 static uint32_t
5310 lpfc_sli4_port_speed_parse(struct lpfc_hba *phba, uint32_t evt_code,
5311 			   uint8_t speed_code)
5312 {
5313 	uint32_t port_speed;
5314 
5315 	switch (evt_code) {
5316 	case LPFC_TRAILER_CODE_LINK:
5317 		switch (speed_code) {
5318 		case LPFC_ASYNC_LINK_SPEED_ZERO:
5319 			port_speed = 0;
5320 			break;
5321 		case LPFC_ASYNC_LINK_SPEED_10MBPS:
5322 			port_speed = 10;
5323 			break;
5324 		case LPFC_ASYNC_LINK_SPEED_100MBPS:
5325 			port_speed = 100;
5326 			break;
5327 		case LPFC_ASYNC_LINK_SPEED_1GBPS:
5328 			port_speed = 1000;
5329 			break;
5330 		case LPFC_ASYNC_LINK_SPEED_10GBPS:
5331 			port_speed = 10000;
5332 			break;
5333 		case LPFC_ASYNC_LINK_SPEED_20GBPS:
5334 			port_speed = 20000;
5335 			break;
5336 		case LPFC_ASYNC_LINK_SPEED_25GBPS:
5337 			port_speed = 25000;
5338 			break;
5339 		case LPFC_ASYNC_LINK_SPEED_40GBPS:
5340 			port_speed = 40000;
5341 			break;
5342 		case LPFC_ASYNC_LINK_SPEED_100GBPS:
5343 			port_speed = 100000;
5344 			break;
5345 		default:
5346 			port_speed = 0;
5347 		}
5348 		break;
5349 	case LPFC_TRAILER_CODE_FC:
5350 		switch (speed_code) {
5351 		case LPFC_FC_LA_SPEED_UNKNOWN:
5352 			port_speed = 0;
5353 			break;
5354 		case LPFC_FC_LA_SPEED_1G:
5355 			port_speed = 1000;
5356 			break;
5357 		case LPFC_FC_LA_SPEED_2G:
5358 			port_speed = 2000;
5359 			break;
5360 		case LPFC_FC_LA_SPEED_4G:
5361 			port_speed = 4000;
5362 			break;
5363 		case LPFC_FC_LA_SPEED_8G:
5364 			port_speed = 8000;
5365 			break;
5366 		case LPFC_FC_LA_SPEED_10G:
5367 			port_speed = 10000;
5368 			break;
5369 		case LPFC_FC_LA_SPEED_16G:
5370 			port_speed = 16000;
5371 			break;
5372 		case LPFC_FC_LA_SPEED_32G:
5373 			port_speed = 32000;
5374 			break;
5375 		case LPFC_FC_LA_SPEED_64G:
5376 			port_speed = 64000;
5377 			break;
5378 		case LPFC_FC_LA_SPEED_128G:
5379 			port_speed = 128000;
5380 			break;
5381 		case LPFC_FC_LA_SPEED_256G:
5382 			port_speed = 256000;
5383 			break;
5384 		default:
5385 			port_speed = 0;
5386 		}
5387 		break;
5388 	default:
5389 		port_speed = 0;
5390 	}
5391 	return port_speed;
5392 }
5393 
5394 /**
5395  * lpfc_sli4_async_link_evt - Process the asynchronous FCoE link event
5396  * @phba: pointer to lpfc hba data structure.
5397  * @acqe_link: pointer to the async link completion queue entry.
5398  *
5399  * This routine is to handle the SLI4 asynchronous FCoE link event.
5400  **/
5401 static void
5402 lpfc_sli4_async_link_evt(struct lpfc_hba *phba,
5403 			 struct lpfc_acqe_link *acqe_link)
5404 {
5405 	LPFC_MBOXQ_t *pmb;
5406 	MAILBOX_t *mb;
5407 	struct lpfc_mbx_read_top *la;
5408 	uint8_t att_type;
5409 	int rc;
5410 
5411 	att_type = lpfc_sli4_parse_latt_type(phba, acqe_link);
5412 	if (att_type != LPFC_ATT_LINK_DOWN && att_type != LPFC_ATT_LINK_UP)
5413 		return;
5414 	phba->fcoe_eventtag = acqe_link->event_tag;
5415 	pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5416 	if (!pmb) {
5417 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5418 				"0395 The mboxq allocation failed\n");
5419 		return;
5420 	}
5421 
5422 	rc = lpfc_mbox_rsrc_prep(phba, pmb);
5423 	if (rc) {
5424 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5425 				"0396 mailbox allocation failed\n");
5426 		goto out_free_pmb;
5427 	}
5428 
5429 	/* Cleanup any outstanding ELS commands */
5430 	lpfc_els_flush_all_cmd(phba);
5431 
5432 	/* Block ELS IOCBs until we have done process link event */
5433 	phba->sli4_hba.els_wq->pring->flag |= LPFC_STOP_IOCB_EVENT;
5434 
5435 	/* Update link event statistics */
5436 	phba->sli.slistat.link_event++;
5437 
5438 	/* Create lpfc_handle_latt mailbox command from link ACQE */
5439 	lpfc_read_topology(phba, pmb, (struct lpfc_dmabuf *)pmb->ctx_buf);
5440 	pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
5441 	pmb->vport = phba->pport;
5442 
5443 	/* Keep the link status for extra SLI4 state machine reference */
5444 	phba->sli4_hba.link_state.speed =
5445 			lpfc_sli4_port_speed_parse(phba, LPFC_TRAILER_CODE_LINK,
5446 				bf_get(lpfc_acqe_link_speed, acqe_link));
5447 	phba->sli4_hba.link_state.duplex =
5448 				bf_get(lpfc_acqe_link_duplex, acqe_link);
5449 	phba->sli4_hba.link_state.status =
5450 				bf_get(lpfc_acqe_link_status, acqe_link);
5451 	phba->sli4_hba.link_state.type =
5452 				bf_get(lpfc_acqe_link_type, acqe_link);
5453 	phba->sli4_hba.link_state.number =
5454 				bf_get(lpfc_acqe_link_number, acqe_link);
5455 	phba->sli4_hba.link_state.fault =
5456 				bf_get(lpfc_acqe_link_fault, acqe_link);
5457 	phba->sli4_hba.link_state.logical_speed =
5458 			bf_get(lpfc_acqe_logical_link_speed, acqe_link) * 10;
5459 
5460 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5461 			"2900 Async FC/FCoE Link event - Speed:%dGBit "
5462 			"duplex:x%x LA Type:x%x Port Type:%d Port Number:%d "
5463 			"Logical speed:%dMbps Fault:%d\n",
5464 			phba->sli4_hba.link_state.speed,
5465 			phba->sli4_hba.link_state.topology,
5466 			phba->sli4_hba.link_state.status,
5467 			phba->sli4_hba.link_state.type,
5468 			phba->sli4_hba.link_state.number,
5469 			phba->sli4_hba.link_state.logical_speed,
5470 			phba->sli4_hba.link_state.fault);
5471 	/*
5472 	 * For FC Mode: issue the READ_TOPOLOGY mailbox command to fetch
5473 	 * topology info. Note: Optional for non FC-AL ports.
5474 	 */
5475 	if (!(phba->hba_flag & HBA_FCOE_MODE)) {
5476 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
5477 		if (rc == MBX_NOT_FINISHED)
5478 			goto out_free_pmb;
5479 		return;
5480 	}
5481 	/*
5482 	 * For FCoE Mode: fill in all the topology information we need and call
5483 	 * the READ_TOPOLOGY completion routine to continue without actually
5484 	 * sending the READ_TOPOLOGY mailbox command to the port.
5485 	 */
5486 	/* Initialize completion status */
5487 	mb = &pmb->u.mb;
5488 	mb->mbxStatus = MBX_SUCCESS;
5489 
5490 	/* Parse port fault information field */
5491 	lpfc_sli4_parse_latt_fault(phba, acqe_link);
5492 
5493 	/* Parse and translate link attention fields */
5494 	la = (struct lpfc_mbx_read_top *) &pmb->u.mb.un.varReadTop;
5495 	la->eventTag = acqe_link->event_tag;
5496 	bf_set(lpfc_mbx_read_top_att_type, la, att_type);
5497 	bf_set(lpfc_mbx_read_top_link_spd, la,
5498 	       (bf_get(lpfc_acqe_link_speed, acqe_link)));
5499 
5500 	/* Fake the the following irrelvant fields */
5501 	bf_set(lpfc_mbx_read_top_topology, la, LPFC_TOPOLOGY_PT_PT);
5502 	bf_set(lpfc_mbx_read_top_alpa_granted, la, 0);
5503 	bf_set(lpfc_mbx_read_top_il, la, 0);
5504 	bf_set(lpfc_mbx_read_top_pb, la, 0);
5505 	bf_set(lpfc_mbx_read_top_fa, la, 0);
5506 	bf_set(lpfc_mbx_read_top_mm, la, 0);
5507 
5508 	/* Invoke the lpfc_handle_latt mailbox command callback function */
5509 	lpfc_mbx_cmpl_read_topology(phba, pmb);
5510 
5511 	return;
5512 
5513 out_free_pmb:
5514 	lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
5515 }
5516 
5517 /**
5518  * lpfc_async_link_speed_to_read_top - Parse async evt link speed code to read
5519  * topology.
5520  * @phba: pointer to lpfc hba data structure.
5521  * @speed_code: asynchronous event link speed code.
5522  *
5523  * This routine is to parse the giving SLI4 async event link speed code into
5524  * value of Read topology link speed.
5525  *
5526  * Return: link speed in terms of Read topology.
5527  **/
5528 static uint8_t
5529 lpfc_async_link_speed_to_read_top(struct lpfc_hba *phba, uint8_t speed_code)
5530 {
5531 	uint8_t port_speed;
5532 
5533 	switch (speed_code) {
5534 	case LPFC_FC_LA_SPEED_1G:
5535 		port_speed = LPFC_LINK_SPEED_1GHZ;
5536 		break;
5537 	case LPFC_FC_LA_SPEED_2G:
5538 		port_speed = LPFC_LINK_SPEED_2GHZ;
5539 		break;
5540 	case LPFC_FC_LA_SPEED_4G:
5541 		port_speed = LPFC_LINK_SPEED_4GHZ;
5542 		break;
5543 	case LPFC_FC_LA_SPEED_8G:
5544 		port_speed = LPFC_LINK_SPEED_8GHZ;
5545 		break;
5546 	case LPFC_FC_LA_SPEED_16G:
5547 		port_speed = LPFC_LINK_SPEED_16GHZ;
5548 		break;
5549 	case LPFC_FC_LA_SPEED_32G:
5550 		port_speed = LPFC_LINK_SPEED_32GHZ;
5551 		break;
5552 	case LPFC_FC_LA_SPEED_64G:
5553 		port_speed = LPFC_LINK_SPEED_64GHZ;
5554 		break;
5555 	case LPFC_FC_LA_SPEED_128G:
5556 		port_speed = LPFC_LINK_SPEED_128GHZ;
5557 		break;
5558 	case LPFC_FC_LA_SPEED_256G:
5559 		port_speed = LPFC_LINK_SPEED_256GHZ;
5560 		break;
5561 	default:
5562 		port_speed = 0;
5563 		break;
5564 	}
5565 
5566 	return port_speed;
5567 }
5568 
5569 void
5570 lpfc_cgn_dump_rxmonitor(struct lpfc_hba *phba)
5571 {
5572 	struct rxtable_entry *entry;
5573 	int cnt = 0, head, tail, last, start;
5574 
5575 	head = atomic_read(&phba->rxtable_idx_head);
5576 	tail = atomic_read(&phba->rxtable_idx_tail);
5577 	if (!phba->rxtable || head == tail) {
5578 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT,
5579 				"4411 Rxtable is empty\n");
5580 		return;
5581 	}
5582 	last = tail;
5583 	start = head;
5584 
5585 	/* Display the last LPFC_MAX_RXMONITOR_DUMP entries from the rxtable */
5586 	while (start != last) {
5587 		if (start)
5588 			start--;
5589 		else
5590 			start = LPFC_MAX_RXMONITOR_ENTRY - 1;
5591 		entry = &phba->rxtable[start];
5592 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5593 				"4410 %02d: MBPI %lld Xmit %lld Cmpl %lld "
5594 				"Lat %lld ASz %lld Info %02d BWUtil %d "
5595 				"Int %d slot %d\n",
5596 				cnt, entry->max_bytes_per_interval,
5597 				entry->total_bytes, entry->rcv_bytes,
5598 				entry->avg_io_latency, entry->avg_io_size,
5599 				entry->cmf_info, entry->timer_utilization,
5600 				entry->timer_interval, start);
5601 		cnt++;
5602 		if (cnt >= LPFC_MAX_RXMONITOR_DUMP)
5603 			return;
5604 	}
5605 }
5606 
5607 /**
5608  * lpfc_cgn_update_stat - Save data into congestion stats buffer
5609  * @phba: pointer to lpfc hba data structure.
5610  * @dtag: FPIN descriptor received
5611  *
5612  * Increment the FPIN received counter/time when it happens.
5613  */
5614 void
5615 lpfc_cgn_update_stat(struct lpfc_hba *phba, uint32_t dtag)
5616 {
5617 	struct lpfc_cgn_info *cp;
5618 	struct tm broken;
5619 	struct timespec64 cur_time;
5620 	u32 cnt;
5621 	u32 value;
5622 
5623 	/* Make sure we have a congestion info buffer */
5624 	if (!phba->cgn_i)
5625 		return;
5626 	cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
5627 	ktime_get_real_ts64(&cur_time);
5628 	time64_to_tm(cur_time.tv_sec, 0, &broken);
5629 
5630 	/* Update congestion statistics */
5631 	switch (dtag) {
5632 	case ELS_DTAG_LNK_INTEGRITY:
5633 		cnt = le32_to_cpu(cp->link_integ_notification);
5634 		cnt++;
5635 		cp->link_integ_notification = cpu_to_le32(cnt);
5636 
5637 		cp->cgn_stat_lnk_month = broken.tm_mon + 1;
5638 		cp->cgn_stat_lnk_day = broken.tm_mday;
5639 		cp->cgn_stat_lnk_year = broken.tm_year - 100;
5640 		cp->cgn_stat_lnk_hour = broken.tm_hour;
5641 		cp->cgn_stat_lnk_min = broken.tm_min;
5642 		cp->cgn_stat_lnk_sec = broken.tm_sec;
5643 		break;
5644 	case ELS_DTAG_DELIVERY:
5645 		cnt = le32_to_cpu(cp->delivery_notification);
5646 		cnt++;
5647 		cp->delivery_notification = cpu_to_le32(cnt);
5648 
5649 		cp->cgn_stat_del_month = broken.tm_mon + 1;
5650 		cp->cgn_stat_del_day = broken.tm_mday;
5651 		cp->cgn_stat_del_year = broken.tm_year - 100;
5652 		cp->cgn_stat_del_hour = broken.tm_hour;
5653 		cp->cgn_stat_del_min = broken.tm_min;
5654 		cp->cgn_stat_del_sec = broken.tm_sec;
5655 		break;
5656 	case ELS_DTAG_PEER_CONGEST:
5657 		cnt = le32_to_cpu(cp->cgn_peer_notification);
5658 		cnt++;
5659 		cp->cgn_peer_notification = cpu_to_le32(cnt);
5660 
5661 		cp->cgn_stat_peer_month = broken.tm_mon + 1;
5662 		cp->cgn_stat_peer_day = broken.tm_mday;
5663 		cp->cgn_stat_peer_year = broken.tm_year - 100;
5664 		cp->cgn_stat_peer_hour = broken.tm_hour;
5665 		cp->cgn_stat_peer_min = broken.tm_min;
5666 		cp->cgn_stat_peer_sec = broken.tm_sec;
5667 		break;
5668 	case ELS_DTAG_CONGESTION:
5669 		cnt = le32_to_cpu(cp->cgn_notification);
5670 		cnt++;
5671 		cp->cgn_notification = cpu_to_le32(cnt);
5672 
5673 		cp->cgn_stat_cgn_month = broken.tm_mon + 1;
5674 		cp->cgn_stat_cgn_day = broken.tm_mday;
5675 		cp->cgn_stat_cgn_year = broken.tm_year - 100;
5676 		cp->cgn_stat_cgn_hour = broken.tm_hour;
5677 		cp->cgn_stat_cgn_min = broken.tm_min;
5678 		cp->cgn_stat_cgn_sec = broken.tm_sec;
5679 	}
5680 	if (phba->cgn_fpin_frequency &&
5681 	    phba->cgn_fpin_frequency != LPFC_FPIN_INIT_FREQ) {
5682 		value = LPFC_CGN_TIMER_TO_MIN / phba->cgn_fpin_frequency;
5683 		cp->cgn_stat_npm = value;
5684 	}
5685 	value = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ,
5686 				    LPFC_CGN_CRC32_SEED);
5687 	cp->cgn_info_crc = cpu_to_le32(value);
5688 }
5689 
5690 /**
5691  * lpfc_cgn_save_evt_cnt - Save data into registered congestion buffer
5692  * @phba: pointer to lpfc hba data structure.
5693  *
5694  * Save the congestion event data every minute.
5695  * On the hour collapse all the minute data into hour data. Every day
5696  * collapse all the hour data into daily data. Separate driver
5697  * and fabrc congestion event counters that will be saved out
5698  * to the registered congestion buffer every minute.
5699  */
5700 static void
5701 lpfc_cgn_save_evt_cnt(struct lpfc_hba *phba)
5702 {
5703 	struct lpfc_cgn_info *cp;
5704 	struct tm broken;
5705 	struct timespec64 cur_time;
5706 	uint32_t i, index;
5707 	uint16_t value, mvalue;
5708 	uint64_t bps;
5709 	uint32_t mbps;
5710 	uint32_t dvalue, wvalue, lvalue, avalue;
5711 	uint64_t latsum;
5712 	__le16 *ptr;
5713 	__le32 *lptr;
5714 	__le16 *mptr;
5715 
5716 	/* Make sure we have a congestion info buffer */
5717 	if (!phba->cgn_i)
5718 		return;
5719 	cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
5720 
5721 	if (time_before(jiffies, phba->cgn_evt_timestamp))
5722 		return;
5723 	phba->cgn_evt_timestamp = jiffies +
5724 			msecs_to_jiffies(LPFC_CGN_TIMER_TO_MIN);
5725 	phba->cgn_evt_minute++;
5726 
5727 	/* We should get to this point in the routine on 1 minute intervals */
5728 
5729 	ktime_get_real_ts64(&cur_time);
5730 	time64_to_tm(cur_time.tv_sec, 0, &broken);
5731 
5732 	if (phba->cgn_fpin_frequency &&
5733 	    phba->cgn_fpin_frequency != LPFC_FPIN_INIT_FREQ) {
5734 		value = LPFC_CGN_TIMER_TO_MIN / phba->cgn_fpin_frequency;
5735 		cp->cgn_stat_npm = value;
5736 	}
5737 
5738 	/* Read and clear the latency counters for this minute */
5739 	lvalue = atomic_read(&phba->cgn_latency_evt_cnt);
5740 	latsum = atomic64_read(&phba->cgn_latency_evt);
5741 	atomic_set(&phba->cgn_latency_evt_cnt, 0);
5742 	atomic64_set(&phba->cgn_latency_evt, 0);
5743 
5744 	/* We need to store MB/sec bandwidth in the congestion information.
5745 	 * block_cnt is count of 512 byte blocks for the entire minute,
5746 	 * bps will get bytes per sec before finally converting to MB/sec.
5747 	 */
5748 	bps = div_u64(phba->rx_block_cnt, LPFC_SEC_MIN) * 512;
5749 	phba->rx_block_cnt = 0;
5750 	mvalue = bps / (1024 * 1024); /* convert to MB/sec */
5751 
5752 	/* Every minute */
5753 	/* cgn parameters */
5754 	cp->cgn_info_mode = phba->cgn_p.cgn_param_mode;
5755 	cp->cgn_info_level0 = phba->cgn_p.cgn_param_level0;
5756 	cp->cgn_info_level1 = phba->cgn_p.cgn_param_level1;
5757 	cp->cgn_info_level2 = phba->cgn_p.cgn_param_level2;
5758 
5759 	/* Fill in default LUN qdepth */
5760 	value = (uint16_t)(phba->pport->cfg_lun_queue_depth);
5761 	cp->cgn_lunq = cpu_to_le16(value);
5762 
5763 	/* Record congestion buffer info - every minute
5764 	 * cgn_driver_evt_cnt (Driver events)
5765 	 * cgn_fabric_warn_cnt (Congestion Warnings)
5766 	 * cgn_latency_evt_cnt / cgn_latency_evt (IO Latency)
5767 	 * cgn_fabric_alarm_cnt (Congestion Alarms)
5768 	 */
5769 	index = ++cp->cgn_index_minute;
5770 	if (cp->cgn_index_minute == LPFC_MIN_HOUR) {
5771 		cp->cgn_index_minute = 0;
5772 		index = 0;
5773 	}
5774 
5775 	/* Get the number of driver events in this sample and reset counter */
5776 	dvalue = atomic_read(&phba->cgn_driver_evt_cnt);
5777 	atomic_set(&phba->cgn_driver_evt_cnt, 0);
5778 
5779 	/* Get the number of warning events - FPIN and Signal for this minute */
5780 	wvalue = 0;
5781 	if ((phba->cgn_reg_fpin & LPFC_CGN_FPIN_WARN) ||
5782 	    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY ||
5783 	    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM)
5784 		wvalue = atomic_read(&phba->cgn_fabric_warn_cnt);
5785 	atomic_set(&phba->cgn_fabric_warn_cnt, 0);
5786 
5787 	/* Get the number of alarm events - FPIN and Signal for this minute */
5788 	avalue = 0;
5789 	if ((phba->cgn_reg_fpin & LPFC_CGN_FPIN_ALARM) ||
5790 	    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM)
5791 		avalue = atomic_read(&phba->cgn_fabric_alarm_cnt);
5792 	atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
5793 
5794 	/* Collect the driver, warning, alarm and latency counts for this
5795 	 * minute into the driver congestion buffer.
5796 	 */
5797 	ptr = &cp->cgn_drvr_min[index];
5798 	value = (uint16_t)dvalue;
5799 	*ptr = cpu_to_le16(value);
5800 
5801 	ptr = &cp->cgn_warn_min[index];
5802 	value = (uint16_t)wvalue;
5803 	*ptr = cpu_to_le16(value);
5804 
5805 	ptr = &cp->cgn_alarm_min[index];
5806 	value = (uint16_t)avalue;
5807 	*ptr = cpu_to_le16(value);
5808 
5809 	lptr = &cp->cgn_latency_min[index];
5810 	if (lvalue) {
5811 		lvalue = (uint32_t)div_u64(latsum, lvalue);
5812 		*lptr = cpu_to_le32(lvalue);
5813 	} else {
5814 		*lptr = 0;
5815 	}
5816 
5817 	/* Collect the bandwidth value into the driver's congesion buffer. */
5818 	mptr = &cp->cgn_bw_min[index];
5819 	*mptr = cpu_to_le16(mvalue);
5820 
5821 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5822 			"2418 Congestion Info - minute (%d): %d %d %d %d %d\n",
5823 			index, dvalue, wvalue, *lptr, mvalue, avalue);
5824 
5825 	/* Every hour */
5826 	if ((phba->cgn_evt_minute % LPFC_MIN_HOUR) == 0) {
5827 		/* Record congestion buffer info - every hour
5828 		 * Collapse all minutes into an hour
5829 		 */
5830 		index = ++cp->cgn_index_hour;
5831 		if (cp->cgn_index_hour == LPFC_HOUR_DAY) {
5832 			cp->cgn_index_hour = 0;
5833 			index = 0;
5834 		}
5835 
5836 		dvalue = 0;
5837 		wvalue = 0;
5838 		lvalue = 0;
5839 		avalue = 0;
5840 		mvalue = 0;
5841 		mbps = 0;
5842 		for (i = 0; i < LPFC_MIN_HOUR; i++) {
5843 			dvalue += le16_to_cpu(cp->cgn_drvr_min[i]);
5844 			wvalue += le16_to_cpu(cp->cgn_warn_min[i]);
5845 			lvalue += le32_to_cpu(cp->cgn_latency_min[i]);
5846 			mbps += le16_to_cpu(cp->cgn_bw_min[i]);
5847 			avalue += le16_to_cpu(cp->cgn_alarm_min[i]);
5848 		}
5849 		if (lvalue)		/* Avg of latency averages */
5850 			lvalue /= LPFC_MIN_HOUR;
5851 		if (mbps)		/* Avg of Bandwidth averages */
5852 			mvalue = mbps / LPFC_MIN_HOUR;
5853 
5854 		lptr = &cp->cgn_drvr_hr[index];
5855 		*lptr = cpu_to_le32(dvalue);
5856 		lptr = &cp->cgn_warn_hr[index];
5857 		*lptr = cpu_to_le32(wvalue);
5858 		lptr = &cp->cgn_latency_hr[index];
5859 		*lptr = cpu_to_le32(lvalue);
5860 		mptr = &cp->cgn_bw_hr[index];
5861 		*mptr = cpu_to_le16(mvalue);
5862 		lptr = &cp->cgn_alarm_hr[index];
5863 		*lptr = cpu_to_le32(avalue);
5864 
5865 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5866 				"2419 Congestion Info - hour "
5867 				"(%d): %d %d %d %d %d\n",
5868 				index, dvalue, wvalue, lvalue, mvalue, avalue);
5869 	}
5870 
5871 	/* Every day */
5872 	if ((phba->cgn_evt_minute % LPFC_MIN_DAY) == 0) {
5873 		/* Record congestion buffer info - every hour
5874 		 * Collapse all hours into a day. Rotate days
5875 		 * after LPFC_MAX_CGN_DAYS.
5876 		 */
5877 		index = ++cp->cgn_index_day;
5878 		if (cp->cgn_index_day == LPFC_MAX_CGN_DAYS) {
5879 			cp->cgn_index_day = 0;
5880 			index = 0;
5881 		}
5882 
5883 		/* Anytime we overwrite daily index 0, after we wrap,
5884 		 * we will be overwriting the oldest day, so we must
5885 		 * update the congestion data start time for that day.
5886 		 * That start time should have previously been saved after
5887 		 * we wrote the last days worth of data.
5888 		 */
5889 		if ((phba->hba_flag & HBA_CGN_DAY_WRAP) && index == 0) {
5890 			time64_to_tm(phba->cgn_daily_ts.tv_sec, 0, &broken);
5891 
5892 			cp->cgn_info_month = broken.tm_mon + 1;
5893 			cp->cgn_info_day = broken.tm_mday;
5894 			cp->cgn_info_year = broken.tm_year - 100;
5895 			cp->cgn_info_hour = broken.tm_hour;
5896 			cp->cgn_info_minute = broken.tm_min;
5897 			cp->cgn_info_second = broken.tm_sec;
5898 
5899 			lpfc_printf_log
5900 				(phba, KERN_INFO, LOG_CGN_MGMT,
5901 				"2646 CGNInfo idx0 Start Time: "
5902 				"%d/%d/%d %d:%d:%d\n",
5903 				cp->cgn_info_day, cp->cgn_info_month,
5904 				cp->cgn_info_year, cp->cgn_info_hour,
5905 				cp->cgn_info_minute, cp->cgn_info_second);
5906 		}
5907 
5908 		dvalue = 0;
5909 		wvalue = 0;
5910 		lvalue = 0;
5911 		mvalue = 0;
5912 		mbps = 0;
5913 		avalue = 0;
5914 		for (i = 0; i < LPFC_HOUR_DAY; i++) {
5915 			dvalue += le32_to_cpu(cp->cgn_drvr_hr[i]);
5916 			wvalue += le32_to_cpu(cp->cgn_warn_hr[i]);
5917 			lvalue += le32_to_cpu(cp->cgn_latency_hr[i]);
5918 			mbps += le16_to_cpu(cp->cgn_bw_hr[i]);
5919 			avalue += le32_to_cpu(cp->cgn_alarm_hr[i]);
5920 		}
5921 		if (lvalue)		/* Avg of latency averages */
5922 			lvalue /= LPFC_HOUR_DAY;
5923 		if (mbps)		/* Avg of Bandwidth averages */
5924 			mvalue = mbps / LPFC_HOUR_DAY;
5925 
5926 		lptr = &cp->cgn_drvr_day[index];
5927 		*lptr = cpu_to_le32(dvalue);
5928 		lptr = &cp->cgn_warn_day[index];
5929 		*lptr = cpu_to_le32(wvalue);
5930 		lptr = &cp->cgn_latency_day[index];
5931 		*lptr = cpu_to_le32(lvalue);
5932 		mptr = &cp->cgn_bw_day[index];
5933 		*mptr = cpu_to_le16(mvalue);
5934 		lptr = &cp->cgn_alarm_day[index];
5935 		*lptr = cpu_to_le32(avalue);
5936 
5937 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5938 				"2420 Congestion Info - daily (%d): "
5939 				"%d %d %d %d %d\n",
5940 				index, dvalue, wvalue, lvalue, mvalue, avalue);
5941 
5942 		/* We just wrote LPFC_MAX_CGN_DAYS of data,
5943 		 * so we are wrapped on any data after this.
5944 		 * Save this as the start time for the next day.
5945 		 */
5946 		if (index == (LPFC_MAX_CGN_DAYS - 1)) {
5947 			phba->hba_flag |= HBA_CGN_DAY_WRAP;
5948 			ktime_get_real_ts64(&phba->cgn_daily_ts);
5949 		}
5950 	}
5951 
5952 	/* Use the frequency found in the last rcv'ed FPIN */
5953 	value = phba->cgn_fpin_frequency;
5954 	cp->cgn_warn_freq = cpu_to_le16(value);
5955 	cp->cgn_alarm_freq = cpu_to_le16(value);
5956 
5957 	lvalue = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ,
5958 				     LPFC_CGN_CRC32_SEED);
5959 	cp->cgn_info_crc = cpu_to_le32(lvalue);
5960 }
5961 
5962 /**
5963  * lpfc_calc_cmf_latency - latency from start of rxate timer interval
5964  * @phba: The Hba for which this call is being executed.
5965  *
5966  * The routine calculates the latency from the beginning of the CMF timer
5967  * interval to the current point in time. It is called from IO completion
5968  * when we exceed our Bandwidth limitation for the time interval.
5969  */
5970 uint32_t
5971 lpfc_calc_cmf_latency(struct lpfc_hba *phba)
5972 {
5973 	struct timespec64 cmpl_time;
5974 	uint32_t msec = 0;
5975 
5976 	ktime_get_real_ts64(&cmpl_time);
5977 
5978 	/* This routine works on a ms granularity so sec and usec are
5979 	 * converted accordingly.
5980 	 */
5981 	if (cmpl_time.tv_sec == phba->cmf_latency.tv_sec) {
5982 		msec = (cmpl_time.tv_nsec - phba->cmf_latency.tv_nsec) /
5983 			NSEC_PER_MSEC;
5984 	} else {
5985 		if (cmpl_time.tv_nsec >= phba->cmf_latency.tv_nsec) {
5986 			msec = (cmpl_time.tv_sec -
5987 				phba->cmf_latency.tv_sec) * MSEC_PER_SEC;
5988 			msec += ((cmpl_time.tv_nsec -
5989 				  phba->cmf_latency.tv_nsec) / NSEC_PER_MSEC);
5990 		} else {
5991 			msec = (cmpl_time.tv_sec - phba->cmf_latency.tv_sec -
5992 				1) * MSEC_PER_SEC;
5993 			msec += (((NSEC_PER_SEC - phba->cmf_latency.tv_nsec) +
5994 				 cmpl_time.tv_nsec) / NSEC_PER_MSEC);
5995 		}
5996 	}
5997 	return msec;
5998 }
5999 
6000 /**
6001  * lpfc_cmf_timer -  This is the timer function for one congestion
6002  * rate interval.
6003  * @timer: Pointer to the high resolution timer that expired
6004  */
6005 static enum hrtimer_restart
6006 lpfc_cmf_timer(struct hrtimer *timer)
6007 {
6008 	struct lpfc_hba *phba = container_of(timer, struct lpfc_hba,
6009 					     cmf_timer);
6010 	struct rxtable_entry *entry;
6011 	uint32_t io_cnt;
6012 	uint32_t head, tail;
6013 	uint32_t busy, max_read;
6014 	uint64_t total, rcv, lat, mbpi, extra, cnt;
6015 	int timer_interval = LPFC_CMF_INTERVAL;
6016 	uint32_t ms;
6017 	struct lpfc_cgn_stat *cgs;
6018 	int cpu;
6019 
6020 	/* Only restart the timer if congestion mgmt is on */
6021 	if (phba->cmf_active_mode == LPFC_CFG_OFF ||
6022 	    !phba->cmf_latency.tv_sec) {
6023 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
6024 				"6224 CMF timer exit: %d %lld\n",
6025 				phba->cmf_active_mode,
6026 				(uint64_t)phba->cmf_latency.tv_sec);
6027 		return HRTIMER_NORESTART;
6028 	}
6029 
6030 	/* If pport is not ready yet, just exit and wait for
6031 	 * the next timer cycle to hit.
6032 	 */
6033 	if (!phba->pport)
6034 		goto skip;
6035 
6036 	/* Do not block SCSI IO while in the timer routine since
6037 	 * total_bytes will be cleared
6038 	 */
6039 	atomic_set(&phba->cmf_stop_io, 1);
6040 
6041 	/* First we need to calculate the actual ms between
6042 	 * the last timer interrupt and this one. We ask for
6043 	 * LPFC_CMF_INTERVAL, however the actual time may
6044 	 * vary depending on system overhead.
6045 	 */
6046 	ms = lpfc_calc_cmf_latency(phba);
6047 
6048 
6049 	/* Immediately after we calculate the time since the last
6050 	 * timer interrupt, set the start time for the next
6051 	 * interrupt
6052 	 */
6053 	ktime_get_real_ts64(&phba->cmf_latency);
6054 
6055 	phba->cmf_link_byte_count =
6056 		div_u64(phba->cmf_max_line_rate * LPFC_CMF_INTERVAL, 1000);
6057 
6058 	/* Collect all the stats from the prior timer interval */
6059 	total = 0;
6060 	io_cnt = 0;
6061 	lat = 0;
6062 	rcv = 0;
6063 	for_each_present_cpu(cpu) {
6064 		cgs = per_cpu_ptr(phba->cmf_stat, cpu);
6065 		total += atomic64_xchg(&cgs->total_bytes, 0);
6066 		io_cnt += atomic_xchg(&cgs->rx_io_cnt, 0);
6067 		lat += atomic64_xchg(&cgs->rx_latency, 0);
6068 		rcv += atomic64_xchg(&cgs->rcv_bytes, 0);
6069 	}
6070 
6071 	/* Before we issue another CMF_SYNC_WQE, retrieve the BW
6072 	 * returned from the last CMF_SYNC_WQE issued, from
6073 	 * cmf_last_sync_bw. This will be the target BW for
6074 	 * this next timer interval.
6075 	 */
6076 	if (phba->cmf_active_mode == LPFC_CFG_MANAGED &&
6077 	    phba->link_state != LPFC_LINK_DOWN &&
6078 	    phba->hba_flag & HBA_SETUP) {
6079 		mbpi = phba->cmf_last_sync_bw;
6080 		phba->cmf_last_sync_bw = 0;
6081 		extra = 0;
6082 
6083 		/* Calculate any extra bytes needed to account for the
6084 		 * timer accuracy. If we are less than LPFC_CMF_INTERVAL
6085 		 * calculate the adjustment needed for total to reflect
6086 		 * a full LPFC_CMF_INTERVAL.
6087 		 */
6088 		if (ms && ms < LPFC_CMF_INTERVAL) {
6089 			cnt = div_u64(total, ms); /* bytes per ms */
6090 			cnt *= LPFC_CMF_INTERVAL; /* what total should be */
6091 
6092 			/* If the timeout is scheduled to be shorter,
6093 			 * this value may skew the data, so cap it at mbpi.
6094 			 */
6095 			if ((phba->hba_flag & HBA_SHORT_CMF) && cnt > mbpi)
6096 				cnt = mbpi;
6097 
6098 			extra = cnt - total;
6099 		}
6100 		lpfc_issue_cmf_sync_wqe(phba, LPFC_CMF_INTERVAL, total + extra);
6101 	} else {
6102 		/* For Monitor mode or link down we want mbpi
6103 		 * to be the full link speed
6104 		 */
6105 		mbpi = phba->cmf_link_byte_count;
6106 		extra = 0;
6107 	}
6108 	phba->cmf_timer_cnt++;
6109 
6110 	if (io_cnt) {
6111 		/* Update congestion info buffer latency in us */
6112 		atomic_add(io_cnt, &phba->cgn_latency_evt_cnt);
6113 		atomic64_add(lat, &phba->cgn_latency_evt);
6114 	}
6115 	busy = atomic_xchg(&phba->cmf_busy, 0);
6116 	max_read = atomic_xchg(&phba->rx_max_read_cnt, 0);
6117 
6118 	/* Calculate MBPI for the next timer interval */
6119 	if (mbpi) {
6120 		if (mbpi > phba->cmf_link_byte_count ||
6121 		    phba->cmf_active_mode == LPFC_CFG_MONITOR)
6122 			mbpi = phba->cmf_link_byte_count;
6123 
6124 		/* Change max_bytes_per_interval to what the prior
6125 		 * CMF_SYNC_WQE cmpl indicated.
6126 		 */
6127 		if (mbpi != phba->cmf_max_bytes_per_interval)
6128 			phba->cmf_max_bytes_per_interval = mbpi;
6129 	}
6130 
6131 	/* Save rxmonitor information for debug */
6132 	if (phba->rxtable) {
6133 		head = atomic_xchg(&phba->rxtable_idx_head,
6134 				   LPFC_RXMONITOR_TABLE_IN_USE);
6135 		entry = &phba->rxtable[head];
6136 		entry->total_bytes = total;
6137 		entry->cmf_bytes = total + extra;
6138 		entry->rcv_bytes = rcv;
6139 		entry->cmf_busy = busy;
6140 		entry->cmf_info = phba->cmf_active_info;
6141 		if (io_cnt) {
6142 			entry->avg_io_latency = div_u64(lat, io_cnt);
6143 			entry->avg_io_size = div_u64(rcv, io_cnt);
6144 		} else {
6145 			entry->avg_io_latency = 0;
6146 			entry->avg_io_size = 0;
6147 		}
6148 		entry->max_read_cnt = max_read;
6149 		entry->io_cnt = io_cnt;
6150 		entry->max_bytes_per_interval = mbpi;
6151 		if (phba->cmf_active_mode == LPFC_CFG_MANAGED)
6152 			entry->timer_utilization = phba->cmf_last_ts;
6153 		else
6154 			entry->timer_utilization = ms;
6155 		entry->timer_interval = ms;
6156 		phba->cmf_last_ts = 0;
6157 
6158 		/* Increment rxtable index */
6159 		head = (head + 1) % LPFC_MAX_RXMONITOR_ENTRY;
6160 		tail = atomic_read(&phba->rxtable_idx_tail);
6161 		if (head == tail) {
6162 			tail = (tail + 1) % LPFC_MAX_RXMONITOR_ENTRY;
6163 			atomic_set(&phba->rxtable_idx_tail, tail);
6164 		}
6165 		atomic_set(&phba->rxtable_idx_head, head);
6166 	}
6167 
6168 	if (phba->cmf_active_mode == LPFC_CFG_MONITOR) {
6169 		/* If Monitor mode, check if we are oversubscribed
6170 		 * against the full line rate.
6171 		 */
6172 		if (mbpi && total > mbpi)
6173 			atomic_inc(&phba->cgn_driver_evt_cnt);
6174 	}
6175 	phba->rx_block_cnt += div_u64(rcv, 512);  /* save 512 byte block cnt */
6176 
6177 	/* Each minute save Fabric and Driver congestion information */
6178 	lpfc_cgn_save_evt_cnt(phba);
6179 
6180 	phba->hba_flag &= ~HBA_SHORT_CMF;
6181 
6182 	/* Since we need to call lpfc_cgn_save_evt_cnt every minute, on the
6183 	 * minute, adjust our next timer interval, if needed, to ensure a
6184 	 * 1 minute granularity when we get the next timer interrupt.
6185 	 */
6186 	if (time_after(jiffies + msecs_to_jiffies(LPFC_CMF_INTERVAL),
6187 		       phba->cgn_evt_timestamp)) {
6188 		timer_interval = jiffies_to_msecs(phba->cgn_evt_timestamp -
6189 						  jiffies);
6190 		if (timer_interval <= 0)
6191 			timer_interval = LPFC_CMF_INTERVAL;
6192 		else
6193 			phba->hba_flag |= HBA_SHORT_CMF;
6194 
6195 		/* If we adjust timer_interval, max_bytes_per_interval
6196 		 * needs to be adjusted as well.
6197 		 */
6198 		phba->cmf_link_byte_count = div_u64(phba->cmf_max_line_rate *
6199 						    timer_interval, 1000);
6200 		if (phba->cmf_active_mode == LPFC_CFG_MONITOR)
6201 			phba->cmf_max_bytes_per_interval =
6202 				phba->cmf_link_byte_count;
6203 	}
6204 
6205 	/* Since total_bytes has already been zero'ed, its okay to unblock
6206 	 * after max_bytes_per_interval is setup.
6207 	 */
6208 	if (atomic_xchg(&phba->cmf_bw_wait, 0))
6209 		queue_work(phba->wq, &phba->unblock_request_work);
6210 
6211 	/* SCSI IO is now unblocked */
6212 	atomic_set(&phba->cmf_stop_io, 0);
6213 
6214 skip:
6215 	hrtimer_forward_now(timer,
6216 			    ktime_set(0, timer_interval * NSEC_PER_MSEC));
6217 	return HRTIMER_RESTART;
6218 }
6219 
6220 #define trunk_link_status(__idx)\
6221 	bf_get(lpfc_acqe_fc_la_trunk_config_port##__idx, acqe_fc) ?\
6222 	       ((phba->trunk_link.link##__idx.state == LPFC_LINK_UP) ?\
6223 		"Link up" : "Link down") : "NA"
6224 /* Did port __idx reported an error */
6225 #define trunk_port_fault(__idx)\
6226 	bf_get(lpfc_acqe_fc_la_trunk_config_port##__idx, acqe_fc) ?\
6227 	       (port_fault & (1 << __idx) ? "YES" : "NO") : "NA"
6228 
6229 static void
6230 lpfc_update_trunk_link_status(struct lpfc_hba *phba,
6231 			      struct lpfc_acqe_fc_la *acqe_fc)
6232 {
6233 	uint8_t port_fault = bf_get(lpfc_acqe_fc_la_trunk_linkmask, acqe_fc);
6234 	uint8_t err = bf_get(lpfc_acqe_fc_la_trunk_fault, acqe_fc);
6235 
6236 	phba->sli4_hba.link_state.speed =
6237 		lpfc_sli4_port_speed_parse(phba, LPFC_TRAILER_CODE_FC,
6238 				bf_get(lpfc_acqe_fc_la_speed, acqe_fc));
6239 
6240 	phba->sli4_hba.link_state.logical_speed =
6241 				bf_get(lpfc_acqe_fc_la_llink_spd, acqe_fc) * 10;
6242 	/* We got FC link speed, convert to fc_linkspeed (READ_TOPOLOGY) */
6243 	phba->fc_linkspeed =
6244 		 lpfc_async_link_speed_to_read_top(
6245 				phba,
6246 				bf_get(lpfc_acqe_fc_la_speed, acqe_fc));
6247 
6248 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port0, acqe_fc)) {
6249 		phba->trunk_link.link0.state =
6250 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port0, acqe_fc)
6251 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
6252 		phba->trunk_link.link0.fault = port_fault & 0x1 ? err : 0;
6253 	}
6254 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port1, acqe_fc)) {
6255 		phba->trunk_link.link1.state =
6256 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port1, acqe_fc)
6257 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
6258 		phba->trunk_link.link1.fault = port_fault & 0x2 ? err : 0;
6259 	}
6260 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port2, acqe_fc)) {
6261 		phba->trunk_link.link2.state =
6262 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port2, acqe_fc)
6263 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
6264 		phba->trunk_link.link2.fault = port_fault & 0x4 ? err : 0;
6265 	}
6266 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port3, acqe_fc)) {
6267 		phba->trunk_link.link3.state =
6268 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port3, acqe_fc)
6269 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
6270 		phba->trunk_link.link3.fault = port_fault & 0x8 ? err : 0;
6271 	}
6272 
6273 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6274 			"2910 Async FC Trunking Event - Speed:%d\n"
6275 			"\tLogical speed:%d "
6276 			"port0: %s port1: %s port2: %s port3: %s\n",
6277 			phba->sli4_hba.link_state.speed,
6278 			phba->sli4_hba.link_state.logical_speed,
6279 			trunk_link_status(0), trunk_link_status(1),
6280 			trunk_link_status(2), trunk_link_status(3));
6281 
6282 	if (phba->cmf_active_mode != LPFC_CFG_OFF)
6283 		lpfc_cmf_signal_init(phba);
6284 
6285 	if (port_fault)
6286 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6287 				"3202 trunk error:0x%x (%s) seen on port0:%s "
6288 				/*
6289 				 * SLI-4: We have only 0xA error codes
6290 				 * defined as of now. print an appropriate
6291 				 * message in case driver needs to be updated.
6292 				 */
6293 				"port1:%s port2:%s port3:%s\n", err, err > 0xA ?
6294 				"UNDEFINED. update driver." : trunk_errmsg[err],
6295 				trunk_port_fault(0), trunk_port_fault(1),
6296 				trunk_port_fault(2), trunk_port_fault(3));
6297 }
6298 
6299 
6300 /**
6301  * lpfc_sli4_async_fc_evt - Process the asynchronous FC link event
6302  * @phba: pointer to lpfc hba data structure.
6303  * @acqe_fc: pointer to the async fc completion queue entry.
6304  *
6305  * This routine is to handle the SLI4 asynchronous FC event. It will simply log
6306  * that the event was received and then issue a read_topology mailbox command so
6307  * that the rest of the driver will treat it the same as SLI3.
6308  **/
6309 static void
6310 lpfc_sli4_async_fc_evt(struct lpfc_hba *phba, struct lpfc_acqe_fc_la *acqe_fc)
6311 {
6312 	LPFC_MBOXQ_t *pmb;
6313 	MAILBOX_t *mb;
6314 	struct lpfc_mbx_read_top *la;
6315 	int rc;
6316 
6317 	if (bf_get(lpfc_trailer_type, acqe_fc) !=
6318 	    LPFC_FC_LA_EVENT_TYPE_FC_LINK) {
6319 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6320 				"2895 Non FC link Event detected.(%d)\n",
6321 				bf_get(lpfc_trailer_type, acqe_fc));
6322 		return;
6323 	}
6324 
6325 	if (bf_get(lpfc_acqe_fc_la_att_type, acqe_fc) ==
6326 	    LPFC_FC_LA_TYPE_TRUNKING_EVENT) {
6327 		lpfc_update_trunk_link_status(phba, acqe_fc);
6328 		return;
6329 	}
6330 
6331 	/* Keep the link status for extra SLI4 state machine reference */
6332 	phba->sli4_hba.link_state.speed =
6333 			lpfc_sli4_port_speed_parse(phba, LPFC_TRAILER_CODE_FC,
6334 				bf_get(lpfc_acqe_fc_la_speed, acqe_fc));
6335 	phba->sli4_hba.link_state.duplex = LPFC_ASYNC_LINK_DUPLEX_FULL;
6336 	phba->sli4_hba.link_state.topology =
6337 				bf_get(lpfc_acqe_fc_la_topology, acqe_fc);
6338 	phba->sli4_hba.link_state.status =
6339 				bf_get(lpfc_acqe_fc_la_att_type, acqe_fc);
6340 	phba->sli4_hba.link_state.type =
6341 				bf_get(lpfc_acqe_fc_la_port_type, acqe_fc);
6342 	phba->sli4_hba.link_state.number =
6343 				bf_get(lpfc_acqe_fc_la_port_number, acqe_fc);
6344 	phba->sli4_hba.link_state.fault =
6345 				bf_get(lpfc_acqe_link_fault, acqe_fc);
6346 
6347 	if (bf_get(lpfc_acqe_fc_la_att_type, acqe_fc) ==
6348 	    LPFC_FC_LA_TYPE_LINK_DOWN)
6349 		phba->sli4_hba.link_state.logical_speed = 0;
6350 	else if	(!phba->sli4_hba.conf_trunk)
6351 		phba->sli4_hba.link_state.logical_speed =
6352 				bf_get(lpfc_acqe_fc_la_llink_spd, acqe_fc) * 10;
6353 
6354 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6355 			"2896 Async FC event - Speed:%dGBaud Topology:x%x "
6356 			"LA Type:x%x Port Type:%d Port Number:%d Logical speed:"
6357 			"%dMbps Fault:%d\n",
6358 			phba->sli4_hba.link_state.speed,
6359 			phba->sli4_hba.link_state.topology,
6360 			phba->sli4_hba.link_state.status,
6361 			phba->sli4_hba.link_state.type,
6362 			phba->sli4_hba.link_state.number,
6363 			phba->sli4_hba.link_state.logical_speed,
6364 			phba->sli4_hba.link_state.fault);
6365 	pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6366 	if (!pmb) {
6367 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6368 				"2897 The mboxq allocation failed\n");
6369 		return;
6370 	}
6371 	rc = lpfc_mbox_rsrc_prep(phba, pmb);
6372 	if (rc) {
6373 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6374 				"2898 The mboxq prep failed\n");
6375 		goto out_free_pmb;
6376 	}
6377 
6378 	/* Cleanup any outstanding ELS commands */
6379 	lpfc_els_flush_all_cmd(phba);
6380 
6381 	/* Block ELS IOCBs until we have done process link event */
6382 	phba->sli4_hba.els_wq->pring->flag |= LPFC_STOP_IOCB_EVENT;
6383 
6384 	/* Update link event statistics */
6385 	phba->sli.slistat.link_event++;
6386 
6387 	/* Create lpfc_handle_latt mailbox command from link ACQE */
6388 	lpfc_read_topology(phba, pmb, (struct lpfc_dmabuf *)pmb->ctx_buf);
6389 	pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
6390 	pmb->vport = phba->pport;
6391 
6392 	if (phba->sli4_hba.link_state.status != LPFC_FC_LA_TYPE_LINK_UP) {
6393 		phba->link_flag &= ~(LS_MDS_LINK_DOWN | LS_MDS_LOOPBACK);
6394 
6395 		switch (phba->sli4_hba.link_state.status) {
6396 		case LPFC_FC_LA_TYPE_MDS_LINK_DOWN:
6397 			phba->link_flag |= LS_MDS_LINK_DOWN;
6398 			break;
6399 		case LPFC_FC_LA_TYPE_MDS_LOOPBACK:
6400 			phba->link_flag |= LS_MDS_LOOPBACK;
6401 			break;
6402 		default:
6403 			break;
6404 		}
6405 
6406 		/* Initialize completion status */
6407 		mb = &pmb->u.mb;
6408 		mb->mbxStatus = MBX_SUCCESS;
6409 
6410 		/* Parse port fault information field */
6411 		lpfc_sli4_parse_latt_fault(phba, (void *)acqe_fc);
6412 
6413 		/* Parse and translate link attention fields */
6414 		la = (struct lpfc_mbx_read_top *)&pmb->u.mb.un.varReadTop;
6415 		la->eventTag = acqe_fc->event_tag;
6416 
6417 		if (phba->sli4_hba.link_state.status ==
6418 		    LPFC_FC_LA_TYPE_UNEXP_WWPN) {
6419 			bf_set(lpfc_mbx_read_top_att_type, la,
6420 			       LPFC_FC_LA_TYPE_UNEXP_WWPN);
6421 		} else {
6422 			bf_set(lpfc_mbx_read_top_att_type, la,
6423 			       LPFC_FC_LA_TYPE_LINK_DOWN);
6424 		}
6425 		/* Invoke the mailbox command callback function */
6426 		lpfc_mbx_cmpl_read_topology(phba, pmb);
6427 
6428 		return;
6429 	}
6430 
6431 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
6432 	if (rc == MBX_NOT_FINISHED)
6433 		goto out_free_pmb;
6434 	return;
6435 
6436 out_free_pmb:
6437 	lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
6438 }
6439 
6440 /**
6441  * lpfc_sli4_async_sli_evt - Process the asynchronous SLI link event
6442  * @phba: pointer to lpfc hba data structure.
6443  * @acqe_sli: pointer to the async SLI completion queue entry.
6444  *
6445  * This routine is to handle the SLI4 asynchronous SLI events.
6446  **/
6447 static void
6448 lpfc_sli4_async_sli_evt(struct lpfc_hba *phba, struct lpfc_acqe_sli *acqe_sli)
6449 {
6450 	char port_name;
6451 	char message[128];
6452 	uint8_t status;
6453 	uint8_t evt_type;
6454 	uint8_t operational = 0;
6455 	struct temp_event temp_event_data;
6456 	struct lpfc_acqe_misconfigured_event *misconfigured;
6457 	struct lpfc_acqe_cgn_signal *cgn_signal;
6458 	struct Scsi_Host  *shost;
6459 	struct lpfc_vport **vports;
6460 	int rc, i, cnt;
6461 
6462 	evt_type = bf_get(lpfc_trailer_type, acqe_sli);
6463 
6464 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6465 			"2901 Async SLI event - Type:%d, Event Data: x%08x "
6466 			"x%08x x%08x x%08x\n", evt_type,
6467 			acqe_sli->event_data1, acqe_sli->event_data2,
6468 			acqe_sli->reserved, acqe_sli->trailer);
6469 
6470 	port_name = phba->Port[0];
6471 	if (port_name == 0x00)
6472 		port_name = '?'; /* get port name is empty */
6473 
6474 	switch (evt_type) {
6475 	case LPFC_SLI_EVENT_TYPE_OVER_TEMP:
6476 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
6477 		temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
6478 		temp_event_data.data = (uint32_t)acqe_sli->event_data1;
6479 
6480 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6481 				"3190 Over Temperature:%d Celsius- Port Name %c\n",
6482 				acqe_sli->event_data1, port_name);
6483 
6484 		phba->sfp_warning |= LPFC_TRANSGRESSION_HIGH_TEMPERATURE;
6485 		shost = lpfc_shost_from_vport(phba->pport);
6486 		fc_host_post_vendor_event(shost, fc_get_event_number(),
6487 					  sizeof(temp_event_data),
6488 					  (char *)&temp_event_data,
6489 					  SCSI_NL_VID_TYPE_PCI
6490 					  | PCI_VENDOR_ID_EMULEX);
6491 		break;
6492 	case LPFC_SLI_EVENT_TYPE_NORM_TEMP:
6493 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
6494 		temp_event_data.event_code = LPFC_NORMAL_TEMP;
6495 		temp_event_data.data = (uint32_t)acqe_sli->event_data1;
6496 
6497 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6498 				"3191 Normal Temperature:%d Celsius - Port Name %c\n",
6499 				acqe_sli->event_data1, port_name);
6500 
6501 		shost = lpfc_shost_from_vport(phba->pport);
6502 		fc_host_post_vendor_event(shost, fc_get_event_number(),
6503 					  sizeof(temp_event_data),
6504 					  (char *)&temp_event_data,
6505 					  SCSI_NL_VID_TYPE_PCI
6506 					  | PCI_VENDOR_ID_EMULEX);
6507 		break;
6508 	case LPFC_SLI_EVENT_TYPE_MISCONFIGURED:
6509 		misconfigured = (struct lpfc_acqe_misconfigured_event *)
6510 					&acqe_sli->event_data1;
6511 
6512 		/* fetch the status for this port */
6513 		switch (phba->sli4_hba.lnk_info.lnk_no) {
6514 		case LPFC_LINK_NUMBER_0:
6515 			status = bf_get(lpfc_sli_misconfigured_port0_state,
6516 					&misconfigured->theEvent);
6517 			operational = bf_get(lpfc_sli_misconfigured_port0_op,
6518 					&misconfigured->theEvent);
6519 			break;
6520 		case LPFC_LINK_NUMBER_1:
6521 			status = bf_get(lpfc_sli_misconfigured_port1_state,
6522 					&misconfigured->theEvent);
6523 			operational = bf_get(lpfc_sli_misconfigured_port1_op,
6524 					&misconfigured->theEvent);
6525 			break;
6526 		case LPFC_LINK_NUMBER_2:
6527 			status = bf_get(lpfc_sli_misconfigured_port2_state,
6528 					&misconfigured->theEvent);
6529 			operational = bf_get(lpfc_sli_misconfigured_port2_op,
6530 					&misconfigured->theEvent);
6531 			break;
6532 		case LPFC_LINK_NUMBER_3:
6533 			status = bf_get(lpfc_sli_misconfigured_port3_state,
6534 					&misconfigured->theEvent);
6535 			operational = bf_get(lpfc_sli_misconfigured_port3_op,
6536 					&misconfigured->theEvent);
6537 			break;
6538 		default:
6539 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6540 					"3296 "
6541 					"LPFC_SLI_EVENT_TYPE_MISCONFIGURED "
6542 					"event: Invalid link %d",
6543 					phba->sli4_hba.lnk_info.lnk_no);
6544 			return;
6545 		}
6546 
6547 		/* Skip if optic state unchanged */
6548 		if (phba->sli4_hba.lnk_info.optic_state == status)
6549 			return;
6550 
6551 		switch (status) {
6552 		case LPFC_SLI_EVENT_STATUS_VALID:
6553 			sprintf(message, "Physical Link is functional");
6554 			break;
6555 		case LPFC_SLI_EVENT_STATUS_NOT_PRESENT:
6556 			sprintf(message, "Optics faulted/incorrectly "
6557 				"installed/not installed - Reseat optics, "
6558 				"if issue not resolved, replace.");
6559 			break;
6560 		case LPFC_SLI_EVENT_STATUS_WRONG_TYPE:
6561 			sprintf(message,
6562 				"Optics of two types installed - Remove one "
6563 				"optic or install matching pair of optics.");
6564 			break;
6565 		case LPFC_SLI_EVENT_STATUS_UNSUPPORTED:
6566 			sprintf(message, "Incompatible optics - Replace with "
6567 				"compatible optics for card to function.");
6568 			break;
6569 		case LPFC_SLI_EVENT_STATUS_UNQUALIFIED:
6570 			sprintf(message, "Unqualified optics - Replace with "
6571 				"Avago optics for Warranty and Technical "
6572 				"Support - Link is%s operational",
6573 				(operational) ? " not" : "");
6574 			break;
6575 		case LPFC_SLI_EVENT_STATUS_UNCERTIFIED:
6576 			sprintf(message, "Uncertified optics - Replace with "
6577 				"Avago-certified optics to enable link "
6578 				"operation - Link is%s operational",
6579 				(operational) ? " not" : "");
6580 			break;
6581 		default:
6582 			/* firmware is reporting a status we don't know about */
6583 			sprintf(message, "Unknown event status x%02x", status);
6584 			break;
6585 		}
6586 
6587 		/* Issue READ_CONFIG mbox command to refresh supported speeds */
6588 		rc = lpfc_sli4_read_config(phba);
6589 		if (rc) {
6590 			phba->lmt = 0;
6591 			lpfc_printf_log(phba, KERN_ERR,
6592 					LOG_TRACE_EVENT,
6593 					"3194 Unable to retrieve supported "
6594 					"speeds, rc = 0x%x\n", rc);
6595 		}
6596 		rc = lpfc_sli4_refresh_params(phba);
6597 		if (rc) {
6598 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6599 					"3174 Unable to update pls support, "
6600 					"rc x%x\n", rc);
6601 		}
6602 		vports = lpfc_create_vport_work_array(phba);
6603 		if (vports != NULL) {
6604 			for (i = 0; i <= phba->max_vports && vports[i] != NULL;
6605 					i++) {
6606 				shost = lpfc_shost_from_vport(vports[i]);
6607 				lpfc_host_supported_speeds_set(shost);
6608 			}
6609 		}
6610 		lpfc_destroy_vport_work_array(phba, vports);
6611 
6612 		phba->sli4_hba.lnk_info.optic_state = status;
6613 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6614 				"3176 Port Name %c %s\n", port_name, message);
6615 		break;
6616 	case LPFC_SLI_EVENT_TYPE_REMOTE_DPORT:
6617 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6618 				"3192 Remote DPort Test Initiated - "
6619 				"Event Data1:x%08x Event Data2: x%08x\n",
6620 				acqe_sli->event_data1, acqe_sli->event_data2);
6621 		break;
6622 	case LPFC_SLI_EVENT_TYPE_PORT_PARAMS_CHG:
6623 		/* Call FW to obtain active parms */
6624 		lpfc_sli4_cgn_parm_chg_evt(phba);
6625 		break;
6626 	case LPFC_SLI_EVENT_TYPE_MISCONF_FAWWN:
6627 		/* Misconfigured WWN. Reports that the SLI Port is configured
6628 		 * to use FA-WWN, but the attached device doesn’t support it.
6629 		 * Event Data1 - N.A, Event Data2 - N.A
6630 		 * This event only happens on the physical port.
6631 		 */
6632 		lpfc_log_msg(phba, KERN_WARNING, LOG_SLI | LOG_DISCOVERY,
6633 			     "2699 Misconfigured FA-PWWN - Attached device "
6634 			     "does not support FA-PWWN\n");
6635 		phba->sli4_hba.fawwpn_flag &= ~LPFC_FAWWPN_FABRIC;
6636 		memset(phba->pport->fc_portname.u.wwn, 0,
6637 		       sizeof(struct lpfc_name));
6638 		break;
6639 	case LPFC_SLI_EVENT_TYPE_EEPROM_FAILURE:
6640 		/* EEPROM failure. No driver action is required */
6641 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6642 			     "2518 EEPROM failure - "
6643 			     "Event Data1: x%08x Event Data2: x%08x\n",
6644 			     acqe_sli->event_data1, acqe_sli->event_data2);
6645 		break;
6646 	case LPFC_SLI_EVENT_TYPE_CGN_SIGNAL:
6647 		if (phba->cmf_active_mode == LPFC_CFG_OFF)
6648 			break;
6649 		cgn_signal = (struct lpfc_acqe_cgn_signal *)
6650 					&acqe_sli->event_data1;
6651 		phba->cgn_acqe_cnt++;
6652 
6653 		cnt = bf_get(lpfc_warn_acqe, cgn_signal);
6654 		atomic64_add(cnt, &phba->cgn_acqe_stat.warn);
6655 		atomic64_add(cgn_signal->alarm_cnt, &phba->cgn_acqe_stat.alarm);
6656 
6657 		/* no threshold for CMF, even 1 signal will trigger an event */
6658 
6659 		/* Alarm overrides warning, so check that first */
6660 		if (cgn_signal->alarm_cnt) {
6661 			if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
6662 				/* Keep track of alarm cnt for CMF_SYNC_WQE */
6663 				atomic_add(cgn_signal->alarm_cnt,
6664 					   &phba->cgn_sync_alarm_cnt);
6665 			}
6666 		} else if (cnt) {
6667 			/* signal action needs to be taken */
6668 			if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY ||
6669 			    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
6670 				/* Keep track of warning cnt for CMF_SYNC_WQE */
6671 				atomic_add(cnt, &phba->cgn_sync_warn_cnt);
6672 			}
6673 		}
6674 		break;
6675 	default:
6676 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6677 				"3193 Unrecognized SLI event, type: 0x%x",
6678 				evt_type);
6679 		break;
6680 	}
6681 }
6682 
6683 /**
6684  * lpfc_sli4_perform_vport_cvl - Perform clear virtual link on a vport
6685  * @vport: pointer to vport data structure.
6686  *
6687  * This routine is to perform Clear Virtual Link (CVL) on a vport in
6688  * response to a CVL event.
6689  *
6690  * Return the pointer to the ndlp with the vport if successful, otherwise
6691  * return NULL.
6692  **/
6693 static struct lpfc_nodelist *
6694 lpfc_sli4_perform_vport_cvl(struct lpfc_vport *vport)
6695 {
6696 	struct lpfc_nodelist *ndlp;
6697 	struct Scsi_Host *shost;
6698 	struct lpfc_hba *phba;
6699 
6700 	if (!vport)
6701 		return NULL;
6702 	phba = vport->phba;
6703 	if (!phba)
6704 		return NULL;
6705 	ndlp = lpfc_findnode_did(vport, Fabric_DID);
6706 	if (!ndlp) {
6707 		/* Cannot find existing Fabric ndlp, so allocate a new one */
6708 		ndlp = lpfc_nlp_init(vport, Fabric_DID);
6709 		if (!ndlp)
6710 			return NULL;
6711 		/* Set the node type */
6712 		ndlp->nlp_type |= NLP_FABRIC;
6713 		/* Put ndlp onto node list */
6714 		lpfc_enqueue_node(vport, ndlp);
6715 	}
6716 	if ((phba->pport->port_state < LPFC_FLOGI) &&
6717 		(phba->pport->port_state != LPFC_VPORT_FAILED))
6718 		return NULL;
6719 	/* If virtual link is not yet instantiated ignore CVL */
6720 	if ((vport != phba->pport) && (vport->port_state < LPFC_FDISC)
6721 		&& (vport->port_state != LPFC_VPORT_FAILED))
6722 		return NULL;
6723 	shost = lpfc_shost_from_vport(vport);
6724 	if (!shost)
6725 		return NULL;
6726 	lpfc_linkdown_port(vport);
6727 	lpfc_cleanup_pending_mbox(vport);
6728 	spin_lock_irq(shost->host_lock);
6729 	vport->fc_flag |= FC_VPORT_CVL_RCVD;
6730 	spin_unlock_irq(shost->host_lock);
6731 
6732 	return ndlp;
6733 }
6734 
6735 /**
6736  * lpfc_sli4_perform_all_vport_cvl - Perform clear virtual link on all vports
6737  * @phba: pointer to lpfc hba data structure.
6738  *
6739  * This routine is to perform Clear Virtual Link (CVL) on all vports in
6740  * response to a FCF dead event.
6741  **/
6742 static void
6743 lpfc_sli4_perform_all_vport_cvl(struct lpfc_hba *phba)
6744 {
6745 	struct lpfc_vport **vports;
6746 	int i;
6747 
6748 	vports = lpfc_create_vport_work_array(phba);
6749 	if (vports)
6750 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++)
6751 			lpfc_sli4_perform_vport_cvl(vports[i]);
6752 	lpfc_destroy_vport_work_array(phba, vports);
6753 }
6754 
6755 /**
6756  * lpfc_sli4_async_fip_evt - Process the asynchronous FCoE FIP event
6757  * @phba: pointer to lpfc hba data structure.
6758  * @acqe_fip: pointer to the async fcoe completion queue entry.
6759  *
6760  * This routine is to handle the SLI4 asynchronous fcoe event.
6761  **/
6762 static void
6763 lpfc_sli4_async_fip_evt(struct lpfc_hba *phba,
6764 			struct lpfc_acqe_fip *acqe_fip)
6765 {
6766 	uint8_t event_type = bf_get(lpfc_trailer_type, acqe_fip);
6767 	int rc;
6768 	struct lpfc_vport *vport;
6769 	struct lpfc_nodelist *ndlp;
6770 	int active_vlink_present;
6771 	struct lpfc_vport **vports;
6772 	int i;
6773 
6774 	phba->fc_eventTag = acqe_fip->event_tag;
6775 	phba->fcoe_eventtag = acqe_fip->event_tag;
6776 	switch (event_type) {
6777 	case LPFC_FIP_EVENT_TYPE_NEW_FCF:
6778 	case LPFC_FIP_EVENT_TYPE_FCF_PARAM_MOD:
6779 		if (event_type == LPFC_FIP_EVENT_TYPE_NEW_FCF)
6780 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6781 					"2546 New FCF event, evt_tag:x%x, "
6782 					"index:x%x\n",
6783 					acqe_fip->event_tag,
6784 					acqe_fip->index);
6785 		else
6786 			lpfc_printf_log(phba, KERN_WARNING, LOG_FIP |
6787 					LOG_DISCOVERY,
6788 					"2788 FCF param modified event, "
6789 					"evt_tag:x%x, index:x%x\n",
6790 					acqe_fip->event_tag,
6791 					acqe_fip->index);
6792 		if (phba->fcf.fcf_flag & FCF_DISCOVERY) {
6793 			/*
6794 			 * During period of FCF discovery, read the FCF
6795 			 * table record indexed by the event to update
6796 			 * FCF roundrobin failover eligible FCF bmask.
6797 			 */
6798 			lpfc_printf_log(phba, KERN_INFO, LOG_FIP |
6799 					LOG_DISCOVERY,
6800 					"2779 Read FCF (x%x) for updating "
6801 					"roundrobin FCF failover bmask\n",
6802 					acqe_fip->index);
6803 			rc = lpfc_sli4_read_fcf_rec(phba, acqe_fip->index);
6804 		}
6805 
6806 		/* If the FCF discovery is in progress, do nothing. */
6807 		spin_lock_irq(&phba->hbalock);
6808 		if (phba->hba_flag & FCF_TS_INPROG) {
6809 			spin_unlock_irq(&phba->hbalock);
6810 			break;
6811 		}
6812 		/* If fast FCF failover rescan event is pending, do nothing */
6813 		if (phba->fcf.fcf_flag & (FCF_REDISC_EVT | FCF_REDISC_PEND)) {
6814 			spin_unlock_irq(&phba->hbalock);
6815 			break;
6816 		}
6817 
6818 		/* If the FCF has been in discovered state, do nothing. */
6819 		if (phba->fcf.fcf_flag & FCF_SCAN_DONE) {
6820 			spin_unlock_irq(&phba->hbalock);
6821 			break;
6822 		}
6823 		spin_unlock_irq(&phba->hbalock);
6824 
6825 		/* Otherwise, scan the entire FCF table and re-discover SAN */
6826 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
6827 				"2770 Start FCF table scan per async FCF "
6828 				"event, evt_tag:x%x, index:x%x\n",
6829 				acqe_fip->event_tag, acqe_fip->index);
6830 		rc = lpfc_sli4_fcf_scan_read_fcf_rec(phba,
6831 						     LPFC_FCOE_FCF_GET_FIRST);
6832 		if (rc)
6833 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6834 					"2547 Issue FCF scan read FCF mailbox "
6835 					"command failed (x%x)\n", rc);
6836 		break;
6837 
6838 	case LPFC_FIP_EVENT_TYPE_FCF_TABLE_FULL:
6839 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6840 				"2548 FCF Table full count 0x%x tag 0x%x\n",
6841 				bf_get(lpfc_acqe_fip_fcf_count, acqe_fip),
6842 				acqe_fip->event_tag);
6843 		break;
6844 
6845 	case LPFC_FIP_EVENT_TYPE_FCF_DEAD:
6846 		phba->fcoe_cvl_eventtag = acqe_fip->event_tag;
6847 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6848 				"2549 FCF (x%x) disconnected from network, "
6849 				 "tag:x%x\n", acqe_fip->index,
6850 				 acqe_fip->event_tag);
6851 		/*
6852 		 * If we are in the middle of FCF failover process, clear
6853 		 * the corresponding FCF bit in the roundrobin bitmap.
6854 		 */
6855 		spin_lock_irq(&phba->hbalock);
6856 		if ((phba->fcf.fcf_flag & FCF_DISCOVERY) &&
6857 		    (phba->fcf.current_rec.fcf_indx != acqe_fip->index)) {
6858 			spin_unlock_irq(&phba->hbalock);
6859 			/* Update FLOGI FCF failover eligible FCF bmask */
6860 			lpfc_sli4_fcf_rr_index_clear(phba, acqe_fip->index);
6861 			break;
6862 		}
6863 		spin_unlock_irq(&phba->hbalock);
6864 
6865 		/* If the event is not for currently used fcf do nothing */
6866 		if (phba->fcf.current_rec.fcf_indx != acqe_fip->index)
6867 			break;
6868 
6869 		/*
6870 		 * Otherwise, request the port to rediscover the entire FCF
6871 		 * table for a fast recovery from case that the current FCF
6872 		 * is no longer valid as we are not in the middle of FCF
6873 		 * failover process already.
6874 		 */
6875 		spin_lock_irq(&phba->hbalock);
6876 		/* Mark the fast failover process in progress */
6877 		phba->fcf.fcf_flag |= FCF_DEAD_DISC;
6878 		spin_unlock_irq(&phba->hbalock);
6879 
6880 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
6881 				"2771 Start FCF fast failover process due to "
6882 				"FCF DEAD event: evt_tag:x%x, fcf_index:x%x "
6883 				"\n", acqe_fip->event_tag, acqe_fip->index);
6884 		rc = lpfc_sli4_redisc_fcf_table(phba);
6885 		if (rc) {
6886 			lpfc_printf_log(phba, KERN_ERR, LOG_FIP |
6887 					LOG_TRACE_EVENT,
6888 					"2772 Issue FCF rediscover mailbox "
6889 					"command failed, fail through to FCF "
6890 					"dead event\n");
6891 			spin_lock_irq(&phba->hbalock);
6892 			phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
6893 			spin_unlock_irq(&phba->hbalock);
6894 			/*
6895 			 * Last resort will fail over by treating this
6896 			 * as a link down to FCF registration.
6897 			 */
6898 			lpfc_sli4_fcf_dead_failthrough(phba);
6899 		} else {
6900 			/* Reset FCF roundrobin bmask for new discovery */
6901 			lpfc_sli4_clear_fcf_rr_bmask(phba);
6902 			/*
6903 			 * Handling fast FCF failover to a DEAD FCF event is
6904 			 * considered equalivant to receiving CVL to all vports.
6905 			 */
6906 			lpfc_sli4_perform_all_vport_cvl(phba);
6907 		}
6908 		break;
6909 	case LPFC_FIP_EVENT_TYPE_CVL:
6910 		phba->fcoe_cvl_eventtag = acqe_fip->event_tag;
6911 		lpfc_printf_log(phba, KERN_ERR,
6912 				LOG_TRACE_EVENT,
6913 			"2718 Clear Virtual Link Received for VPI 0x%x"
6914 			" tag 0x%x\n", acqe_fip->index, acqe_fip->event_tag);
6915 
6916 		vport = lpfc_find_vport_by_vpid(phba,
6917 						acqe_fip->index);
6918 		ndlp = lpfc_sli4_perform_vport_cvl(vport);
6919 		if (!ndlp)
6920 			break;
6921 		active_vlink_present = 0;
6922 
6923 		vports = lpfc_create_vport_work_array(phba);
6924 		if (vports) {
6925 			for (i = 0; i <= phba->max_vports && vports[i] != NULL;
6926 					i++) {
6927 				if ((!(vports[i]->fc_flag &
6928 					FC_VPORT_CVL_RCVD)) &&
6929 					(vports[i]->port_state > LPFC_FDISC)) {
6930 					active_vlink_present = 1;
6931 					break;
6932 				}
6933 			}
6934 			lpfc_destroy_vport_work_array(phba, vports);
6935 		}
6936 
6937 		/*
6938 		 * Don't re-instantiate if vport is marked for deletion.
6939 		 * If we are here first then vport_delete is going to wait
6940 		 * for discovery to complete.
6941 		 */
6942 		if (!(vport->load_flag & FC_UNLOADING) &&
6943 					active_vlink_present) {
6944 			/*
6945 			 * If there are other active VLinks present,
6946 			 * re-instantiate the Vlink using FDISC.
6947 			 */
6948 			mod_timer(&ndlp->nlp_delayfunc,
6949 				  jiffies + msecs_to_jiffies(1000));
6950 			spin_lock_irq(&ndlp->lock);
6951 			ndlp->nlp_flag |= NLP_DELAY_TMO;
6952 			spin_unlock_irq(&ndlp->lock);
6953 			ndlp->nlp_last_elscmd = ELS_CMD_FDISC;
6954 			vport->port_state = LPFC_FDISC;
6955 		} else {
6956 			/*
6957 			 * Otherwise, we request port to rediscover
6958 			 * the entire FCF table for a fast recovery
6959 			 * from possible case that the current FCF
6960 			 * is no longer valid if we are not already
6961 			 * in the FCF failover process.
6962 			 */
6963 			spin_lock_irq(&phba->hbalock);
6964 			if (phba->fcf.fcf_flag & FCF_DISCOVERY) {
6965 				spin_unlock_irq(&phba->hbalock);
6966 				break;
6967 			}
6968 			/* Mark the fast failover process in progress */
6969 			phba->fcf.fcf_flag |= FCF_ACVL_DISC;
6970 			spin_unlock_irq(&phba->hbalock);
6971 			lpfc_printf_log(phba, KERN_INFO, LOG_FIP |
6972 					LOG_DISCOVERY,
6973 					"2773 Start FCF failover per CVL, "
6974 					"evt_tag:x%x\n", acqe_fip->event_tag);
6975 			rc = lpfc_sli4_redisc_fcf_table(phba);
6976 			if (rc) {
6977 				lpfc_printf_log(phba, KERN_ERR, LOG_FIP |
6978 						LOG_TRACE_EVENT,
6979 						"2774 Issue FCF rediscover "
6980 						"mailbox command failed, "
6981 						"through to CVL event\n");
6982 				spin_lock_irq(&phba->hbalock);
6983 				phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
6984 				spin_unlock_irq(&phba->hbalock);
6985 				/*
6986 				 * Last resort will be re-try on the
6987 				 * the current registered FCF entry.
6988 				 */
6989 				lpfc_retry_pport_discovery(phba);
6990 			} else
6991 				/*
6992 				 * Reset FCF roundrobin bmask for new
6993 				 * discovery.
6994 				 */
6995 				lpfc_sli4_clear_fcf_rr_bmask(phba);
6996 		}
6997 		break;
6998 	default:
6999 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7000 				"0288 Unknown FCoE event type 0x%x event tag "
7001 				"0x%x\n", event_type, acqe_fip->event_tag);
7002 		break;
7003 	}
7004 }
7005 
7006 /**
7007  * lpfc_sli4_async_dcbx_evt - Process the asynchronous dcbx event
7008  * @phba: pointer to lpfc hba data structure.
7009  * @acqe_dcbx: pointer to the async dcbx completion queue entry.
7010  *
7011  * This routine is to handle the SLI4 asynchronous dcbx event.
7012  **/
7013 static void
7014 lpfc_sli4_async_dcbx_evt(struct lpfc_hba *phba,
7015 			 struct lpfc_acqe_dcbx *acqe_dcbx)
7016 {
7017 	phba->fc_eventTag = acqe_dcbx->event_tag;
7018 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7019 			"0290 The SLI4 DCBX asynchronous event is not "
7020 			"handled yet\n");
7021 }
7022 
7023 /**
7024  * lpfc_sli4_async_grp5_evt - Process the asynchronous group5 event
7025  * @phba: pointer to lpfc hba data structure.
7026  * @acqe_grp5: pointer to the async grp5 completion queue entry.
7027  *
7028  * This routine is to handle the SLI4 asynchronous grp5 event. A grp5 event
7029  * is an asynchronous notified of a logical link speed change.  The Port
7030  * reports the logical link speed in units of 10Mbps.
7031  **/
7032 static void
7033 lpfc_sli4_async_grp5_evt(struct lpfc_hba *phba,
7034 			 struct lpfc_acqe_grp5 *acqe_grp5)
7035 {
7036 	uint16_t prev_ll_spd;
7037 
7038 	phba->fc_eventTag = acqe_grp5->event_tag;
7039 	phba->fcoe_eventtag = acqe_grp5->event_tag;
7040 	prev_ll_spd = phba->sli4_hba.link_state.logical_speed;
7041 	phba->sli4_hba.link_state.logical_speed =
7042 		(bf_get(lpfc_acqe_grp5_llink_spd, acqe_grp5)) * 10;
7043 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
7044 			"2789 GRP5 Async Event: Updating logical link speed "
7045 			"from %dMbps to %dMbps\n", prev_ll_spd,
7046 			phba->sli4_hba.link_state.logical_speed);
7047 }
7048 
7049 /**
7050  * lpfc_sli4_async_cmstat_evt - Process the asynchronous cmstat event
7051  * @phba: pointer to lpfc hba data structure.
7052  *
7053  * This routine is to handle the SLI4 asynchronous cmstat event. A cmstat event
7054  * is an asynchronous notification of a request to reset CM stats.
7055  **/
7056 static void
7057 lpfc_sli4_async_cmstat_evt(struct lpfc_hba *phba)
7058 {
7059 	if (!phba->cgn_i)
7060 		return;
7061 	lpfc_init_congestion_stat(phba);
7062 }
7063 
7064 /**
7065  * lpfc_cgn_params_val - Validate FW congestion parameters.
7066  * @phba: pointer to lpfc hba data structure.
7067  * @p_cfg_param: pointer to FW provided congestion parameters.
7068  *
7069  * This routine validates the congestion parameters passed
7070  * by the FW to the driver via an ACQE event.
7071  **/
7072 static void
7073 lpfc_cgn_params_val(struct lpfc_hba *phba, struct lpfc_cgn_param *p_cfg_param)
7074 {
7075 	spin_lock_irq(&phba->hbalock);
7076 
7077 	if (!lpfc_rangecheck(p_cfg_param->cgn_param_mode, LPFC_CFG_OFF,
7078 			     LPFC_CFG_MONITOR)) {
7079 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT,
7080 				"6225 CMF mode param out of range: %d\n",
7081 				 p_cfg_param->cgn_param_mode);
7082 		p_cfg_param->cgn_param_mode = LPFC_CFG_OFF;
7083 	}
7084 
7085 	spin_unlock_irq(&phba->hbalock);
7086 }
7087 
7088 /**
7089  * lpfc_cgn_params_parse - Process a FW cong parm change event
7090  * @phba: pointer to lpfc hba data structure.
7091  * @p_cgn_param: pointer to a data buffer with the FW cong params.
7092  * @len: the size of pdata in bytes.
7093  *
7094  * This routine validates the congestion management buffer signature
7095  * from the FW, validates the contents and makes corrections for
7096  * valid, in-range values.  If the signature magic is correct and
7097  * after parameter validation, the contents are copied to the driver's
7098  * @phba structure. If the magic is incorrect, an error message is
7099  * logged.
7100  **/
7101 static void
7102 lpfc_cgn_params_parse(struct lpfc_hba *phba,
7103 		      struct lpfc_cgn_param *p_cgn_param, uint32_t len)
7104 {
7105 	struct lpfc_cgn_info *cp;
7106 	uint32_t crc, oldmode;
7107 
7108 	/* Make sure the FW has encoded the correct magic number to
7109 	 * validate the congestion parameter in FW memory.
7110 	 */
7111 	if (p_cgn_param->cgn_param_magic == LPFC_CFG_PARAM_MAGIC_NUM) {
7112 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT | LOG_INIT,
7113 				"4668 FW cgn parm buffer data: "
7114 				"magic 0x%x version %d mode %d "
7115 				"level0 %d level1 %d "
7116 				"level2 %d byte13 %d "
7117 				"byte14 %d byte15 %d "
7118 				"byte11 %d byte12 %d activeMode %d\n",
7119 				p_cgn_param->cgn_param_magic,
7120 				p_cgn_param->cgn_param_version,
7121 				p_cgn_param->cgn_param_mode,
7122 				p_cgn_param->cgn_param_level0,
7123 				p_cgn_param->cgn_param_level1,
7124 				p_cgn_param->cgn_param_level2,
7125 				p_cgn_param->byte13,
7126 				p_cgn_param->byte14,
7127 				p_cgn_param->byte15,
7128 				p_cgn_param->byte11,
7129 				p_cgn_param->byte12,
7130 				phba->cmf_active_mode);
7131 
7132 		oldmode = phba->cmf_active_mode;
7133 
7134 		/* Any parameters out of range are corrected to defaults
7135 		 * by this routine.  No need to fail.
7136 		 */
7137 		lpfc_cgn_params_val(phba, p_cgn_param);
7138 
7139 		/* Parameters are verified, move them into driver storage */
7140 		spin_lock_irq(&phba->hbalock);
7141 		memcpy(&phba->cgn_p, p_cgn_param,
7142 		       sizeof(struct lpfc_cgn_param));
7143 
7144 		/* Update parameters in congestion info buffer now */
7145 		if (phba->cgn_i) {
7146 			cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
7147 			cp->cgn_info_mode = phba->cgn_p.cgn_param_mode;
7148 			cp->cgn_info_level0 = phba->cgn_p.cgn_param_level0;
7149 			cp->cgn_info_level1 = phba->cgn_p.cgn_param_level1;
7150 			cp->cgn_info_level2 = phba->cgn_p.cgn_param_level2;
7151 			crc = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ,
7152 						  LPFC_CGN_CRC32_SEED);
7153 			cp->cgn_info_crc = cpu_to_le32(crc);
7154 		}
7155 		spin_unlock_irq(&phba->hbalock);
7156 
7157 		phba->cmf_active_mode = phba->cgn_p.cgn_param_mode;
7158 
7159 		switch (oldmode) {
7160 		case LPFC_CFG_OFF:
7161 			if (phba->cgn_p.cgn_param_mode != LPFC_CFG_OFF) {
7162 				/* Turning CMF on */
7163 				lpfc_cmf_start(phba);
7164 
7165 				if (phba->link_state >= LPFC_LINK_UP) {
7166 					phba->cgn_reg_fpin =
7167 						phba->cgn_init_reg_fpin;
7168 					phba->cgn_reg_signal =
7169 						phba->cgn_init_reg_signal;
7170 					lpfc_issue_els_edc(phba->pport, 0);
7171 				}
7172 			}
7173 			break;
7174 		case LPFC_CFG_MANAGED:
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_MONITOR:
7183 				lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
7184 						"4661 Switch from MANAGED to "
7185 						"`MONITOR mode\n");
7186 				phba->cmf_max_bytes_per_interval =
7187 					phba->cmf_link_byte_count;
7188 
7189 				/* Resume blocked IO - unblock on workqueue */
7190 				queue_work(phba->wq,
7191 					   &phba->unblock_request_work);
7192 				break;
7193 			}
7194 			break;
7195 		case LPFC_CFG_MONITOR:
7196 			switch (phba->cgn_p.cgn_param_mode) {
7197 			case LPFC_CFG_OFF:
7198 				/* Turning CMF off */
7199 				lpfc_cmf_stop(phba);
7200 				if (phba->link_state >= LPFC_LINK_UP)
7201 					lpfc_issue_els_edc(phba->pport, 0);
7202 				break;
7203 			case LPFC_CFG_MANAGED:
7204 				lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
7205 						"4662 Switch from MONITOR to "
7206 						"MANAGED mode\n");
7207 				lpfc_cmf_signal_init(phba);
7208 				break;
7209 			}
7210 			break;
7211 		}
7212 	} else {
7213 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7214 				"4669 FW cgn parm buf wrong magic 0x%x "
7215 				"version %d\n", p_cgn_param->cgn_param_magic,
7216 				p_cgn_param->cgn_param_version);
7217 	}
7218 }
7219 
7220 /**
7221  * lpfc_sli4_cgn_params_read - Read and Validate FW congestion parameters.
7222  * @phba: pointer to lpfc hba data structure.
7223  *
7224  * This routine issues a read_object mailbox command to
7225  * get the congestion management parameters from the FW
7226  * parses it and updates the driver maintained values.
7227  *
7228  * Returns
7229  *  0     if the object was empty
7230  *  -Eval if an error was encountered
7231  *  Count if bytes were read from object
7232  **/
7233 int
7234 lpfc_sli4_cgn_params_read(struct lpfc_hba *phba)
7235 {
7236 	int ret = 0;
7237 	struct lpfc_cgn_param *p_cgn_param = NULL;
7238 	u32 *pdata = NULL;
7239 	u32 len = 0;
7240 
7241 	/* Find out if the FW has a new set of congestion parameters. */
7242 	len = sizeof(struct lpfc_cgn_param);
7243 	pdata = kzalloc(len, GFP_KERNEL);
7244 	ret = lpfc_read_object(phba, (char *)LPFC_PORT_CFG_NAME,
7245 			       pdata, len);
7246 
7247 	/* 0 means no data.  A negative means error.  A positive means
7248 	 * bytes were copied.
7249 	 */
7250 	if (!ret) {
7251 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7252 				"4670 CGN RD OBJ returns no data\n");
7253 		goto rd_obj_err;
7254 	} else if (ret < 0) {
7255 		/* Some error.  Just exit and return it to the caller.*/
7256 		goto rd_obj_err;
7257 	}
7258 
7259 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT | LOG_INIT,
7260 			"6234 READ CGN PARAMS Successful %d\n", len);
7261 
7262 	/* Parse data pointer over len and update the phba congestion
7263 	 * parameters with values passed back.  The receive rate values
7264 	 * may have been altered in FW, but take no action here.
7265 	 */
7266 	p_cgn_param = (struct lpfc_cgn_param *)pdata;
7267 	lpfc_cgn_params_parse(phba, p_cgn_param, len);
7268 
7269  rd_obj_err:
7270 	kfree(pdata);
7271 	return ret;
7272 }
7273 
7274 /**
7275  * lpfc_sli4_cgn_parm_chg_evt - Process a FW congestion param change event
7276  * @phba: pointer to lpfc hba data structure.
7277  *
7278  * The FW generated Async ACQE SLI event calls this routine when
7279  * the event type is an SLI Internal Port Event and the Event Code
7280  * indicates a change to the FW maintained congestion parameters.
7281  *
7282  * This routine executes a Read_Object mailbox call to obtain the
7283  * current congestion parameters maintained in FW and corrects
7284  * the driver's active congestion parameters.
7285  *
7286  * The acqe event is not passed because there is no further data
7287  * required.
7288  *
7289  * Returns nonzero error if event processing encountered an error.
7290  * Zero otherwise for success.
7291  **/
7292 static int
7293 lpfc_sli4_cgn_parm_chg_evt(struct lpfc_hba *phba)
7294 {
7295 	int ret = 0;
7296 
7297 	if (!phba->sli4_hba.pc_sli4_params.cmf) {
7298 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7299 				"4664 Cgn Evt when E2E off. Drop event\n");
7300 		return -EACCES;
7301 	}
7302 
7303 	/* If the event is claiming an empty object, it's ok.  A write
7304 	 * could have cleared it.  Only error is a negative return
7305 	 * status.
7306 	 */
7307 	ret = lpfc_sli4_cgn_params_read(phba);
7308 	if (ret < 0) {
7309 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7310 				"4667 Error reading Cgn Params (%d)\n",
7311 				ret);
7312 	} else if (!ret) {
7313 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7314 				"4673 CGN Event empty object.\n");
7315 	}
7316 	return ret;
7317 }
7318 
7319 /**
7320  * lpfc_sli4_async_event_proc - Process all the pending asynchronous event
7321  * @phba: pointer to lpfc hba data structure.
7322  *
7323  * This routine is invoked by the worker thread to process all the pending
7324  * SLI4 asynchronous events.
7325  **/
7326 void lpfc_sli4_async_event_proc(struct lpfc_hba *phba)
7327 {
7328 	struct lpfc_cq_event *cq_event;
7329 	unsigned long iflags;
7330 
7331 	/* First, declare the async event has been handled */
7332 	spin_lock_irqsave(&phba->hbalock, iflags);
7333 	phba->hba_flag &= ~ASYNC_EVENT;
7334 	spin_unlock_irqrestore(&phba->hbalock, iflags);
7335 
7336 	/* Now, handle all the async events */
7337 	spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
7338 	while (!list_empty(&phba->sli4_hba.sp_asynce_work_queue)) {
7339 		list_remove_head(&phba->sli4_hba.sp_asynce_work_queue,
7340 				 cq_event, struct lpfc_cq_event, list);
7341 		spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock,
7342 				       iflags);
7343 
7344 		/* Process the asynchronous event */
7345 		switch (bf_get(lpfc_trailer_code, &cq_event->cqe.mcqe_cmpl)) {
7346 		case LPFC_TRAILER_CODE_LINK:
7347 			lpfc_sli4_async_link_evt(phba,
7348 						 &cq_event->cqe.acqe_link);
7349 			break;
7350 		case LPFC_TRAILER_CODE_FCOE:
7351 			lpfc_sli4_async_fip_evt(phba, &cq_event->cqe.acqe_fip);
7352 			break;
7353 		case LPFC_TRAILER_CODE_DCBX:
7354 			lpfc_sli4_async_dcbx_evt(phba,
7355 						 &cq_event->cqe.acqe_dcbx);
7356 			break;
7357 		case LPFC_TRAILER_CODE_GRP5:
7358 			lpfc_sli4_async_grp5_evt(phba,
7359 						 &cq_event->cqe.acqe_grp5);
7360 			break;
7361 		case LPFC_TRAILER_CODE_FC:
7362 			lpfc_sli4_async_fc_evt(phba, &cq_event->cqe.acqe_fc);
7363 			break;
7364 		case LPFC_TRAILER_CODE_SLI:
7365 			lpfc_sli4_async_sli_evt(phba, &cq_event->cqe.acqe_sli);
7366 			break;
7367 		case LPFC_TRAILER_CODE_CMSTAT:
7368 			lpfc_sli4_async_cmstat_evt(phba);
7369 			break;
7370 		default:
7371 			lpfc_printf_log(phba, KERN_ERR,
7372 					LOG_TRACE_EVENT,
7373 					"1804 Invalid asynchronous event code: "
7374 					"x%x\n", bf_get(lpfc_trailer_code,
7375 					&cq_event->cqe.mcqe_cmpl));
7376 			break;
7377 		}
7378 
7379 		/* Free the completion event processed to the free pool */
7380 		lpfc_sli4_cq_event_release(phba, cq_event);
7381 		spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
7382 	}
7383 	spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock, iflags);
7384 }
7385 
7386 /**
7387  * lpfc_sli4_fcf_redisc_event_proc - Process fcf table rediscovery event
7388  * @phba: pointer to lpfc hba data structure.
7389  *
7390  * This routine is invoked by the worker thread to process FCF table
7391  * rediscovery pending completion event.
7392  **/
7393 void lpfc_sli4_fcf_redisc_event_proc(struct lpfc_hba *phba)
7394 {
7395 	int rc;
7396 
7397 	spin_lock_irq(&phba->hbalock);
7398 	/* Clear FCF rediscovery timeout event */
7399 	phba->fcf.fcf_flag &= ~FCF_REDISC_EVT;
7400 	/* Clear driver fast failover FCF record flag */
7401 	phba->fcf.failover_rec.flag = 0;
7402 	/* Set state for FCF fast failover */
7403 	phba->fcf.fcf_flag |= FCF_REDISC_FOV;
7404 	spin_unlock_irq(&phba->hbalock);
7405 
7406 	/* Scan FCF table from the first entry to re-discover SAN */
7407 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
7408 			"2777 Start post-quiescent FCF table scan\n");
7409 	rc = lpfc_sli4_fcf_scan_read_fcf_rec(phba, LPFC_FCOE_FCF_GET_FIRST);
7410 	if (rc)
7411 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7412 				"2747 Issue FCF scan read FCF mailbox "
7413 				"command failed 0x%x\n", rc);
7414 }
7415 
7416 /**
7417  * lpfc_api_table_setup - Set up per hba pci-device group func api jump table
7418  * @phba: pointer to lpfc hba data structure.
7419  * @dev_grp: The HBA PCI-Device group number.
7420  *
7421  * This routine is invoked to set up the per HBA PCI-Device group function
7422  * API jump table entries.
7423  *
7424  * Return: 0 if success, otherwise -ENODEV
7425  **/
7426 int
7427 lpfc_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
7428 {
7429 	int rc;
7430 
7431 	/* Set up lpfc PCI-device group */
7432 	phba->pci_dev_grp = dev_grp;
7433 
7434 	/* The LPFC_PCI_DEV_OC uses SLI4 */
7435 	if (dev_grp == LPFC_PCI_DEV_OC)
7436 		phba->sli_rev = LPFC_SLI_REV4;
7437 
7438 	/* Set up device INIT API function jump table */
7439 	rc = lpfc_init_api_table_setup(phba, dev_grp);
7440 	if (rc)
7441 		return -ENODEV;
7442 	/* Set up SCSI API function jump table */
7443 	rc = lpfc_scsi_api_table_setup(phba, dev_grp);
7444 	if (rc)
7445 		return -ENODEV;
7446 	/* Set up SLI API function jump table */
7447 	rc = lpfc_sli_api_table_setup(phba, dev_grp);
7448 	if (rc)
7449 		return -ENODEV;
7450 	/* Set up MBOX API function jump table */
7451 	rc = lpfc_mbox_api_table_setup(phba, dev_grp);
7452 	if (rc)
7453 		return -ENODEV;
7454 
7455 	return 0;
7456 }
7457 
7458 /**
7459  * lpfc_log_intr_mode - Log the active interrupt mode
7460  * @phba: pointer to lpfc hba data structure.
7461  * @intr_mode: active interrupt mode adopted.
7462  *
7463  * This routine it invoked to log the currently used active interrupt mode
7464  * to the device.
7465  **/
7466 static void lpfc_log_intr_mode(struct lpfc_hba *phba, uint32_t intr_mode)
7467 {
7468 	switch (intr_mode) {
7469 	case 0:
7470 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7471 				"0470 Enable INTx interrupt mode.\n");
7472 		break;
7473 	case 1:
7474 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7475 				"0481 Enabled MSI interrupt mode.\n");
7476 		break;
7477 	case 2:
7478 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7479 				"0480 Enabled MSI-X interrupt mode.\n");
7480 		break;
7481 	default:
7482 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7483 				"0482 Illegal interrupt mode.\n");
7484 		break;
7485 	}
7486 	return;
7487 }
7488 
7489 /**
7490  * lpfc_enable_pci_dev - Enable a generic PCI device.
7491  * @phba: pointer to lpfc hba data structure.
7492  *
7493  * This routine is invoked to enable the PCI device that is common to all
7494  * PCI devices.
7495  *
7496  * Return codes
7497  * 	0 - successful
7498  * 	other values - error
7499  **/
7500 static int
7501 lpfc_enable_pci_dev(struct lpfc_hba *phba)
7502 {
7503 	struct pci_dev *pdev;
7504 
7505 	/* Obtain PCI device reference */
7506 	if (!phba->pcidev)
7507 		goto out_error;
7508 	else
7509 		pdev = phba->pcidev;
7510 	/* Enable PCI device */
7511 	if (pci_enable_device_mem(pdev))
7512 		goto out_error;
7513 	/* Request PCI resource for the device */
7514 	if (pci_request_mem_regions(pdev, LPFC_DRIVER_NAME))
7515 		goto out_disable_device;
7516 	/* Set up device as PCI master and save state for EEH */
7517 	pci_set_master(pdev);
7518 	pci_try_set_mwi(pdev);
7519 	pci_save_state(pdev);
7520 
7521 	/* PCIe EEH recovery on powerpc platforms needs fundamental reset */
7522 	if (pci_is_pcie(pdev))
7523 		pdev->needs_freset = 1;
7524 
7525 	return 0;
7526 
7527 out_disable_device:
7528 	pci_disable_device(pdev);
7529 out_error:
7530 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7531 			"1401 Failed to enable pci device\n");
7532 	return -ENODEV;
7533 }
7534 
7535 /**
7536  * lpfc_disable_pci_dev - Disable a generic PCI device.
7537  * @phba: pointer to lpfc hba data structure.
7538  *
7539  * This routine is invoked to disable the PCI device that is common to all
7540  * PCI devices.
7541  **/
7542 static void
7543 lpfc_disable_pci_dev(struct lpfc_hba *phba)
7544 {
7545 	struct pci_dev *pdev;
7546 
7547 	/* Obtain PCI device reference */
7548 	if (!phba->pcidev)
7549 		return;
7550 	else
7551 		pdev = phba->pcidev;
7552 	/* Release PCI resource and disable PCI device */
7553 	pci_release_mem_regions(pdev);
7554 	pci_disable_device(pdev);
7555 
7556 	return;
7557 }
7558 
7559 /**
7560  * lpfc_reset_hba - Reset a hba
7561  * @phba: pointer to lpfc hba data structure.
7562  *
7563  * This routine is invoked to reset a hba device. It brings the HBA
7564  * offline, performs a board restart, and then brings the board back
7565  * online. The lpfc_offline calls lpfc_sli_hba_down which will clean up
7566  * on outstanding mailbox commands.
7567  **/
7568 void
7569 lpfc_reset_hba(struct lpfc_hba *phba)
7570 {
7571 	/* If resets are disabled then set error state and return. */
7572 	if (!phba->cfg_enable_hba_reset) {
7573 		phba->link_state = LPFC_HBA_ERROR;
7574 		return;
7575 	}
7576 
7577 	/* If not LPFC_SLI_ACTIVE, force all IO to be flushed */
7578 	if (phba->sli.sli_flag & LPFC_SLI_ACTIVE) {
7579 		lpfc_offline_prep(phba, LPFC_MBX_WAIT);
7580 	} else {
7581 		lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
7582 		lpfc_sli_flush_io_rings(phba);
7583 	}
7584 	lpfc_offline(phba);
7585 	lpfc_sli_brdrestart(phba);
7586 	lpfc_online(phba);
7587 	lpfc_unblock_mgmt_io(phba);
7588 }
7589 
7590 /**
7591  * lpfc_sli_sriov_nr_virtfn_get - Get the number of sr-iov virtual functions
7592  * @phba: pointer to lpfc hba data structure.
7593  *
7594  * This function enables the PCI SR-IOV virtual functions to a physical
7595  * function. It invokes the PCI SR-IOV api with the @nr_vfn provided to
7596  * enable the number of virtual functions to the physical function. As
7597  * not all devices support SR-IOV, the return code from the pci_enable_sriov()
7598  * API call does not considered as an error condition for most of the device.
7599  **/
7600 uint16_t
7601 lpfc_sli_sriov_nr_virtfn_get(struct lpfc_hba *phba)
7602 {
7603 	struct pci_dev *pdev = phba->pcidev;
7604 	uint16_t nr_virtfn;
7605 	int pos;
7606 
7607 	pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_SRIOV);
7608 	if (pos == 0)
7609 		return 0;
7610 
7611 	pci_read_config_word(pdev, pos + PCI_SRIOV_TOTAL_VF, &nr_virtfn);
7612 	return nr_virtfn;
7613 }
7614 
7615 /**
7616  * lpfc_sli_probe_sriov_nr_virtfn - Enable a number of sr-iov virtual functions
7617  * @phba: pointer to lpfc hba data structure.
7618  * @nr_vfn: number of virtual functions to be enabled.
7619  *
7620  * This function enables the PCI SR-IOV virtual functions to a physical
7621  * function. It invokes the PCI SR-IOV api with the @nr_vfn provided to
7622  * enable the number of virtual functions to the physical function. As
7623  * not all devices support SR-IOV, the return code from the pci_enable_sriov()
7624  * API call does not considered as an error condition for most of the device.
7625  **/
7626 int
7627 lpfc_sli_probe_sriov_nr_virtfn(struct lpfc_hba *phba, int nr_vfn)
7628 {
7629 	struct pci_dev *pdev = phba->pcidev;
7630 	uint16_t max_nr_vfn;
7631 	int rc;
7632 
7633 	max_nr_vfn = lpfc_sli_sriov_nr_virtfn_get(phba);
7634 	if (nr_vfn > max_nr_vfn) {
7635 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7636 				"3057 Requested vfs (%d) greater than "
7637 				"supported vfs (%d)", nr_vfn, max_nr_vfn);
7638 		return -EINVAL;
7639 	}
7640 
7641 	rc = pci_enable_sriov(pdev, nr_vfn);
7642 	if (rc) {
7643 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7644 				"2806 Failed to enable sriov on this device "
7645 				"with vfn number nr_vf:%d, rc:%d\n",
7646 				nr_vfn, rc);
7647 	} else
7648 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7649 				"2807 Successful enable sriov on this device "
7650 				"with vfn number nr_vf:%d\n", nr_vfn);
7651 	return rc;
7652 }
7653 
7654 static void
7655 lpfc_unblock_requests_work(struct work_struct *work)
7656 {
7657 	struct lpfc_hba *phba = container_of(work, struct lpfc_hba,
7658 					     unblock_request_work);
7659 
7660 	lpfc_unblock_requests(phba);
7661 }
7662 
7663 /**
7664  * lpfc_setup_driver_resource_phase1 - Phase1 etup driver internal resources.
7665  * @phba: pointer to lpfc hba data structure.
7666  *
7667  * This routine is invoked to set up the driver internal resources before the
7668  * device specific resource setup to support the HBA device it attached to.
7669  *
7670  * Return codes
7671  *	0 - successful
7672  *	other values - error
7673  **/
7674 static int
7675 lpfc_setup_driver_resource_phase1(struct lpfc_hba *phba)
7676 {
7677 	struct lpfc_sli *psli = &phba->sli;
7678 
7679 	/*
7680 	 * Driver resources common to all SLI revisions
7681 	 */
7682 	atomic_set(&phba->fast_event_count, 0);
7683 	atomic_set(&phba->dbg_log_idx, 0);
7684 	atomic_set(&phba->dbg_log_cnt, 0);
7685 	atomic_set(&phba->dbg_log_dmping, 0);
7686 	spin_lock_init(&phba->hbalock);
7687 
7688 	/* Initialize port_list spinlock */
7689 	spin_lock_init(&phba->port_list_lock);
7690 	INIT_LIST_HEAD(&phba->port_list);
7691 
7692 	INIT_LIST_HEAD(&phba->work_list);
7693 
7694 	/* Initialize the wait queue head for the kernel thread */
7695 	init_waitqueue_head(&phba->work_waitq);
7696 
7697 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7698 			"1403 Protocols supported %s %s %s\n",
7699 			((phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP) ?
7700 				"SCSI" : " "),
7701 			((phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) ?
7702 				"NVME" : " "),
7703 			(phba->nvmet_support ? "NVMET" : " "));
7704 
7705 	/* Initialize the IO buffer list used by driver for SLI3 SCSI */
7706 	spin_lock_init(&phba->scsi_buf_list_get_lock);
7707 	INIT_LIST_HEAD(&phba->lpfc_scsi_buf_list_get);
7708 	spin_lock_init(&phba->scsi_buf_list_put_lock);
7709 	INIT_LIST_HEAD(&phba->lpfc_scsi_buf_list_put);
7710 
7711 	/* Initialize the fabric iocb list */
7712 	INIT_LIST_HEAD(&phba->fabric_iocb_list);
7713 
7714 	/* Initialize list to save ELS buffers */
7715 	INIT_LIST_HEAD(&phba->elsbuf);
7716 
7717 	/* Initialize FCF connection rec list */
7718 	INIT_LIST_HEAD(&phba->fcf_conn_rec_list);
7719 
7720 	/* Initialize OAS configuration list */
7721 	spin_lock_init(&phba->devicelock);
7722 	INIT_LIST_HEAD(&phba->luns);
7723 
7724 	/* MBOX heartbeat timer */
7725 	timer_setup(&psli->mbox_tmo, lpfc_mbox_timeout, 0);
7726 	/* Fabric block timer */
7727 	timer_setup(&phba->fabric_block_timer, lpfc_fabric_block_timeout, 0);
7728 	/* EA polling mode timer */
7729 	timer_setup(&phba->eratt_poll, lpfc_poll_eratt, 0);
7730 	/* Heartbeat timer */
7731 	timer_setup(&phba->hb_tmofunc, lpfc_hb_timeout, 0);
7732 
7733 	INIT_DELAYED_WORK(&phba->eq_delay_work, lpfc_hb_eq_delay_work);
7734 
7735 	INIT_DELAYED_WORK(&phba->idle_stat_delay_work,
7736 			  lpfc_idle_stat_delay_work);
7737 	INIT_WORK(&phba->unblock_request_work, lpfc_unblock_requests_work);
7738 	return 0;
7739 }
7740 
7741 /**
7742  * lpfc_sli_driver_resource_setup - Setup driver internal resources for SLI3 dev
7743  * @phba: pointer to lpfc hba data structure.
7744  *
7745  * This routine is invoked to set up the driver internal resources specific to
7746  * support the SLI-3 HBA device it attached to.
7747  *
7748  * Return codes
7749  * 0 - successful
7750  * other values - error
7751  **/
7752 static int
7753 lpfc_sli_driver_resource_setup(struct lpfc_hba *phba)
7754 {
7755 	int rc, entry_sz;
7756 
7757 	/*
7758 	 * Initialize timers used by driver
7759 	 */
7760 
7761 	/* FCP polling mode timer */
7762 	timer_setup(&phba->fcp_poll_timer, lpfc_poll_timeout, 0);
7763 
7764 	/* Host attention work mask setup */
7765 	phba->work_ha_mask = (HA_ERATT | HA_MBATT | HA_LATT);
7766 	phba->work_ha_mask |= (HA_RXMASK << (LPFC_ELS_RING * 4));
7767 
7768 	/* Get all the module params for configuring this host */
7769 	lpfc_get_cfgparam(phba);
7770 	/* Set up phase-1 common device driver resources */
7771 
7772 	rc = lpfc_setup_driver_resource_phase1(phba);
7773 	if (rc)
7774 		return -ENODEV;
7775 
7776 	if (!phba->sli.sli3_ring)
7777 		phba->sli.sli3_ring = kcalloc(LPFC_SLI3_MAX_RING,
7778 					      sizeof(struct lpfc_sli_ring),
7779 					      GFP_KERNEL);
7780 	if (!phba->sli.sli3_ring)
7781 		return -ENOMEM;
7782 
7783 	/*
7784 	 * Since lpfc_sg_seg_cnt is module parameter, the sg_dma_buf_size
7785 	 * used to create the sg_dma_buf_pool must be dynamically calculated.
7786 	 */
7787 
7788 	if (phba->sli_rev == LPFC_SLI_REV4)
7789 		entry_sz = sizeof(struct sli4_sge);
7790 	else
7791 		entry_sz = sizeof(struct ulp_bde64);
7792 
7793 	/* There are going to be 2 reserved BDEs: 1 FCP cmnd + 1 FCP rsp */
7794 	if (phba->cfg_enable_bg) {
7795 		/*
7796 		 * The scsi_buf for a T10-DIF I/O will hold the FCP cmnd,
7797 		 * the FCP rsp, and a BDE for each. Sice we have no control
7798 		 * over how many protection data segments the SCSI Layer
7799 		 * will hand us (ie: there could be one for every block
7800 		 * in the IO), we just allocate enough BDEs to accomidate
7801 		 * our max amount and we need to limit lpfc_sg_seg_cnt to
7802 		 * minimize the risk of running out.
7803 		 */
7804 		phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd) +
7805 			sizeof(struct fcp_rsp) +
7806 			(LPFC_MAX_SG_SEG_CNT * entry_sz);
7807 
7808 		if (phba->cfg_sg_seg_cnt > LPFC_MAX_SG_SEG_CNT_DIF)
7809 			phba->cfg_sg_seg_cnt = LPFC_MAX_SG_SEG_CNT_DIF;
7810 
7811 		/* Total BDEs in BPL for scsi_sg_list and scsi_sg_prot_list */
7812 		phba->cfg_total_seg_cnt = LPFC_MAX_SG_SEG_CNT;
7813 	} else {
7814 		/*
7815 		 * The scsi_buf for a regular I/O will hold the FCP cmnd,
7816 		 * the FCP rsp, a BDE for each, and a BDE for up to
7817 		 * cfg_sg_seg_cnt data segments.
7818 		 */
7819 		phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd) +
7820 			sizeof(struct fcp_rsp) +
7821 			((phba->cfg_sg_seg_cnt + 2) * entry_sz);
7822 
7823 		/* Total BDEs in BPL for scsi_sg_list */
7824 		phba->cfg_total_seg_cnt = phba->cfg_sg_seg_cnt + 2;
7825 	}
7826 
7827 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP,
7828 			"9088 INIT sg_tablesize:%d dmabuf_size:%d total_bde:%d\n",
7829 			phba->cfg_sg_seg_cnt, phba->cfg_sg_dma_buf_size,
7830 			phba->cfg_total_seg_cnt);
7831 
7832 	phba->max_vpi = LPFC_MAX_VPI;
7833 	/* This will be set to correct value after config_port mbox */
7834 	phba->max_vports = 0;
7835 
7836 	/*
7837 	 * Initialize the SLI Layer to run with lpfc HBAs.
7838 	 */
7839 	lpfc_sli_setup(phba);
7840 	lpfc_sli_queue_init(phba);
7841 
7842 	/* Allocate device driver memory */
7843 	if (lpfc_mem_alloc(phba, BPL_ALIGN_SZ))
7844 		return -ENOMEM;
7845 
7846 	phba->lpfc_sg_dma_buf_pool =
7847 		dma_pool_create("lpfc_sg_dma_buf_pool",
7848 				&phba->pcidev->dev, phba->cfg_sg_dma_buf_size,
7849 				BPL_ALIGN_SZ, 0);
7850 
7851 	if (!phba->lpfc_sg_dma_buf_pool)
7852 		goto fail_free_mem;
7853 
7854 	phba->lpfc_cmd_rsp_buf_pool =
7855 			dma_pool_create("lpfc_cmd_rsp_buf_pool",
7856 					&phba->pcidev->dev,
7857 					sizeof(struct fcp_cmnd) +
7858 					sizeof(struct fcp_rsp),
7859 					BPL_ALIGN_SZ, 0);
7860 
7861 	if (!phba->lpfc_cmd_rsp_buf_pool)
7862 		goto fail_free_dma_buf_pool;
7863 
7864 	/*
7865 	 * Enable sr-iov virtual functions if supported and configured
7866 	 * through the module parameter.
7867 	 */
7868 	if (phba->cfg_sriov_nr_virtfn > 0) {
7869 		rc = lpfc_sli_probe_sriov_nr_virtfn(phba,
7870 						 phba->cfg_sriov_nr_virtfn);
7871 		if (rc) {
7872 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7873 					"2808 Requested number of SR-IOV "
7874 					"virtual functions (%d) is not "
7875 					"supported\n",
7876 					phba->cfg_sriov_nr_virtfn);
7877 			phba->cfg_sriov_nr_virtfn = 0;
7878 		}
7879 	}
7880 
7881 	return 0;
7882 
7883 fail_free_dma_buf_pool:
7884 	dma_pool_destroy(phba->lpfc_sg_dma_buf_pool);
7885 	phba->lpfc_sg_dma_buf_pool = NULL;
7886 fail_free_mem:
7887 	lpfc_mem_free(phba);
7888 	return -ENOMEM;
7889 }
7890 
7891 /**
7892  * lpfc_sli_driver_resource_unset - Unset drvr internal resources for SLI3 dev
7893  * @phba: pointer to lpfc hba data structure.
7894  *
7895  * This routine is invoked to unset the driver internal resources set up
7896  * specific for supporting the SLI-3 HBA device it attached to.
7897  **/
7898 static void
7899 lpfc_sli_driver_resource_unset(struct lpfc_hba *phba)
7900 {
7901 	/* Free device driver memory allocated */
7902 	lpfc_mem_free_all(phba);
7903 
7904 	return;
7905 }
7906 
7907 /**
7908  * lpfc_sli4_driver_resource_setup - Setup drvr internal resources for SLI4 dev
7909  * @phba: pointer to lpfc hba data structure.
7910  *
7911  * This routine is invoked to set up the driver internal resources specific to
7912  * support the SLI-4 HBA device it attached to.
7913  *
7914  * Return codes
7915  * 	0 - successful
7916  * 	other values - error
7917  **/
7918 static int
7919 lpfc_sli4_driver_resource_setup(struct lpfc_hba *phba)
7920 {
7921 	LPFC_MBOXQ_t *mboxq;
7922 	MAILBOX_t *mb;
7923 	int rc, i, max_buf_size;
7924 	int longs;
7925 	int extra;
7926 	uint64_t wwn;
7927 	u32 if_type;
7928 	u32 if_fam;
7929 
7930 	phba->sli4_hba.num_present_cpu = lpfc_present_cpu;
7931 	phba->sli4_hba.num_possible_cpu = cpumask_last(cpu_possible_mask) + 1;
7932 	phba->sli4_hba.curr_disp_cpu = 0;
7933 
7934 	/* Get all the module params for configuring this host */
7935 	lpfc_get_cfgparam(phba);
7936 
7937 	/* Set up phase-1 common device driver resources */
7938 	rc = lpfc_setup_driver_resource_phase1(phba);
7939 	if (rc)
7940 		return -ENODEV;
7941 
7942 	/* Before proceed, wait for POST done and device ready */
7943 	rc = lpfc_sli4_post_status_check(phba);
7944 	if (rc)
7945 		return -ENODEV;
7946 
7947 	/* Allocate all driver workqueues here */
7948 
7949 	/* The lpfc_wq workqueue for deferred irq use */
7950 	phba->wq = alloc_workqueue("lpfc_wq", WQ_MEM_RECLAIM, 0);
7951 
7952 	/*
7953 	 * Initialize timers used by driver
7954 	 */
7955 
7956 	timer_setup(&phba->rrq_tmr, lpfc_rrq_timeout, 0);
7957 
7958 	/* FCF rediscover timer */
7959 	timer_setup(&phba->fcf.redisc_wait, lpfc_sli4_fcf_redisc_wait_tmo, 0);
7960 
7961 	/* CMF congestion timer */
7962 	hrtimer_init(&phba->cmf_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
7963 	phba->cmf_timer.function = lpfc_cmf_timer;
7964 
7965 	/*
7966 	 * Control structure for handling external multi-buffer mailbox
7967 	 * command pass-through.
7968 	 */
7969 	memset((uint8_t *)&phba->mbox_ext_buf_ctx, 0,
7970 		sizeof(struct lpfc_mbox_ext_buf_ctx));
7971 	INIT_LIST_HEAD(&phba->mbox_ext_buf_ctx.ext_dmabuf_list);
7972 
7973 	phba->max_vpi = LPFC_MAX_VPI;
7974 
7975 	/* This will be set to correct value after the read_config mbox */
7976 	phba->max_vports = 0;
7977 
7978 	/* Program the default value of vlan_id and fc_map */
7979 	phba->valid_vlan = 0;
7980 	phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
7981 	phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
7982 	phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
7983 
7984 	/*
7985 	 * For SLI4, instead of using ring 0 (LPFC_FCP_RING) for FCP commands
7986 	 * we will associate a new ring, for each EQ/CQ/WQ tuple.
7987 	 * The WQ create will allocate the ring.
7988 	 */
7989 
7990 	/* Initialize buffer queue management fields */
7991 	INIT_LIST_HEAD(&phba->hbqs[LPFC_ELS_HBQ].hbq_buffer_list);
7992 	phba->hbqs[LPFC_ELS_HBQ].hbq_alloc_buffer = lpfc_sli4_rb_alloc;
7993 	phba->hbqs[LPFC_ELS_HBQ].hbq_free_buffer = lpfc_sli4_rb_free;
7994 
7995 	/* for VMID idle timeout if VMID is enabled */
7996 	if (lpfc_is_vmid_enabled(phba))
7997 		timer_setup(&phba->inactive_vmid_poll, lpfc_vmid_poll, 0);
7998 
7999 	/*
8000 	 * Initialize the SLI Layer to run with lpfc SLI4 HBAs.
8001 	 */
8002 	/* Initialize the Abort buffer list used by driver */
8003 	spin_lock_init(&phba->sli4_hba.abts_io_buf_list_lock);
8004 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_io_buf_list);
8005 
8006 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
8007 		/* Initialize the Abort nvme buffer list used by driver */
8008 		spin_lock_init(&phba->sli4_hba.abts_nvmet_buf_list_lock);
8009 		INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
8010 		INIT_LIST_HEAD(&phba->sli4_hba.lpfc_nvmet_io_wait_list);
8011 		spin_lock_init(&phba->sli4_hba.t_active_list_lock);
8012 		INIT_LIST_HEAD(&phba->sli4_hba.t_active_ctx_list);
8013 	}
8014 
8015 	/* This abort list used by worker thread */
8016 	spin_lock_init(&phba->sli4_hba.sgl_list_lock);
8017 	spin_lock_init(&phba->sli4_hba.nvmet_io_wait_lock);
8018 	spin_lock_init(&phba->sli4_hba.asynce_list_lock);
8019 	spin_lock_init(&phba->sli4_hba.els_xri_abrt_list_lock);
8020 
8021 	/*
8022 	 * Initialize driver internal slow-path work queues
8023 	 */
8024 
8025 	/* Driver internel slow-path CQ Event pool */
8026 	INIT_LIST_HEAD(&phba->sli4_hba.sp_cqe_event_pool);
8027 	/* Response IOCB work queue list */
8028 	INIT_LIST_HEAD(&phba->sli4_hba.sp_queue_event);
8029 	/* Asynchronous event CQ Event work queue list */
8030 	INIT_LIST_HEAD(&phba->sli4_hba.sp_asynce_work_queue);
8031 	/* Slow-path XRI aborted CQ Event work queue list */
8032 	INIT_LIST_HEAD(&phba->sli4_hba.sp_els_xri_aborted_work_queue);
8033 	/* Receive queue CQ Event work queue list */
8034 	INIT_LIST_HEAD(&phba->sli4_hba.sp_unsol_work_queue);
8035 
8036 	/* Initialize extent block lists. */
8037 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_rpi_blk_list);
8038 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_xri_blk_list);
8039 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_vfi_blk_list);
8040 	INIT_LIST_HEAD(&phba->lpfc_vpi_blk_list);
8041 
8042 	/* Initialize mboxq lists. If the early init routines fail
8043 	 * these lists need to be correctly initialized.
8044 	 */
8045 	INIT_LIST_HEAD(&phba->sli.mboxq);
8046 	INIT_LIST_HEAD(&phba->sli.mboxq_cmpl);
8047 
8048 	/* initialize optic_state to 0xFF */
8049 	phba->sli4_hba.lnk_info.optic_state = 0xff;
8050 
8051 	/* Allocate device driver memory */
8052 	rc = lpfc_mem_alloc(phba, SGL_ALIGN_SZ);
8053 	if (rc)
8054 		return -ENOMEM;
8055 
8056 	/* IF Type 2 ports get initialized now. */
8057 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) >=
8058 	    LPFC_SLI_INTF_IF_TYPE_2) {
8059 		rc = lpfc_pci_function_reset(phba);
8060 		if (unlikely(rc)) {
8061 			rc = -ENODEV;
8062 			goto out_free_mem;
8063 		}
8064 		phba->temp_sensor_support = 1;
8065 	}
8066 
8067 	/* Create the bootstrap mailbox command */
8068 	rc = lpfc_create_bootstrap_mbox(phba);
8069 	if (unlikely(rc))
8070 		goto out_free_mem;
8071 
8072 	/* Set up the host's endian order with the device. */
8073 	rc = lpfc_setup_endian_order(phba);
8074 	if (unlikely(rc))
8075 		goto out_free_bsmbx;
8076 
8077 	/* Set up the hba's configuration parameters. */
8078 	rc = lpfc_sli4_read_config(phba);
8079 	if (unlikely(rc))
8080 		goto out_free_bsmbx;
8081 
8082 	if (phba->sli4_hba.fawwpn_flag & LPFC_FAWWPN_CONFIG) {
8083 		/* Right now the link is down, if FA-PWWN is configured the
8084 		 * firmware will try FLOGI before the driver gets a link up.
8085 		 * If it fails, the driver should get a MISCONFIGURED async
8086 		 * event which will clear this flag. The only notification
8087 		 * the driver gets is if it fails, if it succeeds there is no
8088 		 * notification given. Assume success.
8089 		 */
8090 		phba->sli4_hba.fawwpn_flag |= LPFC_FAWWPN_FABRIC;
8091 	}
8092 
8093 	rc = lpfc_mem_alloc_active_rrq_pool_s4(phba);
8094 	if (unlikely(rc))
8095 		goto out_free_bsmbx;
8096 
8097 	/* IF Type 0 ports get initialized now. */
8098 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
8099 	    LPFC_SLI_INTF_IF_TYPE_0) {
8100 		rc = lpfc_pci_function_reset(phba);
8101 		if (unlikely(rc))
8102 			goto out_free_bsmbx;
8103 	}
8104 
8105 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
8106 						       GFP_KERNEL);
8107 	if (!mboxq) {
8108 		rc = -ENOMEM;
8109 		goto out_free_bsmbx;
8110 	}
8111 
8112 	/* Check for NVMET being configured */
8113 	phba->nvmet_support = 0;
8114 	if (lpfc_enable_nvmet_cnt) {
8115 
8116 		/* First get WWN of HBA instance */
8117 		lpfc_read_nv(phba, mboxq);
8118 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8119 		if (rc != MBX_SUCCESS) {
8120 			lpfc_printf_log(phba, KERN_ERR,
8121 					LOG_TRACE_EVENT,
8122 					"6016 Mailbox failed , mbxCmd x%x "
8123 					"READ_NV, mbxStatus x%x\n",
8124 					bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8125 					bf_get(lpfc_mqe_status, &mboxq->u.mqe));
8126 			mempool_free(mboxq, phba->mbox_mem_pool);
8127 			rc = -EIO;
8128 			goto out_free_bsmbx;
8129 		}
8130 		mb = &mboxq->u.mb;
8131 		memcpy(&wwn, (char *)mb->un.varRDnvp.nodename,
8132 		       sizeof(uint64_t));
8133 		wwn = cpu_to_be64(wwn);
8134 		phba->sli4_hba.wwnn.u.name = wwn;
8135 		memcpy(&wwn, (char *)mb->un.varRDnvp.portname,
8136 		       sizeof(uint64_t));
8137 		/* wwn is WWPN of HBA instance */
8138 		wwn = cpu_to_be64(wwn);
8139 		phba->sli4_hba.wwpn.u.name = wwn;
8140 
8141 		/* Check to see if it matches any module parameter */
8142 		for (i = 0; i < lpfc_enable_nvmet_cnt; i++) {
8143 			if (wwn == lpfc_enable_nvmet[i]) {
8144 #if (IS_ENABLED(CONFIG_NVME_TARGET_FC))
8145 				if (lpfc_nvmet_mem_alloc(phba))
8146 					break;
8147 
8148 				phba->nvmet_support = 1; /* a match */
8149 
8150 				lpfc_printf_log(phba, KERN_ERR,
8151 						LOG_TRACE_EVENT,
8152 						"6017 NVME Target %016llx\n",
8153 						wwn);
8154 #else
8155 				lpfc_printf_log(phba, KERN_ERR,
8156 						LOG_TRACE_EVENT,
8157 						"6021 Can't enable NVME Target."
8158 						" NVME_TARGET_FC infrastructure"
8159 						" is not in kernel\n");
8160 #endif
8161 				/* Not supported for NVMET */
8162 				phba->cfg_xri_rebalancing = 0;
8163 				if (phba->irq_chann_mode == NHT_MODE) {
8164 					phba->cfg_irq_chann =
8165 						phba->sli4_hba.num_present_cpu;
8166 					phba->cfg_hdw_queue =
8167 						phba->sli4_hba.num_present_cpu;
8168 					phba->irq_chann_mode = NORMAL_MODE;
8169 				}
8170 				break;
8171 			}
8172 		}
8173 	}
8174 
8175 	lpfc_nvme_mod_param_dep(phba);
8176 
8177 	/*
8178 	 * Get sli4 parameters that override parameters from Port capabilities.
8179 	 * If this call fails, it isn't critical unless the SLI4 parameters come
8180 	 * back in conflict.
8181 	 */
8182 	rc = lpfc_get_sli4_parameters(phba, mboxq);
8183 	if (rc) {
8184 		if_type = bf_get(lpfc_sli_intf_if_type,
8185 				 &phba->sli4_hba.sli_intf);
8186 		if_fam = bf_get(lpfc_sli_intf_sli_family,
8187 				&phba->sli4_hba.sli_intf);
8188 		if (phba->sli4_hba.extents_in_use &&
8189 		    phba->sli4_hba.rpi_hdrs_in_use) {
8190 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8191 					"2999 Unsupported SLI4 Parameters "
8192 					"Extents and RPI headers enabled.\n");
8193 			if (if_type == LPFC_SLI_INTF_IF_TYPE_0 &&
8194 			    if_fam ==  LPFC_SLI_INTF_FAMILY_BE2) {
8195 				mempool_free(mboxq, phba->mbox_mem_pool);
8196 				rc = -EIO;
8197 				goto out_free_bsmbx;
8198 			}
8199 		}
8200 		if (!(if_type == LPFC_SLI_INTF_IF_TYPE_0 &&
8201 		      if_fam == LPFC_SLI_INTF_FAMILY_BE2)) {
8202 			mempool_free(mboxq, phba->mbox_mem_pool);
8203 			rc = -EIO;
8204 			goto out_free_bsmbx;
8205 		}
8206 	}
8207 
8208 	/*
8209 	 * 1 for cmd, 1 for rsp, NVME adds an extra one
8210 	 * for boundary conditions in its max_sgl_segment template.
8211 	 */
8212 	extra = 2;
8213 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
8214 		extra++;
8215 
8216 	/*
8217 	 * It doesn't matter what family our adapter is in, we are
8218 	 * limited to 2 Pages, 512 SGEs, for our SGL.
8219 	 * There are going to be 2 reserved SGEs: 1 FCP cmnd + 1 FCP rsp
8220 	 */
8221 	max_buf_size = (2 * SLI4_PAGE_SIZE);
8222 
8223 	/*
8224 	 * Since lpfc_sg_seg_cnt is module param, the sg_dma_buf_size
8225 	 * used to create the sg_dma_buf_pool must be calculated.
8226 	 */
8227 	if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
8228 		/* Both cfg_enable_bg and cfg_external_dif code paths */
8229 
8230 		/*
8231 		 * The scsi_buf for a T10-DIF I/O holds the FCP cmnd,
8232 		 * the FCP rsp, and a SGE. Sice we have no control
8233 		 * over how many protection segments the SCSI Layer
8234 		 * will hand us (ie: there could be one for every block
8235 		 * in the IO), just allocate enough SGEs to accomidate
8236 		 * our max amount and we need to limit lpfc_sg_seg_cnt
8237 		 * to minimize the risk of running out.
8238 		 */
8239 		phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd) +
8240 				sizeof(struct fcp_rsp) + max_buf_size;
8241 
8242 		/* Total SGEs for scsi_sg_list and scsi_sg_prot_list */
8243 		phba->cfg_total_seg_cnt = LPFC_MAX_SGL_SEG_CNT;
8244 
8245 		/*
8246 		 * If supporting DIF, reduce the seg count for scsi to
8247 		 * allow room for the DIF sges.
8248 		 */
8249 		if (phba->cfg_enable_bg &&
8250 		    phba->cfg_sg_seg_cnt > LPFC_MAX_BG_SLI4_SEG_CNT_DIF)
8251 			phba->cfg_scsi_seg_cnt = LPFC_MAX_BG_SLI4_SEG_CNT_DIF;
8252 		else
8253 			phba->cfg_scsi_seg_cnt = phba->cfg_sg_seg_cnt;
8254 
8255 	} else {
8256 		/*
8257 		 * The scsi_buf for a regular I/O holds the FCP cmnd,
8258 		 * the FCP rsp, a SGE for each, and a SGE for up to
8259 		 * cfg_sg_seg_cnt data segments.
8260 		 */
8261 		phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd) +
8262 				sizeof(struct fcp_rsp) +
8263 				((phba->cfg_sg_seg_cnt + extra) *
8264 				sizeof(struct sli4_sge));
8265 
8266 		/* Total SGEs for scsi_sg_list */
8267 		phba->cfg_total_seg_cnt = phba->cfg_sg_seg_cnt + extra;
8268 		phba->cfg_scsi_seg_cnt = phba->cfg_sg_seg_cnt;
8269 
8270 		/*
8271 		 * NOTE: if (phba->cfg_sg_seg_cnt + extra) <= 256 we only
8272 		 * need to post 1 page for the SGL.
8273 		 */
8274 	}
8275 
8276 	if (phba->cfg_xpsgl && !phba->nvmet_support)
8277 		phba->cfg_sg_dma_buf_size = LPFC_DEFAULT_XPSGL_SIZE;
8278 	else if (phba->cfg_sg_dma_buf_size  <= LPFC_MIN_SG_SLI4_BUF_SZ)
8279 		phba->cfg_sg_dma_buf_size = LPFC_MIN_SG_SLI4_BUF_SZ;
8280 	else
8281 		phba->cfg_sg_dma_buf_size =
8282 				SLI4_PAGE_ALIGN(phba->cfg_sg_dma_buf_size);
8283 
8284 	phba->border_sge_num = phba->cfg_sg_dma_buf_size /
8285 			       sizeof(struct sli4_sge);
8286 
8287 	/* Limit to LPFC_MAX_NVME_SEG_CNT for NVME. */
8288 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
8289 		if (phba->cfg_sg_seg_cnt > LPFC_MAX_NVME_SEG_CNT) {
8290 			lpfc_printf_log(phba, KERN_INFO, LOG_NVME | LOG_INIT,
8291 					"6300 Reducing NVME sg segment "
8292 					"cnt to %d\n",
8293 					LPFC_MAX_NVME_SEG_CNT);
8294 			phba->cfg_nvme_seg_cnt = LPFC_MAX_NVME_SEG_CNT;
8295 		} else
8296 			phba->cfg_nvme_seg_cnt = phba->cfg_sg_seg_cnt;
8297 	}
8298 
8299 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP,
8300 			"9087 sg_seg_cnt:%d dmabuf_size:%d "
8301 			"total:%d scsi:%d nvme:%d\n",
8302 			phba->cfg_sg_seg_cnt, phba->cfg_sg_dma_buf_size,
8303 			phba->cfg_total_seg_cnt,  phba->cfg_scsi_seg_cnt,
8304 			phba->cfg_nvme_seg_cnt);
8305 
8306 	if (phba->cfg_sg_dma_buf_size < SLI4_PAGE_SIZE)
8307 		i = phba->cfg_sg_dma_buf_size;
8308 	else
8309 		i = SLI4_PAGE_SIZE;
8310 
8311 	phba->lpfc_sg_dma_buf_pool =
8312 			dma_pool_create("lpfc_sg_dma_buf_pool",
8313 					&phba->pcidev->dev,
8314 					phba->cfg_sg_dma_buf_size,
8315 					i, 0);
8316 	if (!phba->lpfc_sg_dma_buf_pool)
8317 		goto out_free_bsmbx;
8318 
8319 	phba->lpfc_cmd_rsp_buf_pool =
8320 			dma_pool_create("lpfc_cmd_rsp_buf_pool",
8321 					&phba->pcidev->dev,
8322 					sizeof(struct fcp_cmnd) +
8323 					sizeof(struct fcp_rsp),
8324 					i, 0);
8325 	if (!phba->lpfc_cmd_rsp_buf_pool)
8326 		goto out_free_sg_dma_buf;
8327 
8328 	mempool_free(mboxq, phba->mbox_mem_pool);
8329 
8330 	/* Verify OAS is supported */
8331 	lpfc_sli4_oas_verify(phba);
8332 
8333 	/* Verify RAS support on adapter */
8334 	lpfc_sli4_ras_init(phba);
8335 
8336 	/* Verify all the SLI4 queues */
8337 	rc = lpfc_sli4_queue_verify(phba);
8338 	if (rc)
8339 		goto out_free_cmd_rsp_buf;
8340 
8341 	/* Create driver internal CQE event pool */
8342 	rc = lpfc_sli4_cq_event_pool_create(phba);
8343 	if (rc)
8344 		goto out_free_cmd_rsp_buf;
8345 
8346 	/* Initialize sgl lists per host */
8347 	lpfc_init_sgl_list(phba);
8348 
8349 	/* Allocate and initialize active sgl array */
8350 	rc = lpfc_init_active_sgl_array(phba);
8351 	if (rc) {
8352 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8353 				"1430 Failed to initialize sgl list.\n");
8354 		goto out_destroy_cq_event_pool;
8355 	}
8356 	rc = lpfc_sli4_init_rpi_hdrs(phba);
8357 	if (rc) {
8358 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8359 				"1432 Failed to initialize rpi headers.\n");
8360 		goto out_free_active_sgl;
8361 	}
8362 
8363 	/* Allocate eligible FCF bmask memory for FCF roundrobin failover */
8364 	longs = (LPFC_SLI4_FCF_TBL_INDX_MAX + BITS_PER_LONG - 1)/BITS_PER_LONG;
8365 	phba->fcf.fcf_rr_bmask = kcalloc(longs, sizeof(unsigned long),
8366 					 GFP_KERNEL);
8367 	if (!phba->fcf.fcf_rr_bmask) {
8368 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8369 				"2759 Failed allocate memory for FCF round "
8370 				"robin failover bmask\n");
8371 		rc = -ENOMEM;
8372 		goto out_remove_rpi_hdrs;
8373 	}
8374 
8375 	phba->sli4_hba.hba_eq_hdl = kcalloc(phba->cfg_irq_chann,
8376 					    sizeof(struct lpfc_hba_eq_hdl),
8377 					    GFP_KERNEL);
8378 	if (!phba->sli4_hba.hba_eq_hdl) {
8379 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8380 				"2572 Failed allocate memory for "
8381 				"fast-path per-EQ handle array\n");
8382 		rc = -ENOMEM;
8383 		goto out_free_fcf_rr_bmask;
8384 	}
8385 
8386 	phba->sli4_hba.cpu_map = kcalloc(phba->sli4_hba.num_possible_cpu,
8387 					sizeof(struct lpfc_vector_map_info),
8388 					GFP_KERNEL);
8389 	if (!phba->sli4_hba.cpu_map) {
8390 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8391 				"3327 Failed allocate memory for msi-x "
8392 				"interrupt vector mapping\n");
8393 		rc = -ENOMEM;
8394 		goto out_free_hba_eq_hdl;
8395 	}
8396 
8397 	phba->sli4_hba.eq_info = alloc_percpu(struct lpfc_eq_intr_info);
8398 	if (!phba->sli4_hba.eq_info) {
8399 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8400 				"3321 Failed allocation for per_cpu stats\n");
8401 		rc = -ENOMEM;
8402 		goto out_free_hba_cpu_map;
8403 	}
8404 
8405 	phba->sli4_hba.idle_stat = kcalloc(phba->sli4_hba.num_possible_cpu,
8406 					   sizeof(*phba->sli4_hba.idle_stat),
8407 					   GFP_KERNEL);
8408 	if (!phba->sli4_hba.idle_stat) {
8409 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8410 				"3390 Failed allocation for idle_stat\n");
8411 		rc = -ENOMEM;
8412 		goto out_free_hba_eq_info;
8413 	}
8414 
8415 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
8416 	phba->sli4_hba.c_stat = alloc_percpu(struct lpfc_hdwq_stat);
8417 	if (!phba->sli4_hba.c_stat) {
8418 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8419 				"3332 Failed allocating per cpu hdwq stats\n");
8420 		rc = -ENOMEM;
8421 		goto out_free_hba_idle_stat;
8422 	}
8423 #endif
8424 
8425 	phba->cmf_stat = alloc_percpu(struct lpfc_cgn_stat);
8426 	if (!phba->cmf_stat) {
8427 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8428 				"3331 Failed allocating per cpu cgn stats\n");
8429 		rc = -ENOMEM;
8430 		goto out_free_hba_hdwq_info;
8431 	}
8432 
8433 	/*
8434 	 * Enable sr-iov virtual functions if supported and configured
8435 	 * through the module parameter.
8436 	 */
8437 	if (phba->cfg_sriov_nr_virtfn > 0) {
8438 		rc = lpfc_sli_probe_sriov_nr_virtfn(phba,
8439 						 phba->cfg_sriov_nr_virtfn);
8440 		if (rc) {
8441 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
8442 					"3020 Requested number of SR-IOV "
8443 					"virtual functions (%d) is not "
8444 					"supported\n",
8445 					phba->cfg_sriov_nr_virtfn);
8446 			phba->cfg_sriov_nr_virtfn = 0;
8447 		}
8448 	}
8449 
8450 	return 0;
8451 
8452 out_free_hba_hdwq_info:
8453 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
8454 	free_percpu(phba->sli4_hba.c_stat);
8455 out_free_hba_idle_stat:
8456 #endif
8457 	kfree(phba->sli4_hba.idle_stat);
8458 out_free_hba_eq_info:
8459 	free_percpu(phba->sli4_hba.eq_info);
8460 out_free_hba_cpu_map:
8461 	kfree(phba->sli4_hba.cpu_map);
8462 out_free_hba_eq_hdl:
8463 	kfree(phba->sli4_hba.hba_eq_hdl);
8464 out_free_fcf_rr_bmask:
8465 	kfree(phba->fcf.fcf_rr_bmask);
8466 out_remove_rpi_hdrs:
8467 	lpfc_sli4_remove_rpi_hdrs(phba);
8468 out_free_active_sgl:
8469 	lpfc_free_active_sgl(phba);
8470 out_destroy_cq_event_pool:
8471 	lpfc_sli4_cq_event_pool_destroy(phba);
8472 out_free_cmd_rsp_buf:
8473 	dma_pool_destroy(phba->lpfc_cmd_rsp_buf_pool);
8474 	phba->lpfc_cmd_rsp_buf_pool = NULL;
8475 out_free_sg_dma_buf:
8476 	dma_pool_destroy(phba->lpfc_sg_dma_buf_pool);
8477 	phba->lpfc_sg_dma_buf_pool = NULL;
8478 out_free_bsmbx:
8479 	lpfc_destroy_bootstrap_mbox(phba);
8480 out_free_mem:
8481 	lpfc_mem_free(phba);
8482 	return rc;
8483 }
8484 
8485 /**
8486  * lpfc_sli4_driver_resource_unset - Unset drvr internal resources for SLI4 dev
8487  * @phba: pointer to lpfc hba data structure.
8488  *
8489  * This routine is invoked to unset the driver internal resources set up
8490  * specific for supporting the SLI-4 HBA device it attached to.
8491  **/
8492 static void
8493 lpfc_sli4_driver_resource_unset(struct lpfc_hba *phba)
8494 {
8495 	struct lpfc_fcf_conn_entry *conn_entry, *next_conn_entry;
8496 
8497 	free_percpu(phba->sli4_hba.eq_info);
8498 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
8499 	free_percpu(phba->sli4_hba.c_stat);
8500 #endif
8501 	free_percpu(phba->cmf_stat);
8502 	kfree(phba->sli4_hba.idle_stat);
8503 
8504 	/* Free memory allocated for msi-x interrupt vector to CPU mapping */
8505 	kfree(phba->sli4_hba.cpu_map);
8506 	phba->sli4_hba.num_possible_cpu = 0;
8507 	phba->sli4_hba.num_present_cpu = 0;
8508 	phba->sli4_hba.curr_disp_cpu = 0;
8509 	cpumask_clear(&phba->sli4_hba.irq_aff_mask);
8510 
8511 	/* Free memory allocated for fast-path work queue handles */
8512 	kfree(phba->sli4_hba.hba_eq_hdl);
8513 
8514 	/* Free the allocated rpi headers. */
8515 	lpfc_sli4_remove_rpi_hdrs(phba);
8516 	lpfc_sli4_remove_rpis(phba);
8517 
8518 	/* Free eligible FCF index bmask */
8519 	kfree(phba->fcf.fcf_rr_bmask);
8520 
8521 	/* Free the ELS sgl list */
8522 	lpfc_free_active_sgl(phba);
8523 	lpfc_free_els_sgl_list(phba);
8524 	lpfc_free_nvmet_sgl_list(phba);
8525 
8526 	/* Free the completion queue EQ event pool */
8527 	lpfc_sli4_cq_event_release_all(phba);
8528 	lpfc_sli4_cq_event_pool_destroy(phba);
8529 
8530 	/* Release resource identifiers. */
8531 	lpfc_sli4_dealloc_resource_identifiers(phba);
8532 
8533 	/* Free the bsmbx region. */
8534 	lpfc_destroy_bootstrap_mbox(phba);
8535 
8536 	/* Free the SLI Layer memory with SLI4 HBAs */
8537 	lpfc_mem_free_all(phba);
8538 
8539 	/* Free the current connect table */
8540 	list_for_each_entry_safe(conn_entry, next_conn_entry,
8541 		&phba->fcf_conn_rec_list, list) {
8542 		list_del_init(&conn_entry->list);
8543 		kfree(conn_entry);
8544 	}
8545 
8546 	return;
8547 }
8548 
8549 /**
8550  * lpfc_init_api_table_setup - Set up init api function jump table
8551  * @phba: The hba struct for which this call is being executed.
8552  * @dev_grp: The HBA PCI-Device group number.
8553  *
8554  * This routine sets up the device INIT interface API function jump table
8555  * in @phba struct.
8556  *
8557  * Returns: 0 - success, -ENODEV - failure.
8558  **/
8559 int
8560 lpfc_init_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
8561 {
8562 	phba->lpfc_hba_init_link = lpfc_hba_init_link;
8563 	phba->lpfc_hba_down_link = lpfc_hba_down_link;
8564 	phba->lpfc_selective_reset = lpfc_selective_reset;
8565 	switch (dev_grp) {
8566 	case LPFC_PCI_DEV_LP:
8567 		phba->lpfc_hba_down_post = lpfc_hba_down_post_s3;
8568 		phba->lpfc_handle_eratt = lpfc_handle_eratt_s3;
8569 		phba->lpfc_stop_port = lpfc_stop_port_s3;
8570 		break;
8571 	case LPFC_PCI_DEV_OC:
8572 		phba->lpfc_hba_down_post = lpfc_hba_down_post_s4;
8573 		phba->lpfc_handle_eratt = lpfc_handle_eratt_s4;
8574 		phba->lpfc_stop_port = lpfc_stop_port_s4;
8575 		break;
8576 	default:
8577 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8578 				"1431 Invalid HBA PCI-device group: 0x%x\n",
8579 				dev_grp);
8580 		return -ENODEV;
8581 	}
8582 	return 0;
8583 }
8584 
8585 /**
8586  * lpfc_setup_driver_resource_phase2 - Phase2 setup driver internal resources.
8587  * @phba: pointer to lpfc hba data structure.
8588  *
8589  * This routine is invoked to set up the driver internal resources after the
8590  * device specific resource setup to support the HBA device it attached to.
8591  *
8592  * Return codes
8593  * 	0 - successful
8594  * 	other values - error
8595  **/
8596 static int
8597 lpfc_setup_driver_resource_phase2(struct lpfc_hba *phba)
8598 {
8599 	int error;
8600 
8601 	/* Startup the kernel thread for this host adapter. */
8602 	phba->worker_thread = kthread_run(lpfc_do_work, phba,
8603 					  "lpfc_worker_%d", phba->brd_no);
8604 	if (IS_ERR(phba->worker_thread)) {
8605 		error = PTR_ERR(phba->worker_thread);
8606 		return error;
8607 	}
8608 
8609 	return 0;
8610 }
8611 
8612 /**
8613  * lpfc_unset_driver_resource_phase2 - Phase2 unset driver internal resources.
8614  * @phba: pointer to lpfc hba data structure.
8615  *
8616  * This routine is invoked to unset the driver internal resources set up after
8617  * the device specific resource setup for supporting the HBA device it
8618  * attached to.
8619  **/
8620 static void
8621 lpfc_unset_driver_resource_phase2(struct lpfc_hba *phba)
8622 {
8623 	if (phba->wq) {
8624 		destroy_workqueue(phba->wq);
8625 		phba->wq = NULL;
8626 	}
8627 
8628 	/* Stop kernel worker thread */
8629 	if (phba->worker_thread)
8630 		kthread_stop(phba->worker_thread);
8631 }
8632 
8633 /**
8634  * lpfc_free_iocb_list - Free iocb list.
8635  * @phba: pointer to lpfc hba data structure.
8636  *
8637  * This routine is invoked to free the driver's IOCB list and memory.
8638  **/
8639 void
8640 lpfc_free_iocb_list(struct lpfc_hba *phba)
8641 {
8642 	struct lpfc_iocbq *iocbq_entry = NULL, *iocbq_next = NULL;
8643 
8644 	spin_lock_irq(&phba->hbalock);
8645 	list_for_each_entry_safe(iocbq_entry, iocbq_next,
8646 				 &phba->lpfc_iocb_list, list) {
8647 		list_del(&iocbq_entry->list);
8648 		kfree(iocbq_entry);
8649 		phba->total_iocbq_bufs--;
8650 	}
8651 	spin_unlock_irq(&phba->hbalock);
8652 
8653 	return;
8654 }
8655 
8656 /**
8657  * lpfc_init_iocb_list - Allocate and initialize iocb list.
8658  * @phba: pointer to lpfc hba data structure.
8659  * @iocb_count: number of requested iocbs
8660  *
8661  * This routine is invoked to allocate and initizlize the driver's IOCB
8662  * list and set up the IOCB tag array accordingly.
8663  *
8664  * Return codes
8665  *	0 - successful
8666  *	other values - error
8667  **/
8668 int
8669 lpfc_init_iocb_list(struct lpfc_hba *phba, int iocb_count)
8670 {
8671 	struct lpfc_iocbq *iocbq_entry = NULL;
8672 	uint16_t iotag;
8673 	int i;
8674 
8675 	/* Initialize and populate the iocb list per host.  */
8676 	INIT_LIST_HEAD(&phba->lpfc_iocb_list);
8677 	for (i = 0; i < iocb_count; i++) {
8678 		iocbq_entry = kzalloc(sizeof(struct lpfc_iocbq), GFP_KERNEL);
8679 		if (iocbq_entry == NULL) {
8680 			printk(KERN_ERR "%s: only allocated %d iocbs of "
8681 				"expected %d count. Unloading driver.\n",
8682 				__func__, i, iocb_count);
8683 			goto out_free_iocbq;
8684 		}
8685 
8686 		iotag = lpfc_sli_next_iotag(phba, iocbq_entry);
8687 		if (iotag == 0) {
8688 			kfree(iocbq_entry);
8689 			printk(KERN_ERR "%s: failed to allocate IOTAG. "
8690 				"Unloading driver.\n", __func__);
8691 			goto out_free_iocbq;
8692 		}
8693 		iocbq_entry->sli4_lxritag = NO_XRI;
8694 		iocbq_entry->sli4_xritag = NO_XRI;
8695 
8696 		spin_lock_irq(&phba->hbalock);
8697 		list_add(&iocbq_entry->list, &phba->lpfc_iocb_list);
8698 		phba->total_iocbq_bufs++;
8699 		spin_unlock_irq(&phba->hbalock);
8700 	}
8701 
8702 	return 0;
8703 
8704 out_free_iocbq:
8705 	lpfc_free_iocb_list(phba);
8706 
8707 	return -ENOMEM;
8708 }
8709 
8710 /**
8711  * lpfc_free_sgl_list - Free a given sgl list.
8712  * @phba: pointer to lpfc hba data structure.
8713  * @sglq_list: pointer to the head of sgl list.
8714  *
8715  * This routine is invoked to free a give sgl list and memory.
8716  **/
8717 void
8718 lpfc_free_sgl_list(struct lpfc_hba *phba, struct list_head *sglq_list)
8719 {
8720 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
8721 
8722 	list_for_each_entry_safe(sglq_entry, sglq_next, sglq_list, list) {
8723 		list_del(&sglq_entry->list);
8724 		lpfc_mbuf_free(phba, sglq_entry->virt, sglq_entry->phys);
8725 		kfree(sglq_entry);
8726 	}
8727 }
8728 
8729 /**
8730  * lpfc_free_els_sgl_list - Free els sgl list.
8731  * @phba: pointer to lpfc hba data structure.
8732  *
8733  * This routine is invoked to free the driver's els sgl list and memory.
8734  **/
8735 static void
8736 lpfc_free_els_sgl_list(struct lpfc_hba *phba)
8737 {
8738 	LIST_HEAD(sglq_list);
8739 
8740 	/* Retrieve all els sgls from driver list */
8741 	spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
8742 	list_splice_init(&phba->sli4_hba.lpfc_els_sgl_list, &sglq_list);
8743 	spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
8744 
8745 	/* Now free the sgl list */
8746 	lpfc_free_sgl_list(phba, &sglq_list);
8747 }
8748 
8749 /**
8750  * lpfc_free_nvmet_sgl_list - Free nvmet sgl list.
8751  * @phba: pointer to lpfc hba data structure.
8752  *
8753  * This routine is invoked to free the driver's nvmet sgl list and memory.
8754  **/
8755 static void
8756 lpfc_free_nvmet_sgl_list(struct lpfc_hba *phba)
8757 {
8758 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
8759 	LIST_HEAD(sglq_list);
8760 
8761 	/* Retrieve all nvmet sgls from driver list */
8762 	spin_lock_irq(&phba->hbalock);
8763 	spin_lock(&phba->sli4_hba.sgl_list_lock);
8764 	list_splice_init(&phba->sli4_hba.lpfc_nvmet_sgl_list, &sglq_list);
8765 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
8766 	spin_unlock_irq(&phba->hbalock);
8767 
8768 	/* Now free the sgl list */
8769 	list_for_each_entry_safe(sglq_entry, sglq_next, &sglq_list, list) {
8770 		list_del(&sglq_entry->list);
8771 		lpfc_nvmet_buf_free(phba, sglq_entry->virt, sglq_entry->phys);
8772 		kfree(sglq_entry);
8773 	}
8774 
8775 	/* Update the nvmet_xri_cnt to reflect no current sgls.
8776 	 * The next initialization cycle sets the count and allocates
8777 	 * the sgls over again.
8778 	 */
8779 	phba->sli4_hba.nvmet_xri_cnt = 0;
8780 }
8781 
8782 /**
8783  * lpfc_init_active_sgl_array - Allocate the buf to track active ELS XRIs.
8784  * @phba: pointer to lpfc hba data structure.
8785  *
8786  * This routine is invoked to allocate the driver's active sgl memory.
8787  * This array will hold the sglq_entry's for active IOs.
8788  **/
8789 static int
8790 lpfc_init_active_sgl_array(struct lpfc_hba *phba)
8791 {
8792 	int size;
8793 	size = sizeof(struct lpfc_sglq *);
8794 	size *= phba->sli4_hba.max_cfg_param.max_xri;
8795 
8796 	phba->sli4_hba.lpfc_sglq_active_list =
8797 		kzalloc(size, GFP_KERNEL);
8798 	if (!phba->sli4_hba.lpfc_sglq_active_list)
8799 		return -ENOMEM;
8800 	return 0;
8801 }
8802 
8803 /**
8804  * lpfc_free_active_sgl - Free the buf that tracks active ELS XRIs.
8805  * @phba: pointer to lpfc hba data structure.
8806  *
8807  * This routine is invoked to walk through the array of active sglq entries
8808  * and free all of the resources.
8809  * This is just a place holder for now.
8810  **/
8811 static void
8812 lpfc_free_active_sgl(struct lpfc_hba *phba)
8813 {
8814 	kfree(phba->sli4_hba.lpfc_sglq_active_list);
8815 }
8816 
8817 /**
8818  * lpfc_init_sgl_list - Allocate and initialize sgl list.
8819  * @phba: pointer to lpfc hba data structure.
8820  *
8821  * This routine is invoked to allocate and initizlize the driver's sgl
8822  * list and set up the sgl xritag tag array accordingly.
8823  *
8824  **/
8825 static void
8826 lpfc_init_sgl_list(struct lpfc_hba *phba)
8827 {
8828 	/* Initialize and populate the sglq list per host/VF. */
8829 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_els_sgl_list);
8830 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_els_sgl_list);
8831 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_nvmet_sgl_list);
8832 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
8833 
8834 	/* els xri-sgl book keeping */
8835 	phba->sli4_hba.els_xri_cnt = 0;
8836 
8837 	/* nvme xri-buffer book keeping */
8838 	phba->sli4_hba.io_xri_cnt = 0;
8839 }
8840 
8841 /**
8842  * lpfc_sli4_init_rpi_hdrs - Post the rpi header memory region to the port
8843  * @phba: pointer to lpfc hba data structure.
8844  *
8845  * This routine is invoked to post rpi header templates to the
8846  * port for those SLI4 ports that do not support extents.  This routine
8847  * posts a PAGE_SIZE memory region to the port to hold up to
8848  * PAGE_SIZE modulo 64 rpi context headers.  This is an initialization routine
8849  * and should be called only when interrupts are disabled.
8850  *
8851  * Return codes
8852  * 	0 - successful
8853  *	-ERROR - otherwise.
8854  **/
8855 int
8856 lpfc_sli4_init_rpi_hdrs(struct lpfc_hba *phba)
8857 {
8858 	int rc = 0;
8859 	struct lpfc_rpi_hdr *rpi_hdr;
8860 
8861 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_rpi_hdr_list);
8862 	if (!phba->sli4_hba.rpi_hdrs_in_use)
8863 		return rc;
8864 	if (phba->sli4_hba.extents_in_use)
8865 		return -EIO;
8866 
8867 	rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
8868 	if (!rpi_hdr) {
8869 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8870 				"0391 Error during rpi post operation\n");
8871 		lpfc_sli4_remove_rpis(phba);
8872 		rc = -ENODEV;
8873 	}
8874 
8875 	return rc;
8876 }
8877 
8878 /**
8879  * lpfc_sli4_create_rpi_hdr - Allocate an rpi header memory region
8880  * @phba: pointer to lpfc hba data structure.
8881  *
8882  * This routine is invoked to allocate a single 4KB memory region to
8883  * support rpis and stores them in the phba.  This single region
8884  * provides support for up to 64 rpis.  The region is used globally
8885  * by the device.
8886  *
8887  * Returns:
8888  *   A valid rpi hdr on success.
8889  *   A NULL pointer on any failure.
8890  **/
8891 struct lpfc_rpi_hdr *
8892 lpfc_sli4_create_rpi_hdr(struct lpfc_hba *phba)
8893 {
8894 	uint16_t rpi_limit, curr_rpi_range;
8895 	struct lpfc_dmabuf *dmabuf;
8896 	struct lpfc_rpi_hdr *rpi_hdr;
8897 
8898 	/*
8899 	 * If the SLI4 port supports extents, posting the rpi header isn't
8900 	 * required.  Set the expected maximum count and let the actual value
8901 	 * get set when extents are fully allocated.
8902 	 */
8903 	if (!phba->sli4_hba.rpi_hdrs_in_use)
8904 		return NULL;
8905 	if (phba->sli4_hba.extents_in_use)
8906 		return NULL;
8907 
8908 	/* The limit on the logical index is just the max_rpi count. */
8909 	rpi_limit = phba->sli4_hba.max_cfg_param.max_rpi;
8910 
8911 	spin_lock_irq(&phba->hbalock);
8912 	/*
8913 	 * Establish the starting RPI in this header block.  The starting
8914 	 * rpi is normalized to a zero base because the physical rpi is
8915 	 * port based.
8916 	 */
8917 	curr_rpi_range = phba->sli4_hba.next_rpi;
8918 	spin_unlock_irq(&phba->hbalock);
8919 
8920 	/* Reached full RPI range */
8921 	if (curr_rpi_range == rpi_limit)
8922 		return NULL;
8923 
8924 	/*
8925 	 * First allocate the protocol header region for the port.  The
8926 	 * port expects a 4KB DMA-mapped memory region that is 4K aligned.
8927 	 */
8928 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
8929 	if (!dmabuf)
8930 		return NULL;
8931 
8932 	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
8933 					  LPFC_HDR_TEMPLATE_SIZE,
8934 					  &dmabuf->phys, GFP_KERNEL);
8935 	if (!dmabuf->virt) {
8936 		rpi_hdr = NULL;
8937 		goto err_free_dmabuf;
8938 	}
8939 
8940 	if (!IS_ALIGNED(dmabuf->phys, LPFC_HDR_TEMPLATE_SIZE)) {
8941 		rpi_hdr = NULL;
8942 		goto err_free_coherent;
8943 	}
8944 
8945 	/* Save the rpi header data for cleanup later. */
8946 	rpi_hdr = kzalloc(sizeof(struct lpfc_rpi_hdr), GFP_KERNEL);
8947 	if (!rpi_hdr)
8948 		goto err_free_coherent;
8949 
8950 	rpi_hdr->dmabuf = dmabuf;
8951 	rpi_hdr->len = LPFC_HDR_TEMPLATE_SIZE;
8952 	rpi_hdr->page_count = 1;
8953 	spin_lock_irq(&phba->hbalock);
8954 
8955 	/* The rpi_hdr stores the logical index only. */
8956 	rpi_hdr->start_rpi = curr_rpi_range;
8957 	rpi_hdr->next_rpi = phba->sli4_hba.next_rpi + LPFC_RPI_HDR_COUNT;
8958 	list_add_tail(&rpi_hdr->list, &phba->sli4_hba.lpfc_rpi_hdr_list);
8959 
8960 	spin_unlock_irq(&phba->hbalock);
8961 	return rpi_hdr;
8962 
8963  err_free_coherent:
8964 	dma_free_coherent(&phba->pcidev->dev, LPFC_HDR_TEMPLATE_SIZE,
8965 			  dmabuf->virt, dmabuf->phys);
8966  err_free_dmabuf:
8967 	kfree(dmabuf);
8968 	return NULL;
8969 }
8970 
8971 /**
8972  * lpfc_sli4_remove_rpi_hdrs - Remove all rpi header memory regions
8973  * @phba: pointer to lpfc hba data structure.
8974  *
8975  * This routine is invoked to remove all memory resources allocated
8976  * to support rpis for SLI4 ports not supporting extents. This routine
8977  * presumes the caller has released all rpis consumed by fabric or port
8978  * logins and is prepared to have the header pages removed.
8979  **/
8980 void
8981 lpfc_sli4_remove_rpi_hdrs(struct lpfc_hba *phba)
8982 {
8983 	struct lpfc_rpi_hdr *rpi_hdr, *next_rpi_hdr;
8984 
8985 	if (!phba->sli4_hba.rpi_hdrs_in_use)
8986 		goto exit;
8987 
8988 	list_for_each_entry_safe(rpi_hdr, next_rpi_hdr,
8989 				 &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
8990 		list_del(&rpi_hdr->list);
8991 		dma_free_coherent(&phba->pcidev->dev, rpi_hdr->len,
8992 				  rpi_hdr->dmabuf->virt, rpi_hdr->dmabuf->phys);
8993 		kfree(rpi_hdr->dmabuf);
8994 		kfree(rpi_hdr);
8995 	}
8996  exit:
8997 	/* There are no rpis available to the port now. */
8998 	phba->sli4_hba.next_rpi = 0;
8999 }
9000 
9001 /**
9002  * lpfc_hba_alloc - Allocate driver hba data structure for a device.
9003  * @pdev: pointer to pci device data structure.
9004  *
9005  * This routine is invoked to allocate the driver hba data structure for an
9006  * HBA device. If the allocation is successful, the phba reference to the
9007  * PCI device data structure is set.
9008  *
9009  * Return codes
9010  *      pointer to @phba - successful
9011  *      NULL - error
9012  **/
9013 static struct lpfc_hba *
9014 lpfc_hba_alloc(struct pci_dev *pdev)
9015 {
9016 	struct lpfc_hba *phba;
9017 
9018 	/* Allocate memory for HBA structure */
9019 	phba = kzalloc(sizeof(struct lpfc_hba), GFP_KERNEL);
9020 	if (!phba) {
9021 		dev_err(&pdev->dev, "failed to allocate hba struct\n");
9022 		return NULL;
9023 	}
9024 
9025 	/* Set reference to PCI device in HBA structure */
9026 	phba->pcidev = pdev;
9027 
9028 	/* Assign an unused board number */
9029 	phba->brd_no = lpfc_get_instance();
9030 	if (phba->brd_no < 0) {
9031 		kfree(phba);
9032 		return NULL;
9033 	}
9034 	phba->eratt_poll_interval = LPFC_ERATT_POLL_INTERVAL;
9035 
9036 	spin_lock_init(&phba->ct_ev_lock);
9037 	INIT_LIST_HEAD(&phba->ct_ev_waiters);
9038 
9039 	return phba;
9040 }
9041 
9042 /**
9043  * lpfc_hba_free - Free driver hba data structure with a device.
9044  * @phba: pointer to lpfc hba data structure.
9045  *
9046  * This routine is invoked to free the driver hba data structure with an
9047  * HBA device.
9048  **/
9049 static void
9050 lpfc_hba_free(struct lpfc_hba *phba)
9051 {
9052 	if (phba->sli_rev == LPFC_SLI_REV4)
9053 		kfree(phba->sli4_hba.hdwq);
9054 
9055 	/* Release the driver assigned board number */
9056 	idr_remove(&lpfc_hba_index, phba->brd_no);
9057 
9058 	/* Free memory allocated with sli3 rings */
9059 	kfree(phba->sli.sli3_ring);
9060 	phba->sli.sli3_ring = NULL;
9061 
9062 	kfree(phba);
9063 	return;
9064 }
9065 
9066 /**
9067  * lpfc_setup_fdmi_mask - Setup initial FDMI mask for HBA and Port attributes
9068  * @vport: pointer to lpfc vport data structure.
9069  *
9070  * This routine is will setup initial FDMI attribute masks for
9071  * FDMI2 or SmartSAN depending on module parameters. The driver will attempt
9072  * to get these attributes first before falling back, the attribute
9073  * fallback hierarchy is SmartSAN -> FDMI2 -> FMDI1
9074  **/
9075 void
9076 lpfc_setup_fdmi_mask(struct lpfc_vport *vport)
9077 {
9078 	struct lpfc_hba *phba = vport->phba;
9079 
9080 	vport->load_flag |= FC_ALLOW_FDMI;
9081 	if (phba->cfg_enable_SmartSAN ||
9082 	    phba->cfg_fdmi_on == LPFC_FDMI_SUPPORT) {
9083 		/* Setup appropriate attribute masks */
9084 		vport->fdmi_hba_mask = LPFC_FDMI2_HBA_ATTR;
9085 		if (phba->cfg_enable_SmartSAN)
9086 			vport->fdmi_port_mask = LPFC_FDMI2_SMART_ATTR;
9087 		else
9088 			vport->fdmi_port_mask = LPFC_FDMI2_PORT_ATTR;
9089 	}
9090 
9091 	lpfc_printf_log(phba, KERN_INFO, LOG_DISCOVERY,
9092 			"6077 Setup FDMI mask: hba x%x port x%x\n",
9093 			vport->fdmi_hba_mask, vport->fdmi_port_mask);
9094 }
9095 
9096 /**
9097  * lpfc_create_shost - Create hba physical port with associated scsi host.
9098  * @phba: pointer to lpfc hba data structure.
9099  *
9100  * This routine is invoked to create HBA physical port and associate a SCSI
9101  * host with it.
9102  *
9103  * Return codes
9104  *      0 - successful
9105  *      other values - error
9106  **/
9107 static int
9108 lpfc_create_shost(struct lpfc_hba *phba)
9109 {
9110 	struct lpfc_vport *vport;
9111 	struct Scsi_Host  *shost;
9112 
9113 	/* Initialize HBA FC structure */
9114 	phba->fc_edtov = FF_DEF_EDTOV;
9115 	phba->fc_ratov = FF_DEF_RATOV;
9116 	phba->fc_altov = FF_DEF_ALTOV;
9117 	phba->fc_arbtov = FF_DEF_ARBTOV;
9118 
9119 	atomic_set(&phba->sdev_cnt, 0);
9120 	vport = lpfc_create_port(phba, phba->brd_no, &phba->pcidev->dev);
9121 	if (!vport)
9122 		return -ENODEV;
9123 
9124 	shost = lpfc_shost_from_vport(vport);
9125 	phba->pport = vport;
9126 
9127 	if (phba->nvmet_support) {
9128 		/* Only 1 vport (pport) will support NVME target */
9129 		phba->targetport = NULL;
9130 		phba->cfg_enable_fc4_type = LPFC_ENABLE_NVME;
9131 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_NVME_DISC,
9132 				"6076 NVME Target Found\n");
9133 	}
9134 
9135 	lpfc_debugfs_initialize(vport);
9136 	/* Put reference to SCSI host to driver's device private data */
9137 	pci_set_drvdata(phba->pcidev, shost);
9138 
9139 	lpfc_setup_fdmi_mask(vport);
9140 
9141 	/*
9142 	 * At this point we are fully registered with PSA. In addition,
9143 	 * any initial discovery should be completed.
9144 	 */
9145 	return 0;
9146 }
9147 
9148 /**
9149  * lpfc_destroy_shost - Destroy hba physical port with associated scsi host.
9150  * @phba: pointer to lpfc hba data structure.
9151  *
9152  * This routine is invoked to destroy HBA physical port and the associated
9153  * SCSI host.
9154  **/
9155 static void
9156 lpfc_destroy_shost(struct lpfc_hba *phba)
9157 {
9158 	struct lpfc_vport *vport = phba->pport;
9159 
9160 	/* Destroy physical port that associated with the SCSI host */
9161 	destroy_port(vport);
9162 
9163 	return;
9164 }
9165 
9166 /**
9167  * lpfc_setup_bg - Setup Block guard structures and debug areas.
9168  * @phba: pointer to lpfc hba data structure.
9169  * @shost: the shost to be used to detect Block guard settings.
9170  *
9171  * This routine sets up the local Block guard protocol settings for @shost.
9172  * This routine also allocates memory for debugging bg buffers.
9173  **/
9174 static void
9175 lpfc_setup_bg(struct lpfc_hba *phba, struct Scsi_Host *shost)
9176 {
9177 	uint32_t old_mask;
9178 	uint32_t old_guard;
9179 
9180 	if (phba->cfg_prot_mask && phba->cfg_prot_guard) {
9181 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9182 				"1478 Registering BlockGuard with the "
9183 				"SCSI layer\n");
9184 
9185 		old_mask = phba->cfg_prot_mask;
9186 		old_guard = phba->cfg_prot_guard;
9187 
9188 		/* Only allow supported values */
9189 		phba->cfg_prot_mask &= (SHOST_DIF_TYPE1_PROTECTION |
9190 			SHOST_DIX_TYPE0_PROTECTION |
9191 			SHOST_DIX_TYPE1_PROTECTION);
9192 		phba->cfg_prot_guard &= (SHOST_DIX_GUARD_IP |
9193 					 SHOST_DIX_GUARD_CRC);
9194 
9195 		/* DIF Type 1 protection for profiles AST1/C1 is end to end */
9196 		if (phba->cfg_prot_mask == SHOST_DIX_TYPE1_PROTECTION)
9197 			phba->cfg_prot_mask |= SHOST_DIF_TYPE1_PROTECTION;
9198 
9199 		if (phba->cfg_prot_mask && phba->cfg_prot_guard) {
9200 			if ((old_mask != phba->cfg_prot_mask) ||
9201 				(old_guard != phba->cfg_prot_guard))
9202 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9203 					"1475 Registering BlockGuard with the "
9204 					"SCSI layer: mask %d  guard %d\n",
9205 					phba->cfg_prot_mask,
9206 					phba->cfg_prot_guard);
9207 
9208 			scsi_host_set_prot(shost, phba->cfg_prot_mask);
9209 			scsi_host_set_guard(shost, phba->cfg_prot_guard);
9210 		} else
9211 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9212 				"1479 Not Registering BlockGuard with the SCSI "
9213 				"layer, Bad protection parameters: %d %d\n",
9214 				old_mask, old_guard);
9215 	}
9216 }
9217 
9218 /**
9219  * lpfc_post_init_setup - Perform necessary device post initialization setup.
9220  * @phba: pointer to lpfc hba data structure.
9221  *
9222  * This routine is invoked to perform all the necessary post initialization
9223  * setup for the device.
9224  **/
9225 static void
9226 lpfc_post_init_setup(struct lpfc_hba *phba)
9227 {
9228 	struct Scsi_Host  *shost;
9229 	struct lpfc_adapter_event_header adapter_event;
9230 
9231 	/* Get the default values for Model Name and Description */
9232 	lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
9233 
9234 	/*
9235 	 * hba setup may have changed the hba_queue_depth so we need to
9236 	 * adjust the value of can_queue.
9237 	 */
9238 	shost = pci_get_drvdata(phba->pcidev);
9239 	shost->can_queue = phba->cfg_hba_queue_depth - 10;
9240 
9241 	lpfc_host_attrib_init(shost);
9242 
9243 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
9244 		spin_lock_irq(shost->host_lock);
9245 		lpfc_poll_start_timer(phba);
9246 		spin_unlock_irq(shost->host_lock);
9247 	}
9248 
9249 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9250 			"0428 Perform SCSI scan\n");
9251 	/* Send board arrival event to upper layer */
9252 	adapter_event.event_type = FC_REG_ADAPTER_EVENT;
9253 	adapter_event.subcategory = LPFC_EVENT_ARRIVAL;
9254 	fc_host_post_vendor_event(shost, fc_get_event_number(),
9255 				  sizeof(adapter_event),
9256 				  (char *) &adapter_event,
9257 				  LPFC_NL_VENDOR_ID);
9258 	return;
9259 }
9260 
9261 /**
9262  * lpfc_sli_pci_mem_setup - Setup SLI3 HBA PCI memory space.
9263  * @phba: pointer to lpfc hba data structure.
9264  *
9265  * This routine is invoked to set up the PCI device memory space for device
9266  * with SLI-3 interface spec.
9267  *
9268  * Return codes
9269  * 	0 - successful
9270  * 	other values - error
9271  **/
9272 static int
9273 lpfc_sli_pci_mem_setup(struct lpfc_hba *phba)
9274 {
9275 	struct pci_dev *pdev = phba->pcidev;
9276 	unsigned long bar0map_len, bar2map_len;
9277 	int i, hbq_count;
9278 	void *ptr;
9279 	int error;
9280 
9281 	if (!pdev)
9282 		return -ENODEV;
9283 
9284 	/* Set the device DMA mask size */
9285 	error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
9286 	if (error)
9287 		error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32));
9288 	if (error)
9289 		return error;
9290 	error = -ENODEV;
9291 
9292 	/* Get the bus address of Bar0 and Bar2 and the number of bytes
9293 	 * required by each mapping.
9294 	 */
9295 	phba->pci_bar0_map = pci_resource_start(pdev, 0);
9296 	bar0map_len = pci_resource_len(pdev, 0);
9297 
9298 	phba->pci_bar2_map = pci_resource_start(pdev, 2);
9299 	bar2map_len = pci_resource_len(pdev, 2);
9300 
9301 	/* Map HBA SLIM to a kernel virtual address. */
9302 	phba->slim_memmap_p = ioremap(phba->pci_bar0_map, bar0map_len);
9303 	if (!phba->slim_memmap_p) {
9304 		dev_printk(KERN_ERR, &pdev->dev,
9305 			   "ioremap failed for SLIM memory.\n");
9306 		goto out;
9307 	}
9308 
9309 	/* Map HBA Control Registers to a kernel virtual address. */
9310 	phba->ctrl_regs_memmap_p = ioremap(phba->pci_bar2_map, bar2map_len);
9311 	if (!phba->ctrl_regs_memmap_p) {
9312 		dev_printk(KERN_ERR, &pdev->dev,
9313 			   "ioremap failed for HBA control registers.\n");
9314 		goto out_iounmap_slim;
9315 	}
9316 
9317 	/* Allocate memory for SLI-2 structures */
9318 	phba->slim2p.virt = dma_alloc_coherent(&pdev->dev, SLI2_SLIM_SIZE,
9319 					       &phba->slim2p.phys, GFP_KERNEL);
9320 	if (!phba->slim2p.virt)
9321 		goto out_iounmap;
9322 
9323 	phba->mbox = phba->slim2p.virt + offsetof(struct lpfc_sli2_slim, mbx);
9324 	phba->mbox_ext = (phba->slim2p.virt +
9325 		offsetof(struct lpfc_sli2_slim, mbx_ext_words));
9326 	phba->pcb = (phba->slim2p.virt + offsetof(struct lpfc_sli2_slim, pcb));
9327 	phba->IOCBs = (phba->slim2p.virt +
9328 		       offsetof(struct lpfc_sli2_slim, IOCBs));
9329 
9330 	phba->hbqslimp.virt = dma_alloc_coherent(&pdev->dev,
9331 						 lpfc_sli_hbq_size(),
9332 						 &phba->hbqslimp.phys,
9333 						 GFP_KERNEL);
9334 	if (!phba->hbqslimp.virt)
9335 		goto out_free_slim;
9336 
9337 	hbq_count = lpfc_sli_hbq_count();
9338 	ptr = phba->hbqslimp.virt;
9339 	for (i = 0; i < hbq_count; ++i) {
9340 		phba->hbqs[i].hbq_virt = ptr;
9341 		INIT_LIST_HEAD(&phba->hbqs[i].hbq_buffer_list);
9342 		ptr += (lpfc_hbq_defs[i]->entry_count *
9343 			sizeof(struct lpfc_hbq_entry));
9344 	}
9345 	phba->hbqs[LPFC_ELS_HBQ].hbq_alloc_buffer = lpfc_els_hbq_alloc;
9346 	phba->hbqs[LPFC_ELS_HBQ].hbq_free_buffer = lpfc_els_hbq_free;
9347 
9348 	memset(phba->hbqslimp.virt, 0, lpfc_sli_hbq_size());
9349 
9350 	phba->MBslimaddr = phba->slim_memmap_p;
9351 	phba->HAregaddr = phba->ctrl_regs_memmap_p + HA_REG_OFFSET;
9352 	phba->CAregaddr = phba->ctrl_regs_memmap_p + CA_REG_OFFSET;
9353 	phba->HSregaddr = phba->ctrl_regs_memmap_p + HS_REG_OFFSET;
9354 	phba->HCregaddr = phba->ctrl_regs_memmap_p + HC_REG_OFFSET;
9355 
9356 	return 0;
9357 
9358 out_free_slim:
9359 	dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
9360 			  phba->slim2p.virt, phba->slim2p.phys);
9361 out_iounmap:
9362 	iounmap(phba->ctrl_regs_memmap_p);
9363 out_iounmap_slim:
9364 	iounmap(phba->slim_memmap_p);
9365 out:
9366 	return error;
9367 }
9368 
9369 /**
9370  * lpfc_sli_pci_mem_unset - Unset SLI3 HBA PCI memory space.
9371  * @phba: pointer to lpfc hba data structure.
9372  *
9373  * This routine is invoked to unset the PCI device memory space for device
9374  * with SLI-3 interface spec.
9375  **/
9376 static void
9377 lpfc_sli_pci_mem_unset(struct lpfc_hba *phba)
9378 {
9379 	struct pci_dev *pdev;
9380 
9381 	/* Obtain PCI device reference */
9382 	if (!phba->pcidev)
9383 		return;
9384 	else
9385 		pdev = phba->pcidev;
9386 
9387 	/* Free coherent DMA memory allocated */
9388 	dma_free_coherent(&pdev->dev, lpfc_sli_hbq_size(),
9389 			  phba->hbqslimp.virt, phba->hbqslimp.phys);
9390 	dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
9391 			  phba->slim2p.virt, phba->slim2p.phys);
9392 
9393 	/* I/O memory unmap */
9394 	iounmap(phba->ctrl_regs_memmap_p);
9395 	iounmap(phba->slim_memmap_p);
9396 
9397 	return;
9398 }
9399 
9400 /**
9401  * lpfc_sli4_post_status_check - Wait for SLI4 POST done and check status
9402  * @phba: pointer to lpfc hba data structure.
9403  *
9404  * This routine is invoked to wait for SLI4 device Power On Self Test (POST)
9405  * done and check status.
9406  *
9407  * Return 0 if successful, otherwise -ENODEV.
9408  **/
9409 int
9410 lpfc_sli4_post_status_check(struct lpfc_hba *phba)
9411 {
9412 	struct lpfc_register portsmphr_reg, uerrlo_reg, uerrhi_reg;
9413 	struct lpfc_register reg_data;
9414 	int i, port_error = 0;
9415 	uint32_t if_type;
9416 
9417 	memset(&portsmphr_reg, 0, sizeof(portsmphr_reg));
9418 	memset(&reg_data, 0, sizeof(reg_data));
9419 	if (!phba->sli4_hba.PSMPHRregaddr)
9420 		return -ENODEV;
9421 
9422 	/* Wait up to 30 seconds for the SLI Port POST done and ready */
9423 	for (i = 0; i < 3000; i++) {
9424 		if (lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
9425 			&portsmphr_reg.word0) ||
9426 			(bf_get(lpfc_port_smphr_perr, &portsmphr_reg))) {
9427 			/* Port has a fatal POST error, break out */
9428 			port_error = -ENODEV;
9429 			break;
9430 		}
9431 		if (LPFC_POST_STAGE_PORT_READY ==
9432 		    bf_get(lpfc_port_smphr_port_status, &portsmphr_reg))
9433 			break;
9434 		msleep(10);
9435 	}
9436 
9437 	/*
9438 	 * If there was a port error during POST, then don't proceed with
9439 	 * other register reads as the data may not be valid.  Just exit.
9440 	 */
9441 	if (port_error) {
9442 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9443 			"1408 Port Failed POST - portsmphr=0x%x, "
9444 			"perr=x%x, sfi=x%x, nip=x%x, ipc=x%x, scr1=x%x, "
9445 			"scr2=x%x, hscratch=x%x, pstatus=x%x\n",
9446 			portsmphr_reg.word0,
9447 			bf_get(lpfc_port_smphr_perr, &portsmphr_reg),
9448 			bf_get(lpfc_port_smphr_sfi, &portsmphr_reg),
9449 			bf_get(lpfc_port_smphr_nip, &portsmphr_reg),
9450 			bf_get(lpfc_port_smphr_ipc, &portsmphr_reg),
9451 			bf_get(lpfc_port_smphr_scr1, &portsmphr_reg),
9452 			bf_get(lpfc_port_smphr_scr2, &portsmphr_reg),
9453 			bf_get(lpfc_port_smphr_host_scratch, &portsmphr_reg),
9454 			bf_get(lpfc_port_smphr_port_status, &portsmphr_reg));
9455 	} else {
9456 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9457 				"2534 Device Info: SLIFamily=0x%x, "
9458 				"SLIRev=0x%x, IFType=0x%x, SLIHint_1=0x%x, "
9459 				"SLIHint_2=0x%x, FT=0x%x\n",
9460 				bf_get(lpfc_sli_intf_sli_family,
9461 				       &phba->sli4_hba.sli_intf),
9462 				bf_get(lpfc_sli_intf_slirev,
9463 				       &phba->sli4_hba.sli_intf),
9464 				bf_get(lpfc_sli_intf_if_type,
9465 				       &phba->sli4_hba.sli_intf),
9466 				bf_get(lpfc_sli_intf_sli_hint1,
9467 				       &phba->sli4_hba.sli_intf),
9468 				bf_get(lpfc_sli_intf_sli_hint2,
9469 				       &phba->sli4_hba.sli_intf),
9470 				bf_get(lpfc_sli_intf_func_type,
9471 				       &phba->sli4_hba.sli_intf));
9472 		/*
9473 		 * Check for other Port errors during the initialization
9474 		 * process.  Fail the load if the port did not come up
9475 		 * correctly.
9476 		 */
9477 		if_type = bf_get(lpfc_sli_intf_if_type,
9478 				 &phba->sli4_hba.sli_intf);
9479 		switch (if_type) {
9480 		case LPFC_SLI_INTF_IF_TYPE_0:
9481 			phba->sli4_hba.ue_mask_lo =
9482 			      readl(phba->sli4_hba.u.if_type0.UEMASKLOregaddr);
9483 			phba->sli4_hba.ue_mask_hi =
9484 			      readl(phba->sli4_hba.u.if_type0.UEMASKHIregaddr);
9485 			uerrlo_reg.word0 =
9486 			      readl(phba->sli4_hba.u.if_type0.UERRLOregaddr);
9487 			uerrhi_reg.word0 =
9488 				readl(phba->sli4_hba.u.if_type0.UERRHIregaddr);
9489 			if ((~phba->sli4_hba.ue_mask_lo & uerrlo_reg.word0) ||
9490 			    (~phba->sli4_hba.ue_mask_hi & uerrhi_reg.word0)) {
9491 				lpfc_printf_log(phba, KERN_ERR,
9492 						LOG_TRACE_EVENT,
9493 						"1422 Unrecoverable Error "
9494 						"Detected during POST "
9495 						"uerr_lo_reg=0x%x, "
9496 						"uerr_hi_reg=0x%x, "
9497 						"ue_mask_lo_reg=0x%x, "
9498 						"ue_mask_hi_reg=0x%x\n",
9499 						uerrlo_reg.word0,
9500 						uerrhi_reg.word0,
9501 						phba->sli4_hba.ue_mask_lo,
9502 						phba->sli4_hba.ue_mask_hi);
9503 				port_error = -ENODEV;
9504 			}
9505 			break;
9506 		case LPFC_SLI_INTF_IF_TYPE_2:
9507 		case LPFC_SLI_INTF_IF_TYPE_6:
9508 			/* Final checks.  The port status should be clean. */
9509 			if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
9510 				&reg_data.word0) ||
9511 				(bf_get(lpfc_sliport_status_err, &reg_data) &&
9512 				 !bf_get(lpfc_sliport_status_rn, &reg_data))) {
9513 				phba->work_status[0] =
9514 					readl(phba->sli4_hba.u.if_type2.
9515 					      ERR1regaddr);
9516 				phba->work_status[1] =
9517 					readl(phba->sli4_hba.u.if_type2.
9518 					      ERR2regaddr);
9519 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9520 					"2888 Unrecoverable port error "
9521 					"following POST: port status reg "
9522 					"0x%x, port_smphr reg 0x%x, "
9523 					"error 1=0x%x, error 2=0x%x\n",
9524 					reg_data.word0,
9525 					portsmphr_reg.word0,
9526 					phba->work_status[0],
9527 					phba->work_status[1]);
9528 				port_error = -ENODEV;
9529 				break;
9530 			}
9531 
9532 			if (lpfc_pldv_detect &&
9533 			    bf_get(lpfc_sli_intf_sli_family,
9534 				   &phba->sli4_hba.sli_intf) ==
9535 					LPFC_SLI_INTF_FAMILY_G6)
9536 				pci_write_config_byte(phba->pcidev,
9537 						      LPFC_SLI_INTF, CFG_PLD);
9538 			break;
9539 		case LPFC_SLI_INTF_IF_TYPE_1:
9540 		default:
9541 			break;
9542 		}
9543 	}
9544 	return port_error;
9545 }
9546 
9547 /**
9548  * lpfc_sli4_bar0_register_memmap - Set up SLI4 BAR0 register memory map.
9549  * @phba: pointer to lpfc hba data structure.
9550  * @if_type:  The SLI4 interface type getting configured.
9551  *
9552  * This routine is invoked to set up SLI4 BAR0 PCI config space register
9553  * memory map.
9554  **/
9555 static void
9556 lpfc_sli4_bar0_register_memmap(struct lpfc_hba *phba, uint32_t if_type)
9557 {
9558 	switch (if_type) {
9559 	case LPFC_SLI_INTF_IF_TYPE_0:
9560 		phba->sli4_hba.u.if_type0.UERRLOregaddr =
9561 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UERR_STATUS_LO;
9562 		phba->sli4_hba.u.if_type0.UERRHIregaddr =
9563 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UERR_STATUS_HI;
9564 		phba->sli4_hba.u.if_type0.UEMASKLOregaddr =
9565 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UE_MASK_LO;
9566 		phba->sli4_hba.u.if_type0.UEMASKHIregaddr =
9567 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UE_MASK_HI;
9568 		phba->sli4_hba.SLIINTFregaddr =
9569 			phba->sli4_hba.conf_regs_memmap_p + LPFC_SLI_INTF;
9570 		break;
9571 	case LPFC_SLI_INTF_IF_TYPE_2:
9572 		phba->sli4_hba.u.if_type2.EQDregaddr =
9573 			phba->sli4_hba.conf_regs_memmap_p +
9574 						LPFC_CTL_PORT_EQ_DELAY_OFFSET;
9575 		phba->sli4_hba.u.if_type2.ERR1regaddr =
9576 			phba->sli4_hba.conf_regs_memmap_p +
9577 						LPFC_CTL_PORT_ER1_OFFSET;
9578 		phba->sli4_hba.u.if_type2.ERR2regaddr =
9579 			phba->sli4_hba.conf_regs_memmap_p +
9580 						LPFC_CTL_PORT_ER2_OFFSET;
9581 		phba->sli4_hba.u.if_type2.CTRLregaddr =
9582 			phba->sli4_hba.conf_regs_memmap_p +
9583 						LPFC_CTL_PORT_CTL_OFFSET;
9584 		phba->sli4_hba.u.if_type2.STATUSregaddr =
9585 			phba->sli4_hba.conf_regs_memmap_p +
9586 						LPFC_CTL_PORT_STA_OFFSET;
9587 		phba->sli4_hba.SLIINTFregaddr =
9588 			phba->sli4_hba.conf_regs_memmap_p + LPFC_SLI_INTF;
9589 		phba->sli4_hba.PSMPHRregaddr =
9590 			phba->sli4_hba.conf_regs_memmap_p +
9591 						LPFC_CTL_PORT_SEM_OFFSET;
9592 		phba->sli4_hba.RQDBregaddr =
9593 			phba->sli4_hba.conf_regs_memmap_p +
9594 						LPFC_ULP0_RQ_DOORBELL;
9595 		phba->sli4_hba.WQDBregaddr =
9596 			phba->sli4_hba.conf_regs_memmap_p +
9597 						LPFC_ULP0_WQ_DOORBELL;
9598 		phba->sli4_hba.CQDBregaddr =
9599 			phba->sli4_hba.conf_regs_memmap_p + LPFC_EQCQ_DOORBELL;
9600 		phba->sli4_hba.EQDBregaddr = phba->sli4_hba.CQDBregaddr;
9601 		phba->sli4_hba.MQDBregaddr =
9602 			phba->sli4_hba.conf_regs_memmap_p + LPFC_MQ_DOORBELL;
9603 		phba->sli4_hba.BMBXregaddr =
9604 			phba->sli4_hba.conf_regs_memmap_p + LPFC_BMBX;
9605 		break;
9606 	case LPFC_SLI_INTF_IF_TYPE_6:
9607 		phba->sli4_hba.u.if_type2.EQDregaddr =
9608 			phba->sli4_hba.conf_regs_memmap_p +
9609 						LPFC_CTL_PORT_EQ_DELAY_OFFSET;
9610 		phba->sli4_hba.u.if_type2.ERR1regaddr =
9611 			phba->sli4_hba.conf_regs_memmap_p +
9612 						LPFC_CTL_PORT_ER1_OFFSET;
9613 		phba->sli4_hba.u.if_type2.ERR2regaddr =
9614 			phba->sli4_hba.conf_regs_memmap_p +
9615 						LPFC_CTL_PORT_ER2_OFFSET;
9616 		phba->sli4_hba.u.if_type2.CTRLregaddr =
9617 			phba->sli4_hba.conf_regs_memmap_p +
9618 						LPFC_CTL_PORT_CTL_OFFSET;
9619 		phba->sli4_hba.u.if_type2.STATUSregaddr =
9620 			phba->sli4_hba.conf_regs_memmap_p +
9621 						LPFC_CTL_PORT_STA_OFFSET;
9622 		phba->sli4_hba.PSMPHRregaddr =
9623 			phba->sli4_hba.conf_regs_memmap_p +
9624 						LPFC_CTL_PORT_SEM_OFFSET;
9625 		phba->sli4_hba.BMBXregaddr =
9626 			phba->sli4_hba.conf_regs_memmap_p + LPFC_BMBX;
9627 		break;
9628 	case LPFC_SLI_INTF_IF_TYPE_1:
9629 	default:
9630 		dev_printk(KERN_ERR, &phba->pcidev->dev,
9631 			   "FATAL - unsupported SLI4 interface type - %d\n",
9632 			   if_type);
9633 		break;
9634 	}
9635 }
9636 
9637 /**
9638  * lpfc_sli4_bar1_register_memmap - Set up SLI4 BAR1 register memory map.
9639  * @phba: pointer to lpfc hba data structure.
9640  * @if_type: sli if type to operate on.
9641  *
9642  * This routine is invoked to set up SLI4 BAR1 register memory map.
9643  **/
9644 static void
9645 lpfc_sli4_bar1_register_memmap(struct lpfc_hba *phba, uint32_t if_type)
9646 {
9647 	switch (if_type) {
9648 	case LPFC_SLI_INTF_IF_TYPE_0:
9649 		phba->sli4_hba.PSMPHRregaddr =
9650 			phba->sli4_hba.ctrl_regs_memmap_p +
9651 			LPFC_SLIPORT_IF0_SMPHR;
9652 		phba->sli4_hba.ISRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
9653 			LPFC_HST_ISR0;
9654 		phba->sli4_hba.IMRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
9655 			LPFC_HST_IMR0;
9656 		phba->sli4_hba.ISCRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
9657 			LPFC_HST_ISCR0;
9658 		break;
9659 	case LPFC_SLI_INTF_IF_TYPE_6:
9660 		phba->sli4_hba.RQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9661 			LPFC_IF6_RQ_DOORBELL;
9662 		phba->sli4_hba.WQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9663 			LPFC_IF6_WQ_DOORBELL;
9664 		phba->sli4_hba.CQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9665 			LPFC_IF6_CQ_DOORBELL;
9666 		phba->sli4_hba.EQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9667 			LPFC_IF6_EQ_DOORBELL;
9668 		phba->sli4_hba.MQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9669 			LPFC_IF6_MQ_DOORBELL;
9670 		break;
9671 	case LPFC_SLI_INTF_IF_TYPE_2:
9672 	case LPFC_SLI_INTF_IF_TYPE_1:
9673 	default:
9674 		dev_err(&phba->pcidev->dev,
9675 			   "FATAL - unsupported SLI4 interface type - %d\n",
9676 			   if_type);
9677 		break;
9678 	}
9679 }
9680 
9681 /**
9682  * lpfc_sli4_bar2_register_memmap - Set up SLI4 BAR2 register memory map.
9683  * @phba: pointer to lpfc hba data structure.
9684  * @vf: virtual function number
9685  *
9686  * This routine is invoked to set up SLI4 BAR2 doorbell register memory map
9687  * based on the given viftual function number, @vf.
9688  *
9689  * Return 0 if successful, otherwise -ENODEV.
9690  **/
9691 static int
9692 lpfc_sli4_bar2_register_memmap(struct lpfc_hba *phba, uint32_t vf)
9693 {
9694 	if (vf > LPFC_VIR_FUNC_MAX)
9695 		return -ENODEV;
9696 
9697 	phba->sli4_hba.RQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9698 				vf * LPFC_VFR_PAGE_SIZE +
9699 					LPFC_ULP0_RQ_DOORBELL);
9700 	phba->sli4_hba.WQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9701 				vf * LPFC_VFR_PAGE_SIZE +
9702 					LPFC_ULP0_WQ_DOORBELL);
9703 	phba->sli4_hba.CQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9704 				vf * LPFC_VFR_PAGE_SIZE +
9705 					LPFC_EQCQ_DOORBELL);
9706 	phba->sli4_hba.EQDBregaddr = phba->sli4_hba.CQDBregaddr;
9707 	phba->sli4_hba.MQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9708 				vf * LPFC_VFR_PAGE_SIZE + LPFC_MQ_DOORBELL);
9709 	phba->sli4_hba.BMBXregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9710 				vf * LPFC_VFR_PAGE_SIZE + LPFC_BMBX);
9711 	return 0;
9712 }
9713 
9714 /**
9715  * lpfc_create_bootstrap_mbox - Create the bootstrap mailbox
9716  * @phba: pointer to lpfc hba data structure.
9717  *
9718  * This routine is invoked to create the bootstrap mailbox
9719  * region consistent with the SLI-4 interface spec.  This
9720  * routine allocates all memory necessary to communicate
9721  * mailbox commands to the port and sets up all alignment
9722  * needs.  No locks are expected to be held when calling
9723  * this routine.
9724  *
9725  * Return codes
9726  * 	0 - successful
9727  * 	-ENOMEM - could not allocated memory.
9728  **/
9729 static int
9730 lpfc_create_bootstrap_mbox(struct lpfc_hba *phba)
9731 {
9732 	uint32_t bmbx_size;
9733 	struct lpfc_dmabuf *dmabuf;
9734 	struct dma_address *dma_address;
9735 	uint32_t pa_addr;
9736 	uint64_t phys_addr;
9737 
9738 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
9739 	if (!dmabuf)
9740 		return -ENOMEM;
9741 
9742 	/*
9743 	 * The bootstrap mailbox region is comprised of 2 parts
9744 	 * plus an alignment restriction of 16 bytes.
9745 	 */
9746 	bmbx_size = sizeof(struct lpfc_bmbx_create) + (LPFC_ALIGN_16_BYTE - 1);
9747 	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev, bmbx_size,
9748 					  &dmabuf->phys, GFP_KERNEL);
9749 	if (!dmabuf->virt) {
9750 		kfree(dmabuf);
9751 		return -ENOMEM;
9752 	}
9753 
9754 	/*
9755 	 * Initialize the bootstrap mailbox pointers now so that the register
9756 	 * operations are simple later.  The mailbox dma address is required
9757 	 * to be 16-byte aligned.  Also align the virtual memory as each
9758 	 * maibox is copied into the bmbx mailbox region before issuing the
9759 	 * command to the port.
9760 	 */
9761 	phba->sli4_hba.bmbx.dmabuf = dmabuf;
9762 	phba->sli4_hba.bmbx.bmbx_size = bmbx_size;
9763 
9764 	phba->sli4_hba.bmbx.avirt = PTR_ALIGN(dmabuf->virt,
9765 					      LPFC_ALIGN_16_BYTE);
9766 	phba->sli4_hba.bmbx.aphys = ALIGN(dmabuf->phys,
9767 					      LPFC_ALIGN_16_BYTE);
9768 
9769 	/*
9770 	 * Set the high and low physical addresses now.  The SLI4 alignment
9771 	 * requirement is 16 bytes and the mailbox is posted to the port
9772 	 * as two 30-bit addresses.  The other data is a bit marking whether
9773 	 * the 30-bit address is the high or low address.
9774 	 * Upcast bmbx aphys to 64bits so shift instruction compiles
9775 	 * clean on 32 bit machines.
9776 	 */
9777 	dma_address = &phba->sli4_hba.bmbx.dma_address;
9778 	phys_addr = (uint64_t)phba->sli4_hba.bmbx.aphys;
9779 	pa_addr = (uint32_t) ((phys_addr >> 34) & 0x3fffffff);
9780 	dma_address->addr_hi = (uint32_t) ((pa_addr << 2) |
9781 					   LPFC_BMBX_BIT1_ADDR_HI);
9782 
9783 	pa_addr = (uint32_t) ((phba->sli4_hba.bmbx.aphys >> 4) & 0x3fffffff);
9784 	dma_address->addr_lo = (uint32_t) ((pa_addr << 2) |
9785 					   LPFC_BMBX_BIT1_ADDR_LO);
9786 	return 0;
9787 }
9788 
9789 /**
9790  * lpfc_destroy_bootstrap_mbox - Destroy all bootstrap mailbox resources
9791  * @phba: pointer to lpfc hba data structure.
9792  *
9793  * This routine is invoked to teardown the bootstrap mailbox
9794  * region and release all host resources. This routine requires
9795  * the caller to ensure all mailbox commands recovered, no
9796  * additional mailbox comands are sent, and interrupts are disabled
9797  * before calling this routine.
9798  *
9799  **/
9800 static void
9801 lpfc_destroy_bootstrap_mbox(struct lpfc_hba *phba)
9802 {
9803 	dma_free_coherent(&phba->pcidev->dev,
9804 			  phba->sli4_hba.bmbx.bmbx_size,
9805 			  phba->sli4_hba.bmbx.dmabuf->virt,
9806 			  phba->sli4_hba.bmbx.dmabuf->phys);
9807 
9808 	kfree(phba->sli4_hba.bmbx.dmabuf);
9809 	memset(&phba->sli4_hba.bmbx, 0, sizeof(struct lpfc_bmbx));
9810 }
9811 
9812 static const char * const lpfc_topo_to_str[] = {
9813 	"Loop then P2P",
9814 	"Loopback",
9815 	"P2P Only",
9816 	"Unsupported",
9817 	"Loop Only",
9818 	"Unsupported",
9819 	"P2P then Loop",
9820 };
9821 
9822 #define	LINK_FLAGS_DEF	0x0
9823 #define	LINK_FLAGS_P2P	0x1
9824 #define	LINK_FLAGS_LOOP	0x2
9825 /**
9826  * lpfc_map_topology - Map the topology read from READ_CONFIG
9827  * @phba: pointer to lpfc hba data structure.
9828  * @rd_config: pointer to read config data
9829  *
9830  * This routine is invoked to map the topology values as read
9831  * from the read config mailbox command. If the persistent
9832  * topology feature is supported, the firmware will provide the
9833  * saved topology information to be used in INIT_LINK
9834  **/
9835 static void
9836 lpfc_map_topology(struct lpfc_hba *phba, struct lpfc_mbx_read_config *rd_config)
9837 {
9838 	u8 ptv, tf, pt;
9839 
9840 	ptv = bf_get(lpfc_mbx_rd_conf_ptv, rd_config);
9841 	tf = bf_get(lpfc_mbx_rd_conf_tf, rd_config);
9842 	pt = bf_get(lpfc_mbx_rd_conf_pt, rd_config);
9843 
9844 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9845 			"2027 Read Config Data : ptv:0x%x, tf:0x%x pt:0x%x",
9846 			 ptv, tf, pt);
9847 	if (!ptv) {
9848 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9849 				"2019 FW does not support persistent topology "
9850 				"Using driver parameter defined value [%s]",
9851 				lpfc_topo_to_str[phba->cfg_topology]);
9852 		return;
9853 	}
9854 	/* FW supports persistent topology - override module parameter value */
9855 	phba->hba_flag |= HBA_PERSISTENT_TOPO;
9856 
9857 	/* if ASIC_GEN_NUM >= 0xC) */
9858 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
9859 		    LPFC_SLI_INTF_IF_TYPE_6) ||
9860 	    (bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf) ==
9861 		    LPFC_SLI_INTF_FAMILY_G6)) {
9862 		if (!tf) {
9863 			phba->cfg_topology = ((pt == LINK_FLAGS_LOOP)
9864 					? FLAGS_TOPOLOGY_MODE_LOOP
9865 					: FLAGS_TOPOLOGY_MODE_PT_PT);
9866 		} else {
9867 			phba->hba_flag &= ~HBA_PERSISTENT_TOPO;
9868 		}
9869 	} else { /* G5 */
9870 		if (tf) {
9871 			/* If topology failover set - pt is '0' or '1' */
9872 			phba->cfg_topology = (pt ? FLAGS_TOPOLOGY_MODE_PT_LOOP :
9873 					      FLAGS_TOPOLOGY_MODE_LOOP_PT);
9874 		} else {
9875 			phba->cfg_topology = ((pt == LINK_FLAGS_P2P)
9876 					? FLAGS_TOPOLOGY_MODE_PT_PT
9877 					: FLAGS_TOPOLOGY_MODE_LOOP);
9878 		}
9879 	}
9880 	if (phba->hba_flag & HBA_PERSISTENT_TOPO) {
9881 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9882 				"2020 Using persistent topology value [%s]",
9883 				lpfc_topo_to_str[phba->cfg_topology]);
9884 	} else {
9885 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9886 				"2021 Invalid topology values from FW "
9887 				"Using driver parameter defined value [%s]",
9888 				lpfc_topo_to_str[phba->cfg_topology]);
9889 	}
9890 }
9891 
9892 /**
9893  * lpfc_sli4_read_config - Get the config parameters.
9894  * @phba: pointer to lpfc hba data structure.
9895  *
9896  * This routine is invoked to read the configuration parameters from the HBA.
9897  * The configuration parameters are used to set the base and maximum values
9898  * for RPI's XRI's VPI's VFI's and FCFIs. These values also affect the resource
9899  * allocation for the port.
9900  *
9901  * Return codes
9902  * 	0 - successful
9903  * 	-ENOMEM - No available memory
9904  *      -EIO - The mailbox failed to complete successfully.
9905  **/
9906 int
9907 lpfc_sli4_read_config(struct lpfc_hba *phba)
9908 {
9909 	LPFC_MBOXQ_t *pmb;
9910 	struct lpfc_mbx_read_config *rd_config;
9911 	union  lpfc_sli4_cfg_shdr *shdr;
9912 	uint32_t shdr_status, shdr_add_status;
9913 	struct lpfc_mbx_get_func_cfg *get_func_cfg;
9914 	struct lpfc_rsrc_desc_fcfcoe *desc;
9915 	char *pdesc_0;
9916 	uint16_t forced_link_speed;
9917 	uint32_t if_type, qmin, fawwpn;
9918 	int length, i, rc = 0, rc2;
9919 
9920 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
9921 	if (!pmb) {
9922 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9923 				"2011 Unable to allocate memory for issuing "
9924 				"SLI_CONFIG_SPECIAL mailbox command\n");
9925 		return -ENOMEM;
9926 	}
9927 
9928 	lpfc_read_config(phba, pmb);
9929 
9930 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
9931 	if (rc != MBX_SUCCESS) {
9932 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9933 				"2012 Mailbox failed , mbxCmd x%x "
9934 				"READ_CONFIG, mbxStatus x%x\n",
9935 				bf_get(lpfc_mqe_command, &pmb->u.mqe),
9936 				bf_get(lpfc_mqe_status, &pmb->u.mqe));
9937 		rc = -EIO;
9938 	} else {
9939 		rd_config = &pmb->u.mqe.un.rd_config;
9940 		if (bf_get(lpfc_mbx_rd_conf_lnk_ldv, rd_config)) {
9941 			phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL;
9942 			phba->sli4_hba.lnk_info.lnk_tp =
9943 				bf_get(lpfc_mbx_rd_conf_lnk_type, rd_config);
9944 			phba->sli4_hba.lnk_info.lnk_no =
9945 				bf_get(lpfc_mbx_rd_conf_lnk_numb, rd_config);
9946 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9947 					"3081 lnk_type:%d, lnk_numb:%d\n",
9948 					phba->sli4_hba.lnk_info.lnk_tp,
9949 					phba->sli4_hba.lnk_info.lnk_no);
9950 		} else
9951 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9952 					"3082 Mailbox (x%x) returned ldv:x0\n",
9953 					bf_get(lpfc_mqe_command, &pmb->u.mqe));
9954 		if (bf_get(lpfc_mbx_rd_conf_bbscn_def, rd_config)) {
9955 			phba->bbcredit_support = 1;
9956 			phba->sli4_hba.bbscn_params.word0 = rd_config->word8;
9957 		}
9958 
9959 		fawwpn = bf_get(lpfc_mbx_rd_conf_fawwpn, rd_config);
9960 
9961 		if (fawwpn) {
9962 			lpfc_printf_log(phba, KERN_INFO,
9963 					LOG_INIT | LOG_DISCOVERY,
9964 					"2702 READ_CONFIG: FA-PWWN is "
9965 					"configured on\n");
9966 			phba->sli4_hba.fawwpn_flag |= LPFC_FAWWPN_CONFIG;
9967 		} else {
9968 			/* Clear FW configured flag, preserve driver flag */
9969 			phba->sli4_hba.fawwpn_flag &= ~LPFC_FAWWPN_CONFIG;
9970 		}
9971 
9972 		phba->sli4_hba.conf_trunk =
9973 			bf_get(lpfc_mbx_rd_conf_trunk, rd_config);
9974 		phba->sli4_hba.extents_in_use =
9975 			bf_get(lpfc_mbx_rd_conf_extnts_inuse, rd_config);
9976 
9977 		phba->sli4_hba.max_cfg_param.max_xri =
9978 			bf_get(lpfc_mbx_rd_conf_xri_count, rd_config);
9979 		/* Reduce resource usage in kdump environment */
9980 		if (is_kdump_kernel() &&
9981 		    phba->sli4_hba.max_cfg_param.max_xri > 512)
9982 			phba->sli4_hba.max_cfg_param.max_xri = 512;
9983 		phba->sli4_hba.max_cfg_param.xri_base =
9984 			bf_get(lpfc_mbx_rd_conf_xri_base, rd_config);
9985 		phba->sli4_hba.max_cfg_param.max_vpi =
9986 			bf_get(lpfc_mbx_rd_conf_vpi_count, rd_config);
9987 		/* Limit the max we support */
9988 		if (phba->sli4_hba.max_cfg_param.max_vpi > LPFC_MAX_VPORTS)
9989 			phba->sli4_hba.max_cfg_param.max_vpi = LPFC_MAX_VPORTS;
9990 		phba->sli4_hba.max_cfg_param.vpi_base =
9991 			bf_get(lpfc_mbx_rd_conf_vpi_base, rd_config);
9992 		phba->sli4_hba.max_cfg_param.max_rpi =
9993 			bf_get(lpfc_mbx_rd_conf_rpi_count, rd_config);
9994 		phba->sli4_hba.max_cfg_param.rpi_base =
9995 			bf_get(lpfc_mbx_rd_conf_rpi_base, rd_config);
9996 		phba->sli4_hba.max_cfg_param.max_vfi =
9997 			bf_get(lpfc_mbx_rd_conf_vfi_count, rd_config);
9998 		phba->sli4_hba.max_cfg_param.vfi_base =
9999 			bf_get(lpfc_mbx_rd_conf_vfi_base, rd_config);
10000 		phba->sli4_hba.max_cfg_param.max_fcfi =
10001 			bf_get(lpfc_mbx_rd_conf_fcfi_count, rd_config);
10002 		phba->sli4_hba.max_cfg_param.max_eq =
10003 			bf_get(lpfc_mbx_rd_conf_eq_count, rd_config);
10004 		phba->sli4_hba.max_cfg_param.max_rq =
10005 			bf_get(lpfc_mbx_rd_conf_rq_count, rd_config);
10006 		phba->sli4_hba.max_cfg_param.max_wq =
10007 			bf_get(lpfc_mbx_rd_conf_wq_count, rd_config);
10008 		phba->sli4_hba.max_cfg_param.max_cq =
10009 			bf_get(lpfc_mbx_rd_conf_cq_count, rd_config);
10010 		phba->lmt = bf_get(lpfc_mbx_rd_conf_lmt, rd_config);
10011 		phba->sli4_hba.next_xri = phba->sli4_hba.max_cfg_param.xri_base;
10012 		phba->vpi_base = phba->sli4_hba.max_cfg_param.vpi_base;
10013 		phba->vfi_base = phba->sli4_hba.max_cfg_param.vfi_base;
10014 		phba->max_vpi = (phba->sli4_hba.max_cfg_param.max_vpi > 0) ?
10015 				(phba->sli4_hba.max_cfg_param.max_vpi - 1) : 0;
10016 		phba->max_vports = phba->max_vpi;
10017 
10018 		/* Next decide on FPIN or Signal E2E CGN support
10019 		 * For congestion alarms and warnings valid combination are:
10020 		 * 1. FPIN alarms / FPIN warnings
10021 		 * 2. Signal alarms / Signal warnings
10022 		 * 3. FPIN alarms / Signal warnings
10023 		 * 4. Signal alarms / FPIN warnings
10024 		 *
10025 		 * Initialize the adapter frequency to 100 mSecs
10026 		 */
10027 		phba->cgn_reg_fpin = LPFC_CGN_FPIN_BOTH;
10028 		phba->cgn_reg_signal = EDC_CG_SIG_NOTSUPPORTED;
10029 		phba->cgn_sig_freq = lpfc_fabric_cgn_frequency;
10030 
10031 		if (lpfc_use_cgn_signal) {
10032 			if (bf_get(lpfc_mbx_rd_conf_wcs, rd_config)) {
10033 				phba->cgn_reg_signal = EDC_CG_SIG_WARN_ONLY;
10034 				phba->cgn_reg_fpin &= ~LPFC_CGN_FPIN_WARN;
10035 			}
10036 			if (bf_get(lpfc_mbx_rd_conf_acs, rd_config)) {
10037 				/* MUST support both alarm and warning
10038 				 * because EDC does not support alarm alone.
10039 				 */
10040 				if (phba->cgn_reg_signal !=
10041 				    EDC_CG_SIG_WARN_ONLY) {
10042 					/* Must support both or none */
10043 					phba->cgn_reg_fpin = LPFC_CGN_FPIN_BOTH;
10044 					phba->cgn_reg_signal =
10045 						EDC_CG_SIG_NOTSUPPORTED;
10046 				} else {
10047 					phba->cgn_reg_signal =
10048 						EDC_CG_SIG_WARN_ALARM;
10049 					phba->cgn_reg_fpin =
10050 						LPFC_CGN_FPIN_NONE;
10051 				}
10052 			}
10053 		}
10054 
10055 		/* Set the congestion initial signal and fpin values. */
10056 		phba->cgn_init_reg_fpin = phba->cgn_reg_fpin;
10057 		phba->cgn_init_reg_signal = phba->cgn_reg_signal;
10058 
10059 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
10060 				"6446 READ_CONFIG reg_sig x%x reg_fpin:x%x\n",
10061 				phba->cgn_reg_signal, phba->cgn_reg_fpin);
10062 
10063 		lpfc_map_topology(phba, rd_config);
10064 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10065 				"2003 cfg params Extents? %d "
10066 				"XRI(B:%d M:%d), "
10067 				"VPI(B:%d M:%d) "
10068 				"VFI(B:%d M:%d) "
10069 				"RPI(B:%d M:%d) "
10070 				"FCFI:%d EQ:%d CQ:%d WQ:%d RQ:%d lmt:x%x\n",
10071 				phba->sli4_hba.extents_in_use,
10072 				phba->sli4_hba.max_cfg_param.xri_base,
10073 				phba->sli4_hba.max_cfg_param.max_xri,
10074 				phba->sli4_hba.max_cfg_param.vpi_base,
10075 				phba->sli4_hba.max_cfg_param.max_vpi,
10076 				phba->sli4_hba.max_cfg_param.vfi_base,
10077 				phba->sli4_hba.max_cfg_param.max_vfi,
10078 				phba->sli4_hba.max_cfg_param.rpi_base,
10079 				phba->sli4_hba.max_cfg_param.max_rpi,
10080 				phba->sli4_hba.max_cfg_param.max_fcfi,
10081 				phba->sli4_hba.max_cfg_param.max_eq,
10082 				phba->sli4_hba.max_cfg_param.max_cq,
10083 				phba->sli4_hba.max_cfg_param.max_wq,
10084 				phba->sli4_hba.max_cfg_param.max_rq,
10085 				phba->lmt);
10086 
10087 		/*
10088 		 * Calculate queue resources based on how
10089 		 * many WQ/CQ/EQs are available.
10090 		 */
10091 		qmin = phba->sli4_hba.max_cfg_param.max_wq;
10092 		if (phba->sli4_hba.max_cfg_param.max_cq < qmin)
10093 			qmin = phba->sli4_hba.max_cfg_param.max_cq;
10094 		if (phba->sli4_hba.max_cfg_param.max_eq < qmin)
10095 			qmin = phba->sli4_hba.max_cfg_param.max_eq;
10096 		/*
10097 		 * Whats left after this can go toward NVME / FCP.
10098 		 * The minus 4 accounts for ELS, NVME LS, MBOX
10099 		 * plus one extra. When configured for
10100 		 * NVMET, FCP io channel WQs are not created.
10101 		 */
10102 		qmin -= 4;
10103 
10104 		/* Check to see if there is enough for NVME */
10105 		if ((phba->cfg_irq_chann > qmin) ||
10106 		    (phba->cfg_hdw_queue > qmin)) {
10107 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10108 					"2005 Reducing Queues - "
10109 					"FW resource limitation: "
10110 					"WQ %d CQ %d EQ %d: min %d: "
10111 					"IRQ %d HDWQ %d\n",
10112 					phba->sli4_hba.max_cfg_param.max_wq,
10113 					phba->sli4_hba.max_cfg_param.max_cq,
10114 					phba->sli4_hba.max_cfg_param.max_eq,
10115 					qmin, phba->cfg_irq_chann,
10116 					phba->cfg_hdw_queue);
10117 
10118 			if (phba->cfg_irq_chann > qmin)
10119 				phba->cfg_irq_chann = qmin;
10120 			if (phba->cfg_hdw_queue > qmin)
10121 				phba->cfg_hdw_queue = qmin;
10122 		}
10123 	}
10124 
10125 	if (rc)
10126 		goto read_cfg_out;
10127 
10128 	/* Update link speed if forced link speed is supported */
10129 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
10130 	if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
10131 		forced_link_speed =
10132 			bf_get(lpfc_mbx_rd_conf_link_speed, rd_config);
10133 		if (forced_link_speed) {
10134 			phba->hba_flag |= HBA_FORCED_LINK_SPEED;
10135 
10136 			switch (forced_link_speed) {
10137 			case LINK_SPEED_1G:
10138 				phba->cfg_link_speed =
10139 					LPFC_USER_LINK_SPEED_1G;
10140 				break;
10141 			case LINK_SPEED_2G:
10142 				phba->cfg_link_speed =
10143 					LPFC_USER_LINK_SPEED_2G;
10144 				break;
10145 			case LINK_SPEED_4G:
10146 				phba->cfg_link_speed =
10147 					LPFC_USER_LINK_SPEED_4G;
10148 				break;
10149 			case LINK_SPEED_8G:
10150 				phba->cfg_link_speed =
10151 					LPFC_USER_LINK_SPEED_8G;
10152 				break;
10153 			case LINK_SPEED_10G:
10154 				phba->cfg_link_speed =
10155 					LPFC_USER_LINK_SPEED_10G;
10156 				break;
10157 			case LINK_SPEED_16G:
10158 				phba->cfg_link_speed =
10159 					LPFC_USER_LINK_SPEED_16G;
10160 				break;
10161 			case LINK_SPEED_32G:
10162 				phba->cfg_link_speed =
10163 					LPFC_USER_LINK_SPEED_32G;
10164 				break;
10165 			case LINK_SPEED_64G:
10166 				phba->cfg_link_speed =
10167 					LPFC_USER_LINK_SPEED_64G;
10168 				break;
10169 			case 0xffff:
10170 				phba->cfg_link_speed =
10171 					LPFC_USER_LINK_SPEED_AUTO;
10172 				break;
10173 			default:
10174 				lpfc_printf_log(phba, KERN_ERR,
10175 						LOG_TRACE_EVENT,
10176 						"0047 Unrecognized link "
10177 						"speed : %d\n",
10178 						forced_link_speed);
10179 				phba->cfg_link_speed =
10180 					LPFC_USER_LINK_SPEED_AUTO;
10181 			}
10182 		}
10183 	}
10184 
10185 	/* Reset the DFT_HBA_Q_DEPTH to the max xri  */
10186 	length = phba->sli4_hba.max_cfg_param.max_xri -
10187 			lpfc_sli4_get_els_iocb_cnt(phba);
10188 	if (phba->cfg_hba_queue_depth > length) {
10189 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
10190 				"3361 HBA queue depth changed from %d to %d\n",
10191 				phba->cfg_hba_queue_depth, length);
10192 		phba->cfg_hba_queue_depth = length;
10193 	}
10194 
10195 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) <
10196 	    LPFC_SLI_INTF_IF_TYPE_2)
10197 		goto read_cfg_out;
10198 
10199 	/* get the pf# and vf# for SLI4 if_type 2 port */
10200 	length = (sizeof(struct lpfc_mbx_get_func_cfg) -
10201 		  sizeof(struct lpfc_sli4_cfg_mhdr));
10202 	lpfc_sli4_config(phba, pmb, LPFC_MBOX_SUBSYSTEM_COMMON,
10203 			 LPFC_MBOX_OPCODE_GET_FUNCTION_CONFIG,
10204 			 length, LPFC_SLI4_MBX_EMBED);
10205 
10206 	rc2 = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
10207 	shdr = (union lpfc_sli4_cfg_shdr *)
10208 				&pmb->u.mqe.un.sli4_config.header.cfg_shdr;
10209 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
10210 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
10211 	if (rc2 || shdr_status || shdr_add_status) {
10212 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10213 				"3026 Mailbox failed , mbxCmd x%x "
10214 				"GET_FUNCTION_CONFIG, mbxStatus x%x\n",
10215 				bf_get(lpfc_mqe_command, &pmb->u.mqe),
10216 				bf_get(lpfc_mqe_status, &pmb->u.mqe));
10217 		goto read_cfg_out;
10218 	}
10219 
10220 	/* search for fc_fcoe resrouce descriptor */
10221 	get_func_cfg = &pmb->u.mqe.un.get_func_cfg;
10222 
10223 	pdesc_0 = (char *)&get_func_cfg->func_cfg.desc[0];
10224 	desc = (struct lpfc_rsrc_desc_fcfcoe *)pdesc_0;
10225 	length = bf_get(lpfc_rsrc_desc_fcfcoe_length, desc);
10226 	if (length == LPFC_RSRC_DESC_TYPE_FCFCOE_V0_RSVD)
10227 		length = LPFC_RSRC_DESC_TYPE_FCFCOE_V0_LENGTH;
10228 	else if (length != LPFC_RSRC_DESC_TYPE_FCFCOE_V1_LENGTH)
10229 		goto read_cfg_out;
10230 
10231 	for (i = 0; i < LPFC_RSRC_DESC_MAX_NUM; i++) {
10232 		desc = (struct lpfc_rsrc_desc_fcfcoe *)(pdesc_0 + length * i);
10233 		if (LPFC_RSRC_DESC_TYPE_FCFCOE ==
10234 		    bf_get(lpfc_rsrc_desc_fcfcoe_type, desc)) {
10235 			phba->sli4_hba.iov.pf_number =
10236 				bf_get(lpfc_rsrc_desc_fcfcoe_pfnum, desc);
10237 			phba->sli4_hba.iov.vf_number =
10238 				bf_get(lpfc_rsrc_desc_fcfcoe_vfnum, desc);
10239 			break;
10240 		}
10241 	}
10242 
10243 	if (i < LPFC_RSRC_DESC_MAX_NUM)
10244 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10245 				"3027 GET_FUNCTION_CONFIG: pf_number:%d, "
10246 				"vf_number:%d\n", phba->sli4_hba.iov.pf_number,
10247 				phba->sli4_hba.iov.vf_number);
10248 	else
10249 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10250 				"3028 GET_FUNCTION_CONFIG: failed to find "
10251 				"Resource Descriptor:x%x\n",
10252 				LPFC_RSRC_DESC_TYPE_FCFCOE);
10253 
10254 read_cfg_out:
10255 	mempool_free(pmb, phba->mbox_mem_pool);
10256 	return rc;
10257 }
10258 
10259 /**
10260  * lpfc_setup_endian_order - Write endian order to an SLI4 if_type 0 port.
10261  * @phba: pointer to lpfc hba data structure.
10262  *
10263  * This routine is invoked to setup the port-side endian order when
10264  * the port if_type is 0.  This routine has no function for other
10265  * if_types.
10266  *
10267  * Return codes
10268  * 	0 - successful
10269  * 	-ENOMEM - No available memory
10270  *      -EIO - The mailbox failed to complete successfully.
10271  **/
10272 static int
10273 lpfc_setup_endian_order(struct lpfc_hba *phba)
10274 {
10275 	LPFC_MBOXQ_t *mboxq;
10276 	uint32_t if_type, rc = 0;
10277 	uint32_t endian_mb_data[2] = {HOST_ENDIAN_LOW_WORD0,
10278 				      HOST_ENDIAN_HIGH_WORD1};
10279 
10280 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
10281 	switch (if_type) {
10282 	case LPFC_SLI_INTF_IF_TYPE_0:
10283 		mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
10284 						       GFP_KERNEL);
10285 		if (!mboxq) {
10286 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10287 					"0492 Unable to allocate memory for "
10288 					"issuing SLI_CONFIG_SPECIAL mailbox "
10289 					"command\n");
10290 			return -ENOMEM;
10291 		}
10292 
10293 		/*
10294 		 * The SLI4_CONFIG_SPECIAL mailbox command requires the first
10295 		 * two words to contain special data values and no other data.
10296 		 */
10297 		memset(mboxq, 0, sizeof(LPFC_MBOXQ_t));
10298 		memcpy(&mboxq->u.mqe, &endian_mb_data, sizeof(endian_mb_data));
10299 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
10300 		if (rc != MBX_SUCCESS) {
10301 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10302 					"0493 SLI_CONFIG_SPECIAL mailbox "
10303 					"failed with status x%x\n",
10304 					rc);
10305 			rc = -EIO;
10306 		}
10307 		mempool_free(mboxq, phba->mbox_mem_pool);
10308 		break;
10309 	case LPFC_SLI_INTF_IF_TYPE_6:
10310 	case LPFC_SLI_INTF_IF_TYPE_2:
10311 	case LPFC_SLI_INTF_IF_TYPE_1:
10312 	default:
10313 		break;
10314 	}
10315 	return rc;
10316 }
10317 
10318 /**
10319  * lpfc_sli4_queue_verify - Verify and update EQ counts
10320  * @phba: pointer to lpfc hba data structure.
10321  *
10322  * This routine is invoked to check the user settable queue counts for EQs.
10323  * After this routine is called the counts will be set to valid values that
10324  * adhere to the constraints of the system's interrupt vectors and the port's
10325  * queue resources.
10326  *
10327  * Return codes
10328  *      0 - successful
10329  *      -ENOMEM - No available memory
10330  **/
10331 static int
10332 lpfc_sli4_queue_verify(struct lpfc_hba *phba)
10333 {
10334 	/*
10335 	 * Sanity check for configured queue parameters against the run-time
10336 	 * device parameters
10337 	 */
10338 
10339 	if (phba->nvmet_support) {
10340 		if (phba->cfg_hdw_queue < phba->cfg_nvmet_mrq)
10341 			phba->cfg_nvmet_mrq = phba->cfg_hdw_queue;
10342 		if (phba->cfg_nvmet_mrq > LPFC_NVMET_MRQ_MAX)
10343 			phba->cfg_nvmet_mrq = LPFC_NVMET_MRQ_MAX;
10344 	}
10345 
10346 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10347 			"2574 IO channels: hdwQ %d IRQ %d MRQ: %d\n",
10348 			phba->cfg_hdw_queue, phba->cfg_irq_chann,
10349 			phba->cfg_nvmet_mrq);
10350 
10351 	/* Get EQ depth from module parameter, fake the default for now */
10352 	phba->sli4_hba.eq_esize = LPFC_EQE_SIZE_4B;
10353 	phba->sli4_hba.eq_ecount = LPFC_EQE_DEF_COUNT;
10354 
10355 	/* Get CQ depth from module parameter, fake the default for now */
10356 	phba->sli4_hba.cq_esize = LPFC_CQE_SIZE;
10357 	phba->sli4_hba.cq_ecount = LPFC_CQE_DEF_COUNT;
10358 	return 0;
10359 }
10360 
10361 static int
10362 lpfc_alloc_io_wq_cq(struct lpfc_hba *phba, int idx)
10363 {
10364 	struct lpfc_queue *qdesc;
10365 	u32 wqesize;
10366 	int cpu;
10367 
10368 	cpu = lpfc_find_cpu_handle(phba, idx, LPFC_FIND_BY_HDWQ);
10369 	/* Create Fast Path IO CQs */
10370 	if (phba->enab_exp_wqcq_pages)
10371 		/* Increase the CQ size when WQEs contain an embedded cdb */
10372 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_EXPANDED_PAGE_SIZE,
10373 					      phba->sli4_hba.cq_esize,
10374 					      LPFC_CQE_EXP_COUNT, cpu);
10375 
10376 	else
10377 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10378 					      phba->sli4_hba.cq_esize,
10379 					      phba->sli4_hba.cq_ecount, cpu);
10380 	if (!qdesc) {
10381 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10382 				"0499 Failed allocate fast-path IO CQ (%d)\n",
10383 				idx);
10384 		return 1;
10385 	}
10386 	qdesc->qe_valid = 1;
10387 	qdesc->hdwq = idx;
10388 	qdesc->chann = cpu;
10389 	phba->sli4_hba.hdwq[idx].io_cq = qdesc;
10390 
10391 	/* Create Fast Path IO WQs */
10392 	if (phba->enab_exp_wqcq_pages) {
10393 		/* Increase the WQ size when WQEs contain an embedded cdb */
10394 		wqesize = (phba->fcp_embed_io) ?
10395 			LPFC_WQE128_SIZE : phba->sli4_hba.wq_esize;
10396 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_EXPANDED_PAGE_SIZE,
10397 					      wqesize,
10398 					      LPFC_WQE_EXP_COUNT, cpu);
10399 	} else
10400 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10401 					      phba->sli4_hba.wq_esize,
10402 					      phba->sli4_hba.wq_ecount, cpu);
10403 
10404 	if (!qdesc) {
10405 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10406 				"0503 Failed allocate fast-path IO WQ (%d)\n",
10407 				idx);
10408 		return 1;
10409 	}
10410 	qdesc->hdwq = idx;
10411 	qdesc->chann = cpu;
10412 	phba->sli4_hba.hdwq[idx].io_wq = qdesc;
10413 	list_add_tail(&qdesc->wq_list, &phba->sli4_hba.lpfc_wq_list);
10414 	return 0;
10415 }
10416 
10417 /**
10418  * lpfc_sli4_queue_create - Create all the SLI4 queues
10419  * @phba: pointer to lpfc hba data structure.
10420  *
10421  * This routine is invoked to allocate all the SLI4 queues for the FCoE HBA
10422  * operation. For each SLI4 queue type, the parameters such as queue entry
10423  * count (queue depth) shall be taken from the module parameter. For now,
10424  * we just use some constant number as place holder.
10425  *
10426  * Return codes
10427  *      0 - successful
10428  *      -ENOMEM - No availble memory
10429  *      -EIO - The mailbox failed to complete successfully.
10430  **/
10431 int
10432 lpfc_sli4_queue_create(struct lpfc_hba *phba)
10433 {
10434 	struct lpfc_queue *qdesc;
10435 	int idx, cpu, eqcpu;
10436 	struct lpfc_sli4_hdw_queue *qp;
10437 	struct lpfc_vector_map_info *cpup;
10438 	struct lpfc_vector_map_info *eqcpup;
10439 	struct lpfc_eq_intr_info *eqi;
10440 
10441 	/*
10442 	 * Create HBA Record arrays.
10443 	 * Both NVME and FCP will share that same vectors / EQs
10444 	 */
10445 	phba->sli4_hba.mq_esize = LPFC_MQE_SIZE;
10446 	phba->sli4_hba.mq_ecount = LPFC_MQE_DEF_COUNT;
10447 	phba->sli4_hba.wq_esize = LPFC_WQE_SIZE;
10448 	phba->sli4_hba.wq_ecount = LPFC_WQE_DEF_COUNT;
10449 	phba->sli4_hba.rq_esize = LPFC_RQE_SIZE;
10450 	phba->sli4_hba.rq_ecount = LPFC_RQE_DEF_COUNT;
10451 	phba->sli4_hba.eq_esize = LPFC_EQE_SIZE_4B;
10452 	phba->sli4_hba.eq_ecount = LPFC_EQE_DEF_COUNT;
10453 	phba->sli4_hba.cq_esize = LPFC_CQE_SIZE;
10454 	phba->sli4_hba.cq_ecount = LPFC_CQE_DEF_COUNT;
10455 
10456 	if (!phba->sli4_hba.hdwq) {
10457 		phba->sli4_hba.hdwq = kcalloc(
10458 			phba->cfg_hdw_queue, sizeof(struct lpfc_sli4_hdw_queue),
10459 			GFP_KERNEL);
10460 		if (!phba->sli4_hba.hdwq) {
10461 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10462 					"6427 Failed allocate memory for "
10463 					"fast-path Hardware Queue array\n");
10464 			goto out_error;
10465 		}
10466 		/* Prepare hardware queues to take IO buffers */
10467 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10468 			qp = &phba->sli4_hba.hdwq[idx];
10469 			spin_lock_init(&qp->io_buf_list_get_lock);
10470 			spin_lock_init(&qp->io_buf_list_put_lock);
10471 			INIT_LIST_HEAD(&qp->lpfc_io_buf_list_get);
10472 			INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
10473 			qp->get_io_bufs = 0;
10474 			qp->put_io_bufs = 0;
10475 			qp->total_io_bufs = 0;
10476 			spin_lock_init(&qp->abts_io_buf_list_lock);
10477 			INIT_LIST_HEAD(&qp->lpfc_abts_io_buf_list);
10478 			qp->abts_scsi_io_bufs = 0;
10479 			qp->abts_nvme_io_bufs = 0;
10480 			INIT_LIST_HEAD(&qp->sgl_list);
10481 			INIT_LIST_HEAD(&qp->cmd_rsp_buf_list);
10482 			spin_lock_init(&qp->hdwq_lock);
10483 		}
10484 	}
10485 
10486 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
10487 		if (phba->nvmet_support) {
10488 			phba->sli4_hba.nvmet_cqset = kcalloc(
10489 					phba->cfg_nvmet_mrq,
10490 					sizeof(struct lpfc_queue *),
10491 					GFP_KERNEL);
10492 			if (!phba->sli4_hba.nvmet_cqset) {
10493 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10494 					"3121 Fail allocate memory for "
10495 					"fast-path CQ set array\n");
10496 				goto out_error;
10497 			}
10498 			phba->sli4_hba.nvmet_mrq_hdr = kcalloc(
10499 					phba->cfg_nvmet_mrq,
10500 					sizeof(struct lpfc_queue *),
10501 					GFP_KERNEL);
10502 			if (!phba->sli4_hba.nvmet_mrq_hdr) {
10503 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10504 					"3122 Fail allocate memory for "
10505 					"fast-path RQ set hdr array\n");
10506 				goto out_error;
10507 			}
10508 			phba->sli4_hba.nvmet_mrq_data = kcalloc(
10509 					phba->cfg_nvmet_mrq,
10510 					sizeof(struct lpfc_queue *),
10511 					GFP_KERNEL);
10512 			if (!phba->sli4_hba.nvmet_mrq_data) {
10513 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10514 					"3124 Fail allocate memory for "
10515 					"fast-path RQ set data array\n");
10516 				goto out_error;
10517 			}
10518 		}
10519 	}
10520 
10521 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_wq_list);
10522 
10523 	/* Create HBA Event Queues (EQs) */
10524 	for_each_present_cpu(cpu) {
10525 		/* We only want to create 1 EQ per vector, even though
10526 		 * multiple CPUs might be using that vector. so only
10527 		 * selects the CPUs that are LPFC_CPU_FIRST_IRQ.
10528 		 */
10529 		cpup = &phba->sli4_hba.cpu_map[cpu];
10530 		if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
10531 			continue;
10532 
10533 		/* Get a ptr to the Hardware Queue associated with this CPU */
10534 		qp = &phba->sli4_hba.hdwq[cpup->hdwq];
10535 
10536 		/* Allocate an EQ */
10537 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10538 					      phba->sli4_hba.eq_esize,
10539 					      phba->sli4_hba.eq_ecount, cpu);
10540 		if (!qdesc) {
10541 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10542 					"0497 Failed allocate EQ (%d)\n",
10543 					cpup->hdwq);
10544 			goto out_error;
10545 		}
10546 		qdesc->qe_valid = 1;
10547 		qdesc->hdwq = cpup->hdwq;
10548 		qdesc->chann = cpu; /* First CPU this EQ is affinitized to */
10549 		qdesc->last_cpu = qdesc->chann;
10550 
10551 		/* Save the allocated EQ in the Hardware Queue */
10552 		qp->hba_eq = qdesc;
10553 
10554 		eqi = per_cpu_ptr(phba->sli4_hba.eq_info, qdesc->last_cpu);
10555 		list_add(&qdesc->cpu_list, &eqi->list);
10556 	}
10557 
10558 	/* Now we need to populate the other Hardware Queues, that share
10559 	 * an IRQ vector, with the associated EQ ptr.
10560 	 */
10561 	for_each_present_cpu(cpu) {
10562 		cpup = &phba->sli4_hba.cpu_map[cpu];
10563 
10564 		/* Check for EQ already allocated in previous loop */
10565 		if (cpup->flag & LPFC_CPU_FIRST_IRQ)
10566 			continue;
10567 
10568 		/* Check for multiple CPUs per hdwq */
10569 		qp = &phba->sli4_hba.hdwq[cpup->hdwq];
10570 		if (qp->hba_eq)
10571 			continue;
10572 
10573 		/* We need to share an EQ for this hdwq */
10574 		eqcpu = lpfc_find_cpu_handle(phba, cpup->eq, LPFC_FIND_BY_EQ);
10575 		eqcpup = &phba->sli4_hba.cpu_map[eqcpu];
10576 		qp->hba_eq = phba->sli4_hba.hdwq[eqcpup->hdwq].hba_eq;
10577 	}
10578 
10579 	/* Allocate IO Path SLI4 CQ/WQs */
10580 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10581 		if (lpfc_alloc_io_wq_cq(phba, idx))
10582 			goto out_error;
10583 	}
10584 
10585 	if (phba->nvmet_support) {
10586 		for (idx = 0; idx < phba->cfg_nvmet_mrq; idx++) {
10587 			cpu = lpfc_find_cpu_handle(phba, idx,
10588 						   LPFC_FIND_BY_HDWQ);
10589 			qdesc = lpfc_sli4_queue_alloc(phba,
10590 						      LPFC_DEFAULT_PAGE_SIZE,
10591 						      phba->sli4_hba.cq_esize,
10592 						      phba->sli4_hba.cq_ecount,
10593 						      cpu);
10594 			if (!qdesc) {
10595 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10596 						"3142 Failed allocate NVME "
10597 						"CQ Set (%d)\n", idx);
10598 				goto out_error;
10599 			}
10600 			qdesc->qe_valid = 1;
10601 			qdesc->hdwq = idx;
10602 			qdesc->chann = cpu;
10603 			phba->sli4_hba.nvmet_cqset[idx] = qdesc;
10604 		}
10605 	}
10606 
10607 	/*
10608 	 * Create Slow Path Completion Queues (CQs)
10609 	 */
10610 
10611 	cpu = lpfc_find_cpu_handle(phba, 0, LPFC_FIND_BY_EQ);
10612 	/* Create slow-path Mailbox Command Complete Queue */
10613 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10614 				      phba->sli4_hba.cq_esize,
10615 				      phba->sli4_hba.cq_ecount, cpu);
10616 	if (!qdesc) {
10617 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10618 				"0500 Failed allocate slow-path mailbox CQ\n");
10619 		goto out_error;
10620 	}
10621 	qdesc->qe_valid = 1;
10622 	phba->sli4_hba.mbx_cq = qdesc;
10623 
10624 	/* Create slow-path ELS Complete Queue */
10625 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10626 				      phba->sli4_hba.cq_esize,
10627 				      phba->sli4_hba.cq_ecount, cpu);
10628 	if (!qdesc) {
10629 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10630 				"0501 Failed allocate slow-path ELS CQ\n");
10631 		goto out_error;
10632 	}
10633 	qdesc->qe_valid = 1;
10634 	qdesc->chann = cpu;
10635 	phba->sli4_hba.els_cq = qdesc;
10636 
10637 
10638 	/*
10639 	 * Create Slow Path Work Queues (WQs)
10640 	 */
10641 
10642 	/* Create Mailbox Command Queue */
10643 
10644 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10645 				      phba->sli4_hba.mq_esize,
10646 				      phba->sli4_hba.mq_ecount, cpu);
10647 	if (!qdesc) {
10648 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10649 				"0505 Failed allocate slow-path MQ\n");
10650 		goto out_error;
10651 	}
10652 	qdesc->chann = cpu;
10653 	phba->sli4_hba.mbx_wq = qdesc;
10654 
10655 	/*
10656 	 * Create ELS Work Queues
10657 	 */
10658 
10659 	/* Create slow-path ELS Work Queue */
10660 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10661 				      phba->sli4_hba.wq_esize,
10662 				      phba->sli4_hba.wq_ecount, cpu);
10663 	if (!qdesc) {
10664 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10665 				"0504 Failed allocate slow-path ELS WQ\n");
10666 		goto out_error;
10667 	}
10668 	qdesc->chann = cpu;
10669 	phba->sli4_hba.els_wq = qdesc;
10670 	list_add_tail(&qdesc->wq_list, &phba->sli4_hba.lpfc_wq_list);
10671 
10672 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
10673 		/* Create NVME LS Complete Queue */
10674 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10675 					      phba->sli4_hba.cq_esize,
10676 					      phba->sli4_hba.cq_ecount, cpu);
10677 		if (!qdesc) {
10678 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10679 					"6079 Failed allocate NVME LS CQ\n");
10680 			goto out_error;
10681 		}
10682 		qdesc->chann = cpu;
10683 		qdesc->qe_valid = 1;
10684 		phba->sli4_hba.nvmels_cq = qdesc;
10685 
10686 		/* Create NVME LS Work Queue */
10687 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10688 					      phba->sli4_hba.wq_esize,
10689 					      phba->sli4_hba.wq_ecount, cpu);
10690 		if (!qdesc) {
10691 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10692 					"6080 Failed allocate NVME LS WQ\n");
10693 			goto out_error;
10694 		}
10695 		qdesc->chann = cpu;
10696 		phba->sli4_hba.nvmels_wq = qdesc;
10697 		list_add_tail(&qdesc->wq_list, &phba->sli4_hba.lpfc_wq_list);
10698 	}
10699 
10700 	/*
10701 	 * Create Receive Queue (RQ)
10702 	 */
10703 
10704 	/* Create Receive Queue for header */
10705 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10706 				      phba->sli4_hba.rq_esize,
10707 				      phba->sli4_hba.rq_ecount, cpu);
10708 	if (!qdesc) {
10709 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10710 				"0506 Failed allocate receive HRQ\n");
10711 		goto out_error;
10712 	}
10713 	phba->sli4_hba.hdr_rq = qdesc;
10714 
10715 	/* Create Receive Queue for data */
10716 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10717 				      phba->sli4_hba.rq_esize,
10718 				      phba->sli4_hba.rq_ecount, cpu);
10719 	if (!qdesc) {
10720 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10721 				"0507 Failed allocate receive DRQ\n");
10722 		goto out_error;
10723 	}
10724 	phba->sli4_hba.dat_rq = qdesc;
10725 
10726 	if ((phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) &&
10727 	    phba->nvmet_support) {
10728 		for (idx = 0; idx < phba->cfg_nvmet_mrq; idx++) {
10729 			cpu = lpfc_find_cpu_handle(phba, idx,
10730 						   LPFC_FIND_BY_HDWQ);
10731 			/* Create NVMET Receive Queue for header */
10732 			qdesc = lpfc_sli4_queue_alloc(phba,
10733 						      LPFC_DEFAULT_PAGE_SIZE,
10734 						      phba->sli4_hba.rq_esize,
10735 						      LPFC_NVMET_RQE_DEF_COUNT,
10736 						      cpu);
10737 			if (!qdesc) {
10738 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10739 						"3146 Failed allocate "
10740 						"receive HRQ\n");
10741 				goto out_error;
10742 			}
10743 			qdesc->hdwq = idx;
10744 			phba->sli4_hba.nvmet_mrq_hdr[idx] = qdesc;
10745 
10746 			/* Only needed for header of RQ pair */
10747 			qdesc->rqbp = kzalloc_node(sizeof(*qdesc->rqbp),
10748 						   GFP_KERNEL,
10749 						   cpu_to_node(cpu));
10750 			if (qdesc->rqbp == NULL) {
10751 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10752 						"6131 Failed allocate "
10753 						"Header RQBP\n");
10754 				goto out_error;
10755 			}
10756 
10757 			/* Put list in known state in case driver load fails. */
10758 			INIT_LIST_HEAD(&qdesc->rqbp->rqb_buffer_list);
10759 
10760 			/* Create NVMET Receive Queue for data */
10761 			qdesc = lpfc_sli4_queue_alloc(phba,
10762 						      LPFC_DEFAULT_PAGE_SIZE,
10763 						      phba->sli4_hba.rq_esize,
10764 						      LPFC_NVMET_RQE_DEF_COUNT,
10765 						      cpu);
10766 			if (!qdesc) {
10767 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10768 						"3156 Failed allocate "
10769 						"receive DRQ\n");
10770 				goto out_error;
10771 			}
10772 			qdesc->hdwq = idx;
10773 			phba->sli4_hba.nvmet_mrq_data[idx] = qdesc;
10774 		}
10775 	}
10776 
10777 	/* Clear NVME stats */
10778 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
10779 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10780 			memset(&phba->sli4_hba.hdwq[idx].nvme_cstat, 0,
10781 			       sizeof(phba->sli4_hba.hdwq[idx].nvme_cstat));
10782 		}
10783 	}
10784 
10785 	/* Clear SCSI stats */
10786 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP) {
10787 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10788 			memset(&phba->sli4_hba.hdwq[idx].scsi_cstat, 0,
10789 			       sizeof(phba->sli4_hba.hdwq[idx].scsi_cstat));
10790 		}
10791 	}
10792 
10793 	return 0;
10794 
10795 out_error:
10796 	lpfc_sli4_queue_destroy(phba);
10797 	return -ENOMEM;
10798 }
10799 
10800 static inline void
10801 __lpfc_sli4_release_queue(struct lpfc_queue **qp)
10802 {
10803 	if (*qp != NULL) {
10804 		lpfc_sli4_queue_free(*qp);
10805 		*qp = NULL;
10806 	}
10807 }
10808 
10809 static inline void
10810 lpfc_sli4_release_queues(struct lpfc_queue ***qs, int max)
10811 {
10812 	int idx;
10813 
10814 	if (*qs == NULL)
10815 		return;
10816 
10817 	for (idx = 0; idx < max; idx++)
10818 		__lpfc_sli4_release_queue(&(*qs)[idx]);
10819 
10820 	kfree(*qs);
10821 	*qs = NULL;
10822 }
10823 
10824 static inline void
10825 lpfc_sli4_release_hdwq(struct lpfc_hba *phba)
10826 {
10827 	struct lpfc_sli4_hdw_queue *hdwq;
10828 	struct lpfc_queue *eq;
10829 	uint32_t idx;
10830 
10831 	hdwq = phba->sli4_hba.hdwq;
10832 
10833 	/* Loop thru all Hardware Queues */
10834 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10835 		/* Free the CQ/WQ corresponding to the Hardware Queue */
10836 		lpfc_sli4_queue_free(hdwq[idx].io_cq);
10837 		lpfc_sli4_queue_free(hdwq[idx].io_wq);
10838 		hdwq[idx].hba_eq = NULL;
10839 		hdwq[idx].io_cq = NULL;
10840 		hdwq[idx].io_wq = NULL;
10841 		if (phba->cfg_xpsgl && !phba->nvmet_support)
10842 			lpfc_free_sgl_per_hdwq(phba, &hdwq[idx]);
10843 		lpfc_free_cmd_rsp_buf_per_hdwq(phba, &hdwq[idx]);
10844 	}
10845 	/* Loop thru all IRQ vectors */
10846 	for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
10847 		/* Free the EQ corresponding to the IRQ vector */
10848 		eq = phba->sli4_hba.hba_eq_hdl[idx].eq;
10849 		lpfc_sli4_queue_free(eq);
10850 		phba->sli4_hba.hba_eq_hdl[idx].eq = NULL;
10851 	}
10852 }
10853 
10854 /**
10855  * lpfc_sli4_queue_destroy - Destroy all the SLI4 queues
10856  * @phba: pointer to lpfc hba data structure.
10857  *
10858  * This routine is invoked to release all the SLI4 queues with the FCoE HBA
10859  * operation.
10860  *
10861  * Return codes
10862  *      0 - successful
10863  *      -ENOMEM - No available memory
10864  *      -EIO - The mailbox failed to complete successfully.
10865  **/
10866 void
10867 lpfc_sli4_queue_destroy(struct lpfc_hba *phba)
10868 {
10869 	/*
10870 	 * Set FREE_INIT before beginning to free the queues.
10871 	 * Wait until the users of queues to acknowledge to
10872 	 * release queues by clearing FREE_WAIT.
10873 	 */
10874 	spin_lock_irq(&phba->hbalock);
10875 	phba->sli.sli_flag |= LPFC_QUEUE_FREE_INIT;
10876 	while (phba->sli.sli_flag & LPFC_QUEUE_FREE_WAIT) {
10877 		spin_unlock_irq(&phba->hbalock);
10878 		msleep(20);
10879 		spin_lock_irq(&phba->hbalock);
10880 	}
10881 	spin_unlock_irq(&phba->hbalock);
10882 
10883 	lpfc_sli4_cleanup_poll_list(phba);
10884 
10885 	/* Release HBA eqs */
10886 	if (phba->sli4_hba.hdwq)
10887 		lpfc_sli4_release_hdwq(phba);
10888 
10889 	if (phba->nvmet_support) {
10890 		lpfc_sli4_release_queues(&phba->sli4_hba.nvmet_cqset,
10891 					 phba->cfg_nvmet_mrq);
10892 
10893 		lpfc_sli4_release_queues(&phba->sli4_hba.nvmet_mrq_hdr,
10894 					 phba->cfg_nvmet_mrq);
10895 		lpfc_sli4_release_queues(&phba->sli4_hba.nvmet_mrq_data,
10896 					 phba->cfg_nvmet_mrq);
10897 	}
10898 
10899 	/* Release mailbox command work queue */
10900 	__lpfc_sli4_release_queue(&phba->sli4_hba.mbx_wq);
10901 
10902 	/* Release ELS work queue */
10903 	__lpfc_sli4_release_queue(&phba->sli4_hba.els_wq);
10904 
10905 	/* Release ELS work queue */
10906 	__lpfc_sli4_release_queue(&phba->sli4_hba.nvmels_wq);
10907 
10908 	/* Release unsolicited receive queue */
10909 	__lpfc_sli4_release_queue(&phba->sli4_hba.hdr_rq);
10910 	__lpfc_sli4_release_queue(&phba->sli4_hba.dat_rq);
10911 
10912 	/* Release ELS complete queue */
10913 	__lpfc_sli4_release_queue(&phba->sli4_hba.els_cq);
10914 
10915 	/* Release NVME LS complete queue */
10916 	__lpfc_sli4_release_queue(&phba->sli4_hba.nvmels_cq);
10917 
10918 	/* Release mailbox command complete queue */
10919 	__lpfc_sli4_release_queue(&phba->sli4_hba.mbx_cq);
10920 
10921 	/* Everything on this list has been freed */
10922 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_wq_list);
10923 
10924 	/* Done with freeing the queues */
10925 	spin_lock_irq(&phba->hbalock);
10926 	phba->sli.sli_flag &= ~LPFC_QUEUE_FREE_INIT;
10927 	spin_unlock_irq(&phba->hbalock);
10928 }
10929 
10930 int
10931 lpfc_free_rq_buffer(struct lpfc_hba *phba, struct lpfc_queue *rq)
10932 {
10933 	struct lpfc_rqb *rqbp;
10934 	struct lpfc_dmabuf *h_buf;
10935 	struct rqb_dmabuf *rqb_buffer;
10936 
10937 	rqbp = rq->rqbp;
10938 	while (!list_empty(&rqbp->rqb_buffer_list)) {
10939 		list_remove_head(&rqbp->rqb_buffer_list, h_buf,
10940 				 struct lpfc_dmabuf, list);
10941 
10942 		rqb_buffer = container_of(h_buf, struct rqb_dmabuf, hbuf);
10943 		(rqbp->rqb_free_buffer)(phba, rqb_buffer);
10944 		rqbp->buffer_count--;
10945 	}
10946 	return 1;
10947 }
10948 
10949 static int
10950 lpfc_create_wq_cq(struct lpfc_hba *phba, struct lpfc_queue *eq,
10951 	struct lpfc_queue *cq, struct lpfc_queue *wq, uint16_t *cq_map,
10952 	int qidx, uint32_t qtype)
10953 {
10954 	struct lpfc_sli_ring *pring;
10955 	int rc;
10956 
10957 	if (!eq || !cq || !wq) {
10958 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10959 			"6085 Fast-path %s (%d) not allocated\n",
10960 			((eq) ? ((cq) ? "WQ" : "CQ") : "EQ"), qidx);
10961 		return -ENOMEM;
10962 	}
10963 
10964 	/* create the Cq first */
10965 	rc = lpfc_cq_create(phba, cq, eq,
10966 			(qtype == LPFC_MBOX) ? LPFC_MCQ : LPFC_WCQ, qtype);
10967 	if (rc) {
10968 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10969 				"6086 Failed setup of CQ (%d), rc = 0x%x\n",
10970 				qidx, (uint32_t)rc);
10971 		return rc;
10972 	}
10973 
10974 	if (qtype != LPFC_MBOX) {
10975 		/* Setup cq_map for fast lookup */
10976 		if (cq_map)
10977 			*cq_map = cq->queue_id;
10978 
10979 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
10980 			"6087 CQ setup: cq[%d]-id=%d, parent eq[%d]-id=%d\n",
10981 			qidx, cq->queue_id, qidx, eq->queue_id);
10982 
10983 		/* create the wq */
10984 		rc = lpfc_wq_create(phba, wq, cq, qtype);
10985 		if (rc) {
10986 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10987 				"4618 Fail setup fastpath WQ (%d), rc = 0x%x\n",
10988 				qidx, (uint32_t)rc);
10989 			/* no need to tear down cq - caller will do so */
10990 			return rc;
10991 		}
10992 
10993 		/* Bind this CQ/WQ to the NVME ring */
10994 		pring = wq->pring;
10995 		pring->sli.sli4.wqp = (void *)wq;
10996 		cq->pring = pring;
10997 
10998 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
10999 			"2593 WQ setup: wq[%d]-id=%d assoc=%d, cq[%d]-id=%d\n",
11000 			qidx, wq->queue_id, wq->assoc_qid, qidx, cq->queue_id);
11001 	} else {
11002 		rc = lpfc_mq_create(phba, wq, cq, LPFC_MBOX);
11003 		if (rc) {
11004 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11005 					"0539 Failed setup of slow-path MQ: "
11006 					"rc = 0x%x\n", rc);
11007 			/* no need to tear down cq - caller will do so */
11008 			return rc;
11009 		}
11010 
11011 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11012 			"2589 MBX MQ setup: wq-id=%d, parent cq-id=%d\n",
11013 			phba->sli4_hba.mbx_wq->queue_id,
11014 			phba->sli4_hba.mbx_cq->queue_id);
11015 	}
11016 
11017 	return 0;
11018 }
11019 
11020 /**
11021  * lpfc_setup_cq_lookup - Setup the CQ lookup table
11022  * @phba: pointer to lpfc hba data structure.
11023  *
11024  * This routine will populate the cq_lookup table by all
11025  * available CQ queue_id's.
11026  **/
11027 static void
11028 lpfc_setup_cq_lookup(struct lpfc_hba *phba)
11029 {
11030 	struct lpfc_queue *eq, *childq;
11031 	int qidx;
11032 
11033 	memset(phba->sli4_hba.cq_lookup, 0,
11034 	       (sizeof(struct lpfc_queue *) * (phba->sli4_hba.cq_max + 1)));
11035 	/* Loop thru all IRQ vectors */
11036 	for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
11037 		/* Get the EQ corresponding to the IRQ vector */
11038 		eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
11039 		if (!eq)
11040 			continue;
11041 		/* Loop through all CQs associated with that EQ */
11042 		list_for_each_entry(childq, &eq->child_list, list) {
11043 			if (childq->queue_id > phba->sli4_hba.cq_max)
11044 				continue;
11045 			if (childq->subtype == LPFC_IO)
11046 				phba->sli4_hba.cq_lookup[childq->queue_id] =
11047 					childq;
11048 		}
11049 	}
11050 }
11051 
11052 /**
11053  * lpfc_sli4_queue_setup - Set up all the SLI4 queues
11054  * @phba: pointer to lpfc hba data structure.
11055  *
11056  * This routine is invoked to set up all the SLI4 queues for the FCoE HBA
11057  * operation.
11058  *
11059  * Return codes
11060  *      0 - successful
11061  *      -ENOMEM - No available memory
11062  *      -EIO - The mailbox failed to complete successfully.
11063  **/
11064 int
11065 lpfc_sli4_queue_setup(struct lpfc_hba *phba)
11066 {
11067 	uint32_t shdr_status, shdr_add_status;
11068 	union lpfc_sli4_cfg_shdr *shdr;
11069 	struct lpfc_vector_map_info *cpup;
11070 	struct lpfc_sli4_hdw_queue *qp;
11071 	LPFC_MBOXQ_t *mboxq;
11072 	int qidx, cpu;
11073 	uint32_t length, usdelay;
11074 	int rc = -ENOMEM;
11075 
11076 	/* Check for dual-ULP support */
11077 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
11078 	if (!mboxq) {
11079 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11080 				"3249 Unable to allocate memory for "
11081 				"QUERY_FW_CFG mailbox command\n");
11082 		return -ENOMEM;
11083 	}
11084 	length = (sizeof(struct lpfc_mbx_query_fw_config) -
11085 		  sizeof(struct lpfc_sli4_cfg_mhdr));
11086 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
11087 			 LPFC_MBOX_OPCODE_QUERY_FW_CFG,
11088 			 length, LPFC_SLI4_MBX_EMBED);
11089 
11090 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
11091 
11092 	shdr = (union lpfc_sli4_cfg_shdr *)
11093 			&mboxq->u.mqe.un.sli4_config.header.cfg_shdr;
11094 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
11095 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
11096 	if (shdr_status || shdr_add_status || rc) {
11097 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11098 				"3250 QUERY_FW_CFG mailbox failed with status "
11099 				"x%x add_status x%x, mbx status x%x\n",
11100 				shdr_status, shdr_add_status, rc);
11101 		mempool_free(mboxq, phba->mbox_mem_pool);
11102 		rc = -ENXIO;
11103 		goto out_error;
11104 	}
11105 
11106 	phba->sli4_hba.fw_func_mode =
11107 			mboxq->u.mqe.un.query_fw_cfg.rsp.function_mode;
11108 	phba->sli4_hba.ulp0_mode = mboxq->u.mqe.un.query_fw_cfg.rsp.ulp0_mode;
11109 	phba->sli4_hba.ulp1_mode = mboxq->u.mqe.un.query_fw_cfg.rsp.ulp1_mode;
11110 	phba->sli4_hba.physical_port =
11111 			mboxq->u.mqe.un.query_fw_cfg.rsp.physical_port;
11112 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11113 			"3251 QUERY_FW_CFG: func_mode:x%x, ulp0_mode:x%x, "
11114 			"ulp1_mode:x%x\n", phba->sli4_hba.fw_func_mode,
11115 			phba->sli4_hba.ulp0_mode, phba->sli4_hba.ulp1_mode);
11116 
11117 	mempool_free(mboxq, phba->mbox_mem_pool);
11118 
11119 	/*
11120 	 * Set up HBA Event Queues (EQs)
11121 	 */
11122 	qp = phba->sli4_hba.hdwq;
11123 
11124 	/* Set up HBA event queue */
11125 	if (!qp) {
11126 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11127 				"3147 Fast-path EQs not allocated\n");
11128 		rc = -ENOMEM;
11129 		goto out_error;
11130 	}
11131 
11132 	/* Loop thru all IRQ vectors */
11133 	for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
11134 		/* Create HBA Event Queues (EQs) in order */
11135 		for_each_present_cpu(cpu) {
11136 			cpup = &phba->sli4_hba.cpu_map[cpu];
11137 
11138 			/* Look for the CPU thats using that vector with
11139 			 * LPFC_CPU_FIRST_IRQ set.
11140 			 */
11141 			if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
11142 				continue;
11143 			if (qidx != cpup->eq)
11144 				continue;
11145 
11146 			/* Create an EQ for that vector */
11147 			rc = lpfc_eq_create(phba, qp[cpup->hdwq].hba_eq,
11148 					    phba->cfg_fcp_imax);
11149 			if (rc) {
11150 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11151 						"0523 Failed setup of fast-path"
11152 						" EQ (%d), rc = 0x%x\n",
11153 						cpup->eq, (uint32_t)rc);
11154 				goto out_destroy;
11155 			}
11156 
11157 			/* Save the EQ for that vector in the hba_eq_hdl */
11158 			phba->sli4_hba.hba_eq_hdl[cpup->eq].eq =
11159 				qp[cpup->hdwq].hba_eq;
11160 
11161 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11162 					"2584 HBA EQ setup: queue[%d]-id=%d\n",
11163 					cpup->eq,
11164 					qp[cpup->hdwq].hba_eq->queue_id);
11165 		}
11166 	}
11167 
11168 	/* Loop thru all Hardware Queues */
11169 	for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
11170 		cpu = lpfc_find_cpu_handle(phba, qidx, LPFC_FIND_BY_HDWQ);
11171 		cpup = &phba->sli4_hba.cpu_map[cpu];
11172 
11173 		/* Create the CQ/WQ corresponding to the Hardware Queue */
11174 		rc = lpfc_create_wq_cq(phba,
11175 				       phba->sli4_hba.hdwq[cpup->hdwq].hba_eq,
11176 				       qp[qidx].io_cq,
11177 				       qp[qidx].io_wq,
11178 				       &phba->sli4_hba.hdwq[qidx].io_cq_map,
11179 				       qidx,
11180 				       LPFC_IO);
11181 		if (rc) {
11182 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11183 					"0535 Failed to setup fastpath "
11184 					"IO WQ/CQ (%d), rc = 0x%x\n",
11185 					qidx, (uint32_t)rc);
11186 			goto out_destroy;
11187 		}
11188 	}
11189 
11190 	/*
11191 	 * Set up Slow Path Complete Queues (CQs)
11192 	 */
11193 
11194 	/* Set up slow-path MBOX CQ/MQ */
11195 
11196 	if (!phba->sli4_hba.mbx_cq || !phba->sli4_hba.mbx_wq) {
11197 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11198 				"0528 %s not allocated\n",
11199 				phba->sli4_hba.mbx_cq ?
11200 				"Mailbox WQ" : "Mailbox CQ");
11201 		rc = -ENOMEM;
11202 		goto out_destroy;
11203 	}
11204 
11205 	rc = lpfc_create_wq_cq(phba, qp[0].hba_eq,
11206 			       phba->sli4_hba.mbx_cq,
11207 			       phba->sli4_hba.mbx_wq,
11208 			       NULL, 0, LPFC_MBOX);
11209 	if (rc) {
11210 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11211 			"0529 Failed setup of mailbox WQ/CQ: rc = 0x%x\n",
11212 			(uint32_t)rc);
11213 		goto out_destroy;
11214 	}
11215 	if (phba->nvmet_support) {
11216 		if (!phba->sli4_hba.nvmet_cqset) {
11217 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11218 					"3165 Fast-path NVME CQ Set "
11219 					"array not allocated\n");
11220 			rc = -ENOMEM;
11221 			goto out_destroy;
11222 		}
11223 		if (phba->cfg_nvmet_mrq > 1) {
11224 			rc = lpfc_cq_create_set(phba,
11225 					phba->sli4_hba.nvmet_cqset,
11226 					qp,
11227 					LPFC_WCQ, LPFC_NVMET);
11228 			if (rc) {
11229 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11230 						"3164 Failed setup of NVME CQ "
11231 						"Set, rc = 0x%x\n",
11232 						(uint32_t)rc);
11233 				goto out_destroy;
11234 			}
11235 		} else {
11236 			/* Set up NVMET Receive Complete Queue */
11237 			rc = lpfc_cq_create(phba, phba->sli4_hba.nvmet_cqset[0],
11238 					    qp[0].hba_eq,
11239 					    LPFC_WCQ, LPFC_NVMET);
11240 			if (rc) {
11241 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11242 						"6089 Failed setup NVMET CQ: "
11243 						"rc = 0x%x\n", (uint32_t)rc);
11244 				goto out_destroy;
11245 			}
11246 			phba->sli4_hba.nvmet_cqset[0]->chann = 0;
11247 
11248 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11249 					"6090 NVMET CQ setup: cq-id=%d, "
11250 					"parent eq-id=%d\n",
11251 					phba->sli4_hba.nvmet_cqset[0]->queue_id,
11252 					qp[0].hba_eq->queue_id);
11253 		}
11254 	}
11255 
11256 	/* Set up slow-path ELS WQ/CQ */
11257 	if (!phba->sli4_hba.els_cq || !phba->sli4_hba.els_wq) {
11258 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11259 				"0530 ELS %s not allocated\n",
11260 				phba->sli4_hba.els_cq ? "WQ" : "CQ");
11261 		rc = -ENOMEM;
11262 		goto out_destroy;
11263 	}
11264 	rc = lpfc_create_wq_cq(phba, qp[0].hba_eq,
11265 			       phba->sli4_hba.els_cq,
11266 			       phba->sli4_hba.els_wq,
11267 			       NULL, 0, LPFC_ELS);
11268 	if (rc) {
11269 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11270 				"0525 Failed setup of ELS WQ/CQ: rc = 0x%x\n",
11271 				(uint32_t)rc);
11272 		goto out_destroy;
11273 	}
11274 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11275 			"2590 ELS WQ setup: wq-id=%d, parent cq-id=%d\n",
11276 			phba->sli4_hba.els_wq->queue_id,
11277 			phba->sli4_hba.els_cq->queue_id);
11278 
11279 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
11280 		/* Set up NVME LS Complete Queue */
11281 		if (!phba->sli4_hba.nvmels_cq || !phba->sli4_hba.nvmels_wq) {
11282 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11283 					"6091 LS %s not allocated\n",
11284 					phba->sli4_hba.nvmels_cq ? "WQ" : "CQ");
11285 			rc = -ENOMEM;
11286 			goto out_destroy;
11287 		}
11288 		rc = lpfc_create_wq_cq(phba, qp[0].hba_eq,
11289 				       phba->sli4_hba.nvmels_cq,
11290 				       phba->sli4_hba.nvmels_wq,
11291 				       NULL, 0, LPFC_NVME_LS);
11292 		if (rc) {
11293 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11294 					"0526 Failed setup of NVVME LS WQ/CQ: "
11295 					"rc = 0x%x\n", (uint32_t)rc);
11296 			goto out_destroy;
11297 		}
11298 
11299 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11300 				"6096 ELS WQ setup: wq-id=%d, "
11301 				"parent cq-id=%d\n",
11302 				phba->sli4_hba.nvmels_wq->queue_id,
11303 				phba->sli4_hba.nvmels_cq->queue_id);
11304 	}
11305 
11306 	/*
11307 	 * Create NVMET Receive Queue (RQ)
11308 	 */
11309 	if (phba->nvmet_support) {
11310 		if ((!phba->sli4_hba.nvmet_cqset) ||
11311 		    (!phba->sli4_hba.nvmet_mrq_hdr) ||
11312 		    (!phba->sli4_hba.nvmet_mrq_data)) {
11313 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11314 					"6130 MRQ CQ Queues not "
11315 					"allocated\n");
11316 			rc = -ENOMEM;
11317 			goto out_destroy;
11318 		}
11319 		if (phba->cfg_nvmet_mrq > 1) {
11320 			rc = lpfc_mrq_create(phba,
11321 					     phba->sli4_hba.nvmet_mrq_hdr,
11322 					     phba->sli4_hba.nvmet_mrq_data,
11323 					     phba->sli4_hba.nvmet_cqset,
11324 					     LPFC_NVMET);
11325 			if (rc) {
11326 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11327 						"6098 Failed setup of NVMET "
11328 						"MRQ: rc = 0x%x\n",
11329 						(uint32_t)rc);
11330 				goto out_destroy;
11331 			}
11332 
11333 		} else {
11334 			rc = lpfc_rq_create(phba,
11335 					    phba->sli4_hba.nvmet_mrq_hdr[0],
11336 					    phba->sli4_hba.nvmet_mrq_data[0],
11337 					    phba->sli4_hba.nvmet_cqset[0],
11338 					    LPFC_NVMET);
11339 			if (rc) {
11340 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11341 						"6057 Failed setup of NVMET "
11342 						"Receive Queue: rc = 0x%x\n",
11343 						(uint32_t)rc);
11344 				goto out_destroy;
11345 			}
11346 
11347 			lpfc_printf_log(
11348 				phba, KERN_INFO, LOG_INIT,
11349 				"6099 NVMET RQ setup: hdr-rq-id=%d, "
11350 				"dat-rq-id=%d parent cq-id=%d\n",
11351 				phba->sli4_hba.nvmet_mrq_hdr[0]->queue_id,
11352 				phba->sli4_hba.nvmet_mrq_data[0]->queue_id,
11353 				phba->sli4_hba.nvmet_cqset[0]->queue_id);
11354 
11355 		}
11356 	}
11357 
11358 	if (!phba->sli4_hba.hdr_rq || !phba->sli4_hba.dat_rq) {
11359 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11360 				"0540 Receive Queue not allocated\n");
11361 		rc = -ENOMEM;
11362 		goto out_destroy;
11363 	}
11364 
11365 	rc = lpfc_rq_create(phba, phba->sli4_hba.hdr_rq, phba->sli4_hba.dat_rq,
11366 			    phba->sli4_hba.els_cq, LPFC_USOL);
11367 	if (rc) {
11368 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11369 				"0541 Failed setup of Receive Queue: "
11370 				"rc = 0x%x\n", (uint32_t)rc);
11371 		goto out_destroy;
11372 	}
11373 
11374 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11375 			"2592 USL RQ setup: hdr-rq-id=%d, dat-rq-id=%d "
11376 			"parent cq-id=%d\n",
11377 			phba->sli4_hba.hdr_rq->queue_id,
11378 			phba->sli4_hba.dat_rq->queue_id,
11379 			phba->sli4_hba.els_cq->queue_id);
11380 
11381 	if (phba->cfg_fcp_imax)
11382 		usdelay = LPFC_SEC_TO_USEC / phba->cfg_fcp_imax;
11383 	else
11384 		usdelay = 0;
11385 
11386 	for (qidx = 0; qidx < phba->cfg_irq_chann;
11387 	     qidx += LPFC_MAX_EQ_DELAY_EQID_CNT)
11388 		lpfc_modify_hba_eq_delay(phba, qidx, LPFC_MAX_EQ_DELAY_EQID_CNT,
11389 					 usdelay);
11390 
11391 	if (phba->sli4_hba.cq_max) {
11392 		kfree(phba->sli4_hba.cq_lookup);
11393 		phba->sli4_hba.cq_lookup = kcalloc((phba->sli4_hba.cq_max + 1),
11394 			sizeof(struct lpfc_queue *), GFP_KERNEL);
11395 		if (!phba->sli4_hba.cq_lookup) {
11396 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11397 					"0549 Failed setup of CQ Lookup table: "
11398 					"size 0x%x\n", phba->sli4_hba.cq_max);
11399 			rc = -ENOMEM;
11400 			goto out_destroy;
11401 		}
11402 		lpfc_setup_cq_lookup(phba);
11403 	}
11404 	return 0;
11405 
11406 out_destroy:
11407 	lpfc_sli4_queue_unset(phba);
11408 out_error:
11409 	return rc;
11410 }
11411 
11412 /**
11413  * lpfc_sli4_queue_unset - Unset all the SLI4 queues
11414  * @phba: pointer to lpfc hba data structure.
11415  *
11416  * This routine is invoked to unset all the SLI4 queues with the FCoE HBA
11417  * operation.
11418  *
11419  * Return codes
11420  *      0 - successful
11421  *      -ENOMEM - No available memory
11422  *      -EIO - The mailbox failed to complete successfully.
11423  **/
11424 void
11425 lpfc_sli4_queue_unset(struct lpfc_hba *phba)
11426 {
11427 	struct lpfc_sli4_hdw_queue *qp;
11428 	struct lpfc_queue *eq;
11429 	int qidx;
11430 
11431 	/* Unset mailbox command work queue */
11432 	if (phba->sli4_hba.mbx_wq)
11433 		lpfc_mq_destroy(phba, phba->sli4_hba.mbx_wq);
11434 
11435 	/* Unset NVME LS work queue */
11436 	if (phba->sli4_hba.nvmels_wq)
11437 		lpfc_wq_destroy(phba, phba->sli4_hba.nvmels_wq);
11438 
11439 	/* Unset ELS work queue */
11440 	if (phba->sli4_hba.els_wq)
11441 		lpfc_wq_destroy(phba, phba->sli4_hba.els_wq);
11442 
11443 	/* Unset unsolicited receive queue */
11444 	if (phba->sli4_hba.hdr_rq)
11445 		lpfc_rq_destroy(phba, phba->sli4_hba.hdr_rq,
11446 				phba->sli4_hba.dat_rq);
11447 
11448 	/* Unset mailbox command complete queue */
11449 	if (phba->sli4_hba.mbx_cq)
11450 		lpfc_cq_destroy(phba, phba->sli4_hba.mbx_cq);
11451 
11452 	/* Unset ELS complete queue */
11453 	if (phba->sli4_hba.els_cq)
11454 		lpfc_cq_destroy(phba, phba->sli4_hba.els_cq);
11455 
11456 	/* Unset NVME LS complete queue */
11457 	if (phba->sli4_hba.nvmels_cq)
11458 		lpfc_cq_destroy(phba, phba->sli4_hba.nvmels_cq);
11459 
11460 	if (phba->nvmet_support) {
11461 		/* Unset NVMET MRQ queue */
11462 		if (phba->sli4_hba.nvmet_mrq_hdr) {
11463 			for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++)
11464 				lpfc_rq_destroy(
11465 					phba,
11466 					phba->sli4_hba.nvmet_mrq_hdr[qidx],
11467 					phba->sli4_hba.nvmet_mrq_data[qidx]);
11468 		}
11469 
11470 		/* Unset NVMET CQ Set complete queue */
11471 		if (phba->sli4_hba.nvmet_cqset) {
11472 			for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++)
11473 				lpfc_cq_destroy(
11474 					phba, phba->sli4_hba.nvmet_cqset[qidx]);
11475 		}
11476 	}
11477 
11478 	/* Unset fast-path SLI4 queues */
11479 	if (phba->sli4_hba.hdwq) {
11480 		/* Loop thru all Hardware Queues */
11481 		for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
11482 			/* Destroy the CQ/WQ corresponding to Hardware Queue */
11483 			qp = &phba->sli4_hba.hdwq[qidx];
11484 			lpfc_wq_destroy(phba, qp->io_wq);
11485 			lpfc_cq_destroy(phba, qp->io_cq);
11486 		}
11487 		/* Loop thru all IRQ vectors */
11488 		for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
11489 			/* Destroy the EQ corresponding to the IRQ vector */
11490 			eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
11491 			lpfc_eq_destroy(phba, eq);
11492 		}
11493 	}
11494 
11495 	kfree(phba->sli4_hba.cq_lookup);
11496 	phba->sli4_hba.cq_lookup = NULL;
11497 	phba->sli4_hba.cq_max = 0;
11498 }
11499 
11500 /**
11501  * lpfc_sli4_cq_event_pool_create - Create completion-queue event free pool
11502  * @phba: pointer to lpfc hba data structure.
11503  *
11504  * This routine is invoked to allocate and set up a pool of completion queue
11505  * events. The body of the completion queue event is a completion queue entry
11506  * CQE. For now, this pool is used for the interrupt service routine to queue
11507  * the following HBA completion queue events for the worker thread to process:
11508  *   - Mailbox asynchronous events
11509  *   - Receive queue completion unsolicited events
11510  * Later, this can be used for all the slow-path events.
11511  *
11512  * Return codes
11513  *      0 - successful
11514  *      -ENOMEM - No available memory
11515  **/
11516 static int
11517 lpfc_sli4_cq_event_pool_create(struct lpfc_hba *phba)
11518 {
11519 	struct lpfc_cq_event *cq_event;
11520 	int i;
11521 
11522 	for (i = 0; i < (4 * phba->sli4_hba.cq_ecount); i++) {
11523 		cq_event = kmalloc(sizeof(struct lpfc_cq_event), GFP_KERNEL);
11524 		if (!cq_event)
11525 			goto out_pool_create_fail;
11526 		list_add_tail(&cq_event->list,
11527 			      &phba->sli4_hba.sp_cqe_event_pool);
11528 	}
11529 	return 0;
11530 
11531 out_pool_create_fail:
11532 	lpfc_sli4_cq_event_pool_destroy(phba);
11533 	return -ENOMEM;
11534 }
11535 
11536 /**
11537  * lpfc_sli4_cq_event_pool_destroy - Free completion-queue event free pool
11538  * @phba: pointer to lpfc hba data structure.
11539  *
11540  * This routine is invoked to free the pool of completion queue events at
11541  * driver unload time. Note that, it is the responsibility of the driver
11542  * cleanup routine to free all the outstanding completion-queue events
11543  * allocated from this pool back into the pool before invoking this routine
11544  * to destroy the pool.
11545  **/
11546 static void
11547 lpfc_sli4_cq_event_pool_destroy(struct lpfc_hba *phba)
11548 {
11549 	struct lpfc_cq_event *cq_event, *next_cq_event;
11550 
11551 	list_for_each_entry_safe(cq_event, next_cq_event,
11552 				 &phba->sli4_hba.sp_cqe_event_pool, list) {
11553 		list_del(&cq_event->list);
11554 		kfree(cq_event);
11555 	}
11556 }
11557 
11558 /**
11559  * __lpfc_sli4_cq_event_alloc - Allocate a completion-queue event from free pool
11560  * @phba: pointer to lpfc hba data structure.
11561  *
11562  * This routine is the lock free version of the API invoked to allocate a
11563  * completion-queue event from the free pool.
11564  *
11565  * Return: Pointer to the newly allocated completion-queue event if successful
11566  *         NULL otherwise.
11567  **/
11568 struct lpfc_cq_event *
11569 __lpfc_sli4_cq_event_alloc(struct lpfc_hba *phba)
11570 {
11571 	struct lpfc_cq_event *cq_event = NULL;
11572 
11573 	list_remove_head(&phba->sli4_hba.sp_cqe_event_pool, cq_event,
11574 			 struct lpfc_cq_event, list);
11575 	return cq_event;
11576 }
11577 
11578 /**
11579  * lpfc_sli4_cq_event_alloc - Allocate a completion-queue event from free pool
11580  * @phba: pointer to lpfc hba data structure.
11581  *
11582  * This routine is the lock version of the API invoked to allocate a
11583  * completion-queue event from the free pool.
11584  *
11585  * Return: Pointer to the newly allocated completion-queue event if successful
11586  *         NULL otherwise.
11587  **/
11588 struct lpfc_cq_event *
11589 lpfc_sli4_cq_event_alloc(struct lpfc_hba *phba)
11590 {
11591 	struct lpfc_cq_event *cq_event;
11592 	unsigned long iflags;
11593 
11594 	spin_lock_irqsave(&phba->hbalock, iflags);
11595 	cq_event = __lpfc_sli4_cq_event_alloc(phba);
11596 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11597 	return cq_event;
11598 }
11599 
11600 /**
11601  * __lpfc_sli4_cq_event_release - Release a completion-queue event to free pool
11602  * @phba: pointer to lpfc hba data structure.
11603  * @cq_event: pointer to the completion queue event to be freed.
11604  *
11605  * This routine is the lock free version of the API invoked to release a
11606  * completion-queue event back into the free pool.
11607  **/
11608 void
11609 __lpfc_sli4_cq_event_release(struct lpfc_hba *phba,
11610 			     struct lpfc_cq_event *cq_event)
11611 {
11612 	list_add_tail(&cq_event->list, &phba->sli4_hba.sp_cqe_event_pool);
11613 }
11614 
11615 /**
11616  * lpfc_sli4_cq_event_release - Release a completion-queue event to free pool
11617  * @phba: pointer to lpfc hba data structure.
11618  * @cq_event: pointer to the completion queue event to be freed.
11619  *
11620  * This routine is the lock version of the API invoked to release a
11621  * completion-queue event back into the free pool.
11622  **/
11623 void
11624 lpfc_sli4_cq_event_release(struct lpfc_hba *phba,
11625 			   struct lpfc_cq_event *cq_event)
11626 {
11627 	unsigned long iflags;
11628 	spin_lock_irqsave(&phba->hbalock, iflags);
11629 	__lpfc_sli4_cq_event_release(phba, cq_event);
11630 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11631 }
11632 
11633 /**
11634  * lpfc_sli4_cq_event_release_all - Release all cq events to the free pool
11635  * @phba: pointer to lpfc hba data structure.
11636  *
11637  * This routine is to free all the pending completion-queue events to the
11638  * back into the free pool for device reset.
11639  **/
11640 static void
11641 lpfc_sli4_cq_event_release_all(struct lpfc_hba *phba)
11642 {
11643 	LIST_HEAD(cq_event_list);
11644 	struct lpfc_cq_event *cq_event;
11645 	unsigned long iflags;
11646 
11647 	/* Retrieve all the pending WCQEs from pending WCQE lists */
11648 
11649 	/* Pending ELS XRI abort events */
11650 	spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
11651 	list_splice_init(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
11652 			 &cq_event_list);
11653 	spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
11654 
11655 	/* Pending asynnc events */
11656 	spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
11657 	list_splice_init(&phba->sli4_hba.sp_asynce_work_queue,
11658 			 &cq_event_list);
11659 	spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock, iflags);
11660 
11661 	while (!list_empty(&cq_event_list)) {
11662 		list_remove_head(&cq_event_list, cq_event,
11663 				 struct lpfc_cq_event, list);
11664 		lpfc_sli4_cq_event_release(phba, cq_event);
11665 	}
11666 }
11667 
11668 /**
11669  * lpfc_pci_function_reset - Reset pci function.
11670  * @phba: pointer to lpfc hba data structure.
11671  *
11672  * This routine is invoked to request a PCI function reset. It will destroys
11673  * all resources assigned to the PCI function which originates this request.
11674  *
11675  * Return codes
11676  *      0 - successful
11677  *      -ENOMEM - No available memory
11678  *      -EIO - The mailbox failed to complete successfully.
11679  **/
11680 int
11681 lpfc_pci_function_reset(struct lpfc_hba *phba)
11682 {
11683 	LPFC_MBOXQ_t *mboxq;
11684 	uint32_t rc = 0, if_type;
11685 	uint32_t shdr_status, shdr_add_status;
11686 	uint32_t rdy_chk;
11687 	uint32_t port_reset = 0;
11688 	union lpfc_sli4_cfg_shdr *shdr;
11689 	struct lpfc_register reg_data;
11690 	uint16_t devid;
11691 
11692 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
11693 	switch (if_type) {
11694 	case LPFC_SLI_INTF_IF_TYPE_0:
11695 		mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
11696 						       GFP_KERNEL);
11697 		if (!mboxq) {
11698 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11699 					"0494 Unable to allocate memory for "
11700 					"issuing SLI_FUNCTION_RESET mailbox "
11701 					"command\n");
11702 			return -ENOMEM;
11703 		}
11704 
11705 		/* Setup PCI function reset mailbox-ioctl command */
11706 		lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
11707 				 LPFC_MBOX_OPCODE_FUNCTION_RESET, 0,
11708 				 LPFC_SLI4_MBX_EMBED);
11709 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
11710 		shdr = (union lpfc_sli4_cfg_shdr *)
11711 			&mboxq->u.mqe.un.sli4_config.header.cfg_shdr;
11712 		shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
11713 		shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
11714 					 &shdr->response);
11715 		mempool_free(mboxq, phba->mbox_mem_pool);
11716 		if (shdr_status || shdr_add_status || rc) {
11717 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11718 					"0495 SLI_FUNCTION_RESET mailbox "
11719 					"failed with status x%x add_status x%x,"
11720 					" mbx status x%x\n",
11721 					shdr_status, shdr_add_status, rc);
11722 			rc = -ENXIO;
11723 		}
11724 		break;
11725 	case LPFC_SLI_INTF_IF_TYPE_2:
11726 	case LPFC_SLI_INTF_IF_TYPE_6:
11727 wait:
11728 		/*
11729 		 * Poll the Port Status Register and wait for RDY for
11730 		 * up to 30 seconds. If the port doesn't respond, treat
11731 		 * it as an error.
11732 		 */
11733 		for (rdy_chk = 0; rdy_chk < 1500; rdy_chk++) {
11734 			if (lpfc_readl(phba->sli4_hba.u.if_type2.
11735 				STATUSregaddr, &reg_data.word0)) {
11736 				rc = -ENODEV;
11737 				goto out;
11738 			}
11739 			if (bf_get(lpfc_sliport_status_rdy, &reg_data))
11740 				break;
11741 			msleep(20);
11742 		}
11743 
11744 		if (!bf_get(lpfc_sliport_status_rdy, &reg_data)) {
11745 			phba->work_status[0] = readl(
11746 				phba->sli4_hba.u.if_type2.ERR1regaddr);
11747 			phba->work_status[1] = readl(
11748 				phba->sli4_hba.u.if_type2.ERR2regaddr);
11749 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11750 					"2890 Port not ready, port status reg "
11751 					"0x%x error 1=0x%x, error 2=0x%x\n",
11752 					reg_data.word0,
11753 					phba->work_status[0],
11754 					phba->work_status[1]);
11755 			rc = -ENODEV;
11756 			goto out;
11757 		}
11758 
11759 		if (bf_get(lpfc_sliport_status_pldv, &reg_data))
11760 			lpfc_pldv_detect = true;
11761 
11762 		if (!port_reset) {
11763 			/*
11764 			 * Reset the port now
11765 			 */
11766 			reg_data.word0 = 0;
11767 			bf_set(lpfc_sliport_ctrl_end, &reg_data,
11768 			       LPFC_SLIPORT_LITTLE_ENDIAN);
11769 			bf_set(lpfc_sliport_ctrl_ip, &reg_data,
11770 			       LPFC_SLIPORT_INIT_PORT);
11771 			writel(reg_data.word0, phba->sli4_hba.u.if_type2.
11772 			       CTRLregaddr);
11773 			/* flush */
11774 			pci_read_config_word(phba->pcidev,
11775 					     PCI_DEVICE_ID, &devid);
11776 
11777 			port_reset = 1;
11778 			msleep(20);
11779 			goto wait;
11780 		} else if (bf_get(lpfc_sliport_status_rn, &reg_data)) {
11781 			rc = -ENODEV;
11782 			goto out;
11783 		}
11784 		break;
11785 
11786 	case LPFC_SLI_INTF_IF_TYPE_1:
11787 	default:
11788 		break;
11789 	}
11790 
11791 out:
11792 	/* Catch the not-ready port failure after a port reset. */
11793 	if (rc) {
11794 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11795 				"3317 HBA not functional: IP Reset Failed "
11796 				"try: echo fw_reset > board_mode\n");
11797 		rc = -ENODEV;
11798 	}
11799 
11800 	return rc;
11801 }
11802 
11803 /**
11804  * lpfc_sli4_pci_mem_setup - Setup SLI4 HBA PCI memory space.
11805  * @phba: pointer to lpfc hba data structure.
11806  *
11807  * This routine is invoked to set up the PCI device memory space for device
11808  * with SLI-4 interface spec.
11809  *
11810  * Return codes
11811  * 	0 - successful
11812  * 	other values - error
11813  **/
11814 static int
11815 lpfc_sli4_pci_mem_setup(struct lpfc_hba *phba)
11816 {
11817 	struct pci_dev *pdev = phba->pcidev;
11818 	unsigned long bar0map_len, bar1map_len, bar2map_len;
11819 	int error;
11820 	uint32_t if_type;
11821 
11822 	if (!pdev)
11823 		return -ENODEV;
11824 
11825 	/* Set the device DMA mask size */
11826 	error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
11827 	if (error)
11828 		error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32));
11829 	if (error)
11830 		return error;
11831 
11832 	/*
11833 	 * The BARs and register set definitions and offset locations are
11834 	 * dependent on the if_type.
11835 	 */
11836 	if (pci_read_config_dword(pdev, LPFC_SLI_INTF,
11837 				  &phba->sli4_hba.sli_intf.word0)) {
11838 		return -ENODEV;
11839 	}
11840 
11841 	/* There is no SLI3 failback for SLI4 devices. */
11842 	if (bf_get(lpfc_sli_intf_valid, &phba->sli4_hba.sli_intf) !=
11843 	    LPFC_SLI_INTF_VALID) {
11844 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11845 				"2894 SLI_INTF reg contents invalid "
11846 				"sli_intf reg 0x%x\n",
11847 				phba->sli4_hba.sli_intf.word0);
11848 		return -ENODEV;
11849 	}
11850 
11851 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
11852 	/*
11853 	 * Get the bus address of SLI4 device Bar regions and the
11854 	 * number of bytes required by each mapping. The mapping of the
11855 	 * particular PCI BARs regions is dependent on the type of
11856 	 * SLI4 device.
11857 	 */
11858 	if (pci_resource_start(pdev, PCI_64BIT_BAR0)) {
11859 		phba->pci_bar0_map = pci_resource_start(pdev, PCI_64BIT_BAR0);
11860 		bar0map_len = pci_resource_len(pdev, PCI_64BIT_BAR0);
11861 
11862 		/*
11863 		 * Map SLI4 PCI Config Space Register base to a kernel virtual
11864 		 * addr
11865 		 */
11866 		phba->sli4_hba.conf_regs_memmap_p =
11867 			ioremap(phba->pci_bar0_map, bar0map_len);
11868 		if (!phba->sli4_hba.conf_regs_memmap_p) {
11869 			dev_printk(KERN_ERR, &pdev->dev,
11870 				   "ioremap failed for SLI4 PCI config "
11871 				   "registers.\n");
11872 			return -ENODEV;
11873 		}
11874 		phba->pci_bar0_memmap_p = phba->sli4_hba.conf_regs_memmap_p;
11875 		/* Set up BAR0 PCI config space register memory map */
11876 		lpfc_sli4_bar0_register_memmap(phba, if_type);
11877 	} else {
11878 		phba->pci_bar0_map = pci_resource_start(pdev, 1);
11879 		bar0map_len = pci_resource_len(pdev, 1);
11880 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
11881 			dev_printk(KERN_ERR, &pdev->dev,
11882 			   "FATAL - No BAR0 mapping for SLI4, if_type 2\n");
11883 			return -ENODEV;
11884 		}
11885 		phba->sli4_hba.conf_regs_memmap_p =
11886 				ioremap(phba->pci_bar0_map, bar0map_len);
11887 		if (!phba->sli4_hba.conf_regs_memmap_p) {
11888 			dev_printk(KERN_ERR, &pdev->dev,
11889 				"ioremap failed for SLI4 PCI config "
11890 				"registers.\n");
11891 			return -ENODEV;
11892 		}
11893 		lpfc_sli4_bar0_register_memmap(phba, if_type);
11894 	}
11895 
11896 	if (if_type == LPFC_SLI_INTF_IF_TYPE_0) {
11897 		if (pci_resource_start(pdev, PCI_64BIT_BAR2)) {
11898 			/*
11899 			 * Map SLI4 if type 0 HBA Control Register base to a
11900 			 * kernel virtual address and setup the registers.
11901 			 */
11902 			phba->pci_bar1_map = pci_resource_start(pdev,
11903 								PCI_64BIT_BAR2);
11904 			bar1map_len = pci_resource_len(pdev, PCI_64BIT_BAR2);
11905 			phba->sli4_hba.ctrl_regs_memmap_p =
11906 					ioremap(phba->pci_bar1_map,
11907 						bar1map_len);
11908 			if (!phba->sli4_hba.ctrl_regs_memmap_p) {
11909 				dev_err(&pdev->dev,
11910 					   "ioremap failed for SLI4 HBA "
11911 					    "control registers.\n");
11912 				error = -ENOMEM;
11913 				goto out_iounmap_conf;
11914 			}
11915 			phba->pci_bar2_memmap_p =
11916 					 phba->sli4_hba.ctrl_regs_memmap_p;
11917 			lpfc_sli4_bar1_register_memmap(phba, if_type);
11918 		} else {
11919 			error = -ENOMEM;
11920 			goto out_iounmap_conf;
11921 		}
11922 	}
11923 
11924 	if ((if_type == LPFC_SLI_INTF_IF_TYPE_6) &&
11925 	    (pci_resource_start(pdev, PCI_64BIT_BAR2))) {
11926 		/*
11927 		 * Map SLI4 if type 6 HBA Doorbell Register base to a kernel
11928 		 * virtual address and setup the registers.
11929 		 */
11930 		phba->pci_bar1_map = pci_resource_start(pdev, PCI_64BIT_BAR2);
11931 		bar1map_len = pci_resource_len(pdev, PCI_64BIT_BAR2);
11932 		phba->sli4_hba.drbl_regs_memmap_p =
11933 				ioremap(phba->pci_bar1_map, bar1map_len);
11934 		if (!phba->sli4_hba.drbl_regs_memmap_p) {
11935 			dev_err(&pdev->dev,
11936 			   "ioremap failed for SLI4 HBA doorbell registers.\n");
11937 			error = -ENOMEM;
11938 			goto out_iounmap_conf;
11939 		}
11940 		phba->pci_bar2_memmap_p = phba->sli4_hba.drbl_regs_memmap_p;
11941 		lpfc_sli4_bar1_register_memmap(phba, if_type);
11942 	}
11943 
11944 	if (if_type == LPFC_SLI_INTF_IF_TYPE_0) {
11945 		if (pci_resource_start(pdev, PCI_64BIT_BAR4)) {
11946 			/*
11947 			 * Map SLI4 if type 0 HBA Doorbell Register base to
11948 			 * a kernel virtual address and setup the registers.
11949 			 */
11950 			phba->pci_bar2_map = pci_resource_start(pdev,
11951 								PCI_64BIT_BAR4);
11952 			bar2map_len = pci_resource_len(pdev, PCI_64BIT_BAR4);
11953 			phba->sli4_hba.drbl_regs_memmap_p =
11954 					ioremap(phba->pci_bar2_map,
11955 						bar2map_len);
11956 			if (!phba->sli4_hba.drbl_regs_memmap_p) {
11957 				dev_err(&pdev->dev,
11958 					   "ioremap failed for SLI4 HBA"
11959 					   " doorbell registers.\n");
11960 				error = -ENOMEM;
11961 				goto out_iounmap_ctrl;
11962 			}
11963 			phba->pci_bar4_memmap_p =
11964 					phba->sli4_hba.drbl_regs_memmap_p;
11965 			error = lpfc_sli4_bar2_register_memmap(phba, LPFC_VF0);
11966 			if (error)
11967 				goto out_iounmap_all;
11968 		} else {
11969 			error = -ENOMEM;
11970 			goto out_iounmap_all;
11971 		}
11972 	}
11973 
11974 	if (if_type == LPFC_SLI_INTF_IF_TYPE_6 &&
11975 	    pci_resource_start(pdev, PCI_64BIT_BAR4)) {
11976 		/*
11977 		 * Map SLI4 if type 6 HBA DPP Register base to a kernel
11978 		 * virtual address and setup the registers.
11979 		 */
11980 		phba->pci_bar2_map = pci_resource_start(pdev, PCI_64BIT_BAR4);
11981 		bar2map_len = pci_resource_len(pdev, PCI_64BIT_BAR4);
11982 		phba->sli4_hba.dpp_regs_memmap_p =
11983 				ioremap(phba->pci_bar2_map, bar2map_len);
11984 		if (!phba->sli4_hba.dpp_regs_memmap_p) {
11985 			dev_err(&pdev->dev,
11986 			   "ioremap failed for SLI4 HBA dpp registers.\n");
11987 			error = -ENOMEM;
11988 			goto out_iounmap_ctrl;
11989 		}
11990 		phba->pci_bar4_memmap_p = phba->sli4_hba.dpp_regs_memmap_p;
11991 	}
11992 
11993 	/* Set up the EQ/CQ register handeling functions now */
11994 	switch (if_type) {
11995 	case LPFC_SLI_INTF_IF_TYPE_0:
11996 	case LPFC_SLI_INTF_IF_TYPE_2:
11997 		phba->sli4_hba.sli4_eq_clr_intr = lpfc_sli4_eq_clr_intr;
11998 		phba->sli4_hba.sli4_write_eq_db = lpfc_sli4_write_eq_db;
11999 		phba->sli4_hba.sli4_write_cq_db = lpfc_sli4_write_cq_db;
12000 		break;
12001 	case LPFC_SLI_INTF_IF_TYPE_6:
12002 		phba->sli4_hba.sli4_eq_clr_intr = lpfc_sli4_if6_eq_clr_intr;
12003 		phba->sli4_hba.sli4_write_eq_db = lpfc_sli4_if6_write_eq_db;
12004 		phba->sli4_hba.sli4_write_cq_db = lpfc_sli4_if6_write_cq_db;
12005 		break;
12006 	default:
12007 		break;
12008 	}
12009 
12010 	return 0;
12011 
12012 out_iounmap_all:
12013 	iounmap(phba->sli4_hba.drbl_regs_memmap_p);
12014 out_iounmap_ctrl:
12015 	iounmap(phba->sli4_hba.ctrl_regs_memmap_p);
12016 out_iounmap_conf:
12017 	iounmap(phba->sli4_hba.conf_regs_memmap_p);
12018 
12019 	return error;
12020 }
12021 
12022 /**
12023  * lpfc_sli4_pci_mem_unset - Unset SLI4 HBA PCI memory space.
12024  * @phba: pointer to lpfc hba data structure.
12025  *
12026  * This routine is invoked to unset the PCI device memory space for device
12027  * with SLI-4 interface spec.
12028  **/
12029 static void
12030 lpfc_sli4_pci_mem_unset(struct lpfc_hba *phba)
12031 {
12032 	uint32_t if_type;
12033 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
12034 
12035 	switch (if_type) {
12036 	case LPFC_SLI_INTF_IF_TYPE_0:
12037 		iounmap(phba->sli4_hba.drbl_regs_memmap_p);
12038 		iounmap(phba->sli4_hba.ctrl_regs_memmap_p);
12039 		iounmap(phba->sli4_hba.conf_regs_memmap_p);
12040 		break;
12041 	case LPFC_SLI_INTF_IF_TYPE_2:
12042 		iounmap(phba->sli4_hba.conf_regs_memmap_p);
12043 		break;
12044 	case LPFC_SLI_INTF_IF_TYPE_6:
12045 		iounmap(phba->sli4_hba.drbl_regs_memmap_p);
12046 		iounmap(phba->sli4_hba.conf_regs_memmap_p);
12047 		if (phba->sli4_hba.dpp_regs_memmap_p)
12048 			iounmap(phba->sli4_hba.dpp_regs_memmap_p);
12049 		break;
12050 	case LPFC_SLI_INTF_IF_TYPE_1:
12051 	default:
12052 		dev_printk(KERN_ERR, &phba->pcidev->dev,
12053 			   "FATAL - unsupported SLI4 interface type - %d\n",
12054 			   if_type);
12055 		break;
12056 	}
12057 }
12058 
12059 /**
12060  * lpfc_sli_enable_msix - Enable MSI-X interrupt mode on SLI-3 device
12061  * @phba: pointer to lpfc hba data structure.
12062  *
12063  * This routine is invoked to enable the MSI-X interrupt vectors to device
12064  * with SLI-3 interface specs.
12065  *
12066  * Return codes
12067  *   0 - successful
12068  *   other values - error
12069  **/
12070 static int
12071 lpfc_sli_enable_msix(struct lpfc_hba *phba)
12072 {
12073 	int rc;
12074 	LPFC_MBOXQ_t *pmb;
12075 
12076 	/* Set up MSI-X multi-message vectors */
12077 	rc = pci_alloc_irq_vectors(phba->pcidev,
12078 			LPFC_MSIX_VECTORS, LPFC_MSIX_VECTORS, PCI_IRQ_MSIX);
12079 	if (rc < 0) {
12080 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12081 				"0420 PCI enable MSI-X failed (%d)\n", rc);
12082 		goto vec_fail_out;
12083 	}
12084 
12085 	/*
12086 	 * Assign MSI-X vectors to interrupt handlers
12087 	 */
12088 
12089 	/* vector-0 is associated to slow-path handler */
12090 	rc = request_irq(pci_irq_vector(phba->pcidev, 0),
12091 			 &lpfc_sli_sp_intr_handler, 0,
12092 			 LPFC_SP_DRIVER_HANDLER_NAME, phba);
12093 	if (rc) {
12094 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
12095 				"0421 MSI-X slow-path request_irq failed "
12096 				"(%d)\n", rc);
12097 		goto msi_fail_out;
12098 	}
12099 
12100 	/* vector-1 is associated to fast-path handler */
12101 	rc = request_irq(pci_irq_vector(phba->pcidev, 1),
12102 			 &lpfc_sli_fp_intr_handler, 0,
12103 			 LPFC_FP_DRIVER_HANDLER_NAME, phba);
12104 
12105 	if (rc) {
12106 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
12107 				"0429 MSI-X fast-path request_irq failed "
12108 				"(%d)\n", rc);
12109 		goto irq_fail_out;
12110 	}
12111 
12112 	/*
12113 	 * Configure HBA MSI-X attention conditions to messages
12114 	 */
12115 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
12116 
12117 	if (!pmb) {
12118 		rc = -ENOMEM;
12119 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12120 				"0474 Unable to allocate memory for issuing "
12121 				"MBOX_CONFIG_MSI command\n");
12122 		goto mem_fail_out;
12123 	}
12124 	rc = lpfc_config_msi(phba, pmb);
12125 	if (rc)
12126 		goto mbx_fail_out;
12127 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
12128 	if (rc != MBX_SUCCESS) {
12129 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX,
12130 				"0351 Config MSI mailbox command failed, "
12131 				"mbxCmd x%x, mbxStatus x%x\n",
12132 				pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus);
12133 		goto mbx_fail_out;
12134 	}
12135 
12136 	/* Free memory allocated for mailbox command */
12137 	mempool_free(pmb, phba->mbox_mem_pool);
12138 	return rc;
12139 
12140 mbx_fail_out:
12141 	/* Free memory allocated for mailbox command */
12142 	mempool_free(pmb, phba->mbox_mem_pool);
12143 
12144 mem_fail_out:
12145 	/* free the irq already requested */
12146 	free_irq(pci_irq_vector(phba->pcidev, 1), phba);
12147 
12148 irq_fail_out:
12149 	/* free the irq already requested */
12150 	free_irq(pci_irq_vector(phba->pcidev, 0), phba);
12151 
12152 msi_fail_out:
12153 	/* Unconfigure MSI-X capability structure */
12154 	pci_free_irq_vectors(phba->pcidev);
12155 
12156 vec_fail_out:
12157 	return rc;
12158 }
12159 
12160 /**
12161  * lpfc_sli_enable_msi - Enable MSI interrupt mode on SLI-3 device.
12162  * @phba: pointer to lpfc hba data structure.
12163  *
12164  * This routine is invoked to enable the MSI interrupt mode to device with
12165  * SLI-3 interface spec. The kernel function pci_enable_msi() is called to
12166  * enable the MSI vector. The device driver is responsible for calling the
12167  * request_irq() to register MSI vector with a interrupt the handler, which
12168  * is done in this function.
12169  *
12170  * Return codes
12171  * 	0 - successful
12172  * 	other values - error
12173  */
12174 static int
12175 lpfc_sli_enable_msi(struct lpfc_hba *phba)
12176 {
12177 	int rc;
12178 
12179 	rc = pci_enable_msi(phba->pcidev);
12180 	if (!rc)
12181 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12182 				"0012 PCI enable MSI mode success.\n");
12183 	else {
12184 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12185 				"0471 PCI enable MSI mode failed (%d)\n", rc);
12186 		return rc;
12187 	}
12188 
12189 	rc = request_irq(phba->pcidev->irq, lpfc_sli_intr_handler,
12190 			 0, LPFC_DRIVER_NAME, phba);
12191 	if (rc) {
12192 		pci_disable_msi(phba->pcidev);
12193 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
12194 				"0478 MSI request_irq failed (%d)\n", rc);
12195 	}
12196 	return rc;
12197 }
12198 
12199 /**
12200  * lpfc_sli_enable_intr - Enable device interrupt to SLI-3 device.
12201  * @phba: pointer to lpfc hba data structure.
12202  * @cfg_mode: Interrupt configuration mode (INTx, MSI or MSI-X).
12203  *
12204  * This routine is invoked to enable device interrupt and associate driver's
12205  * interrupt handler(s) to interrupt vector(s) to device with SLI-3 interface
12206  * spec. Depends on the interrupt mode configured to the driver, the driver
12207  * will try to fallback from the configured interrupt mode to an interrupt
12208  * mode which is supported by the platform, kernel, and device in the order
12209  * of:
12210  * MSI-X -> MSI -> IRQ.
12211  *
12212  * Return codes
12213  *   0 - successful
12214  *   other values - error
12215  **/
12216 static uint32_t
12217 lpfc_sli_enable_intr(struct lpfc_hba *phba, uint32_t cfg_mode)
12218 {
12219 	uint32_t intr_mode = LPFC_INTR_ERROR;
12220 	int retval;
12221 
12222 	/* Need to issue conf_port mbox cmd before conf_msi mbox cmd */
12223 	retval = lpfc_sli_config_port(phba, LPFC_SLI_REV3);
12224 	if (retval)
12225 		return intr_mode;
12226 	phba->hba_flag &= ~HBA_NEEDS_CFG_PORT;
12227 
12228 	if (cfg_mode == 2) {
12229 		/* Now, try to enable MSI-X interrupt mode */
12230 		retval = lpfc_sli_enable_msix(phba);
12231 		if (!retval) {
12232 			/* Indicate initialization to MSI-X mode */
12233 			phba->intr_type = MSIX;
12234 			intr_mode = 2;
12235 		}
12236 	}
12237 
12238 	/* Fallback to MSI if MSI-X initialization failed */
12239 	if (cfg_mode >= 1 && phba->intr_type == NONE) {
12240 		retval = lpfc_sli_enable_msi(phba);
12241 		if (!retval) {
12242 			/* Indicate initialization to MSI mode */
12243 			phba->intr_type = MSI;
12244 			intr_mode = 1;
12245 		}
12246 	}
12247 
12248 	/* Fallback to INTx if both MSI-X/MSI initalization failed */
12249 	if (phba->intr_type == NONE) {
12250 		retval = request_irq(phba->pcidev->irq, lpfc_sli_intr_handler,
12251 				     IRQF_SHARED, LPFC_DRIVER_NAME, phba);
12252 		if (!retval) {
12253 			/* Indicate initialization to INTx mode */
12254 			phba->intr_type = INTx;
12255 			intr_mode = 0;
12256 		}
12257 	}
12258 	return intr_mode;
12259 }
12260 
12261 /**
12262  * lpfc_sli_disable_intr - Disable device interrupt to SLI-3 device.
12263  * @phba: pointer to lpfc hba data structure.
12264  *
12265  * This routine is invoked to disable device interrupt and disassociate the
12266  * driver's interrupt handler(s) from interrupt vector(s) to device with
12267  * SLI-3 interface spec. Depending on the interrupt mode, the driver will
12268  * release the interrupt vector(s) for the message signaled interrupt.
12269  **/
12270 static void
12271 lpfc_sli_disable_intr(struct lpfc_hba *phba)
12272 {
12273 	int nr_irqs, i;
12274 
12275 	if (phba->intr_type == MSIX)
12276 		nr_irqs = LPFC_MSIX_VECTORS;
12277 	else
12278 		nr_irqs = 1;
12279 
12280 	for (i = 0; i < nr_irqs; i++)
12281 		free_irq(pci_irq_vector(phba->pcidev, i), phba);
12282 	pci_free_irq_vectors(phba->pcidev);
12283 
12284 	/* Reset interrupt management states */
12285 	phba->intr_type = NONE;
12286 	phba->sli.slistat.sli_intr = 0;
12287 }
12288 
12289 /**
12290  * lpfc_find_cpu_handle - Find the CPU that corresponds to the specified Queue
12291  * @phba: pointer to lpfc hba data structure.
12292  * @id: EQ vector index or Hardware Queue index
12293  * @match: LPFC_FIND_BY_EQ = match by EQ
12294  *         LPFC_FIND_BY_HDWQ = match by Hardware Queue
12295  * Return the CPU that matches the selection criteria
12296  */
12297 static uint16_t
12298 lpfc_find_cpu_handle(struct lpfc_hba *phba, uint16_t id, int match)
12299 {
12300 	struct lpfc_vector_map_info *cpup;
12301 	int cpu;
12302 
12303 	/* Loop through all CPUs */
12304 	for_each_present_cpu(cpu) {
12305 		cpup = &phba->sli4_hba.cpu_map[cpu];
12306 
12307 		/* If we are matching by EQ, there may be multiple CPUs using
12308 		 * using the same vector, so select the one with
12309 		 * LPFC_CPU_FIRST_IRQ set.
12310 		 */
12311 		if ((match == LPFC_FIND_BY_EQ) &&
12312 		    (cpup->flag & LPFC_CPU_FIRST_IRQ) &&
12313 		    (cpup->eq == id))
12314 			return cpu;
12315 
12316 		/* If matching by HDWQ, select the first CPU that matches */
12317 		if ((match == LPFC_FIND_BY_HDWQ) && (cpup->hdwq == id))
12318 			return cpu;
12319 	}
12320 	return 0;
12321 }
12322 
12323 #ifdef CONFIG_X86
12324 /**
12325  * lpfc_find_hyper - Determine if the CPU map entry is hyper-threaded
12326  * @phba: pointer to lpfc hba data structure.
12327  * @cpu: CPU map index
12328  * @phys_id: CPU package physical id
12329  * @core_id: CPU core id
12330  */
12331 static int
12332 lpfc_find_hyper(struct lpfc_hba *phba, int cpu,
12333 		uint16_t phys_id, uint16_t core_id)
12334 {
12335 	struct lpfc_vector_map_info *cpup;
12336 	int idx;
12337 
12338 	for_each_present_cpu(idx) {
12339 		cpup = &phba->sli4_hba.cpu_map[idx];
12340 		/* Does the cpup match the one we are looking for */
12341 		if ((cpup->phys_id == phys_id) &&
12342 		    (cpup->core_id == core_id) &&
12343 		    (cpu != idx))
12344 			return 1;
12345 	}
12346 	return 0;
12347 }
12348 #endif
12349 
12350 /*
12351  * lpfc_assign_eq_map_info - Assigns eq for vector_map structure
12352  * @phba: pointer to lpfc hba data structure.
12353  * @eqidx: index for eq and irq vector
12354  * @flag: flags to set for vector_map structure
12355  * @cpu: cpu used to index vector_map structure
12356  *
12357  * The routine assigns eq info into vector_map structure
12358  */
12359 static inline void
12360 lpfc_assign_eq_map_info(struct lpfc_hba *phba, uint16_t eqidx, uint16_t flag,
12361 			unsigned int cpu)
12362 {
12363 	struct lpfc_vector_map_info *cpup = &phba->sli4_hba.cpu_map[cpu];
12364 	struct lpfc_hba_eq_hdl *eqhdl = lpfc_get_eq_hdl(eqidx);
12365 
12366 	cpup->eq = eqidx;
12367 	cpup->flag |= flag;
12368 
12369 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12370 			"3336 Set Affinity: CPU %d irq %d eq %d flag x%x\n",
12371 			cpu, eqhdl->irq, cpup->eq, cpup->flag);
12372 }
12373 
12374 /**
12375  * lpfc_cpu_map_array_init - Initialize cpu_map structure
12376  * @phba: pointer to lpfc hba data structure.
12377  *
12378  * The routine initializes the cpu_map array structure
12379  */
12380 static void
12381 lpfc_cpu_map_array_init(struct lpfc_hba *phba)
12382 {
12383 	struct lpfc_vector_map_info *cpup;
12384 	struct lpfc_eq_intr_info *eqi;
12385 	int cpu;
12386 
12387 	for_each_possible_cpu(cpu) {
12388 		cpup = &phba->sli4_hba.cpu_map[cpu];
12389 		cpup->phys_id = LPFC_VECTOR_MAP_EMPTY;
12390 		cpup->core_id = LPFC_VECTOR_MAP_EMPTY;
12391 		cpup->hdwq = LPFC_VECTOR_MAP_EMPTY;
12392 		cpup->eq = LPFC_VECTOR_MAP_EMPTY;
12393 		cpup->flag = 0;
12394 		eqi = per_cpu_ptr(phba->sli4_hba.eq_info, cpu);
12395 		INIT_LIST_HEAD(&eqi->list);
12396 		eqi->icnt = 0;
12397 	}
12398 }
12399 
12400 /**
12401  * lpfc_hba_eq_hdl_array_init - Initialize hba_eq_hdl structure
12402  * @phba: pointer to lpfc hba data structure.
12403  *
12404  * The routine initializes the hba_eq_hdl array structure
12405  */
12406 static void
12407 lpfc_hba_eq_hdl_array_init(struct lpfc_hba *phba)
12408 {
12409 	struct lpfc_hba_eq_hdl *eqhdl;
12410 	int i;
12411 
12412 	for (i = 0; i < phba->cfg_irq_chann; i++) {
12413 		eqhdl = lpfc_get_eq_hdl(i);
12414 		eqhdl->irq = LPFC_VECTOR_MAP_EMPTY;
12415 		eqhdl->phba = phba;
12416 	}
12417 }
12418 
12419 /**
12420  * lpfc_cpu_affinity_check - Check vector CPU affinity mappings
12421  * @phba: pointer to lpfc hba data structure.
12422  * @vectors: number of msix vectors allocated.
12423  *
12424  * The routine will figure out the CPU affinity assignment for every
12425  * MSI-X vector allocated for the HBA.
12426  * In addition, the CPU to IO channel mapping will be calculated
12427  * and the phba->sli4_hba.cpu_map array will reflect this.
12428  */
12429 static void
12430 lpfc_cpu_affinity_check(struct lpfc_hba *phba, int vectors)
12431 {
12432 	int i, cpu, idx, next_idx, new_cpu, start_cpu, first_cpu;
12433 	int max_phys_id, min_phys_id;
12434 	int max_core_id, min_core_id;
12435 	struct lpfc_vector_map_info *cpup;
12436 	struct lpfc_vector_map_info *new_cpup;
12437 #ifdef CONFIG_X86
12438 	struct cpuinfo_x86 *cpuinfo;
12439 #endif
12440 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
12441 	struct lpfc_hdwq_stat *c_stat;
12442 #endif
12443 
12444 	max_phys_id = 0;
12445 	min_phys_id = LPFC_VECTOR_MAP_EMPTY;
12446 	max_core_id = 0;
12447 	min_core_id = LPFC_VECTOR_MAP_EMPTY;
12448 
12449 	/* Update CPU map with physical id and core id of each CPU */
12450 	for_each_present_cpu(cpu) {
12451 		cpup = &phba->sli4_hba.cpu_map[cpu];
12452 #ifdef CONFIG_X86
12453 		cpuinfo = &cpu_data(cpu);
12454 		cpup->phys_id = cpuinfo->phys_proc_id;
12455 		cpup->core_id = cpuinfo->cpu_core_id;
12456 		if (lpfc_find_hyper(phba, cpu, cpup->phys_id, cpup->core_id))
12457 			cpup->flag |= LPFC_CPU_MAP_HYPER;
12458 #else
12459 		/* No distinction between CPUs for other platforms */
12460 		cpup->phys_id = 0;
12461 		cpup->core_id = cpu;
12462 #endif
12463 
12464 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12465 				"3328 CPU %d physid %d coreid %d flag x%x\n",
12466 				cpu, cpup->phys_id, cpup->core_id, cpup->flag);
12467 
12468 		if (cpup->phys_id > max_phys_id)
12469 			max_phys_id = cpup->phys_id;
12470 		if (cpup->phys_id < min_phys_id)
12471 			min_phys_id = cpup->phys_id;
12472 
12473 		if (cpup->core_id > max_core_id)
12474 			max_core_id = cpup->core_id;
12475 		if (cpup->core_id < min_core_id)
12476 			min_core_id = cpup->core_id;
12477 	}
12478 
12479 	/* After looking at each irq vector assigned to this pcidev, its
12480 	 * possible to see that not ALL CPUs have been accounted for.
12481 	 * Next we will set any unassigned (unaffinitized) cpu map
12482 	 * entries to a IRQ on the same phys_id.
12483 	 */
12484 	first_cpu = cpumask_first(cpu_present_mask);
12485 	start_cpu = first_cpu;
12486 
12487 	for_each_present_cpu(cpu) {
12488 		cpup = &phba->sli4_hba.cpu_map[cpu];
12489 
12490 		/* Is this CPU entry unassigned */
12491 		if (cpup->eq == LPFC_VECTOR_MAP_EMPTY) {
12492 			/* Mark CPU as IRQ not assigned by the kernel */
12493 			cpup->flag |= LPFC_CPU_MAP_UNASSIGN;
12494 
12495 			/* If so, find a new_cpup thats on the the SAME
12496 			 * phys_id as cpup. start_cpu will start where we
12497 			 * left off so all unassigned entries don't get assgined
12498 			 * the IRQ of the first entry.
12499 			 */
12500 			new_cpu = start_cpu;
12501 			for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12502 				new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12503 				if (!(new_cpup->flag & LPFC_CPU_MAP_UNASSIGN) &&
12504 				    (new_cpup->eq != LPFC_VECTOR_MAP_EMPTY) &&
12505 				    (new_cpup->phys_id == cpup->phys_id))
12506 					goto found_same;
12507 				new_cpu = cpumask_next(
12508 					new_cpu, cpu_present_mask);
12509 				if (new_cpu == nr_cpumask_bits)
12510 					new_cpu = first_cpu;
12511 			}
12512 			/* At this point, we leave the CPU as unassigned */
12513 			continue;
12514 found_same:
12515 			/* We found a matching phys_id, so copy the IRQ info */
12516 			cpup->eq = new_cpup->eq;
12517 
12518 			/* Bump start_cpu to the next slot to minmize the
12519 			 * chance of having multiple unassigned CPU entries
12520 			 * selecting the same IRQ.
12521 			 */
12522 			start_cpu = cpumask_next(new_cpu, cpu_present_mask);
12523 			if (start_cpu == nr_cpumask_bits)
12524 				start_cpu = first_cpu;
12525 
12526 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12527 					"3337 Set Affinity: CPU %d "
12528 					"eq %d from peer cpu %d same "
12529 					"phys_id (%d)\n",
12530 					cpu, cpup->eq, new_cpu,
12531 					cpup->phys_id);
12532 		}
12533 	}
12534 
12535 	/* Set any unassigned cpu map entries to a IRQ on any phys_id */
12536 	start_cpu = first_cpu;
12537 
12538 	for_each_present_cpu(cpu) {
12539 		cpup = &phba->sli4_hba.cpu_map[cpu];
12540 
12541 		/* Is this entry unassigned */
12542 		if (cpup->eq == LPFC_VECTOR_MAP_EMPTY) {
12543 			/* Mark it as IRQ not assigned by the kernel */
12544 			cpup->flag |= LPFC_CPU_MAP_UNASSIGN;
12545 
12546 			/* If so, find a new_cpup thats on ANY phys_id
12547 			 * as the cpup. start_cpu will start where we
12548 			 * left off so all unassigned entries don't get
12549 			 * assigned the IRQ of the first entry.
12550 			 */
12551 			new_cpu = start_cpu;
12552 			for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12553 				new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12554 				if (!(new_cpup->flag & LPFC_CPU_MAP_UNASSIGN) &&
12555 				    (new_cpup->eq != LPFC_VECTOR_MAP_EMPTY))
12556 					goto found_any;
12557 				new_cpu = cpumask_next(
12558 					new_cpu, cpu_present_mask);
12559 				if (new_cpu == nr_cpumask_bits)
12560 					new_cpu = first_cpu;
12561 			}
12562 			/* We should never leave an entry unassigned */
12563 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12564 					"3339 Set Affinity: CPU %d "
12565 					"eq %d UNASSIGNED\n",
12566 					cpup->hdwq, cpup->eq);
12567 			continue;
12568 found_any:
12569 			/* We found an available entry, copy the IRQ info */
12570 			cpup->eq = new_cpup->eq;
12571 
12572 			/* Bump start_cpu to the next slot to minmize the
12573 			 * chance of having multiple unassigned CPU entries
12574 			 * selecting the same IRQ.
12575 			 */
12576 			start_cpu = cpumask_next(new_cpu, cpu_present_mask);
12577 			if (start_cpu == nr_cpumask_bits)
12578 				start_cpu = first_cpu;
12579 
12580 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12581 					"3338 Set Affinity: CPU %d "
12582 					"eq %d from peer cpu %d (%d/%d)\n",
12583 					cpu, cpup->eq, new_cpu,
12584 					new_cpup->phys_id, new_cpup->core_id);
12585 		}
12586 	}
12587 
12588 	/* Assign hdwq indices that are unique across all cpus in the map
12589 	 * that are also FIRST_CPUs.
12590 	 */
12591 	idx = 0;
12592 	for_each_present_cpu(cpu) {
12593 		cpup = &phba->sli4_hba.cpu_map[cpu];
12594 
12595 		/* Only FIRST IRQs get a hdwq index assignment. */
12596 		if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
12597 			continue;
12598 
12599 		/* 1 to 1, the first LPFC_CPU_FIRST_IRQ cpus to a unique hdwq */
12600 		cpup->hdwq = idx;
12601 		idx++;
12602 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12603 				"3333 Set Affinity: CPU %d (phys %d core %d): "
12604 				"hdwq %d eq %d flg x%x\n",
12605 				cpu, cpup->phys_id, cpup->core_id,
12606 				cpup->hdwq, cpup->eq, cpup->flag);
12607 	}
12608 	/* Associate a hdwq with each cpu_map entry
12609 	 * This will be 1 to 1 - hdwq to cpu, unless there are less
12610 	 * hardware queues then CPUs. For that case we will just round-robin
12611 	 * the available hardware queues as they get assigned to CPUs.
12612 	 * The next_idx is the idx from the FIRST_CPU loop above to account
12613 	 * for irq_chann < hdwq.  The idx is used for round-robin assignments
12614 	 * and needs to start at 0.
12615 	 */
12616 	next_idx = idx;
12617 	start_cpu = 0;
12618 	idx = 0;
12619 	for_each_present_cpu(cpu) {
12620 		cpup = &phba->sli4_hba.cpu_map[cpu];
12621 
12622 		/* FIRST cpus are already mapped. */
12623 		if (cpup->flag & LPFC_CPU_FIRST_IRQ)
12624 			continue;
12625 
12626 		/* If the cfg_irq_chann < cfg_hdw_queue, set the hdwq
12627 		 * of the unassigned cpus to the next idx so that all
12628 		 * hdw queues are fully utilized.
12629 		 */
12630 		if (next_idx < phba->cfg_hdw_queue) {
12631 			cpup->hdwq = next_idx;
12632 			next_idx++;
12633 			continue;
12634 		}
12635 
12636 		/* Not a First CPU and all hdw_queues are used.  Reuse a
12637 		 * Hardware Queue for another CPU, so be smart about it
12638 		 * and pick one that has its IRQ/EQ mapped to the same phys_id
12639 		 * (CPU package) and core_id.
12640 		 */
12641 		new_cpu = start_cpu;
12642 		for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12643 			new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12644 			if (new_cpup->hdwq != LPFC_VECTOR_MAP_EMPTY &&
12645 			    new_cpup->phys_id == cpup->phys_id &&
12646 			    new_cpup->core_id == cpup->core_id) {
12647 				goto found_hdwq;
12648 			}
12649 			new_cpu = cpumask_next(new_cpu, cpu_present_mask);
12650 			if (new_cpu == nr_cpumask_bits)
12651 				new_cpu = first_cpu;
12652 		}
12653 
12654 		/* If we can't match both phys_id and core_id,
12655 		 * settle for just a phys_id match.
12656 		 */
12657 		new_cpu = start_cpu;
12658 		for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12659 			new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12660 			if (new_cpup->hdwq != LPFC_VECTOR_MAP_EMPTY &&
12661 			    new_cpup->phys_id == cpup->phys_id)
12662 				goto found_hdwq;
12663 
12664 			new_cpu = cpumask_next(new_cpu, cpu_present_mask);
12665 			if (new_cpu == nr_cpumask_bits)
12666 				new_cpu = first_cpu;
12667 		}
12668 
12669 		/* Otherwise just round robin on cfg_hdw_queue */
12670 		cpup->hdwq = idx % phba->cfg_hdw_queue;
12671 		idx++;
12672 		goto logit;
12673  found_hdwq:
12674 		/* We found an available entry, copy the IRQ info */
12675 		start_cpu = cpumask_next(new_cpu, cpu_present_mask);
12676 		if (start_cpu == nr_cpumask_bits)
12677 			start_cpu = first_cpu;
12678 		cpup->hdwq = new_cpup->hdwq;
12679  logit:
12680 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12681 				"3335 Set Affinity: CPU %d (phys %d core %d): "
12682 				"hdwq %d eq %d flg x%x\n",
12683 				cpu, cpup->phys_id, cpup->core_id,
12684 				cpup->hdwq, cpup->eq, cpup->flag);
12685 	}
12686 
12687 	/*
12688 	 * Initialize the cpu_map slots for not-present cpus in case
12689 	 * a cpu is hot-added. Perform a simple hdwq round robin assignment.
12690 	 */
12691 	idx = 0;
12692 	for_each_possible_cpu(cpu) {
12693 		cpup = &phba->sli4_hba.cpu_map[cpu];
12694 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
12695 		c_stat = per_cpu_ptr(phba->sli4_hba.c_stat, cpu);
12696 		c_stat->hdwq_no = cpup->hdwq;
12697 #endif
12698 		if (cpup->hdwq != LPFC_VECTOR_MAP_EMPTY)
12699 			continue;
12700 
12701 		cpup->hdwq = idx++ % phba->cfg_hdw_queue;
12702 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
12703 		c_stat->hdwq_no = cpup->hdwq;
12704 #endif
12705 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12706 				"3340 Set Affinity: not present "
12707 				"CPU %d hdwq %d\n",
12708 				cpu, cpup->hdwq);
12709 	}
12710 
12711 	/* The cpu_map array will be used later during initialization
12712 	 * when EQ / CQ / WQs are allocated and configured.
12713 	 */
12714 	return;
12715 }
12716 
12717 /**
12718  * lpfc_cpuhp_get_eq
12719  *
12720  * @phba:   pointer to lpfc hba data structure.
12721  * @cpu:    cpu going offline
12722  * @eqlist: eq list to append to
12723  */
12724 static int
12725 lpfc_cpuhp_get_eq(struct lpfc_hba *phba, unsigned int cpu,
12726 		  struct list_head *eqlist)
12727 {
12728 	const struct cpumask *maskp;
12729 	struct lpfc_queue *eq;
12730 	struct cpumask *tmp;
12731 	u16 idx;
12732 
12733 	tmp = kzalloc(cpumask_size(), GFP_KERNEL);
12734 	if (!tmp)
12735 		return -ENOMEM;
12736 
12737 	for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
12738 		maskp = pci_irq_get_affinity(phba->pcidev, idx);
12739 		if (!maskp)
12740 			continue;
12741 		/*
12742 		 * if irq is not affinitized to the cpu going
12743 		 * then we don't need to poll the eq attached
12744 		 * to it.
12745 		 */
12746 		if (!cpumask_and(tmp, maskp, cpumask_of(cpu)))
12747 			continue;
12748 		/* get the cpus that are online and are affini-
12749 		 * tized to this irq vector.  If the count is
12750 		 * more than 1 then cpuhp is not going to shut-
12751 		 * down this vector.  Since this cpu has not
12752 		 * gone offline yet, we need >1.
12753 		 */
12754 		cpumask_and(tmp, maskp, cpu_online_mask);
12755 		if (cpumask_weight(tmp) > 1)
12756 			continue;
12757 
12758 		/* Now that we have an irq to shutdown, get the eq
12759 		 * mapped to this irq.  Note: multiple hdwq's in
12760 		 * the software can share an eq, but eventually
12761 		 * only eq will be mapped to this vector
12762 		 */
12763 		eq = phba->sli4_hba.hba_eq_hdl[idx].eq;
12764 		list_add(&eq->_poll_list, eqlist);
12765 	}
12766 	kfree(tmp);
12767 	return 0;
12768 }
12769 
12770 static void __lpfc_cpuhp_remove(struct lpfc_hba *phba)
12771 {
12772 	if (phba->sli_rev != LPFC_SLI_REV4)
12773 		return;
12774 
12775 	cpuhp_state_remove_instance_nocalls(lpfc_cpuhp_state,
12776 					    &phba->cpuhp);
12777 	/*
12778 	 * unregistering the instance doesn't stop the polling
12779 	 * timer. Wait for the poll timer to retire.
12780 	 */
12781 	synchronize_rcu();
12782 	del_timer_sync(&phba->cpuhp_poll_timer);
12783 }
12784 
12785 static void lpfc_cpuhp_remove(struct lpfc_hba *phba)
12786 {
12787 	if (phba->pport->fc_flag & FC_OFFLINE_MODE)
12788 		return;
12789 
12790 	__lpfc_cpuhp_remove(phba);
12791 }
12792 
12793 static void lpfc_cpuhp_add(struct lpfc_hba *phba)
12794 {
12795 	if (phba->sli_rev != LPFC_SLI_REV4)
12796 		return;
12797 
12798 	rcu_read_lock();
12799 
12800 	if (!list_empty(&phba->poll_list))
12801 		mod_timer(&phba->cpuhp_poll_timer,
12802 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
12803 
12804 	rcu_read_unlock();
12805 
12806 	cpuhp_state_add_instance_nocalls(lpfc_cpuhp_state,
12807 					 &phba->cpuhp);
12808 }
12809 
12810 static int __lpfc_cpuhp_checks(struct lpfc_hba *phba, int *retval)
12811 {
12812 	if (phba->pport->load_flag & FC_UNLOADING) {
12813 		*retval = -EAGAIN;
12814 		return true;
12815 	}
12816 
12817 	if (phba->sli_rev != LPFC_SLI_REV4) {
12818 		*retval = 0;
12819 		return true;
12820 	}
12821 
12822 	/* proceed with the hotplug */
12823 	return false;
12824 }
12825 
12826 /**
12827  * lpfc_irq_set_aff - set IRQ affinity
12828  * @eqhdl: EQ handle
12829  * @cpu: cpu to set affinity
12830  *
12831  **/
12832 static inline void
12833 lpfc_irq_set_aff(struct lpfc_hba_eq_hdl *eqhdl, unsigned int cpu)
12834 {
12835 	cpumask_clear(&eqhdl->aff_mask);
12836 	cpumask_set_cpu(cpu, &eqhdl->aff_mask);
12837 	irq_set_status_flags(eqhdl->irq, IRQ_NO_BALANCING);
12838 	irq_set_affinity(eqhdl->irq, &eqhdl->aff_mask);
12839 }
12840 
12841 /**
12842  * lpfc_irq_clear_aff - clear IRQ affinity
12843  * @eqhdl: EQ handle
12844  *
12845  **/
12846 static inline void
12847 lpfc_irq_clear_aff(struct lpfc_hba_eq_hdl *eqhdl)
12848 {
12849 	cpumask_clear(&eqhdl->aff_mask);
12850 	irq_clear_status_flags(eqhdl->irq, IRQ_NO_BALANCING);
12851 }
12852 
12853 /**
12854  * lpfc_irq_rebalance - rebalances IRQ affinity according to cpuhp event
12855  * @phba: pointer to HBA context object.
12856  * @cpu: cpu going offline/online
12857  * @offline: true, cpu is going offline. false, cpu is coming online.
12858  *
12859  * If cpu is going offline, we'll try our best effort to find the next
12860  * online cpu on the phba's original_mask and migrate all offlining IRQ
12861  * affinities.
12862  *
12863  * If cpu is coming online, reaffinitize the IRQ back to the onlining cpu.
12864  *
12865  * Note: Call only if NUMA or NHT mode is enabled, otherwise rely on
12866  *	 PCI_IRQ_AFFINITY to auto-manage IRQ affinity.
12867  *
12868  **/
12869 static void
12870 lpfc_irq_rebalance(struct lpfc_hba *phba, unsigned int cpu, bool offline)
12871 {
12872 	struct lpfc_vector_map_info *cpup;
12873 	struct cpumask *aff_mask;
12874 	unsigned int cpu_select, cpu_next, idx;
12875 	const struct cpumask *orig_mask;
12876 
12877 	if (phba->irq_chann_mode == NORMAL_MODE)
12878 		return;
12879 
12880 	orig_mask = &phba->sli4_hba.irq_aff_mask;
12881 
12882 	if (!cpumask_test_cpu(cpu, orig_mask))
12883 		return;
12884 
12885 	cpup = &phba->sli4_hba.cpu_map[cpu];
12886 
12887 	if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
12888 		return;
12889 
12890 	if (offline) {
12891 		/* Find next online CPU on original mask */
12892 		cpu_next = cpumask_next_wrap(cpu, orig_mask, cpu, true);
12893 		cpu_select = lpfc_next_online_cpu(orig_mask, cpu_next);
12894 
12895 		/* Found a valid CPU */
12896 		if ((cpu_select < nr_cpu_ids) && (cpu_select != cpu)) {
12897 			/* Go through each eqhdl and ensure offlining
12898 			 * cpu aff_mask is migrated
12899 			 */
12900 			for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
12901 				aff_mask = lpfc_get_aff_mask(idx);
12902 
12903 				/* Migrate affinity */
12904 				if (cpumask_test_cpu(cpu, aff_mask))
12905 					lpfc_irq_set_aff(lpfc_get_eq_hdl(idx),
12906 							 cpu_select);
12907 			}
12908 		} else {
12909 			/* Rely on irqbalance if no online CPUs left on NUMA */
12910 			for (idx = 0; idx < phba->cfg_irq_chann; idx++)
12911 				lpfc_irq_clear_aff(lpfc_get_eq_hdl(idx));
12912 		}
12913 	} else {
12914 		/* Migrate affinity back to this CPU */
12915 		lpfc_irq_set_aff(lpfc_get_eq_hdl(cpup->eq), cpu);
12916 	}
12917 }
12918 
12919 static int lpfc_cpu_offline(unsigned int cpu, struct hlist_node *node)
12920 {
12921 	struct lpfc_hba *phba = hlist_entry_safe(node, struct lpfc_hba, cpuhp);
12922 	struct lpfc_queue *eq, *next;
12923 	LIST_HEAD(eqlist);
12924 	int retval;
12925 
12926 	if (!phba) {
12927 		WARN_ONCE(!phba, "cpu: %u. phba:NULL", raw_smp_processor_id());
12928 		return 0;
12929 	}
12930 
12931 	if (__lpfc_cpuhp_checks(phba, &retval))
12932 		return retval;
12933 
12934 	lpfc_irq_rebalance(phba, cpu, true);
12935 
12936 	retval = lpfc_cpuhp_get_eq(phba, cpu, &eqlist);
12937 	if (retval)
12938 		return retval;
12939 
12940 	/* start polling on these eq's */
12941 	list_for_each_entry_safe(eq, next, &eqlist, _poll_list) {
12942 		list_del_init(&eq->_poll_list);
12943 		lpfc_sli4_start_polling(eq);
12944 	}
12945 
12946 	return 0;
12947 }
12948 
12949 static int lpfc_cpu_online(unsigned int cpu, struct hlist_node *node)
12950 {
12951 	struct lpfc_hba *phba = hlist_entry_safe(node, struct lpfc_hba, cpuhp);
12952 	struct lpfc_queue *eq, *next;
12953 	unsigned int n;
12954 	int retval;
12955 
12956 	if (!phba) {
12957 		WARN_ONCE(!phba, "cpu: %u. phba:NULL", raw_smp_processor_id());
12958 		return 0;
12959 	}
12960 
12961 	if (__lpfc_cpuhp_checks(phba, &retval))
12962 		return retval;
12963 
12964 	lpfc_irq_rebalance(phba, cpu, false);
12965 
12966 	list_for_each_entry_safe(eq, next, &phba->poll_list, _poll_list) {
12967 		n = lpfc_find_cpu_handle(phba, eq->hdwq, LPFC_FIND_BY_HDWQ);
12968 		if (n == cpu)
12969 			lpfc_sli4_stop_polling(eq);
12970 	}
12971 
12972 	return 0;
12973 }
12974 
12975 /**
12976  * lpfc_sli4_enable_msix - Enable MSI-X interrupt mode to SLI-4 device
12977  * @phba: pointer to lpfc hba data structure.
12978  *
12979  * This routine is invoked to enable the MSI-X interrupt vectors to device
12980  * with SLI-4 interface spec.  It also allocates MSI-X vectors and maps them
12981  * to cpus on the system.
12982  *
12983  * When cfg_irq_numa is enabled, the adapter will only allocate vectors for
12984  * the number of cpus on the same numa node as this adapter.  The vectors are
12985  * allocated without requesting OS affinity mapping.  A vector will be
12986  * allocated and assigned to each online and offline cpu.  If the cpu is
12987  * online, then affinity will be set to that cpu.  If the cpu is offline, then
12988  * affinity will be set to the nearest peer cpu within the numa node that is
12989  * online.  If there are no online cpus within the numa node, affinity is not
12990  * assigned and the OS may do as it pleases. Note: cpu vector affinity mapping
12991  * is consistent with the way cpu online/offline is handled when cfg_irq_numa is
12992  * configured.
12993  *
12994  * If numa mode is not enabled and there is more than 1 vector allocated, then
12995  * the driver relies on the managed irq interface where the OS assigns vector to
12996  * cpu affinity.  The driver will then use that affinity mapping to setup its
12997  * cpu mapping table.
12998  *
12999  * Return codes
13000  * 0 - successful
13001  * other values - error
13002  **/
13003 static int
13004 lpfc_sli4_enable_msix(struct lpfc_hba *phba)
13005 {
13006 	int vectors, rc, index;
13007 	char *name;
13008 	const struct cpumask *aff_mask = NULL;
13009 	unsigned int cpu = 0, cpu_cnt = 0, cpu_select = nr_cpu_ids;
13010 	struct lpfc_vector_map_info *cpup;
13011 	struct lpfc_hba_eq_hdl *eqhdl;
13012 	const struct cpumask *maskp;
13013 	unsigned int flags = PCI_IRQ_MSIX;
13014 
13015 	/* Set up MSI-X multi-message vectors */
13016 	vectors = phba->cfg_irq_chann;
13017 
13018 	if (phba->irq_chann_mode != NORMAL_MODE)
13019 		aff_mask = &phba->sli4_hba.irq_aff_mask;
13020 
13021 	if (aff_mask) {
13022 		cpu_cnt = cpumask_weight(aff_mask);
13023 		vectors = min(phba->cfg_irq_chann, cpu_cnt);
13024 
13025 		/* cpu: iterates over aff_mask including offline or online
13026 		 * cpu_select: iterates over online aff_mask to set affinity
13027 		 */
13028 		cpu = cpumask_first(aff_mask);
13029 		cpu_select = lpfc_next_online_cpu(aff_mask, cpu);
13030 	} else {
13031 		flags |= PCI_IRQ_AFFINITY;
13032 	}
13033 
13034 	rc = pci_alloc_irq_vectors(phba->pcidev, 1, vectors, flags);
13035 	if (rc < 0) {
13036 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13037 				"0484 PCI enable MSI-X failed (%d)\n", rc);
13038 		goto vec_fail_out;
13039 	}
13040 	vectors = rc;
13041 
13042 	/* Assign MSI-X vectors to interrupt handlers */
13043 	for (index = 0; index < vectors; index++) {
13044 		eqhdl = lpfc_get_eq_hdl(index);
13045 		name = eqhdl->handler_name;
13046 		memset(name, 0, LPFC_SLI4_HANDLER_NAME_SZ);
13047 		snprintf(name, LPFC_SLI4_HANDLER_NAME_SZ,
13048 			 LPFC_DRIVER_HANDLER_NAME"%d", index);
13049 
13050 		eqhdl->idx = index;
13051 		rc = request_irq(pci_irq_vector(phba->pcidev, index),
13052 			 &lpfc_sli4_hba_intr_handler, 0,
13053 			 name, eqhdl);
13054 		if (rc) {
13055 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13056 					"0486 MSI-X fast-path (%d) "
13057 					"request_irq failed (%d)\n", index, rc);
13058 			goto cfg_fail_out;
13059 		}
13060 
13061 		eqhdl->irq = pci_irq_vector(phba->pcidev, index);
13062 
13063 		if (aff_mask) {
13064 			/* If found a neighboring online cpu, set affinity */
13065 			if (cpu_select < nr_cpu_ids)
13066 				lpfc_irq_set_aff(eqhdl, cpu_select);
13067 
13068 			/* Assign EQ to cpu_map */
13069 			lpfc_assign_eq_map_info(phba, index,
13070 						LPFC_CPU_FIRST_IRQ,
13071 						cpu);
13072 
13073 			/* Iterate to next offline or online cpu in aff_mask */
13074 			cpu = cpumask_next(cpu, aff_mask);
13075 
13076 			/* Find next online cpu in aff_mask to set affinity */
13077 			cpu_select = lpfc_next_online_cpu(aff_mask, cpu);
13078 		} else if (vectors == 1) {
13079 			cpu = cpumask_first(cpu_present_mask);
13080 			lpfc_assign_eq_map_info(phba, index, LPFC_CPU_FIRST_IRQ,
13081 						cpu);
13082 		} else {
13083 			maskp = pci_irq_get_affinity(phba->pcidev, index);
13084 
13085 			/* Loop through all CPUs associated with vector index */
13086 			for_each_cpu_and(cpu, maskp, cpu_present_mask) {
13087 				cpup = &phba->sli4_hba.cpu_map[cpu];
13088 
13089 				/* If this is the first CPU thats assigned to
13090 				 * this vector, set LPFC_CPU_FIRST_IRQ.
13091 				 *
13092 				 * With certain platforms its possible that irq
13093 				 * vectors are affinitized to all the cpu's.
13094 				 * This can result in each cpu_map.eq to be set
13095 				 * to the last vector, resulting in overwrite
13096 				 * of all the previous cpu_map.eq.  Ensure that
13097 				 * each vector receives a place in cpu_map.
13098 				 * Later call to lpfc_cpu_affinity_check will
13099 				 * ensure we are nicely balanced out.
13100 				 */
13101 				if (cpup->eq != LPFC_VECTOR_MAP_EMPTY)
13102 					continue;
13103 				lpfc_assign_eq_map_info(phba, index,
13104 							LPFC_CPU_FIRST_IRQ,
13105 							cpu);
13106 				break;
13107 			}
13108 		}
13109 	}
13110 
13111 	if (vectors != phba->cfg_irq_chann) {
13112 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13113 				"3238 Reducing IO channels to match number of "
13114 				"MSI-X vectors, requested %d got %d\n",
13115 				phba->cfg_irq_chann, vectors);
13116 		if (phba->cfg_irq_chann > vectors)
13117 			phba->cfg_irq_chann = vectors;
13118 	}
13119 
13120 	return rc;
13121 
13122 cfg_fail_out:
13123 	/* free the irq already requested */
13124 	for (--index; index >= 0; index--) {
13125 		eqhdl = lpfc_get_eq_hdl(index);
13126 		lpfc_irq_clear_aff(eqhdl);
13127 		free_irq(eqhdl->irq, eqhdl);
13128 	}
13129 
13130 	/* Unconfigure MSI-X capability structure */
13131 	pci_free_irq_vectors(phba->pcidev);
13132 
13133 vec_fail_out:
13134 	return rc;
13135 }
13136 
13137 /**
13138  * lpfc_sli4_enable_msi - Enable MSI interrupt mode to SLI-4 device
13139  * @phba: pointer to lpfc hba data structure.
13140  *
13141  * This routine is invoked to enable the MSI interrupt mode to device with
13142  * SLI-4 interface spec. The kernel function pci_alloc_irq_vectors() is
13143  * called to enable the MSI vector. The device driver is responsible for
13144  * calling the request_irq() to register MSI vector with a interrupt the
13145  * handler, which is done in this function.
13146  *
13147  * Return codes
13148  * 	0 - successful
13149  * 	other values - error
13150  **/
13151 static int
13152 lpfc_sli4_enable_msi(struct lpfc_hba *phba)
13153 {
13154 	int rc, index;
13155 	unsigned int cpu;
13156 	struct lpfc_hba_eq_hdl *eqhdl;
13157 
13158 	rc = pci_alloc_irq_vectors(phba->pcidev, 1, 1,
13159 				   PCI_IRQ_MSI | PCI_IRQ_AFFINITY);
13160 	if (rc > 0)
13161 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13162 				"0487 PCI enable MSI mode success.\n");
13163 	else {
13164 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13165 				"0488 PCI enable MSI mode failed (%d)\n", rc);
13166 		return rc ? rc : -1;
13167 	}
13168 
13169 	rc = request_irq(phba->pcidev->irq, lpfc_sli4_intr_handler,
13170 			 0, LPFC_DRIVER_NAME, phba);
13171 	if (rc) {
13172 		pci_free_irq_vectors(phba->pcidev);
13173 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13174 				"0490 MSI request_irq failed (%d)\n", rc);
13175 		return rc;
13176 	}
13177 
13178 	eqhdl = lpfc_get_eq_hdl(0);
13179 	eqhdl->irq = pci_irq_vector(phba->pcidev, 0);
13180 
13181 	cpu = cpumask_first(cpu_present_mask);
13182 	lpfc_assign_eq_map_info(phba, 0, LPFC_CPU_FIRST_IRQ, cpu);
13183 
13184 	for (index = 0; index < phba->cfg_irq_chann; index++) {
13185 		eqhdl = lpfc_get_eq_hdl(index);
13186 		eqhdl->idx = index;
13187 	}
13188 
13189 	return 0;
13190 }
13191 
13192 /**
13193  * lpfc_sli4_enable_intr - Enable device interrupt to SLI-4 device
13194  * @phba: pointer to lpfc hba data structure.
13195  * @cfg_mode: Interrupt configuration mode (INTx, MSI or MSI-X).
13196  *
13197  * This routine is invoked to enable device interrupt and associate driver's
13198  * interrupt handler(s) to interrupt vector(s) to device with SLI-4
13199  * interface spec. Depends on the interrupt mode configured to the driver,
13200  * the driver will try to fallback from the configured interrupt mode to an
13201  * interrupt mode which is supported by the platform, kernel, and device in
13202  * the order of:
13203  * MSI-X -> MSI -> IRQ.
13204  *
13205  * Return codes
13206  * 	0 - successful
13207  * 	other values - error
13208  **/
13209 static uint32_t
13210 lpfc_sli4_enable_intr(struct lpfc_hba *phba, uint32_t cfg_mode)
13211 {
13212 	uint32_t intr_mode = LPFC_INTR_ERROR;
13213 	int retval, idx;
13214 
13215 	if (cfg_mode == 2) {
13216 		/* Preparation before conf_msi mbox cmd */
13217 		retval = 0;
13218 		if (!retval) {
13219 			/* Now, try to enable MSI-X interrupt mode */
13220 			retval = lpfc_sli4_enable_msix(phba);
13221 			if (!retval) {
13222 				/* Indicate initialization to MSI-X mode */
13223 				phba->intr_type = MSIX;
13224 				intr_mode = 2;
13225 			}
13226 		}
13227 	}
13228 
13229 	/* Fallback to MSI if MSI-X initialization failed */
13230 	if (cfg_mode >= 1 && phba->intr_type == NONE) {
13231 		retval = lpfc_sli4_enable_msi(phba);
13232 		if (!retval) {
13233 			/* Indicate initialization to MSI mode */
13234 			phba->intr_type = MSI;
13235 			intr_mode = 1;
13236 		}
13237 	}
13238 
13239 	/* Fallback to INTx if both MSI-X/MSI initalization failed */
13240 	if (phba->intr_type == NONE) {
13241 		retval = request_irq(phba->pcidev->irq, lpfc_sli4_intr_handler,
13242 				     IRQF_SHARED, LPFC_DRIVER_NAME, phba);
13243 		if (!retval) {
13244 			struct lpfc_hba_eq_hdl *eqhdl;
13245 			unsigned int cpu;
13246 
13247 			/* Indicate initialization to INTx mode */
13248 			phba->intr_type = INTx;
13249 			intr_mode = 0;
13250 
13251 			eqhdl = lpfc_get_eq_hdl(0);
13252 			eqhdl->irq = pci_irq_vector(phba->pcidev, 0);
13253 
13254 			cpu = cpumask_first(cpu_present_mask);
13255 			lpfc_assign_eq_map_info(phba, 0, LPFC_CPU_FIRST_IRQ,
13256 						cpu);
13257 			for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
13258 				eqhdl = lpfc_get_eq_hdl(idx);
13259 				eqhdl->idx = idx;
13260 			}
13261 		}
13262 	}
13263 	return intr_mode;
13264 }
13265 
13266 /**
13267  * lpfc_sli4_disable_intr - Disable device interrupt to SLI-4 device
13268  * @phba: pointer to lpfc hba data structure.
13269  *
13270  * This routine is invoked to disable device interrupt and disassociate
13271  * the driver's interrupt handler(s) from interrupt vector(s) to device
13272  * with SLI-4 interface spec. Depending on the interrupt mode, the driver
13273  * will release the interrupt vector(s) for the message signaled interrupt.
13274  **/
13275 static void
13276 lpfc_sli4_disable_intr(struct lpfc_hba *phba)
13277 {
13278 	/* Disable the currently initialized interrupt mode */
13279 	if (phba->intr_type == MSIX) {
13280 		int index;
13281 		struct lpfc_hba_eq_hdl *eqhdl;
13282 
13283 		/* Free up MSI-X multi-message vectors */
13284 		for (index = 0; index < phba->cfg_irq_chann; index++) {
13285 			eqhdl = lpfc_get_eq_hdl(index);
13286 			lpfc_irq_clear_aff(eqhdl);
13287 			free_irq(eqhdl->irq, eqhdl);
13288 		}
13289 	} else {
13290 		free_irq(phba->pcidev->irq, phba);
13291 	}
13292 
13293 	pci_free_irq_vectors(phba->pcidev);
13294 
13295 	/* Reset interrupt management states */
13296 	phba->intr_type = NONE;
13297 	phba->sli.slistat.sli_intr = 0;
13298 }
13299 
13300 /**
13301  * lpfc_unset_hba - Unset SLI3 hba device initialization
13302  * @phba: pointer to lpfc hba data structure.
13303  *
13304  * This routine is invoked to unset the HBA device initialization steps to
13305  * a device with SLI-3 interface spec.
13306  **/
13307 static void
13308 lpfc_unset_hba(struct lpfc_hba *phba)
13309 {
13310 	struct lpfc_vport *vport = phba->pport;
13311 	struct Scsi_Host  *shost = lpfc_shost_from_vport(vport);
13312 
13313 	spin_lock_irq(shost->host_lock);
13314 	vport->load_flag |= FC_UNLOADING;
13315 	spin_unlock_irq(shost->host_lock);
13316 
13317 	kfree(phba->vpi_bmask);
13318 	kfree(phba->vpi_ids);
13319 
13320 	lpfc_stop_hba_timers(phba);
13321 
13322 	phba->pport->work_port_events = 0;
13323 
13324 	lpfc_sli_hba_down(phba);
13325 
13326 	lpfc_sli_brdrestart(phba);
13327 
13328 	lpfc_sli_disable_intr(phba);
13329 
13330 	return;
13331 }
13332 
13333 /**
13334  * lpfc_sli4_xri_exchange_busy_wait - Wait for device XRI exchange busy
13335  * @phba: Pointer to HBA context object.
13336  *
13337  * This function is called in the SLI4 code path to wait for completion
13338  * of device's XRIs exchange busy. It will check the XRI exchange busy
13339  * on outstanding FCP and ELS I/Os every 10ms for up to 10 seconds; after
13340  * that, it will check the XRI exchange busy on outstanding FCP and ELS
13341  * I/Os every 30 seconds, log error message, and wait forever. Only when
13342  * all XRI exchange busy complete, the driver unload shall proceed with
13343  * invoking the function reset ioctl mailbox command to the CNA and the
13344  * the rest of the driver unload resource release.
13345  **/
13346 static void
13347 lpfc_sli4_xri_exchange_busy_wait(struct lpfc_hba *phba)
13348 {
13349 	struct lpfc_sli4_hdw_queue *qp;
13350 	int idx, ccnt;
13351 	int wait_time = 0;
13352 	int io_xri_cmpl = 1;
13353 	int nvmet_xri_cmpl = 1;
13354 	int els_xri_cmpl = list_empty(&phba->sli4_hba.lpfc_abts_els_sgl_list);
13355 
13356 	/* Driver just aborted IOs during the hba_unset process.  Pause
13357 	 * here to give the HBA time to complete the IO and get entries
13358 	 * into the abts lists.
13359 	 */
13360 	msleep(LPFC_XRI_EXCH_BUSY_WAIT_T1 * 5);
13361 
13362 	/* Wait for NVME pending IO to flush back to transport. */
13363 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
13364 		lpfc_nvme_wait_for_io_drain(phba);
13365 
13366 	ccnt = 0;
13367 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
13368 		qp = &phba->sli4_hba.hdwq[idx];
13369 		io_xri_cmpl = list_empty(&qp->lpfc_abts_io_buf_list);
13370 		if (!io_xri_cmpl) /* if list is NOT empty */
13371 			ccnt++;
13372 	}
13373 	if (ccnt)
13374 		io_xri_cmpl = 0;
13375 
13376 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13377 		nvmet_xri_cmpl =
13378 			list_empty(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
13379 	}
13380 
13381 	while (!els_xri_cmpl || !io_xri_cmpl || !nvmet_xri_cmpl) {
13382 		if (wait_time > LPFC_XRI_EXCH_BUSY_WAIT_TMO) {
13383 			if (!nvmet_xri_cmpl)
13384 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13385 						"6424 NVMET XRI exchange busy "
13386 						"wait time: %d seconds.\n",
13387 						wait_time/1000);
13388 			if (!io_xri_cmpl)
13389 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13390 						"6100 IO XRI exchange busy "
13391 						"wait time: %d seconds.\n",
13392 						wait_time/1000);
13393 			if (!els_xri_cmpl)
13394 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13395 						"2878 ELS XRI exchange busy "
13396 						"wait time: %d seconds.\n",
13397 						wait_time/1000);
13398 			msleep(LPFC_XRI_EXCH_BUSY_WAIT_T2);
13399 			wait_time += LPFC_XRI_EXCH_BUSY_WAIT_T2;
13400 		} else {
13401 			msleep(LPFC_XRI_EXCH_BUSY_WAIT_T1);
13402 			wait_time += LPFC_XRI_EXCH_BUSY_WAIT_T1;
13403 		}
13404 
13405 		ccnt = 0;
13406 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
13407 			qp = &phba->sli4_hba.hdwq[idx];
13408 			io_xri_cmpl = list_empty(
13409 			    &qp->lpfc_abts_io_buf_list);
13410 			if (!io_xri_cmpl) /* if list is NOT empty */
13411 				ccnt++;
13412 		}
13413 		if (ccnt)
13414 			io_xri_cmpl = 0;
13415 
13416 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13417 			nvmet_xri_cmpl = list_empty(
13418 				&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
13419 		}
13420 		els_xri_cmpl =
13421 			list_empty(&phba->sli4_hba.lpfc_abts_els_sgl_list);
13422 
13423 	}
13424 }
13425 
13426 /**
13427  * lpfc_sli4_hba_unset - Unset the fcoe hba
13428  * @phba: Pointer to HBA context object.
13429  *
13430  * This function is called in the SLI4 code path to reset the HBA's FCoE
13431  * function. The caller is not required to hold any lock. This routine
13432  * issues PCI function reset mailbox command to reset the FCoE function.
13433  * At the end of the function, it calls lpfc_hba_down_post function to
13434  * free any pending commands.
13435  **/
13436 static void
13437 lpfc_sli4_hba_unset(struct lpfc_hba *phba)
13438 {
13439 	int wait_cnt = 0;
13440 	LPFC_MBOXQ_t *mboxq;
13441 	struct pci_dev *pdev = phba->pcidev;
13442 
13443 	lpfc_stop_hba_timers(phba);
13444 	hrtimer_cancel(&phba->cmf_timer);
13445 
13446 	if (phba->pport)
13447 		phba->sli4_hba.intr_enable = 0;
13448 
13449 	/*
13450 	 * Gracefully wait out the potential current outstanding asynchronous
13451 	 * mailbox command.
13452 	 */
13453 
13454 	/* First, block any pending async mailbox command from posted */
13455 	spin_lock_irq(&phba->hbalock);
13456 	phba->sli.sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
13457 	spin_unlock_irq(&phba->hbalock);
13458 	/* Now, trying to wait it out if we can */
13459 	while (phba->sli.sli_flag & LPFC_SLI_MBOX_ACTIVE) {
13460 		msleep(10);
13461 		if (++wait_cnt > LPFC_ACTIVE_MBOX_WAIT_CNT)
13462 			break;
13463 	}
13464 	/* Forcefully release the outstanding mailbox command if timed out */
13465 	if (phba->sli.sli_flag & LPFC_SLI_MBOX_ACTIVE) {
13466 		spin_lock_irq(&phba->hbalock);
13467 		mboxq = phba->sli.mbox_active;
13468 		mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
13469 		__lpfc_mbox_cmpl_put(phba, mboxq);
13470 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
13471 		phba->sli.mbox_active = NULL;
13472 		spin_unlock_irq(&phba->hbalock);
13473 	}
13474 
13475 	/* Abort all iocbs associated with the hba */
13476 	lpfc_sli_hba_iocb_abort(phba);
13477 
13478 	if (!pci_channel_offline(phba->pcidev))
13479 		/* Wait for completion of device XRI exchange busy */
13480 		lpfc_sli4_xri_exchange_busy_wait(phba);
13481 
13482 	/* per-phba callback de-registration for hotplug event */
13483 	if (phba->pport)
13484 		lpfc_cpuhp_remove(phba);
13485 
13486 	/* Disable PCI subsystem interrupt */
13487 	lpfc_sli4_disable_intr(phba);
13488 
13489 	/* Disable SR-IOV if enabled */
13490 	if (phba->cfg_sriov_nr_virtfn)
13491 		pci_disable_sriov(pdev);
13492 
13493 	/* Stop kthread signal shall trigger work_done one more time */
13494 	kthread_stop(phba->worker_thread);
13495 
13496 	/* Disable FW logging to host memory */
13497 	lpfc_ras_stop_fwlog(phba);
13498 
13499 	/* Reset SLI4 HBA FCoE function */
13500 	lpfc_pci_function_reset(phba);
13501 
13502 	/* release all queue allocated resources. */
13503 	lpfc_sli4_queue_destroy(phba);
13504 
13505 	/* Free RAS DMA memory */
13506 	if (phba->ras_fwlog.ras_enabled)
13507 		lpfc_sli4_ras_dma_free(phba);
13508 
13509 	/* Stop the SLI4 device port */
13510 	if (phba->pport)
13511 		phba->pport->work_port_events = 0;
13512 }
13513 
13514 static uint32_t
13515 lpfc_cgn_crc32(uint32_t crc, u8 byte)
13516 {
13517 	uint32_t msb = 0;
13518 	uint32_t bit;
13519 
13520 	for (bit = 0; bit < 8; bit++) {
13521 		msb = (crc >> 31) & 1;
13522 		crc <<= 1;
13523 
13524 		if (msb ^ (byte & 1)) {
13525 			crc ^= LPFC_CGN_CRC32_MAGIC_NUMBER;
13526 			crc |= 1;
13527 		}
13528 		byte >>= 1;
13529 	}
13530 	return crc;
13531 }
13532 
13533 static uint32_t
13534 lpfc_cgn_reverse_bits(uint32_t wd)
13535 {
13536 	uint32_t result = 0;
13537 	uint32_t i;
13538 
13539 	for (i = 0; i < 32; i++) {
13540 		result <<= 1;
13541 		result |= (1 & (wd >> i));
13542 	}
13543 	return result;
13544 }
13545 
13546 /*
13547  * The routine corresponds with the algorithm the HBA firmware
13548  * uses to validate the data integrity.
13549  */
13550 uint32_t
13551 lpfc_cgn_calc_crc32(void *ptr, uint32_t byteLen, uint32_t crc)
13552 {
13553 	uint32_t  i;
13554 	uint32_t result;
13555 	uint8_t  *data = (uint8_t *)ptr;
13556 
13557 	for (i = 0; i < byteLen; ++i)
13558 		crc = lpfc_cgn_crc32(crc, data[i]);
13559 
13560 	result = ~lpfc_cgn_reverse_bits(crc);
13561 	return result;
13562 }
13563 
13564 void
13565 lpfc_init_congestion_buf(struct lpfc_hba *phba)
13566 {
13567 	struct lpfc_cgn_info *cp;
13568 	struct timespec64 cmpl_time;
13569 	struct tm broken;
13570 	uint16_t size;
13571 	uint32_t crc;
13572 
13573 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
13574 			"6235 INIT Congestion Buffer %p\n", phba->cgn_i);
13575 
13576 	if (!phba->cgn_i)
13577 		return;
13578 	cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
13579 
13580 	atomic_set(&phba->cgn_fabric_warn_cnt, 0);
13581 	atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
13582 	atomic_set(&phba->cgn_sync_alarm_cnt, 0);
13583 	atomic_set(&phba->cgn_sync_warn_cnt, 0);
13584 
13585 	atomic_set(&phba->cgn_driver_evt_cnt, 0);
13586 	atomic_set(&phba->cgn_latency_evt_cnt, 0);
13587 	atomic64_set(&phba->cgn_latency_evt, 0);
13588 	phba->cgn_evt_minute = 0;
13589 	phba->hba_flag &= ~HBA_CGN_DAY_WRAP;
13590 
13591 	memset(cp, 0xff, offsetof(struct lpfc_cgn_info, cgn_stat));
13592 	cp->cgn_info_size = cpu_to_le16(LPFC_CGN_INFO_SZ);
13593 	cp->cgn_info_version = LPFC_CGN_INFO_V3;
13594 
13595 	/* cgn parameters */
13596 	cp->cgn_info_mode = phba->cgn_p.cgn_param_mode;
13597 	cp->cgn_info_level0 = phba->cgn_p.cgn_param_level0;
13598 	cp->cgn_info_level1 = phba->cgn_p.cgn_param_level1;
13599 	cp->cgn_info_level2 = phba->cgn_p.cgn_param_level2;
13600 
13601 	ktime_get_real_ts64(&cmpl_time);
13602 	time64_to_tm(cmpl_time.tv_sec, 0, &broken);
13603 
13604 	cp->cgn_info_month = broken.tm_mon + 1;
13605 	cp->cgn_info_day = broken.tm_mday;
13606 	cp->cgn_info_year = broken.tm_year - 100; /* relative to 2000 */
13607 	cp->cgn_info_hour = broken.tm_hour;
13608 	cp->cgn_info_minute = broken.tm_min;
13609 	cp->cgn_info_second = broken.tm_sec;
13610 
13611 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT | LOG_INIT,
13612 			"2643 CGNInfo Init: Start Time "
13613 			"%d/%d/%d %d:%d:%d\n",
13614 			cp->cgn_info_day, cp->cgn_info_month,
13615 			cp->cgn_info_year, cp->cgn_info_hour,
13616 			cp->cgn_info_minute, cp->cgn_info_second);
13617 
13618 	/* Fill in default LUN qdepth */
13619 	if (phba->pport) {
13620 		size = (uint16_t)(phba->pport->cfg_lun_queue_depth);
13621 		cp->cgn_lunq = cpu_to_le16(size);
13622 	}
13623 
13624 	/* last used Index initialized to 0xff already */
13625 
13626 	cp->cgn_warn_freq = cpu_to_le16(LPFC_FPIN_INIT_FREQ);
13627 	cp->cgn_alarm_freq = cpu_to_le16(LPFC_FPIN_INIT_FREQ);
13628 	crc = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ, LPFC_CGN_CRC32_SEED);
13629 	cp->cgn_info_crc = cpu_to_le32(crc);
13630 
13631 	phba->cgn_evt_timestamp = jiffies +
13632 		msecs_to_jiffies(LPFC_CGN_TIMER_TO_MIN);
13633 }
13634 
13635 void
13636 lpfc_init_congestion_stat(struct lpfc_hba *phba)
13637 {
13638 	struct lpfc_cgn_info *cp;
13639 	struct timespec64 cmpl_time;
13640 	struct tm broken;
13641 	uint32_t crc;
13642 
13643 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
13644 			"6236 INIT Congestion Stat %p\n", phba->cgn_i);
13645 
13646 	if (!phba->cgn_i)
13647 		return;
13648 
13649 	cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
13650 	memset(&cp->cgn_stat, 0, sizeof(cp->cgn_stat));
13651 
13652 	ktime_get_real_ts64(&cmpl_time);
13653 	time64_to_tm(cmpl_time.tv_sec, 0, &broken);
13654 
13655 	cp->cgn_stat_month = broken.tm_mon + 1;
13656 	cp->cgn_stat_day = broken.tm_mday;
13657 	cp->cgn_stat_year = broken.tm_year - 100; /* relative to 2000 */
13658 	cp->cgn_stat_hour = broken.tm_hour;
13659 	cp->cgn_stat_minute = broken.tm_min;
13660 
13661 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT | LOG_INIT,
13662 			"2647 CGNstat Init: Start Time "
13663 			"%d/%d/%d %d:%d\n",
13664 			cp->cgn_stat_day, cp->cgn_stat_month,
13665 			cp->cgn_stat_year, cp->cgn_stat_hour,
13666 			cp->cgn_stat_minute);
13667 
13668 	crc = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ, LPFC_CGN_CRC32_SEED);
13669 	cp->cgn_info_crc = cpu_to_le32(crc);
13670 }
13671 
13672 /**
13673  * __lpfc_reg_congestion_buf - register congestion info buffer with HBA
13674  * @phba: Pointer to hba context object.
13675  * @reg: flag to determine register or unregister.
13676  */
13677 static int
13678 __lpfc_reg_congestion_buf(struct lpfc_hba *phba, int reg)
13679 {
13680 	struct lpfc_mbx_reg_congestion_buf *reg_congestion_buf;
13681 	union  lpfc_sli4_cfg_shdr *shdr;
13682 	uint32_t shdr_status, shdr_add_status;
13683 	LPFC_MBOXQ_t *mboxq;
13684 	int length, rc;
13685 
13686 	if (!phba->cgn_i)
13687 		return -ENXIO;
13688 
13689 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
13690 	if (!mboxq) {
13691 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX,
13692 				"2641 REG_CONGESTION_BUF mbox allocation fail: "
13693 				"HBA state x%x reg %d\n",
13694 				phba->pport->port_state, reg);
13695 		return -ENOMEM;
13696 	}
13697 
13698 	length = (sizeof(struct lpfc_mbx_reg_congestion_buf) -
13699 		sizeof(struct lpfc_sli4_cfg_mhdr));
13700 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
13701 			 LPFC_MBOX_OPCODE_REG_CONGESTION_BUF, length,
13702 			 LPFC_SLI4_MBX_EMBED);
13703 	reg_congestion_buf = &mboxq->u.mqe.un.reg_congestion_buf;
13704 	bf_set(lpfc_mbx_reg_cgn_buf_type, reg_congestion_buf, 1);
13705 	if (reg > 0)
13706 		bf_set(lpfc_mbx_reg_cgn_buf_cnt, reg_congestion_buf, 1);
13707 	else
13708 		bf_set(lpfc_mbx_reg_cgn_buf_cnt, reg_congestion_buf, 0);
13709 	reg_congestion_buf->length = sizeof(struct lpfc_cgn_info);
13710 	reg_congestion_buf->addr_lo =
13711 		putPaddrLow(phba->cgn_i->phys);
13712 	reg_congestion_buf->addr_hi =
13713 		putPaddrHigh(phba->cgn_i->phys);
13714 
13715 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
13716 	shdr = (union lpfc_sli4_cfg_shdr *)
13717 		&mboxq->u.mqe.un.sli4_config.header.cfg_shdr;
13718 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13719 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
13720 				 &shdr->response);
13721 	mempool_free(mboxq, phba->mbox_mem_pool);
13722 	if (shdr_status || shdr_add_status || rc) {
13723 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13724 				"2642 REG_CONGESTION_BUF mailbox "
13725 				"failed with status x%x add_status x%x,"
13726 				" mbx status x%x reg %d\n",
13727 				shdr_status, shdr_add_status, rc, reg);
13728 		return -ENXIO;
13729 	}
13730 	return 0;
13731 }
13732 
13733 int
13734 lpfc_unreg_congestion_buf(struct lpfc_hba *phba)
13735 {
13736 	lpfc_cmf_stop(phba);
13737 	return __lpfc_reg_congestion_buf(phba, 0);
13738 }
13739 
13740 int
13741 lpfc_reg_congestion_buf(struct lpfc_hba *phba)
13742 {
13743 	return __lpfc_reg_congestion_buf(phba, 1);
13744 }
13745 
13746 /**
13747  * lpfc_get_sli4_parameters - Get the SLI4 Config PARAMETERS.
13748  * @phba: Pointer to HBA context object.
13749  * @mboxq: Pointer to the mailboxq memory for the mailbox command response.
13750  *
13751  * This function is called in the SLI4 code path to read the port's
13752  * sli4 capabilities.
13753  *
13754  * This function may be be called from any context that can block-wait
13755  * for the completion.  The expectation is that this routine is called
13756  * typically from probe_one or from the online routine.
13757  **/
13758 int
13759 lpfc_get_sli4_parameters(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
13760 {
13761 	int rc;
13762 	struct lpfc_mqe *mqe = &mboxq->u.mqe;
13763 	struct lpfc_pc_sli4_params *sli4_params;
13764 	uint32_t mbox_tmo;
13765 	int length;
13766 	bool exp_wqcq_pages = true;
13767 	struct lpfc_sli4_parameters *mbx_sli4_parameters;
13768 
13769 	/*
13770 	 * By default, the driver assumes the SLI4 port requires RPI
13771 	 * header postings.  The SLI4_PARAM response will correct this
13772 	 * assumption.
13773 	 */
13774 	phba->sli4_hba.rpi_hdrs_in_use = 1;
13775 
13776 	/* Read the port's SLI4 Config Parameters */
13777 	length = (sizeof(struct lpfc_mbx_get_sli4_parameters) -
13778 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13779 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
13780 			 LPFC_MBOX_OPCODE_GET_SLI4_PARAMETERS,
13781 			 length, LPFC_SLI4_MBX_EMBED);
13782 	if (!phba->sli4_hba.intr_enable)
13783 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
13784 	else {
13785 		mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
13786 		rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
13787 	}
13788 	if (unlikely(rc))
13789 		return rc;
13790 	sli4_params = &phba->sli4_hba.pc_sli4_params;
13791 	mbx_sli4_parameters = &mqe->un.get_sli4_parameters.sli4_parameters;
13792 	sli4_params->if_type = bf_get(cfg_if_type, mbx_sli4_parameters);
13793 	sli4_params->sli_rev = bf_get(cfg_sli_rev, mbx_sli4_parameters);
13794 	sli4_params->sli_family = bf_get(cfg_sli_family, mbx_sli4_parameters);
13795 	sli4_params->featurelevel_1 = bf_get(cfg_sli_hint_1,
13796 					     mbx_sli4_parameters);
13797 	sli4_params->featurelevel_2 = bf_get(cfg_sli_hint_2,
13798 					     mbx_sli4_parameters);
13799 	if (bf_get(cfg_phwq, mbx_sli4_parameters))
13800 		phba->sli3_options |= LPFC_SLI4_PHWQ_ENABLED;
13801 	else
13802 		phba->sli3_options &= ~LPFC_SLI4_PHWQ_ENABLED;
13803 	sli4_params->sge_supp_len = mbx_sli4_parameters->sge_supp_len;
13804 	sli4_params->loopbk_scope = bf_get(cfg_loopbk_scope,
13805 					   mbx_sli4_parameters);
13806 	sli4_params->oas_supported = bf_get(cfg_oas, mbx_sli4_parameters);
13807 	sli4_params->cqv = bf_get(cfg_cqv, mbx_sli4_parameters);
13808 	sli4_params->mqv = bf_get(cfg_mqv, mbx_sli4_parameters);
13809 	sli4_params->wqv = bf_get(cfg_wqv, mbx_sli4_parameters);
13810 	sli4_params->rqv = bf_get(cfg_rqv, mbx_sli4_parameters);
13811 	sli4_params->eqav = bf_get(cfg_eqav, mbx_sli4_parameters);
13812 	sli4_params->cqav = bf_get(cfg_cqav, mbx_sli4_parameters);
13813 	sli4_params->wqsize = bf_get(cfg_wqsize, mbx_sli4_parameters);
13814 	sli4_params->bv1s = bf_get(cfg_bv1s, mbx_sli4_parameters);
13815 	sli4_params->pls = bf_get(cfg_pvl, mbx_sli4_parameters);
13816 	sli4_params->sgl_pages_max = bf_get(cfg_sgl_page_cnt,
13817 					    mbx_sli4_parameters);
13818 	sli4_params->wqpcnt = bf_get(cfg_wqpcnt, mbx_sli4_parameters);
13819 	sli4_params->sgl_pp_align = bf_get(cfg_sgl_pp_align,
13820 					   mbx_sli4_parameters);
13821 	phba->sli4_hba.extents_in_use = bf_get(cfg_ext, mbx_sli4_parameters);
13822 	phba->sli4_hba.rpi_hdrs_in_use = bf_get(cfg_hdrr, mbx_sli4_parameters);
13823 
13824 	/* Check for Extended Pre-Registered SGL support */
13825 	phba->cfg_xpsgl = bf_get(cfg_xpsgl, mbx_sli4_parameters);
13826 
13827 	/* Check for firmware nvme support */
13828 	rc = (bf_get(cfg_nvme, mbx_sli4_parameters) &&
13829 		     bf_get(cfg_xib, mbx_sli4_parameters));
13830 
13831 	if (rc) {
13832 		/* Save this to indicate the Firmware supports NVME */
13833 		sli4_params->nvme = 1;
13834 
13835 		/* Firmware NVME support, check driver FC4 NVME support */
13836 		if (phba->cfg_enable_fc4_type == LPFC_ENABLE_FCP) {
13837 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_NVME,
13838 					"6133 Disabling NVME support: "
13839 					"FC4 type not supported: x%x\n",
13840 					phba->cfg_enable_fc4_type);
13841 			goto fcponly;
13842 		}
13843 	} else {
13844 		/* No firmware NVME support, check driver FC4 NVME support */
13845 		sli4_params->nvme = 0;
13846 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13847 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_NVME,
13848 					"6101 Disabling NVME support: Not "
13849 					"supported by firmware (%d %d) x%x\n",
13850 					bf_get(cfg_nvme, mbx_sli4_parameters),
13851 					bf_get(cfg_xib, mbx_sli4_parameters),
13852 					phba->cfg_enable_fc4_type);
13853 fcponly:
13854 			phba->nvmet_support = 0;
13855 			phba->cfg_nvmet_mrq = 0;
13856 			phba->cfg_nvme_seg_cnt = 0;
13857 
13858 			/* If no FC4 type support, move to just SCSI support */
13859 			if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP))
13860 				return -ENODEV;
13861 			phba->cfg_enable_fc4_type = LPFC_ENABLE_FCP;
13862 		}
13863 	}
13864 
13865 	/* If the NVME FC4 type is enabled, scale the sg_seg_cnt to
13866 	 * accommodate 512K and 1M IOs in a single nvme buf.
13867 	 */
13868 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
13869 		phba->cfg_sg_seg_cnt = LPFC_MAX_NVME_SEG_CNT;
13870 
13871 	/* Enable embedded Payload BDE if support is indicated */
13872 	if (bf_get(cfg_pbde, mbx_sli4_parameters))
13873 		phba->cfg_enable_pbde = 1;
13874 	else
13875 		phba->cfg_enable_pbde = 0;
13876 
13877 	/*
13878 	 * To support Suppress Response feature we must satisfy 3 conditions.
13879 	 * lpfc_suppress_rsp module parameter must be set (default).
13880 	 * In SLI4-Parameters Descriptor:
13881 	 * Extended Inline Buffers (XIB) must be supported.
13882 	 * Suppress Response IU Not Supported (SRIUNS) must NOT be supported
13883 	 * (double negative).
13884 	 */
13885 	if (phba->cfg_suppress_rsp && bf_get(cfg_xib, mbx_sli4_parameters) &&
13886 	    !(bf_get(cfg_nosr, mbx_sli4_parameters)))
13887 		phba->sli.sli_flag |= LPFC_SLI_SUPPRESS_RSP;
13888 	else
13889 		phba->cfg_suppress_rsp = 0;
13890 
13891 	if (bf_get(cfg_eqdr, mbx_sli4_parameters))
13892 		phba->sli.sli_flag |= LPFC_SLI_USE_EQDR;
13893 
13894 	/* Make sure that sge_supp_len can be handled by the driver */
13895 	if (sli4_params->sge_supp_len > LPFC_MAX_SGE_SIZE)
13896 		sli4_params->sge_supp_len = LPFC_MAX_SGE_SIZE;
13897 
13898 	/*
13899 	 * Check whether the adapter supports an embedded copy of the
13900 	 * FCP CMD IU within the WQE for FCP_Ixxx commands. In order
13901 	 * to use this option, 128-byte WQEs must be used.
13902 	 */
13903 	if (bf_get(cfg_ext_embed_cb, mbx_sli4_parameters))
13904 		phba->fcp_embed_io = 1;
13905 	else
13906 		phba->fcp_embed_io = 0;
13907 
13908 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_NVME,
13909 			"6422 XIB %d PBDE %d: FCP %d NVME %d %d %d\n",
13910 			bf_get(cfg_xib, mbx_sli4_parameters),
13911 			phba->cfg_enable_pbde,
13912 			phba->fcp_embed_io, sli4_params->nvme,
13913 			phba->cfg_nvme_embed_cmd, phba->cfg_suppress_rsp);
13914 
13915 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
13916 	    LPFC_SLI_INTF_IF_TYPE_2) &&
13917 	    (bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf) ==
13918 		 LPFC_SLI_INTF_FAMILY_LNCR_A0))
13919 		exp_wqcq_pages = false;
13920 
13921 	if ((bf_get(cfg_cqpsize, mbx_sli4_parameters) & LPFC_CQ_16K_PAGE_SZ) &&
13922 	    (bf_get(cfg_wqpsize, mbx_sli4_parameters) & LPFC_WQ_16K_PAGE_SZ) &&
13923 	    exp_wqcq_pages &&
13924 	    (sli4_params->wqsize & LPFC_WQ_SZ128_SUPPORT))
13925 		phba->enab_exp_wqcq_pages = 1;
13926 	else
13927 		phba->enab_exp_wqcq_pages = 0;
13928 	/*
13929 	 * Check if the SLI port supports MDS Diagnostics
13930 	 */
13931 	if (bf_get(cfg_mds_diags, mbx_sli4_parameters))
13932 		phba->mds_diags_support = 1;
13933 	else
13934 		phba->mds_diags_support = 0;
13935 
13936 	/*
13937 	 * Check if the SLI port supports NSLER
13938 	 */
13939 	if (bf_get(cfg_nsler, mbx_sli4_parameters))
13940 		phba->nsler = 1;
13941 	else
13942 		phba->nsler = 0;
13943 
13944 	return 0;
13945 }
13946 
13947 /**
13948  * lpfc_pci_probe_one_s3 - PCI probe func to reg SLI-3 device to PCI subsystem.
13949  * @pdev: pointer to PCI device
13950  * @pid: pointer to PCI device identifier
13951  *
13952  * This routine is to be called to attach a device with SLI-3 interface spec
13953  * to the PCI subsystem. When an Emulex HBA with SLI-3 interface spec is
13954  * presented on PCI bus, the kernel PCI subsystem looks at PCI device-specific
13955  * information of the device and driver to see if the driver state that it can
13956  * support this kind of device. If the match is successful, the driver core
13957  * invokes this routine. If this routine determines it can claim the HBA, it
13958  * does all the initialization that it needs to do to handle the HBA properly.
13959  *
13960  * Return code
13961  * 	0 - driver can claim the device
13962  * 	negative value - driver can not claim the device
13963  **/
13964 static int
13965 lpfc_pci_probe_one_s3(struct pci_dev *pdev, const struct pci_device_id *pid)
13966 {
13967 	struct lpfc_hba   *phba;
13968 	struct lpfc_vport *vport = NULL;
13969 	struct Scsi_Host  *shost = NULL;
13970 	int error;
13971 	uint32_t cfg_mode, intr_mode;
13972 
13973 	/* Allocate memory for HBA structure */
13974 	phba = lpfc_hba_alloc(pdev);
13975 	if (!phba)
13976 		return -ENOMEM;
13977 
13978 	/* Perform generic PCI device enabling operation */
13979 	error = lpfc_enable_pci_dev(phba);
13980 	if (error)
13981 		goto out_free_phba;
13982 
13983 	/* Set up SLI API function jump table for PCI-device group-0 HBAs */
13984 	error = lpfc_api_table_setup(phba, LPFC_PCI_DEV_LP);
13985 	if (error)
13986 		goto out_disable_pci_dev;
13987 
13988 	/* Set up SLI-3 specific device PCI memory space */
13989 	error = lpfc_sli_pci_mem_setup(phba);
13990 	if (error) {
13991 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13992 				"1402 Failed to set up pci memory space.\n");
13993 		goto out_disable_pci_dev;
13994 	}
13995 
13996 	/* Set up SLI-3 specific device driver resources */
13997 	error = lpfc_sli_driver_resource_setup(phba);
13998 	if (error) {
13999 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14000 				"1404 Failed to set up driver resource.\n");
14001 		goto out_unset_pci_mem_s3;
14002 	}
14003 
14004 	/* Initialize and populate the iocb list per host */
14005 
14006 	error = lpfc_init_iocb_list(phba, LPFC_IOCB_LIST_CNT);
14007 	if (error) {
14008 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14009 				"1405 Failed to initialize iocb list.\n");
14010 		goto out_unset_driver_resource_s3;
14011 	}
14012 
14013 	/* Set up common device driver resources */
14014 	error = lpfc_setup_driver_resource_phase2(phba);
14015 	if (error) {
14016 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14017 				"1406 Failed to set up driver resource.\n");
14018 		goto out_free_iocb_list;
14019 	}
14020 
14021 	/* Get the default values for Model Name and Description */
14022 	lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
14023 
14024 	/* Create SCSI host to the physical port */
14025 	error = lpfc_create_shost(phba);
14026 	if (error) {
14027 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14028 				"1407 Failed to create scsi host.\n");
14029 		goto out_unset_driver_resource;
14030 	}
14031 
14032 	/* Configure sysfs attributes */
14033 	vport = phba->pport;
14034 	error = lpfc_alloc_sysfs_attr(vport);
14035 	if (error) {
14036 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14037 				"1476 Failed to allocate sysfs attr\n");
14038 		goto out_destroy_shost;
14039 	}
14040 
14041 	shost = lpfc_shost_from_vport(vport); /* save shost for error cleanup */
14042 	/* Now, trying to enable interrupt and bring up the device */
14043 	cfg_mode = phba->cfg_use_msi;
14044 	while (true) {
14045 		/* Put device to a known state before enabling interrupt */
14046 		lpfc_stop_port(phba);
14047 		/* Configure and enable interrupt */
14048 		intr_mode = lpfc_sli_enable_intr(phba, cfg_mode);
14049 		if (intr_mode == LPFC_INTR_ERROR) {
14050 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14051 					"0431 Failed to enable interrupt.\n");
14052 			error = -ENODEV;
14053 			goto out_free_sysfs_attr;
14054 		}
14055 		/* SLI-3 HBA setup */
14056 		if (lpfc_sli_hba_setup(phba)) {
14057 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14058 					"1477 Failed to set up hba\n");
14059 			error = -ENODEV;
14060 			goto out_remove_device;
14061 		}
14062 
14063 		/* Wait 50ms for the interrupts of previous mailbox commands */
14064 		msleep(50);
14065 		/* Check active interrupts on message signaled interrupts */
14066 		if (intr_mode == 0 ||
14067 		    phba->sli.slistat.sli_intr > LPFC_MSIX_VECTORS) {
14068 			/* Log the current active interrupt mode */
14069 			phba->intr_mode = intr_mode;
14070 			lpfc_log_intr_mode(phba, intr_mode);
14071 			break;
14072 		} else {
14073 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
14074 					"0447 Configure interrupt mode (%d) "
14075 					"failed active interrupt test.\n",
14076 					intr_mode);
14077 			/* Disable the current interrupt mode */
14078 			lpfc_sli_disable_intr(phba);
14079 			/* Try next level of interrupt mode */
14080 			cfg_mode = --intr_mode;
14081 		}
14082 	}
14083 
14084 	/* Perform post initialization setup */
14085 	lpfc_post_init_setup(phba);
14086 
14087 	/* Check if there are static vports to be created. */
14088 	lpfc_create_static_vport(phba);
14089 
14090 	return 0;
14091 
14092 out_remove_device:
14093 	lpfc_unset_hba(phba);
14094 out_free_sysfs_attr:
14095 	lpfc_free_sysfs_attr(vport);
14096 out_destroy_shost:
14097 	lpfc_destroy_shost(phba);
14098 out_unset_driver_resource:
14099 	lpfc_unset_driver_resource_phase2(phba);
14100 out_free_iocb_list:
14101 	lpfc_free_iocb_list(phba);
14102 out_unset_driver_resource_s3:
14103 	lpfc_sli_driver_resource_unset(phba);
14104 out_unset_pci_mem_s3:
14105 	lpfc_sli_pci_mem_unset(phba);
14106 out_disable_pci_dev:
14107 	lpfc_disable_pci_dev(phba);
14108 	if (shost)
14109 		scsi_host_put(shost);
14110 out_free_phba:
14111 	lpfc_hba_free(phba);
14112 	return error;
14113 }
14114 
14115 /**
14116  * lpfc_pci_remove_one_s3 - PCI func to unreg SLI-3 device from PCI subsystem.
14117  * @pdev: pointer to PCI device
14118  *
14119  * This routine is to be called to disattach a device with SLI-3 interface
14120  * spec from PCI subsystem. When an Emulex HBA with SLI-3 interface spec is
14121  * removed from PCI bus, it performs all the necessary cleanup for the HBA
14122  * device to be removed from the PCI subsystem properly.
14123  **/
14124 static void
14125 lpfc_pci_remove_one_s3(struct pci_dev *pdev)
14126 {
14127 	struct Scsi_Host  *shost = pci_get_drvdata(pdev);
14128 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
14129 	struct lpfc_vport **vports;
14130 	struct lpfc_hba   *phba = vport->phba;
14131 	int i;
14132 
14133 	spin_lock_irq(&phba->hbalock);
14134 	vport->load_flag |= FC_UNLOADING;
14135 	spin_unlock_irq(&phba->hbalock);
14136 
14137 	lpfc_free_sysfs_attr(vport);
14138 
14139 	/* Release all the vports against this physical port */
14140 	vports = lpfc_create_vport_work_array(phba);
14141 	if (vports != NULL)
14142 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
14143 			if (vports[i]->port_type == LPFC_PHYSICAL_PORT)
14144 				continue;
14145 			fc_vport_terminate(vports[i]->fc_vport);
14146 		}
14147 	lpfc_destroy_vport_work_array(phba, vports);
14148 
14149 	/* Remove FC host with the physical port */
14150 	fc_remove_host(shost);
14151 	scsi_remove_host(shost);
14152 
14153 	/* Clean up all nodes, mailboxes and IOs. */
14154 	lpfc_cleanup(vport);
14155 
14156 	/*
14157 	 * Bring down the SLI Layer. This step disable all interrupts,
14158 	 * clears the rings, discards all mailbox commands, and resets
14159 	 * the HBA.
14160 	 */
14161 
14162 	/* HBA interrupt will be disabled after this call */
14163 	lpfc_sli_hba_down(phba);
14164 	/* Stop kthread signal shall trigger work_done one more time */
14165 	kthread_stop(phba->worker_thread);
14166 	/* Final cleanup of txcmplq and reset the HBA */
14167 	lpfc_sli_brdrestart(phba);
14168 
14169 	kfree(phba->vpi_bmask);
14170 	kfree(phba->vpi_ids);
14171 
14172 	lpfc_stop_hba_timers(phba);
14173 	spin_lock_irq(&phba->port_list_lock);
14174 	list_del_init(&vport->listentry);
14175 	spin_unlock_irq(&phba->port_list_lock);
14176 
14177 	lpfc_debugfs_terminate(vport);
14178 
14179 	/* Disable SR-IOV if enabled */
14180 	if (phba->cfg_sriov_nr_virtfn)
14181 		pci_disable_sriov(pdev);
14182 
14183 	/* Disable interrupt */
14184 	lpfc_sli_disable_intr(phba);
14185 
14186 	scsi_host_put(shost);
14187 
14188 	/*
14189 	 * Call scsi_free before mem_free since scsi bufs are released to their
14190 	 * corresponding pools here.
14191 	 */
14192 	lpfc_scsi_free(phba);
14193 	lpfc_free_iocb_list(phba);
14194 
14195 	lpfc_mem_free_all(phba);
14196 
14197 	dma_free_coherent(&pdev->dev, lpfc_sli_hbq_size(),
14198 			  phba->hbqslimp.virt, phba->hbqslimp.phys);
14199 
14200 	/* Free resources associated with SLI2 interface */
14201 	dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
14202 			  phba->slim2p.virt, phba->slim2p.phys);
14203 
14204 	/* unmap adapter SLIM and Control Registers */
14205 	iounmap(phba->ctrl_regs_memmap_p);
14206 	iounmap(phba->slim_memmap_p);
14207 
14208 	lpfc_hba_free(phba);
14209 
14210 	pci_release_mem_regions(pdev);
14211 	pci_disable_device(pdev);
14212 }
14213 
14214 /**
14215  * lpfc_pci_suspend_one_s3 - PCI func to suspend SLI-3 device for power mgmnt
14216  * @dev_d: pointer to device
14217  *
14218  * This routine is to be called from the kernel's PCI subsystem to support
14219  * system Power Management (PM) to device with SLI-3 interface spec. When
14220  * PM invokes this method, it quiesces the device by stopping the driver's
14221  * worker thread for the device, turning off device's interrupt and DMA,
14222  * and bring the device offline. Note that as the driver implements the
14223  * minimum PM requirements to a power-aware driver's PM support for the
14224  * suspend/resume -- all the possible PM messages (SUSPEND, HIBERNATE, FREEZE)
14225  * to the suspend() method call will be treated as SUSPEND and the driver will
14226  * fully reinitialize its device during resume() method call, the driver will
14227  * set device to PCI_D3hot state in PCI config space instead of setting it
14228  * according to the @msg provided by the PM.
14229  *
14230  * Return code
14231  * 	0 - driver suspended the device
14232  * 	Error otherwise
14233  **/
14234 static int __maybe_unused
14235 lpfc_pci_suspend_one_s3(struct device *dev_d)
14236 {
14237 	struct Scsi_Host *shost = dev_get_drvdata(dev_d);
14238 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14239 
14240 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
14241 			"0473 PCI device Power Management suspend.\n");
14242 
14243 	/* Bring down the device */
14244 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
14245 	lpfc_offline(phba);
14246 	kthread_stop(phba->worker_thread);
14247 
14248 	/* Disable interrupt from device */
14249 	lpfc_sli_disable_intr(phba);
14250 
14251 	return 0;
14252 }
14253 
14254 /**
14255  * lpfc_pci_resume_one_s3 - PCI func to resume SLI-3 device for power mgmnt
14256  * @dev_d: pointer to device
14257  *
14258  * This routine is to be called from the kernel's PCI subsystem to support
14259  * system Power Management (PM) to device with SLI-3 interface spec. When PM
14260  * invokes this method, it restores the device's PCI config space state and
14261  * fully reinitializes the device and brings it online. Note that as the
14262  * driver implements the minimum PM requirements to a power-aware driver's
14263  * PM for suspend/resume -- all the possible PM messages (SUSPEND, HIBERNATE,
14264  * FREEZE) to the suspend() method call will be treated as SUSPEND and the
14265  * driver will fully reinitialize its device during resume() method call,
14266  * the device will be set to PCI_D0 directly in PCI config space before
14267  * restoring the state.
14268  *
14269  * Return code
14270  * 	0 - driver suspended the device
14271  * 	Error otherwise
14272  **/
14273 static int __maybe_unused
14274 lpfc_pci_resume_one_s3(struct device *dev_d)
14275 {
14276 	struct Scsi_Host *shost = dev_get_drvdata(dev_d);
14277 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14278 	uint32_t intr_mode;
14279 	int error;
14280 
14281 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
14282 			"0452 PCI device Power Management resume.\n");
14283 
14284 	/* Startup the kernel thread for this host adapter. */
14285 	phba->worker_thread = kthread_run(lpfc_do_work, phba,
14286 					"lpfc_worker_%d", phba->brd_no);
14287 	if (IS_ERR(phba->worker_thread)) {
14288 		error = PTR_ERR(phba->worker_thread);
14289 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14290 				"0434 PM resume failed to start worker "
14291 				"thread: error=x%x.\n", error);
14292 		return error;
14293 	}
14294 
14295 	/* Init cpu_map array */
14296 	lpfc_cpu_map_array_init(phba);
14297 	/* Init hba_eq_hdl array */
14298 	lpfc_hba_eq_hdl_array_init(phba);
14299 	/* Configure and enable interrupt */
14300 	intr_mode = lpfc_sli_enable_intr(phba, phba->intr_mode);
14301 	if (intr_mode == LPFC_INTR_ERROR) {
14302 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14303 				"0430 PM resume Failed to enable interrupt\n");
14304 		return -EIO;
14305 	} else
14306 		phba->intr_mode = intr_mode;
14307 
14308 	/* Restart HBA and bring it online */
14309 	lpfc_sli_brdrestart(phba);
14310 	lpfc_online(phba);
14311 
14312 	/* Log the current active interrupt mode */
14313 	lpfc_log_intr_mode(phba, phba->intr_mode);
14314 
14315 	return 0;
14316 }
14317 
14318 /**
14319  * lpfc_sli_prep_dev_for_recover - Prepare SLI3 device for pci slot recover
14320  * @phba: pointer to lpfc hba data structure.
14321  *
14322  * This routine is called to prepare the SLI3 device for PCI slot recover. It
14323  * aborts all the outstanding SCSI I/Os to the pci device.
14324  **/
14325 static void
14326 lpfc_sli_prep_dev_for_recover(struct lpfc_hba *phba)
14327 {
14328 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14329 			"2723 PCI channel I/O abort preparing for recovery\n");
14330 
14331 	/*
14332 	 * There may be errored I/Os through HBA, abort all I/Os on txcmplq
14333 	 * and let the SCSI mid-layer to retry them to recover.
14334 	 */
14335 	lpfc_sli_abort_fcp_rings(phba);
14336 }
14337 
14338 /**
14339  * lpfc_sli_prep_dev_for_reset - Prepare SLI3 device for pci slot reset
14340  * @phba: pointer to lpfc hba data structure.
14341  *
14342  * This routine is called to prepare the SLI3 device for PCI slot reset. It
14343  * disables the device interrupt and pci device, and aborts the internal FCP
14344  * pending I/Os.
14345  **/
14346 static void
14347 lpfc_sli_prep_dev_for_reset(struct lpfc_hba *phba)
14348 {
14349 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14350 			"2710 PCI channel disable preparing for reset\n");
14351 
14352 	/* Block any management I/Os to the device */
14353 	lpfc_block_mgmt_io(phba, LPFC_MBX_WAIT);
14354 
14355 	/* Block all SCSI devices' I/Os on the host */
14356 	lpfc_scsi_dev_block(phba);
14357 
14358 	/* Flush all driver's outstanding SCSI I/Os as we are to reset */
14359 	lpfc_sli_flush_io_rings(phba);
14360 
14361 	/* stop all timers */
14362 	lpfc_stop_hba_timers(phba);
14363 
14364 	/* Disable interrupt and pci device */
14365 	lpfc_sli_disable_intr(phba);
14366 	pci_disable_device(phba->pcidev);
14367 }
14368 
14369 /**
14370  * lpfc_sli_prep_dev_for_perm_failure - Prepare SLI3 dev for pci slot disable
14371  * @phba: pointer to lpfc hba data structure.
14372  *
14373  * This routine is called to prepare the SLI3 device for PCI slot permanently
14374  * disabling. It blocks the SCSI transport layer traffic and flushes the FCP
14375  * pending I/Os.
14376  **/
14377 static void
14378 lpfc_sli_prep_dev_for_perm_failure(struct lpfc_hba *phba)
14379 {
14380 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14381 			"2711 PCI channel permanent disable for failure\n");
14382 	/* Block all SCSI devices' I/Os on the host */
14383 	lpfc_scsi_dev_block(phba);
14384 	lpfc_sli4_prep_dev_for_reset(phba);
14385 
14386 	/* stop all timers */
14387 	lpfc_stop_hba_timers(phba);
14388 
14389 	/* Clean up all driver's outstanding SCSI I/Os */
14390 	lpfc_sli_flush_io_rings(phba);
14391 }
14392 
14393 /**
14394  * lpfc_io_error_detected_s3 - Method for handling SLI-3 device PCI I/O error
14395  * @pdev: pointer to PCI device.
14396  * @state: the current PCI connection state.
14397  *
14398  * This routine is called from the PCI subsystem for I/O error handling to
14399  * device with SLI-3 interface spec. This function is called by the PCI
14400  * subsystem after a PCI bus error affecting this device has been detected.
14401  * When this function is invoked, it will need to stop all the I/Os and
14402  * interrupt(s) to the device. Once that is done, it will return
14403  * PCI_ERS_RESULT_NEED_RESET for the PCI subsystem to perform proper recovery
14404  * as desired.
14405  *
14406  * Return codes
14407  * 	PCI_ERS_RESULT_CAN_RECOVER - can be recovered with reset_link
14408  * 	PCI_ERS_RESULT_NEED_RESET - need to reset before recovery
14409  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
14410  **/
14411 static pci_ers_result_t
14412 lpfc_io_error_detected_s3(struct pci_dev *pdev, pci_channel_state_t state)
14413 {
14414 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
14415 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14416 
14417 	switch (state) {
14418 	case pci_channel_io_normal:
14419 		/* Non-fatal error, prepare for recovery */
14420 		lpfc_sli_prep_dev_for_recover(phba);
14421 		return PCI_ERS_RESULT_CAN_RECOVER;
14422 	case pci_channel_io_frozen:
14423 		/* Fatal error, prepare for slot reset */
14424 		lpfc_sli_prep_dev_for_reset(phba);
14425 		return PCI_ERS_RESULT_NEED_RESET;
14426 	case pci_channel_io_perm_failure:
14427 		/* Permanent failure, prepare for device down */
14428 		lpfc_sli_prep_dev_for_perm_failure(phba);
14429 		return PCI_ERS_RESULT_DISCONNECT;
14430 	default:
14431 		/* Unknown state, prepare and request slot reset */
14432 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14433 				"0472 Unknown PCI error state: x%x\n", state);
14434 		lpfc_sli_prep_dev_for_reset(phba);
14435 		return PCI_ERS_RESULT_NEED_RESET;
14436 	}
14437 }
14438 
14439 /**
14440  * lpfc_io_slot_reset_s3 - Method for restarting PCI SLI-3 device from scratch.
14441  * @pdev: pointer to PCI device.
14442  *
14443  * This routine is called from the PCI subsystem for error handling to
14444  * device with SLI-3 interface spec. This is called after PCI bus has been
14445  * reset to restart the PCI card from scratch, as if from a cold-boot.
14446  * During the PCI subsystem error recovery, after driver returns
14447  * PCI_ERS_RESULT_NEED_RESET, the PCI subsystem will perform proper error
14448  * recovery and then call this routine before calling the .resume method
14449  * to recover the device. This function will initialize the HBA device,
14450  * enable the interrupt, but it will just put the HBA to offline state
14451  * without passing any I/O traffic.
14452  *
14453  * Return codes
14454  * 	PCI_ERS_RESULT_RECOVERED - the device has been recovered
14455  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
14456  */
14457 static pci_ers_result_t
14458 lpfc_io_slot_reset_s3(struct pci_dev *pdev)
14459 {
14460 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
14461 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14462 	struct lpfc_sli *psli = &phba->sli;
14463 	uint32_t intr_mode;
14464 
14465 	dev_printk(KERN_INFO, &pdev->dev, "recovering from a slot reset.\n");
14466 	if (pci_enable_device_mem(pdev)) {
14467 		printk(KERN_ERR "lpfc: Cannot re-enable "
14468 			"PCI device after reset.\n");
14469 		return PCI_ERS_RESULT_DISCONNECT;
14470 	}
14471 
14472 	pci_restore_state(pdev);
14473 
14474 	/*
14475 	 * As the new kernel behavior of pci_restore_state() API call clears
14476 	 * device saved_state flag, need to save the restored state again.
14477 	 */
14478 	pci_save_state(pdev);
14479 
14480 	if (pdev->is_busmaster)
14481 		pci_set_master(pdev);
14482 
14483 	spin_lock_irq(&phba->hbalock);
14484 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
14485 	spin_unlock_irq(&phba->hbalock);
14486 
14487 	/* Configure and enable interrupt */
14488 	intr_mode = lpfc_sli_enable_intr(phba, phba->intr_mode);
14489 	if (intr_mode == LPFC_INTR_ERROR) {
14490 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14491 				"0427 Cannot re-enable interrupt after "
14492 				"slot reset.\n");
14493 		return PCI_ERS_RESULT_DISCONNECT;
14494 	} else
14495 		phba->intr_mode = intr_mode;
14496 
14497 	/* Take device offline, it will perform cleanup */
14498 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
14499 	lpfc_offline(phba);
14500 	lpfc_sli_brdrestart(phba);
14501 
14502 	/* Log the current active interrupt mode */
14503 	lpfc_log_intr_mode(phba, phba->intr_mode);
14504 
14505 	return PCI_ERS_RESULT_RECOVERED;
14506 }
14507 
14508 /**
14509  * lpfc_io_resume_s3 - Method for resuming PCI I/O operation on SLI-3 device.
14510  * @pdev: pointer to PCI device
14511  *
14512  * This routine is called from the PCI subsystem for error handling to device
14513  * with SLI-3 interface spec. It is called when kernel error recovery tells
14514  * the lpfc driver that it is ok to resume normal PCI operation after PCI bus
14515  * error recovery. After this call, traffic can start to flow from this device
14516  * again.
14517  */
14518 static void
14519 lpfc_io_resume_s3(struct pci_dev *pdev)
14520 {
14521 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
14522 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14523 
14524 	/* Bring device online, it will be no-op for non-fatal error resume */
14525 	lpfc_online(phba);
14526 }
14527 
14528 /**
14529  * lpfc_sli4_get_els_iocb_cnt - Calculate the # of ELS IOCBs to reserve
14530  * @phba: pointer to lpfc hba data structure.
14531  *
14532  * returns the number of ELS/CT IOCBs to reserve
14533  **/
14534 int
14535 lpfc_sli4_get_els_iocb_cnt(struct lpfc_hba *phba)
14536 {
14537 	int max_xri = phba->sli4_hba.max_cfg_param.max_xri;
14538 
14539 	if (phba->sli_rev == LPFC_SLI_REV4) {
14540 		if (max_xri <= 100)
14541 			return 10;
14542 		else if (max_xri <= 256)
14543 			return 25;
14544 		else if (max_xri <= 512)
14545 			return 50;
14546 		else if (max_xri <= 1024)
14547 			return 100;
14548 		else if (max_xri <= 1536)
14549 			return 150;
14550 		else if (max_xri <= 2048)
14551 			return 200;
14552 		else
14553 			return 250;
14554 	} else
14555 		return 0;
14556 }
14557 
14558 /**
14559  * lpfc_sli4_get_iocb_cnt - Calculate the # of total IOCBs to reserve
14560  * @phba: pointer to lpfc hba data structure.
14561  *
14562  * returns the number of ELS/CT + NVMET IOCBs to reserve
14563  **/
14564 int
14565 lpfc_sli4_get_iocb_cnt(struct lpfc_hba *phba)
14566 {
14567 	int max_xri = lpfc_sli4_get_els_iocb_cnt(phba);
14568 
14569 	if (phba->nvmet_support)
14570 		max_xri += LPFC_NVMET_BUF_POST;
14571 	return max_xri;
14572 }
14573 
14574 
14575 static int
14576 lpfc_log_write_firmware_error(struct lpfc_hba *phba, uint32_t offset,
14577 	uint32_t magic_number, uint32_t ftype, uint32_t fid, uint32_t fsize,
14578 	const struct firmware *fw)
14579 {
14580 	int rc;
14581 	u8 sli_family;
14582 
14583 	sli_family = bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf);
14584 	/* Three cases:  (1) FW was not supported on the detected adapter.
14585 	 * (2) FW update has been locked out administratively.
14586 	 * (3) Some other error during FW update.
14587 	 * In each case, an unmaskable message is written to the console
14588 	 * for admin diagnosis.
14589 	 */
14590 	if (offset == ADD_STATUS_FW_NOT_SUPPORTED ||
14591 	    (sli_family == LPFC_SLI_INTF_FAMILY_G6 &&
14592 	     magic_number != MAGIC_NUMBER_G6) ||
14593 	    (sli_family == LPFC_SLI_INTF_FAMILY_G7 &&
14594 	     magic_number != MAGIC_NUMBER_G7) ||
14595 	    (sli_family == LPFC_SLI_INTF_FAMILY_G7P &&
14596 	     magic_number != MAGIC_NUMBER_G7P)) {
14597 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14598 				"3030 This firmware version is not supported on"
14599 				" this HBA model. Device:%x Magic:%x Type:%x "
14600 				"ID:%x Size %d %zd\n",
14601 				phba->pcidev->device, magic_number, ftype, fid,
14602 				fsize, fw->size);
14603 		rc = -EINVAL;
14604 	} else if (offset == ADD_STATUS_FW_DOWNLOAD_HW_DISABLED) {
14605 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14606 				"3021 Firmware downloads have been prohibited "
14607 				"by a system configuration setting on "
14608 				"Device:%x Magic:%x Type:%x ID:%x Size %d "
14609 				"%zd\n",
14610 				phba->pcidev->device, magic_number, ftype, fid,
14611 				fsize, fw->size);
14612 		rc = -EACCES;
14613 	} else {
14614 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14615 				"3022 FW Download failed. Add Status x%x "
14616 				"Device:%x Magic:%x Type:%x ID:%x Size %d "
14617 				"%zd\n",
14618 				offset, phba->pcidev->device, magic_number,
14619 				ftype, fid, fsize, fw->size);
14620 		rc = -EIO;
14621 	}
14622 	return rc;
14623 }
14624 
14625 /**
14626  * lpfc_write_firmware - attempt to write a firmware image to the port
14627  * @fw: pointer to firmware image returned from request_firmware.
14628  * @context: pointer to firmware image returned from request_firmware.
14629  *
14630  **/
14631 static void
14632 lpfc_write_firmware(const struct firmware *fw, void *context)
14633 {
14634 	struct lpfc_hba *phba = (struct lpfc_hba *)context;
14635 	char fwrev[FW_REV_STR_SIZE];
14636 	struct lpfc_grp_hdr *image;
14637 	struct list_head dma_buffer_list;
14638 	int i, rc = 0;
14639 	struct lpfc_dmabuf *dmabuf, *next;
14640 	uint32_t offset = 0, temp_offset = 0;
14641 	uint32_t magic_number, ftype, fid, fsize;
14642 
14643 	/* It can be null in no-wait mode, sanity check */
14644 	if (!fw) {
14645 		rc = -ENXIO;
14646 		goto out;
14647 	}
14648 	image = (struct lpfc_grp_hdr *)fw->data;
14649 
14650 	magic_number = be32_to_cpu(image->magic_number);
14651 	ftype = bf_get_be32(lpfc_grp_hdr_file_type, image);
14652 	fid = bf_get_be32(lpfc_grp_hdr_id, image);
14653 	fsize = be32_to_cpu(image->size);
14654 
14655 	INIT_LIST_HEAD(&dma_buffer_list);
14656 	lpfc_decode_firmware_rev(phba, fwrev, 1);
14657 	if (strncmp(fwrev, image->revision, strnlen(image->revision, 16))) {
14658 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14659 				"3023 Updating Firmware, Current Version:%s "
14660 				"New Version:%s\n",
14661 				fwrev, image->revision);
14662 		for (i = 0; i < LPFC_MBX_WR_CONFIG_MAX_BDE; i++) {
14663 			dmabuf = kzalloc(sizeof(struct lpfc_dmabuf),
14664 					 GFP_KERNEL);
14665 			if (!dmabuf) {
14666 				rc = -ENOMEM;
14667 				goto release_out;
14668 			}
14669 			dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
14670 							  SLI4_PAGE_SIZE,
14671 							  &dmabuf->phys,
14672 							  GFP_KERNEL);
14673 			if (!dmabuf->virt) {
14674 				kfree(dmabuf);
14675 				rc = -ENOMEM;
14676 				goto release_out;
14677 			}
14678 			list_add_tail(&dmabuf->list, &dma_buffer_list);
14679 		}
14680 		while (offset < fw->size) {
14681 			temp_offset = offset;
14682 			list_for_each_entry(dmabuf, &dma_buffer_list, list) {
14683 				if (temp_offset + SLI4_PAGE_SIZE > fw->size) {
14684 					memcpy(dmabuf->virt,
14685 					       fw->data + temp_offset,
14686 					       fw->size - temp_offset);
14687 					temp_offset = fw->size;
14688 					break;
14689 				}
14690 				memcpy(dmabuf->virt, fw->data + temp_offset,
14691 				       SLI4_PAGE_SIZE);
14692 				temp_offset += SLI4_PAGE_SIZE;
14693 			}
14694 			rc = lpfc_wr_object(phba, &dma_buffer_list,
14695 				    (fw->size - offset), &offset);
14696 			if (rc) {
14697 				rc = lpfc_log_write_firmware_error(phba, offset,
14698 								   magic_number,
14699 								   ftype,
14700 								   fid,
14701 								   fsize,
14702 								   fw);
14703 				goto release_out;
14704 			}
14705 		}
14706 		rc = offset;
14707 	} else
14708 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14709 				"3029 Skipped Firmware update, Current "
14710 				"Version:%s New Version:%s\n",
14711 				fwrev, image->revision);
14712 
14713 release_out:
14714 	list_for_each_entry_safe(dmabuf, next, &dma_buffer_list, list) {
14715 		list_del(&dmabuf->list);
14716 		dma_free_coherent(&phba->pcidev->dev, SLI4_PAGE_SIZE,
14717 				  dmabuf->virt, dmabuf->phys);
14718 		kfree(dmabuf);
14719 	}
14720 	release_firmware(fw);
14721 out:
14722 	if (rc < 0)
14723 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14724 				"3062 Firmware update error, status %d.\n", rc);
14725 	else
14726 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14727 				"3024 Firmware update success: size %d.\n", rc);
14728 }
14729 
14730 /**
14731  * lpfc_sli4_request_firmware_update - Request linux generic firmware upgrade
14732  * @phba: pointer to lpfc hba data structure.
14733  * @fw_upgrade: which firmware to update.
14734  *
14735  * This routine is called to perform Linux generic firmware upgrade on device
14736  * that supports such feature.
14737  **/
14738 int
14739 lpfc_sli4_request_firmware_update(struct lpfc_hba *phba, uint8_t fw_upgrade)
14740 {
14741 	uint8_t file_name[ELX_MODEL_NAME_SIZE];
14742 	int ret;
14743 	const struct firmware *fw;
14744 
14745 	/* Only supported on SLI4 interface type 2 for now */
14746 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) <
14747 	    LPFC_SLI_INTF_IF_TYPE_2)
14748 		return -EPERM;
14749 
14750 	snprintf(file_name, ELX_MODEL_NAME_SIZE, "%s.grp", phba->ModelName);
14751 
14752 	if (fw_upgrade == INT_FW_UPGRADE) {
14753 		ret = request_firmware_nowait(THIS_MODULE, FW_ACTION_UEVENT,
14754 					file_name, &phba->pcidev->dev,
14755 					GFP_KERNEL, (void *)phba,
14756 					lpfc_write_firmware);
14757 	} else if (fw_upgrade == RUN_FW_UPGRADE) {
14758 		ret = request_firmware(&fw, file_name, &phba->pcidev->dev);
14759 		if (!ret)
14760 			lpfc_write_firmware(fw, (void *)phba);
14761 	} else {
14762 		ret = -EINVAL;
14763 	}
14764 
14765 	return ret;
14766 }
14767 
14768 /**
14769  * lpfc_pci_probe_one_s4 - PCI probe func to reg SLI-4 device to PCI subsys
14770  * @pdev: pointer to PCI device
14771  * @pid: pointer to PCI device identifier
14772  *
14773  * This routine is called from the kernel's PCI subsystem to device with
14774  * SLI-4 interface spec. When an Emulex HBA with SLI-4 interface spec is
14775  * presented on PCI bus, the kernel PCI subsystem looks at PCI device-specific
14776  * information of the device and driver to see if the driver state that it
14777  * can support this kind of device. If the match is successful, the driver
14778  * core invokes this routine. If this routine determines it can claim the HBA,
14779  * it does all the initialization that it needs to do to handle the HBA
14780  * properly.
14781  *
14782  * Return code
14783  * 	0 - driver can claim the device
14784  * 	negative value - driver can not claim the device
14785  **/
14786 static int
14787 lpfc_pci_probe_one_s4(struct pci_dev *pdev, const struct pci_device_id *pid)
14788 {
14789 	struct lpfc_hba   *phba;
14790 	struct lpfc_vport *vport = NULL;
14791 	struct Scsi_Host  *shost = NULL;
14792 	int error;
14793 	uint32_t cfg_mode, intr_mode;
14794 
14795 	/* Allocate memory for HBA structure */
14796 	phba = lpfc_hba_alloc(pdev);
14797 	if (!phba)
14798 		return -ENOMEM;
14799 
14800 	INIT_LIST_HEAD(&phba->poll_list);
14801 
14802 	/* Perform generic PCI device enabling operation */
14803 	error = lpfc_enable_pci_dev(phba);
14804 	if (error)
14805 		goto out_free_phba;
14806 
14807 	/* Set up SLI API function jump table for PCI-device group-1 HBAs */
14808 	error = lpfc_api_table_setup(phba, LPFC_PCI_DEV_OC);
14809 	if (error)
14810 		goto out_disable_pci_dev;
14811 
14812 	/* Set up SLI-4 specific device PCI memory space */
14813 	error = lpfc_sli4_pci_mem_setup(phba);
14814 	if (error) {
14815 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14816 				"1410 Failed to set up pci memory space.\n");
14817 		goto out_disable_pci_dev;
14818 	}
14819 
14820 	/* Set up SLI-4 Specific device driver resources */
14821 	error = lpfc_sli4_driver_resource_setup(phba);
14822 	if (error) {
14823 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14824 				"1412 Failed to set up driver resource.\n");
14825 		goto out_unset_pci_mem_s4;
14826 	}
14827 
14828 	INIT_LIST_HEAD(&phba->active_rrq_list);
14829 	INIT_LIST_HEAD(&phba->fcf.fcf_pri_list);
14830 
14831 	/* Set up common device driver resources */
14832 	error = lpfc_setup_driver_resource_phase2(phba);
14833 	if (error) {
14834 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14835 				"1414 Failed to set up driver resource.\n");
14836 		goto out_unset_driver_resource_s4;
14837 	}
14838 
14839 	/* Get the default values for Model Name and Description */
14840 	lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
14841 
14842 	/* Now, trying to enable interrupt and bring up the device */
14843 	cfg_mode = phba->cfg_use_msi;
14844 
14845 	/* Put device to a known state before enabling interrupt */
14846 	phba->pport = NULL;
14847 	lpfc_stop_port(phba);
14848 
14849 	/* Init cpu_map array */
14850 	lpfc_cpu_map_array_init(phba);
14851 
14852 	/* Init hba_eq_hdl array */
14853 	lpfc_hba_eq_hdl_array_init(phba);
14854 
14855 	/* Configure and enable interrupt */
14856 	intr_mode = lpfc_sli4_enable_intr(phba, cfg_mode);
14857 	if (intr_mode == LPFC_INTR_ERROR) {
14858 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14859 				"0426 Failed to enable interrupt.\n");
14860 		error = -ENODEV;
14861 		goto out_unset_driver_resource;
14862 	}
14863 	/* Default to single EQ for non-MSI-X */
14864 	if (phba->intr_type != MSIX) {
14865 		phba->cfg_irq_chann = 1;
14866 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
14867 			if (phba->nvmet_support)
14868 				phba->cfg_nvmet_mrq = 1;
14869 		}
14870 	}
14871 	lpfc_cpu_affinity_check(phba, phba->cfg_irq_chann);
14872 
14873 	/* Create SCSI host to the physical port */
14874 	error = lpfc_create_shost(phba);
14875 	if (error) {
14876 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14877 				"1415 Failed to create scsi host.\n");
14878 		goto out_disable_intr;
14879 	}
14880 	vport = phba->pport;
14881 	shost = lpfc_shost_from_vport(vport); /* save shost for error cleanup */
14882 
14883 	/* Configure sysfs attributes */
14884 	error = lpfc_alloc_sysfs_attr(vport);
14885 	if (error) {
14886 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14887 				"1416 Failed to allocate sysfs attr\n");
14888 		goto out_destroy_shost;
14889 	}
14890 
14891 	/* Set up SLI-4 HBA */
14892 	if (lpfc_sli4_hba_setup(phba)) {
14893 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14894 				"1421 Failed to set up hba\n");
14895 		error = -ENODEV;
14896 		goto out_free_sysfs_attr;
14897 	}
14898 
14899 	/* Log the current active interrupt mode */
14900 	phba->intr_mode = intr_mode;
14901 	lpfc_log_intr_mode(phba, intr_mode);
14902 
14903 	/* Perform post initialization setup */
14904 	lpfc_post_init_setup(phba);
14905 
14906 	/* NVME support in FW earlier in the driver load corrects the
14907 	 * FC4 type making a check for nvme_support unnecessary.
14908 	 */
14909 	if (phba->nvmet_support == 0) {
14910 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
14911 			/* Create NVME binding with nvme_fc_transport. This
14912 			 * ensures the vport is initialized.  If the localport
14913 			 * create fails, it should not unload the driver to
14914 			 * support field issues.
14915 			 */
14916 			error = lpfc_nvme_create_localport(vport);
14917 			if (error) {
14918 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14919 						"6004 NVME registration "
14920 						"failed, error x%x\n",
14921 						error);
14922 			}
14923 		}
14924 	}
14925 
14926 	/* check for firmware upgrade or downgrade */
14927 	if (phba->cfg_request_firmware_upgrade)
14928 		lpfc_sli4_request_firmware_update(phba, INT_FW_UPGRADE);
14929 
14930 	/* Check if there are static vports to be created. */
14931 	lpfc_create_static_vport(phba);
14932 
14933 	timer_setup(&phba->cpuhp_poll_timer, lpfc_sli4_poll_hbtimer, 0);
14934 	cpuhp_state_add_instance_nocalls(lpfc_cpuhp_state, &phba->cpuhp);
14935 
14936 	return 0;
14937 
14938 out_free_sysfs_attr:
14939 	lpfc_free_sysfs_attr(vport);
14940 out_destroy_shost:
14941 	lpfc_destroy_shost(phba);
14942 out_disable_intr:
14943 	lpfc_sli4_disable_intr(phba);
14944 out_unset_driver_resource:
14945 	lpfc_unset_driver_resource_phase2(phba);
14946 out_unset_driver_resource_s4:
14947 	lpfc_sli4_driver_resource_unset(phba);
14948 out_unset_pci_mem_s4:
14949 	lpfc_sli4_pci_mem_unset(phba);
14950 out_disable_pci_dev:
14951 	lpfc_disable_pci_dev(phba);
14952 	if (shost)
14953 		scsi_host_put(shost);
14954 out_free_phba:
14955 	lpfc_hba_free(phba);
14956 	return error;
14957 }
14958 
14959 /**
14960  * lpfc_pci_remove_one_s4 - PCI func to unreg SLI-4 device from PCI subsystem
14961  * @pdev: pointer to PCI device
14962  *
14963  * This routine is called from the kernel's PCI subsystem to device with
14964  * SLI-4 interface spec. When an Emulex HBA with SLI-4 interface spec is
14965  * removed from PCI bus, it performs all the necessary cleanup for the HBA
14966  * device to be removed from the PCI subsystem properly.
14967  **/
14968 static void
14969 lpfc_pci_remove_one_s4(struct pci_dev *pdev)
14970 {
14971 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
14972 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
14973 	struct lpfc_vport **vports;
14974 	struct lpfc_hba *phba = vport->phba;
14975 	int i;
14976 
14977 	/* Mark the device unloading flag */
14978 	spin_lock_irq(&phba->hbalock);
14979 	vport->load_flag |= FC_UNLOADING;
14980 	spin_unlock_irq(&phba->hbalock);
14981 	if (phba->cgn_i)
14982 		lpfc_unreg_congestion_buf(phba);
14983 
14984 	lpfc_free_sysfs_attr(vport);
14985 
14986 	/* Release all the vports against this physical port */
14987 	vports = lpfc_create_vport_work_array(phba);
14988 	if (vports != NULL)
14989 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
14990 			if (vports[i]->port_type == LPFC_PHYSICAL_PORT)
14991 				continue;
14992 			fc_vport_terminate(vports[i]->fc_vport);
14993 		}
14994 	lpfc_destroy_vport_work_array(phba, vports);
14995 
14996 	/* Remove FC host with the physical port */
14997 	fc_remove_host(shost);
14998 	scsi_remove_host(shost);
14999 
15000 	/* Perform ndlp cleanup on the physical port.  The nvme and nvmet
15001 	 * localports are destroyed after to cleanup all transport memory.
15002 	 */
15003 	lpfc_cleanup(vport);
15004 	lpfc_nvmet_destroy_targetport(phba);
15005 	lpfc_nvme_destroy_localport(vport);
15006 
15007 	/* De-allocate multi-XRI pools */
15008 	if (phba->cfg_xri_rebalancing)
15009 		lpfc_destroy_multixri_pools(phba);
15010 
15011 	/*
15012 	 * Bring down the SLI Layer. This step disables all interrupts,
15013 	 * clears the rings, discards all mailbox commands, and resets
15014 	 * the HBA FCoE function.
15015 	 */
15016 	lpfc_debugfs_terminate(vport);
15017 
15018 	lpfc_stop_hba_timers(phba);
15019 	spin_lock_irq(&phba->port_list_lock);
15020 	list_del_init(&vport->listentry);
15021 	spin_unlock_irq(&phba->port_list_lock);
15022 
15023 	/* Perform scsi free before driver resource_unset since scsi
15024 	 * buffers are released to their corresponding pools here.
15025 	 */
15026 	lpfc_io_free(phba);
15027 	lpfc_free_iocb_list(phba);
15028 	lpfc_sli4_hba_unset(phba);
15029 
15030 	lpfc_unset_driver_resource_phase2(phba);
15031 	lpfc_sli4_driver_resource_unset(phba);
15032 
15033 	/* Unmap adapter Control and Doorbell registers */
15034 	lpfc_sli4_pci_mem_unset(phba);
15035 
15036 	/* Release PCI resources and disable device's PCI function */
15037 	scsi_host_put(shost);
15038 	lpfc_disable_pci_dev(phba);
15039 
15040 	/* Finally, free the driver's device data structure */
15041 	lpfc_hba_free(phba);
15042 
15043 	return;
15044 }
15045 
15046 /**
15047  * lpfc_pci_suspend_one_s4 - PCI func to suspend SLI-4 device for power mgmnt
15048  * @dev_d: pointer to device
15049  *
15050  * This routine is called from the kernel's PCI subsystem to support system
15051  * Power Management (PM) to device with SLI-4 interface spec. When PM invokes
15052  * this method, it quiesces the device by stopping the driver's worker
15053  * thread for the device, turning off device's interrupt and DMA, and bring
15054  * the device offline. Note that as the driver implements the minimum PM
15055  * requirements to a power-aware driver's PM support for suspend/resume -- all
15056  * the possible PM messages (SUSPEND, HIBERNATE, FREEZE) to the suspend()
15057  * method call will be treated as SUSPEND and the driver will fully
15058  * reinitialize its device during resume() method call, the driver will set
15059  * device to PCI_D3hot state in PCI config space instead of setting it
15060  * according to the @msg provided by the PM.
15061  *
15062  * Return code
15063  * 	0 - driver suspended the device
15064  * 	Error otherwise
15065  **/
15066 static int __maybe_unused
15067 lpfc_pci_suspend_one_s4(struct device *dev_d)
15068 {
15069 	struct Scsi_Host *shost = dev_get_drvdata(dev_d);
15070 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15071 
15072 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
15073 			"2843 PCI device Power Management suspend.\n");
15074 
15075 	/* Bring down the device */
15076 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
15077 	lpfc_offline(phba);
15078 	kthread_stop(phba->worker_thread);
15079 
15080 	/* Disable interrupt from device */
15081 	lpfc_sli4_disable_intr(phba);
15082 	lpfc_sli4_queue_destroy(phba);
15083 
15084 	return 0;
15085 }
15086 
15087 /**
15088  * lpfc_pci_resume_one_s4 - PCI func to resume SLI-4 device for power mgmnt
15089  * @dev_d: pointer to device
15090  *
15091  * This routine is called from the kernel's PCI subsystem to support system
15092  * Power Management (PM) to device with SLI-4 interface spac. When PM invokes
15093  * this method, it restores the device's PCI config space state and fully
15094  * reinitializes the device and brings it online. Note that as the driver
15095  * implements the minimum PM requirements to a power-aware driver's PM for
15096  * suspend/resume -- all the possible PM messages (SUSPEND, HIBERNATE, FREEZE)
15097  * to the suspend() method call will be treated as SUSPEND and the driver
15098  * will fully reinitialize its device during resume() method call, the device
15099  * will be set to PCI_D0 directly in PCI config space before restoring the
15100  * state.
15101  *
15102  * Return code
15103  * 	0 - driver suspended the device
15104  * 	Error otherwise
15105  **/
15106 static int __maybe_unused
15107 lpfc_pci_resume_one_s4(struct device *dev_d)
15108 {
15109 	struct Scsi_Host *shost = dev_get_drvdata(dev_d);
15110 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15111 	uint32_t intr_mode;
15112 	int error;
15113 
15114 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
15115 			"0292 PCI device Power Management resume.\n");
15116 
15117 	 /* Startup the kernel thread for this host adapter. */
15118 	phba->worker_thread = kthread_run(lpfc_do_work, phba,
15119 					"lpfc_worker_%d", phba->brd_no);
15120 	if (IS_ERR(phba->worker_thread)) {
15121 		error = PTR_ERR(phba->worker_thread);
15122 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15123 				"0293 PM resume failed to start worker "
15124 				"thread: error=x%x.\n", error);
15125 		return error;
15126 	}
15127 
15128 	/* Configure and enable interrupt */
15129 	intr_mode = lpfc_sli4_enable_intr(phba, phba->intr_mode);
15130 	if (intr_mode == LPFC_INTR_ERROR) {
15131 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15132 				"0294 PM resume Failed to enable interrupt\n");
15133 		return -EIO;
15134 	} else
15135 		phba->intr_mode = intr_mode;
15136 
15137 	/* Restart HBA and bring it online */
15138 	lpfc_sli_brdrestart(phba);
15139 	lpfc_online(phba);
15140 
15141 	/* Log the current active interrupt mode */
15142 	lpfc_log_intr_mode(phba, phba->intr_mode);
15143 
15144 	return 0;
15145 }
15146 
15147 /**
15148  * lpfc_sli4_prep_dev_for_recover - Prepare SLI4 device for pci slot recover
15149  * @phba: pointer to lpfc hba data structure.
15150  *
15151  * This routine is called to prepare the SLI4 device for PCI slot recover. It
15152  * aborts all the outstanding SCSI I/Os to the pci device.
15153  **/
15154 static void
15155 lpfc_sli4_prep_dev_for_recover(struct lpfc_hba *phba)
15156 {
15157 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15158 			"2828 PCI channel I/O abort preparing for recovery\n");
15159 	/*
15160 	 * There may be errored I/Os through HBA, abort all I/Os on txcmplq
15161 	 * and let the SCSI mid-layer to retry them to recover.
15162 	 */
15163 	lpfc_sli_abort_fcp_rings(phba);
15164 }
15165 
15166 /**
15167  * lpfc_sli4_prep_dev_for_reset - Prepare SLI4 device for pci slot reset
15168  * @phba: pointer to lpfc hba data structure.
15169  *
15170  * This routine is called to prepare the SLI4 device for PCI slot reset. It
15171  * disables the device interrupt and pci device, and aborts the internal FCP
15172  * pending I/Os.
15173  **/
15174 static void
15175 lpfc_sli4_prep_dev_for_reset(struct lpfc_hba *phba)
15176 {
15177 	int offline =  pci_channel_offline(phba->pcidev);
15178 
15179 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15180 			"2826 PCI channel disable preparing for reset offline"
15181 			" %d\n", offline);
15182 
15183 	/* Block any management I/Os to the device */
15184 	lpfc_block_mgmt_io(phba, LPFC_MBX_NO_WAIT);
15185 
15186 
15187 	/* HBA_PCI_ERR was set in io_error_detect */
15188 	lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
15189 	/* Flush all driver's outstanding I/Os as we are to reset */
15190 	lpfc_sli_flush_io_rings(phba);
15191 	lpfc_offline(phba);
15192 
15193 	/* stop all timers */
15194 	lpfc_stop_hba_timers(phba);
15195 
15196 	lpfc_sli4_queue_destroy(phba);
15197 	/* Disable interrupt and pci device */
15198 	lpfc_sli4_disable_intr(phba);
15199 	pci_disable_device(phba->pcidev);
15200 }
15201 
15202 /**
15203  * lpfc_sli4_prep_dev_for_perm_failure - Prepare SLI4 dev for pci slot disable
15204  * @phba: pointer to lpfc hba data structure.
15205  *
15206  * This routine is called to prepare the SLI4 device for PCI slot permanently
15207  * disabling. It blocks the SCSI transport layer traffic and flushes the FCP
15208  * pending I/Os.
15209  **/
15210 static void
15211 lpfc_sli4_prep_dev_for_perm_failure(struct lpfc_hba *phba)
15212 {
15213 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15214 			"2827 PCI channel permanent disable for failure\n");
15215 
15216 	/* Block all SCSI devices' I/Os on the host */
15217 	lpfc_scsi_dev_block(phba);
15218 
15219 	/* stop all timers */
15220 	lpfc_stop_hba_timers(phba);
15221 
15222 	/* Clean up all driver's outstanding I/Os */
15223 	lpfc_sli_flush_io_rings(phba);
15224 }
15225 
15226 /**
15227  * lpfc_io_error_detected_s4 - Method for handling PCI I/O error to SLI-4 device
15228  * @pdev: pointer to PCI device.
15229  * @state: the current PCI connection state.
15230  *
15231  * This routine is called from the PCI subsystem for error handling to device
15232  * with SLI-4 interface spec. This function is called by the PCI subsystem
15233  * after a PCI bus error affecting this device has been detected. When this
15234  * function is invoked, it will need to stop all the I/Os and interrupt(s)
15235  * to the device. Once that is done, it will return PCI_ERS_RESULT_NEED_RESET
15236  * for the PCI subsystem to perform proper recovery as desired.
15237  *
15238  * Return codes
15239  * 	PCI_ERS_RESULT_NEED_RESET - need to reset before recovery
15240  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15241  **/
15242 static pci_ers_result_t
15243 lpfc_io_error_detected_s4(struct pci_dev *pdev, pci_channel_state_t state)
15244 {
15245 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15246 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15247 	bool hba_pci_err;
15248 
15249 	switch (state) {
15250 	case pci_channel_io_normal:
15251 		/* Non-fatal error, prepare for recovery */
15252 		lpfc_sli4_prep_dev_for_recover(phba);
15253 		return PCI_ERS_RESULT_CAN_RECOVER;
15254 	case pci_channel_io_frozen:
15255 		hba_pci_err = test_and_set_bit(HBA_PCI_ERR, &phba->bit_flags);
15256 		/* Fatal error, prepare for slot reset */
15257 		if (!hba_pci_err)
15258 			lpfc_sli4_prep_dev_for_reset(phba);
15259 		else
15260 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15261 					"2832  Already handling PCI error "
15262 					"state: x%x\n", state);
15263 		return PCI_ERS_RESULT_NEED_RESET;
15264 	case pci_channel_io_perm_failure:
15265 		set_bit(HBA_PCI_ERR, &phba->bit_flags);
15266 		/* Permanent failure, prepare for device down */
15267 		lpfc_sli4_prep_dev_for_perm_failure(phba);
15268 		return PCI_ERS_RESULT_DISCONNECT;
15269 	default:
15270 		hba_pci_err = test_and_set_bit(HBA_PCI_ERR, &phba->bit_flags);
15271 		if (!hba_pci_err)
15272 			lpfc_sli4_prep_dev_for_reset(phba);
15273 		/* Unknown state, prepare and request slot reset */
15274 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15275 				"2825 Unknown PCI error state: x%x\n", state);
15276 		lpfc_sli4_prep_dev_for_reset(phba);
15277 		return PCI_ERS_RESULT_NEED_RESET;
15278 	}
15279 }
15280 
15281 /**
15282  * lpfc_io_slot_reset_s4 - Method for restart PCI SLI-4 device from scratch
15283  * @pdev: pointer to PCI device.
15284  *
15285  * This routine is called from the PCI subsystem for error handling to device
15286  * with SLI-4 interface spec. It is called after PCI bus has been reset to
15287  * restart the PCI card from scratch, as if from a cold-boot. During the
15288  * PCI subsystem error recovery, after the driver returns
15289  * PCI_ERS_RESULT_NEED_RESET, the PCI subsystem will perform proper error
15290  * recovery and then call this routine before calling the .resume method to
15291  * recover the device. This function will initialize the HBA device, enable
15292  * the interrupt, but it will just put the HBA to offline state without
15293  * passing any I/O traffic.
15294  *
15295  * Return codes
15296  * 	PCI_ERS_RESULT_RECOVERED - the device has been recovered
15297  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15298  */
15299 static pci_ers_result_t
15300 lpfc_io_slot_reset_s4(struct pci_dev *pdev)
15301 {
15302 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15303 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15304 	struct lpfc_sli *psli = &phba->sli;
15305 	uint32_t intr_mode;
15306 	bool hba_pci_err;
15307 
15308 	dev_printk(KERN_INFO, &pdev->dev, "recovering from a slot reset.\n");
15309 	if (pci_enable_device_mem(pdev)) {
15310 		printk(KERN_ERR "lpfc: Cannot re-enable "
15311 		       "PCI device after reset.\n");
15312 		return PCI_ERS_RESULT_DISCONNECT;
15313 	}
15314 
15315 	pci_restore_state(pdev);
15316 
15317 	hba_pci_err = test_and_clear_bit(HBA_PCI_ERR, &phba->bit_flags);
15318 	if (!hba_pci_err)
15319 		dev_info(&pdev->dev,
15320 			 "hba_pci_err was not set, recovering slot reset.\n");
15321 	/*
15322 	 * As the new kernel behavior of pci_restore_state() API call clears
15323 	 * device saved_state flag, need to save the restored state again.
15324 	 */
15325 	pci_save_state(pdev);
15326 
15327 	if (pdev->is_busmaster)
15328 		pci_set_master(pdev);
15329 
15330 	spin_lock_irq(&phba->hbalock);
15331 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
15332 	spin_unlock_irq(&phba->hbalock);
15333 
15334 	/* Init cpu_map array */
15335 	lpfc_cpu_map_array_init(phba);
15336 	/* Configure and enable interrupt */
15337 	intr_mode = lpfc_sli4_enable_intr(phba, phba->intr_mode);
15338 	if (intr_mode == LPFC_INTR_ERROR) {
15339 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15340 				"2824 Cannot re-enable interrupt after "
15341 				"slot reset.\n");
15342 		return PCI_ERS_RESULT_DISCONNECT;
15343 	} else
15344 		phba->intr_mode = intr_mode;
15345 	lpfc_cpu_affinity_check(phba, phba->cfg_irq_chann);
15346 
15347 	/* Log the current active interrupt mode */
15348 	lpfc_log_intr_mode(phba, phba->intr_mode);
15349 
15350 	return PCI_ERS_RESULT_RECOVERED;
15351 }
15352 
15353 /**
15354  * lpfc_io_resume_s4 - Method for resuming PCI I/O operation to SLI-4 device
15355  * @pdev: pointer to PCI device
15356  *
15357  * This routine is called from the PCI subsystem for error handling to device
15358  * with SLI-4 interface spec. It is called when kernel error recovery tells
15359  * the lpfc driver that it is ok to resume normal PCI operation after PCI bus
15360  * error recovery. After this call, traffic can start to flow from this device
15361  * again.
15362  **/
15363 static void
15364 lpfc_io_resume_s4(struct pci_dev *pdev)
15365 {
15366 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15367 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15368 
15369 	/*
15370 	 * In case of slot reset, as function reset is performed through
15371 	 * mailbox command which needs DMA to be enabled, this operation
15372 	 * has to be moved to the io resume phase. Taking device offline
15373 	 * will perform the necessary cleanup.
15374 	 */
15375 	if (!(phba->sli.sli_flag & LPFC_SLI_ACTIVE)) {
15376 		/* Perform device reset */
15377 		lpfc_sli_brdrestart(phba);
15378 		/* Bring the device back online */
15379 		lpfc_online(phba);
15380 	}
15381 }
15382 
15383 /**
15384  * lpfc_pci_probe_one - lpfc PCI probe func to reg dev to PCI subsystem
15385  * @pdev: pointer to PCI device
15386  * @pid: pointer to PCI device identifier
15387  *
15388  * This routine is to be registered to the kernel's PCI subsystem. When an
15389  * Emulex HBA device is presented on PCI bus, the kernel PCI subsystem looks
15390  * at PCI device-specific information of the device and driver to see if the
15391  * driver state that it can support this kind of device. If the match is
15392  * successful, the driver core invokes this routine. This routine dispatches
15393  * the action to the proper SLI-3 or SLI-4 device probing routine, which will
15394  * do all the initialization that it needs to do to handle the HBA device
15395  * properly.
15396  *
15397  * Return code
15398  * 	0 - driver can claim the device
15399  * 	negative value - driver can not claim the device
15400  **/
15401 static int
15402 lpfc_pci_probe_one(struct pci_dev *pdev, const struct pci_device_id *pid)
15403 {
15404 	int rc;
15405 	struct lpfc_sli_intf intf;
15406 
15407 	if (pci_read_config_dword(pdev, LPFC_SLI_INTF, &intf.word0))
15408 		return -ENODEV;
15409 
15410 	if ((bf_get(lpfc_sli_intf_valid, &intf) == LPFC_SLI_INTF_VALID) &&
15411 	    (bf_get(lpfc_sli_intf_slirev, &intf) == LPFC_SLI_INTF_REV_SLI4))
15412 		rc = lpfc_pci_probe_one_s4(pdev, pid);
15413 	else
15414 		rc = lpfc_pci_probe_one_s3(pdev, pid);
15415 
15416 	return rc;
15417 }
15418 
15419 /**
15420  * lpfc_pci_remove_one - lpfc PCI func to unreg dev from PCI subsystem
15421  * @pdev: pointer to PCI device
15422  *
15423  * This routine is to be registered to the kernel's PCI subsystem. When an
15424  * Emulex HBA is removed from PCI bus, the driver core invokes this routine.
15425  * This routine dispatches the action to the proper SLI-3 or SLI-4 device
15426  * remove routine, which will perform all the necessary cleanup for the
15427  * device to be removed from the PCI subsystem properly.
15428  **/
15429 static void
15430 lpfc_pci_remove_one(struct pci_dev *pdev)
15431 {
15432 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15433 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15434 
15435 	switch (phba->pci_dev_grp) {
15436 	case LPFC_PCI_DEV_LP:
15437 		lpfc_pci_remove_one_s3(pdev);
15438 		break;
15439 	case LPFC_PCI_DEV_OC:
15440 		lpfc_pci_remove_one_s4(pdev);
15441 		break;
15442 	default:
15443 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15444 				"1424 Invalid PCI device group: 0x%x\n",
15445 				phba->pci_dev_grp);
15446 		break;
15447 	}
15448 	return;
15449 }
15450 
15451 /**
15452  * lpfc_pci_suspend_one - lpfc PCI func to suspend dev for power management
15453  * @dev: pointer to device
15454  *
15455  * This routine is to be registered to the kernel's PCI subsystem to support
15456  * system Power Management (PM). When PM invokes this method, it dispatches
15457  * the action to the proper SLI-3 or SLI-4 device suspend routine, which will
15458  * suspend the device.
15459  *
15460  * Return code
15461  * 	0 - driver suspended the device
15462  * 	Error otherwise
15463  **/
15464 static int __maybe_unused
15465 lpfc_pci_suspend_one(struct device *dev)
15466 {
15467 	struct Scsi_Host *shost = dev_get_drvdata(dev);
15468 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15469 	int rc = -ENODEV;
15470 
15471 	switch (phba->pci_dev_grp) {
15472 	case LPFC_PCI_DEV_LP:
15473 		rc = lpfc_pci_suspend_one_s3(dev);
15474 		break;
15475 	case LPFC_PCI_DEV_OC:
15476 		rc = lpfc_pci_suspend_one_s4(dev);
15477 		break;
15478 	default:
15479 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15480 				"1425 Invalid PCI device group: 0x%x\n",
15481 				phba->pci_dev_grp);
15482 		break;
15483 	}
15484 	return rc;
15485 }
15486 
15487 /**
15488  * lpfc_pci_resume_one - lpfc PCI func to resume dev for power management
15489  * @dev: pointer to device
15490  *
15491  * This routine is to be registered to the kernel's PCI subsystem to support
15492  * system Power Management (PM). When PM invokes this method, it dispatches
15493  * the action to the proper SLI-3 or SLI-4 device resume routine, which will
15494  * resume the device.
15495  *
15496  * Return code
15497  * 	0 - driver suspended the device
15498  * 	Error otherwise
15499  **/
15500 static int __maybe_unused
15501 lpfc_pci_resume_one(struct device *dev)
15502 {
15503 	struct Scsi_Host *shost = dev_get_drvdata(dev);
15504 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15505 	int rc = -ENODEV;
15506 
15507 	switch (phba->pci_dev_grp) {
15508 	case LPFC_PCI_DEV_LP:
15509 		rc = lpfc_pci_resume_one_s3(dev);
15510 		break;
15511 	case LPFC_PCI_DEV_OC:
15512 		rc = lpfc_pci_resume_one_s4(dev);
15513 		break;
15514 	default:
15515 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15516 				"1426 Invalid PCI device group: 0x%x\n",
15517 				phba->pci_dev_grp);
15518 		break;
15519 	}
15520 	return rc;
15521 }
15522 
15523 /**
15524  * lpfc_io_error_detected - lpfc method for handling PCI I/O error
15525  * @pdev: pointer to PCI device.
15526  * @state: the current PCI connection state.
15527  *
15528  * This routine is registered to the PCI subsystem for error handling. This
15529  * function is called by the PCI subsystem after a PCI bus error affecting
15530  * this device has been detected. When this routine is invoked, it dispatches
15531  * the action to the proper SLI-3 or SLI-4 device error detected handling
15532  * routine, which will perform the proper error detected operation.
15533  *
15534  * Return codes
15535  * 	PCI_ERS_RESULT_NEED_RESET - need to reset before recovery
15536  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15537  **/
15538 static pci_ers_result_t
15539 lpfc_io_error_detected(struct pci_dev *pdev, pci_channel_state_t state)
15540 {
15541 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15542 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15543 	pci_ers_result_t rc = PCI_ERS_RESULT_DISCONNECT;
15544 
15545 	if (phba->link_state == LPFC_HBA_ERROR &&
15546 	    phba->hba_flag & HBA_IOQ_FLUSH)
15547 		return PCI_ERS_RESULT_NEED_RESET;
15548 
15549 	switch (phba->pci_dev_grp) {
15550 	case LPFC_PCI_DEV_LP:
15551 		rc = lpfc_io_error_detected_s3(pdev, state);
15552 		break;
15553 	case LPFC_PCI_DEV_OC:
15554 		rc = lpfc_io_error_detected_s4(pdev, state);
15555 		break;
15556 	default:
15557 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15558 				"1427 Invalid PCI device group: 0x%x\n",
15559 				phba->pci_dev_grp);
15560 		break;
15561 	}
15562 	return rc;
15563 }
15564 
15565 /**
15566  * lpfc_io_slot_reset - lpfc method for restart PCI dev from scratch
15567  * @pdev: pointer to PCI device.
15568  *
15569  * This routine is registered to the PCI subsystem for error handling. This
15570  * function is called after PCI bus has been reset to restart the PCI card
15571  * from scratch, as if from a cold-boot. When this routine is invoked, it
15572  * dispatches the action to the proper SLI-3 or SLI-4 device reset handling
15573  * routine, which will perform the proper device reset.
15574  *
15575  * Return codes
15576  * 	PCI_ERS_RESULT_RECOVERED - the device has been recovered
15577  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15578  **/
15579 static pci_ers_result_t
15580 lpfc_io_slot_reset(struct pci_dev *pdev)
15581 {
15582 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15583 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15584 	pci_ers_result_t rc = PCI_ERS_RESULT_DISCONNECT;
15585 
15586 	switch (phba->pci_dev_grp) {
15587 	case LPFC_PCI_DEV_LP:
15588 		rc = lpfc_io_slot_reset_s3(pdev);
15589 		break;
15590 	case LPFC_PCI_DEV_OC:
15591 		rc = lpfc_io_slot_reset_s4(pdev);
15592 		break;
15593 	default:
15594 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15595 				"1428 Invalid PCI device group: 0x%x\n",
15596 				phba->pci_dev_grp);
15597 		break;
15598 	}
15599 	return rc;
15600 }
15601 
15602 /**
15603  * lpfc_io_resume - lpfc method for resuming PCI I/O operation
15604  * @pdev: pointer to PCI device
15605  *
15606  * This routine is registered to the PCI subsystem for error handling. It
15607  * is called when kernel error recovery tells the lpfc driver that it is
15608  * OK to resume normal PCI operation after PCI bus error recovery. When
15609  * this routine is invoked, it dispatches the action to the proper SLI-3
15610  * or SLI-4 device io_resume routine, which will resume the device operation.
15611  **/
15612 static void
15613 lpfc_io_resume(struct pci_dev *pdev)
15614 {
15615 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15616 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15617 
15618 	switch (phba->pci_dev_grp) {
15619 	case LPFC_PCI_DEV_LP:
15620 		lpfc_io_resume_s3(pdev);
15621 		break;
15622 	case LPFC_PCI_DEV_OC:
15623 		lpfc_io_resume_s4(pdev);
15624 		break;
15625 	default:
15626 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15627 				"1429 Invalid PCI device group: 0x%x\n",
15628 				phba->pci_dev_grp);
15629 		break;
15630 	}
15631 	return;
15632 }
15633 
15634 /**
15635  * lpfc_sli4_oas_verify - Verify OAS is supported by this adapter
15636  * @phba: pointer to lpfc hba data structure.
15637  *
15638  * This routine checks to see if OAS is supported for this adapter. If
15639  * supported, the configure Flash Optimized Fabric flag is set.  Otherwise,
15640  * the enable oas flag is cleared and the pool created for OAS device data
15641  * is destroyed.
15642  *
15643  **/
15644 static void
15645 lpfc_sli4_oas_verify(struct lpfc_hba *phba)
15646 {
15647 
15648 	if (!phba->cfg_EnableXLane)
15649 		return;
15650 
15651 	if (phba->sli4_hba.pc_sli4_params.oas_supported) {
15652 		phba->cfg_fof = 1;
15653 	} else {
15654 		phba->cfg_fof = 0;
15655 		mempool_destroy(phba->device_data_mem_pool);
15656 		phba->device_data_mem_pool = NULL;
15657 	}
15658 
15659 	return;
15660 }
15661 
15662 /**
15663  * lpfc_sli4_ras_init - Verify RAS-FW log is supported by this adapter
15664  * @phba: pointer to lpfc hba data structure.
15665  *
15666  * This routine checks to see if RAS is supported by the adapter. Check the
15667  * function through which RAS support enablement is to be done.
15668  **/
15669 void
15670 lpfc_sli4_ras_init(struct lpfc_hba *phba)
15671 {
15672 	/* if ASIC_GEN_NUM >= 0xC) */
15673 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
15674 		    LPFC_SLI_INTF_IF_TYPE_6) ||
15675 	    (bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf) ==
15676 		    LPFC_SLI_INTF_FAMILY_G6)) {
15677 		phba->ras_fwlog.ras_hwsupport = true;
15678 		if (phba->cfg_ras_fwlog_func == PCI_FUNC(phba->pcidev->devfn) &&
15679 		    phba->cfg_ras_fwlog_buffsize)
15680 			phba->ras_fwlog.ras_enabled = true;
15681 		else
15682 			phba->ras_fwlog.ras_enabled = false;
15683 	} else {
15684 		phba->ras_fwlog.ras_hwsupport = false;
15685 	}
15686 }
15687 
15688 
15689 MODULE_DEVICE_TABLE(pci, lpfc_id_table);
15690 
15691 static const struct pci_error_handlers lpfc_err_handler = {
15692 	.error_detected = lpfc_io_error_detected,
15693 	.slot_reset = lpfc_io_slot_reset,
15694 	.resume = lpfc_io_resume,
15695 };
15696 
15697 static SIMPLE_DEV_PM_OPS(lpfc_pci_pm_ops_one,
15698 			 lpfc_pci_suspend_one,
15699 			 lpfc_pci_resume_one);
15700 
15701 static struct pci_driver lpfc_driver = {
15702 	.name		= LPFC_DRIVER_NAME,
15703 	.id_table	= lpfc_id_table,
15704 	.probe		= lpfc_pci_probe_one,
15705 	.remove		= lpfc_pci_remove_one,
15706 	.shutdown	= lpfc_pci_remove_one,
15707 	.driver.pm	= &lpfc_pci_pm_ops_one,
15708 	.err_handler    = &lpfc_err_handler,
15709 };
15710 
15711 static const struct file_operations lpfc_mgmt_fop = {
15712 	.owner = THIS_MODULE,
15713 };
15714 
15715 static struct miscdevice lpfc_mgmt_dev = {
15716 	.minor = MISC_DYNAMIC_MINOR,
15717 	.name = "lpfcmgmt",
15718 	.fops = &lpfc_mgmt_fop,
15719 };
15720 
15721 /**
15722  * lpfc_init - lpfc module initialization routine
15723  *
15724  * This routine is to be invoked when the lpfc module is loaded into the
15725  * kernel. The special kernel macro module_init() is used to indicate the
15726  * role of this routine to the kernel as lpfc module entry point.
15727  *
15728  * Return codes
15729  *   0 - successful
15730  *   -ENOMEM - FC attach transport failed
15731  *   all others - failed
15732  */
15733 static int __init
15734 lpfc_init(void)
15735 {
15736 	int error = 0;
15737 
15738 	pr_info(LPFC_MODULE_DESC "\n");
15739 	pr_info(LPFC_COPYRIGHT "\n");
15740 
15741 	error = misc_register(&lpfc_mgmt_dev);
15742 	if (error)
15743 		printk(KERN_ERR "Could not register lpfcmgmt device, "
15744 			"misc_register returned with status %d", error);
15745 
15746 	error = -ENOMEM;
15747 	lpfc_transport_functions.vport_create = lpfc_vport_create;
15748 	lpfc_transport_functions.vport_delete = lpfc_vport_delete;
15749 	lpfc_transport_template =
15750 				fc_attach_transport(&lpfc_transport_functions);
15751 	if (lpfc_transport_template == NULL)
15752 		goto unregister;
15753 	lpfc_vport_transport_template =
15754 		fc_attach_transport(&lpfc_vport_transport_functions);
15755 	if (lpfc_vport_transport_template == NULL) {
15756 		fc_release_transport(lpfc_transport_template);
15757 		goto unregister;
15758 	}
15759 	lpfc_wqe_cmd_template();
15760 	lpfc_nvmet_cmd_template();
15761 
15762 	/* Initialize in case vector mapping is needed */
15763 	lpfc_present_cpu = num_present_cpus();
15764 
15765 	lpfc_pldv_detect = false;
15766 
15767 	error = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN,
15768 					"lpfc/sli4:online",
15769 					lpfc_cpu_online, lpfc_cpu_offline);
15770 	if (error < 0)
15771 		goto cpuhp_failure;
15772 	lpfc_cpuhp_state = error;
15773 
15774 	error = pci_register_driver(&lpfc_driver);
15775 	if (error)
15776 		goto unwind;
15777 
15778 	return error;
15779 
15780 unwind:
15781 	cpuhp_remove_multi_state(lpfc_cpuhp_state);
15782 cpuhp_failure:
15783 	fc_release_transport(lpfc_transport_template);
15784 	fc_release_transport(lpfc_vport_transport_template);
15785 unregister:
15786 	misc_deregister(&lpfc_mgmt_dev);
15787 
15788 	return error;
15789 }
15790 
15791 void lpfc_dmp_dbg(struct lpfc_hba *phba)
15792 {
15793 	unsigned int start_idx;
15794 	unsigned int dbg_cnt;
15795 	unsigned int temp_idx;
15796 	int i;
15797 	int j = 0;
15798 	unsigned long rem_nsec;
15799 
15800 	if (atomic_cmpxchg(&phba->dbg_log_dmping, 0, 1) != 0)
15801 		return;
15802 
15803 	start_idx = (unsigned int)atomic_read(&phba->dbg_log_idx) % DBG_LOG_SZ;
15804 	dbg_cnt = (unsigned int)atomic_read(&phba->dbg_log_cnt);
15805 	if (!dbg_cnt)
15806 		goto out;
15807 	temp_idx = start_idx;
15808 	if (dbg_cnt >= DBG_LOG_SZ) {
15809 		dbg_cnt = DBG_LOG_SZ;
15810 		temp_idx -= 1;
15811 	} else {
15812 		if ((start_idx + dbg_cnt) > (DBG_LOG_SZ - 1)) {
15813 			temp_idx = (start_idx + dbg_cnt) % DBG_LOG_SZ;
15814 		} else {
15815 			if (start_idx < dbg_cnt)
15816 				start_idx = DBG_LOG_SZ - (dbg_cnt - start_idx);
15817 			else
15818 				start_idx -= dbg_cnt;
15819 		}
15820 	}
15821 	dev_info(&phba->pcidev->dev, "start %d end %d cnt %d\n",
15822 		 start_idx, temp_idx, dbg_cnt);
15823 
15824 	for (i = 0; i < dbg_cnt; i++) {
15825 		if ((start_idx + i) < DBG_LOG_SZ)
15826 			temp_idx = (start_idx + i) % DBG_LOG_SZ;
15827 		else
15828 			temp_idx = j++;
15829 		rem_nsec = do_div(phba->dbg_log[temp_idx].t_ns, NSEC_PER_SEC);
15830 		dev_info(&phba->pcidev->dev, "%d: [%5lu.%06lu] %s",
15831 			 temp_idx,
15832 			 (unsigned long)phba->dbg_log[temp_idx].t_ns,
15833 			 rem_nsec / 1000,
15834 			 phba->dbg_log[temp_idx].log);
15835 	}
15836 out:
15837 	atomic_set(&phba->dbg_log_cnt, 0);
15838 	atomic_set(&phba->dbg_log_dmping, 0);
15839 }
15840 
15841 __printf(2, 3)
15842 void lpfc_dbg_print(struct lpfc_hba *phba, const char *fmt, ...)
15843 {
15844 	unsigned int idx;
15845 	va_list args;
15846 	int dbg_dmping = atomic_read(&phba->dbg_log_dmping);
15847 	struct va_format vaf;
15848 
15849 
15850 	va_start(args, fmt);
15851 	if (unlikely(dbg_dmping)) {
15852 		vaf.fmt = fmt;
15853 		vaf.va = &args;
15854 		dev_info(&phba->pcidev->dev, "%pV", &vaf);
15855 		va_end(args);
15856 		return;
15857 	}
15858 	idx = (unsigned int)atomic_fetch_add(1, &phba->dbg_log_idx) %
15859 		DBG_LOG_SZ;
15860 
15861 	atomic_inc(&phba->dbg_log_cnt);
15862 
15863 	vscnprintf(phba->dbg_log[idx].log,
15864 		   sizeof(phba->dbg_log[idx].log), fmt, args);
15865 	va_end(args);
15866 
15867 	phba->dbg_log[idx].t_ns = local_clock();
15868 }
15869 
15870 /**
15871  * lpfc_exit - lpfc module removal routine
15872  *
15873  * This routine is invoked when the lpfc module is removed from the kernel.
15874  * The special kernel macro module_exit() is used to indicate the role of
15875  * this routine to the kernel as lpfc module exit point.
15876  */
15877 static void __exit
15878 lpfc_exit(void)
15879 {
15880 	misc_deregister(&lpfc_mgmt_dev);
15881 	pci_unregister_driver(&lpfc_driver);
15882 	cpuhp_remove_multi_state(lpfc_cpuhp_state);
15883 	fc_release_transport(lpfc_transport_template);
15884 	fc_release_transport(lpfc_vport_transport_template);
15885 	idr_destroy(&lpfc_hba_index);
15886 }
15887 
15888 module_init(lpfc_init);
15889 module_exit(lpfc_exit);
15890 MODULE_LICENSE("GPL");
15891 MODULE_DESCRIPTION(LPFC_MODULE_DESC);
15892 MODULE_AUTHOR("Broadcom");
15893 MODULE_VERSION("0:" LPFC_DRIVER_VERSION);
15894