xref: /linux/drivers/scsi/lpfc/lpfc_init.c (revision fafb66e5903c2bcfc7b7e259042a8282f18a6faa)
1 /*******************************************************************
2  * This file is part of the Emulex Linux Device Driver for         *
3  * Fibre Channel Host Bus Adapters.                                *
4  * Copyright (C) 2017-2026 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/crc32.h>
26 #include <linux/delay.h>
27 #include <linux/dma-mapping.h>
28 #include <linux/idr.h>
29 #include <linux/interrupt.h>
30 #include <linux/module.h>
31 #include <linux/kthread.h>
32 #include <linux/pci.h>
33 #include <linux/spinlock.h>
34 #include <linux/sched/clock.h>
35 #include <linux/ctype.h>
36 #include <linux/slab.h>
37 #include <linux/firmware.h>
38 #include <linux/miscdevice.h>
39 #include <linux/percpu.h>
40 #include <linux/irq.h>
41 #include <linux/bitops.h>
42 #include <linux/crash_dump.h>
43 #include <linux/cpu.h>
44 #include <linux/cpuhotplug.h>
45 
46 #include <scsi/scsi.h>
47 #include <scsi/scsi_device.h>
48 #include <scsi/scsi_host.h>
49 #include <scsi/scsi_transport_fc.h>
50 #include <scsi/scsi_tcq.h>
51 #include <scsi/fc/fc_fs.h>
52 
53 #include "lpfc_hw4.h"
54 #include "lpfc_hw.h"
55 #include "lpfc_sli.h"
56 #include "lpfc_sli4.h"
57 #include "lpfc_nl.h"
58 #include "lpfc_disc.h"
59 #include "lpfc.h"
60 #include "lpfc_scsi.h"
61 #include "lpfc_nvme.h"
62 #include "lpfc_logmsg.h"
63 #include "lpfc_crtn.h"
64 #include "lpfc_vport.h"
65 #include "lpfc_version.h"
66 #include "lpfc_ids.h"
67 
68 static enum cpuhp_state lpfc_cpuhp_state;
69 /* Used when mapping IRQ vectors in a driver centric manner */
70 static uint32_t lpfc_present_cpu;
71 static bool lpfc_pldv_detect;
72 
73 static void __lpfc_cpuhp_remove(struct lpfc_hba *phba);
74 static void lpfc_cpuhp_remove(struct lpfc_hba *phba);
75 static void lpfc_cpuhp_add(struct lpfc_hba *phba);
76 static void lpfc_get_hba_model_desc(struct lpfc_hba *, uint8_t *, uint8_t *);
77 static int lpfc_post_rcv_buf(struct lpfc_hba *);
78 static int lpfc_sli4_queue_verify(struct lpfc_hba *);
79 static int lpfc_create_bootstrap_mbox(struct lpfc_hba *);
80 static int lpfc_setup_endian_order(struct lpfc_hba *);
81 static void lpfc_destroy_bootstrap_mbox(struct lpfc_hba *);
82 static void lpfc_free_els_sgl_list(struct lpfc_hba *);
83 static void lpfc_free_nvmet_sgl_list(struct lpfc_hba *);
84 static void lpfc_init_sgl_list(struct lpfc_hba *);
85 static int lpfc_init_active_sgl_array(struct lpfc_hba *);
86 static void lpfc_free_active_sgl(struct lpfc_hba *);
87 static int lpfc_hba_down_post_s3(struct lpfc_hba *phba);
88 static int lpfc_hba_down_post_s4(struct lpfc_hba *phba);
89 static int lpfc_sli4_cq_event_pool_create(struct lpfc_hba *);
90 static void lpfc_sli4_cq_event_pool_destroy(struct lpfc_hba *);
91 static void lpfc_sli4_cq_event_release_all(struct lpfc_hba *);
92 static void lpfc_sli4_disable_intr(struct lpfc_hba *);
93 static uint32_t lpfc_sli4_enable_intr(struct lpfc_hba *, uint32_t);
94 static void lpfc_sli4_oas_verify(struct lpfc_hba *phba);
95 static uint16_t lpfc_find_cpu_handle(struct lpfc_hba *, uint16_t, int);
96 static void lpfc_setup_bg(struct lpfc_hba *, struct Scsi_Host *);
97 static int lpfc_sli4_cgn_parm_chg_evt(struct lpfc_hba *);
98 static void lpfc_sli4_async_cmstat_evt(struct lpfc_hba *phba);
99 static void lpfc_sli4_prep_dev_for_reset(struct lpfc_hba *phba);
100 
101 static struct scsi_transport_template *lpfc_transport_template = NULL;
102 static struct scsi_transport_template *lpfc_vport_transport_template = NULL;
103 static DEFINE_IDR(lpfc_hba_index);
104 #define LPFC_NVMET_BUF_POST 254
105 static int lpfc_vmid_res_alloc(struct lpfc_hba *phba, struct lpfc_vport *vport);
106 static void lpfc_cgn_update_tstamp(struct lpfc_hba *phba, struct lpfc_cgn_ts *ts);
107 
108 /**
109  * lpfc_config_port_prep - Perform lpfc initialization prior to config port
110  * @phba: pointer to lpfc hba data structure.
111  *
112  * This routine will do LPFC initialization prior to issuing the CONFIG_PORT
113  * mailbox command. It retrieves the revision information from the HBA and
114  * collects the Vital Product Data (VPD) about the HBA for preparing the
115  * configuration of the HBA.
116  *
117  * Return codes:
118  *   0 - success.
119  *   -ERESTART - requests the SLI layer to reset the HBA and try again.
120  *   Any other value - indicates an error.
121  **/
122 int
123 lpfc_config_port_prep(struct lpfc_hba *phba)
124 {
125 	lpfc_vpd_t *vp = &phba->vpd;
126 	int i = 0, rc;
127 	LPFC_MBOXQ_t *pmb;
128 	MAILBOX_t *mb;
129 	char *lpfc_vpd_data = NULL;
130 	uint16_t offset = 0;
131 	static char licensed[56] =
132 		    "key unlock for use with gnu public licensed code only\0";
133 	static int init_key = 1;
134 
135 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
136 	if (!pmb) {
137 		phba->link_state = LPFC_HBA_ERROR;
138 		return -ENOMEM;
139 	}
140 
141 	mb = &pmb->u.mb;
142 	phba->link_state = LPFC_INIT_MBX_CMDS;
143 
144 	if (lpfc_is_LC_HBA(phba->pcidev->device)) {
145 		if (init_key) {
146 			uint32_t *ptext = (uint32_t *) licensed;
147 
148 			for (i = 0; i < 56; i += sizeof (uint32_t), ptext++)
149 				*ptext = cpu_to_be32(*ptext);
150 			init_key = 0;
151 		}
152 
153 		lpfc_read_nv(phba, pmb);
154 		memset((char*)mb->un.varRDnvp.rsvd3, 0,
155 			sizeof (mb->un.varRDnvp.rsvd3));
156 		memcpy((char*)mb->un.varRDnvp.rsvd3, licensed,
157 			 sizeof (licensed));
158 
159 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
160 
161 		if (rc != MBX_SUCCESS) {
162 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
163 					"0324 Config Port initialization "
164 					"error, mbxCmd x%x READ_NVPARM, "
165 					"mbxStatus x%x\n",
166 					mb->mbxCommand, mb->mbxStatus);
167 			mempool_free(pmb, phba->mbox_mem_pool);
168 			return -ERESTART;
169 		}
170 		memcpy(phba->wwnn, (char *)mb->un.varRDnvp.nodename,
171 		       sizeof(phba->wwnn));
172 		memcpy(phba->wwpn, (char *)mb->un.varRDnvp.portname,
173 		       sizeof(phba->wwpn));
174 	}
175 
176 	/*
177 	 * Clear all option bits except LPFC_SLI3_BG_ENABLED,
178 	 * which was already set in lpfc_get_cfgparam()
179 	 */
180 	phba->sli3_options &= (uint32_t)LPFC_SLI3_BG_ENABLED;
181 
182 	/* Setup and issue mailbox READ REV command */
183 	lpfc_read_rev(phba, pmb);
184 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
185 	if (rc != MBX_SUCCESS) {
186 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
187 				"0439 Adapter failed to init, mbxCmd x%x "
188 				"READ_REV, mbxStatus x%x\n",
189 				mb->mbxCommand, mb->mbxStatus);
190 		mempool_free( pmb, phba->mbox_mem_pool);
191 		return -ERESTART;
192 	}
193 
194 
195 	/*
196 	 * The value of rr must be 1 since the driver set the cv field to 1.
197 	 * This setting requires the FW to set all revision fields.
198 	 */
199 	if (mb->un.varRdRev.rr == 0) {
200 		vp->rev.rBit = 0;
201 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
202 				"0440 Adapter failed to init, READ_REV has "
203 				"missing revision information.\n");
204 		mempool_free(pmb, phba->mbox_mem_pool);
205 		return -ERESTART;
206 	}
207 
208 	if (phba->sli_rev == 3 && !mb->un.varRdRev.v3rsp) {
209 		mempool_free(pmb, phba->mbox_mem_pool);
210 		return -EINVAL;
211 	}
212 
213 	/* Save information as VPD data */
214 	vp->rev.rBit = 1;
215 	memcpy(&vp->sli3Feat, &mb->un.varRdRev.sli3Feat, sizeof(uint32_t));
216 	vp->rev.sli1FwRev = mb->un.varRdRev.sli1FwRev;
217 	memcpy(vp->rev.sli1FwName, (char*) mb->un.varRdRev.sli1FwName, 16);
218 	vp->rev.sli2FwRev = mb->un.varRdRev.sli2FwRev;
219 	memcpy(vp->rev.sli2FwName, (char *) mb->un.varRdRev.sli2FwName, 16);
220 	vp->rev.biuRev = mb->un.varRdRev.biuRev;
221 	vp->rev.smRev = mb->un.varRdRev.smRev;
222 	vp->rev.smFwRev = mb->un.varRdRev.un.smFwRev;
223 	vp->rev.endecRev = mb->un.varRdRev.endecRev;
224 	vp->rev.fcphHigh = mb->un.varRdRev.fcphHigh;
225 	vp->rev.fcphLow = mb->un.varRdRev.fcphLow;
226 	vp->rev.feaLevelHigh = mb->un.varRdRev.feaLevelHigh;
227 	vp->rev.feaLevelLow = mb->un.varRdRev.feaLevelLow;
228 	vp->rev.postKernRev = mb->un.varRdRev.postKernRev;
229 	vp->rev.opFwRev = mb->un.varRdRev.opFwRev;
230 
231 	/* If the sli feature level is less then 9, we must
232 	 * tear down all RPIs and VPIs on link down if NPIV
233 	 * is enabled.
234 	 */
235 	if (vp->rev.feaLevelHigh < 9)
236 		phba->sli3_options |= LPFC_SLI3_VPORT_TEARDOWN;
237 
238 	if (lpfc_is_LC_HBA(phba->pcidev->device))
239 		memcpy(phba->RandomData, (char *)&mb->un.varWords[24],
240 						sizeof (phba->RandomData));
241 
242 	/* Get adapter VPD information */
243 	lpfc_vpd_data = kmalloc(DMP_VPD_SIZE, GFP_KERNEL);
244 	if (!lpfc_vpd_data)
245 		goto out_free_mbox;
246 	do {
247 		lpfc_dump_mem(phba, pmb, offset, DMP_REGION_VPD);
248 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
249 
250 		if (rc != MBX_SUCCESS) {
251 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
252 					"0441 VPD not present on adapter, "
253 					"mbxCmd x%x DUMP VPD, mbxStatus x%x\n",
254 					mb->mbxCommand, mb->mbxStatus);
255 			mb->un.varDmp.word_cnt = 0;
256 		}
257 		/* dump mem may return a zero when finished or we got a
258 		 * mailbox error, either way we are done.
259 		 */
260 		if (mb->un.varDmp.word_cnt == 0)
261 			break;
262 
263 		if (mb->un.varDmp.word_cnt > DMP_VPD_SIZE - offset)
264 			mb->un.varDmp.word_cnt = DMP_VPD_SIZE - offset;
265 		lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
266 				      lpfc_vpd_data + offset,
267 				      mb->un.varDmp.word_cnt);
268 		offset += mb->un.varDmp.word_cnt;
269 	} while (mb->un.varDmp.word_cnt && offset < DMP_VPD_SIZE);
270 
271 	lpfc_parse_vpd(phba, lpfc_vpd_data, offset);
272 
273 	kfree(lpfc_vpd_data);
274 out_free_mbox:
275 	mempool_free(pmb, phba->mbox_mem_pool);
276 	return 0;
277 }
278 
279 /**
280  * lpfc_config_async_cmpl - Completion handler for config async event mbox cmd
281  * @phba: pointer to lpfc hba data structure.
282  * @pmboxq: pointer to the driver internal queue element for mailbox command.
283  *
284  * This is the completion handler for driver's configuring asynchronous event
285  * mailbox command to the device. If the mailbox command returns successfully,
286  * it will set internal async event support flag to 1; otherwise, it will
287  * set internal async event support flag to 0.
288  **/
289 static void
290 lpfc_config_async_cmpl(struct lpfc_hba * phba, LPFC_MBOXQ_t * pmboxq)
291 {
292 	if (pmboxq->u.mb.mbxStatus == MBX_SUCCESS)
293 		phba->temp_sensor_support = 1;
294 	else
295 		phba->temp_sensor_support = 0;
296 	mempool_free(pmboxq, phba->mbox_mem_pool);
297 	return;
298 }
299 
300 /**
301  * lpfc_dump_wakeup_param_cmpl - dump memory mailbox command completion handler
302  * @phba: pointer to lpfc hba data structure.
303  * @pmboxq: pointer to the driver internal queue element for mailbox command.
304  *
305  * This is the completion handler for dump mailbox command for getting
306  * wake up parameters. When this command complete, the response contain
307  * Option rom version of the HBA. This function translate the version number
308  * into a human readable string and store it in OptionROMVersion.
309  **/
310 static void
311 lpfc_dump_wakeup_param_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
312 {
313 	struct prog_id *prg;
314 	uint32_t prog_id_word;
315 	char dist = ' ';
316 	/* character array used for decoding dist type. */
317 	char dist_char[] = "nabx";
318 
319 	if (pmboxq->u.mb.mbxStatus != MBX_SUCCESS) {
320 		mempool_free(pmboxq, phba->mbox_mem_pool);
321 		return;
322 	}
323 
324 	prg = (struct prog_id *) &prog_id_word;
325 
326 	/* word 7 contain option rom version */
327 	prog_id_word = pmboxq->u.mb.un.varWords[7];
328 
329 	/* Decode the Option rom version word to a readable string */
330 	dist = dist_char[prg->dist];
331 
332 	if ((prg->dist == 3) && (prg->num == 0))
333 		snprintf(phba->OptionROMVersion, 32, "%d.%d%d",
334 			prg->ver, prg->rev, prg->lev);
335 	else
336 		snprintf(phba->OptionROMVersion, 32, "%d.%d%d%c%d",
337 			prg->ver, prg->rev, prg->lev,
338 			dist, prg->num);
339 	mempool_free(pmboxq, phba->mbox_mem_pool);
340 	return;
341 }
342 
343 /**
344  * lpfc_update_vport_wwn - Updates the fc_nodename, fc_portname,
345  * @vport: pointer to lpfc vport data structure.
346  *
347  *
348  * Return codes
349  *   None.
350  **/
351 void
352 lpfc_update_vport_wwn(struct lpfc_vport *vport)
353 {
354 	struct lpfc_hba *phba = vport->phba;
355 
356 	/*
357 	 * If the name is empty or there exists a soft name
358 	 * then copy the service params name, otherwise use the fc name
359 	 */
360 	if (vport->fc_nodename.u.wwn[0] == 0)
361 		memcpy(&vport->fc_nodename, &vport->fc_sparam.nodeName,
362 			sizeof(struct lpfc_name));
363 	else
364 		memcpy(&vport->fc_sparam.nodeName, &vport->fc_nodename,
365 			sizeof(struct lpfc_name));
366 
367 	/*
368 	 * If the port name has changed, then set the Param changes flag
369 	 * to unreg the login
370 	 */
371 	if (vport->fc_portname.u.wwn[0] != 0 &&
372 		memcmp(&vport->fc_portname, &vport->fc_sparam.portName,
373 		       sizeof(struct lpfc_name))) {
374 		vport->vport_flag |= FAWWPN_PARAM_CHG;
375 
376 		if (phba->sli_rev == LPFC_SLI_REV4 &&
377 		    vport->port_type == LPFC_PHYSICAL_PORT &&
378 		    phba->sli4_hba.fawwpn_flag & LPFC_FAWWPN_FABRIC) {
379 			if (!(phba->sli4_hba.fawwpn_flag & LPFC_FAWWPN_CONFIG))
380 				phba->sli4_hba.fawwpn_flag &=
381 						~LPFC_FAWWPN_FABRIC;
382 			lpfc_printf_log(phba, KERN_INFO,
383 					LOG_SLI | LOG_DISCOVERY | LOG_ELS,
384 					"2701 FA-PWWN change WWPN from %llx to "
385 					"%llx: vflag x%x fawwpn_flag x%x\n",
386 					wwn_to_u64(vport->fc_portname.u.wwn),
387 					wwn_to_u64
388 					   (vport->fc_sparam.portName.u.wwn),
389 					vport->vport_flag,
390 					phba->sli4_hba.fawwpn_flag);
391 			memcpy(&vport->fc_portname, &vport->fc_sparam.portName,
392 			       sizeof(struct lpfc_name));
393 		}
394 	}
395 
396 	if (vport->fc_portname.u.wwn[0] == 0)
397 		memcpy(&vport->fc_portname, &vport->fc_sparam.portName,
398 		       sizeof(struct lpfc_name));
399 	else
400 		memcpy(&vport->fc_sparam.portName, &vport->fc_portname,
401 		       sizeof(struct lpfc_name));
402 }
403 
404 /**
405  * lpfc_config_port_post - Perform lpfc initialization after config port
406  * @phba: pointer to lpfc hba data structure.
407  *
408  * This routine will do LPFC initialization after the CONFIG_PORT mailbox
409  * command call. It performs all internal resource and state setups on the
410  * port: post IOCB buffers, enable appropriate host interrupt attentions,
411  * ELS ring timers, etc.
412  *
413  * Return codes
414  *   0 - success.
415  *   Any other value - error.
416  **/
417 int
418 lpfc_config_port_post(struct lpfc_hba *phba)
419 {
420 	struct lpfc_vport *vport = phba->pport;
421 	struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
422 	LPFC_MBOXQ_t *pmb;
423 	MAILBOX_t *mb;
424 	struct lpfc_dmabuf *mp;
425 	struct lpfc_sli *psli = &phba->sli;
426 	uint32_t status, timeout;
427 	int i, j;
428 	int rc;
429 
430 	spin_lock_irq(&phba->hbalock);
431 	/*
432 	 * If the Config port completed correctly the HBA is not
433 	 * over heated any more.
434 	 */
435 	if (phba->over_temp_state == HBA_OVER_TEMP)
436 		phba->over_temp_state = HBA_NORMAL_TEMP;
437 	spin_unlock_irq(&phba->hbalock);
438 
439 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
440 	if (!pmb) {
441 		phba->link_state = LPFC_HBA_ERROR;
442 		return -ENOMEM;
443 	}
444 	mb = &pmb->u.mb;
445 
446 	/* Get login parameters for NID.  */
447 	rc = lpfc_read_sparam(phba, pmb, 0);
448 	if (rc) {
449 		mempool_free(pmb, phba->mbox_mem_pool);
450 		return -ENOMEM;
451 	}
452 
453 	pmb->vport = vport;
454 	if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
455 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
456 				"0448 Adapter failed init, mbxCmd x%x "
457 				"READ_SPARM mbxStatus x%x\n",
458 				mb->mbxCommand, mb->mbxStatus);
459 		phba->link_state = LPFC_HBA_ERROR;
460 		lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
461 		return -EIO;
462 	}
463 
464 	mp = pmb->ctx_buf;
465 
466 	/* This dmabuf was allocated by lpfc_read_sparam. The dmabuf is no
467 	 * longer needed.  Prevent unintended ctx_buf access as the mbox is
468 	 * reused.
469 	 */
470 	memcpy(&vport->fc_sparam, mp->virt, sizeof (struct serv_parm));
471 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
472 	kfree(mp);
473 	pmb->ctx_buf = NULL;
474 	lpfc_update_vport_wwn(vport);
475 
476 	/* Update the fc_host data structures with new wwn. */
477 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
478 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
479 	fc_host_max_npiv_vports(shost) = phba->max_vpi;
480 
481 	/* If no serial number in VPD data, use low 6 bytes of WWNN */
482 	/* This should be consolidated into parse_vpd ? - mr */
483 	if (phba->SerialNumber[0] == 0) {
484 		uint8_t *outptr;
485 
486 		outptr = &vport->fc_nodename.u.s.IEEE[0];
487 		for (i = 0; i < 12; i++) {
488 			status = *outptr++;
489 			j = ((status & 0xf0) >> 4);
490 			if (j <= 9)
491 				phba->SerialNumber[i] =
492 				    (char)((uint8_t) 0x30 + (uint8_t) j);
493 			else
494 				phba->SerialNumber[i] =
495 				    (char)((uint8_t) 0x61 + (uint8_t) (j - 10));
496 			i++;
497 			j = (status & 0xf);
498 			if (j <= 9)
499 				phba->SerialNumber[i] =
500 				    (char)((uint8_t) 0x30 + (uint8_t) j);
501 			else
502 				phba->SerialNumber[i] =
503 				    (char)((uint8_t) 0x61 + (uint8_t) (j - 10));
504 		}
505 	}
506 
507 	lpfc_read_config(phba, pmb);
508 	pmb->vport = vport;
509 	if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
510 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
511 				"0453 Adapter failed to init, mbxCmd x%x "
512 				"READ_CONFIG, mbxStatus x%x\n",
513 				mb->mbxCommand, mb->mbxStatus);
514 		phba->link_state = LPFC_HBA_ERROR;
515 		mempool_free( pmb, phba->mbox_mem_pool);
516 		return -EIO;
517 	}
518 
519 	/* Check if the port is disabled */
520 	lpfc_sli_read_link_ste(phba);
521 
522 	/* Reset the DFT_HBA_Q_DEPTH to the max xri  */
523 	if (phba->cfg_hba_queue_depth > mb->un.varRdConfig.max_xri) {
524 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
525 				"3359 HBA queue depth changed from %d to %d\n",
526 				phba->cfg_hba_queue_depth,
527 				mb->un.varRdConfig.max_xri);
528 		phba->cfg_hba_queue_depth = mb->un.varRdConfig.max_xri;
529 	}
530 
531 	phba->lmt = mb->un.varRdConfig.lmt;
532 
533 	/* Get the default values for Model Name and Description */
534 	lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
535 
536 	phba->link_state = LPFC_LINK_DOWN;
537 
538 	/* Only process IOCBs on ELS ring till hba_state is READY */
539 	if (psli->sli3_ring[LPFC_EXTRA_RING].sli.sli3.cmdringaddr)
540 		psli->sli3_ring[LPFC_EXTRA_RING].flag |= LPFC_STOP_IOCB_EVENT;
541 	if (psli->sli3_ring[LPFC_FCP_RING].sli.sli3.cmdringaddr)
542 		psli->sli3_ring[LPFC_FCP_RING].flag |= LPFC_STOP_IOCB_EVENT;
543 
544 	/* Post receive buffers for desired rings */
545 	if (phba->sli_rev != 3)
546 		lpfc_post_rcv_buf(phba);
547 
548 	/*
549 	 * Configure HBA MSI-X attention conditions to messages if MSI-X mode
550 	 */
551 	if (phba->intr_type == MSIX) {
552 		rc = lpfc_config_msi(phba, pmb);
553 		if (rc) {
554 			mempool_free(pmb, phba->mbox_mem_pool);
555 			return -EIO;
556 		}
557 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
558 		if (rc != MBX_SUCCESS) {
559 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
560 					"0352 Config MSI mailbox command "
561 					"failed, mbxCmd x%x, mbxStatus x%x\n",
562 					pmb->u.mb.mbxCommand,
563 					pmb->u.mb.mbxStatus);
564 			mempool_free(pmb, phba->mbox_mem_pool);
565 			return -EIO;
566 		}
567 	}
568 
569 	spin_lock_irq(&phba->hbalock);
570 	/* Initialize ERATT handling flag */
571 	clear_bit(HBA_ERATT_HANDLED, &phba->hba_flag);
572 
573 	/* Enable appropriate host interrupts */
574 	if (lpfc_readl(phba->HCregaddr, &status)) {
575 		spin_unlock_irq(&phba->hbalock);
576 		return -EIO;
577 	}
578 	status |= HC_MBINT_ENA | HC_ERINT_ENA | HC_LAINT_ENA;
579 	if (psli->num_rings > 0)
580 		status |= HC_R0INT_ENA;
581 	if (psli->num_rings > 1)
582 		status |= HC_R1INT_ENA;
583 	if (psli->num_rings > 2)
584 		status |= HC_R2INT_ENA;
585 	if (psli->num_rings > 3)
586 		status |= HC_R3INT_ENA;
587 
588 	if ((phba->cfg_poll & ENABLE_FCP_RING_POLLING) &&
589 	    (phba->cfg_poll & DISABLE_FCP_RING_INT))
590 		status &= ~(HC_R0INT_ENA);
591 
592 	writel(status, phba->HCregaddr);
593 	readl(phba->HCregaddr); /* flush */
594 	spin_unlock_irq(&phba->hbalock);
595 
596 	/* Set up ring-0 (ELS) timer */
597 	timeout = phba->fc_ratov * 2;
598 	mod_timer(&vport->els_tmofunc,
599 		  jiffies + secs_to_jiffies(timeout));
600 	/* Set up heart beat (HB) timer */
601 	mod_timer(&phba->hb_tmofunc,
602 		  jiffies + secs_to_jiffies(LPFC_HB_MBOX_INTERVAL));
603 	clear_bit(HBA_HBEAT_INP, &phba->hba_flag);
604 	clear_bit(HBA_HBEAT_TMO, &phba->hba_flag);
605 	phba->last_completion_time = jiffies;
606 	/* Set up error attention (ERATT) polling timer */
607 	mod_timer(&phba->eratt_poll,
608 		  jiffies + secs_to_jiffies(phba->eratt_poll_interval));
609 
610 	if (test_bit(LINK_DISABLED, &phba->hba_flag)) {
611 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
612 				"2598 Adapter Link is disabled.\n");
613 		lpfc_down_link(phba, pmb);
614 		pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
615 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
616 		if ((rc != MBX_SUCCESS) && (rc != MBX_BUSY)) {
617 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
618 					"2599 Adapter failed to issue DOWN_LINK"
619 					" mbox command rc 0x%x\n", rc);
620 
621 			mempool_free(pmb, phba->mbox_mem_pool);
622 			return -EIO;
623 		}
624 	} else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
625 		mempool_free(pmb, phba->mbox_mem_pool);
626 		rc = phba->lpfc_hba_init_link(phba, MBX_NOWAIT);
627 		if (rc)
628 			return rc;
629 	}
630 	/* MBOX buffer will be freed in mbox compl */
631 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
632 	if (!pmb) {
633 		phba->link_state = LPFC_HBA_ERROR;
634 		return -ENOMEM;
635 	}
636 
637 	lpfc_config_async(phba, pmb, LPFC_ELS_RING);
638 	pmb->mbox_cmpl = lpfc_config_async_cmpl;
639 	pmb->vport = phba->pport;
640 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
641 
642 	if ((rc != MBX_BUSY) && (rc != MBX_SUCCESS)) {
643 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
644 				"0456 Adapter failed to issue "
645 				"ASYNCEVT_ENABLE mbox status x%x\n",
646 				rc);
647 		mempool_free(pmb, phba->mbox_mem_pool);
648 	}
649 
650 	/* Get Option rom version */
651 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
652 	if (!pmb) {
653 		phba->link_state = LPFC_HBA_ERROR;
654 		return -ENOMEM;
655 	}
656 
657 	lpfc_dump_wakeup_param(phba, pmb);
658 	pmb->mbox_cmpl = lpfc_dump_wakeup_param_cmpl;
659 	pmb->vport = phba->pport;
660 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
661 
662 	if ((rc != MBX_BUSY) && (rc != MBX_SUCCESS)) {
663 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
664 				"0435 Adapter failed "
665 				"to get Option ROM version status x%x\n", rc);
666 		mempool_free(pmb, phba->mbox_mem_pool);
667 	}
668 
669 	return 0;
670 }
671 
672 /**
673  * lpfc_sli4_refresh_params - update driver copy of params.
674  * @phba: Pointer to HBA context object.
675  *
676  * This is called to refresh driver copy of dynamic fields from the
677  * common_get_sli4_parameters descriptor.
678  **/
679 int
680 lpfc_sli4_refresh_params(struct lpfc_hba *phba)
681 {
682 	LPFC_MBOXQ_t *mboxq;
683 	struct lpfc_mqe *mqe;
684 	struct lpfc_sli4_parameters *mbx_sli4_parameters;
685 	int length, rc;
686 
687 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
688 	if (!mboxq)
689 		return -ENOMEM;
690 
691 	mqe = &mboxq->u.mqe;
692 	/* Read the port's SLI4 Config Parameters */
693 	length = (sizeof(struct lpfc_mbx_get_sli4_parameters) -
694 		  sizeof(struct lpfc_sli4_cfg_mhdr));
695 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
696 			 LPFC_MBOX_OPCODE_GET_SLI4_PARAMETERS,
697 			 length, LPFC_SLI4_MBX_EMBED);
698 
699 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
700 	if (unlikely(rc)) {
701 		mempool_free(mboxq, phba->mbox_mem_pool);
702 		return rc;
703 	}
704 	mbx_sli4_parameters = &mqe->un.get_sli4_parameters.sli4_parameters;
705 	phba->sli4_hba.pc_sli4_params.mi_cap =
706 		bf_get(cfg_mi_ver, mbx_sli4_parameters);
707 
708 	/* Are we forcing MI off via module parameter? */
709 	if (phba->cfg_enable_mi)
710 		phba->sli4_hba.pc_sli4_params.mi_ver =
711 			bf_get(cfg_mi_ver, mbx_sli4_parameters);
712 	else
713 		phba->sli4_hba.pc_sli4_params.mi_ver = 0;
714 
715 	phba->sli4_hba.pc_sli4_params.cmf =
716 			bf_get(cfg_cmf, mbx_sli4_parameters);
717 	phba->sli4_hba.pc_sli4_params.pls =
718 			bf_get(cfg_pvl, mbx_sli4_parameters);
719 
720 	mempool_free(mboxq, phba->mbox_mem_pool);
721 	return rc;
722 }
723 
724 /**
725  * lpfc_hba_init_link - Initialize the FC link
726  * @phba: pointer to lpfc hba data structure.
727  * @flag: mailbox command issue mode - either MBX_POLL or MBX_NOWAIT
728  *
729  * This routine will issue the INIT_LINK mailbox command call.
730  * It is available to other drivers through the lpfc_hba data
731  * structure for use as a delayed link up mechanism with the
732  * module parameter lpfc_suppress_link_up.
733  *
734  * Return code
735  *		0 - success
736  *		Any other value - error
737  **/
738 static int
739 lpfc_hba_init_link(struct lpfc_hba *phba, uint32_t flag)
740 {
741 	return lpfc_hba_init_link_fc_topology(phba, phba->cfg_topology, flag);
742 }
743 
744 /**
745  * lpfc_hba_init_link_fc_topology - Initialize FC link with desired topology
746  * @phba: pointer to lpfc hba data structure.
747  * @fc_topology: desired fc topology.
748  * @flag: mailbox command issue mode - either MBX_POLL or MBX_NOWAIT
749  *
750  * This routine will issue the INIT_LINK mailbox command call.
751  * It is available to other drivers through the lpfc_hba data
752  * structure for use as a delayed link up mechanism with the
753  * module parameter lpfc_suppress_link_up.
754  *
755  * Return code
756  *              0 - success
757  *              Any other value - error
758  **/
759 int
760 lpfc_hba_init_link_fc_topology(struct lpfc_hba *phba, uint32_t fc_topology,
761 			       uint32_t flag)
762 {
763 	struct lpfc_vport *vport = phba->pport;
764 	LPFC_MBOXQ_t *pmb;
765 	MAILBOX_t *mb;
766 	int rc;
767 
768 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
769 	if (!pmb) {
770 		phba->link_state = LPFC_HBA_ERROR;
771 		return -ENOMEM;
772 	}
773 	mb = &pmb->u.mb;
774 	pmb->vport = vport;
775 
776 	if ((phba->cfg_link_speed > LPFC_USER_LINK_SPEED_MAX) ||
777 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_1G) &&
778 	     !(phba->lmt & LMT_1Gb)) ||
779 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_2G) &&
780 	     !(phba->lmt & LMT_2Gb)) ||
781 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_4G) &&
782 	     !(phba->lmt & LMT_4Gb)) ||
783 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_8G) &&
784 	     !(phba->lmt & LMT_8Gb)) ||
785 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_10G) &&
786 	     !(phba->lmt & LMT_10Gb)) ||
787 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_16G) &&
788 	     !(phba->lmt & LMT_16Gb)) ||
789 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_32G) &&
790 	     !(phba->lmt & LMT_32Gb)) ||
791 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_64G) &&
792 	     !(phba->lmt & LMT_64Gb)) ||
793 	    ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_128G) &&
794 	     !(phba->lmt & LMT_128Gb))) {
795 		/* Reset link speed to auto */
796 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
797 				"1302 Invalid speed for this board:%d "
798 				"Reset link speed to auto.\n",
799 				phba->cfg_link_speed);
800 			phba->cfg_link_speed = LPFC_USER_LINK_SPEED_AUTO;
801 	}
802 	lpfc_init_link(phba, pmb, fc_topology, phba->cfg_link_speed);
803 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
804 	if (phba->sli_rev < LPFC_SLI_REV4)
805 		lpfc_set_loopback_flag(phba);
806 	rc = lpfc_sli_issue_mbox(phba, pmb, flag);
807 	if ((rc != MBX_BUSY) && (rc != MBX_SUCCESS)) {
808 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
809 				"0498 Adapter failed to init, mbxCmd x%x "
810 				"INIT_LINK, mbxStatus x%x\n",
811 				mb->mbxCommand, mb->mbxStatus);
812 		if (phba->sli_rev <= LPFC_SLI_REV3) {
813 			/* Clear all interrupt enable conditions */
814 			writel(0, phba->HCregaddr);
815 			readl(phba->HCregaddr); /* flush */
816 			/* Clear all pending interrupts */
817 			writel(0xffffffff, phba->HAregaddr);
818 			readl(phba->HAregaddr); /* flush */
819 		}
820 		phba->link_state = LPFC_HBA_ERROR;
821 		if (rc != MBX_BUSY || flag == MBX_POLL)
822 			mempool_free(pmb, phba->mbox_mem_pool);
823 		return -EIO;
824 	}
825 	phba->cfg_suppress_link_up = LPFC_INITIALIZE_LINK;
826 	if (flag == MBX_POLL)
827 		mempool_free(pmb, phba->mbox_mem_pool);
828 
829 	return 0;
830 }
831 
832 /**
833  * lpfc_hba_down_link - this routine downs the FC link
834  * @phba: pointer to lpfc hba data structure.
835  * @flag: mailbox command issue mode - either MBX_POLL or MBX_NOWAIT
836  *
837  * This routine will issue the DOWN_LINK mailbox command call.
838  * It is available to other drivers through the lpfc_hba data
839  * structure for use to stop the link.
840  *
841  * Return code
842  *		0 - success
843  *		Any other value - error
844  **/
845 static int
846 lpfc_hba_down_link(struct lpfc_hba *phba, uint32_t flag)
847 {
848 	LPFC_MBOXQ_t *pmb;
849 	int rc;
850 
851 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
852 	if (!pmb) {
853 		phba->link_state = LPFC_HBA_ERROR;
854 		return -ENOMEM;
855 	}
856 
857 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
858 			"0491 Adapter Link is disabled.\n");
859 	lpfc_down_link(phba, pmb);
860 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
861 	rc = lpfc_sli_issue_mbox(phba, pmb, flag);
862 	if ((rc != MBX_SUCCESS) && (rc != MBX_BUSY)) {
863 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
864 				"2522 Adapter failed to issue DOWN_LINK"
865 				" mbox command rc 0x%x\n", rc);
866 
867 		mempool_free(pmb, phba->mbox_mem_pool);
868 		return -EIO;
869 	}
870 	if (flag == MBX_POLL)
871 		mempool_free(pmb, phba->mbox_mem_pool);
872 
873 	return 0;
874 }
875 
876 /**
877  * lpfc_hba_down_prep - Perform lpfc uninitialization prior to HBA reset
878  * @phba: pointer to lpfc HBA data structure.
879  *
880  * This routine will do LPFC uninitialization before the HBA is reset when
881  * bringing down the SLI Layer.
882  *
883  * Return codes
884  *   0 - success.
885  *   Any other value - error.
886  **/
887 int
888 lpfc_hba_down_prep(struct lpfc_hba *phba)
889 {
890 	struct lpfc_vport **vports;
891 	int i;
892 
893 	if (phba->sli_rev <= LPFC_SLI_REV3) {
894 		/* Disable interrupts */
895 		writel(0, phba->HCregaddr);
896 		readl(phba->HCregaddr); /* flush */
897 	}
898 
899 	if (test_bit(FC_UNLOADING, &phba->pport->load_flag))
900 		lpfc_cleanup_discovery_resources(phba->pport);
901 	else {
902 		vports = lpfc_create_vport_work_array(phba);
903 		if (vports != NULL)
904 			for (i = 0; i <= phba->max_vports &&
905 				vports[i] != NULL; i++)
906 				lpfc_cleanup_discovery_resources(vports[i]);
907 		lpfc_destroy_vport_work_array(phba, vports);
908 	}
909 	return 0;
910 }
911 
912 /**
913  * lpfc_sli4_free_sp_events - Cleanup sp_queue_events to free
914  * rspiocb which got deferred
915  *
916  * @phba: pointer to lpfc HBA data structure.
917  *
918  * This routine will cleanup completed slow path events after HBA is reset
919  * when bringing down the SLI Layer.
920  *
921  *
922  * Return codes
923  *   void.
924  **/
925 static void
926 lpfc_sli4_free_sp_events(struct lpfc_hba *phba)
927 {
928 	struct lpfc_iocbq *rspiocbq;
929 	struct hbq_dmabuf *dmabuf;
930 	struct lpfc_cq_event *cq_event;
931 
932 	clear_bit(HBA_SP_QUEUE_EVT, &phba->hba_flag);
933 
934 	while (!list_empty(&phba->sli4_hba.sp_queue_event)) {
935 		/* Get the response iocb from the head of work queue */
936 		spin_lock_irq(&phba->hbalock);
937 		list_remove_head(&phba->sli4_hba.sp_queue_event,
938 				 cq_event, struct lpfc_cq_event, list);
939 		spin_unlock_irq(&phba->hbalock);
940 
941 		switch (bf_get(lpfc_wcqe_c_code, &cq_event->cqe.wcqe_cmpl)) {
942 		case CQE_CODE_COMPL_WQE:
943 			rspiocbq = container_of(cq_event, struct lpfc_iocbq,
944 						 cq_event);
945 			lpfc_sli_release_iocbq(phba, rspiocbq);
946 			break;
947 		case CQE_CODE_RECEIVE:
948 		case CQE_CODE_RECEIVE_V1:
949 			dmabuf = container_of(cq_event, struct hbq_dmabuf,
950 					      cq_event);
951 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
952 		}
953 	}
954 }
955 
956 /**
957  * lpfc_hba_free_post_buf - Perform lpfc uninitialization after HBA reset
958  * @phba: pointer to lpfc HBA data structure.
959  *
960  * This routine will cleanup posted ELS buffers after the HBA is reset
961  * when bringing down the SLI Layer.
962  *
963  *
964  * Return codes
965  *   void.
966  **/
967 static void
968 lpfc_hba_free_post_buf(struct lpfc_hba *phba)
969 {
970 	struct lpfc_sli *psli = &phba->sli;
971 	struct lpfc_sli_ring *pring;
972 	struct lpfc_dmabuf *mp, *next_mp;
973 	LIST_HEAD(buflist);
974 	int count;
975 
976 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)
977 		lpfc_sli_hbqbuf_free_all(phba);
978 	else {
979 		/* Cleanup preposted buffers on the ELS ring */
980 		pring = &psli->sli3_ring[LPFC_ELS_RING];
981 		spin_lock_irq(&phba->hbalock);
982 		list_splice_init(&pring->postbufq, &buflist);
983 		spin_unlock_irq(&phba->hbalock);
984 
985 		count = 0;
986 		list_for_each_entry_safe(mp, next_mp, &buflist, list) {
987 			list_del(&mp->list);
988 			count++;
989 			lpfc_mbuf_free(phba, mp->virt, mp->phys);
990 			kfree(mp);
991 		}
992 
993 		spin_lock_irq(&phba->hbalock);
994 		pring->postbufq_cnt -= count;
995 		spin_unlock_irq(&phba->hbalock);
996 	}
997 }
998 
999 /**
1000  * lpfc_hba_clean_txcmplq - Perform lpfc uninitialization after HBA reset
1001  * @phba: pointer to lpfc HBA data structure.
1002  *
1003  * This routine will cleanup the txcmplq after the HBA is reset when bringing
1004  * down the SLI Layer.
1005  *
1006  * Return codes
1007  *   void
1008  **/
1009 static void
1010 lpfc_hba_clean_txcmplq(struct lpfc_hba *phba)
1011 {
1012 	struct lpfc_sli *psli = &phba->sli;
1013 	struct lpfc_queue *qp = NULL;
1014 	struct lpfc_sli_ring *pring;
1015 	LIST_HEAD(completions);
1016 	int i;
1017 	struct lpfc_iocbq *piocb, *next_iocb;
1018 
1019 	if (phba->sli_rev != LPFC_SLI_REV4) {
1020 		for (i = 0; i < psli->num_rings; i++) {
1021 			pring = &psli->sli3_ring[i];
1022 			spin_lock_irq(&phba->hbalock);
1023 			/* At this point in time the HBA is either reset or DOA
1024 			 * Nothing should be on txcmplq as it will
1025 			 * NEVER complete.
1026 			 */
1027 			list_splice_init(&pring->txcmplq, &completions);
1028 			pring->txcmplq_cnt = 0;
1029 			spin_unlock_irq(&phba->hbalock);
1030 
1031 			lpfc_sli_abort_iocb_ring(phba, pring);
1032 		}
1033 		/* Cancel all the IOCBs from the completions list */
1034 		lpfc_sli_cancel_iocbs(phba, &completions,
1035 				      IOSTAT_LOCAL_REJECT, IOERR_SLI_ABORTED);
1036 		return;
1037 	}
1038 	list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
1039 		pring = qp->pring;
1040 		if (!pring)
1041 			continue;
1042 		spin_lock_irq(&pring->ring_lock);
1043 		list_for_each_entry_safe(piocb, next_iocb,
1044 					 &pring->txcmplq, list)
1045 			piocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
1046 		list_splice_init(&pring->txcmplq, &completions);
1047 		pring->txcmplq_cnt = 0;
1048 		spin_unlock_irq(&pring->ring_lock);
1049 		lpfc_sli_abort_iocb_ring(phba, pring);
1050 	}
1051 	/* Cancel all the IOCBs from the completions list */
1052 	lpfc_sli_cancel_iocbs(phba, &completions,
1053 			      IOSTAT_LOCAL_REJECT, IOERR_SLI_ABORTED);
1054 }
1055 
1056 /**
1057  * lpfc_hba_down_post_s3 - Perform lpfc uninitialization after HBA reset
1058  * @phba: pointer to lpfc HBA data structure.
1059  *
1060  * This routine will do uninitialization after the HBA is reset when bring
1061  * down the SLI Layer.
1062  *
1063  * Return codes
1064  *   0 - success.
1065  *   Any other value - error.
1066  **/
1067 static int
1068 lpfc_hba_down_post_s3(struct lpfc_hba *phba)
1069 {
1070 	lpfc_hba_free_post_buf(phba);
1071 	lpfc_hba_clean_txcmplq(phba);
1072 	return 0;
1073 }
1074 
1075 /**
1076  * lpfc_hba_down_post_s4 - Perform lpfc uninitialization after HBA reset
1077  * @phba: pointer to lpfc HBA data structure.
1078  *
1079  * This routine will do uninitialization after the HBA is reset when bring
1080  * down the SLI Layer.
1081  *
1082  * Return codes
1083  *   0 - success.
1084  *   Any other value - error.
1085  **/
1086 static int
1087 lpfc_hba_down_post_s4(struct lpfc_hba *phba)
1088 {
1089 	struct lpfc_io_buf *psb, *psb_next;
1090 	struct lpfc_async_xchg_ctx *ctxp, *ctxp_next;
1091 	struct lpfc_sli4_hdw_queue *qp;
1092 	LIST_HEAD(aborts);
1093 	LIST_HEAD(nvmet_aborts);
1094 	struct lpfc_sglq *sglq_entry = NULL;
1095 	int cnt, idx;
1096 
1097 
1098 	lpfc_sli_hbqbuf_free_all(phba);
1099 	lpfc_hba_clean_txcmplq(phba);
1100 
1101 	/* At this point in time the HBA is either reset or DOA. Either
1102 	 * way, nothing should be on lpfc_abts_els_sgl_list, it needs to be
1103 	 * on the lpfc_els_sgl_list so that it can either be freed if the
1104 	 * driver is unloading or reposted if the driver is restarting
1105 	 * the port.
1106 	 */
1107 
1108 	/* sgl_list_lock required because worker thread uses this
1109 	 * list.
1110 	 */
1111 	spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
1112 	list_for_each_entry(sglq_entry,
1113 		&phba->sli4_hba.lpfc_abts_els_sgl_list, list)
1114 		sglq_entry->state = SGL_FREED;
1115 
1116 	list_splice_init(&phba->sli4_hba.lpfc_abts_els_sgl_list,
1117 			&phba->sli4_hba.lpfc_els_sgl_list);
1118 
1119 
1120 	spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
1121 
1122 	/* abts_xxxx_buf_list_lock required because worker thread uses this
1123 	 * list.
1124 	 */
1125 	spin_lock_irq(&phba->hbalock);
1126 	cnt = 0;
1127 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
1128 		qp = &phba->sli4_hba.hdwq[idx];
1129 
1130 		spin_lock(&qp->abts_io_buf_list_lock);
1131 		list_splice_init(&qp->lpfc_abts_io_buf_list,
1132 				 &aborts);
1133 
1134 		list_for_each_entry_safe(psb, psb_next, &aborts, list) {
1135 			psb->pCmd = NULL;
1136 			psb->status = IOSTAT_SUCCESS;
1137 			cnt++;
1138 		}
1139 		spin_lock(&qp->io_buf_list_put_lock);
1140 		list_splice_init(&aborts, &qp->lpfc_io_buf_list_put);
1141 		qp->put_io_bufs += qp->abts_scsi_io_bufs;
1142 		qp->put_io_bufs += qp->abts_nvme_io_bufs;
1143 		qp->abts_scsi_io_bufs = 0;
1144 		qp->abts_nvme_io_bufs = 0;
1145 		spin_unlock(&qp->io_buf_list_put_lock);
1146 		spin_unlock(&qp->abts_io_buf_list_lock);
1147 	}
1148 	spin_unlock_irq(&phba->hbalock);
1149 
1150 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
1151 		spin_lock_irq(&phba->sli4_hba.abts_nvmet_buf_list_lock);
1152 		list_splice_init(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list,
1153 				 &nvmet_aborts);
1154 		spin_unlock_irq(&phba->sli4_hba.abts_nvmet_buf_list_lock);
1155 		list_for_each_entry_safe(ctxp, ctxp_next, &nvmet_aborts, list) {
1156 			ctxp->flag &= ~(LPFC_NVME_XBUSY | LPFC_NVME_ABORT_OP);
1157 			lpfc_nvmet_ctxbuf_post(phba, ctxp->ctxbuf);
1158 		}
1159 	}
1160 
1161 	lpfc_sli4_free_sp_events(phba);
1162 	return cnt;
1163 }
1164 
1165 /**
1166  * lpfc_hba_down_post - Wrapper func for hba down post routine
1167  * @phba: pointer to lpfc HBA data structure.
1168  *
1169  * This routine wraps the actual SLI3 or SLI4 routine for performing
1170  * uninitialization after the HBA is reset when bring down the SLI Layer.
1171  *
1172  * Return codes
1173  *   0 - success.
1174  *   Any other value - error.
1175  **/
1176 int
1177 lpfc_hba_down_post(struct lpfc_hba *phba)
1178 {
1179 	return (*phba->lpfc_hba_down_post)(phba);
1180 }
1181 
1182 /**
1183  * lpfc_hb_timeout - The HBA-timer timeout handler
1184  * @t: timer context used to obtain the pointer to lpfc hba data structure.
1185  *
1186  * This is the HBA-timer timeout handler registered to the lpfc driver. When
1187  * this timer fires, a HBA timeout event shall be posted to the lpfc driver
1188  * work-port-events bitmap and the worker thread is notified. This timeout
1189  * event will be used by the worker thread to invoke the actual timeout
1190  * handler routine, lpfc_hb_timeout_handler. Any periodical operations will
1191  * be performed in the timeout handler and the HBA timeout event bit shall
1192  * be cleared by the worker thread after it has taken the event bitmap out.
1193  **/
1194 static void
1195 lpfc_hb_timeout(struct timer_list *t)
1196 {
1197 	struct lpfc_hba *phba;
1198 	uint32_t tmo_posted;
1199 	unsigned long iflag;
1200 
1201 	phba = timer_container_of(phba, t, hb_tmofunc);
1202 
1203 	/* Check for heart beat timeout conditions */
1204 	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
1205 	tmo_posted = phba->pport->work_port_events & WORKER_HB_TMO;
1206 	if (!tmo_posted)
1207 		phba->pport->work_port_events |= WORKER_HB_TMO;
1208 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
1209 
1210 	/* Tell the worker thread there is work to do */
1211 	if (!tmo_posted)
1212 		lpfc_worker_wake_up(phba);
1213 	return;
1214 }
1215 
1216 /**
1217  * lpfc_rrq_timeout - The RRQ-timer timeout handler
1218  * @t: timer context used to obtain the pointer to lpfc hba data structure.
1219  *
1220  * This is the RRQ-timer timeout handler registered to the lpfc driver. When
1221  * this timer fires, a RRQ timeout event shall be posted to the lpfc driver
1222  * work-port-events bitmap and the worker thread is notified. This timeout
1223  * event will be used by the worker thread to invoke the actual timeout
1224  * handler routine, lpfc_rrq_handler. Any periodical operations will
1225  * be performed in the timeout handler and the RRQ timeout event bit shall
1226  * be cleared by the worker thread after it has taken the event bitmap out.
1227  **/
1228 static void
1229 lpfc_rrq_timeout(struct timer_list *t)
1230 {
1231 	struct lpfc_hba *phba;
1232 
1233 	phba = timer_container_of(phba, t, rrq_tmr);
1234 	if (test_bit(FC_UNLOADING, &phba->pport->load_flag)) {
1235 		clear_bit(HBA_RRQ_ACTIVE, &phba->hba_flag);
1236 		return;
1237 	}
1238 
1239 	set_bit(HBA_RRQ_ACTIVE, &phba->hba_flag);
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 	clear_bit(HBA_HBEAT_INP, &phba->hba_flag);
1263 	clear_bit(HBA_HBEAT_TMO, &phba->hba_flag);
1264 
1265 	/* Check and reset heart-beat timer if necessary */
1266 	mempool_free(pmboxq, phba->mbox_mem_pool);
1267 	if (!test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag) &&
1268 	    !(phba->link_state == LPFC_HBA_ERROR) &&
1269 	    !test_bit(FC_UNLOADING, &phba->pport->load_flag))
1270 		mod_timer(&phba->hb_tmofunc,
1271 			  jiffies +
1272 			  secs_to_jiffies(LPFC_HB_MBOX_INTERVAL));
1273 	return;
1274 }
1275 
1276 /*
1277  * lpfc_idle_stat_delay_work - idle_stat tracking
1278  *
1279  * This routine tracks per-eq idle_stat and determines polling decisions.
1280  *
1281  * Return codes:
1282  *   None
1283  **/
1284 static void
1285 lpfc_idle_stat_delay_work(struct work_struct *work)
1286 {
1287 	struct lpfc_hba *phba = container_of(to_delayed_work(work),
1288 					     struct lpfc_hba,
1289 					     idle_stat_delay_work);
1290 	struct lpfc_queue *eq;
1291 	struct lpfc_sli4_hdw_queue *hdwq;
1292 	struct lpfc_idle_stat *idle_stat;
1293 	u32 i, idle_percent;
1294 	u64 wall, wall_idle, diff_wall, diff_idle, busy_time;
1295 
1296 	if (test_bit(FC_UNLOADING, &phba->pport->load_flag))
1297 		return;
1298 
1299 	if (phba->link_state == LPFC_HBA_ERROR ||
1300 	    test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag) ||
1301 	    phba->cmf_active_mode != LPFC_CFG_OFF)
1302 		goto requeue;
1303 
1304 	for_each_present_cpu(i) {
1305 		hdwq = &phba->sli4_hba.hdwq[phba->sli4_hba.cpu_map[i].hdwq];
1306 		eq = hdwq->hba_eq;
1307 
1308 		/* Skip if we've already handled this eq's primary CPU */
1309 		if (eq->chann != i)
1310 			continue;
1311 
1312 		idle_stat = &phba->sli4_hba.idle_stat[i];
1313 
1314 		/* get_cpu_idle_time returns values as running counters. Thus,
1315 		 * to know the amount for this period, the prior counter values
1316 		 * need to be subtracted from the current counter values.
1317 		 * From there, the idle time stat can be calculated as a
1318 		 * percentage of 100 - the sum of the other consumption times.
1319 		 */
1320 		wall_idle = get_cpu_idle_time(i, &wall, 1);
1321 		diff_idle = wall_idle - idle_stat->prev_idle;
1322 		diff_wall = wall - idle_stat->prev_wall;
1323 
1324 		if (diff_wall <= diff_idle)
1325 			busy_time = 0;
1326 		else
1327 			busy_time = diff_wall - diff_idle;
1328 
1329 		idle_percent = div64_u64(100 * busy_time, diff_wall);
1330 		idle_percent = 100 - idle_percent;
1331 
1332 		if (idle_percent < 15)
1333 			eq->poll_mode = LPFC_QUEUE_WORK;
1334 		else
1335 			eq->poll_mode = LPFC_THREADED_IRQ;
1336 
1337 		idle_stat->prev_idle = wall_idle;
1338 		idle_stat->prev_wall = wall;
1339 	}
1340 
1341 requeue:
1342 	schedule_delayed_work(&phba->idle_stat_delay_work,
1343 			      msecs_to_jiffies(LPFC_IDLE_STAT_DELAY));
1344 }
1345 
1346 static void
1347 lpfc_hb_eq_delay_work(struct work_struct *work)
1348 {
1349 	struct lpfc_hba *phba = container_of(to_delayed_work(work),
1350 					     struct lpfc_hba, eq_delay_work);
1351 	struct lpfc_eq_intr_info *eqi, *eqi_new;
1352 	struct lpfc_queue *eq, *eq_next;
1353 	unsigned char *ena_delay = NULL;
1354 	uint32_t usdelay;
1355 	int i;
1356 
1357 	if (!phba->cfg_auto_imax ||
1358 	    test_bit(FC_UNLOADING, &phba->pport->load_flag))
1359 		return;
1360 
1361 	if (phba->link_state == LPFC_HBA_ERROR ||
1362 	    test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag))
1363 		goto requeue;
1364 
1365 	ena_delay = kcalloc(phba->sli4_hba.num_possible_cpu, sizeof(*ena_delay),
1366 			    GFP_KERNEL);
1367 	if (!ena_delay)
1368 		goto requeue;
1369 
1370 	for (i = 0; i < phba->cfg_irq_chann; i++) {
1371 		/* Get the EQ corresponding to the IRQ vector */
1372 		eq = phba->sli4_hba.hba_eq_hdl[i].eq;
1373 		if (!eq)
1374 			continue;
1375 		if (eq->q_mode || eq->q_flag & HBA_EQ_DELAY_CHK) {
1376 			eq->q_flag &= ~HBA_EQ_DELAY_CHK;
1377 			ena_delay[eq->last_cpu] = 1;
1378 		}
1379 	}
1380 
1381 	for_each_present_cpu(i) {
1382 		eqi = per_cpu_ptr(phba->sli4_hba.eq_info, i);
1383 		if (ena_delay[i]) {
1384 			usdelay = (eqi->icnt >> 10) * LPFC_EQ_DELAY_STEP;
1385 			if (usdelay > LPFC_MAX_AUTO_EQ_DELAY)
1386 				usdelay = LPFC_MAX_AUTO_EQ_DELAY;
1387 		} else {
1388 			usdelay = 0;
1389 		}
1390 
1391 		eqi->icnt = 0;
1392 
1393 		list_for_each_entry_safe(eq, eq_next, &eqi->list, cpu_list) {
1394 			if (unlikely(eq->last_cpu != i)) {
1395 				eqi_new = per_cpu_ptr(phba->sli4_hba.eq_info,
1396 						      eq->last_cpu);
1397 				list_move_tail(&eq->cpu_list, &eqi_new->list);
1398 				continue;
1399 			}
1400 			if (usdelay != eq->q_mode)
1401 				lpfc_modify_hba_eq_delay(phba, eq->hdwq, 1,
1402 							 usdelay);
1403 		}
1404 	}
1405 
1406 	kfree(ena_delay);
1407 
1408 requeue:
1409 	queue_delayed_work(phba->wq, &phba->eq_delay_work,
1410 			   msecs_to_jiffies(LPFC_EQ_DELAY_MSECS));
1411 }
1412 
1413 /**
1414  * lpfc_hb_mxp_handler - Multi-XRI pools handler to adjust XRI distribution
1415  * @phba: pointer to lpfc hba data structure.
1416  *
1417  * For each heartbeat, this routine does some heuristic methods to adjust
1418  * XRI distribution. The goal is to fully utilize free XRIs.
1419  **/
1420 static void lpfc_hb_mxp_handler(struct lpfc_hba *phba)
1421 {
1422 	u32 i;
1423 	u32 hwq_count;
1424 
1425 	hwq_count = phba->cfg_hdw_queue;
1426 	for (i = 0; i < hwq_count; i++) {
1427 		/* Adjust XRIs in private pool */
1428 		lpfc_adjust_pvt_pool_count(phba, i);
1429 
1430 		/* Adjust high watermark */
1431 		lpfc_adjust_high_watermark(phba, i);
1432 
1433 #ifdef LPFC_MXP_STAT
1434 		/* Snapshot pbl, pvt and busy count */
1435 		lpfc_snapshot_mxp(phba, i);
1436 #endif
1437 	}
1438 }
1439 
1440 /**
1441  * lpfc_issue_hb_mbox - Issues heart-beat mailbox command
1442  * @phba: pointer to lpfc hba data structure.
1443  *
1444  * If a HB mbox is not already in progrees, this routine will allocate
1445  * a LPFC_MBOXQ_t, populate it with a MBX_HEARTBEAT (0x31) command,
1446  * and issue it. The HBA_HBEAT_INP flag means the command is in progress.
1447  **/
1448 int
1449 lpfc_issue_hb_mbox(struct lpfc_hba *phba)
1450 {
1451 	LPFC_MBOXQ_t *pmboxq;
1452 	int retval;
1453 
1454 	/* Is a Heartbeat mbox already in progress */
1455 	if (test_bit(HBA_HBEAT_INP, &phba->hba_flag))
1456 		return 0;
1457 
1458 	pmboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
1459 	if (!pmboxq)
1460 		return -ENOMEM;
1461 
1462 	lpfc_heart_beat(phba, pmboxq);
1463 	pmboxq->mbox_cmpl = lpfc_hb_mbox_cmpl;
1464 	pmboxq->vport = phba->pport;
1465 	retval = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
1466 
1467 	if (retval != MBX_BUSY && retval != MBX_SUCCESS) {
1468 		mempool_free(pmboxq, phba->mbox_mem_pool);
1469 		return -ENXIO;
1470 	}
1471 	set_bit(HBA_HBEAT_INP, &phba->hba_flag);
1472 
1473 	return 0;
1474 }
1475 
1476 /**
1477  * lpfc_issue_hb_tmo - Signals heartbeat timer to issue mbox command
1478  * @phba: pointer to lpfc hba data structure.
1479  *
1480  * The heartbeat timer (every 5 sec) will fire. If the HBA_HBEAT_TMO
1481  * flag is set, it will force a MBX_HEARTBEAT mbox command, regardless
1482  * of the value of lpfc_enable_hba_heartbeat.
1483  * If lpfc_enable_hba_heartbeat is set, the timeout routine will always
1484  * try to issue a MBX_HEARTBEAT mbox command.
1485  **/
1486 void
1487 lpfc_issue_hb_tmo(struct lpfc_hba *phba)
1488 {
1489 	if (phba->cfg_enable_hba_heartbeat)
1490 		return;
1491 	set_bit(HBA_HBEAT_TMO, &phba->hba_flag);
1492 }
1493 
1494 /**
1495  * lpfc_hb_timeout_handler - The HBA-timer timeout handler
1496  * @phba: pointer to lpfc hba data structure.
1497  *
1498  * This is the actual HBA-timer timeout handler to be invoked by the worker
1499  * thread whenever the HBA timer fired and HBA-timeout event posted. This
1500  * handler performs any periodic operations needed for the device. If such
1501  * periodic event has already been attended to either in the interrupt handler
1502  * or by processing slow-ring or fast-ring events within the HBA-timer
1503  * timeout window (LPFC_HB_MBOX_INTERVAL), this handler just simply resets
1504  * the timer for the next timeout period. If lpfc heart-beat mailbox command
1505  * is configured and there is no heart-beat mailbox command outstanding, a
1506  * heart-beat mailbox is issued and timer set properly. Otherwise, if there
1507  * has been a heart-beat mailbox command outstanding, the HBA shall be put
1508  * to offline.
1509  **/
1510 void
1511 lpfc_hb_timeout_handler(struct lpfc_hba *phba)
1512 {
1513 	struct lpfc_vport **vports;
1514 	struct lpfc_dmabuf *buf_ptr;
1515 	int retval = 0;
1516 	int i, tmo;
1517 	struct lpfc_sli *psli = &phba->sli;
1518 	LIST_HEAD(completions);
1519 
1520 	if (phba->cfg_xri_rebalancing) {
1521 		/* Multi-XRI pools handler */
1522 		lpfc_hb_mxp_handler(phba);
1523 	}
1524 
1525 	vports = lpfc_create_vport_work_array(phba);
1526 	if (vports != NULL)
1527 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
1528 			lpfc_rcv_seq_check_edtov(vports[i]);
1529 			lpfc_fdmi_change_check(vports[i]);
1530 		}
1531 	lpfc_destroy_vport_work_array(phba, vports);
1532 
1533 	if (phba->link_state == LPFC_HBA_ERROR ||
1534 	    test_bit(FC_UNLOADING, &phba->pport->load_flag) ||
1535 	    test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag))
1536 		return;
1537 
1538 	if (phba->elsbuf_cnt &&
1539 		(phba->elsbuf_cnt == phba->elsbuf_prev_cnt)) {
1540 		spin_lock_irq(&phba->hbalock);
1541 		list_splice_init(&phba->elsbuf, &completions);
1542 		phba->elsbuf_cnt = 0;
1543 		phba->elsbuf_prev_cnt = 0;
1544 		spin_unlock_irq(&phba->hbalock);
1545 
1546 		while (!list_empty(&completions)) {
1547 			list_remove_head(&completions, buf_ptr,
1548 				struct lpfc_dmabuf, list);
1549 			lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
1550 			kfree(buf_ptr);
1551 		}
1552 	}
1553 	phba->elsbuf_prev_cnt = phba->elsbuf_cnt;
1554 
1555 	/* If there is no heart beat outstanding, issue a heartbeat command */
1556 	if (phba->cfg_enable_hba_heartbeat) {
1557 		/* If IOs are completing, no need to issue a MBX_HEARTBEAT */
1558 		spin_lock_irq(&phba->pport->work_port_lock);
1559 		if (time_after(phba->last_completion_time +
1560 				secs_to_jiffies(LPFC_HB_MBOX_INTERVAL),
1561 				jiffies)) {
1562 			spin_unlock_irq(&phba->pport->work_port_lock);
1563 			if (test_bit(HBA_HBEAT_INP, &phba->hba_flag))
1564 				tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1565 			else
1566 				tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1567 			goto out;
1568 		}
1569 		spin_unlock_irq(&phba->pport->work_port_lock);
1570 
1571 		/* Check if a MBX_HEARTBEAT is already in progress */
1572 		if (test_bit(HBA_HBEAT_INP, &phba->hba_flag)) {
1573 			/*
1574 			 * If heart beat timeout called with HBA_HBEAT_INP set
1575 			 * we need to give the hb mailbox cmd a chance to
1576 			 * complete or TMO.
1577 			 */
1578 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
1579 				"0459 Adapter heartbeat still outstanding: "
1580 				"last compl time was %d ms.\n",
1581 				jiffies_to_msecs(jiffies
1582 					 - phba->last_completion_time));
1583 			tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1584 		} else {
1585 			if ((!(psli->sli_flag & LPFC_SLI_MBOX_ACTIVE)) &&
1586 				(list_empty(&psli->mboxq))) {
1587 
1588 				retval = lpfc_issue_hb_mbox(phba);
1589 				if (retval) {
1590 					tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1591 					goto out;
1592 				}
1593 				phba->skipped_hb = 0;
1594 			} else if (time_before_eq(phba->last_completion_time,
1595 					phba->skipped_hb)) {
1596 				lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
1597 					"2857 Last completion time not "
1598 					" updated in %d ms\n",
1599 					jiffies_to_msecs(jiffies
1600 						 - phba->last_completion_time));
1601 			} else
1602 				phba->skipped_hb = jiffies;
1603 
1604 			tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1605 			goto out;
1606 		}
1607 	} else {
1608 		/* Check to see if we want to force a MBX_HEARTBEAT */
1609 		if (test_bit(HBA_HBEAT_TMO, &phba->hba_flag)) {
1610 			retval = lpfc_issue_hb_mbox(phba);
1611 			if (retval)
1612 				tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1613 			else
1614 				tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1615 			goto out;
1616 		}
1617 		tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1618 	}
1619 out:
1620 	mod_timer(&phba->hb_tmofunc, jiffies + msecs_to_jiffies(tmo));
1621 }
1622 
1623 /**
1624  * lpfc_offline_eratt - Bring lpfc offline on hardware error attention
1625  * @phba: pointer to lpfc hba data structure.
1626  *
1627  * This routine is called to bring the HBA offline when HBA hardware error
1628  * other than Port Error 6 has been detected.
1629  **/
1630 static void
1631 lpfc_offline_eratt(struct lpfc_hba *phba)
1632 {
1633 	struct lpfc_sli   *psli = &phba->sli;
1634 
1635 	spin_lock_irq(&phba->hbalock);
1636 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1637 	spin_unlock_irq(&phba->hbalock);
1638 	lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
1639 
1640 	lpfc_offline(phba);
1641 	lpfc_reset_barrier(phba);
1642 	spin_lock_irq(&phba->hbalock);
1643 	lpfc_sli_brdreset(phba);
1644 	spin_unlock_irq(&phba->hbalock);
1645 	lpfc_hba_down_post(phba);
1646 	lpfc_sli_brdready(phba, HS_MBRDY);
1647 	lpfc_unblock_mgmt_io(phba);
1648 	phba->link_state = LPFC_HBA_ERROR;
1649 	return;
1650 }
1651 
1652 /**
1653  * lpfc_sli4_offline_eratt - Bring lpfc offline on SLI4 hardware error attention
1654  * @phba: pointer to lpfc hba data structure.
1655  *
1656  * This routine is called to bring a SLI4 HBA offline when HBA hardware error
1657  * other than Port Error 6 has been detected.
1658  **/
1659 void
1660 lpfc_sli4_offline_eratt(struct lpfc_hba *phba)
1661 {
1662 	spin_lock_irq(&phba->hbalock);
1663 	if (phba->link_state == LPFC_HBA_ERROR &&
1664 		test_bit(HBA_PCI_ERR, &phba->bit_flags)) {
1665 		spin_unlock_irq(&phba->hbalock);
1666 		return;
1667 	}
1668 	phba->link_state = LPFC_HBA_ERROR;
1669 	spin_unlock_irq(&phba->hbalock);
1670 
1671 	lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
1672 	lpfc_sli_flush_io_rings(phba);
1673 	lpfc_offline(phba);
1674 	lpfc_hba_down_post(phba);
1675 	lpfc_unblock_mgmt_io(phba);
1676 }
1677 
1678 /**
1679  * lpfc_handle_deferred_eratt - The HBA hardware deferred error handler
1680  * @phba: pointer to lpfc hba data structure.
1681  *
1682  * This routine is invoked to handle the deferred HBA hardware error
1683  * conditions. This type of error is indicated by HBA by setting ER1
1684  * and another ER bit in the host status register. The driver will
1685  * wait until the ER1 bit clears before handling the error condition.
1686  **/
1687 static void
1688 lpfc_handle_deferred_eratt(struct lpfc_hba *phba)
1689 {
1690 	uint32_t old_host_status = phba->work_hs;
1691 	struct lpfc_sli *psli = &phba->sli;
1692 
1693 	/* If the pci channel is offline, ignore possible errors,
1694 	 * since we cannot communicate with the pci card anyway.
1695 	 */
1696 	if (pci_channel_offline(phba->pcidev)) {
1697 		clear_bit(DEFER_ERATT, &phba->hba_flag);
1698 		return;
1699 	}
1700 
1701 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1702 			"0479 Deferred Adapter Hardware Error "
1703 			"Data: x%x x%x x%x\n",
1704 			phba->work_hs, phba->work_status[0],
1705 			phba->work_status[1]);
1706 
1707 	spin_lock_irq(&phba->hbalock);
1708 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1709 	spin_unlock_irq(&phba->hbalock);
1710 
1711 
1712 	/*
1713 	 * Firmware stops when it triggred erratt. That could cause the I/Os
1714 	 * dropped by the firmware. Error iocb (I/O) on txcmplq and let the
1715 	 * SCSI layer retry it after re-establishing link.
1716 	 */
1717 	lpfc_sli_abort_fcp_rings(phba);
1718 
1719 	/*
1720 	 * There was a firmware error. Take the hba offline and then
1721 	 * attempt to restart it.
1722 	 */
1723 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
1724 	lpfc_offline(phba);
1725 
1726 	/* Wait for the ER1 bit to clear.*/
1727 	while (phba->work_hs & HS_FFER1) {
1728 		msleep(100);
1729 		if (lpfc_readl(phba->HSregaddr, &phba->work_hs)) {
1730 			phba->work_hs = UNPLUG_ERR ;
1731 			break;
1732 		}
1733 		/* If driver is unloading let the worker thread continue */
1734 		if (test_bit(FC_UNLOADING, &phba->pport->load_flag)) {
1735 			phba->work_hs = 0;
1736 			break;
1737 		}
1738 	}
1739 
1740 	/*
1741 	 * This is to ptrotect against a race condition in which
1742 	 * first write to the host attention register clear the
1743 	 * host status register.
1744 	 */
1745 	if (!phba->work_hs && !test_bit(FC_UNLOADING, &phba->pport->load_flag))
1746 		phba->work_hs = old_host_status & ~HS_FFER1;
1747 
1748 	clear_bit(DEFER_ERATT, &phba->hba_flag);
1749 	phba->work_status[0] = readl(phba->MBslimaddr + 0xa8);
1750 	phba->work_status[1] = readl(phba->MBslimaddr + 0xac);
1751 }
1752 
1753 static void
1754 lpfc_board_errevt_to_mgmt(struct lpfc_hba *phba)
1755 {
1756 	struct lpfc_board_event_header board_event;
1757 	struct Scsi_Host *shost;
1758 
1759 	board_event.event_type = FC_REG_BOARD_EVENT;
1760 	board_event.subcategory = LPFC_EVENT_PORTINTERR;
1761 	shost = lpfc_shost_from_vport(phba->pport);
1762 	fc_host_post_vendor_event(shost, fc_get_event_number(),
1763 				  sizeof(board_event),
1764 				  (char *) &board_event,
1765 				  LPFC_NL_VENDOR_ID);
1766 }
1767 
1768 /**
1769  * lpfc_handle_eratt_s3 - The SLI3 HBA hardware error handler
1770  * @phba: pointer to lpfc hba data structure.
1771  *
1772  * This routine is invoked to handle the following HBA hardware error
1773  * conditions:
1774  * 1 - HBA error attention interrupt
1775  * 2 - DMA ring index out of range
1776  * 3 - Mailbox command came back as unknown
1777  **/
1778 static void
1779 lpfc_handle_eratt_s3(struct lpfc_hba *phba)
1780 {
1781 	struct lpfc_vport *vport = phba->pport;
1782 	struct lpfc_sli   *psli = &phba->sli;
1783 	uint32_t event_data;
1784 	unsigned long temperature;
1785 	struct temp_event temp_event_data;
1786 	struct Scsi_Host  *shost;
1787 
1788 	/* If the pci channel is offline, ignore possible errors,
1789 	 * since we cannot communicate with the pci card anyway.
1790 	 */
1791 	if (pci_channel_offline(phba->pcidev)) {
1792 		clear_bit(DEFER_ERATT, &phba->hba_flag);
1793 		return;
1794 	}
1795 
1796 	/* If resets are disabled then leave the HBA alone and return */
1797 	if (!phba->cfg_enable_hba_reset)
1798 		return;
1799 
1800 	/* Send an internal error event to mgmt application */
1801 	lpfc_board_errevt_to_mgmt(phba);
1802 
1803 	if (test_bit(DEFER_ERATT, &phba->hba_flag))
1804 		lpfc_handle_deferred_eratt(phba);
1805 
1806 	if ((phba->work_hs & HS_FFER6) || (phba->work_hs & HS_FFER8)) {
1807 		if (phba->work_hs & HS_FFER6)
1808 			/* Re-establishing Link */
1809 			lpfc_printf_log(phba, KERN_INFO, LOG_LINK_EVENT,
1810 					"1301 Re-establishing Link "
1811 					"Data: x%x x%x x%x\n",
1812 					phba->work_hs, phba->work_status[0],
1813 					phba->work_status[1]);
1814 		if (phba->work_hs & HS_FFER8)
1815 			/* Device Zeroization */
1816 			lpfc_printf_log(phba, KERN_INFO, LOG_LINK_EVENT,
1817 					"2861 Host Authentication device "
1818 					"zeroization Data:x%x x%x x%x\n",
1819 					phba->work_hs, phba->work_status[0],
1820 					phba->work_status[1]);
1821 
1822 		spin_lock_irq(&phba->hbalock);
1823 		psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1824 		spin_unlock_irq(&phba->hbalock);
1825 
1826 		/*
1827 		* Firmware stops when it triggled erratt with HS_FFER6.
1828 		* That could cause the I/Os dropped by the firmware.
1829 		* Error iocb (I/O) on txcmplq and let the SCSI layer
1830 		* retry it after re-establishing link.
1831 		*/
1832 		lpfc_sli_abort_fcp_rings(phba);
1833 
1834 		/*
1835 		 * There was a firmware error.  Take the hba offline and then
1836 		 * attempt to restart it.
1837 		 */
1838 		lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
1839 		lpfc_offline(phba);
1840 		lpfc_sli_brdrestart(phba);
1841 		if (lpfc_online(phba) == 0) {	/* Initialize the HBA */
1842 			lpfc_unblock_mgmt_io(phba);
1843 			return;
1844 		}
1845 		lpfc_unblock_mgmt_io(phba);
1846 	} else if (phba->work_hs & HS_CRIT_TEMP) {
1847 		temperature = readl(phba->MBslimaddr + TEMPERATURE_OFFSET);
1848 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
1849 		temp_event_data.event_code = LPFC_CRIT_TEMP;
1850 		temp_event_data.data = (uint32_t)temperature;
1851 
1852 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1853 				"0406 Adapter maximum temperature exceeded "
1854 				"(%ld), taking this port offline "
1855 				"Data: x%x x%x x%x\n",
1856 				temperature, phba->work_hs,
1857 				phba->work_status[0], phba->work_status[1]);
1858 
1859 		shost = lpfc_shost_from_vport(phba->pport);
1860 		fc_host_post_vendor_event(shost, fc_get_event_number(),
1861 					  sizeof(temp_event_data),
1862 					  (char *) &temp_event_data,
1863 					  SCSI_NL_VID_TYPE_PCI
1864 					  | PCI_VENDOR_ID_EMULEX);
1865 
1866 		spin_lock_irq(&phba->hbalock);
1867 		phba->over_temp_state = HBA_OVER_TEMP;
1868 		spin_unlock_irq(&phba->hbalock);
1869 		lpfc_offline_eratt(phba);
1870 
1871 	} else {
1872 		/* The if clause above forces this code path when the status
1873 		 * failure is a value other than FFER6. Do not call the offline
1874 		 * twice. This is the adapter hardware error path.
1875 		 */
1876 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1877 				"0457 Adapter Hardware Error "
1878 				"Data: x%x x%x x%x\n",
1879 				phba->work_hs,
1880 				phba->work_status[0], phba->work_status[1]);
1881 
1882 		event_data = FC_REG_DUMP_EVENT;
1883 		shost = lpfc_shost_from_vport(vport);
1884 		fc_host_post_vendor_event(shost, fc_get_event_number(),
1885 				sizeof(event_data), (char *) &event_data,
1886 				SCSI_NL_VID_TYPE_PCI | PCI_VENDOR_ID_EMULEX);
1887 
1888 		lpfc_offline_eratt(phba);
1889 	}
1890 	return;
1891 }
1892 
1893 /**
1894  * lpfc_sli4_port_sta_fn_reset - The SLI4 function reset due to port status reg
1895  * @phba: pointer to lpfc hba data structure.
1896  * @mbx_action: flag for mailbox shutdown action.
1897  * @en_rn_msg: send reset/port recovery message.
1898  * This routine is invoked to perform an SLI4 port PCI function reset in
1899  * response to port status register polling attention. It waits for port
1900  * status register (ERR, RDY, RN) bits before proceeding with function reset.
1901  * During this process, interrupt vectors are freed and later requested
1902  * for handling possible port resource change.
1903  **/
1904 static int
1905 lpfc_sli4_port_sta_fn_reset(struct lpfc_hba *phba, int mbx_action,
1906 			    bool en_rn_msg)
1907 {
1908 	int rc;
1909 	uint32_t intr_mode;
1910 	LPFC_MBOXQ_t *mboxq;
1911 
1912 	/* Notifying the transport that the targets are going offline. */
1913 	lpfc_scsi_dev_block(phba);
1914 
1915 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) >=
1916 	    LPFC_SLI_INTF_IF_TYPE_2) {
1917 		/*
1918 		 * On error status condition, driver need to wait for port
1919 		 * ready before performing reset.
1920 		 */
1921 		rc = lpfc_sli4_pdev_status_reg_wait(phba);
1922 		if (rc)
1923 			return rc;
1924 	}
1925 
1926 	/* need reset: attempt for port recovery */
1927 	if (en_rn_msg)
1928 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
1929 				"2887 Reset Needed: Attempting Port "
1930 				"Recovery...\n");
1931 
1932 	/* If we are no wait, the HBA has been reset and is not
1933 	 * functional, thus we should clear
1934 	 * (LPFC_SLI_ACTIVE | LPFC_SLI_MBOX_ACTIVE) flags.
1935 	 */
1936 	if (mbx_action == LPFC_MBX_NO_WAIT) {
1937 		spin_lock_irq(&phba->hbalock);
1938 		phba->sli.sli_flag &= ~LPFC_SLI_ACTIVE;
1939 		if (phba->sli.mbox_active) {
1940 			mboxq = phba->sli.mbox_active;
1941 			mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
1942 			__lpfc_mbox_cmpl_put(phba, mboxq);
1943 			phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
1944 			phba->sli.mbox_active = NULL;
1945 		}
1946 		spin_unlock_irq(&phba->hbalock);
1947 	}
1948 
1949 	lpfc_offline_prep(phba, mbx_action);
1950 	lpfc_sli_flush_io_rings(phba);
1951 	lpfc_nvme_flush_abts_list(phba);
1952 	lpfc_nvmels_flush_cmd(phba);
1953 	lpfc_offline(phba);
1954 	/* release interrupt for possible resource change */
1955 	lpfc_sli4_disable_intr(phba);
1956 	rc = lpfc_sli_brdrestart(phba);
1957 	if (rc) {
1958 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1959 				"6309 Failed to restart board\n");
1960 		return rc;
1961 	}
1962 	/* request and enable interrupt */
1963 	intr_mode = lpfc_sli4_enable_intr(phba, phba->intr_mode);
1964 	if (intr_mode == LPFC_INTR_ERROR) {
1965 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1966 				"3175 Failed to enable interrupt\n");
1967 		return -EIO;
1968 	}
1969 	phba->intr_mode = intr_mode;
1970 	rc = lpfc_online(phba);
1971 	if (rc == 0)
1972 		lpfc_unblock_mgmt_io(phba);
1973 
1974 	return rc;
1975 }
1976 
1977 /**
1978  * lpfc_handle_eratt_s4 - The SLI4 HBA hardware error handler
1979  * @phba: pointer to lpfc hba data structure.
1980  *
1981  * This routine is invoked to handle the SLI4 HBA hardware error attention
1982  * conditions.
1983  **/
1984 static void
1985 lpfc_handle_eratt_s4(struct lpfc_hba *phba)
1986 {
1987 	struct lpfc_vport *vport = phba->pport;
1988 	uint32_t event_data;
1989 	struct Scsi_Host *shost;
1990 	uint32_t if_type;
1991 	struct lpfc_register portstat_reg = {0};
1992 	uint32_t reg_err1, reg_err2;
1993 	uint32_t uerrlo_reg, uemasklo_reg;
1994 	uint32_t smphr_port_status = 0, pci_rd_rc1, pci_rd_rc2;
1995 	bool en_rn_msg = true;
1996 	struct temp_event temp_event_data;
1997 	struct lpfc_register portsmphr_reg;
1998 	int rc, i;
1999 
2000 	/* If the pci channel is offline, ignore possible errors, since
2001 	 * we cannot communicate with the pci card anyway.
2002 	 */
2003 	if (pci_channel_offline(phba->pcidev)) {
2004 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2005 				"3166 pci channel is offline\n");
2006 		lpfc_sli_flush_io_rings(phba);
2007 		return;
2008 	}
2009 
2010 	memset(&portsmphr_reg, 0, sizeof(portsmphr_reg));
2011 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
2012 	switch (if_type) {
2013 	case LPFC_SLI_INTF_IF_TYPE_0:
2014 		pci_rd_rc1 = lpfc_readl(
2015 				phba->sli4_hba.u.if_type0.UERRLOregaddr,
2016 				&uerrlo_reg);
2017 		pci_rd_rc2 = lpfc_readl(
2018 				phba->sli4_hba.u.if_type0.UEMASKLOregaddr,
2019 				&uemasklo_reg);
2020 		/* consider PCI bus read error as pci_channel_offline */
2021 		if (pci_rd_rc1 == -EIO && pci_rd_rc2 == -EIO)
2022 			return;
2023 		if (!test_bit(HBA_RECOVERABLE_UE, &phba->hba_flag)) {
2024 			lpfc_sli4_offline_eratt(phba);
2025 			return;
2026 		}
2027 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2028 				"7623 Checking UE recoverable");
2029 
2030 		for (i = 0; i < phba->sli4_hba.ue_to_sr / 1000; i++) {
2031 			if (lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
2032 				       &portsmphr_reg.word0))
2033 				continue;
2034 
2035 			smphr_port_status = bf_get(lpfc_port_smphr_port_status,
2036 						   &portsmphr_reg);
2037 			if ((smphr_port_status & LPFC_PORT_SEM_MASK) ==
2038 			    LPFC_PORT_SEM_UE_RECOVERABLE)
2039 				break;
2040 			/*Sleep for 1Sec, before checking SEMAPHORE */
2041 			msleep(1000);
2042 		}
2043 
2044 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2045 				"4827 smphr_port_status x%x : Waited %dSec",
2046 				smphr_port_status, i);
2047 
2048 		/* Recoverable UE, reset the HBA device */
2049 		if ((smphr_port_status & LPFC_PORT_SEM_MASK) ==
2050 		    LPFC_PORT_SEM_UE_RECOVERABLE) {
2051 			for (i = 0; i < 20; i++) {
2052 				msleep(1000);
2053 				if (!lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
2054 				    &portsmphr_reg.word0) &&
2055 				    (LPFC_POST_STAGE_PORT_READY ==
2056 				     bf_get(lpfc_port_smphr_port_status,
2057 				     &portsmphr_reg))) {
2058 					rc = lpfc_sli4_port_sta_fn_reset(phba,
2059 						LPFC_MBX_NO_WAIT, en_rn_msg);
2060 					if (rc == 0)
2061 						return;
2062 					lpfc_printf_log(phba, KERN_ERR,
2063 						LOG_TRACE_EVENT,
2064 						"4215 Failed to recover UE");
2065 					break;
2066 				}
2067 			}
2068 		}
2069 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2070 				"7624 Firmware not ready: Failing UE recovery,"
2071 				" waited %dSec", i);
2072 		phba->link_state = LPFC_HBA_ERROR;
2073 		break;
2074 
2075 	case LPFC_SLI_INTF_IF_TYPE_2:
2076 	case LPFC_SLI_INTF_IF_TYPE_6:
2077 		pci_rd_rc1 = lpfc_readl(
2078 				phba->sli4_hba.u.if_type2.STATUSregaddr,
2079 				&portstat_reg.word0);
2080 		/* consider PCI bus read error as pci_channel_offline */
2081 		if (pci_rd_rc1 == -EIO) {
2082 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2083 				"3151 PCI bus read access failure: x%x\n",
2084 				readl(phba->sli4_hba.u.if_type2.STATUSregaddr));
2085 			lpfc_sli4_offline_eratt(phba);
2086 			return;
2087 		}
2088 		reg_err1 = readl(phba->sli4_hba.u.if_type2.ERR1regaddr);
2089 		reg_err2 = readl(phba->sli4_hba.u.if_type2.ERR2regaddr);
2090 		if (bf_get(lpfc_sliport_status_oti, &portstat_reg)) {
2091 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2092 					"2889 Port Overtemperature event, "
2093 					"taking port offline Data: x%x x%x\n",
2094 					reg_err1, reg_err2);
2095 
2096 			phba->sfp_alarm |= LPFC_TRANSGRESSION_HIGH_TEMPERATURE;
2097 			temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
2098 			temp_event_data.event_code = LPFC_CRIT_TEMP;
2099 			temp_event_data.data = 0xFFFFFFFF;
2100 
2101 			shost = lpfc_shost_from_vport(phba->pport);
2102 			fc_host_post_vendor_event(shost, fc_get_event_number(),
2103 						  sizeof(temp_event_data),
2104 						  (char *)&temp_event_data,
2105 						  SCSI_NL_VID_TYPE_PCI
2106 						  | PCI_VENDOR_ID_EMULEX);
2107 
2108 			spin_lock_irq(&phba->hbalock);
2109 			phba->over_temp_state = HBA_OVER_TEMP;
2110 			spin_unlock_irq(&phba->hbalock);
2111 			lpfc_sli4_offline_eratt(phba);
2112 			return;
2113 		}
2114 		if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2115 		    reg_err2 == SLIPORT_ERR2_REG_FW_RESTART) {
2116 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2117 					"3143 Port Down: Firmware Update "
2118 					"Detected\n");
2119 			en_rn_msg = false;
2120 		} else if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2121 			 reg_err2 == SLIPORT_ERR2_REG_FORCED_DUMP)
2122 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2123 					"3144 Port Down: Debug Dump\n");
2124 		else if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2125 			 reg_err2 == SLIPORT_ERR2_REG_FUNC_PROVISON)
2126 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2127 					"3145 Port Down: Provisioning\n");
2128 
2129 		/* If resets are disabled then leave the HBA alone and return */
2130 		if (!phba->cfg_enable_hba_reset)
2131 			return;
2132 
2133 		/* Check port status register for function reset */
2134 		rc = lpfc_sli4_port_sta_fn_reset(phba, LPFC_MBX_NO_WAIT,
2135 				en_rn_msg);
2136 		if (rc == 0) {
2137 			/* don't report event on forced debug dump */
2138 			if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2139 			    reg_err2 == SLIPORT_ERR2_REG_FORCED_DUMP)
2140 				return;
2141 			else
2142 				break;
2143 		}
2144 		/* fall through for not able to recover */
2145 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2146 				"3152 Unrecoverable error\n");
2147 		lpfc_sli4_offline_eratt(phba);
2148 		break;
2149 	case LPFC_SLI_INTF_IF_TYPE_1:
2150 	default:
2151 		break;
2152 	}
2153 	lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
2154 			"3123 Report dump event to upper layer\n");
2155 	/* Send an internal error event to mgmt application */
2156 	lpfc_board_errevt_to_mgmt(phba);
2157 
2158 	event_data = FC_REG_DUMP_EVENT;
2159 	shost = lpfc_shost_from_vport(vport);
2160 	fc_host_post_vendor_event(shost, fc_get_event_number(),
2161 				  sizeof(event_data), (char *) &event_data,
2162 				  SCSI_NL_VID_TYPE_PCI | PCI_VENDOR_ID_EMULEX);
2163 }
2164 
2165 /**
2166  * lpfc_handle_eratt - Wrapper func for handling hba error attention
2167  * @phba: pointer to lpfc HBA data structure.
2168  *
2169  * This routine wraps the actual SLI3 or SLI4 hba error attention handling
2170  * routine from the API jump table function pointer from the lpfc_hba struct.
2171  *
2172  * Return codes
2173  *   0 - success.
2174  *   Any other value - error.
2175  **/
2176 void
2177 lpfc_handle_eratt(struct lpfc_hba *phba)
2178 {
2179 	(*phba->lpfc_handle_eratt)(phba);
2180 }
2181 
2182 /**
2183  * lpfc_handle_latt - The HBA link event handler
2184  * @phba: pointer to lpfc hba data structure.
2185  *
2186  * This routine is invoked from the worker thread to handle a HBA host
2187  * attention link event. SLI3 only.
2188  **/
2189 void
2190 lpfc_handle_latt(struct lpfc_hba *phba)
2191 {
2192 	struct lpfc_vport *vport = phba->pport;
2193 	struct lpfc_sli   *psli = &phba->sli;
2194 	LPFC_MBOXQ_t *pmb;
2195 	volatile uint32_t control;
2196 	int rc = 0;
2197 
2198 	pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
2199 	if (!pmb) {
2200 		rc = 1;
2201 		goto lpfc_handle_latt_err_exit;
2202 	}
2203 
2204 	rc = lpfc_mbox_rsrc_prep(phba, pmb);
2205 	if (rc) {
2206 		rc = 2;
2207 		mempool_free(pmb, phba->mbox_mem_pool);
2208 		goto lpfc_handle_latt_err_exit;
2209 	}
2210 
2211 	/* Cleanup any outstanding ELS commands */
2212 	lpfc_els_flush_all_cmd(phba);
2213 	psli->slistat.link_event++;
2214 	lpfc_read_topology(phba, pmb, pmb->ctx_buf);
2215 	pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
2216 	pmb->vport = vport;
2217 	/* Block ELS IOCBs until we have processed this mbox command */
2218 	phba->sli.sli3_ring[LPFC_ELS_RING].flag |= LPFC_STOP_IOCB_EVENT;
2219 	rc = lpfc_sli_issue_mbox (phba, pmb, MBX_NOWAIT);
2220 	if (rc == MBX_NOT_FINISHED) {
2221 		rc = 4;
2222 		goto lpfc_handle_latt_free_mbuf;
2223 	}
2224 
2225 	/* Clear Link Attention in HA REG */
2226 	spin_lock_irq(&phba->hbalock);
2227 	writel(HA_LATT, phba->HAregaddr);
2228 	readl(phba->HAregaddr); /* flush */
2229 	spin_unlock_irq(&phba->hbalock);
2230 
2231 	return;
2232 
2233 lpfc_handle_latt_free_mbuf:
2234 	phba->sli.sli3_ring[LPFC_ELS_RING].flag &= ~LPFC_STOP_IOCB_EVENT;
2235 	lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
2236 lpfc_handle_latt_err_exit:
2237 	/* Enable Link attention interrupts */
2238 	spin_lock_irq(&phba->hbalock);
2239 	psli->sli_flag |= LPFC_PROCESS_LA;
2240 	control = readl(phba->HCregaddr);
2241 	control |= HC_LAINT_ENA;
2242 	writel(control, phba->HCregaddr);
2243 	readl(phba->HCregaddr); /* flush */
2244 
2245 	/* Clear Link Attention in HA REG */
2246 	writel(HA_LATT, phba->HAregaddr);
2247 	readl(phba->HAregaddr); /* flush */
2248 	spin_unlock_irq(&phba->hbalock);
2249 	lpfc_linkdown(phba);
2250 	phba->link_state = LPFC_HBA_ERROR;
2251 
2252 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2253 			"0300 LATT: Cannot issue READ_LA: Data:%d\n", rc);
2254 
2255 	return;
2256 }
2257 
2258 static void
2259 lpfc_fill_vpd(struct lpfc_hba *phba, uint8_t *vpd, int length, int *pindex)
2260 {
2261 	int i, j;
2262 
2263 	while (length > 0) {
2264 		/* Look for Serial Number */
2265 		if ((vpd[*pindex] == 'S') && (vpd[*pindex + 1] == 'N')) {
2266 			*pindex += 2;
2267 			i = vpd[*pindex];
2268 			*pindex += 1;
2269 			j = 0;
2270 			length -= (3+i);
2271 			while (i--) {
2272 				phba->SerialNumber[j++] = vpd[(*pindex)++];
2273 				if (j == 31)
2274 					break;
2275 			}
2276 			phba->SerialNumber[j] = 0;
2277 			continue;
2278 		} else if ((vpd[*pindex] == 'V') && (vpd[*pindex + 1] == '1')) {
2279 			phba->vpd_flag |= VPD_MODEL_DESC;
2280 			*pindex += 2;
2281 			i = vpd[*pindex];
2282 			*pindex += 1;
2283 			j = 0;
2284 			length -= (3+i);
2285 			while (i--) {
2286 				phba->ModelDesc[j++] = vpd[(*pindex)++];
2287 				if (j == 255)
2288 					break;
2289 			}
2290 			phba->ModelDesc[j] = 0;
2291 			continue;
2292 		} else if ((vpd[*pindex] == 'V') && (vpd[*pindex + 1] == '2')) {
2293 			phba->vpd_flag |= VPD_MODEL_NAME;
2294 			*pindex += 2;
2295 			i = vpd[*pindex];
2296 			*pindex += 1;
2297 			j = 0;
2298 			length -= (3+i);
2299 			while (i--) {
2300 				phba->ModelName[j++] = vpd[(*pindex)++];
2301 				if (j == 79)
2302 					break;
2303 			}
2304 			phba->ModelName[j] = 0;
2305 			continue;
2306 		} else if ((vpd[*pindex] == 'V') && (vpd[*pindex + 1] == '3')) {
2307 			phba->vpd_flag |= VPD_PROGRAM_TYPE;
2308 			*pindex += 2;
2309 			i = vpd[*pindex];
2310 			*pindex += 1;
2311 			j = 0;
2312 			length -= (3+i);
2313 			while (i--) {
2314 				phba->ProgramType[j++] = vpd[(*pindex)++];
2315 				if (j == 255)
2316 					break;
2317 			}
2318 			phba->ProgramType[j] = 0;
2319 			continue;
2320 		} else if ((vpd[*pindex] == 'V') && (vpd[*pindex + 1] == '4')) {
2321 			phba->vpd_flag |= VPD_PORT;
2322 			*pindex += 2;
2323 			i = vpd[*pindex];
2324 			*pindex += 1;
2325 			j = 0;
2326 			length -= (3 + i);
2327 			while (i--) {
2328 				if ((phba->sli_rev == LPFC_SLI_REV4) &&
2329 				    (phba->sli4_hba.pport_name_sta ==
2330 				     LPFC_SLI4_PPNAME_GET)) {
2331 					j++;
2332 					(*pindex)++;
2333 				} else
2334 					phba->Port[j++] = vpd[(*pindex)++];
2335 				if (j == 19)
2336 					break;
2337 			}
2338 			if ((phba->sli_rev != LPFC_SLI_REV4) ||
2339 			    (phba->sli4_hba.pport_name_sta ==
2340 			     LPFC_SLI4_PPNAME_NON))
2341 				phba->Port[j] = 0;
2342 			continue;
2343 		} else {
2344 			*pindex += 2;
2345 			i = vpd[*pindex];
2346 			*pindex += 1;
2347 			*pindex += i;
2348 			length -= (3 + i);
2349 		}
2350 	}
2351 }
2352 
2353 /**
2354  * lpfc_parse_vpd - Parse VPD (Vital Product Data)
2355  * @phba: pointer to lpfc hba data structure.
2356  * @vpd: pointer to the vital product data.
2357  * @len: length of the vital product data in bytes.
2358  *
2359  * This routine parses the Vital Product Data (VPD). The VPD is treated as
2360  * an array of characters. In this routine, the ModelName, ProgramType, and
2361  * ModelDesc, etc. fields of the phba data structure will be populated.
2362  *
2363  * Return codes
2364  *   0 - pointer to the VPD passed in is NULL
2365  *   1 - success
2366  **/
2367 int
2368 lpfc_parse_vpd(struct lpfc_hba *phba, uint8_t *vpd, int len)
2369 {
2370 	uint8_t lenlo, lenhi;
2371 	int Length;
2372 	int i;
2373 	int finished = 0;
2374 	int index = 0;
2375 
2376 	if (!vpd)
2377 		return 0;
2378 
2379 	/* Vital Product */
2380 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
2381 			"0455 Vital Product Data: x%x x%x x%x x%x\n",
2382 			(uint32_t) vpd[0], (uint32_t) vpd[1], (uint32_t) vpd[2],
2383 			(uint32_t) vpd[3]);
2384 	while (!finished && (index < (len - 4))) {
2385 		switch (vpd[index]) {
2386 		case 0x82:
2387 		case 0x91:
2388 			index += 1;
2389 			lenlo = vpd[index];
2390 			index += 1;
2391 			lenhi = vpd[index];
2392 			index += 1;
2393 			i = ((((unsigned short)lenhi) << 8) + lenlo);
2394 			index += i;
2395 			break;
2396 		case 0x90:
2397 			index += 1;
2398 			lenlo = vpd[index];
2399 			index += 1;
2400 			lenhi = vpd[index];
2401 			index += 1;
2402 			Length = ((((unsigned short)lenhi) << 8) + lenlo);
2403 			if (Length > len - index)
2404 				Length = len - index;
2405 
2406 			lpfc_fill_vpd(phba, vpd, Length, &index);
2407 			finished = 0;
2408 			break;
2409 		case 0x78:
2410 			finished = 1;
2411 			break;
2412 		default:
2413 			index ++;
2414 			break;
2415 		}
2416 	}
2417 
2418 	return(1);
2419 }
2420 
2421 /**
2422  * lpfc_get_atto_model_desc - Retrieve ATTO HBA device model name and description
2423  * @phba: pointer to lpfc hba data structure.
2424  * @mdp: pointer to the data structure to hold the derived model name.
2425  * @descp: pointer to the data structure to hold the derived description.
2426  *
2427  * This routine retrieves HBA's description based on its registered PCI device
2428  * ID. The @descp passed into this function points to an array of 256 chars. It
2429  * shall be returned with the model name, maximum speed, and the host bus type.
2430  * The @mdp passed into this function points to an array of 80 chars. When the
2431  * function returns, the @mdp will be filled with the model name.
2432  **/
2433 static void
2434 lpfc_get_atto_model_desc(struct lpfc_hba *phba, uint8_t *mdp, uint8_t *descp)
2435 {
2436 	uint16_t sub_dev_id = phba->pcidev->subsystem_device;
2437 	char *model = "<Unknown>";
2438 	int tbolt = 0;
2439 
2440 	switch (sub_dev_id) {
2441 	case PCI_DEVICE_ID_CLRY_161E:
2442 		model = "161E";
2443 		break;
2444 	case PCI_DEVICE_ID_CLRY_162E:
2445 		model = "162E";
2446 		break;
2447 	case PCI_DEVICE_ID_CLRY_164E:
2448 		model = "164E";
2449 		break;
2450 	case PCI_DEVICE_ID_CLRY_161P:
2451 		model = "161P";
2452 		break;
2453 	case PCI_DEVICE_ID_CLRY_162P:
2454 		model = "162P";
2455 		break;
2456 	case PCI_DEVICE_ID_CLRY_164P:
2457 		model = "164P";
2458 		break;
2459 	case PCI_DEVICE_ID_CLRY_321E:
2460 		model = "321E";
2461 		break;
2462 	case PCI_DEVICE_ID_CLRY_322E:
2463 		model = "322E";
2464 		break;
2465 	case PCI_DEVICE_ID_CLRY_324E:
2466 		model = "324E";
2467 		break;
2468 	case PCI_DEVICE_ID_CLRY_321P:
2469 		model = "321P";
2470 		break;
2471 	case PCI_DEVICE_ID_CLRY_322P:
2472 		model = "322P";
2473 		break;
2474 	case PCI_DEVICE_ID_CLRY_324P:
2475 		model = "324P";
2476 		break;
2477 	case PCI_DEVICE_ID_TLFC_2XX2:
2478 		model = "2XX2";
2479 		tbolt = 1;
2480 		break;
2481 	case PCI_DEVICE_ID_TLFC_3162:
2482 		model = "3162";
2483 		tbolt = 1;
2484 		break;
2485 	case PCI_DEVICE_ID_TLFC_3322:
2486 		model = "3322";
2487 		tbolt = 1;
2488 		break;
2489 	default:
2490 		model = "Unknown";
2491 		break;
2492 	}
2493 
2494 	if (mdp && mdp[0] == '\0')
2495 		snprintf(mdp, 79, "%s", model);
2496 
2497 	if (descp && descp[0] == '\0')
2498 		snprintf(descp, 255,
2499 			 "ATTO %s%s, Fibre Channel Adapter Initiator, Port %s",
2500 			 (tbolt) ? "ThunderLink FC " : "Celerity FC-",
2501 			 model,
2502 			 phba->Port);
2503 }
2504 
2505 /**
2506  * lpfc_get_hba_model_desc - Retrieve HBA device model name and description
2507  * @phba: pointer to lpfc hba data structure.
2508  * @mdp: pointer to the data structure to hold the derived model name.
2509  * @descp: pointer to the data structure to hold the derived description.
2510  *
2511  * This routine retrieves HBA's description based on its registered PCI device
2512  * ID. The @descp passed into this function points to an array of 256 chars. It
2513  * shall be returned with the model name, maximum speed, and the host bus type.
2514  * The @mdp passed into this function points to an array of 80 chars. When the
2515  * function returns, the @mdp will be filled with the model name.
2516  **/
2517 static void
2518 lpfc_get_hba_model_desc(struct lpfc_hba *phba, uint8_t *mdp, uint8_t *descp)
2519 {
2520 	lpfc_vpd_t *vp;
2521 	uint16_t dev_id = phba->pcidev->device;
2522 	int max_speed;
2523 	int GE = 0;
2524 	int oneConnect = 0; /* default is not a oneConnect */
2525 	struct {
2526 		char *name;
2527 		char *bus;
2528 		char *function;
2529 	} m = {"<Unknown>", "", ""};
2530 
2531 	if (mdp && mdp[0] != '\0'
2532 		&& descp && descp[0] != '\0')
2533 		return;
2534 
2535 	if (phba->pcidev->vendor == PCI_VENDOR_ID_ATTO) {
2536 		lpfc_get_atto_model_desc(phba, mdp, descp);
2537 		return;
2538 	}
2539 
2540 	if (phba->lmt & LMT_128Gb)
2541 		max_speed = 128;
2542 	else if (phba->lmt & LMT_64Gb)
2543 		max_speed = 64;
2544 	else if (phba->lmt & LMT_32Gb)
2545 		max_speed = 32;
2546 	else if (phba->lmt & LMT_16Gb)
2547 		max_speed = 16;
2548 	else if (phba->lmt & LMT_10Gb)
2549 		max_speed = 10;
2550 	else if (phba->lmt & LMT_8Gb)
2551 		max_speed = 8;
2552 	else if (phba->lmt & LMT_4Gb)
2553 		max_speed = 4;
2554 	else if (phba->lmt & LMT_2Gb)
2555 		max_speed = 2;
2556 	else if (phba->lmt & LMT_1Gb)
2557 		max_speed = 1;
2558 	else
2559 		max_speed = 0;
2560 
2561 	vp = &phba->vpd;
2562 
2563 	switch (dev_id) {
2564 	case PCI_DEVICE_ID_FIREFLY:
2565 		m = (typeof(m)){"LP6000", "PCI",
2566 				"Obsolete, Unsupported Fibre Channel Adapter"};
2567 		break;
2568 	case PCI_DEVICE_ID_SUPERFLY:
2569 		if (vp->rev.biuRev >= 1 && vp->rev.biuRev <= 3)
2570 			m = (typeof(m)){"LP7000", "PCI", ""};
2571 		else
2572 			m = (typeof(m)){"LP7000E", "PCI", ""};
2573 		m.function = "Obsolete, Unsupported Fibre Channel Adapter";
2574 		break;
2575 	case PCI_DEVICE_ID_DRAGONFLY:
2576 		m = (typeof(m)){"LP8000", "PCI",
2577 				"Obsolete, Unsupported Fibre Channel Adapter"};
2578 		break;
2579 	case PCI_DEVICE_ID_CENTAUR:
2580 		if (FC_JEDEC_ID(vp->rev.biuRev) == CENTAUR_2G_JEDEC_ID)
2581 			m = (typeof(m)){"LP9002", "PCI", ""};
2582 		else
2583 			m = (typeof(m)){"LP9000", "PCI", ""};
2584 		m.function = "Obsolete, Unsupported Fibre Channel Adapter";
2585 		break;
2586 	case PCI_DEVICE_ID_RFLY:
2587 		m = (typeof(m)){"LP952", "PCI",
2588 				"Obsolete, Unsupported Fibre Channel Adapter"};
2589 		break;
2590 	case PCI_DEVICE_ID_PEGASUS:
2591 		m = (typeof(m)){"LP9802", "PCI-X",
2592 				"Obsolete, Unsupported Fibre Channel Adapter"};
2593 		break;
2594 	case PCI_DEVICE_ID_THOR:
2595 		m = (typeof(m)){"LP10000", "PCI-X",
2596 				"Obsolete, Unsupported Fibre Channel Adapter"};
2597 		break;
2598 	case PCI_DEVICE_ID_VIPER:
2599 		m = (typeof(m)){"LPX1000",  "PCI-X",
2600 				"Obsolete, Unsupported Fibre Channel Adapter"};
2601 		break;
2602 	case PCI_DEVICE_ID_PFLY:
2603 		m = (typeof(m)){"LP982", "PCI-X",
2604 				"Obsolete, Unsupported Fibre Channel Adapter"};
2605 		break;
2606 	case PCI_DEVICE_ID_TFLY:
2607 		m = (typeof(m)){"LP1050", "PCI-X",
2608 				"Obsolete, Unsupported Fibre Channel Adapter"};
2609 		break;
2610 	case PCI_DEVICE_ID_HELIOS:
2611 		m = (typeof(m)){"LP11000", "PCI-X2",
2612 				"Obsolete, Unsupported Fibre Channel Adapter"};
2613 		break;
2614 	case PCI_DEVICE_ID_HELIOS_SCSP:
2615 		m = (typeof(m)){"LP11000-SP", "PCI-X2",
2616 				"Obsolete, Unsupported Fibre Channel Adapter"};
2617 		break;
2618 	case PCI_DEVICE_ID_HELIOS_DCSP:
2619 		m = (typeof(m)){"LP11002-SP",  "PCI-X2",
2620 				"Obsolete, Unsupported Fibre Channel Adapter"};
2621 		break;
2622 	case PCI_DEVICE_ID_NEPTUNE:
2623 		m = (typeof(m)){"LPe1000", "PCIe",
2624 				"Obsolete, Unsupported Fibre Channel Adapter"};
2625 		break;
2626 	case PCI_DEVICE_ID_NEPTUNE_SCSP:
2627 		m = (typeof(m)){"LPe1000-SP", "PCIe",
2628 				"Obsolete, Unsupported Fibre Channel Adapter"};
2629 		break;
2630 	case PCI_DEVICE_ID_NEPTUNE_DCSP:
2631 		m = (typeof(m)){"LPe1002-SP", "PCIe",
2632 				"Obsolete, Unsupported Fibre Channel Adapter"};
2633 		break;
2634 	case PCI_DEVICE_ID_BMID:
2635 		m = (typeof(m)){"LP1150", "PCI-X2",
2636 				"Obsolete, Unsupported Fibre Channel Adapter"};
2637 		break;
2638 	case PCI_DEVICE_ID_BSMB:
2639 		m = (typeof(m)){"LP111", "PCI-X2",
2640 				"Obsolete, Unsupported Fibre Channel Adapter"};
2641 		break;
2642 	case PCI_DEVICE_ID_ZEPHYR:
2643 		m = (typeof(m)){"LPe11000", "PCIe",
2644 				"Obsolete, Unsupported Fibre Channel Adapter"};
2645 		break;
2646 	case PCI_DEVICE_ID_ZEPHYR_SCSP:
2647 		m = (typeof(m)){"LPe11000", "PCIe",
2648 				"Obsolete, Unsupported Fibre Channel Adapter"};
2649 		break;
2650 	case PCI_DEVICE_ID_ZEPHYR_DCSP:
2651 		m = (typeof(m)){"LP2105", "PCIe",
2652 				"Obsolete, Unsupported FCoE Adapter"};
2653 		GE = 1;
2654 		break;
2655 	case PCI_DEVICE_ID_ZMID:
2656 		m = (typeof(m)){"LPe1150", "PCIe",
2657 				"Obsolete, Unsupported Fibre Channel Adapter"};
2658 		break;
2659 	case PCI_DEVICE_ID_ZSMB:
2660 		m = (typeof(m)){"LPe111", "PCIe",
2661 				"Obsolete, Unsupported Fibre Channel Adapter"};
2662 		break;
2663 	case PCI_DEVICE_ID_LP101:
2664 		m = (typeof(m)){"LP101", "PCI-X",
2665 				"Obsolete, Unsupported Fibre Channel Adapter"};
2666 		break;
2667 	case PCI_DEVICE_ID_LP10000S:
2668 		m = (typeof(m)){"LP10000-S", "PCI",
2669 				"Obsolete, Unsupported Fibre Channel Adapter"};
2670 		break;
2671 	case PCI_DEVICE_ID_LP11000S:
2672 		m = (typeof(m)){"LP11000-S", "PCI-X2",
2673 				"Obsolete, Unsupported Fibre Channel Adapter"};
2674 		break;
2675 	case PCI_DEVICE_ID_LPE11000S:
2676 		m = (typeof(m)){"LPe11000-S", "PCIe",
2677 				"Obsolete, Unsupported Fibre Channel Adapter"};
2678 		break;
2679 	case PCI_DEVICE_ID_SAT:
2680 		m = (typeof(m)){"LPe12000", "PCIe",
2681 				"Obsolete, Unsupported Fibre Channel Adapter"};
2682 		break;
2683 	case PCI_DEVICE_ID_SAT_MID:
2684 		m = (typeof(m)){"LPe1250", "PCIe",
2685 				"Obsolete, Unsupported Fibre Channel Adapter"};
2686 		break;
2687 	case PCI_DEVICE_ID_SAT_SMB:
2688 		m = (typeof(m)){"LPe121", "PCIe",
2689 				"Obsolete, Unsupported Fibre Channel Adapter"};
2690 		break;
2691 	case PCI_DEVICE_ID_SAT_DCSP:
2692 		m = (typeof(m)){"LPe12002-SP", "PCIe",
2693 				"Obsolete, Unsupported Fibre Channel Adapter"};
2694 		break;
2695 	case PCI_DEVICE_ID_SAT_SCSP:
2696 		m = (typeof(m)){"LPe12000-SP", "PCIe",
2697 				"Obsolete, Unsupported Fibre Channel Adapter"};
2698 		break;
2699 	case PCI_DEVICE_ID_SAT_S:
2700 		m = (typeof(m)){"LPe12000-S", "PCIe",
2701 				"Obsolete, Unsupported Fibre Channel Adapter"};
2702 		break;
2703 	case PCI_DEVICE_ID_PROTEUS_VF:
2704 		m = (typeof(m)){"LPev12000", "PCIe IOV",
2705 				"Obsolete, Unsupported Fibre Channel Adapter"};
2706 		break;
2707 	case PCI_DEVICE_ID_PROTEUS_PF:
2708 		m = (typeof(m)){"LPev12000", "PCIe IOV",
2709 				"Obsolete, Unsupported Fibre Channel Adapter"};
2710 		break;
2711 	case PCI_DEVICE_ID_PROTEUS_S:
2712 		m = (typeof(m)){"LPemv12002-S", "PCIe IOV",
2713 				"Obsolete, Unsupported Fibre Channel Adapter"};
2714 		break;
2715 	case PCI_DEVICE_ID_TIGERSHARK:
2716 		oneConnect = 1;
2717 		m = (typeof(m)){"OCe10100", "PCIe",
2718 				"Obsolete, Unsupported FCoE Adapter"};
2719 		break;
2720 	case PCI_DEVICE_ID_TOMCAT:
2721 		oneConnect = 1;
2722 		m = (typeof(m)){"OCe11100", "PCIe",
2723 				"Obsolete, Unsupported FCoE Adapter"};
2724 		break;
2725 	case PCI_DEVICE_ID_FALCON:
2726 		m = (typeof(m)){"LPSe12002-ML1-E", "PCIe",
2727 				"Obsolete, Unsupported Fibre Channel Adapter"};
2728 		break;
2729 	case PCI_DEVICE_ID_BALIUS:
2730 		m = (typeof(m)){"LPVe12002", "PCIe Shared I/O",
2731 				"Obsolete, Unsupported Fibre Channel Adapter"};
2732 		break;
2733 	case PCI_DEVICE_ID_LANCER_FC:
2734 		m = (typeof(m)){"LPe16000", "PCIe",
2735 				"Obsolete, Unsupported Fibre Channel Adapter"};
2736 		break;
2737 	case PCI_DEVICE_ID_LANCER_FC_VF:
2738 		m = (typeof(m)){"LPe16000", "PCIe",
2739 				"Obsolete, Unsupported Fibre Channel Adapter"};
2740 		break;
2741 	case PCI_DEVICE_ID_LANCER_FCOE:
2742 		oneConnect = 1;
2743 		m = (typeof(m)){"OCe15100", "PCIe",
2744 				"Obsolete, Unsupported FCoE Adapter"};
2745 		break;
2746 	case PCI_DEVICE_ID_LANCER_FCOE_VF:
2747 		oneConnect = 1;
2748 		m = (typeof(m)){"OCe15100", "PCIe",
2749 				"Obsolete, Unsupported FCoE Adapter"};
2750 		break;
2751 	case PCI_DEVICE_ID_LANCER_G6_FC:
2752 		m = (typeof(m)){"LPe32000", "PCIe", "Fibre Channel Adapter"};
2753 		break;
2754 	case PCI_DEVICE_ID_LANCER_G7_FC:
2755 		m = (typeof(m)){"LPe36000", "PCIe", "Fibre Channel Adapter"};
2756 		break;
2757 	case PCI_DEVICE_ID_LANCER_G7P_FC:
2758 		m = (typeof(m)){"LPe38000", "PCIe", "Fibre Channel Adapter"};
2759 		break;
2760 	case PCI_DEVICE_ID_LANCER_G8_FC:
2761 		m = (typeof(m)){"LPe42100", "PCIe", "Fibre Channel Adapter"};
2762 		break;
2763 	case PCI_DEVICE_ID_SKYHAWK:
2764 	case PCI_DEVICE_ID_SKYHAWK_VF:
2765 		oneConnect = 1;
2766 		m = (typeof(m)){"OCe14000", "PCIe",
2767 				"Obsolete, Unsupported FCoE Adapter"};
2768 		break;
2769 	default:
2770 		m = (typeof(m)){"Unknown", "", ""};
2771 		break;
2772 	}
2773 
2774 	if (mdp && mdp[0] == '\0')
2775 		snprintf(mdp, 79,"%s", m.name);
2776 	/*
2777 	 * oneConnect hba requires special processing, they are all initiators
2778 	 * and we put the port number on the end
2779 	 */
2780 	if (descp && descp[0] == '\0') {
2781 		if (oneConnect)
2782 			snprintf(descp, 255,
2783 				"Emulex OneConnect %s, %s Initiator %s",
2784 				m.name, m.function,
2785 				phba->Port);
2786 		else if (max_speed == 0)
2787 			snprintf(descp, 255,
2788 				"Emulex %s %s %s",
2789 				m.name, m.bus, m.function);
2790 		else
2791 			snprintf(descp, 255,
2792 				"Emulex %s %d%s %s %s",
2793 				m.name, max_speed, (GE) ? "GE" : "Gb",
2794 				m.bus, m.function);
2795 	}
2796 }
2797 
2798 /**
2799  * lpfc_sli3_post_buffer - Post IOCB(s) with DMA buffer descriptor(s) to a IOCB ring
2800  * @phba: pointer to lpfc hba data structure.
2801  * @pring: pointer to a IOCB ring.
2802  * @cnt: the number of IOCBs to be posted to the IOCB ring.
2803  *
2804  * This routine posts a given number of IOCBs with the associated DMA buffer
2805  * descriptors specified by the cnt argument to the given IOCB ring.
2806  *
2807  * Return codes
2808  *   The number of IOCBs NOT able to be posted to the IOCB ring.
2809  **/
2810 int
2811 lpfc_sli3_post_buffer(struct lpfc_hba *phba, struct lpfc_sli_ring *pring, int cnt)
2812 {
2813 	IOCB_t *icmd;
2814 	struct lpfc_iocbq *iocb;
2815 	struct lpfc_dmabuf *mp1, *mp2;
2816 
2817 	cnt += pring->missbufcnt;
2818 
2819 	/* While there are buffers to post */
2820 	while (cnt > 0) {
2821 		/* Allocate buffer for  command iocb */
2822 		iocb = lpfc_sli_get_iocbq(phba);
2823 		if (iocb == NULL) {
2824 			pring->missbufcnt = cnt;
2825 			return cnt;
2826 		}
2827 		icmd = &iocb->iocb;
2828 
2829 		/* 2 buffers can be posted per command */
2830 		/* Allocate buffer to post */
2831 		mp1 = kmalloc_obj(struct lpfc_dmabuf);
2832 		if (mp1)
2833 		    mp1->virt = lpfc_mbuf_alloc(phba, MEM_PRI, &mp1->phys);
2834 		if (!mp1 || !mp1->virt) {
2835 			kfree(mp1);
2836 			lpfc_sli_release_iocbq(phba, iocb);
2837 			pring->missbufcnt = cnt;
2838 			return cnt;
2839 		}
2840 
2841 		INIT_LIST_HEAD(&mp1->list);
2842 		/* Allocate buffer to post */
2843 		if (cnt > 1) {
2844 			mp2 = kmalloc_obj(struct lpfc_dmabuf);
2845 			if (mp2)
2846 				mp2->virt = lpfc_mbuf_alloc(phba, MEM_PRI,
2847 							    &mp2->phys);
2848 			if (!mp2 || !mp2->virt) {
2849 				kfree(mp2);
2850 				lpfc_mbuf_free(phba, mp1->virt, mp1->phys);
2851 				kfree(mp1);
2852 				lpfc_sli_release_iocbq(phba, iocb);
2853 				pring->missbufcnt = cnt;
2854 				return cnt;
2855 			}
2856 
2857 			INIT_LIST_HEAD(&mp2->list);
2858 		} else {
2859 			mp2 = NULL;
2860 		}
2861 
2862 		icmd->un.cont64[0].addrHigh = putPaddrHigh(mp1->phys);
2863 		icmd->un.cont64[0].addrLow = putPaddrLow(mp1->phys);
2864 		icmd->un.cont64[0].tus.f.bdeSize = FCELSSIZE;
2865 		icmd->ulpBdeCount = 1;
2866 		cnt--;
2867 		if (mp2) {
2868 			icmd->un.cont64[1].addrHigh = putPaddrHigh(mp2->phys);
2869 			icmd->un.cont64[1].addrLow = putPaddrLow(mp2->phys);
2870 			icmd->un.cont64[1].tus.f.bdeSize = FCELSSIZE;
2871 			cnt--;
2872 			icmd->ulpBdeCount = 2;
2873 		}
2874 
2875 		icmd->ulpCommand = CMD_QUE_RING_BUF64_CN;
2876 		icmd->ulpLe = 1;
2877 
2878 		if (lpfc_sli_issue_iocb(phba, pring->ringno, iocb, 0) ==
2879 		    IOCB_ERROR) {
2880 			lpfc_mbuf_free(phba, mp1->virt, mp1->phys);
2881 			kfree(mp1);
2882 			cnt++;
2883 			if (mp2) {
2884 				lpfc_mbuf_free(phba, mp2->virt, mp2->phys);
2885 				kfree(mp2);
2886 				cnt++;
2887 			}
2888 			lpfc_sli_release_iocbq(phba, iocb);
2889 			pring->missbufcnt = cnt;
2890 			return cnt;
2891 		}
2892 		lpfc_sli_ringpostbuf_put(phba, pring, mp1);
2893 		if (mp2)
2894 			lpfc_sli_ringpostbuf_put(phba, pring, mp2);
2895 	}
2896 	pring->missbufcnt = 0;
2897 	return 0;
2898 }
2899 
2900 /**
2901  * lpfc_post_rcv_buf - Post the initial receive IOCB buffers to ELS ring
2902  * @phba: pointer to lpfc hba data structure.
2903  *
2904  * This routine posts initial receive IOCB buffers to the ELS ring. The
2905  * current number of initial IOCB buffers specified by LPFC_BUF_RING0 is
2906  * set to 64 IOCBs. SLI3 only.
2907  *
2908  * Return codes
2909  *   0 - success (currently always success)
2910  **/
2911 static int
2912 lpfc_post_rcv_buf(struct lpfc_hba *phba)
2913 {
2914 	struct lpfc_sli *psli = &phba->sli;
2915 
2916 	/* Ring 0, ELS / CT buffers */
2917 	lpfc_sli3_post_buffer(phba, &psli->sli3_ring[LPFC_ELS_RING], LPFC_BUF_RING0);
2918 	/* Ring 2 - FCP no buffers needed */
2919 
2920 	return 0;
2921 }
2922 
2923 #define S(N,V) (((V)<<(N))|((V)>>(32-(N))))
2924 
2925 /**
2926  * lpfc_sha_init - Set up initial array of hash table entries
2927  * @HashResultPointer: pointer to an array as hash table.
2928  *
2929  * This routine sets up the initial values to the array of hash table entries
2930  * for the LC HBAs.
2931  **/
2932 static void
2933 lpfc_sha_init(uint32_t * HashResultPointer)
2934 {
2935 	HashResultPointer[0] = 0x67452301;
2936 	HashResultPointer[1] = 0xEFCDAB89;
2937 	HashResultPointer[2] = 0x98BADCFE;
2938 	HashResultPointer[3] = 0x10325476;
2939 	HashResultPointer[4] = 0xC3D2E1F0;
2940 }
2941 
2942 /**
2943  * lpfc_sha_iterate - Iterate initial hash table with the working hash table
2944  * @HashResultPointer: pointer to an initial/result hash table.
2945  * @HashWorkingPointer: pointer to an working hash table.
2946  *
2947  * This routine iterates an initial hash table pointed by @HashResultPointer
2948  * with the values from the working hash table pointeed by @HashWorkingPointer.
2949  * The results are putting back to the initial hash table, returned through
2950  * the @HashResultPointer as the result hash table.
2951  **/
2952 static void
2953 lpfc_sha_iterate(uint32_t * HashResultPointer, uint32_t * HashWorkingPointer)
2954 {
2955 	int t;
2956 	uint32_t TEMP;
2957 	uint32_t A, B, C, D, E;
2958 	t = 16;
2959 	do {
2960 		HashWorkingPointer[t] =
2961 		    S(1,
2962 		      HashWorkingPointer[t - 3] ^ HashWorkingPointer[t -
2963 								     8] ^
2964 		      HashWorkingPointer[t - 14] ^ HashWorkingPointer[t - 16]);
2965 	} while (++t <= 79);
2966 	t = 0;
2967 	A = HashResultPointer[0];
2968 	B = HashResultPointer[1];
2969 	C = HashResultPointer[2];
2970 	D = HashResultPointer[3];
2971 	E = HashResultPointer[4];
2972 
2973 	do {
2974 		if (t < 20) {
2975 			TEMP = ((B & C) | ((~B) & D)) + 0x5A827999;
2976 		} else if (t < 40) {
2977 			TEMP = (B ^ C ^ D) + 0x6ED9EBA1;
2978 		} else if (t < 60) {
2979 			TEMP = ((B & C) | (B & D) | (C & D)) + 0x8F1BBCDC;
2980 		} else {
2981 			TEMP = (B ^ C ^ D) + 0xCA62C1D6;
2982 		}
2983 		TEMP += S(5, A) + E + HashWorkingPointer[t];
2984 		E = D;
2985 		D = C;
2986 		C = S(30, B);
2987 		B = A;
2988 		A = TEMP;
2989 	} while (++t <= 79);
2990 
2991 	HashResultPointer[0] += A;
2992 	HashResultPointer[1] += B;
2993 	HashResultPointer[2] += C;
2994 	HashResultPointer[3] += D;
2995 	HashResultPointer[4] += E;
2996 
2997 }
2998 
2999 /**
3000  * lpfc_challenge_key - Create challenge key based on WWPN of the HBA
3001  * @RandomChallenge: pointer to the entry of host challenge random number array.
3002  * @HashWorking: pointer to the entry of the working hash array.
3003  *
3004  * This routine calculates the working hash array referred by @HashWorking
3005  * from the challenge random numbers associated with the host, referred by
3006  * @RandomChallenge. The result is put into the entry of the working hash
3007  * array and returned by reference through @HashWorking.
3008  **/
3009 static void
3010 lpfc_challenge_key(uint32_t * RandomChallenge, uint32_t * HashWorking)
3011 {
3012 	*HashWorking = (*RandomChallenge ^ *HashWorking);
3013 }
3014 
3015 /**
3016  * lpfc_hba_init - Perform special handling for LC HBA initialization
3017  * @phba: pointer to lpfc hba data structure.
3018  * @hbainit: pointer to an array of unsigned 32-bit integers.
3019  *
3020  * This routine performs the special handling for LC HBA initialization.
3021  **/
3022 void
3023 lpfc_hba_init(struct lpfc_hba *phba, uint32_t *hbainit)
3024 {
3025 	int t;
3026 	uint32_t *HashWorking;
3027 	uint32_t *pwwnn = (uint32_t *) phba->wwnn;
3028 
3029 	HashWorking = kcalloc(80, sizeof(uint32_t), GFP_KERNEL);
3030 	if (!HashWorking)
3031 		return;
3032 
3033 	HashWorking[0] = HashWorking[78] = *pwwnn++;
3034 	HashWorking[1] = HashWorking[79] = *pwwnn;
3035 
3036 	for (t = 0; t < 7; t++)
3037 		lpfc_challenge_key(phba->RandomData + t, HashWorking + t);
3038 
3039 	lpfc_sha_init(hbainit);
3040 	lpfc_sha_iterate(hbainit, HashWorking);
3041 	kfree(HashWorking);
3042 }
3043 
3044 /**
3045  * lpfc_cleanup - Performs vport cleanups before deleting a vport
3046  * @vport: pointer to a virtual N_Port data structure.
3047  *
3048  * This routine performs the necessary cleanups before deleting the @vport.
3049  * It invokes the discovery state machine to perform necessary state
3050  * transitions and to release the ndlps associated with the @vport. Note,
3051  * the physical port is treated as @vport 0.
3052  **/
3053 void
3054 lpfc_cleanup(struct lpfc_vport *vport)
3055 {
3056 	struct lpfc_hba   *phba = vport->phba;
3057 	struct lpfc_nodelist *ndlp, *next_ndlp;
3058 	int i = 0;
3059 
3060 	if (phba->link_state > LPFC_LINK_DOWN)
3061 		lpfc_port_link_failure(vport);
3062 
3063 	/* Clean up VMID resources */
3064 	if (lpfc_is_vmid_enabled(phba))
3065 		lpfc_vmid_vport_cleanup(vport);
3066 
3067 	list_for_each_entry_safe(ndlp, next_ndlp, &vport->fc_nodes, nlp_listp) {
3068 		/* Fabric Ports not in UNMAPPED state are cleaned up in the
3069 		 * DEVICE_RM event.
3070 		 */
3071 		if (ndlp->nlp_type & NLP_FABRIC &&
3072 		    ndlp->nlp_state == NLP_STE_UNMAPPED_NODE)
3073 			lpfc_disc_state_machine(vport, ndlp, NULL,
3074 					NLP_EVT_DEVICE_RECOVERY);
3075 
3076 		if (!(ndlp->fc4_xpt_flags & (NVME_XPT_REGD|SCSI_XPT_REGD)))
3077 			lpfc_disc_state_machine(vport, ndlp, NULL,
3078 					NLP_EVT_DEVICE_RM);
3079 	}
3080 
3081 	/* This is a special case flush to return all
3082 	 * IOs before entering this loop. There are
3083 	 * two points in the code where a flush is
3084 	 * avoided if the FC_UNLOADING flag is set.
3085 	 * one is in the multipool destroy,
3086 	 * (this prevents a crash) and the other is
3087 	 * in the nvme abort handler, ( also prevents
3088 	 * a crash). Both of these exceptions are
3089 	 * cases where the slot is still accessible.
3090 	 * The flush here is only when the pci slot
3091 	 * is offline.
3092 	 */
3093 	if (test_bit(FC_UNLOADING, &vport->load_flag) &&
3094 	    pci_channel_offline(phba->pcidev))
3095 		lpfc_sli_flush_io_rings(vport->phba);
3096 
3097 	/* At this point, ALL ndlp's should be gone
3098 	 * because of the previous NLP_EVT_DEVICE_RM.
3099 	 * Lets wait for this to happen, if needed.
3100 	 */
3101 	while (!list_empty(&vport->fc_nodes)) {
3102 		if (i++ > 3000) {
3103 			lpfc_printf_vlog(vport, KERN_ERR,
3104 					 LOG_TRACE_EVENT,
3105 				"0233 Nodelist not empty\n");
3106 			list_for_each_entry_safe(ndlp, next_ndlp,
3107 						&vport->fc_nodes, nlp_listp) {
3108 				lpfc_printf_vlog(ndlp->vport, KERN_ERR,
3109 						 LOG_DISCOVERY,
3110 						 "0282 did:x%x ndlp:x%px "
3111 						 "refcnt:%d xflags x%x "
3112 						 "nflag x%lx\n",
3113 						 ndlp->nlp_DID, (void *)ndlp,
3114 						 kref_read(&ndlp->kref),
3115 						 ndlp->fc4_xpt_flags,
3116 						 ndlp->nlp_flag);
3117 			}
3118 			break;
3119 		}
3120 
3121 		/* Wait for any activity on ndlps to settle */
3122 		msleep(10);
3123 	}
3124 	lpfc_cleanup_vports_rrqs(vport, NULL);
3125 }
3126 
3127 /**
3128  * lpfc_stop_vport_timers - Stop all the timers associated with a vport
3129  * @vport: pointer to a virtual N_Port data structure.
3130  *
3131  * This routine stops all the timers associated with a @vport. This function
3132  * is invoked before disabling or deleting a @vport. Note that the physical
3133  * port is treated as @vport 0.
3134  **/
3135 void
3136 lpfc_stop_vport_timers(struct lpfc_vport *vport)
3137 {
3138 	timer_delete_sync(&vport->els_tmofunc);
3139 	timer_delete_sync(&vport->delayed_disc_tmo);
3140 	lpfc_can_disctmo(vport);
3141 	return;
3142 }
3143 
3144 /**
3145  * __lpfc_sli4_stop_fcf_redisc_wait_timer - Stop FCF rediscovery wait timer
3146  * @phba: pointer to lpfc hba data structure.
3147  *
3148  * This routine stops the SLI4 FCF rediscover wait timer if it's on. The
3149  * caller of this routine should already hold the host lock.
3150  **/
3151 void
3152 __lpfc_sli4_stop_fcf_redisc_wait_timer(struct lpfc_hba *phba)
3153 {
3154 	/* Clear pending FCF rediscovery wait flag */
3155 	phba->fcf.fcf_flag &= ~FCF_REDISC_PEND;
3156 
3157 	/* Now, try to stop the timer */
3158 	timer_delete(&phba->fcf.redisc_wait);
3159 }
3160 
3161 /**
3162  * lpfc_sli4_stop_fcf_redisc_wait_timer - Stop FCF rediscovery wait timer
3163  * @phba: pointer to lpfc hba data structure.
3164  *
3165  * This routine stops the SLI4 FCF rediscover wait timer if it's on. It
3166  * checks whether the FCF rediscovery wait timer is pending with the host
3167  * lock held before proceeding with disabling the timer and clearing the
3168  * wait timer pendig flag.
3169  **/
3170 void
3171 lpfc_sli4_stop_fcf_redisc_wait_timer(struct lpfc_hba *phba)
3172 {
3173 	spin_lock_irq(&phba->hbalock);
3174 	if (!(phba->fcf.fcf_flag & FCF_REDISC_PEND)) {
3175 		/* FCF rediscovery timer already fired or stopped */
3176 		spin_unlock_irq(&phba->hbalock);
3177 		return;
3178 	}
3179 	__lpfc_sli4_stop_fcf_redisc_wait_timer(phba);
3180 	/* Clear failover in progress flags */
3181 	phba->fcf.fcf_flag &= ~(FCF_DEAD_DISC | FCF_ACVL_DISC);
3182 	spin_unlock_irq(&phba->hbalock);
3183 }
3184 
3185 /**
3186  * lpfc_cmf_stop - Stop CMF processing
3187  * @phba: pointer to lpfc hba data structure.
3188  *
3189  * This is called when the link goes down or if CMF mode is turned OFF.
3190  * It is also called when going offline or unloaded just before the
3191  * congestion info buffer is unregistered.
3192  **/
3193 void
3194 lpfc_cmf_stop(struct lpfc_hba *phba)
3195 {
3196 	int cpu;
3197 	struct lpfc_cgn_stat *cgs;
3198 
3199 	/* We only do something if CMF is enabled */
3200 	if (!phba->sli4_hba.pc_sli4_params.cmf)
3201 		return;
3202 
3203 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
3204 			"6221 Stop CMF / Cancel Timer\n");
3205 
3206 	/* Cancel the CMF timer */
3207 	hrtimer_cancel(&phba->cmf_stats_timer);
3208 	hrtimer_cancel(&phba->cmf_timer);
3209 
3210 	/* Zero CMF counters */
3211 	atomic_set(&phba->cmf_busy, 0);
3212 	for_each_present_cpu(cpu) {
3213 		cgs = per_cpu_ptr(phba->cmf_stat, cpu);
3214 		atomic64_set(&cgs->total_bytes, 0);
3215 		atomic64_set(&cgs->rcv_bytes, 0);
3216 		atomic_set(&cgs->rx_io_cnt, 0);
3217 		atomic64_set(&cgs->rx_latency, 0);
3218 	}
3219 	atomic_set(&phba->cmf_bw_wait, 0);
3220 
3221 	/* Resume any blocked IO - Queue unblock on workqueue */
3222 	queue_work(phba->wq, &phba->unblock_request_work);
3223 }
3224 
3225 static inline uint64_t
3226 lpfc_get_max_line_rate(struct lpfc_hba *phba)
3227 {
3228 	uint64_t rate = lpfc_sli_port_speed_get(phba);
3229 
3230 	return ((((unsigned long)rate) * 1024 * 1024) / 10);
3231 }
3232 
3233 void
3234 lpfc_cmf_signal_init(struct lpfc_hba *phba)
3235 {
3236 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
3237 			"6223 Signal CMF init\n");
3238 
3239 	/* Use the new fc_linkspeed to recalculate */
3240 	phba->cmf_interval_rate = LPFC_CMF_INTERVAL;
3241 	phba->cmf_max_line_rate = lpfc_get_max_line_rate(phba);
3242 	phba->cmf_link_byte_count = div_u64(phba->cmf_max_line_rate *
3243 					    phba->cmf_interval_rate, 1000);
3244 	phba->cmf_max_bytes_per_interval = phba->cmf_link_byte_count;
3245 
3246 	/* This is a signal to firmware to sync up CMF BW with link speed */
3247 	lpfc_issue_cmf_sync_wqe(phba, 0, 0);
3248 }
3249 
3250 /**
3251  * lpfc_cmf_start - Start CMF processing
3252  * @phba: pointer to lpfc hba data structure.
3253  *
3254  * This is called when the link comes up or if CMF mode is turned OFF
3255  * to Monitor or Managed.
3256  **/
3257 void
3258 lpfc_cmf_start(struct lpfc_hba *phba)
3259 {
3260 	struct lpfc_cgn_stat *cgs;
3261 	int cpu;
3262 
3263 	/* We only do something if CMF is enabled */
3264 	if (!phba->sli4_hba.pc_sli4_params.cmf ||
3265 	    phba->cmf_active_mode == LPFC_CFG_OFF)
3266 		return;
3267 
3268 	/* Reinitialize congestion buffer info */
3269 	lpfc_init_congestion_buf(phba);
3270 
3271 	atomic_set(&phba->cgn_fabric_warn_cnt, 0);
3272 	atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
3273 	atomic_set(&phba->cgn_sync_alarm_cnt, 0);
3274 	atomic_set(&phba->cgn_sync_warn_cnt, 0);
3275 
3276 	atomic_set(&phba->cmf_busy, 0);
3277 	for_each_present_cpu(cpu) {
3278 		cgs = per_cpu_ptr(phba->cmf_stat, cpu);
3279 		atomic64_set(&cgs->total_bytes, 0);
3280 		atomic64_set(&cgs->rcv_bytes, 0);
3281 		atomic_set(&cgs->rx_io_cnt, 0);
3282 		atomic64_set(&cgs->rx_latency, 0);
3283 	}
3284 	phba->cmf_latency.tv_sec = 0;
3285 	phba->cmf_latency.tv_nsec = 0;
3286 
3287 	lpfc_cmf_signal_init(phba);
3288 
3289 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
3290 			"6222 Start CMF / Timer\n");
3291 
3292 	phba->cmf_timer_cnt = 0;
3293 	hrtimer_start(&phba->cmf_timer,
3294 		      ktime_set(0, LPFC_CMF_INTERVAL * NSEC_PER_MSEC),
3295 		      HRTIMER_MODE_REL);
3296 	hrtimer_start(&phba->cmf_stats_timer,
3297 		      ktime_set(0, LPFC_SEC_MIN * NSEC_PER_SEC),
3298 		      HRTIMER_MODE_REL);
3299 	/* Setup for latency check in IO cmpl routines */
3300 	ktime_get_real_ts64(&phba->cmf_latency);
3301 
3302 	atomic_set(&phba->cmf_bw_wait, 0);
3303 	atomic_set(&phba->cmf_stop_io, 0);
3304 }
3305 
3306 /**
3307  * lpfc_stop_hba_timers - Stop all the timers associated with an HBA
3308  * @phba: pointer to lpfc hba data structure.
3309  *
3310  * This routine stops all the timers associated with a HBA. This function is
3311  * invoked before either putting a HBA offline or unloading the driver.
3312  **/
3313 void
3314 lpfc_stop_hba_timers(struct lpfc_hba *phba)
3315 {
3316 	if (phba->pport)
3317 		lpfc_stop_vport_timers(phba->pport);
3318 	cancel_delayed_work_sync(&phba->eq_delay_work);
3319 	cancel_delayed_work_sync(&phba->idle_stat_delay_work);
3320 	timer_delete_sync(&phba->sli.mbox_tmo);
3321 	timer_delete_sync(&phba->fabric_block_timer);
3322 	timer_delete_sync(&phba->eratt_poll);
3323 	timer_delete_sync(&phba->hb_tmofunc);
3324 	if (phba->sli_rev == LPFC_SLI_REV4) {
3325 		timer_delete_sync(&phba->rrq_tmr);
3326 		clear_bit(HBA_RRQ_ACTIVE, &phba->hba_flag);
3327 	}
3328 	clear_bit(HBA_HBEAT_INP, &phba->hba_flag);
3329 	clear_bit(HBA_HBEAT_TMO, &phba->hba_flag);
3330 
3331 	switch (phba->pci_dev_grp) {
3332 	case LPFC_PCI_DEV_LP:
3333 		/* Stop any LightPulse device specific driver timers */
3334 		timer_delete_sync(&phba->fcp_poll_timer);
3335 		break;
3336 	case LPFC_PCI_DEV_OC:
3337 		/* Stop any OneConnect device specific driver timers */
3338 		lpfc_sli4_stop_fcf_redisc_wait_timer(phba);
3339 		break;
3340 	default:
3341 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3342 				"0297 Invalid device group (x%x)\n",
3343 				phba->pci_dev_grp);
3344 		break;
3345 	}
3346 	return;
3347 }
3348 
3349 /**
3350  * lpfc_block_mgmt_io - Mark a HBA's management interface as blocked
3351  * @phba: pointer to lpfc hba data structure.
3352  * @mbx_action: flag for mailbox no wait action.
3353  *
3354  * This routine marks a HBA's management interface as blocked. Once the HBA's
3355  * management interface is marked as blocked, all the user space access to
3356  * the HBA, whether they are from sysfs interface or libdfc interface will
3357  * all be blocked. The HBA is set to block the management interface when the
3358  * driver prepares the HBA interface for online or offline.
3359  **/
3360 static void
3361 lpfc_block_mgmt_io(struct lpfc_hba *phba, int mbx_action)
3362 {
3363 	unsigned long iflag;
3364 	uint8_t actcmd = MBX_HEARTBEAT;
3365 	unsigned long timeout;
3366 
3367 	spin_lock_irqsave(&phba->hbalock, iflag);
3368 	phba->sli.sli_flag |= LPFC_BLOCK_MGMT_IO;
3369 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3370 	if (mbx_action == LPFC_MBX_NO_WAIT)
3371 		return;
3372 	timeout = secs_to_jiffies(LPFC_MBOX_TMO) + jiffies;
3373 	spin_lock_irqsave(&phba->hbalock, iflag);
3374 	if (phba->sli.mbox_active) {
3375 		actcmd = phba->sli.mbox_active->u.mb.mbxCommand;
3376 		/* Determine how long we might wait for the active mailbox
3377 		 * command to be gracefully completed by firmware.
3378 		 */
3379 		timeout = secs_to_jiffies(lpfc_mbox_tmo_val(phba,
3380 				phba->sli.mbox_active)) + jiffies;
3381 	}
3382 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3383 
3384 	/* Wait for the outstnading mailbox command to complete */
3385 	while (phba->sli.mbox_active) {
3386 		/* Check active mailbox complete status every 2ms */
3387 		msleep(2);
3388 		if (time_after(jiffies, timeout)) {
3389 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3390 					"2813 Mgmt IO is Blocked %x "
3391 					"- mbox cmd %x still active\n",
3392 					phba->sli.sli_flag, actcmd);
3393 			break;
3394 		}
3395 	}
3396 }
3397 
3398 /**
3399  * lpfc_sli4_node_rpi_restore - Recover assigned RPIs for active nodes.
3400  * @phba: pointer to lpfc hba data structure.
3401  *
3402  * Allocate RPIs for all active remote nodes. This is needed whenever
3403  * an SLI4 adapter is reset and the driver is not unloading. Its purpose
3404  * is to fixup the temporary rpi assignments.
3405  **/
3406 void
3407 lpfc_sli4_node_rpi_restore(struct lpfc_hba *phba)
3408 {
3409 	struct lpfc_nodelist  *ndlp, *next_ndlp;
3410 	struct lpfc_vport **vports;
3411 	int i, rpi;
3412 
3413 	if (phba->sli_rev != LPFC_SLI_REV4)
3414 		return;
3415 
3416 	vports = lpfc_create_vport_work_array(phba);
3417 	if (!vports)
3418 		return;
3419 
3420 	for (i = 0; i <= phba->max_vports && vports[i]; i++) {
3421 		if (test_bit(FC_UNLOADING, &vports[i]->load_flag))
3422 			continue;
3423 
3424 		list_for_each_entry_safe(ndlp, next_ndlp,
3425 					 &vports[i]->fc_nodes,
3426 					 nlp_listp) {
3427 			rpi = lpfc_sli4_alloc_rpi(phba);
3428 			if (rpi == LPFC_RPI_ALLOC_ERROR) {
3429 				lpfc_printf_vlog(ndlp->vport, KERN_INFO,
3430 						 LOG_NODE | LOG_DISCOVERY,
3431 						 "0099 RPI alloc error for "
3432 						 "ndlp x%px DID:x%06x "
3433 						 "flg:x%lx\n",
3434 						 ndlp, ndlp->nlp_DID,
3435 						 ndlp->nlp_flag);
3436 				continue;
3437 			}
3438 			ndlp->nlp_rpi = rpi;
3439 			lpfc_printf_vlog(ndlp->vport, KERN_INFO,
3440 					 LOG_NODE | LOG_DISCOVERY,
3441 					 "0009 Assign RPI x%x to ndlp x%px "
3442 					 "DID:x%06x flg:x%lx\n",
3443 					 ndlp->nlp_rpi, ndlp, ndlp->nlp_DID,
3444 					 ndlp->nlp_flag);
3445 		}
3446 	}
3447 	lpfc_destroy_vport_work_array(phba, vports);
3448 }
3449 
3450 /**
3451  * lpfc_create_expedite_pool - create expedite pool
3452  * @phba: pointer to lpfc hba data structure.
3453  *
3454  * This routine moves a batch of XRIs from lpfc_io_buf_list_put of HWQ 0
3455  * to expedite pool. Mark them as expedite.
3456  **/
3457 static void lpfc_create_expedite_pool(struct lpfc_hba *phba)
3458 {
3459 	struct lpfc_sli4_hdw_queue *qp;
3460 	struct lpfc_io_buf *lpfc_ncmd;
3461 	struct lpfc_io_buf *lpfc_ncmd_next;
3462 	struct lpfc_epd_pool *epd_pool;
3463 	unsigned long iflag;
3464 
3465 	epd_pool = &phba->epd_pool;
3466 	qp = &phba->sli4_hba.hdwq[0];
3467 
3468 	spin_lock_init(&epd_pool->lock);
3469 	spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3470 	spin_lock(&epd_pool->lock);
3471 	INIT_LIST_HEAD(&epd_pool->list);
3472 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3473 				 &qp->lpfc_io_buf_list_put, list) {
3474 		list_move_tail(&lpfc_ncmd->list, &epd_pool->list);
3475 		lpfc_ncmd->expedite = true;
3476 		qp->put_io_bufs--;
3477 		epd_pool->count++;
3478 		if (epd_pool->count >= XRI_BATCH)
3479 			break;
3480 	}
3481 	spin_unlock(&epd_pool->lock);
3482 	spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3483 }
3484 
3485 /**
3486  * lpfc_destroy_expedite_pool - destroy expedite pool
3487  * @phba: pointer to lpfc hba data structure.
3488  *
3489  * This routine returns XRIs from expedite pool to lpfc_io_buf_list_put
3490  * of HWQ 0. Clear the mark.
3491  **/
3492 static void lpfc_destroy_expedite_pool(struct lpfc_hba *phba)
3493 {
3494 	struct lpfc_sli4_hdw_queue *qp;
3495 	struct lpfc_io_buf *lpfc_ncmd;
3496 	struct lpfc_io_buf *lpfc_ncmd_next;
3497 	struct lpfc_epd_pool *epd_pool;
3498 	unsigned long iflag;
3499 
3500 	epd_pool = &phba->epd_pool;
3501 	qp = &phba->sli4_hba.hdwq[0];
3502 
3503 	spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3504 	spin_lock(&epd_pool->lock);
3505 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3506 				 &epd_pool->list, list) {
3507 		list_move_tail(&lpfc_ncmd->list,
3508 			       &qp->lpfc_io_buf_list_put);
3509 		lpfc_ncmd->flags = false;
3510 		qp->put_io_bufs++;
3511 		epd_pool->count--;
3512 	}
3513 	spin_unlock(&epd_pool->lock);
3514 	spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3515 }
3516 
3517 /**
3518  * lpfc_create_multixri_pools - create multi-XRI pools
3519  * @phba: pointer to lpfc hba data structure.
3520  *
3521  * This routine initialize public, private per HWQ. Then, move XRIs from
3522  * lpfc_io_buf_list_put to public pool. High and low watermark are also
3523  * Initialized.
3524  **/
3525 void lpfc_create_multixri_pools(struct lpfc_hba *phba)
3526 {
3527 	u32 i, j;
3528 	u32 hwq_count;
3529 	u32 count_per_hwq;
3530 	struct lpfc_io_buf *lpfc_ncmd;
3531 	struct lpfc_io_buf *lpfc_ncmd_next;
3532 	unsigned long iflag;
3533 	struct lpfc_sli4_hdw_queue *qp;
3534 	struct lpfc_multixri_pool *multixri_pool;
3535 	struct lpfc_pbl_pool *pbl_pool;
3536 	struct lpfc_pvt_pool *pvt_pool;
3537 
3538 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3539 			"1234 num_hdw_queue=%d num_present_cpu=%d common_xri_cnt=%d\n",
3540 			phba->cfg_hdw_queue, phba->sli4_hba.num_present_cpu,
3541 			phba->sli4_hba.io_xri_cnt);
3542 
3543 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
3544 		lpfc_create_expedite_pool(phba);
3545 
3546 	hwq_count = phba->cfg_hdw_queue;
3547 	count_per_hwq = phba->sli4_hba.io_xri_cnt / hwq_count;
3548 
3549 	for (i = 0; i < hwq_count; i++) {
3550 		multixri_pool = kzalloc_obj(*multixri_pool);
3551 
3552 		if (!multixri_pool) {
3553 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3554 					"1238 Failed to allocate memory for "
3555 					"multixri_pool\n");
3556 
3557 			if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
3558 				lpfc_destroy_expedite_pool(phba);
3559 
3560 			j = 0;
3561 			while (j < i) {
3562 				qp = &phba->sli4_hba.hdwq[j];
3563 				kfree(qp->p_multixri_pool);
3564 				j++;
3565 			}
3566 			phba->cfg_xri_rebalancing = 0;
3567 			return;
3568 		}
3569 
3570 		qp = &phba->sli4_hba.hdwq[i];
3571 		qp->p_multixri_pool = multixri_pool;
3572 
3573 		multixri_pool->xri_limit = count_per_hwq;
3574 		multixri_pool->rrb_next_hwqid = i;
3575 
3576 		/* Deal with public free xri pool */
3577 		pbl_pool = &multixri_pool->pbl_pool;
3578 		spin_lock_init(&pbl_pool->lock);
3579 		spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3580 		spin_lock(&pbl_pool->lock);
3581 		INIT_LIST_HEAD(&pbl_pool->list);
3582 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3583 					 &qp->lpfc_io_buf_list_put, list) {
3584 			list_move_tail(&lpfc_ncmd->list, &pbl_pool->list);
3585 			qp->put_io_bufs--;
3586 			pbl_pool->count++;
3587 		}
3588 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3589 				"1235 Moved %d buffers from PUT list over to pbl_pool[%d]\n",
3590 				pbl_pool->count, i);
3591 		spin_unlock(&pbl_pool->lock);
3592 		spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3593 
3594 		/* Deal with private free xri pool */
3595 		pvt_pool = &multixri_pool->pvt_pool;
3596 		pvt_pool->high_watermark = multixri_pool->xri_limit / 2;
3597 		pvt_pool->low_watermark = XRI_BATCH;
3598 		spin_lock_init(&pvt_pool->lock);
3599 		spin_lock_irqsave(&pvt_pool->lock, iflag);
3600 		INIT_LIST_HEAD(&pvt_pool->list);
3601 		pvt_pool->count = 0;
3602 		spin_unlock_irqrestore(&pvt_pool->lock, iflag);
3603 	}
3604 }
3605 
3606 /**
3607  * lpfc_destroy_multixri_pools - destroy multi-XRI pools
3608  * @phba: pointer to lpfc hba data structure.
3609  *
3610  * This routine returns XRIs from public/private to lpfc_io_buf_list_put.
3611  **/
3612 static void lpfc_destroy_multixri_pools(struct lpfc_hba *phba)
3613 {
3614 	u32 i;
3615 	u32 hwq_count;
3616 	struct lpfc_io_buf *lpfc_ncmd;
3617 	struct lpfc_io_buf *lpfc_ncmd_next;
3618 	unsigned long iflag;
3619 	struct lpfc_sli4_hdw_queue *qp;
3620 	struct lpfc_multixri_pool *multixri_pool;
3621 	struct lpfc_pbl_pool *pbl_pool;
3622 	struct lpfc_pvt_pool *pvt_pool;
3623 
3624 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
3625 		lpfc_destroy_expedite_pool(phba);
3626 
3627 	if (!test_bit(FC_UNLOADING, &phba->pport->load_flag))
3628 		lpfc_sli_flush_io_rings(phba);
3629 
3630 	hwq_count = phba->cfg_hdw_queue;
3631 
3632 	for (i = 0; i < hwq_count; i++) {
3633 		qp = &phba->sli4_hba.hdwq[i];
3634 		multixri_pool = qp->p_multixri_pool;
3635 		if (!multixri_pool)
3636 			continue;
3637 
3638 		qp->p_multixri_pool = NULL;
3639 
3640 		spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3641 
3642 		/* Deal with public free xri pool */
3643 		pbl_pool = &multixri_pool->pbl_pool;
3644 		spin_lock(&pbl_pool->lock);
3645 
3646 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3647 				"1236 Moving %d buffers from pbl_pool[%d] TO PUT list\n",
3648 				pbl_pool->count, i);
3649 
3650 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3651 					 &pbl_pool->list, list) {
3652 			list_move_tail(&lpfc_ncmd->list,
3653 				       &qp->lpfc_io_buf_list_put);
3654 			qp->put_io_bufs++;
3655 			pbl_pool->count--;
3656 		}
3657 
3658 		INIT_LIST_HEAD(&pbl_pool->list);
3659 		pbl_pool->count = 0;
3660 
3661 		spin_unlock(&pbl_pool->lock);
3662 
3663 		/* Deal with private free xri pool */
3664 		pvt_pool = &multixri_pool->pvt_pool;
3665 		spin_lock(&pvt_pool->lock);
3666 
3667 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3668 				"1237 Moving %d buffers from pvt_pool[%d] TO PUT list\n",
3669 				pvt_pool->count, i);
3670 
3671 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3672 					 &pvt_pool->list, list) {
3673 			list_move_tail(&lpfc_ncmd->list,
3674 				       &qp->lpfc_io_buf_list_put);
3675 			qp->put_io_bufs++;
3676 			pvt_pool->count--;
3677 		}
3678 
3679 		INIT_LIST_HEAD(&pvt_pool->list);
3680 		pvt_pool->count = 0;
3681 
3682 		spin_unlock(&pvt_pool->lock);
3683 		spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3684 
3685 		kfree(multixri_pool);
3686 	}
3687 }
3688 
3689 /**
3690  * lpfc_online - Initialize and bring a HBA online
3691  * @phba: pointer to lpfc hba data structure.
3692  *
3693  * This routine initializes the HBA and brings a HBA online. During this
3694  * process, the management interface is blocked to prevent user space access
3695  * to the HBA interfering with the driver initialization.
3696  *
3697  * Return codes
3698  *   0 - successful
3699  *   1 - failed
3700  **/
3701 int
3702 lpfc_online(struct lpfc_hba *phba)
3703 {
3704 	struct lpfc_vport *vport;
3705 	struct lpfc_vport **vports;
3706 	int i, error = 0;
3707 	bool vpis_cleared = false;
3708 
3709 	if (!phba)
3710 		return 0;
3711 	vport = phba->pport;
3712 
3713 	if (!test_bit(FC_OFFLINE_MODE, &vport->fc_flag))
3714 		return 0;
3715 
3716 	lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
3717 			"0458 Bring Adapter online\n");
3718 
3719 	lpfc_block_mgmt_io(phba, LPFC_MBX_WAIT);
3720 
3721 	if (phba->sli_rev == LPFC_SLI_REV4) {
3722 		if (lpfc_sli4_hba_setup(phba)) { /* Initialize SLI4 HBA */
3723 			lpfc_unblock_mgmt_io(phba);
3724 			return 1;
3725 		}
3726 		spin_lock_irq(&phba->hbalock);
3727 		if (!phba->sli4_hba.max_cfg_param.vpi_used)
3728 			vpis_cleared = true;
3729 		spin_unlock_irq(&phba->hbalock);
3730 
3731 		/* Reestablish the local initiator port.
3732 		 * The offline process destroyed the previous lport.
3733 		 */
3734 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME &&
3735 				!phba->nvmet_support) {
3736 			error = lpfc_nvme_create_localport(phba->pport);
3737 			if (error)
3738 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3739 					"6132 NVME restore reg failed "
3740 					"on nvmei error x%x\n", error);
3741 		}
3742 	} else {
3743 		lpfc_sli_queue_init(phba);
3744 		if (lpfc_sli_hba_setup(phba)) {	/* Initialize SLI2/SLI3 HBA */
3745 			lpfc_unblock_mgmt_io(phba);
3746 			return 1;
3747 		}
3748 	}
3749 
3750 	vports = lpfc_create_vport_work_array(phba);
3751 	if (vports != NULL) {
3752 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3753 			clear_bit(FC_OFFLINE_MODE, &vports[i]->fc_flag);
3754 			if (phba->sli3_options & LPFC_SLI3_NPIV_ENABLED)
3755 				set_bit(FC_VPORT_NEEDS_REG_VPI,
3756 					&vports[i]->fc_flag);
3757 			if (phba->sli_rev == LPFC_SLI_REV4) {
3758 				set_bit(FC_VPORT_NEEDS_INIT_VPI,
3759 					&vports[i]->fc_flag);
3760 				if ((vpis_cleared) &&
3761 				    (vports[i]->port_type !=
3762 					LPFC_PHYSICAL_PORT))
3763 					vports[i]->vpi = 0;
3764 			}
3765 		}
3766 	}
3767 	lpfc_destroy_vport_work_array(phba, vports);
3768 
3769 	if (phba->cfg_xri_rebalancing)
3770 		lpfc_create_multixri_pools(phba);
3771 
3772 	lpfc_cpuhp_add(phba);
3773 
3774 	lpfc_unblock_mgmt_io(phba);
3775 	return 0;
3776 }
3777 
3778 /**
3779  * lpfc_unblock_mgmt_io - Mark a HBA's management interface to be not blocked
3780  * @phba: pointer to lpfc hba data structure.
3781  *
3782  * This routine marks a HBA's management interface as not blocked. Once the
3783  * HBA's management interface is marked as not blocked, all the user space
3784  * access to the HBA, whether they are from sysfs interface or libdfc
3785  * interface will be allowed. The HBA is set to block the management interface
3786  * when the driver prepares the HBA interface for online or offline and then
3787  * set to unblock the management interface afterwards.
3788  **/
3789 void
3790 lpfc_unblock_mgmt_io(struct lpfc_hba * phba)
3791 {
3792 	unsigned long iflag;
3793 
3794 	spin_lock_irqsave(&phba->hbalock, iflag);
3795 	phba->sli.sli_flag &= ~LPFC_BLOCK_MGMT_IO;
3796 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3797 }
3798 
3799 /**
3800  * lpfc_offline_prep - Prepare a HBA to be brought offline
3801  * @phba: pointer to lpfc hba data structure.
3802  * @mbx_action: flag for mailbox shutdown action.
3803  *
3804  * This routine is invoked to prepare a HBA to be brought offline. It performs
3805  * unregistration login to all the nodes on all vports and flushes the mailbox
3806  * queue to make it ready to be brought offline.
3807  **/
3808 void
3809 lpfc_offline_prep(struct lpfc_hba *phba, int mbx_action)
3810 {
3811 	struct lpfc_vport *vport = phba->pport;
3812 	struct lpfc_nodelist  *ndlp, *next_ndlp;
3813 	struct lpfc_vport **vports;
3814 	struct Scsi_Host *shost;
3815 	int i;
3816 	int offline;
3817 	bool hba_pci_err;
3818 
3819 	if (test_bit(FC_OFFLINE_MODE, &vport->fc_flag))
3820 		return;
3821 
3822 	lpfc_block_mgmt_io(phba, mbx_action);
3823 
3824 	lpfc_linkdown(phba);
3825 
3826 	offline =  pci_channel_offline(phba->pcidev);
3827 	hba_pci_err = test_bit(HBA_PCI_ERR, &phba->bit_flags);
3828 
3829 	/* Issue an unreg_login to all nodes on all vports */
3830 	vports = lpfc_create_vport_work_array(phba);
3831 	if (vports != NULL) {
3832 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3833 			if (test_bit(FC_UNLOADING, &vports[i]->load_flag))
3834 				continue;
3835 			shost = lpfc_shost_from_vport(vports[i]);
3836 			spin_lock_irq(shost->host_lock);
3837 			vports[i]->vpi_state &= ~LPFC_VPI_REGISTERED;
3838 			spin_unlock_irq(shost->host_lock);
3839 			set_bit(FC_VPORT_NEEDS_REG_VPI, &vports[i]->fc_flag);
3840 			clear_bit(FC_VFI_REGISTERED, &vports[i]->fc_flag);
3841 
3842 			list_for_each_entry_safe(ndlp, next_ndlp,
3843 						 &vports[i]->fc_nodes,
3844 						 nlp_listp) {
3845 
3846 				clear_bit(NLP_NPR_ADISC, &ndlp->nlp_flag);
3847 				if (offline || hba_pci_err) {
3848 					clear_bit(NLP_UNREG_INP,
3849 						  &ndlp->nlp_flag);
3850 					clear_bit(NLP_RPI_REGISTERED,
3851 						  &ndlp->nlp_flag);
3852 				}
3853 
3854 				if (ndlp->nlp_type & NLP_FABRIC) {
3855 					lpfc_disc_state_machine(vports[i], ndlp,
3856 						NULL, NLP_EVT_DEVICE_RECOVERY);
3857 
3858 					/* Don't remove the node unless the node
3859 					 * has been unregistered with the
3860 					 * transport, and we're not in recovery
3861 					 * before dev_loss_tmo triggered.
3862 					 * Otherwise, let dev_loss take care of
3863 					 * the node.
3864 					 */
3865 					if (!test_bit(NLP_IN_RECOV_POST_DEV_LOSS,
3866 						      &ndlp->save_flags) &&
3867 					    !(ndlp->fc4_xpt_flags &
3868 					      (NVME_XPT_REGD | SCSI_XPT_REGD)))
3869 						lpfc_disc_state_machine
3870 							(vports[i], ndlp,
3871 							 NULL,
3872 							 NLP_EVT_DEVICE_RM);
3873 				}
3874 			}
3875 		}
3876 	}
3877 	lpfc_destroy_vport_work_array(phba, vports);
3878 
3879 	lpfc_sli_mbox_sys_shutdown(phba, mbx_action);
3880 
3881 	if (phba->wq)
3882 		flush_workqueue(phba->wq);
3883 }
3884 
3885 /**
3886  * lpfc_offline - Bring a HBA offline
3887  * @phba: pointer to lpfc hba data structure.
3888  *
3889  * This routine actually brings a HBA offline. It stops all the timers
3890  * associated with the HBA, brings down the SLI layer, and eventually
3891  * marks the HBA as in offline state for the upper layer protocol.
3892  **/
3893 void
3894 lpfc_offline(struct lpfc_hba *phba)
3895 {
3896 	struct Scsi_Host  *shost;
3897 	struct lpfc_vport **vports;
3898 	int i;
3899 
3900 	if (test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag))
3901 		return;
3902 
3903 	/* stop port and all timers associated with this hba */
3904 	lpfc_stop_port(phba);
3905 
3906 	/* Tear down the local and target port registrations.  The
3907 	 * nvme transports need to cleanup.
3908 	 */
3909 	lpfc_nvmet_destroy_targetport(phba);
3910 	lpfc_nvme_destroy_localport(phba->pport);
3911 
3912 	vports = lpfc_create_vport_work_array(phba);
3913 	if (vports != NULL)
3914 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++)
3915 			lpfc_stop_vport_timers(vports[i]);
3916 	lpfc_destroy_vport_work_array(phba, vports);
3917 	lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
3918 			"0460 Bring Adapter offline\n");
3919 	/* Bring down the SLI Layer and cleanup.  The HBA is offline
3920 	   now.  */
3921 	lpfc_sli_hba_down(phba);
3922 	spin_lock_irq(&phba->hbalock);
3923 	phba->work_ha = 0;
3924 	spin_unlock_irq(&phba->hbalock);
3925 	vports = lpfc_create_vport_work_array(phba);
3926 	if (vports != NULL)
3927 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3928 			shost = lpfc_shost_from_vport(vports[i]);
3929 			spin_lock_irq(shost->host_lock);
3930 			vports[i]->work_port_events = 0;
3931 			spin_unlock_irq(shost->host_lock);
3932 			set_bit(FC_OFFLINE_MODE, &vports[i]->fc_flag);
3933 		}
3934 	lpfc_destroy_vport_work_array(phba, vports);
3935 	/* If OFFLINE flag is clear (i.e. unloading), cpuhp removal is handled
3936 	 * in hba_unset
3937 	 */
3938 	if (test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag))
3939 		__lpfc_cpuhp_remove(phba);
3940 
3941 	if (phba->cfg_xri_rebalancing)
3942 		lpfc_destroy_multixri_pools(phba);
3943 }
3944 
3945 /**
3946  * lpfc_scsi_free - Free all the SCSI buffers and IOCBs from driver lists
3947  * @phba: pointer to lpfc hba data structure.
3948  *
3949  * This routine is to free all the SCSI buffers and IOCBs from the driver
3950  * list back to kernel. It is called from lpfc_pci_remove_one to free
3951  * the internal resources before the device is removed from the system.
3952  **/
3953 static void
3954 lpfc_scsi_free(struct lpfc_hba *phba)
3955 {
3956 	struct lpfc_io_buf *sb, *sb_next;
3957 
3958 	if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP))
3959 		return;
3960 
3961 	spin_lock_irq(&phba->hbalock);
3962 
3963 	/* Release all the lpfc_scsi_bufs maintained by this host. */
3964 
3965 	spin_lock(&phba->scsi_buf_list_put_lock);
3966 	list_for_each_entry_safe(sb, sb_next, &phba->lpfc_scsi_buf_list_put,
3967 				 list) {
3968 		list_del(&sb->list);
3969 		dma_pool_free(phba->lpfc_sg_dma_buf_pool, sb->data,
3970 			      sb->dma_handle);
3971 		kfree(sb);
3972 		phba->total_scsi_bufs--;
3973 	}
3974 	spin_unlock(&phba->scsi_buf_list_put_lock);
3975 
3976 	spin_lock(&phba->scsi_buf_list_get_lock);
3977 	list_for_each_entry_safe(sb, sb_next, &phba->lpfc_scsi_buf_list_get,
3978 				 list) {
3979 		list_del(&sb->list);
3980 		dma_pool_free(phba->lpfc_sg_dma_buf_pool, sb->data,
3981 			      sb->dma_handle);
3982 		kfree(sb);
3983 		phba->total_scsi_bufs--;
3984 	}
3985 	spin_unlock(&phba->scsi_buf_list_get_lock);
3986 	spin_unlock_irq(&phba->hbalock);
3987 }
3988 
3989 /**
3990  * lpfc_io_free - Free all the IO buffers and IOCBs from driver lists
3991  * @phba: pointer to lpfc hba data structure.
3992  *
3993  * This routine is to free all the IO buffers and IOCBs from the driver
3994  * list back to kernel. It is called from lpfc_pci_remove_one to free
3995  * the internal resources before the device is removed from the system.
3996  **/
3997 void
3998 lpfc_io_free(struct lpfc_hba *phba)
3999 {
4000 	struct lpfc_io_buf *lpfc_ncmd, *lpfc_ncmd_next;
4001 	struct lpfc_sli4_hdw_queue *qp;
4002 	int idx;
4003 
4004 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
4005 		qp = &phba->sli4_hba.hdwq[idx];
4006 		/* Release all the lpfc_nvme_bufs maintained by this host. */
4007 		spin_lock(&qp->io_buf_list_put_lock);
4008 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
4009 					 &qp->lpfc_io_buf_list_put,
4010 					 list) {
4011 			list_del(&lpfc_ncmd->list);
4012 			qp->put_io_bufs--;
4013 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4014 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4015 			if (phba->cfg_xpsgl && !phba->nvmet_support)
4016 				lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
4017 			lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
4018 			kfree(lpfc_ncmd);
4019 			qp->total_io_bufs--;
4020 		}
4021 		spin_unlock(&qp->io_buf_list_put_lock);
4022 
4023 		spin_lock(&qp->io_buf_list_get_lock);
4024 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
4025 					 &qp->lpfc_io_buf_list_get,
4026 					 list) {
4027 			list_del(&lpfc_ncmd->list);
4028 			qp->get_io_bufs--;
4029 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4030 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4031 			if (phba->cfg_xpsgl && !phba->nvmet_support)
4032 				lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
4033 			lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
4034 			kfree(lpfc_ncmd);
4035 			qp->total_io_bufs--;
4036 		}
4037 		spin_unlock(&qp->io_buf_list_get_lock);
4038 	}
4039 }
4040 
4041 /**
4042  * lpfc_sli4_els_sgl_update - update ELS xri-sgl sizing and mapping
4043  * @phba: pointer to lpfc hba data structure.
4044  *
4045  * This routine first calculates the sizes of the current els and allocated
4046  * scsi sgl lists, and then goes through all sgls to updates the physical
4047  * XRIs assigned due to port function reset. During port initialization, the
4048  * current els and allocated scsi sgl lists are 0s.
4049  *
4050  * Return codes
4051  *   0 - successful (for now, it always returns 0)
4052  **/
4053 int
4054 lpfc_sli4_els_sgl_update(struct lpfc_hba *phba)
4055 {
4056 	struct lpfc_sglq *sglq_entry = NULL, *sglq_entry_next = NULL;
4057 	uint16_t i, lxri, xri_cnt, els_xri_cnt;
4058 	LIST_HEAD(els_sgl_list);
4059 	int rc;
4060 
4061 	/*
4062 	 * update on pci function's els xri-sgl list
4063 	 */
4064 	els_xri_cnt = lpfc_sli4_get_els_iocb_cnt(phba);
4065 
4066 	if (els_xri_cnt > phba->sli4_hba.els_xri_cnt) {
4067 		/* els xri-sgl expanded */
4068 		xri_cnt = els_xri_cnt - phba->sli4_hba.els_xri_cnt;
4069 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4070 				"3157 ELS xri-sgl count increased from "
4071 				"%d to %d\n", phba->sli4_hba.els_xri_cnt,
4072 				els_xri_cnt);
4073 		/* allocate the additional els sgls */
4074 		for (i = 0; i < xri_cnt; i++) {
4075 			sglq_entry = kzalloc_obj(struct lpfc_sglq);
4076 			if (sglq_entry == NULL) {
4077 				lpfc_printf_log(phba, KERN_ERR,
4078 						LOG_TRACE_EVENT,
4079 						"2562 Failure to allocate an "
4080 						"ELS sgl entry:%d\n", i);
4081 				rc = -ENOMEM;
4082 				goto out_free_mem;
4083 			}
4084 			sglq_entry->buff_type = GEN_BUFF_TYPE;
4085 			sglq_entry->virt = lpfc_mbuf_alloc(phba, 0,
4086 							   &sglq_entry->phys);
4087 			if (sglq_entry->virt == NULL) {
4088 				kfree(sglq_entry);
4089 				lpfc_printf_log(phba, KERN_ERR,
4090 						LOG_TRACE_EVENT,
4091 						"2563 Failure to allocate an "
4092 						"ELS mbuf:%d\n", i);
4093 				rc = -ENOMEM;
4094 				goto out_free_mem;
4095 			}
4096 			sglq_entry->sgl = sglq_entry->virt;
4097 			memset(sglq_entry->sgl, 0, LPFC_BPL_SIZE);
4098 			sglq_entry->state = SGL_FREED;
4099 			list_add_tail(&sglq_entry->list, &els_sgl_list);
4100 		}
4101 		spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
4102 		list_splice_init(&els_sgl_list,
4103 				 &phba->sli4_hba.lpfc_els_sgl_list);
4104 		spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
4105 	} else if (els_xri_cnt < phba->sli4_hba.els_xri_cnt) {
4106 		/* els xri-sgl shrunk */
4107 		xri_cnt = phba->sli4_hba.els_xri_cnt - els_xri_cnt;
4108 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4109 				"3158 ELS xri-sgl count decreased from "
4110 				"%d to %d\n", phba->sli4_hba.els_xri_cnt,
4111 				els_xri_cnt);
4112 		spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
4113 		list_splice_init(&phba->sli4_hba.lpfc_els_sgl_list,
4114 				 &els_sgl_list);
4115 		/* release extra els sgls from list */
4116 		for (i = 0; i < xri_cnt; i++) {
4117 			list_remove_head(&els_sgl_list,
4118 					 sglq_entry, struct lpfc_sglq, list);
4119 			if (sglq_entry) {
4120 				__lpfc_mbuf_free(phba, sglq_entry->virt,
4121 						 sglq_entry->phys);
4122 				kfree(sglq_entry);
4123 			}
4124 		}
4125 		list_splice_init(&els_sgl_list,
4126 				 &phba->sli4_hba.lpfc_els_sgl_list);
4127 		spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
4128 	} else
4129 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4130 				"3163 ELS xri-sgl count unchanged: %d\n",
4131 				els_xri_cnt);
4132 	phba->sli4_hba.els_xri_cnt = els_xri_cnt;
4133 
4134 	/* update xris to els sgls on the list */
4135 	sglq_entry = NULL;
4136 	sglq_entry_next = NULL;
4137 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
4138 				 &phba->sli4_hba.lpfc_els_sgl_list, list) {
4139 		lxri = lpfc_sli4_next_xritag(phba);
4140 		if (lxri == NO_XRI) {
4141 			lpfc_printf_log(phba, KERN_ERR,
4142 					LOG_TRACE_EVENT,
4143 					"2400 Failed to allocate xri for "
4144 					"ELS sgl\n");
4145 			rc = -ENOMEM;
4146 			goto out_free_mem;
4147 		}
4148 		sglq_entry->sli4_lxritag = lxri;
4149 		sglq_entry->sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4150 	}
4151 	return 0;
4152 
4153 out_free_mem:
4154 	lpfc_free_els_sgl_list(phba);
4155 	return rc;
4156 }
4157 
4158 /**
4159  * lpfc_sli4_nvmet_sgl_update - update xri-sgl sizing and mapping
4160  * @phba: pointer to lpfc hba data structure.
4161  *
4162  * This routine first calculates the sizes of the current els and allocated
4163  * scsi sgl lists, and then goes through all sgls to updates the physical
4164  * XRIs assigned due to port function reset. During port initialization, the
4165  * current els and allocated scsi sgl lists are 0s.
4166  *
4167  * Return codes
4168  *   0 - successful (for now, it always returns 0)
4169  **/
4170 int
4171 lpfc_sli4_nvmet_sgl_update(struct lpfc_hba *phba)
4172 {
4173 	struct lpfc_sglq *sglq_entry = NULL, *sglq_entry_next = NULL;
4174 	uint16_t i, lxri, xri_cnt, els_xri_cnt;
4175 	uint16_t nvmet_xri_cnt;
4176 	LIST_HEAD(nvmet_sgl_list);
4177 	int rc;
4178 
4179 	/*
4180 	 * update on pci function's nvmet xri-sgl list
4181 	 */
4182 	els_xri_cnt = lpfc_sli4_get_els_iocb_cnt(phba);
4183 
4184 	/* For NVMET, ALL remaining XRIs are dedicated for IO processing */
4185 	nvmet_xri_cnt = phba->sli4_hba.max_cfg_param.max_xri - els_xri_cnt;
4186 	if (nvmet_xri_cnt > phba->sli4_hba.nvmet_xri_cnt) {
4187 		/* els xri-sgl expanded */
4188 		xri_cnt = nvmet_xri_cnt - phba->sli4_hba.nvmet_xri_cnt;
4189 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4190 				"6302 NVMET xri-sgl cnt grew from %d to %d\n",
4191 				phba->sli4_hba.nvmet_xri_cnt, nvmet_xri_cnt);
4192 		/* allocate the additional nvmet sgls */
4193 		for (i = 0; i < xri_cnt; i++) {
4194 			sglq_entry = kzalloc_obj(struct lpfc_sglq);
4195 			if (sglq_entry == NULL) {
4196 				lpfc_printf_log(phba, KERN_ERR,
4197 						LOG_TRACE_EVENT,
4198 						"6303 Failure to allocate an "
4199 						"NVMET sgl entry:%d\n", i);
4200 				rc = -ENOMEM;
4201 				goto out_free_mem;
4202 			}
4203 			sglq_entry->buff_type = NVMET_BUFF_TYPE;
4204 			sglq_entry->virt = lpfc_nvmet_buf_alloc(phba, 0,
4205 							   &sglq_entry->phys);
4206 			if (sglq_entry->virt == NULL) {
4207 				kfree(sglq_entry);
4208 				lpfc_printf_log(phba, KERN_ERR,
4209 						LOG_TRACE_EVENT,
4210 						"6304 Failure to allocate an "
4211 						"NVMET buf:%d\n", i);
4212 				rc = -ENOMEM;
4213 				goto out_free_mem;
4214 			}
4215 			sglq_entry->sgl = sglq_entry->virt;
4216 			memset(sglq_entry->sgl, 0,
4217 			       phba->cfg_sg_dma_buf_size);
4218 			sglq_entry->state = SGL_FREED;
4219 			list_add_tail(&sglq_entry->list, &nvmet_sgl_list);
4220 		}
4221 		spin_lock_irq(&phba->hbalock);
4222 		spin_lock(&phba->sli4_hba.sgl_list_lock);
4223 		list_splice_init(&nvmet_sgl_list,
4224 				 &phba->sli4_hba.lpfc_nvmet_sgl_list);
4225 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
4226 		spin_unlock_irq(&phba->hbalock);
4227 	} else if (nvmet_xri_cnt < phba->sli4_hba.nvmet_xri_cnt) {
4228 		/* nvmet xri-sgl shrunk */
4229 		xri_cnt = phba->sli4_hba.nvmet_xri_cnt - nvmet_xri_cnt;
4230 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4231 				"6305 NVMET xri-sgl count decreased from "
4232 				"%d to %d\n", phba->sli4_hba.nvmet_xri_cnt,
4233 				nvmet_xri_cnt);
4234 		spin_lock_irq(&phba->hbalock);
4235 		spin_lock(&phba->sli4_hba.sgl_list_lock);
4236 		list_splice_init(&phba->sli4_hba.lpfc_nvmet_sgl_list,
4237 				 &nvmet_sgl_list);
4238 		/* release extra nvmet sgls from list */
4239 		for (i = 0; i < xri_cnt; i++) {
4240 			list_remove_head(&nvmet_sgl_list,
4241 					 sglq_entry, struct lpfc_sglq, list);
4242 			if (sglq_entry) {
4243 				lpfc_nvmet_buf_free(phba, sglq_entry->virt,
4244 						    sglq_entry->phys);
4245 				kfree(sglq_entry);
4246 			}
4247 		}
4248 		list_splice_init(&nvmet_sgl_list,
4249 				 &phba->sli4_hba.lpfc_nvmet_sgl_list);
4250 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
4251 		spin_unlock_irq(&phba->hbalock);
4252 	} else
4253 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4254 				"6306 NVMET xri-sgl count unchanged: %d\n",
4255 				nvmet_xri_cnt);
4256 	phba->sli4_hba.nvmet_xri_cnt = nvmet_xri_cnt;
4257 
4258 	/* update xris to nvmet sgls on the list */
4259 	sglq_entry = NULL;
4260 	sglq_entry_next = NULL;
4261 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
4262 				 &phba->sli4_hba.lpfc_nvmet_sgl_list, list) {
4263 		lxri = lpfc_sli4_next_xritag(phba);
4264 		if (lxri == NO_XRI) {
4265 			lpfc_printf_log(phba, KERN_ERR,
4266 					LOG_TRACE_EVENT,
4267 					"6307 Failed to allocate xri for "
4268 					"NVMET sgl\n");
4269 			rc = -ENOMEM;
4270 			goto out_free_mem;
4271 		}
4272 		sglq_entry->sli4_lxritag = lxri;
4273 		sglq_entry->sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4274 	}
4275 	return 0;
4276 
4277 out_free_mem:
4278 	lpfc_free_nvmet_sgl_list(phba);
4279 	return rc;
4280 }
4281 
4282 int
4283 lpfc_io_buf_flush(struct lpfc_hba *phba, struct list_head *cbuf)
4284 {
4285 	LIST_HEAD(blist);
4286 	struct lpfc_sli4_hdw_queue *qp;
4287 	struct lpfc_io_buf *lpfc_cmd;
4288 	struct lpfc_io_buf *iobufp, *prev_iobufp;
4289 	int idx, cnt, xri, inserted;
4290 
4291 	cnt = 0;
4292 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
4293 		qp = &phba->sli4_hba.hdwq[idx];
4294 		spin_lock_irq(&qp->io_buf_list_get_lock);
4295 		spin_lock(&qp->io_buf_list_put_lock);
4296 
4297 		/* Take everything off the get and put lists */
4298 		list_splice_init(&qp->lpfc_io_buf_list_get, &blist);
4299 		list_splice(&qp->lpfc_io_buf_list_put, &blist);
4300 		INIT_LIST_HEAD(&qp->lpfc_io_buf_list_get);
4301 		INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
4302 		cnt += qp->get_io_bufs + qp->put_io_bufs;
4303 		qp->get_io_bufs = 0;
4304 		qp->put_io_bufs = 0;
4305 		qp->total_io_bufs = 0;
4306 		spin_unlock(&qp->io_buf_list_put_lock);
4307 		spin_unlock_irq(&qp->io_buf_list_get_lock);
4308 	}
4309 
4310 	/*
4311 	 * Take IO buffers off blist and put on cbuf sorted by XRI.
4312 	 * This is because POST_SGL takes a sequential range of XRIs
4313 	 * to post to the firmware.
4314 	 */
4315 	for (idx = 0; idx < cnt; idx++) {
4316 		list_remove_head(&blist, lpfc_cmd, struct lpfc_io_buf, list);
4317 		if (!lpfc_cmd)
4318 			return cnt;
4319 		if (idx == 0) {
4320 			list_add_tail(&lpfc_cmd->list, cbuf);
4321 			continue;
4322 		}
4323 		xri = lpfc_cmd->cur_iocbq.sli4_xritag;
4324 		inserted = 0;
4325 		prev_iobufp = NULL;
4326 		list_for_each_entry(iobufp, cbuf, list) {
4327 			if (xri < iobufp->cur_iocbq.sli4_xritag) {
4328 				if (prev_iobufp)
4329 					list_add(&lpfc_cmd->list,
4330 						 &prev_iobufp->list);
4331 				else
4332 					list_add(&lpfc_cmd->list, cbuf);
4333 				inserted = 1;
4334 				break;
4335 			}
4336 			prev_iobufp = iobufp;
4337 		}
4338 		if (!inserted)
4339 			list_add_tail(&lpfc_cmd->list, cbuf);
4340 	}
4341 	return cnt;
4342 }
4343 
4344 int
4345 lpfc_io_buf_replenish(struct lpfc_hba *phba, struct list_head *cbuf)
4346 {
4347 	struct lpfc_sli4_hdw_queue *qp;
4348 	struct lpfc_io_buf *lpfc_cmd;
4349 	int idx, cnt;
4350 	unsigned long iflags;
4351 
4352 	qp = phba->sli4_hba.hdwq;
4353 	cnt = 0;
4354 	while (!list_empty(cbuf)) {
4355 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
4356 			list_remove_head(cbuf, lpfc_cmd,
4357 					 struct lpfc_io_buf, list);
4358 			if (!lpfc_cmd)
4359 				return cnt;
4360 			cnt++;
4361 			qp = &phba->sli4_hba.hdwq[idx];
4362 			lpfc_cmd->hdwq_no = idx;
4363 			lpfc_cmd->hdwq = qp;
4364 			lpfc_cmd->cur_iocbq.cmd_cmpl = NULL;
4365 			spin_lock_irqsave(&qp->io_buf_list_put_lock, iflags);
4366 			list_add_tail(&lpfc_cmd->list,
4367 				      &qp->lpfc_io_buf_list_put);
4368 			qp->put_io_bufs++;
4369 			qp->total_io_bufs++;
4370 			spin_unlock_irqrestore(&qp->io_buf_list_put_lock,
4371 					       iflags);
4372 		}
4373 	}
4374 	return cnt;
4375 }
4376 
4377 /**
4378  * lpfc_sli4_io_sgl_update - update xri-sgl sizing and mapping
4379  * @phba: pointer to lpfc hba data structure.
4380  *
4381  * This routine first calculates the sizes of the current els and allocated
4382  * scsi sgl lists, and then goes through all sgls to updates the physical
4383  * XRIs assigned due to port function reset. During port initialization, the
4384  * current els and allocated scsi sgl lists are 0s.
4385  *
4386  * Return codes
4387  *   0 - successful (for now, it always returns 0)
4388  **/
4389 int
4390 lpfc_sli4_io_sgl_update(struct lpfc_hba *phba)
4391 {
4392 	struct lpfc_io_buf *lpfc_ncmd = NULL, *lpfc_ncmd_next = NULL;
4393 	uint16_t i, lxri, els_xri_cnt;
4394 	uint16_t io_xri_cnt, io_xri_max;
4395 	LIST_HEAD(io_sgl_list);
4396 	int rc, cnt;
4397 
4398 	/*
4399 	 * update on pci function's allocated nvme xri-sgl list
4400 	 */
4401 
4402 	/* maximum number of xris available for nvme buffers */
4403 	els_xri_cnt = lpfc_sli4_get_els_iocb_cnt(phba);
4404 	io_xri_max = phba->sli4_hba.max_cfg_param.max_xri - els_xri_cnt;
4405 	phba->sli4_hba.io_xri_max = io_xri_max;
4406 
4407 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4408 			"6074 Current allocated XRI sgl count:%d, "
4409 			"maximum XRI count:%d els_xri_cnt:%d\n\n",
4410 			phba->sli4_hba.io_xri_cnt,
4411 			phba->sli4_hba.io_xri_max,
4412 			els_xri_cnt);
4413 
4414 	cnt = lpfc_io_buf_flush(phba, &io_sgl_list);
4415 
4416 	if (phba->sli4_hba.io_xri_cnt > phba->sli4_hba.io_xri_max) {
4417 		/* max nvme xri shrunk below the allocated nvme buffers */
4418 		io_xri_cnt = phba->sli4_hba.io_xri_cnt -
4419 					phba->sli4_hba.io_xri_max;
4420 		/* release the extra allocated nvme buffers */
4421 		for (i = 0; i < io_xri_cnt; i++) {
4422 			list_remove_head(&io_sgl_list, lpfc_ncmd,
4423 					 struct lpfc_io_buf, list);
4424 			if (lpfc_ncmd) {
4425 				dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4426 					      lpfc_ncmd->data,
4427 					      lpfc_ncmd->dma_handle);
4428 				kfree(lpfc_ncmd);
4429 			}
4430 		}
4431 		phba->sli4_hba.io_xri_cnt -= io_xri_cnt;
4432 	}
4433 
4434 	/* update xris associated to remaining allocated nvme buffers */
4435 	lpfc_ncmd = NULL;
4436 	lpfc_ncmd_next = NULL;
4437 	phba->sli4_hba.io_xri_cnt = cnt;
4438 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
4439 				 &io_sgl_list, list) {
4440 		lxri = lpfc_sli4_next_xritag(phba);
4441 		if (lxri == NO_XRI) {
4442 			lpfc_printf_log(phba, KERN_ERR,
4443 					LOG_TRACE_EVENT,
4444 					"6075 Failed to allocate xri for "
4445 					"nvme buffer\n");
4446 			rc = -ENOMEM;
4447 			goto out_free_mem;
4448 		}
4449 		lpfc_ncmd->cur_iocbq.sli4_lxritag = lxri;
4450 		lpfc_ncmd->cur_iocbq.sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4451 	}
4452 	cnt = lpfc_io_buf_replenish(phba, &io_sgl_list);
4453 	return 0;
4454 
4455 out_free_mem:
4456 	lpfc_io_free(phba);
4457 	return rc;
4458 }
4459 
4460 /**
4461  * lpfc_new_io_buf - IO buffer allocator for HBA with SLI4 IF spec
4462  * @phba: Pointer to lpfc hba data structure.
4463  * @num_to_alloc: The requested number of buffers to allocate.
4464  *
4465  * This routine allocates nvme buffers for device with SLI-4 interface spec,
4466  * the nvme buffer contains all the necessary information needed to initiate
4467  * an I/O. After allocating up to @num_to_allocate IO buffers and put
4468  * them on a list, it post them to the port by using SGL block post.
4469  *
4470  * Return codes:
4471  *   int - number of IO buffers that were allocated and posted.
4472  *   0 = failure, less than num_to_alloc is a partial failure.
4473  **/
4474 int
4475 lpfc_new_io_buf(struct lpfc_hba *phba, int num_to_alloc)
4476 {
4477 	struct lpfc_io_buf *lpfc_ncmd;
4478 	struct lpfc_iocbq *pwqeq;
4479 	uint16_t iotag, lxri = 0;
4480 	int bcnt, num_posted;
4481 	LIST_HEAD(prep_nblist);
4482 	LIST_HEAD(post_nblist);
4483 	LIST_HEAD(nvme_nblist);
4484 
4485 	phba->sli4_hba.io_xri_cnt = 0;
4486 	for (bcnt = 0; bcnt < num_to_alloc; bcnt++) {
4487 		lpfc_ncmd = kzalloc_obj(*lpfc_ncmd);
4488 		if (!lpfc_ncmd)
4489 			break;
4490 		/*
4491 		 * Get memory from the pci pool to map the virt space to
4492 		 * pci bus space for an I/O. The DMA buffer includes the
4493 		 * number of SGE's necessary to support the sg_tablesize.
4494 		 */
4495 		lpfc_ncmd->data = dma_pool_zalloc(phba->lpfc_sg_dma_buf_pool,
4496 						  GFP_KERNEL,
4497 						  &lpfc_ncmd->dma_handle);
4498 		if (!lpfc_ncmd->data) {
4499 			kfree(lpfc_ncmd);
4500 			break;
4501 		}
4502 
4503 		if (phba->cfg_xpsgl && !phba->nvmet_support) {
4504 			INIT_LIST_HEAD(&lpfc_ncmd->dma_sgl_xtra_list);
4505 		} else {
4506 			/*
4507 			 * 4K Page alignment is CRITICAL to BlockGuard, double
4508 			 * check to be sure.
4509 			 */
4510 			if ((phba->sli3_options & LPFC_SLI3_BG_ENABLED) &&
4511 			    (((unsigned long)(lpfc_ncmd->data) &
4512 			    (unsigned long)(SLI4_PAGE_SIZE - 1)) != 0)) {
4513 				lpfc_printf_log(phba, KERN_ERR,
4514 						LOG_TRACE_EVENT,
4515 						"3369 Memory alignment err: "
4516 						"addr=%lx\n",
4517 						(unsigned long)lpfc_ncmd->data);
4518 				dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4519 					      lpfc_ncmd->data,
4520 					      lpfc_ncmd->dma_handle);
4521 				kfree(lpfc_ncmd);
4522 				break;
4523 			}
4524 		}
4525 
4526 		INIT_LIST_HEAD(&lpfc_ncmd->dma_cmd_rsp_list);
4527 
4528 		lxri = lpfc_sli4_next_xritag(phba);
4529 		if (lxri == NO_XRI) {
4530 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4531 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4532 			kfree(lpfc_ncmd);
4533 			break;
4534 		}
4535 		pwqeq = &lpfc_ncmd->cur_iocbq;
4536 
4537 		/* Allocate iotag for lpfc_ncmd->cur_iocbq. */
4538 		iotag = lpfc_sli_next_iotag(phba, pwqeq);
4539 		if (iotag == 0) {
4540 			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4541 				      lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4542 			kfree(lpfc_ncmd);
4543 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4544 					"6121 Failed to allocate IOTAG for"
4545 					" XRI:0x%x\n", lxri);
4546 			lpfc_sli4_free_xri(phba, lxri);
4547 			break;
4548 		}
4549 		pwqeq->sli4_lxritag = lxri;
4550 		pwqeq->sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4551 
4552 		/* Initialize local short-hand pointers. */
4553 		lpfc_ncmd->dma_sgl = lpfc_ncmd->data;
4554 		lpfc_ncmd->dma_phys_sgl = lpfc_ncmd->dma_handle;
4555 		lpfc_ncmd->cur_iocbq.io_buf = lpfc_ncmd;
4556 		spin_lock_init(&lpfc_ncmd->buf_lock);
4557 
4558 		/* add the nvme buffer to a post list */
4559 		list_add_tail(&lpfc_ncmd->list, &post_nblist);
4560 		phba->sli4_hba.io_xri_cnt++;
4561 	}
4562 	lpfc_printf_log(phba, KERN_INFO, LOG_NVME,
4563 			"6114 Allocate %d out of %d requested new NVME "
4564 			"buffers of size x%zu bytes\n", bcnt, num_to_alloc,
4565 			sizeof(*lpfc_ncmd));
4566 
4567 
4568 	/* post the list of nvme buffer sgls to port if available */
4569 	if (!list_empty(&post_nblist))
4570 		num_posted = lpfc_sli4_post_io_sgl_list(
4571 				phba, &post_nblist, bcnt);
4572 	else
4573 		num_posted = 0;
4574 
4575 	return num_posted;
4576 }
4577 
4578 static uint64_t
4579 lpfc_get_wwpn(struct lpfc_hba *phba)
4580 {
4581 	uint64_t wwn;
4582 	int rc;
4583 	LPFC_MBOXQ_t *mboxq;
4584 	MAILBOX_t *mb;
4585 
4586 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
4587 						GFP_KERNEL);
4588 	if (!mboxq)
4589 		return (uint64_t)-1;
4590 
4591 	/* First get WWN of HBA instance */
4592 	lpfc_read_nv(phba, mboxq);
4593 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
4594 	if (rc != MBX_SUCCESS) {
4595 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4596 				"6019 Mailbox failed , mbxCmd x%x "
4597 				"READ_NV, mbxStatus x%x\n",
4598 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
4599 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
4600 		mempool_free(mboxq, phba->mbox_mem_pool);
4601 		return (uint64_t) -1;
4602 	}
4603 	mb = &mboxq->u.mb;
4604 	memcpy(&wwn, (char *)mb->un.varRDnvp.portname, sizeof(uint64_t));
4605 	/* wwn is WWPN of HBA instance */
4606 	mempool_free(mboxq, phba->mbox_mem_pool);
4607 	if (phba->sli_rev == LPFC_SLI_REV4)
4608 		return be64_to_cpu(wwn);
4609 	else
4610 		return rol64(wwn, 32);
4611 }
4612 
4613 static unsigned short lpfc_get_sg_tablesize(struct lpfc_hba *phba)
4614 {
4615 	if (phba->sli_rev == LPFC_SLI_REV4)
4616 		if (phba->cfg_xpsgl && !phba->nvmet_support)
4617 			return LPFC_MAX_SG_TABLESIZE;
4618 		else
4619 			return phba->cfg_scsi_seg_cnt;
4620 	else
4621 		return phba->cfg_sg_seg_cnt;
4622 }
4623 
4624 /**
4625  * lpfc_vmid_res_alloc - Allocates resources for VMID
4626  * @phba: pointer to lpfc hba data structure.
4627  * @vport: pointer to vport data structure
4628  *
4629  * This routine allocated the resources needed for the VMID.
4630  *
4631  * Return codes
4632  *	0 on Success
4633  *	Non-0 on Failure
4634  */
4635 static int
4636 lpfc_vmid_res_alloc(struct lpfc_hba *phba, struct lpfc_vport *vport)
4637 {
4638 	/* VMID feature is supported only on SLI4 */
4639 	if (phba->sli_rev == LPFC_SLI_REV3) {
4640 		phba->cfg_vmid_app_header = 0;
4641 		phba->cfg_vmid_priority_tagging = 0;
4642 	}
4643 
4644 	if (lpfc_is_vmid_enabled(phba)) {
4645 		vport->vmid =
4646 		    kzalloc_objs(struct lpfc_vmid, phba->cfg_max_vmid);
4647 		if (!vport->vmid)
4648 			return -ENOMEM;
4649 
4650 		rwlock_init(&vport->vmid_lock);
4651 
4652 		/* Set the VMID parameters for the vport */
4653 		vport->vmid_priority_tagging = phba->cfg_vmid_priority_tagging;
4654 		vport->vmid_inactivity_timeout =
4655 		    phba->cfg_vmid_inactivity_timeout;
4656 		vport->max_vmid = phba->cfg_max_vmid;
4657 		vport->cur_vmid_cnt = 0;
4658 
4659 		vport->vmid_priority_range = bitmap_zalloc
4660 			(LPFC_VMID_MAX_PRIORITY_RANGE, GFP_KERNEL);
4661 
4662 		if (!vport->vmid_priority_range) {
4663 			kfree(vport->vmid);
4664 			return -ENOMEM;
4665 		}
4666 
4667 		hash_init(vport->hash_table);
4668 	}
4669 	return 0;
4670 }
4671 
4672 /**
4673  * lpfc_create_port - Create an FC port
4674  * @phba: pointer to lpfc hba data structure.
4675  * @instance: a unique integer ID to this FC port.
4676  * @dev: pointer to the device data structure.
4677  *
4678  * This routine creates a FC port for the upper layer protocol. The FC port
4679  * can be created on top of either a physical port or a virtual port provided
4680  * by the HBA. This routine also allocates a SCSI host data structure (shost)
4681  * and associates the FC port created before adding the shost into the SCSI
4682  * layer.
4683  *
4684  * Return codes
4685  *   @vport - pointer to the virtual N_Port data structure.
4686  *   NULL - port create failed.
4687  **/
4688 struct lpfc_vport *
4689 lpfc_create_port(struct lpfc_hba *phba, int instance, struct device *dev)
4690 {
4691 	struct lpfc_vport *vport;
4692 	struct Scsi_Host  *shost = NULL;
4693 	struct scsi_host_template *template;
4694 	int error = 0;
4695 	int i;
4696 	uint64_t wwn;
4697 	bool use_no_reset_hba = false;
4698 	int rc;
4699 	u8 if_type;
4700 
4701 	if (lpfc_no_hba_reset_cnt) {
4702 		if (phba->sli_rev < LPFC_SLI_REV4 &&
4703 		    dev == &phba->pcidev->dev) {
4704 			/* Reset the port first */
4705 			lpfc_sli_brdrestart(phba);
4706 			rc = lpfc_sli_chipset_init(phba);
4707 			if (rc)
4708 				return NULL;
4709 		}
4710 		wwn = lpfc_get_wwpn(phba);
4711 	}
4712 
4713 	for (i = 0; i < lpfc_no_hba_reset_cnt; i++) {
4714 		if (wwn == lpfc_no_hba_reset[i]) {
4715 			lpfc_printf_log(phba, KERN_ERR,
4716 					LOG_TRACE_EVENT,
4717 					"6020 Setting use_no_reset port=%llx\n",
4718 					wwn);
4719 			use_no_reset_hba = true;
4720 			break;
4721 		}
4722 	}
4723 
4724 	/* Seed template for SCSI host registration */
4725 	if (dev == &phba->pcidev->dev) {
4726 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP) {
4727 			/* Seed physical port template */
4728 			template = &lpfc_template;
4729 
4730 			if (use_no_reset_hba)
4731 				/* template is for a no reset SCSI Host */
4732 				template->eh_host_reset_handler = NULL;
4733 
4734 			/* Seed updated value of sg_tablesize */
4735 			template->sg_tablesize = lpfc_get_sg_tablesize(phba);
4736 		} else {
4737 			/* NVMET is for physical port only */
4738 			template = &lpfc_template_nvme;
4739 		}
4740 	} else {
4741 		/* Seed vport template */
4742 		template = &lpfc_vport_template;
4743 
4744 		/* Seed updated value of sg_tablesize */
4745 		template->sg_tablesize = lpfc_get_sg_tablesize(phba);
4746 	}
4747 
4748 	shost = scsi_host_alloc(template, sizeof(struct lpfc_vport));
4749 	if (!shost)
4750 		goto out;
4751 
4752 	vport = (struct lpfc_vport *) shost->hostdata;
4753 	vport->phba = phba;
4754 	set_bit(FC_LOADING, &vport->load_flag);
4755 	set_bit(FC_VPORT_NEEDS_REG_VPI, &vport->fc_flag);
4756 	vport->fc_rscn_flush = 0;
4757 	atomic_set(&vport->fc_plogi_cnt, 0);
4758 	atomic_set(&vport->fc_adisc_cnt, 0);
4759 	atomic_set(&vport->fc_reglogin_cnt, 0);
4760 	atomic_set(&vport->fc_prli_cnt, 0);
4761 	atomic_set(&vport->fc_unmap_cnt, 0);
4762 	atomic_set(&vport->fc_map_cnt, 0);
4763 	atomic_set(&vport->fc_npr_cnt, 0);
4764 	atomic_set(&vport->fc_unused_cnt, 0);
4765 	lpfc_get_vport_cfgparam(vport);
4766 
4767 	/* Adjust value in vport */
4768 	vport->cfg_enable_fc4_type = phba->cfg_enable_fc4_type;
4769 
4770 	shost->unique_id = instance;
4771 	shost->max_id = LPFC_MAX_TARGET;
4772 	shost->max_lun = vport->cfg_max_luns;
4773 	shost->this_id = -1;
4774 
4775 	/* Set max_cmd_len applicable to ASIC support */
4776 	if (phba->sli_rev == LPFC_SLI_REV4) {
4777 		if_type = bf_get(lpfc_sli_intf_if_type,
4778 				 &phba->sli4_hba.sli_intf);
4779 		switch (if_type) {
4780 		case LPFC_SLI_INTF_IF_TYPE_2:
4781 			fallthrough;
4782 		case LPFC_SLI_INTF_IF_TYPE_6:
4783 			shost->max_cmd_len = LPFC_FCP_CDB_LEN_32;
4784 			break;
4785 		default:
4786 			shost->max_cmd_len = LPFC_FCP_CDB_LEN;
4787 			break;
4788 		}
4789 	} else {
4790 		shost->max_cmd_len = LPFC_FCP_CDB_LEN;
4791 	}
4792 
4793 	if (phba->sli_rev == LPFC_SLI_REV4) {
4794 		if (!phba->cfg_fcp_mq_threshold ||
4795 		    phba->cfg_fcp_mq_threshold > phba->cfg_hdw_queue)
4796 			phba->cfg_fcp_mq_threshold = phba->cfg_hdw_queue;
4797 
4798 		shost->nr_hw_queues = min_t(int, 2 * num_possible_nodes(),
4799 					    phba->cfg_fcp_mq_threshold);
4800 
4801 		shost->dma_boundary =
4802 			phba->sli4_hba.pc_sli4_params.sge_supp_len-1;
4803 	} else
4804 		/* SLI-3 has a limited number of hardware queues (3),
4805 		 * thus there is only one for FCP processing.
4806 		 */
4807 		shost->nr_hw_queues = 1;
4808 
4809 	/*
4810 	 * Set initial can_queue value since 0 is no longer supported and
4811 	 * scsi_add_host will fail. This will be adjusted later based on the
4812 	 * max xri value determined in hba setup.
4813 	 */
4814 	shost->can_queue = phba->cfg_hba_queue_depth - 10;
4815 	if (dev != &phba->pcidev->dev) {
4816 		shost->transportt = lpfc_vport_transport_template;
4817 		vport->port_type = LPFC_NPIV_PORT;
4818 	} else {
4819 		shost->transportt = lpfc_transport_template;
4820 		vport->port_type = LPFC_PHYSICAL_PORT;
4821 	}
4822 
4823 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP,
4824 			"9081 CreatePort TMPLATE type %x TBLsize %d "
4825 			"SEGcnt %d/%d\n",
4826 			vport->port_type, shost->sg_tablesize,
4827 			phba->cfg_scsi_seg_cnt, phba->cfg_sg_seg_cnt);
4828 
4829 	/* Allocate the resources for VMID */
4830 	rc = lpfc_vmid_res_alloc(phba, vport);
4831 
4832 	if (rc)
4833 		goto out_put_shost;
4834 
4835 	/* Initialize all internally managed lists. */
4836 	INIT_LIST_HEAD(&vport->fc_nodes);
4837 	spin_lock_init(&vport->fc_nodes_list_lock);
4838 	INIT_LIST_HEAD(&vport->rcv_buffer_list);
4839 	spin_lock_init(&vport->work_port_lock);
4840 
4841 	timer_setup(&vport->fc_disctmo, lpfc_disc_timeout, 0);
4842 
4843 	timer_setup(&vport->els_tmofunc, lpfc_els_timeout, 0);
4844 
4845 	timer_setup(&vport->delayed_disc_tmo, lpfc_delayed_disc_tmo, 0);
4846 
4847 	if (phba->sli3_options & LPFC_SLI3_BG_ENABLED)
4848 		lpfc_setup_bg(phba, shost);
4849 
4850 	error = scsi_add_host_with_dma(shost, dev, &phba->pcidev->dev);
4851 	if (error)
4852 		goto out_free_vmid;
4853 
4854 	spin_lock_irq(&phba->port_list_lock);
4855 	list_add_tail(&vport->listentry, &phba->port_list);
4856 	spin_unlock_irq(&phba->port_list_lock);
4857 	return vport;
4858 
4859 out_free_vmid:
4860 	kfree(vport->vmid);
4861 	bitmap_free(vport->vmid_priority_range);
4862 out_put_shost:
4863 	scsi_host_put(shost);
4864 out:
4865 	return NULL;
4866 }
4867 
4868 /**
4869  * destroy_port -  destroy an FC port
4870  * @vport: pointer to an lpfc virtual N_Port data structure.
4871  *
4872  * This routine destroys a FC port from the upper layer protocol. All the
4873  * resources associated with the port are released.
4874  **/
4875 void
4876 destroy_port(struct lpfc_vport *vport)
4877 {
4878 	struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
4879 	struct lpfc_hba  *phba = vport->phba;
4880 
4881 	lpfc_debugfs_terminate(vport);
4882 	fc_remove_host(shost);
4883 	scsi_remove_host(shost);
4884 
4885 	spin_lock_irq(&phba->port_list_lock);
4886 	list_del_init(&vport->listentry);
4887 	spin_unlock_irq(&phba->port_list_lock);
4888 
4889 	lpfc_cleanup(vport);
4890 	return;
4891 }
4892 
4893 /**
4894  * lpfc_get_instance - Get a unique integer ID
4895  *
4896  * This routine allocates a unique integer ID from lpfc_hba_index pool. It
4897  * uses the kernel idr facility to perform the task.
4898  *
4899  * Return codes:
4900  *   instance - a unique integer ID allocated as the new instance.
4901  *   -1 - lpfc get instance failed.
4902  **/
4903 int
4904 lpfc_get_instance(void)
4905 {
4906 	int ret;
4907 
4908 	ret = idr_alloc(&lpfc_hba_index, NULL, 0, 0, GFP_KERNEL);
4909 	return ret < 0 ? -1 : ret;
4910 }
4911 
4912 /**
4913  * lpfc_scan_finished - method for SCSI layer to detect whether scan is done
4914  * @shost: pointer to SCSI host data structure.
4915  * @time: elapsed time of the scan in jiffies.
4916  *
4917  * This routine is called by the SCSI layer with a SCSI host to determine
4918  * whether the scan host is finished.
4919  *
4920  * Note: there is no scan_start function as adapter initialization will have
4921  * asynchronously kicked off the link initialization.
4922  *
4923  * Return codes
4924  *   0 - SCSI host scan is not over yet.
4925  *   1 - SCSI host scan is over.
4926  **/
4927 int lpfc_scan_finished(struct Scsi_Host *shost, unsigned long time)
4928 {
4929 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
4930 	struct lpfc_hba   *phba = vport->phba;
4931 	int stat = 0;
4932 
4933 	spin_lock_irq(shost->host_lock);
4934 
4935 	if (test_bit(FC_UNLOADING, &vport->load_flag)) {
4936 		stat = 1;
4937 		goto finished;
4938 	}
4939 	if (time >= secs_to_jiffies(30)) {
4940 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4941 				"0461 Scanning longer than 30 "
4942 				"seconds.  Continuing initialization\n");
4943 		stat = 1;
4944 		goto finished;
4945 	}
4946 	if (time >= secs_to_jiffies(15) &&
4947 	    phba->link_state <= LPFC_LINK_DOWN) {
4948 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4949 				"0465 Link down longer than 15 "
4950 				"seconds.  Continuing initialization\n");
4951 		stat = 1;
4952 		goto finished;
4953 	}
4954 
4955 	if (vport->port_state != LPFC_VPORT_READY)
4956 		goto finished;
4957 	if (vport->num_disc_nodes || vport->fc_prli_sent)
4958 		goto finished;
4959 	if (!atomic_read(&vport->fc_map_cnt) &&
4960 	    time < secs_to_jiffies(2))
4961 		goto finished;
4962 	if ((phba->sli.sli_flag & LPFC_SLI_MBOX_ACTIVE) != 0)
4963 		goto finished;
4964 
4965 	stat = 1;
4966 
4967 finished:
4968 	spin_unlock_irq(shost->host_lock);
4969 	return stat;
4970 }
4971 
4972 static void lpfc_host_supported_speeds_set(struct Scsi_Host *shost)
4973 {
4974 	struct lpfc_vport *vport = (struct lpfc_vport *)shost->hostdata;
4975 	struct lpfc_hba   *phba = vport->phba;
4976 
4977 	fc_host_supported_speeds(shost) = 0;
4978 	/*
4979 	 * Avoid reporting supported link speed for FCoE as it can't be
4980 	 * controlled via FCoE.
4981 	 */
4982 	if (test_bit(HBA_FCOE_MODE, &phba->hba_flag))
4983 		return;
4984 
4985 	if (phba->lmt & LMT_256Gb)
4986 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_256GBIT;
4987 	if (phba->lmt & LMT_128Gb)
4988 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_128GBIT;
4989 	if (phba->lmt & LMT_64Gb)
4990 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_64GBIT;
4991 	if (phba->lmt & LMT_32Gb)
4992 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_32GBIT;
4993 	if (phba->lmt & LMT_16Gb)
4994 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_16GBIT;
4995 	if (phba->lmt & LMT_10Gb)
4996 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_10GBIT;
4997 	if (phba->lmt & LMT_8Gb)
4998 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_8GBIT;
4999 	if (phba->lmt & LMT_4Gb)
5000 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_4GBIT;
5001 	if (phba->lmt & LMT_2Gb)
5002 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_2GBIT;
5003 	if (phba->lmt & LMT_1Gb)
5004 		fc_host_supported_speeds(shost) |= FC_PORTSPEED_1GBIT;
5005 }
5006 
5007 /**
5008  * lpfc_host_attrib_init - Initialize SCSI host attributes on a FC port
5009  * @shost: pointer to SCSI host data structure.
5010  *
5011  * This routine initializes a given SCSI host attributes on a FC port. The
5012  * SCSI host can be either on top of a physical port or a virtual port.
5013  **/
5014 void lpfc_host_attrib_init(struct Scsi_Host *shost)
5015 {
5016 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
5017 	struct lpfc_hba   *phba = vport->phba;
5018 	/*
5019 	 * Set fixed host attributes.  Must done after lpfc_sli_hba_setup().
5020 	 */
5021 
5022 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
5023 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
5024 	fc_host_supported_classes(shost) = FC_COS_CLASS3;
5025 
5026 	memset(fc_host_supported_fc4s(shost), 0,
5027 	       sizeof(fc_host_supported_fc4s(shost)));
5028 	fc_host_supported_fc4s(shost)[2] = 1;
5029 	fc_host_supported_fc4s(shost)[7] = 1;
5030 
5031 	lpfc_vport_symbolic_node_name(vport, fc_host_symbolic_name(shost),
5032 				 sizeof fc_host_symbolic_name(shost));
5033 
5034 	lpfc_host_supported_speeds_set(shost);
5035 
5036 	fc_host_maxframe_size(shost) =
5037 		(((uint32_t) vport->fc_sparam.cmn.bbRcvSizeMsb & 0x0F) << 8) |
5038 		(uint32_t) vport->fc_sparam.cmn.bbRcvSizeLsb;
5039 
5040 	fc_host_dev_loss_tmo(shost) = vport->cfg_devloss_tmo;
5041 
5042 	/* This value is also unchanging */
5043 	memset(fc_host_active_fc4s(shost), 0,
5044 	       sizeof(fc_host_active_fc4s(shost)));
5045 	fc_host_active_fc4s(shost)[2] = 1;
5046 	fc_host_active_fc4s(shost)[7] = 1;
5047 
5048 	fc_host_max_npiv_vports(shost) = phba->max_vpi;
5049 	clear_bit(FC_LOADING, &vport->load_flag);
5050 }
5051 
5052 /**
5053  * lpfc_stop_port_s3 - Stop SLI3 device port
5054  * @phba: pointer to lpfc hba data structure.
5055  *
5056  * This routine is invoked to stop an SLI3 device port, it stops the device
5057  * from generating interrupts and stops the device driver's timers for the
5058  * device.
5059  **/
5060 static void
5061 lpfc_stop_port_s3(struct lpfc_hba *phba)
5062 {
5063 	/* Clear all interrupt enable conditions */
5064 	writel(0, phba->HCregaddr);
5065 	readl(phba->HCregaddr); /* flush */
5066 	/* Clear all pending interrupts */
5067 	writel(0xffffffff, phba->HAregaddr);
5068 	readl(phba->HAregaddr); /* flush */
5069 
5070 	/* Reset some HBA SLI setup states */
5071 	lpfc_stop_hba_timers(phba);
5072 	phba->pport->work_port_events = 0;
5073 }
5074 
5075 /**
5076  * lpfc_stop_port_s4 - Stop SLI4 device port
5077  * @phba: pointer to lpfc hba data structure.
5078  *
5079  * This routine is invoked to stop an SLI4 device port, it stops the device
5080  * from generating interrupts and stops the device driver's timers for the
5081  * device.
5082  **/
5083 static void
5084 lpfc_stop_port_s4(struct lpfc_hba *phba)
5085 {
5086 	/* Reset some HBA SLI4 setup states */
5087 	lpfc_stop_hba_timers(phba);
5088 	if (phba->pport)
5089 		phba->pport->work_port_events = 0;
5090 	phba->sli4_hba.intr_enable = 0;
5091 }
5092 
5093 /**
5094  * lpfc_stop_port - Wrapper function for stopping hba port
5095  * @phba: Pointer to HBA context object.
5096  *
5097  * This routine wraps the actual SLI3 or SLI4 hba stop port routine from
5098  * the API jump table function pointer from the lpfc_hba struct.
5099  **/
5100 void
5101 lpfc_stop_port(struct lpfc_hba *phba)
5102 {
5103 	phba->lpfc_stop_port(phba);
5104 
5105 	if (phba->wq)
5106 		flush_workqueue(phba->wq);
5107 }
5108 
5109 /**
5110  * lpfc_fcf_redisc_wait_start_timer - Start fcf rediscover wait timer
5111  * @phba: Pointer to hba for which this call is being executed.
5112  *
5113  * This routine starts the timer waiting for the FCF rediscovery to complete.
5114  **/
5115 void
5116 lpfc_fcf_redisc_wait_start_timer(struct lpfc_hba *phba)
5117 {
5118 	unsigned long fcf_redisc_wait_tmo =
5119 		(jiffies + msecs_to_jiffies(LPFC_FCF_REDISCOVER_WAIT_TMO));
5120 	/* Start fcf rediscovery wait period timer */
5121 	mod_timer(&phba->fcf.redisc_wait, fcf_redisc_wait_tmo);
5122 	spin_lock_irq(&phba->hbalock);
5123 	/* Allow action to new fcf asynchronous event */
5124 	phba->fcf.fcf_flag &= ~(FCF_AVAILABLE | FCF_SCAN_DONE);
5125 	/* Mark the FCF rediscovery pending state */
5126 	phba->fcf.fcf_flag |= FCF_REDISC_PEND;
5127 	spin_unlock_irq(&phba->hbalock);
5128 }
5129 
5130 /**
5131  * lpfc_sli4_fcf_redisc_wait_tmo - FCF table rediscover wait timeout
5132  * @t: Timer context used to obtain the pointer to lpfc hba data structure.
5133  *
5134  * This routine is invoked when waiting for FCF table rediscover has been
5135  * timed out. If new FCF record(s) has (have) been discovered during the
5136  * wait period, a new FCF event shall be added to the FCOE async event
5137  * list, and then worker thread shall be waked up for processing from the
5138  * worker thread context.
5139  **/
5140 static void
5141 lpfc_sli4_fcf_redisc_wait_tmo(struct timer_list *t)
5142 {
5143 	struct lpfc_hba *phba = timer_container_of(phba, t, fcf.redisc_wait);
5144 
5145 	/* Don't send FCF rediscovery event if timer cancelled */
5146 	spin_lock_irq(&phba->hbalock);
5147 	if (!(phba->fcf.fcf_flag & FCF_REDISC_PEND)) {
5148 		spin_unlock_irq(&phba->hbalock);
5149 		return;
5150 	}
5151 	/* Clear FCF rediscovery timer pending flag */
5152 	phba->fcf.fcf_flag &= ~FCF_REDISC_PEND;
5153 	/* FCF rediscovery event to worker thread */
5154 	phba->fcf.fcf_flag |= FCF_REDISC_EVT;
5155 	spin_unlock_irq(&phba->hbalock);
5156 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
5157 			"2776 FCF rediscover quiescent timer expired\n");
5158 	/* wake up worker thread */
5159 	lpfc_worker_wake_up(phba);
5160 }
5161 
5162 /**
5163  * lpfc_vmid_poll - VMID timeout detection
5164  * @t: Timer context used to obtain the pointer to lpfc hba data structure.
5165  *
5166  * This routine is invoked when there is no I/O on by a VM for the specified
5167  * amount of time. When this situation is detected, the VMID has to be
5168  * deregistered from the switch and all the local resources freed. The VMID
5169  * will be reassigned to the VM once the I/O begins.
5170  **/
5171 static void
5172 lpfc_vmid_poll(struct timer_list *t)
5173 {
5174 	struct lpfc_hba *phba = timer_container_of(phba, t,
5175 						   inactive_vmid_poll);
5176 	u32 wake_up = 0;
5177 
5178 	/* check if there is a need to issue QFPA */
5179 	if (phba->pport->vmid_priority_tagging) {
5180 		wake_up = 1;
5181 		phba->pport->work_port_events |= WORKER_CHECK_VMID_ISSUE_QFPA;
5182 	}
5183 
5184 	/* Is the vmid inactivity timer enabled */
5185 	if (phba->pport->vmid_inactivity_timeout ||
5186 	    test_bit(FC_DEREGISTER_ALL_APP_ID, &phba->pport->load_flag)) {
5187 		wake_up = 1;
5188 		phba->pport->work_port_events |= WORKER_CHECK_INACTIVE_VMID;
5189 	}
5190 
5191 	if (wake_up)
5192 		lpfc_worker_wake_up(phba);
5193 
5194 	/* restart the timer for the next iteration */
5195 	mod_timer(&phba->inactive_vmid_poll,
5196 		  jiffies + secs_to_jiffies(LPFC_VMID_TIMER));
5197 }
5198 
5199 /**
5200  * lpfc_sli4_parse_latt_fault - Parse sli4 link-attention link fault code
5201  * @phba: pointer to lpfc hba data structure.
5202  * @acqe_link: pointer to the async link completion queue entry.
5203  *
5204  * This routine is to parse the SLI4 link-attention link fault code.
5205  **/
5206 static void
5207 lpfc_sli4_parse_latt_fault(struct lpfc_hba *phba,
5208 			   struct lpfc_acqe_link *acqe_link)
5209 {
5210 	switch (bf_get(lpfc_acqe_fc_la_att_type, acqe_link)) {
5211 	case LPFC_FC_LA_TYPE_LINK_DOWN:
5212 	case LPFC_FC_LA_TYPE_TRUNKING_EVENT:
5213 	case LPFC_FC_LA_TYPE_ACTIVATE_FAIL:
5214 	case LPFC_FC_LA_TYPE_LINK_RESET_PRTCL_EVT:
5215 		break;
5216 	default:
5217 		switch (bf_get(lpfc_acqe_link_fault, acqe_link)) {
5218 		case LPFC_ASYNC_LINK_FAULT_NONE:
5219 		case LPFC_ASYNC_LINK_FAULT_LOCAL:
5220 		case LPFC_ASYNC_LINK_FAULT_REMOTE:
5221 		case LPFC_ASYNC_LINK_FAULT_LR_LRR:
5222 			break;
5223 		default:
5224 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5225 					"0398 Unknown link fault code: x%x\n",
5226 					bf_get(lpfc_acqe_link_fault, acqe_link));
5227 			break;
5228 		}
5229 		break;
5230 	}
5231 }
5232 
5233 /**
5234  * lpfc_sli4_parse_latt_type - Parse sli4 link attention type
5235  * @phba: pointer to lpfc hba data structure.
5236  * @acqe_link: pointer to the async link completion queue entry.
5237  *
5238  * This routine is to parse the SLI4 link attention type and translate it
5239  * into the base driver's link attention type coding.
5240  *
5241  * Return: Link attention type in terms of base driver's coding.
5242  **/
5243 static uint8_t
5244 lpfc_sli4_parse_latt_type(struct lpfc_hba *phba,
5245 			  struct lpfc_acqe_link *acqe_link)
5246 {
5247 	uint8_t att_type;
5248 
5249 	switch (bf_get(lpfc_acqe_link_status, acqe_link)) {
5250 	case LPFC_ASYNC_LINK_STATUS_DOWN:
5251 	case LPFC_ASYNC_LINK_STATUS_LOGICAL_DOWN:
5252 		att_type = LPFC_ATT_LINK_DOWN;
5253 		break;
5254 	case LPFC_ASYNC_LINK_STATUS_UP:
5255 		/* Ignore physical link up events - wait for logical link up */
5256 		att_type = LPFC_ATT_RESERVED;
5257 		break;
5258 	case LPFC_ASYNC_LINK_STATUS_LOGICAL_UP:
5259 		att_type = LPFC_ATT_LINK_UP;
5260 		break;
5261 	default:
5262 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5263 				"0399 Invalid link attention type: x%x\n",
5264 				bf_get(lpfc_acqe_link_status, acqe_link));
5265 		att_type = LPFC_ATT_RESERVED;
5266 		break;
5267 	}
5268 	return att_type;
5269 }
5270 
5271 /**
5272  * lpfc_sli_port_speed_get - Get sli3 link speed code to link speed
5273  * @phba: pointer to lpfc hba data structure.
5274  *
5275  * This routine is to get an SLI3 FC port's link speed in Mbps.
5276  *
5277  * Return: link speed in terms of Mbps.
5278  **/
5279 uint32_t
5280 lpfc_sli_port_speed_get(struct lpfc_hba *phba)
5281 {
5282 	uint32_t link_speed;
5283 
5284 	if (!lpfc_is_link_up(phba))
5285 		return 0;
5286 
5287 	if (phba->sli_rev <= LPFC_SLI_REV3) {
5288 		switch (phba->fc_linkspeed) {
5289 		case LPFC_LINK_SPEED_1GHZ:
5290 			link_speed = 1000;
5291 			break;
5292 		case LPFC_LINK_SPEED_2GHZ:
5293 			link_speed = 2000;
5294 			break;
5295 		case LPFC_LINK_SPEED_4GHZ:
5296 			link_speed = 4000;
5297 			break;
5298 		case LPFC_LINK_SPEED_8GHZ:
5299 			link_speed = 8000;
5300 			break;
5301 		case LPFC_LINK_SPEED_10GHZ:
5302 			link_speed = 10000;
5303 			break;
5304 		case LPFC_LINK_SPEED_16GHZ:
5305 			link_speed = 16000;
5306 			break;
5307 		default:
5308 			link_speed = 0;
5309 		}
5310 	} else {
5311 		if (phba->sli4_hba.link_state.logical_speed)
5312 			link_speed =
5313 			      phba->sli4_hba.link_state.logical_speed;
5314 		else
5315 			link_speed = phba->sli4_hba.link_state.speed;
5316 	}
5317 	return link_speed;
5318 }
5319 
5320 /**
5321  * lpfc_sli4_port_speed_parse - Parse async evt link speed code to link speed
5322  * @phba: pointer to lpfc hba data structure.
5323  * @evt_code: asynchronous event code.
5324  * @speed_code: asynchronous event link speed code.
5325  *
5326  * This routine is to parse the giving SLI4 async event link speed code into
5327  * value of Mbps for the link speed.
5328  *
5329  * Return: link speed in terms of Mbps.
5330  **/
5331 static uint32_t
5332 lpfc_sli4_port_speed_parse(struct lpfc_hba *phba, uint32_t evt_code,
5333 			   uint8_t speed_code)
5334 {
5335 	uint32_t port_speed;
5336 
5337 	switch (evt_code) {
5338 	case LPFC_TRAILER_CODE_LINK:
5339 		switch (speed_code) {
5340 		case LPFC_ASYNC_LINK_SPEED_ZERO:
5341 			port_speed = 0;
5342 			break;
5343 		case LPFC_ASYNC_LINK_SPEED_10MBPS:
5344 			port_speed = 10;
5345 			break;
5346 		case LPFC_ASYNC_LINK_SPEED_100MBPS:
5347 			port_speed = 100;
5348 			break;
5349 		case LPFC_ASYNC_LINK_SPEED_1GBPS:
5350 			port_speed = 1000;
5351 			break;
5352 		case LPFC_ASYNC_LINK_SPEED_10GBPS:
5353 			port_speed = 10000;
5354 			break;
5355 		case LPFC_ASYNC_LINK_SPEED_20GBPS:
5356 			port_speed = 20000;
5357 			break;
5358 		case LPFC_ASYNC_LINK_SPEED_25GBPS:
5359 			port_speed = 25000;
5360 			break;
5361 		case LPFC_ASYNC_LINK_SPEED_40GBPS:
5362 			port_speed = 40000;
5363 			break;
5364 		case LPFC_ASYNC_LINK_SPEED_100GBPS:
5365 			port_speed = 100000;
5366 			break;
5367 		default:
5368 			port_speed = 0;
5369 		}
5370 		break;
5371 	case LPFC_TRAILER_CODE_FC:
5372 		switch (speed_code) {
5373 		case LPFC_FC_LA_SPEED_UNKNOWN:
5374 			port_speed = 0;
5375 			break;
5376 		case LPFC_FC_LA_SPEED_1G:
5377 			port_speed = 1000;
5378 			break;
5379 		case LPFC_FC_LA_SPEED_2G:
5380 			port_speed = 2000;
5381 			break;
5382 		case LPFC_FC_LA_SPEED_4G:
5383 			port_speed = 4000;
5384 			break;
5385 		case LPFC_FC_LA_SPEED_8G:
5386 			port_speed = 8000;
5387 			break;
5388 		case LPFC_FC_LA_SPEED_10G:
5389 			port_speed = 10000;
5390 			break;
5391 		case LPFC_FC_LA_SPEED_16G:
5392 			port_speed = 16000;
5393 			break;
5394 		case LPFC_FC_LA_SPEED_32G:
5395 			port_speed = 32000;
5396 			break;
5397 		case LPFC_FC_LA_SPEED_64G:
5398 			port_speed = 64000;
5399 			break;
5400 		case LPFC_FC_LA_SPEED_128G:
5401 			port_speed = 128000;
5402 			break;
5403 		case LPFC_FC_LA_SPEED_256G:
5404 			port_speed = 256000;
5405 			break;
5406 		default:
5407 			port_speed = 0;
5408 		}
5409 		break;
5410 	default:
5411 		port_speed = 0;
5412 	}
5413 	return port_speed;
5414 }
5415 
5416 /**
5417  * lpfc_sli4_async_link_evt - Process the asynchronous FCoE link event
5418  * @phba: pointer to lpfc hba data structure.
5419  * @acqe_link: pointer to the async link completion queue entry.
5420  *
5421  * This routine is to handle the SLI4 asynchronous FCoE link event.
5422  **/
5423 static void
5424 lpfc_sli4_async_link_evt(struct lpfc_hba *phba,
5425 			 struct lpfc_acqe_link *acqe_link)
5426 {
5427 	LPFC_MBOXQ_t *pmb;
5428 	MAILBOX_t *mb;
5429 	struct lpfc_mbx_read_top *la;
5430 	uint8_t att_type;
5431 	int rc;
5432 
5433 	att_type = lpfc_sli4_parse_latt_type(phba, acqe_link);
5434 	if (att_type != LPFC_ATT_LINK_DOWN && att_type != LPFC_ATT_LINK_UP)
5435 		return;
5436 	phba->fcoe_eventtag = acqe_link->event_tag;
5437 	pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5438 	if (!pmb) {
5439 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5440 				"0395 The mboxq allocation failed\n");
5441 		return;
5442 	}
5443 
5444 	rc = lpfc_mbox_rsrc_prep(phba, pmb);
5445 	if (rc) {
5446 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5447 				"0396 mailbox allocation failed\n");
5448 		goto out_free_pmb;
5449 	}
5450 
5451 	/* Cleanup any outstanding ELS commands */
5452 	lpfc_els_flush_all_cmd(phba);
5453 
5454 	/* Block ELS IOCBs until we have done process link event */
5455 	phba->sli4_hba.els_wq->pring->flag |= LPFC_STOP_IOCB_EVENT;
5456 
5457 	/* Update link event statistics */
5458 	phba->sli.slistat.link_event++;
5459 
5460 	/* Create lpfc_handle_latt mailbox command from link ACQE */
5461 	lpfc_read_topology(phba, pmb, pmb->ctx_buf);
5462 	pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
5463 	pmb->vport = phba->pport;
5464 
5465 	/* Keep the link status for extra SLI4 state machine reference */
5466 	phba->sli4_hba.link_state.speed =
5467 			lpfc_sli4_port_speed_parse(phba, LPFC_TRAILER_CODE_LINK,
5468 				bf_get(lpfc_acqe_link_speed, acqe_link));
5469 	phba->sli4_hba.link_state.duplex =
5470 				bf_get(lpfc_acqe_link_duplex, acqe_link);
5471 	phba->sli4_hba.link_state.status =
5472 				bf_get(lpfc_acqe_link_status, acqe_link);
5473 	phba->sli4_hba.link_state.type =
5474 				bf_get(lpfc_acqe_link_type, acqe_link);
5475 	phba->sli4_hba.link_state.number =
5476 				bf_get(lpfc_acqe_link_number, acqe_link);
5477 	phba->sli4_hba.link_state.fault =
5478 				bf_get(lpfc_acqe_link_fault, acqe_link);
5479 	phba->sli4_hba.link_state.logical_speed =
5480 			bf_get(lpfc_acqe_logical_link_speed, acqe_link) * 10;
5481 
5482 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5483 			"2900 Async FC/FCoE Link event - Speed:%dGBit "
5484 			"duplex:x%x LA Type:x%x Port Type:%d Port Number:%d "
5485 			"Logical speed:%dMbps Fault:%d\n",
5486 			phba->sli4_hba.link_state.speed,
5487 			phba->sli4_hba.link_state.topology,
5488 			phba->sli4_hba.link_state.status,
5489 			phba->sli4_hba.link_state.type,
5490 			phba->sli4_hba.link_state.number,
5491 			phba->sli4_hba.link_state.logical_speed,
5492 			phba->sli4_hba.link_state.fault);
5493 	/*
5494 	 * For FC Mode: issue the READ_TOPOLOGY mailbox command to fetch
5495 	 * topology info. Note: Optional for non FC-AL ports.
5496 	 */
5497 	if (!test_bit(HBA_FCOE_MODE, &phba->hba_flag)) {
5498 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
5499 		if (rc == MBX_NOT_FINISHED)
5500 			goto out_free_pmb;
5501 		return;
5502 	}
5503 	/*
5504 	 * For FCoE Mode: fill in all the topology information we need and call
5505 	 * the READ_TOPOLOGY completion routine to continue without actually
5506 	 * sending the READ_TOPOLOGY mailbox command to the port.
5507 	 */
5508 	/* Initialize completion status */
5509 	mb = &pmb->u.mb;
5510 	mb->mbxStatus = MBX_SUCCESS;
5511 
5512 	/* Parse port fault information field */
5513 	lpfc_sli4_parse_latt_fault(phba, acqe_link);
5514 
5515 	/* Parse and translate link attention fields */
5516 	la = (struct lpfc_mbx_read_top *) &pmb->u.mb.un.varReadTop;
5517 	la->eventTag = acqe_link->event_tag;
5518 	bf_set(lpfc_mbx_read_top_att_type, la, att_type);
5519 	bf_set(lpfc_mbx_read_top_link_spd, la,
5520 	       (bf_get(lpfc_acqe_link_speed, acqe_link)));
5521 
5522 	/* Fake the following irrelevant fields */
5523 	bf_set(lpfc_mbx_read_top_topology, la, LPFC_TOPOLOGY_PT_PT);
5524 	bf_set(lpfc_mbx_read_top_alpa_granted, la, 0);
5525 	bf_set(lpfc_mbx_read_top_il, la, 0);
5526 	bf_set(lpfc_mbx_read_top_pb, la, 0);
5527 	bf_set(lpfc_mbx_read_top_fa, la, 0);
5528 	bf_set(lpfc_mbx_read_top_mm, la, 0);
5529 
5530 	/* Invoke the lpfc_handle_latt mailbox command callback function */
5531 	lpfc_mbx_cmpl_read_topology(phba, pmb);
5532 
5533 	return;
5534 
5535 out_free_pmb:
5536 	lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
5537 }
5538 
5539 /**
5540  * lpfc_async_link_speed_to_read_top - Parse async evt link speed code to read
5541  * topology.
5542  * @phba: pointer to lpfc hba data structure.
5543  * @speed_code: asynchronous event link speed code.
5544  *
5545  * This routine is to parse the giving SLI4 async event link speed code into
5546  * value of Read topology link speed.
5547  *
5548  * Return: link speed in terms of Read topology.
5549  **/
5550 static uint8_t
5551 lpfc_async_link_speed_to_read_top(struct lpfc_hba *phba, uint8_t speed_code)
5552 {
5553 	uint8_t port_speed;
5554 
5555 	switch (speed_code) {
5556 	case LPFC_FC_LA_SPEED_1G:
5557 		port_speed = LPFC_LINK_SPEED_1GHZ;
5558 		break;
5559 	case LPFC_FC_LA_SPEED_2G:
5560 		port_speed = LPFC_LINK_SPEED_2GHZ;
5561 		break;
5562 	case LPFC_FC_LA_SPEED_4G:
5563 		port_speed = LPFC_LINK_SPEED_4GHZ;
5564 		break;
5565 	case LPFC_FC_LA_SPEED_8G:
5566 		port_speed = LPFC_LINK_SPEED_8GHZ;
5567 		break;
5568 	case LPFC_FC_LA_SPEED_16G:
5569 		port_speed = LPFC_LINK_SPEED_16GHZ;
5570 		break;
5571 	case LPFC_FC_LA_SPEED_32G:
5572 		port_speed = LPFC_LINK_SPEED_32GHZ;
5573 		break;
5574 	case LPFC_FC_LA_SPEED_64G:
5575 		port_speed = LPFC_LINK_SPEED_64GHZ;
5576 		break;
5577 	case LPFC_FC_LA_SPEED_128G:
5578 		port_speed = LPFC_LINK_SPEED_128GHZ;
5579 		break;
5580 	case LPFC_FC_LA_SPEED_256G:
5581 		port_speed = LPFC_LINK_SPEED_256GHZ;
5582 		break;
5583 	default:
5584 		port_speed = 0;
5585 		break;
5586 	}
5587 
5588 	return port_speed;
5589 }
5590 
5591 void
5592 lpfc_cgn_dump_rxmonitor(struct lpfc_hba *phba)
5593 {
5594 	if (!phba->rx_monitor) {
5595 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5596 				"4411 Rx Monitor Info is empty.\n");
5597 	} else {
5598 		lpfc_rx_monitor_report(phba, phba->rx_monitor, NULL, 0,
5599 				       LPFC_MAX_RXMONITOR_DUMP);
5600 	}
5601 }
5602 
5603 /**
5604  * lpfc_cgn_update_stat - Save data into congestion stats buffer
5605  * @phba: pointer to lpfc hba data structure.
5606  * @dtag: FPIN descriptor received
5607  *
5608  * Increment the FPIN received counter/time when it happens.
5609  */
5610 void
5611 lpfc_cgn_update_stat(struct lpfc_hba *phba, uint32_t dtag)
5612 {
5613 	struct lpfc_cgn_info *cp;
5614 	u32 value;
5615 
5616 	/* Make sure we have a congestion info buffer */
5617 	if (!phba->cgn_i)
5618 		return;
5619 	cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
5620 
5621 	/* Update congestion statistics */
5622 	switch (dtag) {
5623 	case ELS_DTAG_LNK_INTEGRITY:
5624 		le32_add_cpu(&cp->link_integ_notification, 1);
5625 		lpfc_cgn_update_tstamp(phba, &cp->stat_lnk);
5626 		break;
5627 	case ELS_DTAG_DELIVERY:
5628 		le32_add_cpu(&cp->delivery_notification, 1);
5629 		lpfc_cgn_update_tstamp(phba, &cp->stat_delivery);
5630 		break;
5631 	case ELS_DTAG_PEER_CONGEST:
5632 		le32_add_cpu(&cp->cgn_peer_notification, 1);
5633 		lpfc_cgn_update_tstamp(phba, &cp->stat_peer);
5634 		break;
5635 	case ELS_DTAG_CONGESTION:
5636 		le32_add_cpu(&cp->cgn_notification, 1);
5637 		lpfc_cgn_update_tstamp(phba, &cp->stat_fpin);
5638 	}
5639 	if (phba->cgn_fpin_frequency &&
5640 	    phba->cgn_fpin_frequency != LPFC_FPIN_INIT_FREQ) {
5641 		value = LPFC_CGN_TIMER_TO_MIN / phba->cgn_fpin_frequency;
5642 		cp->cgn_stat_npm = value;
5643 	}
5644 
5645 	value = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ);
5646 	cp->cgn_info_crc = cpu_to_le32(value);
5647 }
5648 
5649 /**
5650  * lpfc_cgn_update_tstamp - Update cmf timestamp
5651  * @phba: pointer to lpfc hba data structure.
5652  * @ts: structure to write the timestamp to.
5653  */
5654 void
5655 lpfc_cgn_update_tstamp(struct lpfc_hba *phba, struct lpfc_cgn_ts *ts)
5656 {
5657 	struct timespec64 cur_time;
5658 	struct tm tm_val;
5659 
5660 	ktime_get_real_ts64(&cur_time);
5661 	time64_to_tm(cur_time.tv_sec, 0, &tm_val);
5662 
5663 	ts->month = tm_val.tm_mon + 1;
5664 	ts->day	= tm_val.tm_mday;
5665 	ts->year = tm_val.tm_year - 100;
5666 	ts->hour = tm_val.tm_hour;
5667 	ts->minute = tm_val.tm_min;
5668 	ts->second = tm_val.tm_sec;
5669 
5670 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5671 			"2646 Updated CMF timestamp : "
5672 			"%u/%u/%u %u:%u:%u\n",
5673 			ts->day, ts->month,
5674 			ts->year, ts->hour,
5675 			ts->minute, ts->second);
5676 }
5677 
5678 /**
5679  * lpfc_cmf_stats_timer - Save data into registered congestion buffer
5680  * @timer: Timer cookie to access lpfc private data
5681  *
5682  * Save the congestion event data every minute.
5683  * On the hour collapse all the minute data into hour data. Every day
5684  * collapse all the hour data into daily data. Separate driver
5685  * and fabrc congestion event counters that will be saved out
5686  * to the registered congestion buffer every minute.
5687  */
5688 static enum hrtimer_restart
5689 lpfc_cmf_stats_timer(struct hrtimer *timer)
5690 {
5691 	struct lpfc_hba *phba;
5692 	struct lpfc_cgn_info *cp;
5693 	uint32_t i, index;
5694 	uint16_t value, mvalue;
5695 	uint64_t bps;
5696 	uint32_t mbps;
5697 	uint32_t dvalue, wvalue, lvalue, avalue;
5698 	uint64_t latsum;
5699 	__le16 *ptr;
5700 	__le32 *lptr;
5701 	__le16 *mptr;
5702 
5703 	phba = container_of(timer, struct lpfc_hba, cmf_stats_timer);
5704 	/* Make sure we have a congestion info buffer */
5705 	if (!phba->cgn_i)
5706 		return HRTIMER_NORESTART;
5707 	cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
5708 
5709 	phba->cgn_evt_timestamp = jiffies +
5710 			msecs_to_jiffies(LPFC_CGN_TIMER_TO_MIN);
5711 	phba->cgn_evt_minute++;
5712 
5713 	/* We should get to this point in the routine on 1 minute intervals */
5714 	lpfc_cgn_update_tstamp(phba, &cp->base_time);
5715 
5716 	if (phba->cgn_fpin_frequency &&
5717 	    phba->cgn_fpin_frequency != LPFC_FPIN_INIT_FREQ) {
5718 		value = LPFC_CGN_TIMER_TO_MIN / phba->cgn_fpin_frequency;
5719 		cp->cgn_stat_npm = value;
5720 	}
5721 
5722 	/* Read and clear the latency counters for this minute */
5723 	lvalue = atomic_read(&phba->cgn_latency_evt_cnt);
5724 	latsum = atomic64_read(&phba->cgn_latency_evt);
5725 	atomic_set(&phba->cgn_latency_evt_cnt, 0);
5726 	atomic64_set(&phba->cgn_latency_evt, 0);
5727 
5728 	/* We need to store MB/sec bandwidth in the congestion information.
5729 	 * block_cnt is count of 512 byte blocks for the entire minute,
5730 	 * bps will get bytes per sec before finally converting to MB/sec.
5731 	 */
5732 	bps = div_u64(phba->rx_block_cnt, LPFC_SEC_MIN) * 512;
5733 	phba->rx_block_cnt = 0;
5734 	mvalue = bps / (1024 * 1024); /* convert to MB/sec */
5735 
5736 	/* Every minute */
5737 	/* cgn parameters */
5738 	cp->cgn_info_mode = phba->cgn_p.cgn_param_mode;
5739 	cp->cgn_info_level0 = phba->cgn_p.cgn_param_level0;
5740 	cp->cgn_info_level1 = phba->cgn_p.cgn_param_level1;
5741 	cp->cgn_info_level2 = phba->cgn_p.cgn_param_level2;
5742 
5743 	/* Fill in default LUN qdepth */
5744 	value = (uint16_t)(phba->pport->cfg_lun_queue_depth);
5745 	cp->cgn_lunq = cpu_to_le16(value);
5746 
5747 	/* Record congestion buffer info - every minute
5748 	 * cgn_driver_evt_cnt (Driver events)
5749 	 * cgn_fabric_warn_cnt (Congestion Warnings)
5750 	 * cgn_latency_evt_cnt / cgn_latency_evt (IO Latency)
5751 	 * cgn_fabric_alarm_cnt (Congestion Alarms)
5752 	 */
5753 	index = ++cp->cgn_index_minute;
5754 	if (cp->cgn_index_minute == LPFC_MIN_HOUR) {
5755 		cp->cgn_index_minute = 0;
5756 		index = 0;
5757 	}
5758 
5759 	/* Get the number of driver events in this sample and reset counter */
5760 	dvalue = atomic_read(&phba->cgn_driver_evt_cnt);
5761 	atomic_set(&phba->cgn_driver_evt_cnt, 0);
5762 
5763 	/* Get the number of warning events - FPIN and Signal for this minute */
5764 	wvalue = 0;
5765 	if ((phba->cgn_reg_fpin & LPFC_CGN_FPIN_WARN) ||
5766 	    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY ||
5767 	    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM)
5768 		wvalue = atomic_read(&phba->cgn_fabric_warn_cnt);
5769 	atomic_set(&phba->cgn_fabric_warn_cnt, 0);
5770 
5771 	/* Get the number of alarm events - FPIN and Signal for this minute */
5772 	avalue = 0;
5773 	if ((phba->cgn_reg_fpin & LPFC_CGN_FPIN_ALARM) ||
5774 	    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM)
5775 		avalue = atomic_read(&phba->cgn_fabric_alarm_cnt);
5776 	atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
5777 
5778 	/* Collect the driver, warning, alarm and latency counts for this
5779 	 * minute into the driver congestion buffer.
5780 	 */
5781 	ptr = &cp->cgn_drvr_min[index];
5782 	value = (uint16_t)dvalue;
5783 	*ptr = cpu_to_le16(value);
5784 
5785 	ptr = &cp->cgn_warn_min[index];
5786 	value = (uint16_t)wvalue;
5787 	*ptr = cpu_to_le16(value);
5788 
5789 	ptr = &cp->cgn_alarm_min[index];
5790 	value = (uint16_t)avalue;
5791 	*ptr = cpu_to_le16(value);
5792 
5793 	lptr = &cp->cgn_latency_min[index];
5794 	if (lvalue) {
5795 		lvalue = (uint32_t)div_u64(latsum, lvalue);
5796 		*lptr = cpu_to_le32(lvalue);
5797 	} else {
5798 		*lptr = 0;
5799 	}
5800 
5801 	/* Collect the bandwidth value into the driver's congesion buffer. */
5802 	mptr = &cp->cgn_bw_min[index];
5803 	*mptr = cpu_to_le16(mvalue);
5804 
5805 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5806 			"2418 Congestion Info - minute (%d): %d %d %d %d %d\n",
5807 			index, dvalue, wvalue, *lptr, mvalue, avalue);
5808 
5809 	/* Every hour */
5810 	if ((phba->cgn_evt_minute % LPFC_MIN_HOUR) == 0) {
5811 		/* Record congestion buffer info - every hour
5812 		 * Collapse all minutes into an hour
5813 		 */
5814 		index = ++cp->cgn_index_hour;
5815 		if (cp->cgn_index_hour == LPFC_HOUR_DAY) {
5816 			cp->cgn_index_hour = 0;
5817 			index = 0;
5818 		}
5819 
5820 		dvalue = 0;
5821 		wvalue = 0;
5822 		lvalue = 0;
5823 		avalue = 0;
5824 		mvalue = 0;
5825 		mbps = 0;
5826 		for (i = 0; i < LPFC_MIN_HOUR; i++) {
5827 			dvalue += le16_to_cpu(cp->cgn_drvr_min[i]);
5828 			wvalue += le16_to_cpu(cp->cgn_warn_min[i]);
5829 			lvalue += le32_to_cpu(cp->cgn_latency_min[i]);
5830 			mbps += le16_to_cpu(cp->cgn_bw_min[i]);
5831 			avalue += le16_to_cpu(cp->cgn_alarm_min[i]);
5832 		}
5833 		if (lvalue)		/* Avg of latency averages */
5834 			lvalue /= LPFC_MIN_HOUR;
5835 		if (mbps)		/* Avg of Bandwidth averages */
5836 			mvalue = mbps / LPFC_MIN_HOUR;
5837 
5838 		lptr = &cp->cgn_drvr_hr[index];
5839 		*lptr = cpu_to_le32(dvalue);
5840 		lptr = &cp->cgn_warn_hr[index];
5841 		*lptr = cpu_to_le32(wvalue);
5842 		lptr = &cp->cgn_latency_hr[index];
5843 		*lptr = cpu_to_le32(lvalue);
5844 		mptr = &cp->cgn_bw_hr[index];
5845 		*mptr = cpu_to_le16(mvalue);
5846 		lptr = &cp->cgn_alarm_hr[index];
5847 		*lptr = cpu_to_le32(avalue);
5848 
5849 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5850 				"2419 Congestion Info - hour "
5851 				"(%d): %d %d %d %d %d\n",
5852 				index, dvalue, wvalue, lvalue, mvalue, avalue);
5853 	}
5854 
5855 	/* Every day */
5856 	if ((phba->cgn_evt_minute % LPFC_MIN_DAY) == 0) {
5857 		/* Record congestion buffer info - every hour
5858 		 * Collapse all hours into a day. Rotate days
5859 		 * after LPFC_MAX_CGN_DAYS.
5860 		 */
5861 		index = ++cp->cgn_index_day;
5862 		if (cp->cgn_index_day == LPFC_MAX_CGN_DAYS) {
5863 			cp->cgn_index_day = 0;
5864 			index = 0;
5865 		}
5866 
5867 		dvalue = 0;
5868 		wvalue = 0;
5869 		lvalue = 0;
5870 		mvalue = 0;
5871 		mbps = 0;
5872 		avalue = 0;
5873 		for (i = 0; i < LPFC_HOUR_DAY; i++) {
5874 			dvalue += le32_to_cpu(cp->cgn_drvr_hr[i]);
5875 			wvalue += le32_to_cpu(cp->cgn_warn_hr[i]);
5876 			lvalue += le32_to_cpu(cp->cgn_latency_hr[i]);
5877 			mbps += le16_to_cpu(cp->cgn_bw_hr[i]);
5878 			avalue += le32_to_cpu(cp->cgn_alarm_hr[i]);
5879 		}
5880 		if (lvalue)		/* Avg of latency averages */
5881 			lvalue /= LPFC_HOUR_DAY;
5882 		if (mbps)		/* Avg of Bandwidth averages */
5883 			mvalue = mbps / LPFC_HOUR_DAY;
5884 
5885 		lptr = &cp->cgn_drvr_day[index];
5886 		*lptr = cpu_to_le32(dvalue);
5887 		lptr = &cp->cgn_warn_day[index];
5888 		*lptr = cpu_to_le32(wvalue);
5889 		lptr = &cp->cgn_latency_day[index];
5890 		*lptr = cpu_to_le32(lvalue);
5891 		mptr = &cp->cgn_bw_day[index];
5892 		*mptr = cpu_to_le16(mvalue);
5893 		lptr = &cp->cgn_alarm_day[index];
5894 		*lptr = cpu_to_le32(avalue);
5895 
5896 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5897 				"2420 Congestion Info - daily (%d): "
5898 				"%d %d %d %d %d\n",
5899 				index, dvalue, wvalue, lvalue, mvalue, avalue);
5900 	}
5901 
5902 	/* Use the frequency found in the last rcv'ed FPIN */
5903 	value = phba->cgn_fpin_frequency;
5904 	cp->cgn_warn_freq = cpu_to_le16(value);
5905 	cp->cgn_alarm_freq = cpu_to_le16(value);
5906 
5907 	lvalue = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ);
5908 	cp->cgn_info_crc = cpu_to_le32(lvalue);
5909 
5910 	hrtimer_forward_now(timer, ktime_set(0, LPFC_SEC_MIN * NSEC_PER_SEC));
5911 
5912 	return HRTIMER_RESTART;
5913 }
5914 
5915 /**
5916  * lpfc_calc_cmf_latency - latency from start of rxate timer interval
5917  * @phba: The Hba for which this call is being executed.
5918  *
5919  * The routine calculates the latency from the beginning of the CMF timer
5920  * interval to the current point in time. It is called from IO completion
5921  * when we exceed our Bandwidth limitation for the time interval.
5922  */
5923 uint32_t
5924 lpfc_calc_cmf_latency(struct lpfc_hba *phba)
5925 {
5926 	struct timespec64 cmpl_time;
5927 	uint32_t msec = 0;
5928 
5929 	ktime_get_real_ts64(&cmpl_time);
5930 
5931 	/* This routine works on a ms granularity so sec and usec are
5932 	 * converted accordingly.
5933 	 */
5934 	if (cmpl_time.tv_sec == phba->cmf_latency.tv_sec) {
5935 		msec = (cmpl_time.tv_nsec - phba->cmf_latency.tv_nsec) /
5936 			NSEC_PER_MSEC;
5937 	} else {
5938 		if (cmpl_time.tv_nsec >= phba->cmf_latency.tv_nsec) {
5939 			msec = (cmpl_time.tv_sec -
5940 				phba->cmf_latency.tv_sec) * MSEC_PER_SEC;
5941 			msec += ((cmpl_time.tv_nsec -
5942 				  phba->cmf_latency.tv_nsec) / NSEC_PER_MSEC);
5943 		} else {
5944 			msec = (cmpl_time.tv_sec - phba->cmf_latency.tv_sec -
5945 				1) * MSEC_PER_SEC;
5946 			msec += (((NSEC_PER_SEC - phba->cmf_latency.tv_nsec) +
5947 				 cmpl_time.tv_nsec) / NSEC_PER_MSEC);
5948 		}
5949 	}
5950 	return msec;
5951 }
5952 
5953 /**
5954  * lpfc_cmf_timer -  This is the timer function for one congestion
5955  * rate interval.
5956  * @timer: Pointer to the high resolution timer that expired
5957  */
5958 static enum hrtimer_restart
5959 lpfc_cmf_timer(struct hrtimer *timer)
5960 {
5961 	struct lpfc_hba *phba = container_of(timer, struct lpfc_hba,
5962 					     cmf_timer);
5963 	struct rx_info_entry entry;
5964 	uint32_t io_cnt;
5965 	uint32_t busy, max_read;
5966 	uint64_t total, rcv, lat, mbpi, extra, cnt;
5967 	int timer_interval = LPFC_CMF_INTERVAL;
5968 	uint32_t ms;
5969 	struct lpfc_cgn_stat *cgs;
5970 	int cpu;
5971 
5972 	/* Only restart the timer if congestion mgmt is on */
5973 	if (phba->cmf_active_mode == LPFC_CFG_OFF ||
5974 	    !phba->cmf_latency.tv_sec) {
5975 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5976 				"6224 CMF timer exit: %d %lld\n",
5977 				phba->cmf_active_mode,
5978 				(uint64_t)phba->cmf_latency.tv_sec);
5979 		return HRTIMER_NORESTART;
5980 	}
5981 
5982 	/* If pport is not ready yet, just exit and wait for
5983 	 * the next timer cycle to hit.
5984 	 */
5985 	if (!phba->pport)
5986 		goto skip;
5987 
5988 	/* Do not block SCSI IO while in the timer routine since
5989 	 * total_bytes will be cleared
5990 	 */
5991 	atomic_set(&phba->cmf_stop_io, 1);
5992 
5993 	/* First we need to calculate the actual ms between
5994 	 * the last timer interrupt and this one. We ask for
5995 	 * LPFC_CMF_INTERVAL, however the actual time may
5996 	 * vary depending on system overhead.
5997 	 */
5998 	ms = lpfc_calc_cmf_latency(phba);
5999 
6000 
6001 	/* Immediately after we calculate the time since the last
6002 	 * timer interrupt, set the start time for the next
6003 	 * interrupt
6004 	 */
6005 	ktime_get_real_ts64(&phba->cmf_latency);
6006 
6007 	phba->cmf_link_byte_count =
6008 		div_u64(phba->cmf_max_line_rate * LPFC_CMF_INTERVAL, 1000);
6009 
6010 	/* Collect all the stats from the prior timer interval */
6011 	total = 0;
6012 	io_cnt = 0;
6013 	lat = 0;
6014 	rcv = 0;
6015 	for_each_present_cpu(cpu) {
6016 		cgs = per_cpu_ptr(phba->cmf_stat, cpu);
6017 		total += atomic64_xchg(&cgs->total_bytes, 0);
6018 		io_cnt += atomic_xchg(&cgs->rx_io_cnt, 0);
6019 		lat += atomic64_xchg(&cgs->rx_latency, 0);
6020 		rcv += atomic64_xchg(&cgs->rcv_bytes, 0);
6021 	}
6022 
6023 	/* Before we issue another CMF_SYNC_WQE, retrieve the BW
6024 	 * returned from the last CMF_SYNC_WQE issued, from
6025 	 * cmf_last_sync_bw. This will be the target BW for
6026 	 * this next timer interval.
6027 	 */
6028 	if (phba->cmf_active_mode == LPFC_CFG_MANAGED &&
6029 	    phba->link_state != LPFC_LINK_DOWN &&
6030 	    test_bit(HBA_SETUP, &phba->hba_flag)) {
6031 		mbpi = phba->cmf_last_sync_bw;
6032 		phba->cmf_last_sync_bw = 0;
6033 		extra = 0;
6034 
6035 		/* Calculate any extra bytes needed to account for the
6036 		 * timer accuracy. If we are less than LPFC_CMF_INTERVAL
6037 		 * calculate the adjustment needed for total to reflect
6038 		 * a full LPFC_CMF_INTERVAL.
6039 		 */
6040 		if (ms && ms < LPFC_CMF_INTERVAL) {
6041 			cnt = div_u64(total, ms); /* bytes per ms */
6042 			cnt *= LPFC_CMF_INTERVAL; /* what total should be */
6043 			extra = cnt - total;
6044 		}
6045 		lpfc_issue_cmf_sync_wqe(phba, LPFC_CMF_INTERVAL, total + extra);
6046 	} else {
6047 		/* For Monitor mode or link down we want mbpi
6048 		 * to be the full link speed
6049 		 */
6050 		mbpi = phba->cmf_link_byte_count;
6051 		extra = 0;
6052 	}
6053 	phba->cmf_timer_cnt++;
6054 
6055 	if (io_cnt) {
6056 		/* Update congestion info buffer latency in us */
6057 		atomic_add(io_cnt, &phba->cgn_latency_evt_cnt);
6058 		atomic64_add(lat, &phba->cgn_latency_evt);
6059 	}
6060 	busy = atomic_xchg(&phba->cmf_busy, 0);
6061 	max_read = atomic_xchg(&phba->rx_max_read_cnt, 0);
6062 
6063 	/* Calculate MBPI for the next timer interval */
6064 	if (mbpi) {
6065 		if (mbpi > phba->cmf_link_byte_count ||
6066 		    phba->cmf_active_mode == LPFC_CFG_MONITOR)
6067 			mbpi = phba->cmf_link_byte_count;
6068 
6069 		/* Change max_bytes_per_interval to what the prior
6070 		 * CMF_SYNC_WQE cmpl indicated.
6071 		 */
6072 		if (mbpi != phba->cmf_max_bytes_per_interval)
6073 			phba->cmf_max_bytes_per_interval = mbpi;
6074 	}
6075 
6076 	/* Save rxmonitor information for debug */
6077 	if (phba->rx_monitor) {
6078 		entry.total_bytes = total;
6079 		entry.cmf_bytes = total + extra;
6080 		entry.rcv_bytes = rcv;
6081 		entry.cmf_busy = busy;
6082 		entry.cmf_info = phba->cmf_active_info;
6083 		if (io_cnt) {
6084 			entry.avg_io_latency = div_u64(lat, io_cnt);
6085 			entry.avg_io_size = div_u64(rcv, io_cnt);
6086 		} else {
6087 			entry.avg_io_latency = 0;
6088 			entry.avg_io_size = 0;
6089 		}
6090 		entry.max_read_cnt = max_read;
6091 		entry.io_cnt = io_cnt;
6092 		entry.max_bytes_per_interval = mbpi;
6093 		if (phba->cmf_active_mode == LPFC_CFG_MANAGED)
6094 			entry.timer_utilization = phba->cmf_last_ts;
6095 		else
6096 			entry.timer_utilization = ms;
6097 		entry.timer_interval = ms;
6098 		phba->cmf_last_ts = 0;
6099 
6100 		lpfc_rx_monitor_record(phba->rx_monitor, &entry);
6101 	}
6102 
6103 	if (phba->cmf_active_mode == LPFC_CFG_MONITOR) {
6104 		/* If Monitor mode, check if we are oversubscribed
6105 		 * against the full line rate.
6106 		 */
6107 		if (mbpi && total > mbpi)
6108 			atomic_inc(&phba->cgn_driver_evt_cnt);
6109 	}
6110 	phba->rx_block_cnt += div_u64(rcv, 512);  /* save 512 byte block cnt */
6111 
6112 	/* Since total_bytes has already been zero'ed, its okay to unblock
6113 	 * after max_bytes_per_interval is setup.
6114 	 */
6115 	if (atomic_xchg(&phba->cmf_bw_wait, 0))
6116 		queue_work(phba->wq, &phba->unblock_request_work);
6117 
6118 	/* SCSI IO is now unblocked */
6119 	atomic_set(&phba->cmf_stop_io, 0);
6120 
6121 skip:
6122 	hrtimer_forward_now(timer,
6123 			    ktime_set(0, timer_interval * NSEC_PER_MSEC));
6124 	return HRTIMER_RESTART;
6125 }
6126 
6127 #define trunk_link_status(__idx)\
6128 	bf_get(lpfc_acqe_fc_la_trunk_config_port##__idx, acqe_fc) ?\
6129 	       ((phba->trunk_link.link##__idx.state == LPFC_LINK_UP) ?\
6130 		"Link up" : "Link down") : "NA"
6131 /* Did port __idx reported an error */
6132 #define trunk_port_fault(__idx)\
6133 	bf_get(lpfc_acqe_fc_la_trunk_config_port##__idx, acqe_fc) ?\
6134 	       (port_fault & (1 << __idx) ? "YES" : "NO") : "NA"
6135 
6136 static void
6137 lpfc_update_trunk_link_status(struct lpfc_hba *phba,
6138 			      struct lpfc_acqe_fc_la *acqe_fc)
6139 {
6140 	uint8_t port_fault = bf_get(lpfc_acqe_fc_la_trunk_linkmask, acqe_fc);
6141 	uint8_t err = bf_get(lpfc_acqe_fc_la_trunk_fault, acqe_fc);
6142 	u8 cnt = 0;
6143 
6144 	phba->sli4_hba.link_state.speed =
6145 		lpfc_sli4_port_speed_parse(phba, LPFC_TRAILER_CODE_FC,
6146 				bf_get(lpfc_acqe_fc_la_speed, acqe_fc));
6147 
6148 	phba->sli4_hba.link_state.logical_speed =
6149 				bf_get(lpfc_acqe_fc_la_llink_spd, acqe_fc) * 10;
6150 	/* We got FC link speed, convert to fc_linkspeed (READ_TOPOLOGY) */
6151 	phba->fc_linkspeed =
6152 		 lpfc_async_link_speed_to_read_top(
6153 				phba,
6154 				bf_get(lpfc_acqe_fc_la_speed, acqe_fc));
6155 
6156 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port0, acqe_fc)) {
6157 		phba->trunk_link.link0.state =
6158 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port0, acqe_fc)
6159 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
6160 		phba->trunk_link.link0.fault = port_fault & 0x1 ? err : 0;
6161 		cnt++;
6162 	}
6163 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port1, acqe_fc)) {
6164 		phba->trunk_link.link1.state =
6165 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port1, acqe_fc)
6166 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
6167 		phba->trunk_link.link1.fault = port_fault & 0x2 ? err : 0;
6168 		cnt++;
6169 	}
6170 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port2, acqe_fc)) {
6171 		phba->trunk_link.link2.state =
6172 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port2, acqe_fc)
6173 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
6174 		phba->trunk_link.link2.fault = port_fault & 0x4 ? err : 0;
6175 		cnt++;
6176 	}
6177 	if (bf_get(lpfc_acqe_fc_la_trunk_config_port3, acqe_fc)) {
6178 		phba->trunk_link.link3.state =
6179 			bf_get(lpfc_acqe_fc_la_trunk_link_status_port3, acqe_fc)
6180 			? LPFC_LINK_UP : LPFC_LINK_DOWN;
6181 		phba->trunk_link.link3.fault = port_fault & 0x8 ? err : 0;
6182 		cnt++;
6183 	}
6184 
6185 	if (cnt)
6186 		phba->trunk_link.phy_lnk_speed =
6187 			phba->sli4_hba.link_state.logical_speed / (cnt * 1000);
6188 	else
6189 		phba->trunk_link.phy_lnk_speed = LPFC_LINK_SPEED_UNKNOWN;
6190 
6191 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6192 			"2910 Async FC Trunking Event - Speed:%d\n"
6193 			"\tLogical speed:%d "
6194 			"port0: %s port1: %s port2: %s port3: %s\n",
6195 			phba->sli4_hba.link_state.speed,
6196 			phba->sli4_hba.link_state.logical_speed,
6197 			trunk_link_status(0), trunk_link_status(1),
6198 			trunk_link_status(2), trunk_link_status(3));
6199 
6200 	if (phba->cmf_active_mode != LPFC_CFG_OFF)
6201 		lpfc_cmf_signal_init(phba);
6202 
6203 	if (port_fault)
6204 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6205 				"3202 trunk error:0x%x (%s) seen on port0:%s "
6206 				/*
6207 				 * SLI-4: We have only 0xA error codes
6208 				 * defined as of now. print an appropriate
6209 				 * message in case driver needs to be updated.
6210 				 */
6211 				"port1:%s port2:%s port3:%s\n", err, err > 0xA ?
6212 				"UNDEFINED. update driver." : trunk_errmsg[err],
6213 				trunk_port_fault(0), trunk_port_fault(1),
6214 				trunk_port_fault(2), trunk_port_fault(3));
6215 }
6216 
6217 
6218 /**
6219  * lpfc_sli4_async_fc_evt - Process the asynchronous FC link event
6220  * @phba: pointer to lpfc hba data structure.
6221  * @acqe_fc: pointer to the async fc completion queue entry.
6222  *
6223  * This routine is to handle the SLI4 asynchronous FC event. It will simply log
6224  * that the event was received and then issue a read_topology mailbox command so
6225  * that the rest of the driver will treat it the same as SLI3.
6226  **/
6227 static void
6228 lpfc_sli4_async_fc_evt(struct lpfc_hba *phba, struct lpfc_acqe_fc_la *acqe_fc)
6229 {
6230 	LPFC_MBOXQ_t *pmb;
6231 	MAILBOX_t *mb;
6232 	struct lpfc_mbx_read_top *la;
6233 	char *log_level;
6234 	int rc;
6235 
6236 	if (bf_get(lpfc_trailer_type, acqe_fc) !=
6237 	    LPFC_FC_LA_EVENT_TYPE_FC_LINK) {
6238 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6239 				"2895 Non FC link Event detected.(%d)\n",
6240 				bf_get(lpfc_trailer_type, acqe_fc));
6241 		return;
6242 	}
6243 
6244 	if (bf_get(lpfc_acqe_fc_la_att_type, acqe_fc) ==
6245 	    LPFC_FC_LA_TYPE_TRUNKING_EVENT) {
6246 		lpfc_update_trunk_link_status(phba, acqe_fc);
6247 		return;
6248 	}
6249 
6250 	/* Keep the link status for extra SLI4 state machine reference */
6251 	phba->sli4_hba.link_state.speed =
6252 			lpfc_sli4_port_speed_parse(phba, LPFC_TRAILER_CODE_FC,
6253 				bf_get(lpfc_acqe_fc_la_speed, acqe_fc));
6254 	phba->sli4_hba.link_state.duplex = LPFC_ASYNC_LINK_DUPLEX_FULL;
6255 	phba->sli4_hba.link_state.topology =
6256 				bf_get(lpfc_acqe_fc_la_topology, acqe_fc);
6257 	phba->sli4_hba.link_state.status =
6258 				bf_get(lpfc_acqe_fc_la_att_type, acqe_fc);
6259 	phba->sli4_hba.link_state.type =
6260 				bf_get(lpfc_acqe_fc_la_port_type, acqe_fc);
6261 	phba->sli4_hba.link_state.number =
6262 				bf_get(lpfc_acqe_fc_la_port_number, acqe_fc);
6263 	phba->sli4_hba.link_state.fault =
6264 				bf_get(lpfc_acqe_link_fault, acqe_fc);
6265 	phba->sli4_hba.link_state.link_status =
6266 				bf_get(lpfc_acqe_fc_la_link_status, acqe_fc);
6267 
6268 	/*
6269 	 * Only select attention types need logical speed modification to what
6270 	 * was previously set.
6271 	 */
6272 	if (phba->sli4_hba.link_state.status >= LPFC_FC_LA_TYPE_LINK_UP &&
6273 	    phba->sli4_hba.link_state.status < LPFC_FC_LA_TYPE_ACTIVATE_FAIL) {
6274 		if (bf_get(lpfc_acqe_fc_la_att_type, acqe_fc) ==
6275 		    LPFC_FC_LA_TYPE_LINK_DOWN)
6276 			phba->sli4_hba.link_state.logical_speed = 0;
6277 		else if (!phba->sli4_hba.conf_trunk)
6278 			phba->sli4_hba.link_state.logical_speed =
6279 				bf_get(lpfc_acqe_fc_la_llink_spd, acqe_fc) * 10;
6280 	}
6281 
6282 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6283 			"2896 Async FC event - Speed:%dGBaud Topology:x%x "
6284 			"LA Type:x%x Port Type:%d Port Number:%d Logical speed:"
6285 			"%dMbps Fault:x%x Link Status:x%x\n",
6286 			phba->sli4_hba.link_state.speed,
6287 			phba->sli4_hba.link_state.topology,
6288 			phba->sli4_hba.link_state.status,
6289 			phba->sli4_hba.link_state.type,
6290 			phba->sli4_hba.link_state.number,
6291 			phba->sli4_hba.link_state.logical_speed,
6292 			phba->sli4_hba.link_state.fault,
6293 			phba->sli4_hba.link_state.link_status);
6294 
6295 	/*
6296 	 * The following attention types are informational only, providing
6297 	 * further details about link status.  Overwrite the value of
6298 	 * link_state.status appropriately.  No further action is required.
6299 	 */
6300 	if (phba->sli4_hba.link_state.status >= LPFC_FC_LA_TYPE_ACTIVATE_FAIL) {
6301 		switch (phba->sli4_hba.link_state.status) {
6302 		case LPFC_FC_LA_TYPE_ACTIVATE_FAIL:
6303 			log_level = KERN_WARNING;
6304 			phba->sli4_hba.link_state.status =
6305 					LPFC_FC_LA_TYPE_LINK_DOWN;
6306 			break;
6307 		case LPFC_FC_LA_TYPE_LINK_RESET_PRTCL_EVT:
6308 			/*
6309 			 * During bb credit recovery establishment, receiving
6310 			 * this attention type is normal.  Link Up attention
6311 			 * type is expected to occur before this informational
6312 			 * attention type so keep the Link Up status.
6313 			 */
6314 			log_level = KERN_INFO;
6315 			phba->sli4_hba.link_state.status =
6316 					LPFC_FC_LA_TYPE_LINK_UP;
6317 			break;
6318 		default:
6319 			log_level = KERN_INFO;
6320 			break;
6321 		}
6322 		lpfc_log_msg(phba, log_level, LOG_SLI,
6323 			     "2992 Async FC event - Informational Link "
6324 			     "Attention Type x%x\n",
6325 			     bf_get(lpfc_acqe_fc_la_att_type, acqe_fc));
6326 		return;
6327 	}
6328 
6329 	pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6330 	if (!pmb) {
6331 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6332 				"2897 The mboxq allocation failed\n");
6333 		return;
6334 	}
6335 	rc = lpfc_mbox_rsrc_prep(phba, pmb);
6336 	if (rc) {
6337 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6338 				"2898 The mboxq prep failed\n");
6339 		goto out_free_pmb;
6340 	}
6341 
6342 	/* Cleanup any outstanding ELS commands */
6343 	lpfc_els_flush_all_cmd(phba);
6344 
6345 	/* Block ELS IOCBs until we have done process link event */
6346 	phba->sli4_hba.els_wq->pring->flag |= LPFC_STOP_IOCB_EVENT;
6347 
6348 	/* Update link event statistics */
6349 	phba->sli.slistat.link_event++;
6350 
6351 	/* Create lpfc_handle_latt mailbox command from link ACQE */
6352 	lpfc_read_topology(phba, pmb, pmb->ctx_buf);
6353 	pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
6354 	pmb->vport = phba->pport;
6355 
6356 	if (phba->sli4_hba.link_state.status != LPFC_FC_LA_TYPE_LINK_UP) {
6357 		phba->link_flag &= ~(LS_MDS_LINK_DOWN | LS_MDS_LOOPBACK);
6358 
6359 		switch (phba->sli4_hba.link_state.status) {
6360 		case LPFC_FC_LA_TYPE_MDS_LINK_DOWN:
6361 			phba->link_flag |= LS_MDS_LINK_DOWN;
6362 			break;
6363 		case LPFC_FC_LA_TYPE_MDS_LOOPBACK:
6364 			phba->link_flag |= LS_MDS_LOOPBACK;
6365 			break;
6366 		default:
6367 			break;
6368 		}
6369 
6370 		/* Initialize completion status */
6371 		mb = &pmb->u.mb;
6372 		mb->mbxStatus = MBX_SUCCESS;
6373 
6374 		/* Parse port fault information field */
6375 		lpfc_sli4_parse_latt_fault(phba, (void *)acqe_fc);
6376 
6377 		/* Parse and translate link attention fields */
6378 		la = (struct lpfc_mbx_read_top *)&pmb->u.mb.un.varReadTop;
6379 		la->eventTag = acqe_fc->event_tag;
6380 
6381 		if (phba->sli4_hba.link_state.status ==
6382 		    LPFC_FC_LA_TYPE_UNEXP_WWPN) {
6383 			bf_set(lpfc_mbx_read_top_att_type, la,
6384 			       LPFC_FC_LA_TYPE_UNEXP_WWPN);
6385 		} else {
6386 			bf_set(lpfc_mbx_read_top_att_type, la,
6387 			       LPFC_FC_LA_TYPE_LINK_DOWN);
6388 		}
6389 		/* Invoke the mailbox command callback function */
6390 		lpfc_mbx_cmpl_read_topology(phba, pmb);
6391 
6392 		return;
6393 	}
6394 
6395 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
6396 	if (rc == MBX_NOT_FINISHED)
6397 		goto out_free_pmb;
6398 	return;
6399 
6400 out_free_pmb:
6401 	lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
6402 }
6403 
6404 /**
6405  * lpfc_sli4_async_sli_evt - Process the asynchronous SLI link event
6406  * @phba: pointer to lpfc hba data structure.
6407  * @acqe_sli: pointer to the async SLI completion queue entry.
6408  *
6409  * This routine is to handle the SLI4 asynchronous SLI events.
6410  **/
6411 static void
6412 lpfc_sli4_async_sli_evt(struct lpfc_hba *phba, struct lpfc_acqe_sli *acqe_sli)
6413 {
6414 	char port_name;
6415 	char message[128];
6416 	uint8_t status;
6417 	uint8_t evt_type;
6418 	uint8_t operational = 0;
6419 	struct temp_event temp_event_data;
6420 	struct lpfc_acqe_misconfigured_event *misconfigured;
6421 	struct lpfc_acqe_cgn_signal *cgn_signal;
6422 	struct Scsi_Host  *shost;
6423 	struct lpfc_vport **vports;
6424 	int rc, i, cnt;
6425 
6426 	evt_type = bf_get(lpfc_trailer_type, acqe_sli);
6427 
6428 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6429 			"2901 Async SLI event - Type:%d, Event Data: x%08x "
6430 			"x%08x x%08x x%08x\n", evt_type,
6431 			acqe_sli->event_data1, acqe_sli->event_data2,
6432 			acqe_sli->event_data3, acqe_sli->trailer);
6433 
6434 	port_name = phba->Port[0];
6435 	if (port_name == 0x00)
6436 		port_name = '?'; /* get port name is empty */
6437 
6438 	switch (evt_type) {
6439 	case LPFC_SLI_EVENT_TYPE_OVER_TEMP:
6440 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
6441 		temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
6442 		temp_event_data.data = (uint32_t)acqe_sli->event_data1;
6443 
6444 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6445 				"3190 Over Temperature:%d Celsius- Port Name %c\n",
6446 				acqe_sli->event_data1, port_name);
6447 
6448 		phba->sfp_warning |= LPFC_TRANSGRESSION_HIGH_TEMPERATURE;
6449 		shost = lpfc_shost_from_vport(phba->pport);
6450 		fc_host_post_vendor_event(shost, fc_get_event_number(),
6451 					  sizeof(temp_event_data),
6452 					  (char *)&temp_event_data,
6453 					  SCSI_NL_VID_TYPE_PCI
6454 					  | PCI_VENDOR_ID_EMULEX);
6455 		break;
6456 	case LPFC_SLI_EVENT_TYPE_NORM_TEMP:
6457 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
6458 		temp_event_data.event_code = LPFC_NORMAL_TEMP;
6459 		temp_event_data.data = (uint32_t)acqe_sli->event_data1;
6460 
6461 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI | LOG_LDS_EVENT,
6462 				"3191 Normal Temperature:%d Celsius - Port Name %c\n",
6463 				acqe_sli->event_data1, port_name);
6464 
6465 		shost = lpfc_shost_from_vport(phba->pport);
6466 		fc_host_post_vendor_event(shost, fc_get_event_number(),
6467 					  sizeof(temp_event_data),
6468 					  (char *)&temp_event_data,
6469 					  SCSI_NL_VID_TYPE_PCI
6470 					  | PCI_VENDOR_ID_EMULEX);
6471 		break;
6472 	case LPFC_SLI_EVENT_TYPE_MISCONFIGURED:
6473 		misconfigured = (struct lpfc_acqe_misconfigured_event *)
6474 					&acqe_sli->event_data1;
6475 
6476 		/* fetch the status for this port */
6477 		switch (phba->sli4_hba.lnk_info.lnk_no) {
6478 		case LPFC_LINK_NUMBER_0:
6479 			status = bf_get(lpfc_sli_misconfigured_port0_state,
6480 					&misconfigured->theEvent);
6481 			operational = bf_get(lpfc_sli_misconfigured_port0_op,
6482 					&misconfigured->theEvent);
6483 			break;
6484 		case LPFC_LINK_NUMBER_1:
6485 			status = bf_get(lpfc_sli_misconfigured_port1_state,
6486 					&misconfigured->theEvent);
6487 			operational = bf_get(lpfc_sli_misconfigured_port1_op,
6488 					&misconfigured->theEvent);
6489 			break;
6490 		case LPFC_LINK_NUMBER_2:
6491 			status = bf_get(lpfc_sli_misconfigured_port2_state,
6492 					&misconfigured->theEvent);
6493 			operational = bf_get(lpfc_sli_misconfigured_port2_op,
6494 					&misconfigured->theEvent);
6495 			break;
6496 		case LPFC_LINK_NUMBER_3:
6497 			status = bf_get(lpfc_sli_misconfigured_port3_state,
6498 					&misconfigured->theEvent);
6499 			operational = bf_get(lpfc_sli_misconfigured_port3_op,
6500 					&misconfigured->theEvent);
6501 			break;
6502 		default:
6503 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6504 					"3296 "
6505 					"LPFC_SLI_EVENT_TYPE_MISCONFIGURED "
6506 					"event: Invalid link %d",
6507 					phba->sli4_hba.lnk_info.lnk_no);
6508 			return;
6509 		}
6510 
6511 		/* Skip if optic state unchanged */
6512 		if (phba->sli4_hba.lnk_info.optic_state == status)
6513 			return;
6514 
6515 		switch (status) {
6516 		case LPFC_SLI_EVENT_STATUS_VALID:
6517 			sprintf(message, "Physical Link is functional");
6518 			break;
6519 		case LPFC_SLI_EVENT_STATUS_NOT_PRESENT:
6520 			sprintf(message, "Optics faulted/incorrectly "
6521 				"installed/not installed - Reseat optics, "
6522 				"if issue not resolved, replace.");
6523 			break;
6524 		case LPFC_SLI_EVENT_STATUS_WRONG_TYPE:
6525 			sprintf(message,
6526 				"Optics of two types installed - Remove one "
6527 				"optic or install matching pair of optics.");
6528 			break;
6529 		case LPFC_SLI_EVENT_STATUS_UNSUPPORTED:
6530 			sprintf(message, "Incompatible optics - Replace with "
6531 				"compatible optics for card to function.");
6532 			break;
6533 		case LPFC_SLI_EVENT_STATUS_UNQUALIFIED:
6534 			sprintf(message, "Unqualified optics - Replace with "
6535 				"Avago optics for Warranty and Technical "
6536 				"Support - Link is%s operational",
6537 				(operational) ? " not" : "");
6538 			break;
6539 		case LPFC_SLI_EVENT_STATUS_UNCERTIFIED:
6540 			sprintf(message, "Uncertified optics - Replace with "
6541 				"Avago-certified optics to enable link "
6542 				"operation - Link is%s operational",
6543 				(operational) ? " not" : "");
6544 			break;
6545 		default:
6546 			/* firmware is reporting a status we don't know about */
6547 			sprintf(message, "Unknown event status x%02x", status);
6548 			break;
6549 		}
6550 
6551 		/* Issue READ_CONFIG mbox command to refresh supported speeds */
6552 		rc = lpfc_sli4_read_config(phba);
6553 		if (rc) {
6554 			phba->lmt = 0;
6555 			lpfc_printf_log(phba, KERN_ERR,
6556 					LOG_TRACE_EVENT,
6557 					"3194 Unable to retrieve supported "
6558 					"speeds, rc = 0x%x\n", rc);
6559 		}
6560 		rc = lpfc_sli4_refresh_params(phba);
6561 		if (rc) {
6562 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6563 					"3174 Unable to update pls support, "
6564 					"rc x%x\n", rc);
6565 		}
6566 		vports = lpfc_create_vport_work_array(phba);
6567 		if (vports != NULL) {
6568 			for (i = 0; i <= phba->max_vports && vports[i] != NULL;
6569 					i++) {
6570 				shost = lpfc_shost_from_vport(vports[i]);
6571 				lpfc_host_supported_speeds_set(shost);
6572 			}
6573 		}
6574 		lpfc_destroy_vport_work_array(phba, vports);
6575 
6576 		phba->sli4_hba.lnk_info.optic_state = status;
6577 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6578 				"3176 Port Name %c %s\n", port_name, message);
6579 		break;
6580 	case LPFC_SLI_EVENT_TYPE_REMOTE_DPORT:
6581 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6582 				"3192 Remote DPort Test Initiated - "
6583 				"Event Data1:x%08x Event Data2: x%08x\n",
6584 				acqe_sli->event_data1, acqe_sli->event_data2);
6585 		break;
6586 	case LPFC_SLI_EVENT_TYPE_PORT_PARAMS_CHG:
6587 		/* Call FW to obtain active parms */
6588 		lpfc_sli4_cgn_parm_chg_evt(phba);
6589 		break;
6590 	case LPFC_SLI_EVENT_TYPE_MISCONF_FAWWN:
6591 		/* Misconfigured WWN. Reports that the SLI Port is configured
6592 		 * to use FA-WWN, but the attached device doesn’t support it.
6593 		 * Event Data1 - N.A, Event Data2 - N.A
6594 		 * This event only happens on the physical port.
6595 		 */
6596 		lpfc_log_msg(phba, KERN_WARNING, LOG_SLI | LOG_DISCOVERY,
6597 			     "2699 Misconfigured FA-PWWN - Attached device "
6598 			     "does not support FA-PWWN\n");
6599 		phba->sli4_hba.fawwpn_flag &= ~LPFC_FAWWPN_FABRIC;
6600 		memset(phba->pport->fc_portname.u.wwn, 0,
6601 		       sizeof(struct lpfc_name));
6602 		break;
6603 	case LPFC_SLI_EVENT_TYPE_EEPROM_FAILURE:
6604 		/* EEPROM failure. No driver action is required */
6605 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6606 			     "2518 EEPROM failure - "
6607 			     "Event Data1: x%08x Event Data2: x%08x\n",
6608 			     acqe_sli->event_data1, acqe_sli->event_data2);
6609 		break;
6610 	case LPFC_SLI_EVENT_TYPE_CGN_SIGNAL:
6611 		if (phba->cmf_active_mode == LPFC_CFG_OFF)
6612 			break;
6613 		cgn_signal = (struct lpfc_acqe_cgn_signal *)
6614 					&acqe_sli->event_data1;
6615 		phba->cgn_acqe_cnt++;
6616 
6617 		cnt = bf_get(lpfc_warn_acqe, cgn_signal);
6618 		atomic64_add(cnt, &phba->cgn_acqe_stat.warn);
6619 		atomic64_add(cgn_signal->alarm_cnt, &phba->cgn_acqe_stat.alarm);
6620 
6621 		/* no threshold for CMF, even 1 signal will trigger an event */
6622 
6623 		/* Alarm overrides warning, so check that first */
6624 		if (cgn_signal->alarm_cnt) {
6625 			if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
6626 				/* Keep track of alarm cnt for CMF_SYNC_WQE */
6627 				atomic_add(cgn_signal->alarm_cnt,
6628 					   &phba->cgn_sync_alarm_cnt);
6629 			}
6630 		} else if (cnt) {
6631 			/* signal action needs to be taken */
6632 			if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY ||
6633 			    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
6634 				/* Keep track of warning cnt for CMF_SYNC_WQE */
6635 				atomic_add(cnt, &phba->cgn_sync_warn_cnt);
6636 			}
6637 		}
6638 		break;
6639 	case LPFC_SLI_EVENT_TYPE_RD_SIGNAL:
6640 		/* May be accompanied by a temperature event */
6641 		lpfc_printf_log(phba, KERN_INFO,
6642 				LOG_SLI | LOG_LINK_EVENT | LOG_LDS_EVENT,
6643 				"2902 Remote Degrade Signaling: x%08x x%08x "
6644 				"x%08x\n",
6645 				acqe_sli->event_data1, acqe_sli->event_data2,
6646 				acqe_sli->event_data3);
6647 		break;
6648 	case LPFC_SLI_EVENT_TYPE_RESET_CM_STATS:
6649 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
6650 				"2905 Reset CM statistics\n");
6651 		lpfc_sli4_async_cmstat_evt(phba);
6652 		break;
6653 	default:
6654 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6655 				"3193 Unrecognized SLI event, type: 0x%x",
6656 				evt_type);
6657 		break;
6658 	}
6659 }
6660 
6661 /**
6662  * lpfc_sli4_perform_vport_cvl - Perform clear virtual link on a vport
6663  * @vport: pointer to vport data structure.
6664  *
6665  * This routine is to perform Clear Virtual Link (CVL) on a vport in
6666  * response to a CVL event.
6667  *
6668  * Return the pointer to the ndlp with the vport if successful, otherwise
6669  * return NULL.
6670  **/
6671 static struct lpfc_nodelist *
6672 lpfc_sli4_perform_vport_cvl(struct lpfc_vport *vport)
6673 {
6674 	struct lpfc_nodelist *ndlp;
6675 	struct Scsi_Host *shost;
6676 	struct lpfc_hba *phba;
6677 
6678 	if (!vport)
6679 		return NULL;
6680 	phba = vport->phba;
6681 	if (!phba)
6682 		return NULL;
6683 	ndlp = lpfc_findnode_did(vport, Fabric_DID);
6684 	if (!ndlp) {
6685 		/* Cannot find existing Fabric ndlp, so allocate a new one */
6686 		ndlp = lpfc_nlp_init(vport, Fabric_DID);
6687 		if (!ndlp)
6688 			return NULL;
6689 		/* Set the node type */
6690 		ndlp->nlp_type |= NLP_FABRIC;
6691 		/* Put ndlp onto node list */
6692 		lpfc_enqueue_node(vport, ndlp);
6693 	}
6694 	if ((phba->pport->port_state < LPFC_FLOGI) &&
6695 		(phba->pport->port_state != LPFC_VPORT_FAILED))
6696 		return NULL;
6697 	/* If virtual link is not yet instantiated ignore CVL */
6698 	if ((vport != phba->pport) && (vport->port_state < LPFC_FDISC)
6699 		&& (vport->port_state != LPFC_VPORT_FAILED))
6700 		return NULL;
6701 	shost = lpfc_shost_from_vport(vport);
6702 	if (!shost)
6703 		return NULL;
6704 	lpfc_linkdown_port(vport);
6705 	lpfc_cleanup_pending_mbox(vport);
6706 	set_bit(FC_VPORT_CVL_RCVD, &vport->fc_flag);
6707 
6708 	return ndlp;
6709 }
6710 
6711 /**
6712  * lpfc_sli4_perform_all_vport_cvl - Perform clear virtual link on all vports
6713  * @phba: pointer to lpfc hba data structure.
6714  *
6715  * This routine is to perform Clear Virtual Link (CVL) on all vports in
6716  * response to a FCF dead event.
6717  **/
6718 static void
6719 lpfc_sli4_perform_all_vport_cvl(struct lpfc_hba *phba)
6720 {
6721 	struct lpfc_vport **vports;
6722 	int i;
6723 
6724 	vports = lpfc_create_vport_work_array(phba);
6725 	if (vports)
6726 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++)
6727 			lpfc_sli4_perform_vport_cvl(vports[i]);
6728 	lpfc_destroy_vport_work_array(phba, vports);
6729 }
6730 
6731 /**
6732  * lpfc_sli4_async_fip_evt - Process the asynchronous FCoE FIP event
6733  * @phba: pointer to lpfc hba data structure.
6734  * @acqe_fip: pointer to the async fcoe completion queue entry.
6735  *
6736  * This routine is to handle the SLI4 asynchronous fcoe event.
6737  **/
6738 static void
6739 lpfc_sli4_async_fip_evt(struct lpfc_hba *phba,
6740 			struct lpfc_acqe_fip *acqe_fip)
6741 {
6742 	uint8_t event_type = bf_get(lpfc_trailer_type, acqe_fip);
6743 	int rc;
6744 	struct lpfc_vport *vport;
6745 	struct lpfc_nodelist *ndlp;
6746 	int active_vlink_present;
6747 	struct lpfc_vport **vports;
6748 	int i;
6749 
6750 	phba->fc_eventTag = acqe_fip->event_tag;
6751 	phba->fcoe_eventtag = acqe_fip->event_tag;
6752 	switch (event_type) {
6753 	case LPFC_FIP_EVENT_TYPE_NEW_FCF:
6754 	case LPFC_FIP_EVENT_TYPE_FCF_PARAM_MOD:
6755 		if (event_type == LPFC_FIP_EVENT_TYPE_NEW_FCF)
6756 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6757 					"2546 New FCF event, evt_tag:x%x, "
6758 					"index:x%x\n",
6759 					acqe_fip->event_tag,
6760 					acqe_fip->index);
6761 		else
6762 			lpfc_printf_log(phba, KERN_WARNING, LOG_FIP |
6763 					LOG_DISCOVERY,
6764 					"2788 FCF param modified event, "
6765 					"evt_tag:x%x, index:x%x\n",
6766 					acqe_fip->event_tag,
6767 					acqe_fip->index);
6768 		if (phba->fcf.fcf_flag & FCF_DISCOVERY) {
6769 			/*
6770 			 * During period of FCF discovery, read the FCF
6771 			 * table record indexed by the event to update
6772 			 * FCF roundrobin failover eligible FCF bmask.
6773 			 */
6774 			lpfc_printf_log(phba, KERN_INFO, LOG_FIP |
6775 					LOG_DISCOVERY,
6776 					"2779 Read FCF (x%x) for updating "
6777 					"roundrobin FCF failover bmask\n",
6778 					acqe_fip->index);
6779 			rc = lpfc_sli4_read_fcf_rec(phba, acqe_fip->index);
6780 		}
6781 
6782 		/* If the FCF discovery is in progress, do nothing. */
6783 		if (test_bit(FCF_TS_INPROG, &phba->hba_flag))
6784 			break;
6785 		spin_lock_irq(&phba->hbalock);
6786 		/* If fast FCF failover rescan event is pending, do nothing */
6787 		if (phba->fcf.fcf_flag & (FCF_REDISC_EVT | FCF_REDISC_PEND)) {
6788 			spin_unlock_irq(&phba->hbalock);
6789 			break;
6790 		}
6791 
6792 		/* If the FCF has been in discovered state, do nothing. */
6793 		if (phba->fcf.fcf_flag & FCF_SCAN_DONE) {
6794 			spin_unlock_irq(&phba->hbalock);
6795 			break;
6796 		}
6797 		spin_unlock_irq(&phba->hbalock);
6798 
6799 		/* Otherwise, scan the entire FCF table and re-discover SAN */
6800 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
6801 				"2770 Start FCF table scan per async FCF "
6802 				"event, evt_tag:x%x, index:x%x\n",
6803 				acqe_fip->event_tag, acqe_fip->index);
6804 		rc = lpfc_sli4_fcf_scan_read_fcf_rec(phba,
6805 						     LPFC_FCOE_FCF_GET_FIRST);
6806 		if (rc)
6807 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6808 					"2547 Issue FCF scan read FCF mailbox "
6809 					"command failed (x%x)\n", rc);
6810 		break;
6811 
6812 	case LPFC_FIP_EVENT_TYPE_FCF_TABLE_FULL:
6813 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6814 				"2548 FCF Table full count 0x%x tag 0x%x\n",
6815 				bf_get(lpfc_acqe_fip_fcf_count, acqe_fip),
6816 				acqe_fip->event_tag);
6817 		break;
6818 
6819 	case LPFC_FIP_EVENT_TYPE_FCF_DEAD:
6820 		phba->fcoe_cvl_eventtag = acqe_fip->event_tag;
6821 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6822 				"2549 FCF (x%x) disconnected from network, "
6823 				 "tag:x%x\n", acqe_fip->index,
6824 				 acqe_fip->event_tag);
6825 		/*
6826 		 * If we are in the middle of FCF failover process, clear
6827 		 * the corresponding FCF bit in the roundrobin bitmap.
6828 		 */
6829 		spin_lock_irq(&phba->hbalock);
6830 		if ((phba->fcf.fcf_flag & FCF_DISCOVERY) &&
6831 		    (phba->fcf.current_rec.fcf_indx != acqe_fip->index)) {
6832 			spin_unlock_irq(&phba->hbalock);
6833 			/* Update FLOGI FCF failover eligible FCF bmask */
6834 			lpfc_sli4_fcf_rr_index_clear(phba, acqe_fip->index);
6835 			break;
6836 		}
6837 		spin_unlock_irq(&phba->hbalock);
6838 
6839 		/* If the event is not for currently used fcf do nothing */
6840 		if (phba->fcf.current_rec.fcf_indx != acqe_fip->index)
6841 			break;
6842 
6843 		/*
6844 		 * Otherwise, request the port to rediscover the entire FCF
6845 		 * table for a fast recovery from case that the current FCF
6846 		 * is no longer valid as we are not in the middle of FCF
6847 		 * failover process already.
6848 		 */
6849 		spin_lock_irq(&phba->hbalock);
6850 		/* Mark the fast failover process in progress */
6851 		phba->fcf.fcf_flag |= FCF_DEAD_DISC;
6852 		spin_unlock_irq(&phba->hbalock);
6853 
6854 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
6855 				"2771 Start FCF fast failover process due to "
6856 				"FCF DEAD event: evt_tag:x%x, fcf_index:x%x "
6857 				"\n", acqe_fip->event_tag, acqe_fip->index);
6858 		rc = lpfc_sli4_redisc_fcf_table(phba);
6859 		if (rc) {
6860 			lpfc_printf_log(phba, KERN_ERR, LOG_FIP |
6861 					LOG_TRACE_EVENT,
6862 					"2772 Issue FCF rediscover mailbox "
6863 					"command failed, fail through to FCF "
6864 					"dead event\n");
6865 			spin_lock_irq(&phba->hbalock);
6866 			phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
6867 			spin_unlock_irq(&phba->hbalock);
6868 			/*
6869 			 * Last resort will fail over by treating this
6870 			 * as a link down to FCF registration.
6871 			 */
6872 			lpfc_sli4_fcf_dead_failthrough(phba);
6873 		} else {
6874 			/* Reset FCF roundrobin bmask for new discovery */
6875 			lpfc_sli4_clear_fcf_rr_bmask(phba);
6876 			/*
6877 			 * Handling fast FCF failover to a DEAD FCF event is
6878 			 * considered equalivant to receiving CVL to all vports.
6879 			 */
6880 			lpfc_sli4_perform_all_vport_cvl(phba);
6881 		}
6882 		break;
6883 	case LPFC_FIP_EVENT_TYPE_CVL:
6884 		phba->fcoe_cvl_eventtag = acqe_fip->event_tag;
6885 		lpfc_printf_log(phba, KERN_ERR,
6886 				LOG_TRACE_EVENT,
6887 			"2718 Clear Virtual Link Received for VPI 0x%x"
6888 			" tag 0x%x\n", acqe_fip->index, acqe_fip->event_tag);
6889 
6890 		vport = lpfc_find_vport_by_vpid(phba,
6891 						acqe_fip->index);
6892 		ndlp = lpfc_sli4_perform_vport_cvl(vport);
6893 		if (!ndlp)
6894 			break;
6895 		active_vlink_present = 0;
6896 
6897 		vports = lpfc_create_vport_work_array(phba);
6898 		if (vports) {
6899 			for (i = 0; i <= phba->max_vports && vports[i] != NULL;
6900 					i++) {
6901 				if (!test_bit(FC_VPORT_CVL_RCVD,
6902 					      &vports[i]->fc_flag) &&
6903 				    vports[i]->port_state > LPFC_FDISC) {
6904 					active_vlink_present = 1;
6905 					break;
6906 				}
6907 			}
6908 			lpfc_destroy_vport_work_array(phba, vports);
6909 		}
6910 
6911 		/*
6912 		 * Don't re-instantiate if vport is marked for deletion.
6913 		 * If we are here first then vport_delete is going to wait
6914 		 * for discovery to complete.
6915 		 */
6916 		if (!test_bit(FC_UNLOADING, &vport->load_flag) &&
6917 		    active_vlink_present) {
6918 			/*
6919 			 * If there are other active VLinks present,
6920 			 * re-instantiate the Vlink using FDISC.
6921 			 */
6922 			mod_timer(&ndlp->nlp_delayfunc,
6923 				  jiffies + secs_to_jiffies(1));
6924 			set_bit(NLP_DELAY_TMO, &ndlp->nlp_flag);
6925 			ndlp->nlp_last_elscmd = ELS_CMD_FDISC;
6926 			vport->port_state = LPFC_FDISC;
6927 		} else {
6928 			/*
6929 			 * Otherwise, we request port to rediscover
6930 			 * the entire FCF table for a fast recovery
6931 			 * from possible case that the current FCF
6932 			 * is no longer valid if we are not already
6933 			 * in the FCF failover process.
6934 			 */
6935 			spin_lock_irq(&phba->hbalock);
6936 			if (phba->fcf.fcf_flag & FCF_DISCOVERY) {
6937 				spin_unlock_irq(&phba->hbalock);
6938 				break;
6939 			}
6940 			/* Mark the fast failover process in progress */
6941 			phba->fcf.fcf_flag |= FCF_ACVL_DISC;
6942 			spin_unlock_irq(&phba->hbalock);
6943 			lpfc_printf_log(phba, KERN_INFO, LOG_FIP |
6944 					LOG_DISCOVERY,
6945 					"2773 Start FCF failover per CVL, "
6946 					"evt_tag:x%x\n", acqe_fip->event_tag);
6947 			rc = lpfc_sli4_redisc_fcf_table(phba);
6948 			if (rc) {
6949 				lpfc_printf_log(phba, KERN_ERR, LOG_FIP |
6950 						LOG_TRACE_EVENT,
6951 						"2774 Issue FCF rediscover "
6952 						"mailbox command failed, "
6953 						"through to CVL event\n");
6954 				spin_lock_irq(&phba->hbalock);
6955 				phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
6956 				spin_unlock_irq(&phba->hbalock);
6957 				/*
6958 				 * Last resort will be re-try on the
6959 				 * the current registered FCF entry.
6960 				 */
6961 				lpfc_retry_pport_discovery(phba);
6962 			} else
6963 				/*
6964 				 * Reset FCF roundrobin bmask for new
6965 				 * discovery.
6966 				 */
6967 				lpfc_sli4_clear_fcf_rr_bmask(phba);
6968 		}
6969 		break;
6970 	default:
6971 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6972 				"0288 Unknown FCoE event type 0x%x event tag "
6973 				"0x%x\n", event_type, acqe_fip->event_tag);
6974 		break;
6975 	}
6976 }
6977 
6978 /**
6979  * lpfc_sli4_async_dcbx_evt - Process the asynchronous dcbx event
6980  * @phba: pointer to lpfc hba data structure.
6981  * @acqe_dcbx: pointer to the async dcbx completion queue entry.
6982  *
6983  * This routine is to handle the SLI4 asynchronous dcbx event.
6984  **/
6985 static void
6986 lpfc_sli4_async_dcbx_evt(struct lpfc_hba *phba,
6987 			 struct lpfc_acqe_dcbx *acqe_dcbx)
6988 {
6989 	phba->fc_eventTag = acqe_dcbx->event_tag;
6990 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6991 			"0290 The SLI4 DCBX asynchronous event is not "
6992 			"handled yet\n");
6993 }
6994 
6995 /**
6996  * lpfc_sli4_async_grp5_evt - Process the asynchronous group5 event
6997  * @phba: pointer to lpfc hba data structure.
6998  * @acqe_grp5: pointer to the async grp5 completion queue entry.
6999  *
7000  * This routine is to handle the SLI4 asynchronous grp5 event. A grp5 event
7001  * is an asynchronous notified of a logical link speed change.  The Port
7002  * reports the logical link speed in units of 10Mbps.
7003  **/
7004 static void
7005 lpfc_sli4_async_grp5_evt(struct lpfc_hba *phba,
7006 			 struct lpfc_acqe_grp5 *acqe_grp5)
7007 {
7008 	uint16_t prev_ll_spd;
7009 
7010 	phba->fc_eventTag = acqe_grp5->event_tag;
7011 	phba->fcoe_eventtag = acqe_grp5->event_tag;
7012 	prev_ll_spd = phba->sli4_hba.link_state.logical_speed;
7013 	phba->sli4_hba.link_state.logical_speed =
7014 		(bf_get(lpfc_acqe_grp5_llink_spd, acqe_grp5)) * 10;
7015 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
7016 			"2789 GRP5 Async Event: Updating logical link speed "
7017 			"from %dMbps to %dMbps\n", prev_ll_spd,
7018 			phba->sli4_hba.link_state.logical_speed);
7019 }
7020 
7021 /**
7022  * lpfc_sli4_async_cmstat_evt - Process the asynchronous cmstat event
7023  * @phba: pointer to lpfc hba data structure.
7024  *
7025  * This routine is to handle the SLI4 asynchronous cmstat event. A cmstat event
7026  * is an asynchronous notification of a request to reset CM stats.
7027  **/
7028 static void
7029 lpfc_sli4_async_cmstat_evt(struct lpfc_hba *phba)
7030 {
7031 	if (!phba->cgn_i)
7032 		return;
7033 	lpfc_init_congestion_stat(phba);
7034 }
7035 
7036 /**
7037  * lpfc_cgn_params_val - Validate FW congestion parameters.
7038  * @phba: pointer to lpfc hba data structure.
7039  * @p_cfg_param: pointer to FW provided congestion parameters.
7040  *
7041  * This routine validates the congestion parameters passed
7042  * by the FW to the driver via an ACQE event.
7043  **/
7044 static void
7045 lpfc_cgn_params_val(struct lpfc_hba *phba, struct lpfc_cgn_param *p_cfg_param)
7046 {
7047 	spin_lock_irq(&phba->hbalock);
7048 
7049 	if (!lpfc_rangecheck(p_cfg_param->cgn_param_mode, LPFC_CFG_OFF,
7050 			     LPFC_CFG_MONITOR)) {
7051 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT,
7052 				"6225 CMF mode param out of range: %d\n",
7053 				 p_cfg_param->cgn_param_mode);
7054 		p_cfg_param->cgn_param_mode = LPFC_CFG_OFF;
7055 	}
7056 
7057 	spin_unlock_irq(&phba->hbalock);
7058 }
7059 
7060 static const char * const lpfc_cmf_mode_to_str[] = {
7061 	"OFF",
7062 	"MANAGED",
7063 	"MONITOR",
7064 };
7065 
7066 /**
7067  * lpfc_cgn_params_parse - Process a FW cong parm change event
7068  * @phba: pointer to lpfc hba data structure.
7069  * @p_cgn_param: pointer to a data buffer with the FW cong params.
7070  * @len: the size of pdata in bytes.
7071  *
7072  * This routine validates the congestion management buffer signature
7073  * from the FW, validates the contents and makes corrections for
7074  * valid, in-range values.  If the signature magic is correct and
7075  * after parameter validation, the contents are copied to the driver's
7076  * @phba structure. If the magic is incorrect, an error message is
7077  * logged.
7078  **/
7079 static void
7080 lpfc_cgn_params_parse(struct lpfc_hba *phba,
7081 		      struct lpfc_cgn_param *p_cgn_param, uint32_t len)
7082 {
7083 	struct lpfc_cgn_info *cp;
7084 	uint32_t crc, oldmode;
7085 	char acr_string[4] = {0};
7086 
7087 	/* Make sure the FW has encoded the correct magic number to
7088 	 * validate the congestion parameter in FW memory.
7089 	 */
7090 	if (p_cgn_param->cgn_param_magic == LPFC_CFG_PARAM_MAGIC_NUM) {
7091 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT | LOG_INIT,
7092 				"4668 FW cgn parm buffer data: "
7093 				"magic 0x%x version %d mode %d "
7094 				"level0 %d level1 %d "
7095 				"level2 %d byte13 %d "
7096 				"byte14 %d byte15 %d "
7097 				"byte11 %d byte12 %d activeMode %d\n",
7098 				p_cgn_param->cgn_param_magic,
7099 				p_cgn_param->cgn_param_version,
7100 				p_cgn_param->cgn_param_mode,
7101 				p_cgn_param->cgn_param_level0,
7102 				p_cgn_param->cgn_param_level1,
7103 				p_cgn_param->cgn_param_level2,
7104 				p_cgn_param->byte13,
7105 				p_cgn_param->byte14,
7106 				p_cgn_param->byte15,
7107 				p_cgn_param->byte11,
7108 				p_cgn_param->byte12,
7109 				phba->cmf_active_mode);
7110 
7111 		oldmode = phba->cmf_active_mode;
7112 
7113 		/* Any parameters out of range are corrected to defaults
7114 		 * by this routine.  No need to fail.
7115 		 */
7116 		lpfc_cgn_params_val(phba, p_cgn_param);
7117 
7118 		/* Parameters are verified, move them into driver storage */
7119 		spin_lock_irq(&phba->hbalock);
7120 		memcpy(&phba->cgn_p, p_cgn_param,
7121 		       sizeof(struct lpfc_cgn_param));
7122 
7123 		/* Update parameters in congestion info buffer now */
7124 		if (phba->cgn_i) {
7125 			cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
7126 			cp->cgn_info_mode = phba->cgn_p.cgn_param_mode;
7127 			cp->cgn_info_level0 = phba->cgn_p.cgn_param_level0;
7128 			cp->cgn_info_level1 = phba->cgn_p.cgn_param_level1;
7129 			cp->cgn_info_level2 = phba->cgn_p.cgn_param_level2;
7130 			crc = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ);
7131 			cp->cgn_info_crc = cpu_to_le32(crc);
7132 		}
7133 		spin_unlock_irq(&phba->hbalock);
7134 
7135 		phba->cmf_active_mode = phba->cgn_p.cgn_param_mode;
7136 
7137 		switch (oldmode) {
7138 		case LPFC_CFG_OFF:
7139 			if (phba->cgn_p.cgn_param_mode != LPFC_CFG_OFF) {
7140 				/* Turning CMF on */
7141 				lpfc_cmf_start(phba);
7142 
7143 				if (phba->link_state >= LPFC_LINK_UP) {
7144 					phba->cgn_reg_fpin =
7145 						phba->cgn_init_reg_fpin;
7146 					phba->cgn_reg_signal =
7147 						phba->cgn_init_reg_signal;
7148 					lpfc_issue_els_edc(phba->pport, 0);
7149 				}
7150 			}
7151 			break;
7152 		case LPFC_CFG_MANAGED:
7153 			switch (phba->cgn_p.cgn_param_mode) {
7154 			case LPFC_CFG_OFF:
7155 				/* Turning CMF off */
7156 				lpfc_cmf_stop(phba);
7157 				if (phba->link_state >= LPFC_LINK_UP)
7158 					lpfc_issue_els_edc(phba->pport, 0);
7159 				break;
7160 			case LPFC_CFG_MONITOR:
7161 				phba->cmf_max_bytes_per_interval =
7162 					phba->cmf_link_byte_count;
7163 
7164 				/* Resume blocked IO - unblock on workqueue */
7165 				queue_work(phba->wq,
7166 					   &phba->unblock_request_work);
7167 				break;
7168 			}
7169 			break;
7170 		case LPFC_CFG_MONITOR:
7171 			switch (phba->cgn_p.cgn_param_mode) {
7172 			case LPFC_CFG_OFF:
7173 				/* Turning CMF off */
7174 				lpfc_cmf_stop(phba);
7175 				if (phba->link_state >= LPFC_LINK_UP)
7176 					lpfc_issue_els_edc(phba->pport, 0);
7177 				break;
7178 			case LPFC_CFG_MANAGED:
7179 				lpfc_cmf_signal_init(phba);
7180 				break;
7181 			}
7182 			break;
7183 		}
7184 		if (oldmode != LPFC_CFG_OFF ||
7185 		    oldmode != phba->cgn_p.cgn_param_mode) {
7186 			if (phba->cgn_p.cgn_param_mode == LPFC_CFG_MANAGED)
7187 				scnprintf(acr_string, sizeof(acr_string), "%u",
7188 					  phba->cgn_p.cgn_param_level0);
7189 			else
7190 				scnprintf(acr_string, sizeof(acr_string), "NA");
7191 
7192 			dev_info(&phba->pcidev->dev, "%d: "
7193 				 "4663 CMF: Mode %s acr %s\n",
7194 				 phba->brd_no,
7195 				 lpfc_cmf_mode_to_str
7196 				 [phba->cgn_p.cgn_param_mode],
7197 				 acr_string);
7198 		}
7199 	} else {
7200 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7201 				"4669 FW cgn parm buf wrong magic 0x%x "
7202 				"version %d\n", p_cgn_param->cgn_param_magic,
7203 				p_cgn_param->cgn_param_version);
7204 	}
7205 }
7206 
7207 /**
7208  * lpfc_sli4_cgn_params_read - Read and Validate FW congestion parameters.
7209  * @phba: pointer to lpfc hba data structure.
7210  *
7211  * This routine issues a read_object mailbox command to
7212  * get the congestion management parameters from the FW
7213  * parses it and updates the driver maintained values.
7214  *
7215  * Returns
7216  *  0     if the object was empty
7217  *  -Eval if an error was encountered
7218  *  Count if bytes were read from object
7219  **/
7220 int
7221 lpfc_sli4_cgn_params_read(struct lpfc_hba *phba)
7222 {
7223 	int ret = 0;
7224 	struct lpfc_cgn_param *p_cgn_param = NULL;
7225 	u32 *pdata = NULL;
7226 	u32 len = 0;
7227 
7228 	/* Find out if the FW has a new set of congestion parameters. */
7229 	len = sizeof(struct lpfc_cgn_param);
7230 	pdata = kzalloc(len, GFP_KERNEL);
7231 	if (!pdata)
7232 		return -ENOMEM;
7233 	ret = lpfc_read_object(phba, (char *)LPFC_PORT_CFG_NAME,
7234 			       pdata, len);
7235 
7236 	/* 0 means no data.  A negative means error.  A positive means
7237 	 * bytes were copied.
7238 	 */
7239 	if (!ret) {
7240 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7241 				"4670 CGN RD OBJ returns no data\n");
7242 		goto rd_obj_err;
7243 	} else if (ret < 0) {
7244 		/* Some error.  Just exit and return it to the caller.*/
7245 		goto rd_obj_err;
7246 	}
7247 
7248 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT | LOG_INIT,
7249 			"6234 READ CGN PARAMS Successful %d\n", len);
7250 
7251 	/* Parse data pointer over len and update the phba congestion
7252 	 * parameters with values passed back.  The receive rate values
7253 	 * may have been altered in FW, but take no action here.
7254 	 */
7255 	p_cgn_param = (struct lpfc_cgn_param *)pdata;
7256 	lpfc_cgn_params_parse(phba, p_cgn_param, len);
7257 
7258  rd_obj_err:
7259 	kfree(pdata);
7260 	return ret;
7261 }
7262 
7263 /**
7264  * lpfc_sli4_cgn_parm_chg_evt - Process a FW congestion param change event
7265  * @phba: pointer to lpfc hba data structure.
7266  *
7267  * The FW generated Async ACQE SLI event calls this routine when
7268  * the event type is an SLI Internal Port Event and the Event Code
7269  * indicates a change to the FW maintained congestion parameters.
7270  *
7271  * This routine executes a Read_Object mailbox call to obtain the
7272  * current congestion parameters maintained in FW and corrects
7273  * the driver's active congestion parameters.
7274  *
7275  * The acqe event is not passed because there is no further data
7276  * required.
7277  *
7278  * Returns nonzero error if event processing encountered an error.
7279  * Zero otherwise for success.
7280  **/
7281 static int
7282 lpfc_sli4_cgn_parm_chg_evt(struct lpfc_hba *phba)
7283 {
7284 	int ret = 0;
7285 
7286 	if (!phba->sli4_hba.pc_sli4_params.cmf) {
7287 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7288 				"4664 Cgn Evt when E2E off. Drop event\n");
7289 		return -EACCES;
7290 	}
7291 
7292 	/* If the event is claiming an empty object, it's ok.  A write
7293 	 * could have cleared it.  Only error is a negative return
7294 	 * status.
7295 	 */
7296 	ret = lpfc_sli4_cgn_params_read(phba);
7297 	if (ret < 0) {
7298 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7299 				"4667 Error reading Cgn Params (%d)\n",
7300 				ret);
7301 	} else if (!ret) {
7302 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7303 				"4673 CGN Event empty object.\n");
7304 	}
7305 	return ret;
7306 }
7307 
7308 /**
7309  * lpfc_sli4_async_event_proc - Process all the pending asynchronous event
7310  * @phba: pointer to lpfc hba data structure.
7311  *
7312  * This routine is invoked by the worker thread to process all the pending
7313  * SLI4 asynchronous events.
7314  **/
7315 void lpfc_sli4_async_event_proc(struct lpfc_hba *phba)
7316 {
7317 	struct lpfc_cq_event *cq_event;
7318 	unsigned long iflags;
7319 
7320 	/* First, declare the async event has been handled */
7321 	clear_bit(ASYNC_EVENT, &phba->hba_flag);
7322 
7323 	/* Now, handle all the async events */
7324 	spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
7325 	while (!list_empty(&phba->sli4_hba.sp_asynce_work_queue)) {
7326 		list_remove_head(&phba->sli4_hba.sp_asynce_work_queue,
7327 				 cq_event, struct lpfc_cq_event, list);
7328 		spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock,
7329 				       iflags);
7330 
7331 		/* Process the asynchronous event */
7332 		switch (bf_get(lpfc_trailer_code, &cq_event->cqe.mcqe_cmpl)) {
7333 		case LPFC_TRAILER_CODE_LINK:
7334 			lpfc_sli4_async_link_evt(phba,
7335 						 &cq_event->cqe.acqe_link);
7336 			break;
7337 		case LPFC_TRAILER_CODE_FCOE:
7338 			lpfc_sli4_async_fip_evt(phba, &cq_event->cqe.acqe_fip);
7339 			break;
7340 		case LPFC_TRAILER_CODE_DCBX:
7341 			lpfc_sli4_async_dcbx_evt(phba,
7342 						 &cq_event->cqe.acqe_dcbx);
7343 			break;
7344 		case LPFC_TRAILER_CODE_GRP5:
7345 			lpfc_sli4_async_grp5_evt(phba,
7346 						 &cq_event->cqe.acqe_grp5);
7347 			break;
7348 		case LPFC_TRAILER_CODE_FC:
7349 			lpfc_sli4_async_fc_evt(phba, &cq_event->cqe.acqe_fc);
7350 			break;
7351 		case LPFC_TRAILER_CODE_SLI:
7352 			lpfc_sli4_async_sli_evt(phba, &cq_event->cqe.acqe_sli);
7353 			break;
7354 		default:
7355 			lpfc_printf_log(phba, KERN_ERR,
7356 					LOG_TRACE_EVENT,
7357 					"1804 Invalid asynchronous event code: "
7358 					"x%x\n", bf_get(lpfc_trailer_code,
7359 					&cq_event->cqe.mcqe_cmpl));
7360 			break;
7361 		}
7362 
7363 		/* Free the completion event processed to the free pool */
7364 		lpfc_sli4_cq_event_release(phba, cq_event);
7365 		spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
7366 	}
7367 	spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock, iflags);
7368 }
7369 
7370 /**
7371  * lpfc_sli4_fcf_redisc_event_proc - Process fcf table rediscovery event
7372  * @phba: pointer to lpfc hba data structure.
7373  *
7374  * This routine is invoked by the worker thread to process FCF table
7375  * rediscovery pending completion event.
7376  **/
7377 void lpfc_sli4_fcf_redisc_event_proc(struct lpfc_hba *phba)
7378 {
7379 	int rc;
7380 
7381 	spin_lock_irq(&phba->hbalock);
7382 	/* Clear FCF rediscovery timeout event */
7383 	phba->fcf.fcf_flag &= ~FCF_REDISC_EVT;
7384 	/* Clear driver fast failover FCF record flag */
7385 	phba->fcf.failover_rec.flag = 0;
7386 	/* Set state for FCF fast failover */
7387 	phba->fcf.fcf_flag |= FCF_REDISC_FOV;
7388 	spin_unlock_irq(&phba->hbalock);
7389 
7390 	/* Scan FCF table from the first entry to re-discover SAN */
7391 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
7392 			"2777 Start post-quiescent FCF table scan\n");
7393 	rc = lpfc_sli4_fcf_scan_read_fcf_rec(phba, LPFC_FCOE_FCF_GET_FIRST);
7394 	if (rc)
7395 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7396 				"2747 Issue FCF scan read FCF mailbox "
7397 				"command failed 0x%x\n", rc);
7398 }
7399 
7400 /**
7401  * lpfc_api_table_setup - Set up per hba pci-device group func api jump table
7402  * @phba: pointer to lpfc hba data structure.
7403  * @dev_grp: The HBA PCI-Device group number.
7404  *
7405  * This routine is invoked to set up the per HBA PCI-Device group function
7406  * API jump table entries.
7407  *
7408  * Return: 0 if success, otherwise -ENODEV
7409  **/
7410 int
7411 lpfc_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
7412 {
7413 	int rc;
7414 
7415 	/* Set up lpfc PCI-device group */
7416 	phba->pci_dev_grp = dev_grp;
7417 
7418 	/* The LPFC_PCI_DEV_OC uses SLI4 */
7419 	if (dev_grp == LPFC_PCI_DEV_OC)
7420 		phba->sli_rev = LPFC_SLI_REV4;
7421 
7422 	/* Set up device INIT API function jump table */
7423 	rc = lpfc_init_api_table_setup(phba, dev_grp);
7424 	if (rc)
7425 		return -ENODEV;
7426 	/* Set up SCSI API function jump table */
7427 	rc = lpfc_scsi_api_table_setup(phba, dev_grp);
7428 	if (rc)
7429 		return -ENODEV;
7430 	/* Set up SLI API function jump table */
7431 	rc = lpfc_sli_api_table_setup(phba, dev_grp);
7432 	if (rc)
7433 		return -ENODEV;
7434 	/* Set up MBOX API function jump table */
7435 	rc = lpfc_mbox_api_table_setup(phba, dev_grp);
7436 	if (rc)
7437 		return -ENODEV;
7438 
7439 	return 0;
7440 }
7441 
7442 /**
7443  * lpfc_log_intr_mode - Log the active interrupt mode
7444  * @phba: pointer to lpfc hba data structure.
7445  * @intr_mode: active interrupt mode adopted.
7446  *
7447  * This routine it invoked to log the currently used active interrupt mode
7448  * to the device.
7449  **/
7450 static void lpfc_log_intr_mode(struct lpfc_hba *phba, uint32_t intr_mode)
7451 {
7452 	switch (intr_mode) {
7453 	case 0:
7454 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7455 				"0470 Enable INTx interrupt mode.\n");
7456 		break;
7457 	case 1:
7458 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7459 				"0481 Enabled MSI interrupt mode.\n");
7460 		break;
7461 	case 2:
7462 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7463 				"0480 Enabled MSI-X interrupt mode.\n");
7464 		break;
7465 	default:
7466 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7467 				"0482 Illegal interrupt mode.\n");
7468 		break;
7469 	}
7470 	return;
7471 }
7472 
7473 /**
7474  * lpfc_enable_pci_dev - Enable a generic PCI device.
7475  * @phba: pointer to lpfc hba data structure.
7476  *
7477  * This routine is invoked to enable the PCI device that is common to all
7478  * PCI devices.
7479  *
7480  * Return codes
7481  * 	0 - successful
7482  * 	other values - error
7483  **/
7484 static int
7485 lpfc_enable_pci_dev(struct lpfc_hba *phba)
7486 {
7487 	struct pci_dev *pdev;
7488 
7489 	/* Obtain PCI device reference */
7490 	if (!phba->pcidev)
7491 		goto out_error;
7492 	else
7493 		pdev = phba->pcidev;
7494 	/* Enable PCI device */
7495 	if (pci_enable_device_mem(pdev))
7496 		goto out_error;
7497 	/* Request PCI resource for the device */
7498 	if (pci_request_mem_regions(pdev, LPFC_DRIVER_NAME))
7499 		goto out_disable_device;
7500 	/* Set up device as PCI master and save state for EEH */
7501 	pci_set_master(pdev);
7502 	pci_try_set_mwi(pdev);
7503 	pci_save_state(pdev);
7504 
7505 	/* PCIe EEH recovery on powerpc platforms needs fundamental reset */
7506 	if (pci_is_pcie(pdev))
7507 		pdev->needs_freset = 1;
7508 
7509 	return 0;
7510 
7511 out_disable_device:
7512 	pci_disable_device(pdev);
7513 out_error:
7514 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7515 			"1401 Failed to enable pci device\n");
7516 	return -ENODEV;
7517 }
7518 
7519 /**
7520  * lpfc_disable_pci_dev - Disable a generic PCI device.
7521  * @phba: pointer to lpfc hba data structure.
7522  *
7523  * This routine is invoked to disable the PCI device that is common to all
7524  * PCI devices.
7525  **/
7526 static void
7527 lpfc_disable_pci_dev(struct lpfc_hba *phba)
7528 {
7529 	struct pci_dev *pdev;
7530 
7531 	/* Obtain PCI device reference */
7532 	if (!phba->pcidev)
7533 		return;
7534 	else
7535 		pdev = phba->pcidev;
7536 	/* Release PCI resource and disable PCI device */
7537 	pci_release_mem_regions(pdev);
7538 	pci_disable_device(pdev);
7539 
7540 	return;
7541 }
7542 
7543 /**
7544  * lpfc_reset_hba - Reset a hba
7545  * @phba: pointer to lpfc hba data structure.
7546  *
7547  * This routine is invoked to reset a hba device. It brings the HBA
7548  * offline, performs a board restart, and then brings the board back
7549  * online. The lpfc_offline calls lpfc_sli_hba_down which will clean up
7550  * on outstanding mailbox commands.
7551  **/
7552 void
7553 lpfc_reset_hba(struct lpfc_hba *phba)
7554 {
7555 	int rc = 0;
7556 
7557 	/* If resets are disabled then set error state and return. */
7558 	if (!phba->cfg_enable_hba_reset) {
7559 		phba->link_state = LPFC_HBA_ERROR;
7560 		return;
7561 	}
7562 
7563 	/* If not LPFC_SLI_ACTIVE, force all IO to be flushed */
7564 	if (phba->sli.sli_flag & LPFC_SLI_ACTIVE) {
7565 		lpfc_offline_prep(phba, LPFC_MBX_WAIT);
7566 	} else {
7567 		if (test_bit(MBX_TMO_ERR, &phba->bit_flags)) {
7568 			/* Perform a PCI function reset to start from clean */
7569 			rc = lpfc_pci_function_reset(phba);
7570 			lpfc_els_flush_all_cmd(phba);
7571 		}
7572 		lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
7573 		lpfc_sli_flush_io_rings(phba);
7574 	}
7575 	lpfc_offline(phba);
7576 	clear_bit(MBX_TMO_ERR, &phba->bit_flags);
7577 	if (unlikely(rc)) {
7578 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
7579 				"8888 PCI function reset failed rc %x\n",
7580 				rc);
7581 	} else {
7582 		lpfc_sli_brdrestart(phba);
7583 		lpfc_online(phba);
7584 		lpfc_unblock_mgmt_io(phba);
7585 	}
7586 }
7587 
7588 /**
7589  * lpfc_sli_sriov_nr_virtfn_get - Get the number of sr-iov virtual functions
7590  * @phba: pointer to lpfc hba data structure.
7591  *
7592  * This function enables the PCI SR-IOV virtual functions to a physical
7593  * function. It invokes the PCI SR-IOV api with the @nr_vfn provided to
7594  * enable the number of virtual functions to the physical function. As
7595  * not all devices support SR-IOV, the return code from the pci_enable_sriov()
7596  * API call does not considered as an error condition for most of the device.
7597  **/
7598 uint16_t
7599 lpfc_sli_sriov_nr_virtfn_get(struct lpfc_hba *phba)
7600 {
7601 	struct pci_dev *pdev = phba->pcidev;
7602 	uint16_t nr_virtfn;
7603 	int pos;
7604 
7605 	pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_SRIOV);
7606 	if (pos == 0)
7607 		return 0;
7608 
7609 	pci_read_config_word(pdev, pos + PCI_SRIOV_TOTAL_VF, &nr_virtfn);
7610 	return nr_virtfn;
7611 }
7612 
7613 /**
7614  * lpfc_sli_probe_sriov_nr_virtfn - Enable a number of sr-iov virtual functions
7615  * @phba: pointer to lpfc hba data structure.
7616  * @nr_vfn: number of virtual functions to be enabled.
7617  *
7618  * This function enables the PCI SR-IOV virtual functions to a physical
7619  * function. It invokes the PCI SR-IOV api with the @nr_vfn provided to
7620  * enable the number of virtual functions to the physical function. As
7621  * not all devices support SR-IOV, the return code from the pci_enable_sriov()
7622  * API call does not considered as an error condition for most of the device.
7623  **/
7624 int
7625 lpfc_sli_probe_sriov_nr_virtfn(struct lpfc_hba *phba, int nr_vfn)
7626 {
7627 	struct pci_dev *pdev = phba->pcidev;
7628 	uint16_t max_nr_vfn;
7629 	int rc;
7630 
7631 	max_nr_vfn = lpfc_sli_sriov_nr_virtfn_get(phba);
7632 	if (nr_vfn > max_nr_vfn) {
7633 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7634 				"3057 Requested vfs (%d) greater than "
7635 				"supported vfs (%d)", nr_vfn, max_nr_vfn);
7636 		return -EINVAL;
7637 	}
7638 
7639 	rc = pci_enable_sriov(pdev, nr_vfn);
7640 	if (rc) {
7641 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7642 				"2806 Failed to enable sriov on this device "
7643 				"with vfn number nr_vf:%d, rc:%d\n",
7644 				nr_vfn, rc);
7645 	} else
7646 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7647 				"2807 Successful enable sriov on this device "
7648 				"with vfn number nr_vf:%d\n", nr_vfn);
7649 	return rc;
7650 }
7651 
7652 static void
7653 lpfc_unblock_requests_work(struct work_struct *work)
7654 {
7655 	struct lpfc_hba *phba = container_of(work, struct lpfc_hba,
7656 					     unblock_request_work);
7657 
7658 	lpfc_unblock_requests(phba);
7659 }
7660 
7661 /**
7662  * lpfc_setup_driver_resource_phase1 - Phase1 etup driver internal resources.
7663  * @phba: pointer to lpfc hba data structure.
7664  *
7665  * This routine is invoked to set up the driver internal resources before the
7666  * device specific resource setup to support the HBA device it attached to.
7667  *
7668  * Return codes
7669  *	0 - successful
7670  *	other values - error
7671  **/
7672 static int
7673 lpfc_setup_driver_resource_phase1(struct lpfc_hba *phba)
7674 {
7675 	struct lpfc_sli *psli = &phba->sli;
7676 
7677 	/*
7678 	 * Driver resources common to all SLI revisions
7679 	 */
7680 	atomic_set(&phba->fast_event_count, 0);
7681 	atomic_set(&phba->dbg_log_idx, 0);
7682 	atomic_set(&phba->dbg_log_cnt, 0);
7683 	atomic_set(&phba->dbg_log_dmping, 0);
7684 	spin_lock_init(&phba->hbalock);
7685 
7686 	/* Initialize port_list spinlock */
7687 	spin_lock_init(&phba->port_list_lock);
7688 	INIT_LIST_HEAD(&phba->port_list);
7689 
7690 	INIT_LIST_HEAD(&phba->work_list);
7691 
7692 	/* Initialize the wait queue head for the kernel thread */
7693 	init_waitqueue_head(&phba->work_waitq);
7694 
7695 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7696 			"1403 Protocols supported %s %s %s\n",
7697 			((phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP) ?
7698 				"SCSI" : " "),
7699 			((phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) ?
7700 				"NVME" : " "),
7701 			(phba->nvmet_support ? "NVMET" : " "));
7702 
7703 	/* ras_fwlog state */
7704 	spin_lock_init(&phba->ras_fwlog_lock);
7705 
7706 	/* Initialize the IO buffer list used by driver for SLI3 SCSI */
7707 	spin_lock_init(&phba->scsi_buf_list_get_lock);
7708 	INIT_LIST_HEAD(&phba->lpfc_scsi_buf_list_get);
7709 	spin_lock_init(&phba->scsi_buf_list_put_lock);
7710 	INIT_LIST_HEAD(&phba->lpfc_scsi_buf_list_put);
7711 
7712 	/* Initialize the fabric iocb list */
7713 	INIT_LIST_HEAD(&phba->fabric_iocb_list);
7714 
7715 	/* Initialize list to save ELS buffers */
7716 	INIT_LIST_HEAD(&phba->elsbuf);
7717 
7718 	/* Initialize FCF connection rec list */
7719 	INIT_LIST_HEAD(&phba->fcf_conn_rec_list);
7720 
7721 	/* Initialize OAS configuration list */
7722 	spin_lock_init(&phba->devicelock);
7723 	INIT_LIST_HEAD(&phba->luns);
7724 
7725 	/* MBOX heartbeat timer */
7726 	timer_setup(&psli->mbox_tmo, lpfc_mbox_timeout, 0);
7727 	/* Fabric block timer */
7728 	timer_setup(&phba->fabric_block_timer, lpfc_fabric_block_timeout, 0);
7729 	/* EA polling mode timer */
7730 	timer_setup(&phba->eratt_poll, lpfc_poll_eratt, 0);
7731 	/* Heartbeat timer */
7732 	timer_setup(&phba->hb_tmofunc, lpfc_hb_timeout, 0);
7733 
7734 	INIT_DELAYED_WORK(&phba->eq_delay_work, lpfc_hb_eq_delay_work);
7735 
7736 	INIT_DELAYED_WORK(&phba->idle_stat_delay_work,
7737 			  lpfc_idle_stat_delay_work);
7738 	INIT_WORK(&phba->unblock_request_work, lpfc_unblock_requests_work);
7739 	return 0;
7740 }
7741 
7742 /**
7743  * lpfc_sli_driver_resource_setup - Setup driver internal resources for SLI3 dev
7744  * @phba: pointer to lpfc hba data structure.
7745  *
7746  * This routine is invoked to set up the driver internal resources specific to
7747  * support the SLI-3 HBA device it attached to.
7748  *
7749  * Return codes
7750  * 0 - successful
7751  * other values - error
7752  **/
7753 static int
7754 lpfc_sli_driver_resource_setup(struct lpfc_hba *phba)
7755 {
7756 	int rc, entry_sz;
7757 
7758 	/*
7759 	 * Initialize timers used by driver
7760 	 */
7761 
7762 	/* FCP polling mode timer */
7763 	timer_setup(&phba->fcp_poll_timer, lpfc_poll_timeout, 0);
7764 
7765 	/* Host attention work mask setup */
7766 	phba->work_ha_mask = (HA_ERATT | HA_MBATT | HA_LATT);
7767 	phba->work_ha_mask |= (HA_RXMASK << (LPFC_ELS_RING * 4));
7768 
7769 	/* Get all the module params for configuring this host */
7770 	lpfc_get_cfgparam(phba);
7771 	/* Set up phase-1 common device driver resources */
7772 
7773 	rc = lpfc_setup_driver_resource_phase1(phba);
7774 	if (rc)
7775 		return -ENODEV;
7776 
7777 	if (!phba->sli.sli3_ring)
7778 		phba->sli.sli3_ring = kzalloc_objs(struct lpfc_sli_ring,
7779 						   LPFC_SLI3_MAX_RING);
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 
7928 	phba->sli4_hba.num_present_cpu = lpfc_present_cpu;
7929 	phba->sli4_hba.num_possible_cpu = cpumask_last(cpu_possible_mask) + 1;
7930 	phba->sli4_hba.curr_disp_cpu = 0;
7931 
7932 	/* Get all the module params for configuring this host */
7933 	lpfc_get_cfgparam(phba);
7934 
7935 	/* Set up phase-1 common device driver resources */
7936 	rc = lpfc_setup_driver_resource_phase1(phba);
7937 	if (rc)
7938 		return -ENODEV;
7939 
7940 	/* Before proceed, wait for POST done and device ready */
7941 	rc = lpfc_sli4_post_status_check(phba);
7942 	if (rc)
7943 		return -ENODEV;
7944 
7945 	/* Allocate all driver workqueues here */
7946 
7947 	/* The lpfc_wq workqueue for deferred irq use */
7948 	phba->wq = alloc_workqueue("lpfc_wq", WQ_MEM_RECLAIM | WQ_PERCPU, 0);
7949 	if (!phba->wq)
7950 		return -ENOMEM;
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_setup(&phba->cmf_timer, lpfc_cmf_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
7963 	/* CMF 1 minute stats collection timer */
7964 	hrtimer_setup(&phba->cmf_stats_timer, lpfc_cmf_stats_timer, CLOCK_MONOTONIC,
7965 		      HRTIMER_MODE_REL);
7966 
7967 	/*
7968 	 * Control structure for handling external multi-buffer mailbox
7969 	 * command pass-through.
7970 	 */
7971 	memset((uint8_t *)&phba->mbox_ext_buf_ctx, 0,
7972 		sizeof(struct lpfc_mbox_ext_buf_ctx));
7973 	INIT_LIST_HEAD(&phba->mbox_ext_buf_ctx.ext_dmabuf_list);
7974 
7975 	phba->max_vpi = LPFC_MAX_VPI;
7976 
7977 	/* This will be set to correct value after the read_config mbox */
7978 	phba->max_vports = 0;
7979 
7980 	/* Program the default value of vlan_id and fc_map */
7981 	phba->valid_vlan = 0;
7982 	phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
7983 	phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
7984 	phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
7985 
7986 	/*
7987 	 * For SLI4, instead of using ring 0 (LPFC_FCP_RING) for FCP commands
7988 	 * we will associate a new ring, for each EQ/CQ/WQ tuple.
7989 	 * The WQ create will allocate the ring.
7990 	 */
7991 
7992 	/* Initialize buffer queue management fields */
7993 	INIT_LIST_HEAD(&phba->hbqs[LPFC_ELS_HBQ].hbq_buffer_list);
7994 	phba->hbqs[LPFC_ELS_HBQ].hbq_alloc_buffer = lpfc_sli4_rb_alloc;
7995 	phba->hbqs[LPFC_ELS_HBQ].hbq_free_buffer = lpfc_sli4_rb_free;
7996 
7997 	/* for VMID idle timeout if VMID is enabled */
7998 	if (lpfc_is_vmid_enabled(phba))
7999 		timer_setup(&phba->inactive_vmid_poll, lpfc_vmid_poll, 0);
8000 
8001 	/*
8002 	 * Initialize the SLI Layer to run with lpfc SLI4 HBAs.
8003 	 */
8004 	/* Initialize the Abort buffer list used by driver */
8005 	spin_lock_init(&phba->sli4_hba.abts_io_buf_list_lock);
8006 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_io_buf_list);
8007 
8008 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
8009 		/* Initialize the Abort nvme buffer list used by driver */
8010 		spin_lock_init(&phba->sli4_hba.abts_nvmet_buf_list_lock);
8011 		INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
8012 		INIT_LIST_HEAD(&phba->sli4_hba.lpfc_nvmet_io_wait_list);
8013 		spin_lock_init(&phba->sli4_hba.t_active_list_lock);
8014 		INIT_LIST_HEAD(&phba->sli4_hba.t_active_ctx_list);
8015 	}
8016 
8017 	/* This abort list used by worker thread */
8018 	spin_lock_init(&phba->sli4_hba.sgl_list_lock);
8019 	spin_lock_init(&phba->sli4_hba.nvmet_io_wait_lock);
8020 	spin_lock_init(&phba->sli4_hba.asynce_list_lock);
8021 	spin_lock_init(&phba->sli4_hba.els_xri_abrt_list_lock);
8022 
8023 	/*
8024 	 * Initialize driver internal slow-path work queues
8025 	 */
8026 
8027 	/* Driver internal slow-path CQ Event pool */
8028 	INIT_LIST_HEAD(&phba->sli4_hba.sp_cqe_event_pool);
8029 	/* Response IOCB work queue list */
8030 	INIT_LIST_HEAD(&phba->sli4_hba.sp_queue_event);
8031 	/* Asynchronous event CQ Event work queue list */
8032 	INIT_LIST_HEAD(&phba->sli4_hba.sp_asynce_work_queue);
8033 	/* Slow-path XRI aborted CQ Event work queue list */
8034 	INIT_LIST_HEAD(&phba->sli4_hba.sp_els_xri_aborted_work_queue);
8035 	/* Receive queue CQ Event work queue list */
8036 	INIT_LIST_HEAD(&phba->sli4_hba.sp_unsol_work_queue);
8037 
8038 	/* Initialize extent block lists. */
8039 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_rpi_blk_list);
8040 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_xri_blk_list);
8041 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_vfi_blk_list);
8042 	INIT_LIST_HEAD(&phba->lpfc_vpi_blk_list);
8043 
8044 	/* Initialize mboxq lists. If the early init routines fail
8045 	 * these lists need to be correctly initialized.
8046 	 */
8047 	INIT_LIST_HEAD(&phba->sli.mboxq);
8048 	INIT_LIST_HEAD(&phba->sli.mboxq_cmpl);
8049 
8050 	/* initialize optic_state to 0xFF */
8051 	phba->sli4_hba.lnk_info.optic_state = 0xff;
8052 
8053 	/* Allocate device driver memory */
8054 	rc = lpfc_mem_alloc(phba, SGL_ALIGN_SZ);
8055 	if (rc)
8056 		goto out_destroy_workqueue;
8057 
8058 	/* IF Type 2 ports get initialized now. */
8059 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) >=
8060 	    LPFC_SLI_INTF_IF_TYPE_2) {
8061 		rc = lpfc_pci_function_reset(phba);
8062 		if (unlikely(rc)) {
8063 			rc = -ENODEV;
8064 			goto out_free_mem;
8065 		}
8066 		phba->temp_sensor_support = 1;
8067 	}
8068 
8069 	/* Create the bootstrap mailbox command */
8070 	rc = lpfc_create_bootstrap_mbox(phba);
8071 	if (unlikely(rc))
8072 		goto out_free_mem;
8073 
8074 	/* Set up the host's endian order with the device. */
8075 	rc = lpfc_setup_endian_order(phba);
8076 	if (unlikely(rc))
8077 		goto out_free_bsmbx;
8078 
8079 	/* Set up the hba's configuration parameters. */
8080 	rc = lpfc_sli4_read_config(phba);
8081 	if (unlikely(rc))
8082 		goto out_free_bsmbx;
8083 
8084 	if (phba->sli4_hba.fawwpn_flag & LPFC_FAWWPN_CONFIG) {
8085 		/* Right now the link is down, if FA-PWWN is configured the
8086 		 * firmware will try FLOGI before the driver gets a link up.
8087 		 * If it fails, the driver should get a MISCONFIGURED async
8088 		 * event which will clear this flag. The only notification
8089 		 * the driver gets is if it fails, if it succeeds there is no
8090 		 * notification given. Assume success.
8091 		 */
8092 		phba->sli4_hba.fawwpn_flag |= LPFC_FAWWPN_FABRIC;
8093 	}
8094 
8095 	rc = lpfc_mem_alloc_active_rrq_pool_s4(phba);
8096 	if (unlikely(rc))
8097 		goto out_free_bsmbx;
8098 
8099 	/* IF Type 0 ports get initialized now. */
8100 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
8101 	    LPFC_SLI_INTF_IF_TYPE_0) {
8102 		rc = lpfc_pci_function_reset(phba);
8103 		if (unlikely(rc))
8104 			goto out_free_bsmbx;
8105 	}
8106 
8107 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
8108 						       GFP_KERNEL);
8109 	if (!mboxq) {
8110 		rc = -ENOMEM;
8111 		goto out_free_bsmbx;
8112 	}
8113 
8114 	/* Check for NVMET being configured */
8115 	phba->nvmet_support = 0;
8116 	if (lpfc_enable_nvmet_cnt) {
8117 
8118 		/* First get WWN of HBA instance */
8119 		lpfc_read_nv(phba, mboxq);
8120 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8121 		if (rc != MBX_SUCCESS) {
8122 			lpfc_printf_log(phba, KERN_ERR,
8123 					LOG_TRACE_EVENT,
8124 					"6016 Mailbox failed , mbxCmd x%x "
8125 					"READ_NV, mbxStatus x%x\n",
8126 					bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8127 					bf_get(lpfc_mqe_status, &mboxq->u.mqe));
8128 			mempool_free(mboxq, phba->mbox_mem_pool);
8129 			rc = -EIO;
8130 			goto out_free_bsmbx;
8131 		}
8132 		mb = &mboxq->u.mb;
8133 		memcpy(&wwn, (char *)mb->un.varRDnvp.nodename,
8134 		       sizeof(uint64_t));
8135 		wwn = cpu_to_be64(wwn);
8136 		phba->sli4_hba.wwnn.u.name = wwn;
8137 		memcpy(&wwn, (char *)mb->un.varRDnvp.portname,
8138 		       sizeof(uint64_t));
8139 		/* wwn is WWPN of HBA instance */
8140 		wwn = cpu_to_be64(wwn);
8141 		phba->sli4_hba.wwpn.u.name = wwn;
8142 
8143 		/* Check to see if it matches any module parameter */
8144 		for (i = 0; i < lpfc_enable_nvmet_cnt; i++) {
8145 			if (wwn == lpfc_enable_nvmet[i]) {
8146 #if (IS_ENABLED(CONFIG_NVME_TARGET_FC))
8147 				if (lpfc_nvmet_mem_alloc(phba))
8148 					break;
8149 
8150 				phba->nvmet_support = 1; /* a match */
8151 
8152 				lpfc_printf_log(phba, KERN_ERR,
8153 						LOG_TRACE_EVENT,
8154 						"6017 NVME Target %016llx\n",
8155 						wwn);
8156 #else
8157 				lpfc_printf_log(phba, KERN_ERR,
8158 						LOG_TRACE_EVENT,
8159 						"6021 Can't enable NVME Target."
8160 						" NVME_TARGET_FC infrastructure"
8161 						" is not in kernel\n");
8162 #endif
8163 				/* Not supported for NVMET */
8164 				phba->cfg_xri_rebalancing = 0;
8165 				if (phba->irq_chann_mode == NHT_MODE) {
8166 					phba->cfg_irq_chann =
8167 						phba->sli4_hba.num_present_cpu;
8168 					phba->cfg_hdw_queue =
8169 						phba->sli4_hba.num_present_cpu;
8170 					phba->irq_chann_mode = NORMAL_MODE;
8171 				}
8172 				break;
8173 			}
8174 		}
8175 	}
8176 
8177 	lpfc_nvme_mod_param_dep(phba);
8178 
8179 	/*
8180 	 * Get sli4 parameters that override parameters from Port capabilities.
8181 	 * If this call fails, it isn't critical unless the SLI4 parameters come
8182 	 * back in conflict.
8183 	 */
8184 	rc = lpfc_get_sli4_parameters(phba, mboxq);
8185 	if (rc) {
8186 		lpfc_log_msg(phba, KERN_WARNING, LOG_INIT,
8187 			     "2999 Could not get SLI4 parameters\n");
8188 		rc = -EIO;
8189 		mempool_free(mboxq, phba->mbox_mem_pool);
8190 		goto out_free_bsmbx;
8191 	}
8192 	mempool_free(mboxq, phba->mbox_mem_pool);
8193 
8194 	/*
8195 	 * 1 for cmd, 1 for rsp, NVME adds an extra one
8196 	 * for boundary conditions in its max_sgl_segment template.
8197 	 */
8198 	extra = 2;
8199 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
8200 		extra++;
8201 
8202 	/*
8203 	 * It doesn't matter what family our adapter is in, we are
8204 	 * limited to 2 Pages, 512 SGEs, for our SGL.
8205 	 * There are going to be 2 reserved SGEs: 1 FCP cmnd + 1 FCP rsp
8206 	 */
8207 	max_buf_size = (2 * SLI4_PAGE_SIZE);
8208 
8209 	/*
8210 	 * Since lpfc_sg_seg_cnt is module param, the sg_dma_buf_size
8211 	 * used to create the sg_dma_buf_pool must be calculated.
8212 	 */
8213 	if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
8214 		/* Both cfg_enable_bg and cfg_external_dif code paths */
8215 
8216 		/*
8217 		 * The scsi_buf for a T10-DIF I/O holds the FCP cmnd,
8218 		 * the FCP rsp, and a SGE. Sice we have no control
8219 		 * over how many protection segments the SCSI Layer
8220 		 * will hand us (ie: there could be one for every block
8221 		 * in the IO), just allocate enough SGEs to accomidate
8222 		 * our max amount and we need to limit lpfc_sg_seg_cnt
8223 		 * to minimize the risk of running out.
8224 		 */
8225 		phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd32) +
8226 				sizeof(struct fcp_rsp) + max_buf_size;
8227 
8228 		/* Total SGEs for scsi_sg_list and scsi_sg_prot_list */
8229 		phba->cfg_total_seg_cnt = LPFC_MAX_SGL_SEG_CNT;
8230 
8231 		/*
8232 		 * If supporting DIF, reduce the seg count for scsi to
8233 		 * allow room for the DIF sges.
8234 		 */
8235 		if (phba->cfg_enable_bg &&
8236 		    phba->cfg_sg_seg_cnt > LPFC_MAX_BG_SLI4_SEG_CNT_DIF)
8237 			phba->cfg_scsi_seg_cnt = LPFC_MAX_BG_SLI4_SEG_CNT_DIF;
8238 		else
8239 			phba->cfg_scsi_seg_cnt = phba->cfg_sg_seg_cnt;
8240 
8241 	} else {
8242 		/*
8243 		 * The scsi_buf for a regular I/O holds the FCP cmnd,
8244 		 * the FCP rsp, a SGE for each, and a SGE for up to
8245 		 * cfg_sg_seg_cnt data segments.
8246 		 */
8247 		phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd32) +
8248 				sizeof(struct fcp_rsp) +
8249 				((phba->cfg_sg_seg_cnt + extra) *
8250 				sizeof(struct sli4_sge));
8251 
8252 		/* Total SGEs for scsi_sg_list */
8253 		phba->cfg_total_seg_cnt = phba->cfg_sg_seg_cnt + extra;
8254 		phba->cfg_scsi_seg_cnt = phba->cfg_sg_seg_cnt;
8255 
8256 		/*
8257 		 * NOTE: if (phba->cfg_sg_seg_cnt + extra) <= 256 we only
8258 		 * need to post 1 page for the SGL.
8259 		 */
8260 	}
8261 
8262 	if (phba->cfg_xpsgl && !phba->nvmet_support)
8263 		phba->cfg_sg_dma_buf_size = LPFC_DEFAULT_XPSGL_SIZE;
8264 	else if (phba->cfg_sg_dma_buf_size  <= LPFC_MIN_SG_SLI4_BUF_SZ)
8265 		phba->cfg_sg_dma_buf_size = LPFC_MIN_SG_SLI4_BUF_SZ;
8266 	else
8267 		phba->cfg_sg_dma_buf_size =
8268 				SLI4_PAGE_ALIGN(phba->cfg_sg_dma_buf_size);
8269 
8270 	phba->border_sge_num = phba->cfg_sg_dma_buf_size /
8271 			       sizeof(struct sli4_sge);
8272 
8273 	/* Limit to LPFC_MAX_NVME_SEG_CNT for NVME. */
8274 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
8275 		if (phba->cfg_sg_seg_cnt > LPFC_MAX_NVME_SEG_CNT) {
8276 			lpfc_printf_log(phba, KERN_INFO, LOG_NVME | LOG_INIT,
8277 					"6300 Reducing NVME sg segment "
8278 					"cnt to %d\n",
8279 					LPFC_MAX_NVME_SEG_CNT);
8280 			phba->cfg_nvme_seg_cnt = LPFC_MAX_NVME_SEG_CNT;
8281 		} else
8282 			phba->cfg_nvme_seg_cnt = phba->cfg_sg_seg_cnt;
8283 	}
8284 
8285 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP,
8286 			"9087 sg_seg_cnt:%d dmabuf_size:%d "
8287 			"total:%d scsi:%d nvme:%d\n",
8288 			phba->cfg_sg_seg_cnt, phba->cfg_sg_dma_buf_size,
8289 			phba->cfg_total_seg_cnt,  phba->cfg_scsi_seg_cnt,
8290 			phba->cfg_nvme_seg_cnt);
8291 
8292 	i = min_t(u32, phba->cfg_sg_dma_buf_size, SLI4_PAGE_SIZE);
8293 
8294 	phba->lpfc_sg_dma_buf_pool =
8295 			dma_pool_create("lpfc_sg_dma_buf_pool",
8296 					&phba->pcidev->dev,
8297 					phba->cfg_sg_dma_buf_size,
8298 					i, 0);
8299 	if (!phba->lpfc_sg_dma_buf_pool) {
8300 		rc = -ENOMEM;
8301 		goto out_free_bsmbx;
8302 	}
8303 
8304 	phba->lpfc_cmd_rsp_buf_pool =
8305 			dma_pool_create("lpfc_cmd_rsp_buf_pool",
8306 					&phba->pcidev->dev,
8307 					sizeof(struct fcp_cmnd32) +
8308 					sizeof(struct fcp_rsp),
8309 					i, 0);
8310 	if (!phba->lpfc_cmd_rsp_buf_pool) {
8311 		rc = -ENOMEM;
8312 		goto out_free_sg_dma_buf;
8313 	}
8314 
8315 	/* Verify OAS is supported */
8316 	lpfc_sli4_oas_verify(phba);
8317 
8318 	/* Verify RAS support on adapter */
8319 	lpfc_sli4_ras_init(phba);
8320 
8321 	/* Verify all the SLI4 queues */
8322 	rc = lpfc_sli4_queue_verify(phba);
8323 	if (rc)
8324 		goto out_free_cmd_rsp_buf;
8325 
8326 	/* Create driver internal CQE event pool */
8327 	rc = lpfc_sli4_cq_event_pool_create(phba);
8328 	if (rc)
8329 		goto out_free_cmd_rsp_buf;
8330 
8331 	/* Initialize sgl lists per host */
8332 	lpfc_init_sgl_list(phba);
8333 
8334 	/* Allocate and initialize active sgl array */
8335 	rc = lpfc_init_active_sgl_array(phba);
8336 	if (rc) {
8337 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8338 				"1430 Failed to initialize sgl list.\n");
8339 		goto out_destroy_cq_event_pool;
8340 	}
8341 	rc = lpfc_sli4_init_rpi_hdrs(phba);
8342 	if (rc) {
8343 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8344 				"1432 Failed to initialize rpi headers.\n");
8345 		goto out_free_active_sgl;
8346 	}
8347 
8348 	/* Allocate eligible FCF bmask memory for FCF roundrobin failover */
8349 	longs = (LPFC_SLI4_FCF_TBL_INDX_MAX + BITS_PER_LONG - 1)/BITS_PER_LONG;
8350 	phba->fcf.fcf_rr_bmask = kcalloc(longs, sizeof(unsigned long),
8351 					 GFP_KERNEL);
8352 	if (!phba->fcf.fcf_rr_bmask) {
8353 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8354 				"2759 Failed allocate memory for FCF round "
8355 				"robin failover bmask\n");
8356 		rc = -ENOMEM;
8357 		goto out_remove_rpi_hdrs;
8358 	}
8359 
8360 	phba->sli4_hba.hba_eq_hdl = kzalloc_objs(struct lpfc_hba_eq_hdl,
8361 						 phba->cfg_irq_chann);
8362 	if (!phba->sli4_hba.hba_eq_hdl) {
8363 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8364 				"2572 Failed allocate memory for "
8365 				"fast-path per-EQ handle array\n");
8366 		rc = -ENOMEM;
8367 		goto out_free_fcf_rr_bmask;
8368 	}
8369 
8370 	phba->sli4_hba.cpu_map = kzalloc_objs(struct lpfc_vector_map_info,
8371 					      phba->sli4_hba.num_possible_cpu);
8372 	if (!phba->sli4_hba.cpu_map) {
8373 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8374 				"3327 Failed allocate memory for msi-x "
8375 				"interrupt vector mapping\n");
8376 		rc = -ENOMEM;
8377 		goto out_free_hba_eq_hdl;
8378 	}
8379 
8380 	phba->sli4_hba.eq_info = alloc_percpu(struct lpfc_eq_intr_info);
8381 	if (!phba->sli4_hba.eq_info) {
8382 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8383 				"3321 Failed allocation for per_cpu stats\n");
8384 		rc = -ENOMEM;
8385 		goto out_free_hba_cpu_map;
8386 	}
8387 
8388 	phba->sli4_hba.idle_stat = kzalloc_objs(*phba->sli4_hba.idle_stat,
8389 						phba->sli4_hba.num_possible_cpu);
8390 	if (!phba->sli4_hba.idle_stat) {
8391 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8392 				"3390 Failed allocation for idle_stat\n");
8393 		rc = -ENOMEM;
8394 		goto out_free_hba_eq_info;
8395 	}
8396 
8397 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
8398 	phba->sli4_hba.c_stat = alloc_percpu(struct lpfc_hdwq_stat);
8399 	if (!phba->sli4_hba.c_stat) {
8400 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8401 				"3332 Failed allocating per cpu hdwq stats\n");
8402 		rc = -ENOMEM;
8403 		goto out_free_hba_idle_stat;
8404 	}
8405 #endif
8406 
8407 	phba->cmf_stat = alloc_percpu(struct lpfc_cgn_stat);
8408 	if (!phba->cmf_stat) {
8409 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8410 				"3331 Failed allocating per cpu cgn stats\n");
8411 		rc = -ENOMEM;
8412 		goto out_free_hba_hdwq_info;
8413 	}
8414 
8415 	/*
8416 	 * Enable sr-iov virtual functions if supported and configured
8417 	 * through the module parameter.
8418 	 */
8419 	if (phba->cfg_sriov_nr_virtfn > 0) {
8420 		rc = lpfc_sli_probe_sriov_nr_virtfn(phba,
8421 						 phba->cfg_sriov_nr_virtfn);
8422 		if (rc) {
8423 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
8424 					"3020 Requested number of SR-IOV "
8425 					"virtual functions (%d) is not "
8426 					"supported\n",
8427 					phba->cfg_sriov_nr_virtfn);
8428 			phba->cfg_sriov_nr_virtfn = 0;
8429 		}
8430 	}
8431 
8432 	return 0;
8433 
8434 out_free_hba_hdwq_info:
8435 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
8436 	free_percpu(phba->sli4_hba.c_stat);
8437 out_free_hba_idle_stat:
8438 #endif
8439 	kfree(phba->sli4_hba.idle_stat);
8440 out_free_hba_eq_info:
8441 	free_percpu(phba->sli4_hba.eq_info);
8442 out_free_hba_cpu_map:
8443 	kfree(phba->sli4_hba.cpu_map);
8444 out_free_hba_eq_hdl:
8445 	kfree(phba->sli4_hba.hba_eq_hdl);
8446 out_free_fcf_rr_bmask:
8447 	kfree(phba->fcf.fcf_rr_bmask);
8448 out_remove_rpi_hdrs:
8449 	lpfc_sli4_remove_rpi_hdrs(phba);
8450 out_free_active_sgl:
8451 	lpfc_free_active_sgl(phba);
8452 out_destroy_cq_event_pool:
8453 	lpfc_sli4_cq_event_pool_destroy(phba);
8454 out_free_cmd_rsp_buf:
8455 	dma_pool_destroy(phba->lpfc_cmd_rsp_buf_pool);
8456 	phba->lpfc_cmd_rsp_buf_pool = NULL;
8457 out_free_sg_dma_buf:
8458 	dma_pool_destroy(phba->lpfc_sg_dma_buf_pool);
8459 	phba->lpfc_sg_dma_buf_pool = NULL;
8460 out_free_bsmbx:
8461 	lpfc_destroy_bootstrap_mbox(phba);
8462 out_free_mem:
8463 	lpfc_mem_free(phba);
8464 out_destroy_workqueue:
8465 	destroy_workqueue(phba->wq);
8466 	phba->wq = NULL;
8467 	return rc;
8468 }
8469 
8470 /**
8471  * lpfc_sli4_driver_resource_unset - Unset drvr internal resources for SLI4 dev
8472  * @phba: pointer to lpfc hba data structure.
8473  *
8474  * This routine is invoked to unset the driver internal resources set up
8475  * specific for supporting the SLI-4 HBA device it attached to.
8476  **/
8477 static void
8478 lpfc_sli4_driver_resource_unset(struct lpfc_hba *phba)
8479 {
8480 	struct lpfc_fcf_conn_entry *conn_entry, *next_conn_entry;
8481 
8482 	free_percpu(phba->sli4_hba.eq_info);
8483 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
8484 	free_percpu(phba->sli4_hba.c_stat);
8485 #endif
8486 	free_percpu(phba->cmf_stat);
8487 	kfree(phba->sli4_hba.idle_stat);
8488 
8489 	/* Free memory allocated for msi-x interrupt vector to CPU mapping */
8490 	kfree(phba->sli4_hba.cpu_map);
8491 	phba->sli4_hba.num_possible_cpu = 0;
8492 	phba->sli4_hba.num_present_cpu = 0;
8493 	phba->sli4_hba.curr_disp_cpu = 0;
8494 	cpumask_clear(&phba->sli4_hba.irq_aff_mask);
8495 
8496 	/* Free memory allocated for fast-path work queue handles */
8497 	kfree(phba->sli4_hba.hba_eq_hdl);
8498 
8499 	/* Free the allocated rpi headers. */
8500 	lpfc_sli4_remove_rpi_hdrs(phba);
8501 	lpfc_sli4_remove_rpis(phba);
8502 
8503 	/* Free eligible FCF index bmask */
8504 	kfree(phba->fcf.fcf_rr_bmask);
8505 
8506 	/* Free the ELS sgl list */
8507 	lpfc_free_active_sgl(phba);
8508 	lpfc_free_els_sgl_list(phba);
8509 	lpfc_free_nvmet_sgl_list(phba);
8510 
8511 	/* Free the completion queue EQ event pool */
8512 	lpfc_sli4_cq_event_release_all(phba);
8513 	lpfc_sli4_cq_event_pool_destroy(phba);
8514 
8515 	/* Release resource identifiers. */
8516 	lpfc_sli4_dealloc_resource_identifiers(phba);
8517 
8518 	/* Free the bsmbx region. */
8519 	lpfc_destroy_bootstrap_mbox(phba);
8520 
8521 	/* Free the SLI Layer memory with SLI4 HBAs */
8522 	lpfc_mem_free_all(phba);
8523 
8524 	/* Free the current connect table */
8525 	list_for_each_entry_safe(conn_entry, next_conn_entry,
8526 		&phba->fcf_conn_rec_list, list) {
8527 		list_del_init(&conn_entry->list);
8528 		kfree(conn_entry);
8529 	}
8530 
8531 	return;
8532 }
8533 
8534 /**
8535  * lpfc_init_api_table_setup - Set up init api function jump table
8536  * @phba: The hba struct for which this call is being executed.
8537  * @dev_grp: The HBA PCI-Device group number.
8538  *
8539  * This routine sets up the device INIT interface API function jump table
8540  * in @phba struct.
8541  *
8542  * Returns: 0 - success, -ENODEV - failure.
8543  **/
8544 int
8545 lpfc_init_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
8546 {
8547 	phba->lpfc_hba_init_link = lpfc_hba_init_link;
8548 	phba->lpfc_hba_down_link = lpfc_hba_down_link;
8549 	phba->lpfc_selective_reset = lpfc_selective_reset;
8550 	switch (dev_grp) {
8551 	case LPFC_PCI_DEV_LP:
8552 		phba->lpfc_hba_down_post = lpfc_hba_down_post_s3;
8553 		phba->lpfc_handle_eratt = lpfc_handle_eratt_s3;
8554 		phba->lpfc_stop_port = lpfc_stop_port_s3;
8555 		break;
8556 	case LPFC_PCI_DEV_OC:
8557 		phba->lpfc_hba_down_post = lpfc_hba_down_post_s4;
8558 		phba->lpfc_handle_eratt = lpfc_handle_eratt_s4;
8559 		phba->lpfc_stop_port = lpfc_stop_port_s4;
8560 		break;
8561 	default:
8562 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8563 				"1431 Invalid HBA PCI-device group: 0x%x\n",
8564 				dev_grp);
8565 		return -ENODEV;
8566 	}
8567 	return 0;
8568 }
8569 
8570 /**
8571  * lpfc_setup_driver_resource_phase2 - Phase2 setup driver internal resources.
8572  * @phba: pointer to lpfc hba data structure.
8573  *
8574  * This routine is invoked to set up the driver internal resources after the
8575  * device specific resource setup to support the HBA device it attached to.
8576  *
8577  * Return codes
8578  * 	0 - successful
8579  * 	other values - error
8580  **/
8581 static int
8582 lpfc_setup_driver_resource_phase2(struct lpfc_hba *phba)
8583 {
8584 	int error;
8585 
8586 	/* Startup the kernel thread for this host adapter. */
8587 	phba->worker_thread = kthread_run(lpfc_do_work, phba,
8588 					  "lpfc_worker_%d", phba->brd_no);
8589 	if (IS_ERR(phba->worker_thread)) {
8590 		error = PTR_ERR(phba->worker_thread);
8591 		return error;
8592 	}
8593 
8594 	return 0;
8595 }
8596 
8597 /**
8598  * lpfc_unset_driver_resource_phase2 - Phase2 unset driver internal resources.
8599  * @phba: pointer to lpfc hba data structure.
8600  *
8601  * This routine is invoked to unset the driver internal resources set up after
8602  * the device specific resource setup for supporting the HBA device it
8603  * attached to.
8604  **/
8605 static void
8606 lpfc_unset_driver_resource_phase2(struct lpfc_hba *phba)
8607 {
8608 	if (phba->wq) {
8609 		destroy_workqueue(phba->wq);
8610 		phba->wq = NULL;
8611 	}
8612 
8613 	/* Stop kernel worker thread */
8614 	if (phba->worker_thread)
8615 		kthread_stop(phba->worker_thread);
8616 }
8617 
8618 /**
8619  * lpfc_free_iocb_list - Free iocb list.
8620  * @phba: pointer to lpfc hba data structure.
8621  *
8622  * This routine is invoked to free the driver's IOCB list and memory.
8623  **/
8624 void
8625 lpfc_free_iocb_list(struct lpfc_hba *phba)
8626 {
8627 	struct lpfc_iocbq *iocbq_entry = NULL, *iocbq_next = NULL;
8628 
8629 	spin_lock_irq(&phba->hbalock);
8630 	list_for_each_entry_safe(iocbq_entry, iocbq_next,
8631 				 &phba->lpfc_iocb_list, list) {
8632 		list_del(&iocbq_entry->list);
8633 		kfree(iocbq_entry);
8634 		phba->total_iocbq_bufs--;
8635 	}
8636 	spin_unlock_irq(&phba->hbalock);
8637 
8638 	return;
8639 }
8640 
8641 /**
8642  * lpfc_init_iocb_list - Allocate and initialize iocb list.
8643  * @phba: pointer to lpfc hba data structure.
8644  * @iocb_count: number of requested iocbs
8645  *
8646  * This routine is invoked to allocate and initizlize the driver's IOCB
8647  * list and set up the IOCB tag array accordingly.
8648  *
8649  * Return codes
8650  *	0 - successful
8651  *	other values - error
8652  **/
8653 int
8654 lpfc_init_iocb_list(struct lpfc_hba *phba, int iocb_count)
8655 {
8656 	struct lpfc_iocbq *iocbq_entry = NULL;
8657 	uint16_t iotag;
8658 	int i;
8659 
8660 	/* Initialize and populate the iocb list per host.  */
8661 	INIT_LIST_HEAD(&phba->lpfc_iocb_list);
8662 	for (i = 0; i < iocb_count; i++) {
8663 		iocbq_entry = kzalloc_obj(struct lpfc_iocbq);
8664 		if (iocbq_entry == NULL) {
8665 			printk(KERN_ERR "%s: only allocated %d iocbs of "
8666 				"expected %d count. Unloading driver.\n",
8667 				__func__, i, iocb_count);
8668 			goto out_free_iocbq;
8669 		}
8670 
8671 		iotag = lpfc_sli_next_iotag(phba, iocbq_entry);
8672 		if (iotag == 0) {
8673 			kfree(iocbq_entry);
8674 			printk(KERN_ERR "%s: failed to allocate IOTAG. "
8675 				"Unloading driver.\n", __func__);
8676 			goto out_free_iocbq;
8677 		}
8678 		iocbq_entry->sli4_lxritag = NO_XRI;
8679 		iocbq_entry->sli4_xritag = NO_XRI;
8680 
8681 		spin_lock_irq(&phba->hbalock);
8682 		list_add(&iocbq_entry->list, &phba->lpfc_iocb_list);
8683 		phba->total_iocbq_bufs++;
8684 		spin_unlock_irq(&phba->hbalock);
8685 	}
8686 
8687 	return 0;
8688 
8689 out_free_iocbq:
8690 	lpfc_free_iocb_list(phba);
8691 
8692 	return -ENOMEM;
8693 }
8694 
8695 /**
8696  * lpfc_free_sgl_list - Free a given sgl list.
8697  * @phba: pointer to lpfc hba data structure.
8698  * @sglq_list: pointer to the head of sgl list.
8699  *
8700  * This routine is invoked to free a give sgl list and memory.
8701  **/
8702 void
8703 lpfc_free_sgl_list(struct lpfc_hba *phba, struct list_head *sglq_list)
8704 {
8705 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
8706 
8707 	list_for_each_entry_safe(sglq_entry, sglq_next, sglq_list, list) {
8708 		list_del(&sglq_entry->list);
8709 		lpfc_mbuf_free(phba, sglq_entry->virt, sglq_entry->phys);
8710 		kfree(sglq_entry);
8711 	}
8712 }
8713 
8714 /**
8715  * lpfc_free_els_sgl_list - Free els sgl list.
8716  * @phba: pointer to lpfc hba data structure.
8717  *
8718  * This routine is invoked to free the driver's els sgl list and memory.
8719  **/
8720 static void
8721 lpfc_free_els_sgl_list(struct lpfc_hba *phba)
8722 {
8723 	LIST_HEAD(sglq_list);
8724 
8725 	/* Retrieve all els sgls from driver list */
8726 	spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
8727 	list_splice_init(&phba->sli4_hba.lpfc_els_sgl_list, &sglq_list);
8728 	spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
8729 
8730 	/* Now free the sgl list */
8731 	lpfc_free_sgl_list(phba, &sglq_list);
8732 }
8733 
8734 /**
8735  * lpfc_free_nvmet_sgl_list - Free nvmet sgl list.
8736  * @phba: pointer to lpfc hba data structure.
8737  *
8738  * This routine is invoked to free the driver's nvmet sgl list and memory.
8739  **/
8740 static void
8741 lpfc_free_nvmet_sgl_list(struct lpfc_hba *phba)
8742 {
8743 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
8744 	LIST_HEAD(sglq_list);
8745 
8746 	/* Retrieve all nvmet sgls from driver list */
8747 	spin_lock_irq(&phba->hbalock);
8748 	spin_lock(&phba->sli4_hba.sgl_list_lock);
8749 	list_splice_init(&phba->sli4_hba.lpfc_nvmet_sgl_list, &sglq_list);
8750 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
8751 	spin_unlock_irq(&phba->hbalock);
8752 
8753 	/* Now free the sgl list */
8754 	list_for_each_entry_safe(sglq_entry, sglq_next, &sglq_list, list) {
8755 		list_del(&sglq_entry->list);
8756 		lpfc_nvmet_buf_free(phba, sglq_entry->virt, sglq_entry->phys);
8757 		kfree(sglq_entry);
8758 	}
8759 
8760 	/* Update the nvmet_xri_cnt to reflect no current sgls.
8761 	 * The next initialization cycle sets the count and allocates
8762 	 * the sgls over again.
8763 	 */
8764 	phba->sli4_hba.nvmet_xri_cnt = 0;
8765 }
8766 
8767 /**
8768  * lpfc_init_active_sgl_array - Allocate the buf to track active ELS XRIs.
8769  * @phba: pointer to lpfc hba data structure.
8770  *
8771  * This routine is invoked to allocate the driver's active sgl memory.
8772  * This array will hold the sglq_entry's for active IOs.
8773  **/
8774 static int
8775 lpfc_init_active_sgl_array(struct lpfc_hba *phba)
8776 {
8777 	int size;
8778 	size = sizeof(struct lpfc_sglq *);
8779 	size *= phba->sli4_hba.max_cfg_param.max_xri;
8780 
8781 	phba->sli4_hba.lpfc_sglq_active_list =
8782 		kzalloc(size, GFP_KERNEL);
8783 	if (!phba->sli4_hba.lpfc_sglq_active_list)
8784 		return -ENOMEM;
8785 	return 0;
8786 }
8787 
8788 /**
8789  * lpfc_free_active_sgl - Free the buf that tracks active ELS XRIs.
8790  * @phba: pointer to lpfc hba data structure.
8791  *
8792  * This routine is invoked to walk through the array of active sglq entries
8793  * and free all of the resources.
8794  * This is just a place holder for now.
8795  **/
8796 static void
8797 lpfc_free_active_sgl(struct lpfc_hba *phba)
8798 {
8799 	kfree(phba->sli4_hba.lpfc_sglq_active_list);
8800 }
8801 
8802 /**
8803  * lpfc_init_sgl_list - Allocate and initialize sgl list.
8804  * @phba: pointer to lpfc hba data structure.
8805  *
8806  * This routine is invoked to allocate and initizlize the driver's sgl
8807  * list and set up the sgl xritag tag array accordingly.
8808  *
8809  **/
8810 static void
8811 lpfc_init_sgl_list(struct lpfc_hba *phba)
8812 {
8813 	/* Initialize and populate the sglq list per host/VF. */
8814 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_els_sgl_list);
8815 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_els_sgl_list);
8816 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_nvmet_sgl_list);
8817 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
8818 
8819 	/* els xri-sgl book keeping */
8820 	phba->sli4_hba.els_xri_cnt = 0;
8821 
8822 	/* nvme xri-buffer book keeping */
8823 	phba->sli4_hba.io_xri_cnt = 0;
8824 }
8825 
8826 /**
8827  * lpfc_sli4_init_rpi_hdrs - Post the rpi header memory region to the port
8828  * @phba: pointer to lpfc hba data structure.
8829  *
8830  * This routine is invoked to post rpi header templates to the
8831  * port for those SLI4 ports that do not support extents.  This routine
8832  * posts a PAGE_SIZE memory region to the port to hold up to
8833  * PAGE_SIZE modulo 64 rpi context headers.  This is an initialization routine
8834  * and should be called only when interrupts are disabled.
8835  *
8836  * Return codes
8837  * 	0 - successful
8838  *	-ERROR - otherwise.
8839  **/
8840 int
8841 lpfc_sli4_init_rpi_hdrs(struct lpfc_hba *phba)
8842 {
8843 	int rc = 0;
8844 	struct lpfc_rpi_hdr *rpi_hdr;
8845 
8846 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_rpi_hdr_list);
8847 	if (!phba->sli4_hba.rpi_hdrs_in_use)
8848 		return rc;
8849 	if (phba->sli4_hba.extents_in_use)
8850 		return -EIO;
8851 
8852 	rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
8853 	if (!rpi_hdr) {
8854 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8855 				"0391 Error during rpi post operation\n");
8856 		lpfc_sli4_remove_rpis(phba);
8857 		rc = -ENODEV;
8858 	}
8859 
8860 	return rc;
8861 }
8862 
8863 /**
8864  * lpfc_sli4_create_rpi_hdr - Allocate an rpi header memory region
8865  * @phba: pointer to lpfc hba data structure.
8866  *
8867  * This routine is invoked to allocate a single 4KB memory region to
8868  * support rpis and stores them in the phba.  This single region
8869  * provides support for up to 64 rpis.  The region is used globally
8870  * by the device.
8871  *
8872  * Returns:
8873  *   A valid rpi hdr on success.
8874  *   A NULL pointer on any failure.
8875  **/
8876 struct lpfc_rpi_hdr *
8877 lpfc_sli4_create_rpi_hdr(struct lpfc_hba *phba)
8878 {
8879 	uint16_t rpi_limit, curr_rpi_range;
8880 	struct lpfc_dmabuf *dmabuf;
8881 	struct lpfc_rpi_hdr *rpi_hdr;
8882 
8883 	/*
8884 	 * If the SLI4 port supports extents, posting the rpi header isn't
8885 	 * required.  Set the expected maximum count and let the actual value
8886 	 * get set when extents are fully allocated.
8887 	 */
8888 	if (!phba->sli4_hba.rpi_hdrs_in_use)
8889 		return NULL;
8890 	if (phba->sli4_hba.extents_in_use)
8891 		return NULL;
8892 
8893 	/* The limit on the logical index is just the max_rpi count. */
8894 	rpi_limit = phba->sli4_hba.max_cfg_param.max_rpi;
8895 
8896 	spin_lock_irq(&phba->hbalock);
8897 	/*
8898 	 * Establish the starting RPI in this header block.  The starting
8899 	 * rpi is normalized to a zero base because the physical rpi is
8900 	 * port based.
8901 	 */
8902 	curr_rpi_range = phba->sli4_hba.next_rpi;
8903 	spin_unlock_irq(&phba->hbalock);
8904 
8905 	/* Reached full RPI range */
8906 	if (curr_rpi_range == rpi_limit)
8907 		return NULL;
8908 
8909 	/*
8910 	 * First allocate the protocol header region for the port.  The
8911 	 * port expects a 4KB DMA-mapped memory region that is 4K aligned.
8912 	 */
8913 	dmabuf = kzalloc_obj(struct lpfc_dmabuf);
8914 	if (!dmabuf)
8915 		return NULL;
8916 
8917 	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
8918 					  LPFC_HDR_TEMPLATE_SIZE,
8919 					  &dmabuf->phys, GFP_KERNEL);
8920 	if (!dmabuf->virt) {
8921 		rpi_hdr = NULL;
8922 		goto err_free_dmabuf;
8923 	}
8924 
8925 	if (!IS_ALIGNED(dmabuf->phys, LPFC_HDR_TEMPLATE_SIZE)) {
8926 		rpi_hdr = NULL;
8927 		goto err_free_coherent;
8928 	}
8929 
8930 	/* Save the rpi header data for cleanup later. */
8931 	rpi_hdr = kzalloc_obj(struct lpfc_rpi_hdr);
8932 	if (!rpi_hdr)
8933 		goto err_free_coherent;
8934 
8935 	rpi_hdr->dmabuf = dmabuf;
8936 	rpi_hdr->len = LPFC_HDR_TEMPLATE_SIZE;
8937 	rpi_hdr->page_count = 1;
8938 	spin_lock_irq(&phba->hbalock);
8939 
8940 	/* The rpi_hdr stores the logical index only. */
8941 	rpi_hdr->start_rpi = curr_rpi_range;
8942 	rpi_hdr->next_rpi = phba->sli4_hba.next_rpi + LPFC_RPI_HDR_COUNT;
8943 	list_add_tail(&rpi_hdr->list, &phba->sli4_hba.lpfc_rpi_hdr_list);
8944 
8945 	spin_unlock_irq(&phba->hbalock);
8946 	return rpi_hdr;
8947 
8948  err_free_coherent:
8949 	dma_free_coherent(&phba->pcidev->dev, LPFC_HDR_TEMPLATE_SIZE,
8950 			  dmabuf->virt, dmabuf->phys);
8951  err_free_dmabuf:
8952 	kfree(dmabuf);
8953 	return NULL;
8954 }
8955 
8956 /**
8957  * lpfc_sli4_remove_rpi_hdrs - Remove all rpi header memory regions
8958  * @phba: pointer to lpfc hba data structure.
8959  *
8960  * This routine is invoked to remove all memory resources allocated
8961  * to support rpis for SLI4 ports not supporting extents. This routine
8962  * presumes the caller has released all rpis consumed by fabric or port
8963  * logins and is prepared to have the header pages removed.
8964  **/
8965 void
8966 lpfc_sli4_remove_rpi_hdrs(struct lpfc_hba *phba)
8967 {
8968 	struct lpfc_rpi_hdr *rpi_hdr, *next_rpi_hdr;
8969 
8970 	if (!phba->sli4_hba.rpi_hdrs_in_use)
8971 		goto exit;
8972 
8973 	list_for_each_entry_safe(rpi_hdr, next_rpi_hdr,
8974 				 &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
8975 		list_del(&rpi_hdr->list);
8976 		dma_free_coherent(&phba->pcidev->dev, rpi_hdr->len,
8977 				  rpi_hdr->dmabuf->virt, rpi_hdr->dmabuf->phys);
8978 		kfree(rpi_hdr->dmabuf);
8979 		kfree(rpi_hdr);
8980 	}
8981  exit:
8982 	/* There are no rpis available to the port now. */
8983 	phba->sli4_hba.next_rpi = 0;
8984 }
8985 
8986 /**
8987  * lpfc_hba_alloc - Allocate driver hba data structure for a device.
8988  * @pdev: pointer to pci device data structure.
8989  *
8990  * This routine is invoked to allocate the driver hba data structure for an
8991  * HBA device. If the allocation is successful, the phba reference to the
8992  * PCI device data structure is set.
8993  *
8994  * Return codes
8995  *      pointer to @phba - successful
8996  *      NULL - error
8997  **/
8998 static struct lpfc_hba *
8999 lpfc_hba_alloc(struct pci_dev *pdev)
9000 {
9001 	struct lpfc_hba *phba;
9002 
9003 	/* Allocate memory for HBA structure */
9004 	phba = kzalloc_obj(struct lpfc_hba);
9005 	if (!phba) {
9006 		dev_err(&pdev->dev, "failed to allocate hba struct\n");
9007 		return NULL;
9008 	}
9009 
9010 	/* Set reference to PCI device in HBA structure */
9011 	phba->pcidev = pdev;
9012 
9013 	/* Assign an unused board number */
9014 	phba->brd_no = lpfc_get_instance();
9015 	if (phba->brd_no < 0) {
9016 		kfree(phba);
9017 		return NULL;
9018 	}
9019 	phba->eratt_poll_interval = LPFC_ERATT_POLL_INTERVAL;
9020 
9021 	spin_lock_init(&phba->ct_ev_lock);
9022 	INIT_LIST_HEAD(&phba->ct_ev_waiters);
9023 
9024 	return phba;
9025 }
9026 
9027 /**
9028  * lpfc_hba_free - Free driver hba data structure with a device.
9029  * @phba: pointer to lpfc hba data structure.
9030  *
9031  * This routine is invoked to free the driver hba data structure with an
9032  * HBA device.
9033  **/
9034 static void
9035 lpfc_hba_free(struct lpfc_hba *phba)
9036 {
9037 	if (phba->sli_rev == LPFC_SLI_REV4)
9038 		kfree(phba->sli4_hba.hdwq);
9039 
9040 	/* Release the driver assigned board number */
9041 	idr_remove(&lpfc_hba_index, phba->brd_no);
9042 
9043 	/* Free memory allocated with sli3 rings */
9044 	kfree(phba->sli.sli3_ring);
9045 	phba->sli.sli3_ring = NULL;
9046 
9047 	kfree(phba);
9048 	return;
9049 }
9050 
9051 /**
9052  * lpfc_setup_fdmi_mask - Setup initial FDMI mask for HBA and Port attributes
9053  * @vport: pointer to lpfc vport data structure.
9054  *
9055  * This routine is will setup initial FDMI attribute masks for
9056  * FDMI2 or SmartSAN depending on module parameters. The driver will attempt
9057  * to get these attributes first before falling back, the attribute
9058  * fallback hierarchy is SmartSAN -> FDMI2 -> FMDI1
9059  **/
9060 void
9061 lpfc_setup_fdmi_mask(struct lpfc_vport *vport)
9062 {
9063 	struct lpfc_hba *phba = vport->phba;
9064 
9065 	set_bit(FC_ALLOW_FDMI, &vport->load_flag);
9066 	if (phba->cfg_enable_SmartSAN ||
9067 	    phba->cfg_fdmi_on == LPFC_FDMI_SUPPORT) {
9068 		/* Setup appropriate attribute masks */
9069 		vport->fdmi_hba_mask = LPFC_FDMI2_HBA_ATTR;
9070 		if (phba->cfg_enable_SmartSAN)
9071 			vport->fdmi_port_mask = LPFC_FDMI2_SMART_ATTR;
9072 		else
9073 			vport->fdmi_port_mask = LPFC_FDMI2_PORT_ATTR;
9074 	}
9075 
9076 	lpfc_printf_vlog(vport, KERN_INFO, LOG_DISCOVERY,
9077 			 "6077 Setup FDMI mask: hba x%x port x%x\n",
9078 			 vport->fdmi_hba_mask, vport->fdmi_port_mask);
9079 }
9080 
9081 /**
9082  * lpfc_create_shost - Create hba physical port with associated scsi host.
9083  * @phba: pointer to lpfc hba data structure.
9084  *
9085  * This routine is invoked to create HBA physical port and associate a SCSI
9086  * host with it.
9087  *
9088  * Return codes
9089  *      0 - successful
9090  *      other values - error
9091  **/
9092 static int
9093 lpfc_create_shost(struct lpfc_hba *phba)
9094 {
9095 	struct lpfc_vport *vport;
9096 	struct Scsi_Host  *shost;
9097 
9098 	/* Initialize HBA FC structure */
9099 	phba->fc_edtov = FF_DEF_EDTOV;
9100 	phba->fc_ratov = FF_DEF_RATOV;
9101 	phba->fc_altov = FF_DEF_ALTOV;
9102 	phba->fc_arbtov = FF_DEF_ARBTOV;
9103 
9104 	atomic_set(&phba->sdev_cnt, 0);
9105 	vport = lpfc_create_port(phba, phba->brd_no, &phba->pcidev->dev);
9106 	if (!vport)
9107 		return -ENODEV;
9108 
9109 	shost = lpfc_shost_from_vport(vport);
9110 	phba->pport = vport;
9111 
9112 	if (phba->nvmet_support) {
9113 		/* Only 1 vport (pport) will support NVME target */
9114 		phba->targetport = NULL;
9115 		phba->cfg_enable_fc4_type = LPFC_ENABLE_NVME;
9116 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_NVME_DISC,
9117 				"6076 NVME Target Found\n");
9118 	}
9119 
9120 	lpfc_debugfs_initialize(vport);
9121 	/* Put reference to SCSI host to driver's device private data */
9122 	pci_set_drvdata(phba->pcidev, shost);
9123 
9124 	lpfc_setup_fdmi_mask(vport);
9125 
9126 	/*
9127 	 * At this point we are fully registered with PSA. In addition,
9128 	 * any initial discovery should be completed.
9129 	 */
9130 	return 0;
9131 }
9132 
9133 /**
9134  * lpfc_destroy_shost - Destroy hba physical port with associated scsi host.
9135  * @phba: pointer to lpfc hba data structure.
9136  *
9137  * This routine is invoked to destroy HBA physical port and the associated
9138  * SCSI host.
9139  **/
9140 static void
9141 lpfc_destroy_shost(struct lpfc_hba *phba)
9142 {
9143 	struct lpfc_vport *vport = phba->pport;
9144 
9145 	/* Destroy physical port that associated with the SCSI host */
9146 	destroy_port(vport);
9147 
9148 	return;
9149 }
9150 
9151 /**
9152  * lpfc_setup_bg - Setup Block guard structures and debug areas.
9153  * @phba: pointer to lpfc hba data structure.
9154  * @shost: the shost to be used to detect Block guard settings.
9155  *
9156  * This routine sets up the local Block guard protocol settings for @shost.
9157  * This routine also allocates memory for debugging bg buffers.
9158  **/
9159 static void
9160 lpfc_setup_bg(struct lpfc_hba *phba, struct Scsi_Host *shost)
9161 {
9162 	uint32_t old_mask;
9163 	uint32_t old_guard;
9164 
9165 	if (phba->cfg_prot_mask && phba->cfg_prot_guard) {
9166 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9167 				"1478 Registering BlockGuard with the "
9168 				"SCSI layer\n");
9169 
9170 		old_mask = phba->cfg_prot_mask;
9171 		old_guard = phba->cfg_prot_guard;
9172 
9173 		/* Only allow supported values */
9174 		phba->cfg_prot_mask &= (SHOST_DIF_TYPE1_PROTECTION |
9175 			SHOST_DIX_TYPE0_PROTECTION |
9176 			SHOST_DIX_TYPE1_PROTECTION);
9177 		phba->cfg_prot_guard &= (SHOST_DIX_GUARD_IP |
9178 					 SHOST_DIX_GUARD_CRC);
9179 
9180 		/* DIF Type 1 protection for profiles AST1/C1 is end to end */
9181 		if (phba->cfg_prot_mask == SHOST_DIX_TYPE1_PROTECTION)
9182 			phba->cfg_prot_mask |= SHOST_DIF_TYPE1_PROTECTION;
9183 
9184 		if (phba->cfg_prot_mask && phba->cfg_prot_guard) {
9185 			if ((old_mask != phba->cfg_prot_mask) ||
9186 				(old_guard != phba->cfg_prot_guard))
9187 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9188 					"1475 Registering BlockGuard with the "
9189 					"SCSI layer: mask %d  guard %d\n",
9190 					phba->cfg_prot_mask,
9191 					phba->cfg_prot_guard);
9192 
9193 			scsi_host_set_prot(shost, phba->cfg_prot_mask);
9194 			scsi_host_set_guard(shost, phba->cfg_prot_guard);
9195 		} else
9196 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9197 				"1479 Not Registering BlockGuard with the SCSI "
9198 				"layer, Bad protection parameters: %d %d\n",
9199 				old_mask, old_guard);
9200 	}
9201 }
9202 
9203 /**
9204  * lpfc_post_init_setup - Perform necessary device post initialization setup.
9205  * @phba: pointer to lpfc hba data structure.
9206  *
9207  * This routine is invoked to perform all the necessary post initialization
9208  * setup for the device.
9209  **/
9210 static void
9211 lpfc_post_init_setup(struct lpfc_hba *phba)
9212 {
9213 	struct Scsi_Host  *shost;
9214 	struct lpfc_adapter_event_header adapter_event;
9215 
9216 	/* Get the default values for Model Name and Description */
9217 	lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
9218 
9219 	/*
9220 	 * hba setup may have changed the hba_queue_depth so we need to
9221 	 * adjust the value of can_queue.
9222 	 */
9223 	shost = pci_get_drvdata(phba->pcidev);
9224 	shost->can_queue = phba->cfg_hba_queue_depth - 10;
9225 
9226 	lpfc_host_attrib_init(shost);
9227 
9228 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
9229 		spin_lock_irq(shost->host_lock);
9230 		lpfc_poll_start_timer(phba);
9231 		spin_unlock_irq(shost->host_lock);
9232 	}
9233 
9234 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9235 			"0428 Perform SCSI scan\n");
9236 	/* Send board arrival event to upper layer */
9237 	adapter_event.event_type = FC_REG_ADAPTER_EVENT;
9238 	adapter_event.subcategory = LPFC_EVENT_ARRIVAL;
9239 	fc_host_post_vendor_event(shost, fc_get_event_number(),
9240 				  sizeof(adapter_event),
9241 				  (char *) &adapter_event,
9242 				  LPFC_NL_VENDOR_ID);
9243 	return;
9244 }
9245 
9246 /**
9247  * lpfc_sli_pci_mem_setup - Setup SLI3 HBA PCI memory space.
9248  * @phba: pointer to lpfc hba data structure.
9249  *
9250  * This routine is invoked to set up the PCI device memory space for device
9251  * with SLI-3 interface spec.
9252  *
9253  * Return codes
9254  * 	0 - successful
9255  * 	other values - error
9256  **/
9257 static int
9258 lpfc_sli_pci_mem_setup(struct lpfc_hba *phba)
9259 {
9260 	struct pci_dev *pdev = phba->pcidev;
9261 	unsigned long bar0map_len, bar2map_len;
9262 	int i, hbq_count;
9263 	void *ptr;
9264 	int error;
9265 
9266 	if (!pdev)
9267 		return -ENODEV;
9268 
9269 	/* Set the device DMA mask size */
9270 	error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
9271 	if (error)
9272 		error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32));
9273 	if (error)
9274 		return error;
9275 	error = -ENODEV;
9276 
9277 	/* Get the bus address of Bar0 and Bar2 and the number of bytes
9278 	 * required by each mapping.
9279 	 */
9280 	phba->pci_bar0_map = pci_resource_start(pdev, 0);
9281 	bar0map_len = pci_resource_len(pdev, 0);
9282 
9283 	phba->pci_bar2_map = pci_resource_start(pdev, 2);
9284 	bar2map_len = pci_resource_len(pdev, 2);
9285 
9286 	/* Map HBA SLIM to a kernel virtual address. */
9287 	phba->slim_memmap_p = ioremap(phba->pci_bar0_map, bar0map_len);
9288 	if (!phba->slim_memmap_p) {
9289 		dev_printk(KERN_ERR, &pdev->dev,
9290 			   "ioremap failed for SLIM memory.\n");
9291 		goto out;
9292 	}
9293 
9294 	/* Map HBA Control Registers to a kernel virtual address. */
9295 	phba->ctrl_regs_memmap_p = ioremap(phba->pci_bar2_map, bar2map_len);
9296 	if (!phba->ctrl_regs_memmap_p) {
9297 		dev_printk(KERN_ERR, &pdev->dev,
9298 			   "ioremap failed for HBA control registers.\n");
9299 		goto out_iounmap_slim;
9300 	}
9301 
9302 	/* Allocate memory for SLI-2 structures */
9303 	phba->slim2p.virt = dma_alloc_coherent(&pdev->dev, SLI2_SLIM_SIZE,
9304 					       &phba->slim2p.phys, GFP_KERNEL);
9305 	if (!phba->slim2p.virt)
9306 		goto out_iounmap;
9307 
9308 	phba->mbox = phba->slim2p.virt + offsetof(struct lpfc_sli2_slim, mbx);
9309 	phba->mbox_ext = (phba->slim2p.virt +
9310 		offsetof(struct lpfc_sli2_slim, mbx_ext_words));
9311 	phba->pcb = (phba->slim2p.virt + offsetof(struct lpfc_sli2_slim, pcb));
9312 	phba->IOCBs = (phba->slim2p.virt +
9313 		       offsetof(struct lpfc_sli2_slim, IOCBs));
9314 
9315 	phba->hbqslimp.virt = dma_alloc_coherent(&pdev->dev,
9316 						 lpfc_sli_hbq_size(),
9317 						 &phba->hbqslimp.phys,
9318 						 GFP_KERNEL);
9319 	if (!phba->hbqslimp.virt)
9320 		goto out_free_slim;
9321 
9322 	hbq_count = lpfc_sli_hbq_count();
9323 	ptr = phba->hbqslimp.virt;
9324 	for (i = 0; i < hbq_count; ++i) {
9325 		phba->hbqs[i].hbq_virt = ptr;
9326 		INIT_LIST_HEAD(&phba->hbqs[i].hbq_buffer_list);
9327 		ptr += (lpfc_hbq_defs[i]->entry_count *
9328 			sizeof(struct lpfc_hbq_entry));
9329 	}
9330 	phba->hbqs[LPFC_ELS_HBQ].hbq_alloc_buffer = lpfc_els_hbq_alloc;
9331 	phba->hbqs[LPFC_ELS_HBQ].hbq_free_buffer = lpfc_els_hbq_free;
9332 
9333 	memset(phba->hbqslimp.virt, 0, lpfc_sli_hbq_size());
9334 
9335 	phba->MBslimaddr = phba->slim_memmap_p;
9336 	phba->HAregaddr = phba->ctrl_regs_memmap_p + HA_REG_OFFSET;
9337 	phba->CAregaddr = phba->ctrl_regs_memmap_p + CA_REG_OFFSET;
9338 	phba->HSregaddr = phba->ctrl_regs_memmap_p + HS_REG_OFFSET;
9339 	phba->HCregaddr = phba->ctrl_regs_memmap_p + HC_REG_OFFSET;
9340 
9341 	return 0;
9342 
9343 out_free_slim:
9344 	dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
9345 			  phba->slim2p.virt, phba->slim2p.phys);
9346 out_iounmap:
9347 	iounmap(phba->ctrl_regs_memmap_p);
9348 out_iounmap_slim:
9349 	iounmap(phba->slim_memmap_p);
9350 out:
9351 	return error;
9352 }
9353 
9354 /**
9355  * lpfc_sli_pci_mem_unset - Unset SLI3 HBA PCI memory space.
9356  * @phba: pointer to lpfc hba data structure.
9357  *
9358  * This routine is invoked to unset the PCI device memory space for device
9359  * with SLI-3 interface spec.
9360  **/
9361 static void
9362 lpfc_sli_pci_mem_unset(struct lpfc_hba *phba)
9363 {
9364 	struct pci_dev *pdev;
9365 
9366 	/* Obtain PCI device reference */
9367 	if (!phba->pcidev)
9368 		return;
9369 	else
9370 		pdev = phba->pcidev;
9371 
9372 	/* Free coherent DMA memory allocated */
9373 	dma_free_coherent(&pdev->dev, lpfc_sli_hbq_size(),
9374 			  phba->hbqslimp.virt, phba->hbqslimp.phys);
9375 	dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
9376 			  phba->slim2p.virt, phba->slim2p.phys);
9377 
9378 	/* I/O memory unmap */
9379 	iounmap(phba->ctrl_regs_memmap_p);
9380 	iounmap(phba->slim_memmap_p);
9381 
9382 	return;
9383 }
9384 
9385 /**
9386  * lpfc_sli4_post_status_check - Wait for SLI4 POST done and check status
9387  * @phba: pointer to lpfc hba data structure.
9388  *
9389  * This routine is invoked to wait for SLI4 device Power On Self Test (POST)
9390  * done and check status.
9391  *
9392  * Return 0 if successful, otherwise -ENODEV.
9393  **/
9394 int
9395 lpfc_sli4_post_status_check(struct lpfc_hba *phba)
9396 {
9397 	struct lpfc_register portsmphr_reg, uerrlo_reg, uerrhi_reg;
9398 	struct lpfc_register reg_data;
9399 	int i, port_error = 0;
9400 	uint32_t if_type;
9401 
9402 	memset(&portsmphr_reg, 0, sizeof(portsmphr_reg));
9403 	memset(&reg_data, 0, sizeof(reg_data));
9404 	if (!phba->sli4_hba.PSMPHRregaddr)
9405 		return -ENODEV;
9406 
9407 	/* Wait up to 30 seconds for the SLI Port POST done and ready */
9408 	for (i = 0; i < 3000; i++) {
9409 		if (lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
9410 			&portsmphr_reg.word0) ||
9411 			(bf_get(lpfc_port_smphr_perr, &portsmphr_reg))) {
9412 			/* Port has a fatal POST error, break out */
9413 			port_error = -ENODEV;
9414 			break;
9415 		}
9416 		if (LPFC_POST_STAGE_PORT_READY ==
9417 		    bf_get(lpfc_port_smphr_port_status, &portsmphr_reg))
9418 			break;
9419 		msleep(10);
9420 	}
9421 
9422 	/*
9423 	 * If there was a port error during POST, then don't proceed with
9424 	 * other register reads as the data may not be valid.  Just exit.
9425 	 */
9426 	if (port_error) {
9427 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9428 			"1408 Port Failed POST - portsmphr=0x%x, "
9429 			"perr=x%x, sfi=x%x, nip=x%x, ipc=x%x, scr1=x%x, "
9430 			"scr2=x%x, hscratch=x%x, pstatus=x%x\n",
9431 			portsmphr_reg.word0,
9432 			bf_get(lpfc_port_smphr_perr, &portsmphr_reg),
9433 			bf_get(lpfc_port_smphr_sfi, &portsmphr_reg),
9434 			bf_get(lpfc_port_smphr_nip, &portsmphr_reg),
9435 			bf_get(lpfc_port_smphr_ipc, &portsmphr_reg),
9436 			bf_get(lpfc_port_smphr_scr1, &portsmphr_reg),
9437 			bf_get(lpfc_port_smphr_scr2, &portsmphr_reg),
9438 			bf_get(lpfc_port_smphr_host_scratch, &portsmphr_reg),
9439 			bf_get(lpfc_port_smphr_port_status, &portsmphr_reg));
9440 	} else {
9441 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9442 				"2534 Device Info: SLIFamily=0x%x, "
9443 				"SLIRev=0x%x, IFType=0x%x, SLIHint_1=0x%x, "
9444 				"SLIHint_2=0x%x, FT=0x%x\n",
9445 				bf_get(lpfc_sli_intf_sli_family,
9446 				       &phba->sli4_hba.sli_intf),
9447 				bf_get(lpfc_sli_intf_slirev,
9448 				       &phba->sli4_hba.sli_intf),
9449 				bf_get(lpfc_sli_intf_if_type,
9450 				       &phba->sli4_hba.sli_intf),
9451 				bf_get(lpfc_sli_intf_sli_hint1,
9452 				       &phba->sli4_hba.sli_intf),
9453 				bf_get(lpfc_sli_intf_sli_hint2,
9454 				       &phba->sli4_hba.sli_intf),
9455 				bf_get(lpfc_sli_intf_func_type,
9456 				       &phba->sli4_hba.sli_intf));
9457 		/*
9458 		 * Check for other Port errors during the initialization
9459 		 * process.  Fail the load if the port did not come up
9460 		 * correctly.
9461 		 */
9462 		if_type = bf_get(lpfc_sli_intf_if_type,
9463 				 &phba->sli4_hba.sli_intf);
9464 		switch (if_type) {
9465 		case LPFC_SLI_INTF_IF_TYPE_0:
9466 			phba->sli4_hba.ue_mask_lo =
9467 			      readl(phba->sli4_hba.u.if_type0.UEMASKLOregaddr);
9468 			phba->sli4_hba.ue_mask_hi =
9469 			      readl(phba->sli4_hba.u.if_type0.UEMASKHIregaddr);
9470 			uerrlo_reg.word0 =
9471 			      readl(phba->sli4_hba.u.if_type0.UERRLOregaddr);
9472 			uerrhi_reg.word0 =
9473 				readl(phba->sli4_hba.u.if_type0.UERRHIregaddr);
9474 			if ((~phba->sli4_hba.ue_mask_lo & uerrlo_reg.word0) ||
9475 			    (~phba->sli4_hba.ue_mask_hi & uerrhi_reg.word0)) {
9476 				lpfc_printf_log(phba, KERN_ERR,
9477 						LOG_TRACE_EVENT,
9478 						"1422 Unrecoverable Error "
9479 						"Detected during POST "
9480 						"uerr_lo_reg=0x%x, "
9481 						"uerr_hi_reg=0x%x, "
9482 						"ue_mask_lo_reg=0x%x, "
9483 						"ue_mask_hi_reg=0x%x\n",
9484 						uerrlo_reg.word0,
9485 						uerrhi_reg.word0,
9486 						phba->sli4_hba.ue_mask_lo,
9487 						phba->sli4_hba.ue_mask_hi);
9488 				port_error = -ENODEV;
9489 			}
9490 			break;
9491 		case LPFC_SLI_INTF_IF_TYPE_2:
9492 		case LPFC_SLI_INTF_IF_TYPE_6:
9493 			/* Final checks.  The port status should be clean. */
9494 			if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
9495 				&reg_data.word0) ||
9496 				lpfc_sli4_unrecoverable_port(&reg_data)) {
9497 				phba->work_status[0] =
9498 					readl(phba->sli4_hba.u.if_type2.
9499 					      ERR1regaddr);
9500 				phba->work_status[1] =
9501 					readl(phba->sli4_hba.u.if_type2.
9502 					      ERR2regaddr);
9503 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9504 					"2888 Unrecoverable port error "
9505 					"following POST: port status reg "
9506 					"0x%x, port_smphr reg 0x%x, "
9507 					"error 1=0x%x, error 2=0x%x\n",
9508 					reg_data.word0,
9509 					portsmphr_reg.word0,
9510 					phba->work_status[0],
9511 					phba->work_status[1]);
9512 				port_error = -ENODEV;
9513 				break;
9514 			}
9515 
9516 			if (lpfc_pldv_detect &&
9517 			    bf_get(lpfc_sli_intf_sli_family,
9518 				   &phba->sli4_hba.sli_intf) ==
9519 					LPFC_SLI_INTF_FAMILY_G6)
9520 				pci_write_config_byte(phba->pcidev,
9521 						      LPFC_SLI_INTF, CFG_PLD);
9522 			break;
9523 		case LPFC_SLI_INTF_IF_TYPE_1:
9524 		default:
9525 			break;
9526 		}
9527 	}
9528 	return port_error;
9529 }
9530 
9531 /**
9532  * lpfc_sli4_bar0_register_memmap - Set up SLI4 BAR0 register memory map.
9533  * @phba: pointer to lpfc hba data structure.
9534  * @if_type:  The SLI4 interface type getting configured.
9535  *
9536  * This routine is invoked to set up SLI4 BAR0 PCI config space register
9537  * memory map.
9538  **/
9539 static void
9540 lpfc_sli4_bar0_register_memmap(struct lpfc_hba *phba, uint32_t if_type)
9541 {
9542 	switch (if_type) {
9543 	case LPFC_SLI_INTF_IF_TYPE_0:
9544 		phba->sli4_hba.u.if_type0.UERRLOregaddr =
9545 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UERR_STATUS_LO;
9546 		phba->sli4_hba.u.if_type0.UERRHIregaddr =
9547 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UERR_STATUS_HI;
9548 		phba->sli4_hba.u.if_type0.UEMASKLOregaddr =
9549 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UE_MASK_LO;
9550 		phba->sli4_hba.u.if_type0.UEMASKHIregaddr =
9551 			phba->sli4_hba.conf_regs_memmap_p + LPFC_UE_MASK_HI;
9552 		phba->sli4_hba.SLIINTFregaddr =
9553 			phba->sli4_hba.conf_regs_memmap_p + LPFC_SLI_INTF;
9554 		break;
9555 	case LPFC_SLI_INTF_IF_TYPE_2:
9556 		phba->sli4_hba.u.if_type2.EQDregaddr =
9557 			phba->sli4_hba.conf_regs_memmap_p +
9558 						LPFC_CTL_PORT_EQ_DELAY_OFFSET;
9559 		phba->sli4_hba.u.if_type2.ERR1regaddr =
9560 			phba->sli4_hba.conf_regs_memmap_p +
9561 						LPFC_CTL_PORT_ER1_OFFSET;
9562 		phba->sli4_hba.u.if_type2.ERR2regaddr =
9563 			phba->sli4_hba.conf_regs_memmap_p +
9564 						LPFC_CTL_PORT_ER2_OFFSET;
9565 		phba->sli4_hba.u.if_type2.CTRLregaddr =
9566 			phba->sli4_hba.conf_regs_memmap_p +
9567 						LPFC_CTL_PORT_CTL_OFFSET;
9568 		phba->sli4_hba.u.if_type2.STATUSregaddr =
9569 			phba->sli4_hba.conf_regs_memmap_p +
9570 						LPFC_CTL_PORT_STA_OFFSET;
9571 		phba->sli4_hba.SLIINTFregaddr =
9572 			phba->sli4_hba.conf_regs_memmap_p + LPFC_SLI_INTF;
9573 		phba->sli4_hba.PSMPHRregaddr =
9574 			phba->sli4_hba.conf_regs_memmap_p +
9575 						LPFC_CTL_PORT_SEM_OFFSET;
9576 		phba->sli4_hba.RQDBregaddr =
9577 			phba->sli4_hba.conf_regs_memmap_p +
9578 						LPFC_ULP0_RQ_DOORBELL;
9579 		phba->sli4_hba.WQDBregaddr =
9580 			phba->sli4_hba.conf_regs_memmap_p +
9581 						LPFC_ULP0_WQ_DOORBELL;
9582 		phba->sli4_hba.CQDBregaddr =
9583 			phba->sli4_hba.conf_regs_memmap_p + LPFC_EQCQ_DOORBELL;
9584 		phba->sli4_hba.EQDBregaddr = phba->sli4_hba.CQDBregaddr;
9585 		phba->sli4_hba.MQDBregaddr =
9586 			phba->sli4_hba.conf_regs_memmap_p + LPFC_MQ_DOORBELL;
9587 		phba->sli4_hba.BMBXregaddr =
9588 			phba->sli4_hba.conf_regs_memmap_p + LPFC_BMBX;
9589 		break;
9590 	case LPFC_SLI_INTF_IF_TYPE_6:
9591 		phba->sli4_hba.u.if_type2.EQDregaddr =
9592 			phba->sli4_hba.conf_regs_memmap_p +
9593 						LPFC_CTL_PORT_EQ_DELAY_OFFSET;
9594 		phba->sli4_hba.u.if_type2.ERR1regaddr =
9595 			phba->sli4_hba.conf_regs_memmap_p +
9596 						LPFC_CTL_PORT_ER1_OFFSET;
9597 		phba->sli4_hba.u.if_type2.ERR2regaddr =
9598 			phba->sli4_hba.conf_regs_memmap_p +
9599 						LPFC_CTL_PORT_ER2_OFFSET;
9600 		phba->sli4_hba.u.if_type2.CTRLregaddr =
9601 			phba->sli4_hba.conf_regs_memmap_p +
9602 						LPFC_CTL_PORT_CTL_OFFSET;
9603 		phba->sli4_hba.u.if_type2.STATUSregaddr =
9604 			phba->sli4_hba.conf_regs_memmap_p +
9605 						LPFC_CTL_PORT_STA_OFFSET;
9606 		phba->sli4_hba.PSMPHRregaddr =
9607 			phba->sli4_hba.conf_regs_memmap_p +
9608 						LPFC_CTL_PORT_SEM_OFFSET;
9609 		phba->sli4_hba.BMBXregaddr =
9610 			phba->sli4_hba.conf_regs_memmap_p + LPFC_BMBX;
9611 		break;
9612 	case LPFC_SLI_INTF_IF_TYPE_1:
9613 	default:
9614 		dev_printk(KERN_ERR, &phba->pcidev->dev,
9615 			   "FATAL - unsupported SLI4 interface type - %d\n",
9616 			   if_type);
9617 		break;
9618 	}
9619 }
9620 
9621 /**
9622  * lpfc_sli4_bar1_register_memmap - Set up SLI4 BAR1 register memory map.
9623  * @phba: pointer to lpfc hba data structure.
9624  * @if_type: sli if type to operate on.
9625  *
9626  * This routine is invoked to set up SLI4 BAR1 register memory map.
9627  **/
9628 static void
9629 lpfc_sli4_bar1_register_memmap(struct lpfc_hba *phba, uint32_t if_type)
9630 {
9631 	switch (if_type) {
9632 	case LPFC_SLI_INTF_IF_TYPE_0:
9633 		phba->sli4_hba.PSMPHRregaddr =
9634 			phba->sli4_hba.ctrl_regs_memmap_p +
9635 			LPFC_SLIPORT_IF0_SMPHR;
9636 		phba->sli4_hba.ISRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
9637 			LPFC_HST_ISR0;
9638 		phba->sli4_hba.IMRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
9639 			LPFC_HST_IMR0;
9640 		phba->sli4_hba.ISCRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
9641 			LPFC_HST_ISCR0;
9642 		break;
9643 	case LPFC_SLI_INTF_IF_TYPE_6:
9644 		phba->sli4_hba.RQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9645 			LPFC_IF6_RQ_DOORBELL;
9646 		phba->sli4_hba.WQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9647 			LPFC_IF6_WQ_DOORBELL;
9648 		phba->sli4_hba.CQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9649 			LPFC_IF6_CQ_DOORBELL;
9650 		phba->sli4_hba.EQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9651 			LPFC_IF6_EQ_DOORBELL;
9652 		phba->sli4_hba.MQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9653 			LPFC_IF6_MQ_DOORBELL;
9654 		break;
9655 	case LPFC_SLI_INTF_IF_TYPE_2:
9656 	case LPFC_SLI_INTF_IF_TYPE_1:
9657 	default:
9658 		dev_err(&phba->pcidev->dev,
9659 			   "FATAL - unsupported SLI4 interface type - %d\n",
9660 			   if_type);
9661 		break;
9662 	}
9663 }
9664 
9665 /**
9666  * lpfc_sli4_bar2_register_memmap - Set up SLI4 BAR2 register memory map.
9667  * @phba: pointer to lpfc hba data structure.
9668  * @vf: virtual function number
9669  *
9670  * This routine is invoked to set up SLI4 BAR2 doorbell register memory map
9671  * based on the given viftual function number, @vf.
9672  *
9673  * Return 0 if successful, otherwise -ENODEV.
9674  **/
9675 static int
9676 lpfc_sli4_bar2_register_memmap(struct lpfc_hba *phba, uint32_t vf)
9677 {
9678 	if (vf > LPFC_VIR_FUNC_MAX)
9679 		return -ENODEV;
9680 
9681 	phba->sli4_hba.RQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9682 				vf * LPFC_VFR_PAGE_SIZE +
9683 					LPFC_ULP0_RQ_DOORBELL);
9684 	phba->sli4_hba.WQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9685 				vf * LPFC_VFR_PAGE_SIZE +
9686 					LPFC_ULP0_WQ_DOORBELL);
9687 	phba->sli4_hba.CQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9688 				vf * LPFC_VFR_PAGE_SIZE +
9689 					LPFC_EQCQ_DOORBELL);
9690 	phba->sli4_hba.EQDBregaddr = phba->sli4_hba.CQDBregaddr;
9691 	phba->sli4_hba.MQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9692 				vf * LPFC_VFR_PAGE_SIZE + LPFC_MQ_DOORBELL);
9693 	phba->sli4_hba.BMBXregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9694 				vf * LPFC_VFR_PAGE_SIZE + LPFC_BMBX);
9695 	return 0;
9696 }
9697 
9698 /**
9699  * lpfc_create_bootstrap_mbox - Create the bootstrap mailbox
9700  * @phba: pointer to lpfc hba data structure.
9701  *
9702  * This routine is invoked to create the bootstrap mailbox
9703  * region consistent with the SLI-4 interface spec.  This
9704  * routine allocates all memory necessary to communicate
9705  * mailbox commands to the port and sets up all alignment
9706  * needs.  No locks are expected to be held when calling
9707  * this routine.
9708  *
9709  * Return codes
9710  * 	0 - successful
9711  * 	-ENOMEM - could not allocated memory.
9712  **/
9713 static int
9714 lpfc_create_bootstrap_mbox(struct lpfc_hba *phba)
9715 {
9716 	uint32_t bmbx_size;
9717 	struct lpfc_dmabuf *dmabuf;
9718 	struct dma_address *dma_address;
9719 	uint32_t pa_addr;
9720 	uint64_t phys_addr;
9721 
9722 	dmabuf = kzalloc_obj(struct lpfc_dmabuf);
9723 	if (!dmabuf)
9724 		return -ENOMEM;
9725 
9726 	/*
9727 	 * The bootstrap mailbox region is comprised of 2 parts
9728 	 * plus an alignment restriction of 16 bytes.
9729 	 */
9730 	bmbx_size = sizeof(struct lpfc_bmbx_create) + (LPFC_ALIGN_16_BYTE - 1);
9731 	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev, bmbx_size,
9732 					  &dmabuf->phys, GFP_KERNEL);
9733 	if (!dmabuf->virt) {
9734 		kfree(dmabuf);
9735 		return -ENOMEM;
9736 	}
9737 
9738 	/*
9739 	 * Initialize the bootstrap mailbox pointers now so that the register
9740 	 * operations are simple later.  The mailbox dma address is required
9741 	 * to be 16-byte aligned.  Also align the virtual memory as each
9742 	 * mailbox is copied into the bmbx mailbox region before issuing the
9743 	 * command to the port.
9744 	 */
9745 	phba->sli4_hba.bmbx.dmabuf = dmabuf;
9746 	phba->sli4_hba.bmbx.bmbx_size = bmbx_size;
9747 
9748 	phba->sli4_hba.bmbx.avirt = PTR_ALIGN(dmabuf->virt,
9749 					      LPFC_ALIGN_16_BYTE);
9750 	phba->sli4_hba.bmbx.aphys = ALIGN(dmabuf->phys,
9751 					      LPFC_ALIGN_16_BYTE);
9752 
9753 	/*
9754 	 * Set the high and low physical addresses now.  The SLI4 alignment
9755 	 * requirement is 16 bytes and the mailbox is posted to the port
9756 	 * as two 30-bit addresses.  The other data is a bit marking whether
9757 	 * the 30-bit address is the high or low address.
9758 	 * Upcast bmbx aphys to 64bits so shift instruction compiles
9759 	 * clean on 32 bit machines.
9760 	 */
9761 	dma_address = &phba->sli4_hba.bmbx.dma_address;
9762 	phys_addr = (uint64_t)phba->sli4_hba.bmbx.aphys;
9763 	pa_addr = (uint32_t) ((phys_addr >> 34) & 0x3fffffff);
9764 	dma_address->addr_hi = (uint32_t) ((pa_addr << 2) |
9765 					   LPFC_BMBX_BIT1_ADDR_HI);
9766 
9767 	pa_addr = (uint32_t) ((phba->sli4_hba.bmbx.aphys >> 4) & 0x3fffffff);
9768 	dma_address->addr_lo = (uint32_t) ((pa_addr << 2) |
9769 					   LPFC_BMBX_BIT1_ADDR_LO);
9770 	return 0;
9771 }
9772 
9773 /**
9774  * lpfc_destroy_bootstrap_mbox - Destroy all bootstrap mailbox resources
9775  * @phba: pointer to lpfc hba data structure.
9776  *
9777  * This routine is invoked to teardown the bootstrap mailbox
9778  * region and release all host resources. This routine requires
9779  * the caller to ensure all mailbox commands recovered, no
9780  * additional mailbox comands are sent, and interrupts are disabled
9781  * before calling this routine.
9782  *
9783  **/
9784 static void
9785 lpfc_destroy_bootstrap_mbox(struct lpfc_hba *phba)
9786 {
9787 	dma_free_coherent(&phba->pcidev->dev,
9788 			  phba->sli4_hba.bmbx.bmbx_size,
9789 			  phba->sli4_hba.bmbx.dmabuf->virt,
9790 			  phba->sli4_hba.bmbx.dmabuf->phys);
9791 
9792 	kfree(phba->sli4_hba.bmbx.dmabuf);
9793 	memset(&phba->sli4_hba.bmbx, 0, sizeof(struct lpfc_bmbx));
9794 }
9795 
9796 static const char * const lpfc_topo_to_str[] = {
9797 	"Loop then P2P",
9798 	"Loopback",
9799 	"P2P Only",
9800 	"Unsupported",
9801 	"Loop Only",
9802 	"Unsupported",
9803 	"P2P then Loop",
9804 };
9805 
9806 #define	LINK_FLAGS_DEF	0x0
9807 #define	LINK_FLAGS_P2P	0x1
9808 #define	LINK_FLAGS_LOOP	0x2
9809 /**
9810  * lpfc_map_topology - Map the topology read from READ_CONFIG
9811  * @phba: pointer to lpfc hba data structure.
9812  * @rd_config: pointer to read config data
9813  *
9814  * This routine is invoked to map the topology values as read
9815  * from the read config mailbox command. If the persistent
9816  * topology feature is supported, the firmware will provide the
9817  * saved topology information to be used in INIT_LINK
9818  **/
9819 static void
9820 lpfc_map_topology(struct lpfc_hba *phba, struct lpfc_mbx_read_config *rd_config)
9821 {
9822 	u8 ptv, tf, pt;
9823 
9824 	ptv = bf_get(lpfc_mbx_rd_conf_ptv, rd_config);
9825 	tf = bf_get(lpfc_mbx_rd_conf_tf, rd_config);
9826 	pt = bf_get(lpfc_mbx_rd_conf_pt, rd_config);
9827 
9828 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9829 			"2027 Read Config Data : ptv:0x%x, tf:0x%x pt:0x%x",
9830 			 ptv, tf, pt);
9831 	if (!ptv) {
9832 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9833 				"2019 FW does not support persistent topology "
9834 				"Using driver parameter defined value [%s]",
9835 				lpfc_topo_to_str[phba->cfg_topology]);
9836 		return;
9837 	}
9838 	/* FW supports persistent topology - override module parameter value */
9839 	set_bit(HBA_PERSISTENT_TOPO, &phba->hba_flag);
9840 
9841 	/* if ASIC_GEN_NUM >= 0xC) */
9842 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
9843 		    LPFC_SLI_INTF_IF_TYPE_6) ||
9844 	    (bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf) ==
9845 		    LPFC_SLI_INTF_FAMILY_G6)) {
9846 		if (!tf)
9847 			phba->cfg_topology = ((pt == LINK_FLAGS_LOOP)
9848 					? FLAGS_TOPOLOGY_MODE_LOOP
9849 					: FLAGS_TOPOLOGY_MODE_PT_PT);
9850 		else
9851 			clear_bit(HBA_PERSISTENT_TOPO, &phba->hba_flag);
9852 	} else { /* G5 */
9853 		if (tf)
9854 			/* If topology failover set - pt is '0' or '1' */
9855 			phba->cfg_topology = (pt ? FLAGS_TOPOLOGY_MODE_PT_LOOP :
9856 					      FLAGS_TOPOLOGY_MODE_LOOP_PT);
9857 		else
9858 			phba->cfg_topology = ((pt == LINK_FLAGS_P2P)
9859 					? FLAGS_TOPOLOGY_MODE_PT_PT
9860 					: FLAGS_TOPOLOGY_MODE_LOOP);
9861 	}
9862 	if (test_bit(HBA_PERSISTENT_TOPO, &phba->hba_flag))
9863 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9864 				"2020 Using persistent topology value [%s]",
9865 				lpfc_topo_to_str[phba->cfg_topology]);
9866 	else
9867 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9868 				"2021 Invalid topology values from FW "
9869 				"Using driver parameter defined value [%s]",
9870 				lpfc_topo_to_str[phba->cfg_topology]);
9871 }
9872 
9873 /**
9874  * lpfc_sli4_read_config - Get the config parameters.
9875  * @phba: pointer to lpfc hba data structure.
9876  *
9877  * This routine is invoked to read the configuration parameters from the HBA.
9878  * The configuration parameters are used to set the base and maximum values
9879  * for RPI's XRI's VPI's VFI's and FCFIs. These values also affect the resource
9880  * allocation for the port.
9881  *
9882  * Return codes
9883  * 	0 - successful
9884  * 	-ENOMEM - No available memory
9885  *      -EIO - The mailbox failed to complete successfully.
9886  **/
9887 int
9888 lpfc_sli4_read_config(struct lpfc_hba *phba)
9889 {
9890 	LPFC_MBOXQ_t *pmb;
9891 	struct lpfc_mbx_read_config *rd_config;
9892 	union  lpfc_sli4_cfg_shdr *shdr;
9893 	uint32_t shdr_status, shdr_add_status;
9894 	struct lpfc_mbx_get_func_cfg *get_func_cfg;
9895 	struct lpfc_rsrc_desc_fcfcoe *desc;
9896 	char *pdesc_0;
9897 	uint16_t forced_link_speed;
9898 	uint32_t if_type, qmin, fawwpn;
9899 	int length, i, rc = 0, rc2;
9900 
9901 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
9902 	if (!pmb) {
9903 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9904 				"2011 Unable to allocate memory for issuing "
9905 				"SLI_CONFIG_SPECIAL mailbox command\n");
9906 		return -ENOMEM;
9907 	}
9908 
9909 	lpfc_read_config(phba, pmb);
9910 
9911 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
9912 	if (rc != MBX_SUCCESS) {
9913 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9914 				"2012 Mailbox failed , mbxCmd x%x "
9915 				"READ_CONFIG, mbxStatus x%x\n",
9916 				bf_get(lpfc_mqe_command, &pmb->u.mqe),
9917 				bf_get(lpfc_mqe_status, &pmb->u.mqe));
9918 		rc = -EIO;
9919 	} else {
9920 		rd_config = &pmb->u.mqe.un.rd_config;
9921 		if (bf_get(lpfc_mbx_rd_conf_lnk_ldv, rd_config)) {
9922 			phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL;
9923 			phba->sli4_hba.lnk_info.lnk_tp =
9924 				bf_get(lpfc_mbx_rd_conf_lnk_type, rd_config);
9925 			phba->sli4_hba.lnk_info.lnk_no =
9926 				bf_get(lpfc_mbx_rd_conf_lnk_numb, rd_config);
9927 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9928 					"3081 lnk_type:%d, lnk_numb:%d\n",
9929 					phba->sli4_hba.lnk_info.lnk_tp,
9930 					phba->sli4_hba.lnk_info.lnk_no);
9931 		} else
9932 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9933 					"3082 Mailbox (x%x) returned ldv:x0\n",
9934 					bf_get(lpfc_mqe_command, &pmb->u.mqe));
9935 		if (bf_get(lpfc_mbx_rd_conf_bbscn_def, rd_config)) {
9936 			phba->bbcredit_support = 1;
9937 			phba->sli4_hba.bbscn_params.word0 = rd_config->word8;
9938 		}
9939 
9940 		fawwpn = bf_get(lpfc_mbx_rd_conf_fawwpn, rd_config);
9941 
9942 		if (fawwpn) {
9943 			lpfc_printf_log(phba, KERN_INFO,
9944 					LOG_INIT | LOG_DISCOVERY,
9945 					"2702 READ_CONFIG: FA-PWWN is "
9946 					"configured on\n");
9947 			phba->sli4_hba.fawwpn_flag |= LPFC_FAWWPN_CONFIG;
9948 		} else {
9949 			/* Clear FW configured flag, preserve driver flag */
9950 			phba->sli4_hba.fawwpn_flag &= ~LPFC_FAWWPN_CONFIG;
9951 		}
9952 
9953 		phba->sli4_hba.conf_trunk =
9954 			bf_get(lpfc_mbx_rd_conf_trunk, rd_config);
9955 		phba->sli4_hba.extents_in_use =
9956 			bf_get(lpfc_mbx_rd_conf_extnts_inuse, rd_config);
9957 
9958 		phba->sli4_hba.max_cfg_param.max_xri =
9959 			bf_get(lpfc_mbx_rd_conf_xri_count, rd_config);
9960 		/* Reduce resource usage in kdump environment */
9961 		if (is_kdump_kernel() &&
9962 		    phba->sli4_hba.max_cfg_param.max_xri > 512)
9963 			phba->sli4_hba.max_cfg_param.max_xri = 512;
9964 		phba->sli4_hba.max_cfg_param.xri_base =
9965 			bf_get(lpfc_mbx_rd_conf_xri_base, rd_config);
9966 		phba->sli4_hba.max_cfg_param.max_vpi =
9967 			bf_get(lpfc_mbx_rd_conf_vpi_count, rd_config);
9968 		/* Limit the max we support */
9969 		if (phba->sli4_hba.max_cfg_param.max_vpi > LPFC_MAX_VPORTS)
9970 			phba->sli4_hba.max_cfg_param.max_vpi = LPFC_MAX_VPORTS;
9971 		phba->sli4_hba.max_cfg_param.vpi_base =
9972 			bf_get(lpfc_mbx_rd_conf_vpi_base, rd_config);
9973 		phba->sli4_hba.max_cfg_param.max_rpi =
9974 			bf_get(lpfc_mbx_rd_conf_rpi_count, rd_config);
9975 		phba->sli4_hba.max_cfg_param.rpi_base =
9976 			bf_get(lpfc_mbx_rd_conf_rpi_base, rd_config);
9977 		phba->sli4_hba.max_cfg_param.max_vfi =
9978 			bf_get(lpfc_mbx_rd_conf_vfi_count, rd_config);
9979 		phba->sli4_hba.max_cfg_param.vfi_base =
9980 			bf_get(lpfc_mbx_rd_conf_vfi_base, rd_config);
9981 		phba->sli4_hba.max_cfg_param.max_fcfi =
9982 			bf_get(lpfc_mbx_rd_conf_fcfi_count, rd_config);
9983 		phba->sli4_hba.max_cfg_param.max_eq =
9984 			bf_get(lpfc_mbx_rd_conf_eq_count, rd_config);
9985 		phba->sli4_hba.max_cfg_param.max_rq =
9986 			bf_get(lpfc_mbx_rd_conf_rq_count, rd_config);
9987 		phba->sli4_hba.max_cfg_param.max_wq =
9988 			bf_get(lpfc_mbx_rd_conf_wq_count, rd_config);
9989 		phba->sli4_hba.max_cfg_param.max_cq =
9990 			bf_get(lpfc_mbx_rd_conf_cq_count, rd_config);
9991 		phba->lmt = bf_get(lpfc_mbx_rd_conf_lmt, rd_config);
9992 		phba->sli4_hba.next_xri = phba->sli4_hba.max_cfg_param.xri_base;
9993 		phba->vpi_base = phba->sli4_hba.max_cfg_param.vpi_base;
9994 		phba->vfi_base = phba->sli4_hba.max_cfg_param.vfi_base;
9995 		phba->max_vpi = (phba->sli4_hba.max_cfg_param.max_vpi > 0) ?
9996 				(phba->sli4_hba.max_cfg_param.max_vpi - 1) : 0;
9997 		phba->max_vports = phba->max_vpi;
9998 
9999 		if (bf_get(lpfc_mbx_rd_conf_fedif, rd_config))
10000 			phba->sli4_hba.encryption_support = true;
10001 		else
10002 			phba->sli4_hba.encryption_support = false;
10003 
10004 		/* Next decide on FPIN or Signal E2E CGN support
10005 		 * For congestion alarms and warnings valid combination are:
10006 		 * 1. FPIN alarms / FPIN warnings
10007 		 * 2. Signal alarms / Signal warnings
10008 		 * 3. FPIN alarms / Signal warnings
10009 		 * 4. Signal alarms / FPIN warnings
10010 		 *
10011 		 * Initialize the adapter frequency to 100 mSecs
10012 		 */
10013 		phba->cgn_reg_fpin = LPFC_CGN_FPIN_BOTH;
10014 		phba->cgn_reg_signal = EDC_CG_SIG_NOTSUPPORTED;
10015 		phba->cgn_sig_freq = lpfc_fabric_cgn_frequency;
10016 
10017 		if (lpfc_use_cgn_signal) {
10018 			if (bf_get(lpfc_mbx_rd_conf_wcs, rd_config)) {
10019 				phba->cgn_reg_signal = EDC_CG_SIG_WARN_ONLY;
10020 				phba->cgn_reg_fpin &= ~LPFC_CGN_FPIN_WARN;
10021 			}
10022 			if (bf_get(lpfc_mbx_rd_conf_acs, rd_config)) {
10023 				/* MUST support both alarm and warning
10024 				 * because EDC does not support alarm alone.
10025 				 */
10026 				if (phba->cgn_reg_signal !=
10027 				    EDC_CG_SIG_WARN_ONLY) {
10028 					/* Must support both or none */
10029 					phba->cgn_reg_fpin = LPFC_CGN_FPIN_BOTH;
10030 					phba->cgn_reg_signal =
10031 						EDC_CG_SIG_NOTSUPPORTED;
10032 				} else {
10033 					phba->cgn_reg_signal =
10034 						EDC_CG_SIG_WARN_ALARM;
10035 					phba->cgn_reg_fpin =
10036 						LPFC_CGN_FPIN_NONE;
10037 				}
10038 			}
10039 		}
10040 
10041 		/* Set the congestion initial signal and fpin values. */
10042 		phba->cgn_init_reg_fpin = phba->cgn_reg_fpin;
10043 		phba->cgn_init_reg_signal = phba->cgn_reg_signal;
10044 
10045 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
10046 				"6446 READ_CONFIG reg_sig x%x reg_fpin:x%x\n",
10047 				phba->cgn_reg_signal, phba->cgn_reg_fpin);
10048 
10049 		lpfc_map_topology(phba, rd_config);
10050 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10051 				"2003 cfg params Extents? %d "
10052 				"XRI(B:%d M:%d), "
10053 				"VPI(B:%d M:%d) "
10054 				"VFI(B:%d M:%d) "
10055 				"RPI(B:%d M:%d) "
10056 				"FCFI:%d EQ:%d CQ:%d WQ:%d RQ:%d lmt:x%x\n",
10057 				phba->sli4_hba.extents_in_use,
10058 				phba->sli4_hba.max_cfg_param.xri_base,
10059 				phba->sli4_hba.max_cfg_param.max_xri,
10060 				phba->sli4_hba.max_cfg_param.vpi_base,
10061 				phba->sli4_hba.max_cfg_param.max_vpi,
10062 				phba->sli4_hba.max_cfg_param.vfi_base,
10063 				phba->sli4_hba.max_cfg_param.max_vfi,
10064 				phba->sli4_hba.max_cfg_param.rpi_base,
10065 				phba->sli4_hba.max_cfg_param.max_rpi,
10066 				phba->sli4_hba.max_cfg_param.max_fcfi,
10067 				phba->sli4_hba.max_cfg_param.max_eq,
10068 				phba->sli4_hba.max_cfg_param.max_cq,
10069 				phba->sli4_hba.max_cfg_param.max_wq,
10070 				phba->sli4_hba.max_cfg_param.max_rq,
10071 				phba->lmt);
10072 
10073 		/*
10074 		 * Calculate queue resources based on how
10075 		 * many WQ/CQ/EQs are available.
10076 		 */
10077 		qmin = phba->sli4_hba.max_cfg_param.max_wq;
10078 		if (phba->sli4_hba.max_cfg_param.max_cq < qmin)
10079 			qmin = phba->sli4_hba.max_cfg_param.max_cq;
10080 		/*
10081 		 * Reserve 4 (ELS, NVME LS, MBOX, plus one extra) and
10082 		 * the remainder can be used for NVME / FCP.
10083 		 */
10084 		qmin -= 4;
10085 		if (phba->sli4_hba.max_cfg_param.max_eq < qmin)
10086 			qmin = phba->sli4_hba.max_cfg_param.max_eq;
10087 
10088 		/* Check to see if there is enough for default cfg */
10089 		if ((phba->cfg_irq_chann > qmin) ||
10090 		    (phba->cfg_hdw_queue > qmin)) {
10091 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10092 					"2005 Reducing Queues - "
10093 					"FW resource limitation: "
10094 					"WQ %d CQ %d EQ %d: min %d: "
10095 					"IRQ %d HDWQ %d\n",
10096 					phba->sli4_hba.max_cfg_param.max_wq,
10097 					phba->sli4_hba.max_cfg_param.max_cq,
10098 					phba->sli4_hba.max_cfg_param.max_eq,
10099 					qmin, phba->cfg_irq_chann,
10100 					phba->cfg_hdw_queue);
10101 
10102 			if (phba->cfg_irq_chann > qmin)
10103 				phba->cfg_irq_chann = qmin;
10104 			if (phba->cfg_hdw_queue > qmin)
10105 				phba->cfg_hdw_queue = qmin;
10106 		}
10107 	}
10108 
10109 	if (rc)
10110 		goto read_cfg_out;
10111 
10112 	/* Update link speed if forced link speed is supported */
10113 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
10114 	if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
10115 		forced_link_speed =
10116 			bf_get(lpfc_mbx_rd_conf_link_speed, rd_config);
10117 		if (forced_link_speed) {
10118 			set_bit(HBA_FORCED_LINK_SPEED, &phba->hba_flag);
10119 
10120 			switch (forced_link_speed) {
10121 			case LINK_SPEED_1G:
10122 				phba->cfg_link_speed =
10123 					LPFC_USER_LINK_SPEED_1G;
10124 				break;
10125 			case LINK_SPEED_2G:
10126 				phba->cfg_link_speed =
10127 					LPFC_USER_LINK_SPEED_2G;
10128 				break;
10129 			case LINK_SPEED_4G:
10130 				phba->cfg_link_speed =
10131 					LPFC_USER_LINK_SPEED_4G;
10132 				break;
10133 			case LINK_SPEED_8G:
10134 				phba->cfg_link_speed =
10135 					LPFC_USER_LINK_SPEED_8G;
10136 				break;
10137 			case LINK_SPEED_10G:
10138 				phba->cfg_link_speed =
10139 					LPFC_USER_LINK_SPEED_10G;
10140 				break;
10141 			case LINK_SPEED_16G:
10142 				phba->cfg_link_speed =
10143 					LPFC_USER_LINK_SPEED_16G;
10144 				break;
10145 			case LINK_SPEED_32G:
10146 				phba->cfg_link_speed =
10147 					LPFC_USER_LINK_SPEED_32G;
10148 				break;
10149 			case LINK_SPEED_64G:
10150 				phba->cfg_link_speed =
10151 					LPFC_USER_LINK_SPEED_64G;
10152 				break;
10153 			case LINK_SPEED_128G:
10154 				phba->cfg_link_speed =
10155 					LPFC_USER_LINK_SPEED_128G;
10156 				break;
10157 			case 0xffff:
10158 				phba->cfg_link_speed =
10159 					LPFC_USER_LINK_SPEED_AUTO;
10160 				break;
10161 			default:
10162 				lpfc_printf_log(phba, KERN_ERR,
10163 						LOG_TRACE_EVENT,
10164 						"0047 Unrecognized link "
10165 						"speed : %d\n",
10166 						forced_link_speed);
10167 				phba->cfg_link_speed =
10168 					LPFC_USER_LINK_SPEED_AUTO;
10169 			}
10170 		}
10171 	}
10172 
10173 	/* Reset the DFT_HBA_Q_DEPTH to the max xri  */
10174 	length = phba->sli4_hba.max_cfg_param.max_xri -
10175 			lpfc_sli4_get_els_iocb_cnt(phba);
10176 	if (phba->cfg_hba_queue_depth > length) {
10177 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
10178 				"3361 HBA queue depth changed from %d to %d\n",
10179 				phba->cfg_hba_queue_depth, length);
10180 		phba->cfg_hba_queue_depth = length;
10181 	}
10182 
10183 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) <
10184 	    LPFC_SLI_INTF_IF_TYPE_2)
10185 		goto read_cfg_out;
10186 
10187 	/* get the pf# and vf# for SLI4 if_type 2 port */
10188 	length = (sizeof(struct lpfc_mbx_get_func_cfg) -
10189 		  sizeof(struct lpfc_sli4_cfg_mhdr));
10190 	lpfc_sli4_config(phba, pmb, LPFC_MBOX_SUBSYSTEM_COMMON,
10191 			 LPFC_MBOX_OPCODE_GET_FUNCTION_CONFIG,
10192 			 length, LPFC_SLI4_MBX_EMBED);
10193 
10194 	rc2 = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
10195 	shdr = (union lpfc_sli4_cfg_shdr *)
10196 				&pmb->u.mqe.un.sli4_config.header.cfg_shdr;
10197 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
10198 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
10199 	if (rc2 || shdr_status || shdr_add_status) {
10200 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10201 				"3026 Mailbox failed , mbxCmd x%x "
10202 				"GET_FUNCTION_CONFIG, mbxStatus x%x\n",
10203 				bf_get(lpfc_mqe_command, &pmb->u.mqe),
10204 				bf_get(lpfc_mqe_status, &pmb->u.mqe));
10205 		goto read_cfg_out;
10206 	}
10207 
10208 	/* search for fc_fcoe resource descriptor */
10209 	get_func_cfg = &pmb->u.mqe.un.get_func_cfg;
10210 
10211 	pdesc_0 = (char *)&get_func_cfg->func_cfg.desc[0];
10212 	desc = (struct lpfc_rsrc_desc_fcfcoe *)pdesc_0;
10213 	length = bf_get(lpfc_rsrc_desc_fcfcoe_length, desc);
10214 	if (length == LPFC_RSRC_DESC_TYPE_FCFCOE_V0_RSVD)
10215 		length = LPFC_RSRC_DESC_TYPE_FCFCOE_V0_LENGTH;
10216 	else if (length != LPFC_RSRC_DESC_TYPE_FCFCOE_V1_LENGTH)
10217 		goto read_cfg_out;
10218 
10219 	for (i = 0; i < LPFC_RSRC_DESC_MAX_NUM; i++) {
10220 		desc = (struct lpfc_rsrc_desc_fcfcoe *)(pdesc_0 + length * i);
10221 		if (LPFC_RSRC_DESC_TYPE_FCFCOE ==
10222 		    bf_get(lpfc_rsrc_desc_fcfcoe_type, desc)) {
10223 			phba->sli4_hba.iov.pf_number =
10224 				bf_get(lpfc_rsrc_desc_fcfcoe_pfnum, desc);
10225 			phba->sli4_hba.iov.vf_number =
10226 				bf_get(lpfc_rsrc_desc_fcfcoe_vfnum, desc);
10227 			break;
10228 		}
10229 	}
10230 
10231 	if (i < LPFC_RSRC_DESC_MAX_NUM)
10232 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10233 				"3027 GET_FUNCTION_CONFIG: pf_number:%d, "
10234 				"vf_number:%d\n", phba->sli4_hba.iov.pf_number,
10235 				phba->sli4_hba.iov.vf_number);
10236 	else
10237 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10238 				"3028 GET_FUNCTION_CONFIG: failed to find "
10239 				"Resource Descriptor:x%x\n",
10240 				LPFC_RSRC_DESC_TYPE_FCFCOE);
10241 
10242 read_cfg_out:
10243 	mempool_free(pmb, phba->mbox_mem_pool);
10244 	return rc;
10245 }
10246 
10247 /**
10248  * lpfc_setup_endian_order - Write endian order to an SLI4 if_type 0 port.
10249  * @phba: pointer to lpfc hba data structure.
10250  *
10251  * This routine is invoked to setup the port-side endian order when
10252  * the port if_type is 0.  This routine has no function for other
10253  * if_types.
10254  *
10255  * Return codes
10256  * 	0 - successful
10257  * 	-ENOMEM - No available memory
10258  *      -EIO - The mailbox failed to complete successfully.
10259  **/
10260 static int
10261 lpfc_setup_endian_order(struct lpfc_hba *phba)
10262 {
10263 	LPFC_MBOXQ_t *mboxq;
10264 	uint32_t if_type, rc = 0;
10265 	uint32_t endian_mb_data[2] = {HOST_ENDIAN_LOW_WORD0,
10266 				      HOST_ENDIAN_HIGH_WORD1};
10267 
10268 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
10269 	switch (if_type) {
10270 	case LPFC_SLI_INTF_IF_TYPE_0:
10271 		mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
10272 						       GFP_KERNEL);
10273 		if (!mboxq) {
10274 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10275 					"0492 Unable to allocate memory for "
10276 					"issuing SLI_CONFIG_SPECIAL mailbox "
10277 					"command\n");
10278 			return -ENOMEM;
10279 		}
10280 
10281 		/*
10282 		 * The SLI4_CONFIG_SPECIAL mailbox command requires the first
10283 		 * two words to contain special data values and no other data.
10284 		 */
10285 		memset(mboxq, 0, sizeof(LPFC_MBOXQ_t));
10286 		memcpy(&mboxq->u.mqe, &endian_mb_data, sizeof(endian_mb_data));
10287 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
10288 		if (rc != MBX_SUCCESS) {
10289 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10290 					"0493 SLI_CONFIG_SPECIAL mailbox "
10291 					"failed with status x%x\n",
10292 					rc);
10293 			rc = -EIO;
10294 		}
10295 		mempool_free(mboxq, phba->mbox_mem_pool);
10296 		break;
10297 	case LPFC_SLI_INTF_IF_TYPE_6:
10298 	case LPFC_SLI_INTF_IF_TYPE_2:
10299 	case LPFC_SLI_INTF_IF_TYPE_1:
10300 	default:
10301 		break;
10302 	}
10303 	return rc;
10304 }
10305 
10306 /**
10307  * lpfc_sli4_queue_verify - Verify and update EQ counts
10308  * @phba: pointer to lpfc hba data structure.
10309  *
10310  * This routine is invoked to check the user settable queue counts for EQs.
10311  * After this routine is called the counts will be set to valid values that
10312  * adhere to the constraints of the system's interrupt vectors and the port's
10313  * queue resources.
10314  *
10315  * Return codes
10316  *      0 - successful
10317  *      -ENOMEM - No available memory
10318  **/
10319 static int
10320 lpfc_sli4_queue_verify(struct lpfc_hba *phba)
10321 {
10322 	/*
10323 	 * Sanity check for configured queue parameters against the run-time
10324 	 * device parameters
10325 	 */
10326 
10327 	if (phba->nvmet_support) {
10328 		if (phba->cfg_hdw_queue < phba->cfg_nvmet_mrq)
10329 			phba->cfg_nvmet_mrq = phba->cfg_hdw_queue;
10330 		if (phba->cfg_nvmet_mrq > LPFC_NVMET_MRQ_MAX)
10331 			phba->cfg_nvmet_mrq = LPFC_NVMET_MRQ_MAX;
10332 	}
10333 
10334 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10335 			"2574 IO channels: hdwQ %d IRQ %d MRQ: %d\n",
10336 			phba->cfg_hdw_queue, phba->cfg_irq_chann,
10337 			phba->cfg_nvmet_mrq);
10338 
10339 	/* Get EQ depth from module parameter, fake the default for now */
10340 	phba->sli4_hba.eq_esize = LPFC_EQE_SIZE_4B;
10341 	phba->sli4_hba.eq_ecount = LPFC_EQE_DEF_COUNT;
10342 
10343 	/* Get CQ depth from module parameter, fake the default for now */
10344 	phba->sli4_hba.cq_esize = LPFC_CQE_SIZE;
10345 	phba->sli4_hba.cq_ecount = LPFC_CQE_DEF_COUNT;
10346 	return 0;
10347 }
10348 
10349 static int
10350 lpfc_alloc_io_wq_cq(struct lpfc_hba *phba, int idx)
10351 {
10352 	struct lpfc_queue *qdesc;
10353 	u32 wqesize;
10354 	int cpu;
10355 
10356 	cpu = lpfc_find_cpu_handle(phba, idx, LPFC_FIND_BY_HDWQ);
10357 	/* Create Fast Path IO CQs */
10358 	if (phba->enab_exp_wqcq_pages)
10359 		/* Increase the CQ size when WQEs contain an embedded cdb */
10360 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_EXPANDED_PAGE_SIZE,
10361 					      phba->sli4_hba.cq_esize,
10362 					      LPFC_CQE_EXP_COUNT, cpu);
10363 
10364 	else
10365 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10366 					      phba->sli4_hba.cq_esize,
10367 					      phba->sli4_hba.cq_ecount, cpu);
10368 	if (!qdesc) {
10369 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10370 				"0499 Failed allocate fast-path IO CQ (%d)\n",
10371 				idx);
10372 		return 1;
10373 	}
10374 	qdesc->qe_valid = 1;
10375 	qdesc->hdwq = idx;
10376 	qdesc->chann = cpu;
10377 	phba->sli4_hba.hdwq[idx].io_cq = qdesc;
10378 
10379 	/* Create Fast Path IO WQs */
10380 	if (phba->enab_exp_wqcq_pages) {
10381 		/* Increase the WQ size when WQEs contain an embedded cdb */
10382 		wqesize = (phba->fcp_embed_io) ?
10383 			LPFC_WQE128_SIZE : phba->sli4_hba.wq_esize;
10384 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_EXPANDED_PAGE_SIZE,
10385 					      wqesize,
10386 					      LPFC_WQE_EXP_COUNT, cpu);
10387 	} else
10388 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10389 					      phba->sli4_hba.wq_esize,
10390 					      phba->sli4_hba.wq_ecount, cpu);
10391 
10392 	if (!qdesc) {
10393 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10394 				"0503 Failed allocate fast-path IO WQ (%d)\n",
10395 				idx);
10396 		return 1;
10397 	}
10398 	qdesc->hdwq = idx;
10399 	qdesc->chann = cpu;
10400 	phba->sli4_hba.hdwq[idx].io_wq = qdesc;
10401 	list_add_tail(&qdesc->wq_list, &phba->sli4_hba.lpfc_wq_list);
10402 	return 0;
10403 }
10404 
10405 /**
10406  * lpfc_sli4_queue_create - Create all the SLI4 queues
10407  * @phba: pointer to lpfc hba data structure.
10408  *
10409  * This routine is invoked to allocate all the SLI4 queues for the FCoE HBA
10410  * operation. For each SLI4 queue type, the parameters such as queue entry
10411  * count (queue depth) shall be taken from the module parameter. For now,
10412  * we just use some constant number as place holder.
10413  *
10414  * Return codes
10415  *      0 - successful
10416  *      -ENOMEM - No available memory
10417  *      -EIO - The mailbox failed to complete successfully.
10418  **/
10419 int
10420 lpfc_sli4_queue_create(struct lpfc_hba *phba)
10421 {
10422 	struct lpfc_queue *qdesc;
10423 	int idx, cpu, eqcpu;
10424 	struct lpfc_sli4_hdw_queue *qp;
10425 	struct lpfc_vector_map_info *cpup;
10426 	struct lpfc_vector_map_info *eqcpup;
10427 	struct lpfc_eq_intr_info *eqi;
10428 	u32 wqesize;
10429 
10430 	/*
10431 	 * Create HBA Record arrays.
10432 	 * Both NVME and FCP will share that same vectors / EQs
10433 	 */
10434 	phba->sli4_hba.mq_esize = LPFC_MQE_SIZE;
10435 	phba->sli4_hba.mq_ecount = LPFC_MQE_DEF_COUNT;
10436 	phba->sli4_hba.wq_esize = LPFC_WQE_SIZE;
10437 	phba->sli4_hba.wq_ecount = LPFC_WQE_DEF_COUNT;
10438 	phba->sli4_hba.rq_esize = LPFC_RQE_SIZE;
10439 	phba->sli4_hba.rq_ecount = LPFC_RQE_DEF_COUNT;
10440 	phba->sli4_hba.eq_esize = LPFC_EQE_SIZE_4B;
10441 	phba->sli4_hba.eq_ecount = LPFC_EQE_DEF_COUNT;
10442 	phba->sli4_hba.cq_esize = LPFC_CQE_SIZE;
10443 	phba->sli4_hba.cq_ecount = LPFC_CQE_DEF_COUNT;
10444 
10445 	if (!phba->sli4_hba.hdwq) {
10446 		phba->sli4_hba.hdwq = kzalloc_objs(struct lpfc_sli4_hdw_queue,
10447 						   phba->cfg_hdw_queue);
10448 		if (!phba->sli4_hba.hdwq) {
10449 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10450 					"6427 Failed allocate memory for "
10451 					"fast-path Hardware Queue array\n");
10452 			goto out_error;
10453 		}
10454 		/* Prepare hardware queues to take IO buffers */
10455 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10456 			qp = &phba->sli4_hba.hdwq[idx];
10457 			spin_lock_init(&qp->io_buf_list_get_lock);
10458 			spin_lock_init(&qp->io_buf_list_put_lock);
10459 			INIT_LIST_HEAD(&qp->lpfc_io_buf_list_get);
10460 			INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
10461 			qp->get_io_bufs = 0;
10462 			qp->put_io_bufs = 0;
10463 			qp->total_io_bufs = 0;
10464 			spin_lock_init(&qp->abts_io_buf_list_lock);
10465 			INIT_LIST_HEAD(&qp->lpfc_abts_io_buf_list);
10466 			qp->abts_scsi_io_bufs = 0;
10467 			qp->abts_nvme_io_bufs = 0;
10468 			INIT_LIST_HEAD(&qp->sgl_list);
10469 			INIT_LIST_HEAD(&qp->cmd_rsp_buf_list);
10470 			spin_lock_init(&qp->hdwq_lock);
10471 		}
10472 	}
10473 
10474 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
10475 		if (phba->nvmet_support) {
10476 			phba->sli4_hba.nvmet_cqset = kzalloc_objs(struct lpfc_queue *,
10477 								  phba->cfg_nvmet_mrq);
10478 			if (!phba->sli4_hba.nvmet_cqset) {
10479 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10480 					"3121 Fail allocate memory for "
10481 					"fast-path CQ set array\n");
10482 				goto out_error;
10483 			}
10484 			phba->sli4_hba.nvmet_mrq_hdr = kzalloc_objs(struct lpfc_queue *,
10485 								    phba->cfg_nvmet_mrq);
10486 			if (!phba->sli4_hba.nvmet_mrq_hdr) {
10487 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10488 					"3122 Fail allocate memory for "
10489 					"fast-path RQ set hdr array\n");
10490 				goto out_error;
10491 			}
10492 			phba->sli4_hba.nvmet_mrq_data = kzalloc_objs(struct lpfc_queue *,
10493 								     phba->cfg_nvmet_mrq);
10494 			if (!phba->sli4_hba.nvmet_mrq_data) {
10495 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10496 					"3124 Fail allocate memory for "
10497 					"fast-path RQ set data array\n");
10498 				goto out_error;
10499 			}
10500 		}
10501 	}
10502 
10503 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_wq_list);
10504 
10505 	/* Create HBA Event Queues (EQs) */
10506 	for_each_present_cpu(cpu) {
10507 		/* We only want to create 1 EQ per vector, even though
10508 		 * multiple CPUs might be using that vector. so only
10509 		 * selects the CPUs that are LPFC_CPU_FIRST_IRQ.
10510 		 */
10511 		cpup = &phba->sli4_hba.cpu_map[cpu];
10512 		if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
10513 			continue;
10514 
10515 		/* Get a ptr to the Hardware Queue associated with this CPU */
10516 		qp = &phba->sli4_hba.hdwq[cpup->hdwq];
10517 
10518 		/* Allocate an EQ */
10519 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10520 					      phba->sli4_hba.eq_esize,
10521 					      phba->sli4_hba.eq_ecount, cpu);
10522 		if (!qdesc) {
10523 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10524 					"0497 Failed allocate EQ (%d)\n",
10525 					cpup->hdwq);
10526 			goto out_error;
10527 		}
10528 		qdesc->qe_valid = 1;
10529 		qdesc->hdwq = cpup->hdwq;
10530 		qdesc->chann = cpu; /* First CPU this EQ is affinitized to */
10531 		qdesc->last_cpu = qdesc->chann;
10532 
10533 		/* Save the allocated EQ in the Hardware Queue */
10534 		qp->hba_eq = qdesc;
10535 
10536 		eqi = per_cpu_ptr(phba->sli4_hba.eq_info, qdesc->last_cpu);
10537 		list_add(&qdesc->cpu_list, &eqi->list);
10538 	}
10539 
10540 	/* Now we need to populate the other Hardware Queues, that share
10541 	 * an IRQ vector, with the associated EQ ptr.
10542 	 */
10543 	for_each_present_cpu(cpu) {
10544 		cpup = &phba->sli4_hba.cpu_map[cpu];
10545 
10546 		/* Check for EQ already allocated in previous loop */
10547 		if (cpup->flag & LPFC_CPU_FIRST_IRQ)
10548 			continue;
10549 
10550 		/* Check for multiple CPUs per hdwq */
10551 		qp = &phba->sli4_hba.hdwq[cpup->hdwq];
10552 		if (qp->hba_eq)
10553 			continue;
10554 
10555 		/* We need to share an EQ for this hdwq */
10556 		eqcpu = lpfc_find_cpu_handle(phba, cpup->eq, LPFC_FIND_BY_EQ);
10557 		eqcpup = &phba->sli4_hba.cpu_map[eqcpu];
10558 		qp->hba_eq = phba->sli4_hba.hdwq[eqcpup->hdwq].hba_eq;
10559 	}
10560 
10561 	/* Allocate IO Path SLI4 CQ/WQs */
10562 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10563 		if (lpfc_alloc_io_wq_cq(phba, idx))
10564 			goto out_error;
10565 	}
10566 
10567 	if (phba->nvmet_support) {
10568 		for (idx = 0; idx < phba->cfg_nvmet_mrq; idx++) {
10569 			cpu = lpfc_find_cpu_handle(phba, idx,
10570 						   LPFC_FIND_BY_HDWQ);
10571 			qdesc = lpfc_sli4_queue_alloc(phba,
10572 						      LPFC_DEFAULT_PAGE_SIZE,
10573 						      phba->sli4_hba.cq_esize,
10574 						      phba->sli4_hba.cq_ecount,
10575 						      cpu);
10576 			if (!qdesc) {
10577 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10578 						"3142 Failed allocate NVME "
10579 						"CQ Set (%d)\n", idx);
10580 				goto out_error;
10581 			}
10582 			qdesc->qe_valid = 1;
10583 			qdesc->hdwq = idx;
10584 			qdesc->chann = cpu;
10585 			phba->sli4_hba.nvmet_cqset[idx] = qdesc;
10586 		}
10587 	}
10588 
10589 	/*
10590 	 * Create Slow Path Completion Queues (CQs)
10591 	 */
10592 
10593 	cpu = lpfc_find_cpu_handle(phba, 0, LPFC_FIND_BY_EQ);
10594 	/* Create slow-path Mailbox Command Complete Queue */
10595 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10596 				      phba->sli4_hba.cq_esize,
10597 				      phba->sli4_hba.cq_ecount, cpu);
10598 	if (!qdesc) {
10599 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10600 				"0500 Failed allocate slow-path mailbox CQ\n");
10601 		goto out_error;
10602 	}
10603 	qdesc->qe_valid = 1;
10604 	phba->sli4_hba.mbx_cq = qdesc;
10605 
10606 	/* Create slow-path ELS Complete Queue */
10607 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10608 				      phba->sli4_hba.cq_esize,
10609 				      phba->sli4_hba.cq_ecount, cpu);
10610 	if (!qdesc) {
10611 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10612 				"0501 Failed allocate slow-path ELS CQ\n");
10613 		goto out_error;
10614 	}
10615 	qdesc->qe_valid = 1;
10616 	qdesc->chann = cpu;
10617 	phba->sli4_hba.els_cq = qdesc;
10618 
10619 
10620 	/*
10621 	 * Create Slow Path Work Queues (WQs)
10622 	 */
10623 
10624 	/* Create Mailbox Command Queue */
10625 
10626 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10627 				      phba->sli4_hba.mq_esize,
10628 				      phba->sli4_hba.mq_ecount, cpu);
10629 	if (!qdesc) {
10630 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10631 				"0505 Failed allocate slow-path MQ\n");
10632 		goto out_error;
10633 	}
10634 	qdesc->chann = cpu;
10635 	phba->sli4_hba.mbx_wq = qdesc;
10636 
10637 	/*
10638 	 * Create ELS Work Queues
10639 	 */
10640 
10641 	/*
10642 	 * Create slow-path ELS Work Queue.
10643 	 * Increase the ELS WQ size when WQEs contain an embedded cdb
10644 	 */
10645 	wqesize = (phba->fcp_embed_io) ?
10646 			LPFC_WQE128_SIZE : phba->sli4_hba.wq_esize;
10647 
10648 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10649 				      wqesize,
10650 				      phba->sli4_hba.wq_ecount, cpu);
10651 	if (!qdesc) {
10652 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10653 				"0504 Failed allocate slow-path ELS WQ\n");
10654 		goto out_error;
10655 	}
10656 	qdesc->chann = cpu;
10657 	phba->sli4_hba.els_wq = qdesc;
10658 	list_add_tail(&qdesc->wq_list, &phba->sli4_hba.lpfc_wq_list);
10659 
10660 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
10661 		/* Create NVME LS Complete Queue */
10662 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10663 					      phba->sli4_hba.cq_esize,
10664 					      phba->sli4_hba.cq_ecount, cpu);
10665 		if (!qdesc) {
10666 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10667 					"6079 Failed allocate NVME LS CQ\n");
10668 			goto out_error;
10669 		}
10670 		qdesc->chann = cpu;
10671 		qdesc->qe_valid = 1;
10672 		phba->sli4_hba.nvmels_cq = qdesc;
10673 
10674 		/* Create NVME LS Work Queue */
10675 		qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10676 					      phba->sli4_hba.wq_esize,
10677 					      phba->sli4_hba.wq_ecount, cpu);
10678 		if (!qdesc) {
10679 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10680 					"6080 Failed allocate NVME LS WQ\n");
10681 			goto out_error;
10682 		}
10683 		qdesc->chann = cpu;
10684 		phba->sli4_hba.nvmels_wq = qdesc;
10685 		list_add_tail(&qdesc->wq_list, &phba->sli4_hba.lpfc_wq_list);
10686 	}
10687 
10688 	/*
10689 	 * Create Receive Queue (RQ)
10690 	 */
10691 
10692 	/* Create Receive Queue for header */
10693 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10694 				      phba->sli4_hba.rq_esize,
10695 				      phba->sli4_hba.rq_ecount, cpu);
10696 	if (!qdesc) {
10697 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10698 				"0506 Failed allocate receive HRQ\n");
10699 		goto out_error;
10700 	}
10701 	phba->sli4_hba.hdr_rq = qdesc;
10702 
10703 	/* Create Receive Queue for data */
10704 	qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10705 				      phba->sli4_hba.rq_esize,
10706 				      phba->sli4_hba.rq_ecount, cpu);
10707 	if (!qdesc) {
10708 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10709 				"0507 Failed allocate receive DRQ\n");
10710 		goto out_error;
10711 	}
10712 	phba->sli4_hba.dat_rq = qdesc;
10713 
10714 	if ((phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) &&
10715 	    phba->nvmet_support) {
10716 		for (idx = 0; idx < phba->cfg_nvmet_mrq; idx++) {
10717 			cpu = lpfc_find_cpu_handle(phba, idx,
10718 						   LPFC_FIND_BY_HDWQ);
10719 			/* Create NVMET Receive Queue for header */
10720 			qdesc = lpfc_sli4_queue_alloc(phba,
10721 						      LPFC_DEFAULT_PAGE_SIZE,
10722 						      phba->sli4_hba.rq_esize,
10723 						      LPFC_NVMET_RQE_DEF_COUNT,
10724 						      cpu);
10725 			if (!qdesc) {
10726 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10727 						"3146 Failed allocate "
10728 						"receive HRQ\n");
10729 				goto out_error;
10730 			}
10731 			qdesc->hdwq = idx;
10732 			phba->sli4_hba.nvmet_mrq_hdr[idx] = qdesc;
10733 
10734 			/* Only needed for header of RQ pair */
10735 			qdesc->rqbp = kzalloc_node(sizeof(*qdesc->rqbp),
10736 						   GFP_KERNEL,
10737 						   cpu_to_node(cpu));
10738 			if (qdesc->rqbp == NULL) {
10739 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10740 						"6131 Failed allocate "
10741 						"Header RQBP\n");
10742 				goto out_error;
10743 			}
10744 
10745 			/* Put list in known state in case driver load fails. */
10746 			INIT_LIST_HEAD(&qdesc->rqbp->rqb_buffer_list);
10747 
10748 			/* Create NVMET Receive Queue for data */
10749 			qdesc = lpfc_sli4_queue_alloc(phba,
10750 						      LPFC_DEFAULT_PAGE_SIZE,
10751 						      phba->sli4_hba.rq_esize,
10752 						      LPFC_NVMET_RQE_DEF_COUNT,
10753 						      cpu);
10754 			if (!qdesc) {
10755 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10756 						"3156 Failed allocate "
10757 						"receive DRQ\n");
10758 				goto out_error;
10759 			}
10760 			qdesc->hdwq = idx;
10761 			phba->sli4_hba.nvmet_mrq_data[idx] = qdesc;
10762 		}
10763 	}
10764 
10765 	/* Clear NVME stats */
10766 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
10767 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10768 			memset(&phba->sli4_hba.hdwq[idx].nvme_cstat, 0,
10769 			       sizeof(phba->sli4_hba.hdwq[idx].nvme_cstat));
10770 		}
10771 	}
10772 
10773 	/* Clear SCSI stats */
10774 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP) {
10775 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10776 			memset(&phba->sli4_hba.hdwq[idx].scsi_cstat, 0,
10777 			       sizeof(phba->sli4_hba.hdwq[idx].scsi_cstat));
10778 		}
10779 	}
10780 
10781 	return 0;
10782 
10783 out_error:
10784 	lpfc_sli4_queue_destroy(phba);
10785 	return -ENOMEM;
10786 }
10787 
10788 static inline void
10789 __lpfc_sli4_release_queue(struct lpfc_queue **qp)
10790 {
10791 	if (*qp != NULL) {
10792 		lpfc_sli4_queue_free(*qp);
10793 		*qp = NULL;
10794 	}
10795 }
10796 
10797 static inline void
10798 lpfc_sli4_release_queues(struct lpfc_queue ***qs, int max)
10799 {
10800 	int idx;
10801 
10802 	if (*qs == NULL)
10803 		return;
10804 
10805 	for (idx = 0; idx < max; idx++)
10806 		__lpfc_sli4_release_queue(&(*qs)[idx]);
10807 
10808 	kfree(*qs);
10809 	*qs = NULL;
10810 }
10811 
10812 static inline void
10813 lpfc_sli4_release_hdwq(struct lpfc_hba *phba)
10814 {
10815 	struct lpfc_sli4_hdw_queue *hdwq;
10816 	struct lpfc_queue *eq;
10817 	uint32_t idx;
10818 
10819 	hdwq = phba->sli4_hba.hdwq;
10820 
10821 	/* Loop thru all Hardware Queues */
10822 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10823 		/* Free the CQ/WQ corresponding to the Hardware Queue */
10824 		lpfc_sli4_queue_free(hdwq[idx].io_cq);
10825 		lpfc_sli4_queue_free(hdwq[idx].io_wq);
10826 		hdwq[idx].hba_eq = NULL;
10827 		hdwq[idx].io_cq = NULL;
10828 		hdwq[idx].io_wq = NULL;
10829 		if (phba->cfg_xpsgl && !phba->nvmet_support)
10830 			lpfc_free_sgl_per_hdwq(phba, &hdwq[idx]);
10831 		lpfc_free_cmd_rsp_buf_per_hdwq(phba, &hdwq[idx]);
10832 	}
10833 	/* Loop thru all IRQ vectors */
10834 	for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
10835 		/* Free the EQ corresponding to the IRQ vector */
10836 		eq = phba->sli4_hba.hba_eq_hdl[idx].eq;
10837 		lpfc_sli4_queue_free(eq);
10838 		phba->sli4_hba.hba_eq_hdl[idx].eq = NULL;
10839 	}
10840 }
10841 
10842 /**
10843  * lpfc_sli4_queue_destroy - Destroy all the SLI4 queues
10844  * @phba: pointer to lpfc hba data structure.
10845  *
10846  * This routine is invoked to release all the SLI4 queues with the FCoE HBA
10847  * operation.
10848  *
10849  * Return codes
10850  *      0 - successful
10851  *      -ENOMEM - No available memory
10852  *      -EIO - The mailbox failed to complete successfully.
10853  **/
10854 void
10855 lpfc_sli4_queue_destroy(struct lpfc_hba *phba)
10856 {
10857 	/*
10858 	 * Set FREE_INIT before beginning to free the queues.
10859 	 * Wait until the users of queues to acknowledge to
10860 	 * release queues by clearing FREE_WAIT.
10861 	 */
10862 	spin_lock_irq(&phba->hbalock);
10863 	phba->sli.sli_flag |= LPFC_QUEUE_FREE_INIT;
10864 	while (phba->sli.sli_flag & LPFC_QUEUE_FREE_WAIT) {
10865 		spin_unlock_irq(&phba->hbalock);
10866 		msleep(20);
10867 		spin_lock_irq(&phba->hbalock);
10868 	}
10869 	spin_unlock_irq(&phba->hbalock);
10870 
10871 	lpfc_sli4_cleanup_poll_list(phba);
10872 
10873 	/* Release HBA eqs */
10874 	if (phba->sli4_hba.hdwq)
10875 		lpfc_sli4_release_hdwq(phba);
10876 
10877 	if (phba->nvmet_support) {
10878 		lpfc_sli4_release_queues(&phba->sli4_hba.nvmet_cqset,
10879 					 phba->cfg_nvmet_mrq);
10880 
10881 		lpfc_sli4_release_queues(&phba->sli4_hba.nvmet_mrq_hdr,
10882 					 phba->cfg_nvmet_mrq);
10883 		lpfc_sli4_release_queues(&phba->sli4_hba.nvmet_mrq_data,
10884 					 phba->cfg_nvmet_mrq);
10885 	}
10886 
10887 	/* Release mailbox command work queue */
10888 	__lpfc_sli4_release_queue(&phba->sli4_hba.mbx_wq);
10889 
10890 	/* Release ELS work queue */
10891 	__lpfc_sli4_release_queue(&phba->sli4_hba.els_wq);
10892 
10893 	/* Release ELS work queue */
10894 	__lpfc_sli4_release_queue(&phba->sli4_hba.nvmels_wq);
10895 
10896 	/* Release unsolicited receive queue */
10897 	__lpfc_sli4_release_queue(&phba->sli4_hba.hdr_rq);
10898 	__lpfc_sli4_release_queue(&phba->sli4_hba.dat_rq);
10899 
10900 	/* Release ELS complete queue */
10901 	__lpfc_sli4_release_queue(&phba->sli4_hba.els_cq);
10902 
10903 	/* Release NVME LS complete queue */
10904 	__lpfc_sli4_release_queue(&phba->sli4_hba.nvmels_cq);
10905 
10906 	/* Release mailbox command complete queue */
10907 	__lpfc_sli4_release_queue(&phba->sli4_hba.mbx_cq);
10908 
10909 	/* Everything on this list has been freed */
10910 	INIT_LIST_HEAD(&phba->sli4_hba.lpfc_wq_list);
10911 
10912 	/* Done with freeing the queues */
10913 	spin_lock_irq(&phba->hbalock);
10914 	phba->sli.sli_flag &= ~LPFC_QUEUE_FREE_INIT;
10915 	spin_unlock_irq(&phba->hbalock);
10916 }
10917 
10918 int
10919 lpfc_free_rq_buffer(struct lpfc_hba *phba, struct lpfc_queue *rq)
10920 {
10921 	struct lpfc_rqb *rqbp;
10922 	struct lpfc_dmabuf *h_buf;
10923 	struct rqb_dmabuf *rqb_buffer;
10924 
10925 	rqbp = rq->rqbp;
10926 	while (!list_empty(&rqbp->rqb_buffer_list)) {
10927 		list_remove_head(&rqbp->rqb_buffer_list, h_buf,
10928 				 struct lpfc_dmabuf, list);
10929 
10930 		rqb_buffer = container_of(h_buf, struct rqb_dmabuf, hbuf);
10931 		(rqbp->rqb_free_buffer)(phba, rqb_buffer);
10932 		rqbp->buffer_count--;
10933 	}
10934 	return 1;
10935 }
10936 
10937 static int
10938 lpfc_create_wq_cq(struct lpfc_hba *phba, struct lpfc_queue *eq,
10939 	struct lpfc_queue *cq, struct lpfc_queue *wq, uint16_t *cq_map,
10940 	int qidx, uint32_t qtype)
10941 {
10942 	struct lpfc_sli_ring *pring;
10943 	int rc;
10944 
10945 	if (!eq || !cq || !wq) {
10946 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10947 			"6085 Fast-path %s (%d) not allocated\n",
10948 			((eq) ? ((cq) ? "WQ" : "CQ") : "EQ"), qidx);
10949 		return -ENOMEM;
10950 	}
10951 
10952 	/* create the Cq first */
10953 	rc = lpfc_cq_create(phba, cq, eq,
10954 			(qtype == LPFC_MBOX) ? LPFC_MCQ : LPFC_WCQ, qtype);
10955 	if (rc) {
10956 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10957 				"6086 Failed setup of CQ (%d), rc = 0x%x\n",
10958 				qidx, (uint32_t)rc);
10959 		return rc;
10960 	}
10961 
10962 	if (qtype != LPFC_MBOX) {
10963 		/* Setup cq_map for fast lookup */
10964 		if (cq_map)
10965 			*cq_map = cq->queue_id;
10966 
10967 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
10968 			"6087 CQ setup: cq[%d]-id=%d, parent eq[%d]-id=%d\n",
10969 			qidx, cq->queue_id, qidx, eq->queue_id);
10970 
10971 		/* create the wq */
10972 		rc = lpfc_wq_create(phba, wq, cq, qtype);
10973 		if (rc) {
10974 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10975 				"4618 Fail setup fastpath WQ (%d), rc = 0x%x\n",
10976 				qidx, (uint32_t)rc);
10977 			/* no need to tear down cq - caller will do so */
10978 			return rc;
10979 		}
10980 
10981 		/* Bind this CQ/WQ to the NVME ring */
10982 		pring = wq->pring;
10983 		pring->sli.sli4.wqp = (void *)wq;
10984 		cq->pring = pring;
10985 
10986 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
10987 			"2593 WQ setup: wq[%d]-id=%d assoc=%d, cq[%d]-id=%d\n",
10988 			qidx, wq->queue_id, wq->assoc_qid, qidx, cq->queue_id);
10989 	} else {
10990 		rc = lpfc_mq_create(phba, wq, cq, LPFC_MBOX);
10991 		if (rc) {
10992 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10993 					"0539 Failed setup of slow-path MQ: "
10994 					"rc = 0x%x\n", rc);
10995 			/* no need to tear down cq - caller will do so */
10996 			return rc;
10997 		}
10998 
10999 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11000 			"2589 MBX MQ setup: wq-id=%d, parent cq-id=%d\n",
11001 			phba->sli4_hba.mbx_wq->queue_id,
11002 			phba->sli4_hba.mbx_cq->queue_id);
11003 	}
11004 
11005 	return 0;
11006 }
11007 
11008 /**
11009  * lpfc_setup_cq_lookup - Setup the CQ lookup table
11010  * @phba: pointer to lpfc hba data structure.
11011  *
11012  * This routine will populate the cq_lookup table by all
11013  * available CQ queue_id's.
11014  **/
11015 static void
11016 lpfc_setup_cq_lookup(struct lpfc_hba *phba)
11017 {
11018 	struct lpfc_queue *eq, *childq;
11019 	int qidx;
11020 
11021 	memset(phba->sli4_hba.cq_lookup, 0,
11022 	       (sizeof(struct lpfc_queue *) * (phba->sli4_hba.cq_max + 1)));
11023 	/* Loop thru all IRQ vectors */
11024 	for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
11025 		/* Get the EQ corresponding to the IRQ vector */
11026 		eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
11027 		if (!eq)
11028 			continue;
11029 		/* Loop through all CQs associated with that EQ */
11030 		list_for_each_entry(childq, &eq->child_list, list) {
11031 			if (childq->queue_id > phba->sli4_hba.cq_max)
11032 				continue;
11033 			if (childq->subtype == LPFC_IO)
11034 				phba->sli4_hba.cq_lookup[childq->queue_id] =
11035 					childq;
11036 		}
11037 	}
11038 }
11039 
11040 /**
11041  * lpfc_sli4_queue_setup - Set up all the SLI4 queues
11042  * @phba: pointer to lpfc hba data structure.
11043  *
11044  * This routine is invoked to set up all the SLI4 queues for the FCoE HBA
11045  * operation.
11046  *
11047  * Return codes
11048  *      0 - successful
11049  *      -ENOMEM - No available memory
11050  *      -EIO - The mailbox failed to complete successfully.
11051  **/
11052 int
11053 lpfc_sli4_queue_setup(struct lpfc_hba *phba)
11054 {
11055 	uint32_t shdr_status, shdr_add_status;
11056 	union lpfc_sli4_cfg_shdr *shdr;
11057 	struct lpfc_vector_map_info *cpup;
11058 	struct lpfc_sli4_hdw_queue *qp;
11059 	LPFC_MBOXQ_t *mboxq;
11060 	int qidx, cpu;
11061 	uint32_t length, usdelay;
11062 	int rc = -ENOMEM;
11063 
11064 	/* Check for dual-ULP support */
11065 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
11066 	if (!mboxq) {
11067 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11068 				"3249 Unable to allocate memory for "
11069 				"QUERY_FW_CFG mailbox command\n");
11070 		return -ENOMEM;
11071 	}
11072 	length = (sizeof(struct lpfc_mbx_query_fw_config) -
11073 		  sizeof(struct lpfc_sli4_cfg_mhdr));
11074 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
11075 			 LPFC_MBOX_OPCODE_QUERY_FW_CFG,
11076 			 length, LPFC_SLI4_MBX_EMBED);
11077 
11078 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
11079 
11080 	shdr = (union lpfc_sli4_cfg_shdr *)
11081 			&mboxq->u.mqe.un.sli4_config.header.cfg_shdr;
11082 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
11083 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
11084 	if (shdr_status || shdr_add_status || rc) {
11085 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11086 				"3250 QUERY_FW_CFG mailbox failed with status "
11087 				"x%x add_status x%x, mbx status x%x\n",
11088 				shdr_status, shdr_add_status, rc);
11089 		mempool_free(mboxq, phba->mbox_mem_pool);
11090 		rc = -ENXIO;
11091 		goto out_error;
11092 	}
11093 
11094 	phba->sli4_hba.fw_func_mode =
11095 			mboxq->u.mqe.un.query_fw_cfg.rsp.function_mode;
11096 	phba->sli4_hba.physical_port =
11097 			mboxq->u.mqe.un.query_fw_cfg.rsp.physical_port;
11098 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11099 			"3251 QUERY_FW_CFG: func_mode:x%x\n",
11100 			phba->sli4_hba.fw_func_mode);
11101 
11102 	mempool_free(mboxq, phba->mbox_mem_pool);
11103 
11104 	/*
11105 	 * Set up HBA Event Queues (EQs)
11106 	 */
11107 	qp = phba->sli4_hba.hdwq;
11108 
11109 	/* Set up HBA event queue */
11110 	if (!qp) {
11111 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11112 				"3147 Fast-path EQs not allocated\n");
11113 		rc = -ENOMEM;
11114 		goto out_error;
11115 	}
11116 
11117 	/* Loop thru all IRQ vectors */
11118 	for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
11119 		/* Create HBA Event Queues (EQs) in order */
11120 		for_each_present_cpu(cpu) {
11121 			cpup = &phba->sli4_hba.cpu_map[cpu];
11122 
11123 			/* Look for the CPU thats using that vector with
11124 			 * LPFC_CPU_FIRST_IRQ set.
11125 			 */
11126 			if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
11127 				continue;
11128 			if (qidx != cpup->eq)
11129 				continue;
11130 
11131 			/* Create an EQ for that vector */
11132 			rc = lpfc_eq_create(phba, qp[cpup->hdwq].hba_eq,
11133 					    phba->cfg_fcp_imax);
11134 			if (rc) {
11135 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11136 						"0523 Failed setup of fast-path"
11137 						" EQ (%d), rc = 0x%x\n",
11138 						cpup->eq, (uint32_t)rc);
11139 				goto out_destroy;
11140 			}
11141 
11142 			/* Save the EQ for that vector in the hba_eq_hdl */
11143 			phba->sli4_hba.hba_eq_hdl[cpup->eq].eq =
11144 				qp[cpup->hdwq].hba_eq;
11145 
11146 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11147 					"2584 HBA EQ setup: queue[%d]-id=%d\n",
11148 					cpup->eq,
11149 					qp[cpup->hdwq].hba_eq->queue_id);
11150 		}
11151 	}
11152 
11153 	/* Loop thru all Hardware Queues */
11154 	for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
11155 		cpu = lpfc_find_cpu_handle(phba, qidx, LPFC_FIND_BY_HDWQ);
11156 		cpup = &phba->sli4_hba.cpu_map[cpu];
11157 
11158 		/* Create the CQ/WQ corresponding to the Hardware Queue */
11159 		rc = lpfc_create_wq_cq(phba,
11160 				       phba->sli4_hba.hdwq[cpup->hdwq].hba_eq,
11161 				       qp[qidx].io_cq,
11162 				       qp[qidx].io_wq,
11163 				       &phba->sli4_hba.hdwq[qidx].io_cq_map,
11164 				       qidx,
11165 				       LPFC_IO);
11166 		if (rc) {
11167 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11168 					"0535 Failed to setup fastpath "
11169 					"IO WQ/CQ (%d), rc = 0x%x\n",
11170 					qidx, (uint32_t)rc);
11171 			goto out_destroy;
11172 		}
11173 	}
11174 
11175 	/*
11176 	 * Set up Slow Path Complete Queues (CQs)
11177 	 */
11178 
11179 	/* Set up slow-path MBOX CQ/MQ */
11180 
11181 	if (!phba->sli4_hba.mbx_cq || !phba->sli4_hba.mbx_wq) {
11182 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11183 				"0528 %s not allocated\n",
11184 				phba->sli4_hba.mbx_cq ?
11185 				"Mailbox WQ" : "Mailbox CQ");
11186 		rc = -ENOMEM;
11187 		goto out_destroy;
11188 	}
11189 
11190 	rc = lpfc_create_wq_cq(phba, qp[0].hba_eq,
11191 			       phba->sli4_hba.mbx_cq,
11192 			       phba->sli4_hba.mbx_wq,
11193 			       NULL, 0, LPFC_MBOX);
11194 	if (rc) {
11195 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11196 			"0529 Failed setup of mailbox WQ/CQ: rc = 0x%x\n",
11197 			(uint32_t)rc);
11198 		goto out_destroy;
11199 	}
11200 	if (phba->nvmet_support) {
11201 		if (!phba->sli4_hba.nvmet_cqset) {
11202 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11203 					"3165 Fast-path NVME CQ Set "
11204 					"array not allocated\n");
11205 			rc = -ENOMEM;
11206 			goto out_destroy;
11207 		}
11208 		if (phba->cfg_nvmet_mrq > 1) {
11209 			rc = lpfc_cq_create_set(phba,
11210 					phba->sli4_hba.nvmet_cqset,
11211 					qp,
11212 					LPFC_WCQ, LPFC_NVMET);
11213 			if (rc) {
11214 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11215 						"3164 Failed setup of NVME CQ "
11216 						"Set, rc = 0x%x\n",
11217 						(uint32_t)rc);
11218 				goto out_destroy;
11219 			}
11220 		} else {
11221 			/* Set up NVMET Receive Complete Queue */
11222 			rc = lpfc_cq_create(phba, phba->sli4_hba.nvmet_cqset[0],
11223 					    qp[0].hba_eq,
11224 					    LPFC_WCQ, LPFC_NVMET);
11225 			if (rc) {
11226 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11227 						"6089 Failed setup NVMET CQ: "
11228 						"rc = 0x%x\n", (uint32_t)rc);
11229 				goto out_destroy;
11230 			}
11231 			phba->sli4_hba.nvmet_cqset[0]->chann = 0;
11232 
11233 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11234 					"6090 NVMET CQ setup: cq-id=%d, "
11235 					"parent eq-id=%d\n",
11236 					phba->sli4_hba.nvmet_cqset[0]->queue_id,
11237 					qp[0].hba_eq->queue_id);
11238 		}
11239 	}
11240 
11241 	/* Set up slow-path ELS WQ/CQ */
11242 	if (!phba->sli4_hba.els_cq || !phba->sli4_hba.els_wq) {
11243 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11244 				"0530 ELS %s not allocated\n",
11245 				phba->sli4_hba.els_cq ? "WQ" : "CQ");
11246 		rc = -ENOMEM;
11247 		goto out_destroy;
11248 	}
11249 	rc = lpfc_create_wq_cq(phba, qp[0].hba_eq,
11250 			       phba->sli4_hba.els_cq,
11251 			       phba->sli4_hba.els_wq,
11252 			       NULL, 0, LPFC_ELS);
11253 	if (rc) {
11254 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11255 				"0525 Failed setup of ELS WQ/CQ: rc = 0x%x\n",
11256 				(uint32_t)rc);
11257 		goto out_destroy;
11258 	}
11259 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11260 			"2590 ELS WQ setup: wq-id=%d, parent cq-id=%d\n",
11261 			phba->sli4_hba.els_wq->queue_id,
11262 			phba->sli4_hba.els_cq->queue_id);
11263 
11264 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
11265 		/* Set up NVME LS Complete Queue */
11266 		if (!phba->sli4_hba.nvmels_cq || !phba->sli4_hba.nvmels_wq) {
11267 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11268 					"6091 LS %s not allocated\n",
11269 					phba->sli4_hba.nvmels_cq ? "WQ" : "CQ");
11270 			rc = -ENOMEM;
11271 			goto out_destroy;
11272 		}
11273 		rc = lpfc_create_wq_cq(phba, qp[0].hba_eq,
11274 				       phba->sli4_hba.nvmels_cq,
11275 				       phba->sli4_hba.nvmels_wq,
11276 				       NULL, 0, LPFC_NVME_LS);
11277 		if (rc) {
11278 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11279 					"0526 Failed setup of NVVME LS WQ/CQ: "
11280 					"rc = 0x%x\n", (uint32_t)rc);
11281 			goto out_destroy;
11282 		}
11283 
11284 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11285 				"6096 ELS WQ setup: wq-id=%d, "
11286 				"parent cq-id=%d\n",
11287 				phba->sli4_hba.nvmels_wq->queue_id,
11288 				phba->sli4_hba.nvmels_cq->queue_id);
11289 	}
11290 
11291 	/*
11292 	 * Create NVMET Receive Queue (RQ)
11293 	 */
11294 	if (phba->nvmet_support) {
11295 		if ((!phba->sli4_hba.nvmet_cqset) ||
11296 		    (!phba->sli4_hba.nvmet_mrq_hdr) ||
11297 		    (!phba->sli4_hba.nvmet_mrq_data)) {
11298 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11299 					"6130 MRQ CQ Queues not "
11300 					"allocated\n");
11301 			rc = -ENOMEM;
11302 			goto out_destroy;
11303 		}
11304 		if (phba->cfg_nvmet_mrq > 1) {
11305 			rc = lpfc_mrq_create(phba,
11306 					     phba->sli4_hba.nvmet_mrq_hdr,
11307 					     phba->sli4_hba.nvmet_mrq_data,
11308 					     phba->sli4_hba.nvmet_cqset,
11309 					     LPFC_NVMET);
11310 			if (rc) {
11311 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11312 						"6098 Failed setup of NVMET "
11313 						"MRQ: rc = 0x%x\n",
11314 						(uint32_t)rc);
11315 				goto out_destroy;
11316 			}
11317 
11318 		} else {
11319 			rc = lpfc_rq_create(phba,
11320 					    phba->sli4_hba.nvmet_mrq_hdr[0],
11321 					    phba->sli4_hba.nvmet_mrq_data[0],
11322 					    phba->sli4_hba.nvmet_cqset[0],
11323 					    LPFC_NVMET);
11324 			if (rc) {
11325 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11326 						"6057 Failed setup of NVMET "
11327 						"Receive Queue: rc = 0x%x\n",
11328 						(uint32_t)rc);
11329 				goto out_destroy;
11330 			}
11331 
11332 			lpfc_printf_log(
11333 				phba, KERN_INFO, LOG_INIT,
11334 				"6099 NVMET RQ setup: hdr-rq-id=%d, "
11335 				"dat-rq-id=%d parent cq-id=%d\n",
11336 				phba->sli4_hba.nvmet_mrq_hdr[0]->queue_id,
11337 				phba->sli4_hba.nvmet_mrq_data[0]->queue_id,
11338 				phba->sli4_hba.nvmet_cqset[0]->queue_id);
11339 
11340 		}
11341 	}
11342 
11343 	if (!phba->sli4_hba.hdr_rq || !phba->sli4_hba.dat_rq) {
11344 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11345 				"0540 Receive Queue not allocated\n");
11346 		rc = -ENOMEM;
11347 		goto out_destroy;
11348 	}
11349 
11350 	rc = lpfc_rq_create(phba, phba->sli4_hba.hdr_rq, phba->sli4_hba.dat_rq,
11351 			    phba->sli4_hba.els_cq, LPFC_USOL);
11352 	if (rc) {
11353 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11354 				"0541 Failed setup of Receive Queue: "
11355 				"rc = 0x%x\n", (uint32_t)rc);
11356 		goto out_destroy;
11357 	}
11358 
11359 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11360 			"2592 USL RQ setup: hdr-rq-id=%d, dat-rq-id=%d "
11361 			"parent cq-id=%d\n",
11362 			phba->sli4_hba.hdr_rq->queue_id,
11363 			phba->sli4_hba.dat_rq->queue_id,
11364 			phba->sli4_hba.els_cq->queue_id);
11365 
11366 	if (phba->cfg_fcp_imax)
11367 		usdelay = LPFC_SEC_TO_USEC / phba->cfg_fcp_imax;
11368 	else
11369 		usdelay = 0;
11370 
11371 	for (qidx = 0; qidx < phba->cfg_irq_chann;
11372 	     qidx += LPFC_MAX_EQ_DELAY_EQID_CNT)
11373 		lpfc_modify_hba_eq_delay(phba, qidx, LPFC_MAX_EQ_DELAY_EQID_CNT,
11374 					 usdelay);
11375 
11376 	if (phba->sli4_hba.cq_max) {
11377 		kfree(phba->sli4_hba.cq_lookup);
11378 		phba->sli4_hba.cq_lookup = kzalloc_objs(struct lpfc_queue *,
11379 							(phba->sli4_hba.cq_max + 1));
11380 		if (!phba->sli4_hba.cq_lookup) {
11381 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11382 					"0549 Failed setup of CQ Lookup table: "
11383 					"size 0x%x\n", phba->sli4_hba.cq_max);
11384 			rc = -ENOMEM;
11385 			goto out_destroy;
11386 		}
11387 		lpfc_setup_cq_lookup(phba);
11388 	}
11389 	return 0;
11390 
11391 out_destroy:
11392 	lpfc_sli4_queue_unset(phba);
11393 out_error:
11394 	return rc;
11395 }
11396 
11397 /**
11398  * lpfc_sli4_queue_unset - Unset all the SLI4 queues
11399  * @phba: pointer to lpfc hba data structure.
11400  *
11401  * This routine is invoked to unset all the SLI4 queues with the FCoE HBA
11402  * operation.
11403  *
11404  * Return codes
11405  *      0 - successful
11406  *      -ENOMEM - No available memory
11407  *      -EIO - The mailbox failed to complete successfully.
11408  **/
11409 void
11410 lpfc_sli4_queue_unset(struct lpfc_hba *phba)
11411 {
11412 	struct lpfc_sli4_hdw_queue *qp;
11413 	struct lpfc_queue *eq;
11414 	int qidx;
11415 
11416 	/* Unset mailbox command work queue */
11417 	if (phba->sli4_hba.mbx_wq)
11418 		lpfc_mq_destroy(phba, phba->sli4_hba.mbx_wq);
11419 
11420 	/* Unset NVME LS work queue */
11421 	if (phba->sli4_hba.nvmels_wq)
11422 		lpfc_wq_destroy(phba, phba->sli4_hba.nvmels_wq);
11423 
11424 	/* Unset ELS work queue */
11425 	if (phba->sli4_hba.els_wq)
11426 		lpfc_wq_destroy(phba, phba->sli4_hba.els_wq);
11427 
11428 	/* Unset unsolicited receive queue */
11429 	if (phba->sli4_hba.hdr_rq)
11430 		lpfc_rq_destroy(phba, phba->sli4_hba.hdr_rq,
11431 				phba->sli4_hba.dat_rq);
11432 
11433 	/* Unset mailbox command complete queue */
11434 	if (phba->sli4_hba.mbx_cq)
11435 		lpfc_cq_destroy(phba, phba->sli4_hba.mbx_cq);
11436 
11437 	/* Unset ELS complete queue */
11438 	if (phba->sli4_hba.els_cq)
11439 		lpfc_cq_destroy(phba, phba->sli4_hba.els_cq);
11440 
11441 	/* Unset NVME LS complete queue */
11442 	if (phba->sli4_hba.nvmels_cq)
11443 		lpfc_cq_destroy(phba, phba->sli4_hba.nvmels_cq);
11444 
11445 	if (phba->nvmet_support) {
11446 		/* Unset NVMET MRQ queue */
11447 		if (phba->sli4_hba.nvmet_mrq_hdr) {
11448 			for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++)
11449 				lpfc_rq_destroy(
11450 					phba,
11451 					phba->sli4_hba.nvmet_mrq_hdr[qidx],
11452 					phba->sli4_hba.nvmet_mrq_data[qidx]);
11453 		}
11454 
11455 		/* Unset NVMET CQ Set complete queue */
11456 		if (phba->sli4_hba.nvmet_cqset) {
11457 			for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++)
11458 				lpfc_cq_destroy(
11459 					phba, phba->sli4_hba.nvmet_cqset[qidx]);
11460 		}
11461 	}
11462 
11463 	/* Unset fast-path SLI4 queues */
11464 	if (phba->sli4_hba.hdwq) {
11465 		/* Loop thru all Hardware Queues */
11466 		for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
11467 			/* Destroy the CQ/WQ corresponding to Hardware Queue */
11468 			qp = &phba->sli4_hba.hdwq[qidx];
11469 			lpfc_wq_destroy(phba, qp->io_wq);
11470 			lpfc_cq_destroy(phba, qp->io_cq);
11471 		}
11472 		/* Loop thru all IRQ vectors */
11473 		for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
11474 			/* Destroy the EQ corresponding to the IRQ vector */
11475 			eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
11476 			lpfc_eq_destroy(phba, eq);
11477 		}
11478 	}
11479 
11480 	kfree(phba->sli4_hba.cq_lookup);
11481 	phba->sli4_hba.cq_lookup = NULL;
11482 	phba->sli4_hba.cq_max = 0;
11483 }
11484 
11485 /**
11486  * lpfc_sli4_cq_event_pool_create - Create completion-queue event free pool
11487  * @phba: pointer to lpfc hba data structure.
11488  *
11489  * This routine is invoked to allocate and set up a pool of completion queue
11490  * events. The body of the completion queue event is a completion queue entry
11491  * CQE. For now, this pool is used for the interrupt service routine to queue
11492  * the following HBA completion queue events for the worker thread to process:
11493  *   - Mailbox asynchronous events
11494  *   - Receive queue completion unsolicited events
11495  * Later, this can be used for all the slow-path events.
11496  *
11497  * Return codes
11498  *      0 - successful
11499  *      -ENOMEM - No available memory
11500  **/
11501 static int
11502 lpfc_sli4_cq_event_pool_create(struct lpfc_hba *phba)
11503 {
11504 	struct lpfc_cq_event *cq_event;
11505 	int i;
11506 
11507 	for (i = 0; i < (4 * phba->sli4_hba.cq_ecount); i++) {
11508 		cq_event = kmalloc_obj(struct lpfc_cq_event);
11509 		if (!cq_event)
11510 			goto out_pool_create_fail;
11511 		list_add_tail(&cq_event->list,
11512 			      &phba->sli4_hba.sp_cqe_event_pool);
11513 	}
11514 	return 0;
11515 
11516 out_pool_create_fail:
11517 	lpfc_sli4_cq_event_pool_destroy(phba);
11518 	return -ENOMEM;
11519 }
11520 
11521 /**
11522  * lpfc_sli4_cq_event_pool_destroy - Free completion-queue event free pool
11523  * @phba: pointer to lpfc hba data structure.
11524  *
11525  * This routine is invoked to free the pool of completion queue events at
11526  * driver unload time. Note that, it is the responsibility of the driver
11527  * cleanup routine to free all the outstanding completion-queue events
11528  * allocated from this pool back into the pool before invoking this routine
11529  * to destroy the pool.
11530  **/
11531 static void
11532 lpfc_sli4_cq_event_pool_destroy(struct lpfc_hba *phba)
11533 {
11534 	struct lpfc_cq_event *cq_event, *next_cq_event;
11535 
11536 	list_for_each_entry_safe(cq_event, next_cq_event,
11537 				 &phba->sli4_hba.sp_cqe_event_pool, list) {
11538 		list_del(&cq_event->list);
11539 		kfree(cq_event);
11540 	}
11541 }
11542 
11543 /**
11544  * __lpfc_sli4_cq_event_alloc - Allocate a completion-queue event from free pool
11545  * @phba: pointer to lpfc hba data structure.
11546  *
11547  * This routine is the lock free version of the API invoked to allocate a
11548  * completion-queue event from the free pool.
11549  *
11550  * Return: Pointer to the newly allocated completion-queue event if successful
11551  *         NULL otherwise.
11552  **/
11553 struct lpfc_cq_event *
11554 __lpfc_sli4_cq_event_alloc(struct lpfc_hba *phba)
11555 {
11556 	struct lpfc_cq_event *cq_event = NULL;
11557 
11558 	list_remove_head(&phba->sli4_hba.sp_cqe_event_pool, cq_event,
11559 			 struct lpfc_cq_event, list);
11560 	return cq_event;
11561 }
11562 
11563 /**
11564  * lpfc_sli4_cq_event_alloc - Allocate a completion-queue event from free pool
11565  * @phba: pointer to lpfc hba data structure.
11566  *
11567  * This routine is the lock version of the API invoked to allocate a
11568  * completion-queue event from the free pool.
11569  *
11570  * Return: Pointer to the newly allocated completion-queue event if successful
11571  *         NULL otherwise.
11572  **/
11573 struct lpfc_cq_event *
11574 lpfc_sli4_cq_event_alloc(struct lpfc_hba *phba)
11575 {
11576 	struct lpfc_cq_event *cq_event;
11577 	unsigned long iflags;
11578 
11579 	spin_lock_irqsave(&phba->hbalock, iflags);
11580 	cq_event = __lpfc_sli4_cq_event_alloc(phba);
11581 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11582 	return cq_event;
11583 }
11584 
11585 /**
11586  * __lpfc_sli4_cq_event_release - Release a completion-queue event to free pool
11587  * @phba: pointer to lpfc hba data structure.
11588  * @cq_event: pointer to the completion queue event to be freed.
11589  *
11590  * This routine is the lock free version of the API invoked to release a
11591  * completion-queue event back into the free pool.
11592  **/
11593 void
11594 __lpfc_sli4_cq_event_release(struct lpfc_hba *phba,
11595 			     struct lpfc_cq_event *cq_event)
11596 {
11597 	list_add_tail(&cq_event->list, &phba->sli4_hba.sp_cqe_event_pool);
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 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 	unsigned long iflags;
11613 	spin_lock_irqsave(&phba->hbalock, iflags);
11614 	__lpfc_sli4_cq_event_release(phba, cq_event);
11615 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11616 }
11617 
11618 /**
11619  * lpfc_sli4_cq_event_release_all - Release all cq events to the free pool
11620  * @phba: pointer to lpfc hba data structure.
11621  *
11622  * This routine is to free all the pending completion-queue events to the
11623  * back into the free pool for device reset.
11624  **/
11625 static void
11626 lpfc_sli4_cq_event_release_all(struct lpfc_hba *phba)
11627 {
11628 	LIST_HEAD(cq_event_list);
11629 	struct lpfc_cq_event *cq_event;
11630 	unsigned long iflags;
11631 
11632 	/* Retrieve all the pending WCQEs from pending WCQE lists */
11633 
11634 	/* Pending ELS XRI abort events */
11635 	spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
11636 	list_splice_init(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
11637 			 &cq_event_list);
11638 	spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
11639 
11640 	/* Pending asynnc events */
11641 	spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
11642 	list_splice_init(&phba->sli4_hba.sp_asynce_work_queue,
11643 			 &cq_event_list);
11644 	spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock, iflags);
11645 
11646 	while (!list_empty(&cq_event_list)) {
11647 		list_remove_head(&cq_event_list, cq_event,
11648 				 struct lpfc_cq_event, list);
11649 		lpfc_sli4_cq_event_release(phba, cq_event);
11650 	}
11651 }
11652 
11653 /**
11654  * lpfc_pci_function_reset - Reset pci function.
11655  * @phba: pointer to lpfc hba data structure.
11656  *
11657  * This routine is invoked to request a PCI function reset. It will destroys
11658  * all resources assigned to the PCI function which originates this request.
11659  *
11660  * Return codes
11661  *      0 - successful
11662  *      -ENOMEM - No available memory
11663  *      -EIO - The mailbox failed to complete successfully.
11664  **/
11665 int
11666 lpfc_pci_function_reset(struct lpfc_hba *phba)
11667 {
11668 	LPFC_MBOXQ_t *mboxq;
11669 	uint32_t rc = 0, if_type;
11670 	uint32_t shdr_status, shdr_add_status;
11671 	uint32_t rdy_chk;
11672 	uint32_t port_reset = 0;
11673 	union lpfc_sli4_cfg_shdr *shdr;
11674 	struct lpfc_register reg_data;
11675 	uint16_t devid;
11676 
11677 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
11678 	switch (if_type) {
11679 	case LPFC_SLI_INTF_IF_TYPE_0:
11680 		mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
11681 						       GFP_KERNEL);
11682 		if (!mboxq) {
11683 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11684 					"0494 Unable to allocate memory for "
11685 					"issuing SLI_FUNCTION_RESET mailbox "
11686 					"command\n");
11687 			return -ENOMEM;
11688 		}
11689 
11690 		/* Setup PCI function reset mailbox-ioctl command */
11691 		lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
11692 				 LPFC_MBOX_OPCODE_FUNCTION_RESET, 0,
11693 				 LPFC_SLI4_MBX_EMBED);
11694 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
11695 		shdr = (union lpfc_sli4_cfg_shdr *)
11696 			&mboxq->u.mqe.un.sli4_config.header.cfg_shdr;
11697 		shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
11698 		shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
11699 					 &shdr->response);
11700 		mempool_free(mboxq, phba->mbox_mem_pool);
11701 		if (shdr_status || shdr_add_status || rc) {
11702 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11703 					"0495 SLI_FUNCTION_RESET mailbox "
11704 					"failed with status x%x add_status x%x,"
11705 					" mbx status x%x\n",
11706 					shdr_status, shdr_add_status, rc);
11707 			rc = -ENXIO;
11708 		}
11709 		break;
11710 	case LPFC_SLI_INTF_IF_TYPE_2:
11711 	case LPFC_SLI_INTF_IF_TYPE_6:
11712 wait:
11713 		/*
11714 		 * Poll the Port Status Register and wait for RDY for
11715 		 * up to 30 seconds. If the port doesn't respond, treat
11716 		 * it as an error.
11717 		 */
11718 		for (rdy_chk = 0; rdy_chk < 1500; rdy_chk++) {
11719 			if (lpfc_readl(phba->sli4_hba.u.if_type2.
11720 				STATUSregaddr, &reg_data.word0)) {
11721 				rc = -ENODEV;
11722 				goto out;
11723 			}
11724 			if (bf_get(lpfc_sliport_status_rdy, &reg_data))
11725 				break;
11726 			msleep(20);
11727 		}
11728 
11729 		if (!bf_get(lpfc_sliport_status_rdy, &reg_data)) {
11730 			phba->work_status[0] = readl(
11731 				phba->sli4_hba.u.if_type2.ERR1regaddr);
11732 			phba->work_status[1] = readl(
11733 				phba->sli4_hba.u.if_type2.ERR2regaddr);
11734 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11735 					"2890 Port not ready, port status reg "
11736 					"0x%x error 1=0x%x, error 2=0x%x\n",
11737 					reg_data.word0,
11738 					phba->work_status[0],
11739 					phba->work_status[1]);
11740 			rc = -ENODEV;
11741 			goto out;
11742 		}
11743 
11744 		if (bf_get(lpfc_sliport_status_pldv, &reg_data))
11745 			lpfc_pldv_detect = true;
11746 
11747 		if (!port_reset) {
11748 			/*
11749 			 * Reset the port now
11750 			 */
11751 			reg_data.word0 = 0;
11752 			bf_set(lpfc_sliport_ctrl_end, &reg_data,
11753 			       LPFC_SLIPORT_LITTLE_ENDIAN);
11754 			bf_set(lpfc_sliport_ctrl_ip, &reg_data,
11755 			       LPFC_SLIPORT_INIT_PORT);
11756 			writel(reg_data.word0, phba->sli4_hba.u.if_type2.
11757 			       CTRLregaddr);
11758 			/* flush */
11759 			pci_read_config_word(phba->pcidev,
11760 					     PCI_DEVICE_ID, &devid);
11761 
11762 			port_reset = 1;
11763 			msleep(20);
11764 			goto wait;
11765 		} else if (bf_get(lpfc_sliport_status_rn, &reg_data)) {
11766 			rc = -ENODEV;
11767 			goto out;
11768 		}
11769 		break;
11770 
11771 	case LPFC_SLI_INTF_IF_TYPE_1:
11772 	default:
11773 		break;
11774 	}
11775 
11776 out:
11777 	/* Catch the not-ready port failure after a port reset. */
11778 	if (rc) {
11779 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11780 				"3317 HBA not functional: IP Reset Failed "
11781 				"try: echo fw_reset > board_mode\n");
11782 		rc = -ENODEV;
11783 	}
11784 
11785 	return rc;
11786 }
11787 
11788 /**
11789  * lpfc_sli4_pci_mem_setup - Setup SLI4 HBA PCI memory space.
11790  * @phba: pointer to lpfc hba data structure.
11791  *
11792  * This routine is invoked to set up the PCI device memory space for device
11793  * with SLI-4 interface spec.
11794  *
11795  * Return codes
11796  * 	0 - successful
11797  * 	other values - error
11798  **/
11799 static int
11800 lpfc_sli4_pci_mem_setup(struct lpfc_hba *phba)
11801 {
11802 	struct pci_dev *pdev = phba->pcidev;
11803 	unsigned long bar0map_len, bar1map_len, bar2map_len;
11804 	int error;
11805 	uint32_t if_type;
11806 	u8 sli_family;
11807 
11808 	if (!pdev)
11809 		return -ENODEV;
11810 
11811 	/* Set the device DMA mask size */
11812 	error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
11813 	if (error)
11814 		error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32));
11815 	if (error)
11816 		return error;
11817 
11818 	/*
11819 	 * The BARs and register set definitions and offset locations are
11820 	 * dependent on the if_type.
11821 	 */
11822 	if (pci_read_config_dword(pdev, LPFC_SLI_INTF,
11823 				  &phba->sli4_hba.sli_intf.word0)) {
11824 		return -ENODEV;
11825 	}
11826 
11827 	/* There is no SLI3 failback for SLI4 devices. */
11828 	if (bf_get(lpfc_sli_intf_valid, &phba->sli4_hba.sli_intf) !=
11829 	    LPFC_SLI_INTF_VALID) {
11830 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11831 				"2894 SLI_INTF reg contents invalid "
11832 				"sli_intf reg 0x%x\n",
11833 				phba->sli4_hba.sli_intf.word0);
11834 		return -ENODEV;
11835 	}
11836 
11837 	/* Check if ASIC_ID register should be read */
11838 	sli_family = bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf);
11839 	if (sli_family == LPFC_SLI_INTF_ASIC_ID) {
11840 		if (pci_read_config_dword(pdev, LPFC_ASIC_ID_OFFSET,
11841 					  &phba->sli4_hba.asic_id.word0))
11842 			return -ENODEV;
11843 	}
11844 
11845 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
11846 	/*
11847 	 * Get the bus address of SLI4 device Bar regions and the
11848 	 * number of bytes required by each mapping. The mapping of the
11849 	 * particular PCI BARs regions is dependent on the type of
11850 	 * SLI4 device.
11851 	 */
11852 	if (pci_resource_start(pdev, PCI_64BIT_BAR0)) {
11853 		phba->pci_bar0_map = pci_resource_start(pdev, PCI_64BIT_BAR0);
11854 		bar0map_len = pci_resource_len(pdev, PCI_64BIT_BAR0);
11855 
11856 		/*
11857 		 * Map SLI4 PCI Config Space Register base to a kernel virtual
11858 		 * addr
11859 		 */
11860 		phba->sli4_hba.conf_regs_memmap_p =
11861 			ioremap(phba->pci_bar0_map, bar0map_len);
11862 		if (!phba->sli4_hba.conf_regs_memmap_p) {
11863 			dev_printk(KERN_ERR, &pdev->dev,
11864 				   "ioremap failed for SLI4 PCI config "
11865 				   "registers.\n");
11866 			return -ENODEV;
11867 		}
11868 		phba->pci_bar0_memmap_p = phba->sli4_hba.conf_regs_memmap_p;
11869 		/* Set up BAR0 PCI config space register memory map */
11870 		lpfc_sli4_bar0_register_memmap(phba, if_type);
11871 	} else {
11872 		phba->pci_bar0_map = pci_resource_start(pdev, 1);
11873 		bar0map_len = pci_resource_len(pdev, 1);
11874 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
11875 			dev_printk(KERN_ERR, &pdev->dev,
11876 			   "FATAL - No BAR0 mapping for SLI4, if_type 2\n");
11877 			return -ENODEV;
11878 		}
11879 		phba->sli4_hba.conf_regs_memmap_p =
11880 				ioremap(phba->pci_bar0_map, bar0map_len);
11881 		if (!phba->sli4_hba.conf_regs_memmap_p) {
11882 			dev_printk(KERN_ERR, &pdev->dev,
11883 				"ioremap failed for SLI4 PCI config "
11884 				"registers.\n");
11885 			return -ENODEV;
11886 		}
11887 		lpfc_sli4_bar0_register_memmap(phba, if_type);
11888 	}
11889 
11890 	if (if_type == LPFC_SLI_INTF_IF_TYPE_0) {
11891 		if (pci_resource_start(pdev, PCI_64BIT_BAR2)) {
11892 			/*
11893 			 * Map SLI4 if type 0 HBA Control Register base to a
11894 			 * kernel virtual address and setup the registers.
11895 			 */
11896 			phba->pci_bar1_map = pci_resource_start(pdev,
11897 								PCI_64BIT_BAR2);
11898 			bar1map_len = pci_resource_len(pdev, PCI_64BIT_BAR2);
11899 			phba->sli4_hba.ctrl_regs_memmap_p =
11900 					ioremap(phba->pci_bar1_map,
11901 						bar1map_len);
11902 			if (!phba->sli4_hba.ctrl_regs_memmap_p) {
11903 				dev_err(&pdev->dev,
11904 					   "ioremap failed for SLI4 HBA "
11905 					    "control registers.\n");
11906 				error = -ENOMEM;
11907 				goto out_iounmap_conf;
11908 			}
11909 			phba->pci_bar2_memmap_p =
11910 					 phba->sli4_hba.ctrl_regs_memmap_p;
11911 			lpfc_sli4_bar1_register_memmap(phba, if_type);
11912 		} else {
11913 			error = -ENOMEM;
11914 			goto out_iounmap_conf;
11915 		}
11916 	}
11917 
11918 	if ((if_type == LPFC_SLI_INTF_IF_TYPE_6) &&
11919 	    (pci_resource_start(pdev, PCI_64BIT_BAR2))) {
11920 		/*
11921 		 * Map SLI4 if type 6 HBA Doorbell Register base to a kernel
11922 		 * virtual address and setup the registers.
11923 		 */
11924 		phba->pci_bar1_map = pci_resource_start(pdev, PCI_64BIT_BAR2);
11925 		bar1map_len = pci_resource_len(pdev, PCI_64BIT_BAR2);
11926 		phba->sli4_hba.drbl_regs_memmap_p =
11927 				ioremap(phba->pci_bar1_map, bar1map_len);
11928 		if (!phba->sli4_hba.drbl_regs_memmap_p) {
11929 			dev_err(&pdev->dev,
11930 			   "ioremap failed for SLI4 HBA doorbell registers.\n");
11931 			error = -ENOMEM;
11932 			goto out_iounmap_conf;
11933 		}
11934 		phba->pci_bar2_memmap_p = phba->sli4_hba.drbl_regs_memmap_p;
11935 		lpfc_sli4_bar1_register_memmap(phba, if_type);
11936 	}
11937 
11938 	if (if_type == LPFC_SLI_INTF_IF_TYPE_0) {
11939 		if (pci_resource_start(pdev, PCI_64BIT_BAR4)) {
11940 			/*
11941 			 * Map SLI4 if type 0 HBA Doorbell Register base to
11942 			 * a kernel virtual address and setup the registers.
11943 			 */
11944 			phba->pci_bar2_map = pci_resource_start(pdev,
11945 								PCI_64BIT_BAR4);
11946 			bar2map_len = pci_resource_len(pdev, PCI_64BIT_BAR4);
11947 			phba->sli4_hba.drbl_regs_memmap_p =
11948 					ioremap(phba->pci_bar2_map,
11949 						bar2map_len);
11950 			if (!phba->sli4_hba.drbl_regs_memmap_p) {
11951 				dev_err(&pdev->dev,
11952 					   "ioremap failed for SLI4 HBA"
11953 					   " doorbell registers.\n");
11954 				error = -ENOMEM;
11955 				goto out_iounmap_ctrl;
11956 			}
11957 			phba->pci_bar4_memmap_p =
11958 					phba->sli4_hba.drbl_regs_memmap_p;
11959 			error = lpfc_sli4_bar2_register_memmap(phba, LPFC_VF0);
11960 			if (error)
11961 				goto out_iounmap_all;
11962 		} else {
11963 			error = -ENOMEM;
11964 			goto out_iounmap_ctrl;
11965 		}
11966 	}
11967 
11968 	if (if_type == LPFC_SLI_INTF_IF_TYPE_6 &&
11969 	    pci_resource_start(pdev, PCI_64BIT_BAR4)) {
11970 		/*
11971 		 * Map SLI4 if type 6 HBA DPP Register base to a kernel
11972 		 * virtual address and setup the registers.
11973 		 */
11974 		phba->pci_bar2_map = pci_resource_start(pdev, PCI_64BIT_BAR4);
11975 		bar2map_len = pci_resource_len(pdev, PCI_64BIT_BAR4);
11976 		phba->sli4_hba.dpp_regs_memmap_p =
11977 				ioremap(phba->pci_bar2_map, bar2map_len);
11978 		if (!phba->sli4_hba.dpp_regs_memmap_p) {
11979 			dev_err(&pdev->dev,
11980 			   "ioremap failed for SLI4 HBA dpp registers.\n");
11981 			error = -ENOMEM;
11982 			goto out_iounmap_all;
11983 		}
11984 		phba->pci_bar4_memmap_p = phba->sli4_hba.dpp_regs_memmap_p;
11985 	}
11986 
11987 	/* Set up the EQ/CQ register handeling functions now */
11988 	switch (if_type) {
11989 	case LPFC_SLI_INTF_IF_TYPE_0:
11990 	case LPFC_SLI_INTF_IF_TYPE_2:
11991 		phba->sli4_hba.sli4_eq_clr_intr = lpfc_sli4_eq_clr_intr;
11992 		phba->sli4_hba.sli4_write_eq_db = lpfc_sli4_write_eq_db;
11993 		phba->sli4_hba.sli4_write_cq_db = lpfc_sli4_write_cq_db;
11994 		break;
11995 	case LPFC_SLI_INTF_IF_TYPE_6:
11996 		phba->sli4_hba.sli4_eq_clr_intr = lpfc_sli4_if6_eq_clr_intr;
11997 		phba->sli4_hba.sli4_write_eq_db = lpfc_sli4_if6_write_eq_db;
11998 		phba->sli4_hba.sli4_write_cq_db = lpfc_sli4_if6_write_cq_db;
11999 		break;
12000 	default:
12001 		break;
12002 	}
12003 
12004 	return 0;
12005 
12006 out_iounmap_all:
12007 	if (phba->sli4_hba.drbl_regs_memmap_p)
12008 		iounmap(phba->sli4_hba.drbl_regs_memmap_p);
12009 out_iounmap_ctrl:
12010 	if (phba->sli4_hba.ctrl_regs_memmap_p)
12011 		iounmap(phba->sli4_hba.ctrl_regs_memmap_p);
12012 out_iounmap_conf:
12013 	iounmap(phba->sli4_hba.conf_regs_memmap_p);
12014 
12015 	return error;
12016 }
12017 
12018 /**
12019  * lpfc_sli4_pci_mem_unset - Unset SLI4 HBA PCI memory space.
12020  * @phba: pointer to lpfc hba data structure.
12021  *
12022  * This routine is invoked to unset the PCI device memory space for device
12023  * with SLI-4 interface spec.
12024  **/
12025 static void
12026 lpfc_sli4_pci_mem_unset(struct lpfc_hba *phba)
12027 {
12028 	uint32_t if_type;
12029 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
12030 
12031 	switch (if_type) {
12032 	case LPFC_SLI_INTF_IF_TYPE_0:
12033 		iounmap(phba->sli4_hba.drbl_regs_memmap_p);
12034 		iounmap(phba->sli4_hba.ctrl_regs_memmap_p);
12035 		iounmap(phba->sli4_hba.conf_regs_memmap_p);
12036 		break;
12037 	case LPFC_SLI_INTF_IF_TYPE_2:
12038 		iounmap(phba->sli4_hba.conf_regs_memmap_p);
12039 		break;
12040 	case LPFC_SLI_INTF_IF_TYPE_6:
12041 		iounmap(phba->sli4_hba.drbl_regs_memmap_p);
12042 		iounmap(phba->sli4_hba.conf_regs_memmap_p);
12043 		if (phba->sli4_hba.dpp_regs_memmap_p)
12044 			iounmap(phba->sli4_hba.dpp_regs_memmap_p);
12045 		if (phba->sli4_hba.dpp_regs_memmap_wc_p)
12046 			iounmap(phba->sli4_hba.dpp_regs_memmap_wc_p);
12047 		break;
12048 	case LPFC_SLI_INTF_IF_TYPE_1:
12049 		break;
12050 	default:
12051 		dev_printk(KERN_ERR, &phba->pcidev->dev,
12052 			   "FATAL - unsupported SLI4 interface type - %d\n",
12053 			   if_type);
12054 		break;
12055 	}
12056 }
12057 
12058 /**
12059  * lpfc_sli_enable_msix - Enable MSI-X interrupt mode on SLI-3 device
12060  * @phba: pointer to lpfc hba data structure.
12061  *
12062  * This routine is invoked to enable the MSI-X interrupt vectors to device
12063  * with SLI-3 interface specs.
12064  *
12065  * Return codes
12066  *   0 - successful
12067  *   other values - error
12068  **/
12069 static int
12070 lpfc_sli_enable_msix(struct lpfc_hba *phba)
12071 {
12072 	int rc;
12073 	LPFC_MBOXQ_t *pmb;
12074 
12075 	/* Set up MSI-X multi-message vectors */
12076 	rc = pci_alloc_irq_vectors(phba->pcidev,
12077 			LPFC_MSIX_VECTORS, LPFC_MSIX_VECTORS, PCI_IRQ_MSIX);
12078 	if (rc < 0) {
12079 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12080 				"0420 PCI enable MSI-X failed (%d)\n", rc);
12081 		goto vec_fail_out;
12082 	}
12083 
12084 	/*
12085 	 * Assign MSI-X vectors to interrupt handlers
12086 	 */
12087 
12088 	/* vector-0 is associated to slow-path handler */
12089 	rc = request_irq(pci_irq_vector(phba->pcidev, 0),
12090 			 &lpfc_sli_sp_intr_handler, 0,
12091 			 LPFC_SP_DRIVER_HANDLER_NAME, phba);
12092 	if (rc) {
12093 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
12094 				"0421 MSI-X slow-path request_irq failed "
12095 				"(%d)\n", rc);
12096 		goto msi_fail_out;
12097 	}
12098 
12099 	/* vector-1 is associated to fast-path handler */
12100 	rc = request_irq(pci_irq_vector(phba->pcidev, 1),
12101 			 &lpfc_sli_fp_intr_handler, 0,
12102 			 LPFC_FP_DRIVER_HANDLER_NAME, phba);
12103 
12104 	if (rc) {
12105 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
12106 				"0429 MSI-X fast-path request_irq failed "
12107 				"(%d)\n", rc);
12108 		goto irq_fail_out;
12109 	}
12110 
12111 	/*
12112 	 * Configure HBA MSI-X attention conditions to messages
12113 	 */
12114 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
12115 
12116 	if (!pmb) {
12117 		rc = -ENOMEM;
12118 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12119 				"0474 Unable to allocate memory for issuing "
12120 				"MBOX_CONFIG_MSI command\n");
12121 		goto mem_fail_out;
12122 	}
12123 	rc = lpfc_config_msi(phba, pmb);
12124 	if (rc)
12125 		goto mbx_fail_out;
12126 	rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
12127 	if (rc != MBX_SUCCESS) {
12128 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX,
12129 				"0351 Config MSI mailbox command failed, "
12130 				"mbxCmd x%x, mbxStatus x%x\n",
12131 				pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus);
12132 		goto mbx_fail_out;
12133 	}
12134 
12135 	/* Free memory allocated for mailbox command */
12136 	mempool_free(pmb, phba->mbox_mem_pool);
12137 	return rc;
12138 
12139 mbx_fail_out:
12140 	/* Free memory allocated for mailbox command */
12141 	mempool_free(pmb, phba->mbox_mem_pool);
12142 
12143 mem_fail_out:
12144 	/* free the irq already requested */
12145 	free_irq(pci_irq_vector(phba->pcidev, 1), phba);
12146 
12147 irq_fail_out:
12148 	/* free the irq already requested */
12149 	free_irq(pci_irq_vector(phba->pcidev, 0), phba);
12150 
12151 msi_fail_out:
12152 	/* Unconfigure MSI-X capability structure */
12153 	pci_free_irq_vectors(phba->pcidev);
12154 
12155 vec_fail_out:
12156 	return rc;
12157 }
12158 
12159 /**
12160  * lpfc_sli_enable_msi - Enable MSI interrupt mode on SLI-3 device.
12161  * @phba: pointer to lpfc hba data structure.
12162  *
12163  * This routine is invoked to enable the MSI interrupt mode to device with
12164  * SLI-3 interface spec. The kernel function pci_enable_msi() is called to
12165  * enable the MSI vector. The device driver is responsible for calling the
12166  * request_irq() to register MSI vector with a interrupt the handler, which
12167  * is done in this function.
12168  *
12169  * Return codes
12170  * 	0 - successful
12171  * 	other values - error
12172  */
12173 static int
12174 lpfc_sli_enable_msi(struct lpfc_hba *phba)
12175 {
12176 	int rc;
12177 
12178 	rc = pci_enable_msi(phba->pcidev);
12179 	if (!rc)
12180 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12181 				"0012 PCI enable MSI mode success.\n");
12182 	else {
12183 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12184 				"0471 PCI enable MSI mode failed (%d)\n", rc);
12185 		return rc;
12186 	}
12187 
12188 	rc = request_irq(phba->pcidev->irq, lpfc_sli_intr_handler,
12189 			 0, LPFC_DRIVER_NAME, phba);
12190 	if (rc) {
12191 		pci_disable_msi(phba->pcidev);
12192 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
12193 				"0478 MSI request_irq failed (%d)\n", rc);
12194 	}
12195 	return rc;
12196 }
12197 
12198 /**
12199  * lpfc_sli_enable_intr - Enable device interrupt to SLI-3 device.
12200  * @phba: pointer to lpfc hba data structure.
12201  * @cfg_mode: Interrupt configuration mode (INTx, MSI or MSI-X).
12202  *
12203  * This routine is invoked to enable device interrupt and associate driver's
12204  * interrupt handler(s) to interrupt vector(s) to device with SLI-3 interface
12205  * spec. Depends on the interrupt mode configured to the driver, the driver
12206  * will try to fallback from the configured interrupt mode to an interrupt
12207  * mode which is supported by the platform, kernel, and device in the order
12208  * of:
12209  * MSI-X -> MSI -> IRQ.
12210  *
12211  * Return codes
12212  *   0 - successful
12213  *   other values - error
12214  **/
12215 static uint32_t
12216 lpfc_sli_enable_intr(struct lpfc_hba *phba, uint32_t cfg_mode)
12217 {
12218 	uint32_t intr_mode = LPFC_INTR_ERROR;
12219 	int retval;
12220 
12221 	/* Need to issue conf_port mbox cmd before conf_msi mbox cmd */
12222 	retval = lpfc_sli_config_port(phba, LPFC_SLI_REV3);
12223 	if (retval)
12224 		return intr_mode;
12225 	clear_bit(HBA_NEEDS_CFG_PORT, &phba->hba_flag);
12226 
12227 	if (cfg_mode == 2) {
12228 		/* Now, try to enable MSI-X interrupt mode */
12229 		retval = lpfc_sli_enable_msix(phba);
12230 		if (!retval) {
12231 			/* Indicate initialization to MSI-X mode */
12232 			phba->intr_type = MSIX;
12233 			intr_mode = 2;
12234 		}
12235 	}
12236 
12237 	/* Fallback to MSI if MSI-X initialization failed */
12238 	if (cfg_mode >= 1 && phba->intr_type == NONE) {
12239 		retval = lpfc_sli_enable_msi(phba);
12240 		if (!retval) {
12241 			/* Indicate initialization to MSI mode */
12242 			phba->intr_type = MSI;
12243 			intr_mode = 1;
12244 		}
12245 	}
12246 
12247 	/* Fallback to INTx if both MSI-X/MSI initalization failed */
12248 	if (phba->intr_type == NONE) {
12249 		retval = request_irq(phba->pcidev->irq, lpfc_sli_intr_handler,
12250 				     IRQF_SHARED, LPFC_DRIVER_NAME, phba);
12251 		if (!retval) {
12252 			/* Indicate initialization to INTx mode */
12253 			phba->intr_type = INTx;
12254 			intr_mode = 0;
12255 		}
12256 	}
12257 	return intr_mode;
12258 }
12259 
12260 /**
12261  * lpfc_sli_disable_intr - Disable device interrupt to SLI-3 device.
12262  * @phba: pointer to lpfc hba data structure.
12263  *
12264  * This routine is invoked to disable device interrupt and disassociate the
12265  * driver's interrupt handler(s) from interrupt vector(s) to device with
12266  * SLI-3 interface spec. Depending on the interrupt mode, the driver will
12267  * release the interrupt vector(s) for the message signaled interrupt.
12268  **/
12269 static void
12270 lpfc_sli_disable_intr(struct lpfc_hba *phba)
12271 {
12272 	int nr_irqs, i;
12273 
12274 	if (phba->intr_type == MSIX)
12275 		nr_irqs = LPFC_MSIX_VECTORS;
12276 	else
12277 		nr_irqs = 1;
12278 
12279 	for (i = 0; i < nr_irqs; i++)
12280 		free_irq(pci_irq_vector(phba->pcidev, i), phba);
12281 	pci_free_irq_vectors(phba->pcidev);
12282 
12283 	/* Reset interrupt management states */
12284 	phba->intr_type = NONE;
12285 	phba->sli.slistat.sli_intr = 0;
12286 }
12287 
12288 /**
12289  * lpfc_find_cpu_handle - Find the CPU that corresponds to the specified Queue
12290  * @phba: pointer to lpfc hba data structure.
12291  * @id: EQ vector index or Hardware Queue index
12292  * @match: LPFC_FIND_BY_EQ = match by EQ
12293  *         LPFC_FIND_BY_HDWQ = match by Hardware Queue
12294  * Return the CPU that matches the selection criteria
12295  */
12296 static uint16_t
12297 lpfc_find_cpu_handle(struct lpfc_hba *phba, uint16_t id, int match)
12298 {
12299 	struct lpfc_vector_map_info *cpup;
12300 	int cpu;
12301 
12302 	/* Loop through all CPUs */
12303 	for_each_present_cpu(cpu) {
12304 		cpup = &phba->sli4_hba.cpu_map[cpu];
12305 
12306 		/* If we are matching by EQ, there may be multiple CPUs using
12307 		 * using the same vector, so select the one with
12308 		 * LPFC_CPU_FIRST_IRQ set.
12309 		 */
12310 		if ((match == LPFC_FIND_BY_EQ) &&
12311 		    (cpup->flag & LPFC_CPU_FIRST_IRQ) &&
12312 		    (cpup->eq == id))
12313 			return cpu;
12314 
12315 		/* If matching by HDWQ, select the first CPU that matches */
12316 		if ((match == LPFC_FIND_BY_HDWQ) && (cpup->hdwq == id))
12317 			return cpu;
12318 	}
12319 	return 0;
12320 }
12321 
12322 #ifdef CONFIG_X86
12323 /**
12324  * lpfc_find_hyper - Determine if the CPU map entry is hyper-threaded
12325  * @phba: pointer to lpfc hba data structure.
12326  * @cpu: CPU map index
12327  * @phys_id: CPU package physical id
12328  * @core_id: CPU core id
12329  */
12330 static int
12331 lpfc_find_hyper(struct lpfc_hba *phba, int cpu,
12332 		uint16_t phys_id, uint16_t core_id)
12333 {
12334 	struct lpfc_vector_map_info *cpup;
12335 	int idx;
12336 
12337 	for_each_present_cpu(idx) {
12338 		cpup = &phba->sli4_hba.cpu_map[idx];
12339 		/* Does the cpup match the one we are looking for */
12340 		if ((cpup->phys_id == phys_id) &&
12341 		    (cpup->core_id == core_id) &&
12342 		    (cpu != idx))
12343 			return 1;
12344 	}
12345 	return 0;
12346 }
12347 #endif
12348 
12349 /*
12350  * lpfc_assign_eq_map_info - Assigns eq for vector_map structure
12351  * @phba: pointer to lpfc hba data structure.
12352  * @eqidx: index for eq and irq vector
12353  * @flag: flags to set for vector_map structure
12354  * @cpu: cpu used to index vector_map structure
12355  *
12356  * The routine assigns eq info into vector_map structure
12357  */
12358 static inline void
12359 lpfc_assign_eq_map_info(struct lpfc_hba *phba, uint16_t eqidx, uint16_t flag,
12360 			unsigned int cpu)
12361 {
12362 	struct lpfc_vector_map_info *cpup = &phba->sli4_hba.cpu_map[cpu];
12363 	struct lpfc_hba_eq_hdl *eqhdl = lpfc_get_eq_hdl(eqidx);
12364 
12365 	cpup->eq = eqidx;
12366 	cpup->flag |= flag;
12367 
12368 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12369 			"3336 Set Affinity: CPU %d irq %d eq %d flag x%x\n",
12370 			cpu, eqhdl->irq, cpup->eq, cpup->flag);
12371 }
12372 
12373 /**
12374  * lpfc_cpu_map_array_init - Initialize cpu_map structure
12375  * @phba: pointer to lpfc hba data structure.
12376  *
12377  * The routine initializes the cpu_map array structure
12378  */
12379 static void
12380 lpfc_cpu_map_array_init(struct lpfc_hba *phba)
12381 {
12382 	struct lpfc_vector_map_info *cpup;
12383 	struct lpfc_eq_intr_info *eqi;
12384 	int cpu;
12385 
12386 	for_each_possible_cpu(cpu) {
12387 		cpup = &phba->sli4_hba.cpu_map[cpu];
12388 		cpup->phys_id = LPFC_VECTOR_MAP_EMPTY;
12389 		cpup->core_id = LPFC_VECTOR_MAP_EMPTY;
12390 		cpup->hdwq = LPFC_VECTOR_MAP_EMPTY;
12391 		cpup->eq = LPFC_VECTOR_MAP_EMPTY;
12392 		cpup->flag = 0;
12393 		eqi = per_cpu_ptr(phba->sli4_hba.eq_info, cpu);
12394 		INIT_LIST_HEAD(&eqi->list);
12395 		eqi->icnt = 0;
12396 	}
12397 }
12398 
12399 /**
12400  * lpfc_hba_eq_hdl_array_init - Initialize hba_eq_hdl structure
12401  * @phba: pointer to lpfc hba data structure.
12402  *
12403  * The routine initializes the hba_eq_hdl array structure
12404  */
12405 static void
12406 lpfc_hba_eq_hdl_array_init(struct lpfc_hba *phba)
12407 {
12408 	struct lpfc_hba_eq_hdl *eqhdl;
12409 	int i;
12410 
12411 	for (i = 0; i < phba->cfg_irq_chann; i++) {
12412 		eqhdl = lpfc_get_eq_hdl(i);
12413 		eqhdl->irq = LPFC_IRQ_EMPTY;
12414 		eqhdl->phba = phba;
12415 	}
12416 }
12417 
12418 /**
12419  * lpfc_cpu_affinity_check - Check vector CPU affinity mappings
12420  * @phba: pointer to lpfc hba data structure.
12421  * @vectors: number of msix vectors allocated.
12422  *
12423  * The routine will figure out the CPU affinity assignment for every
12424  * MSI-X vector allocated for the HBA.
12425  * In addition, the CPU to IO channel mapping will be calculated
12426  * and the phba->sli4_hba.cpu_map array will reflect this.
12427  */
12428 static void
12429 lpfc_cpu_affinity_check(struct lpfc_hba *phba, int vectors)
12430 {
12431 	int i, cpu, idx, next_idx, new_cpu, start_cpu, first_cpu;
12432 	int max_phys_id, min_phys_id;
12433 	int max_core_id, min_core_id;
12434 	struct lpfc_vector_map_info *cpup;
12435 	struct lpfc_vector_map_info *new_cpup;
12436 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
12437 	struct lpfc_hdwq_stat *c_stat;
12438 #endif
12439 
12440 	max_phys_id = 0;
12441 	min_phys_id = LPFC_VECTOR_MAP_EMPTY;
12442 	max_core_id = 0;
12443 	min_core_id = LPFC_VECTOR_MAP_EMPTY;
12444 
12445 	/* Update CPU map with physical id and core id of each CPU */
12446 	for_each_present_cpu(cpu) {
12447 		cpup = &phba->sli4_hba.cpu_map[cpu];
12448 #ifdef CONFIG_X86
12449 		cpup->phys_id = topology_physical_package_id(cpu);
12450 		cpup->core_id = topology_core_id(cpu);
12451 		if (lpfc_find_hyper(phba, cpu, cpup->phys_id, cpup->core_id))
12452 			cpup->flag |= LPFC_CPU_MAP_HYPER;
12453 #else
12454 		/* No distinction between CPUs for other platforms */
12455 		cpup->phys_id = 0;
12456 		cpup->core_id = cpu;
12457 #endif
12458 
12459 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12460 				"3328 CPU %d physid %d coreid %d flag x%x\n",
12461 				cpu, cpup->phys_id, cpup->core_id, cpup->flag);
12462 
12463 		if (cpup->phys_id > max_phys_id)
12464 			max_phys_id = cpup->phys_id;
12465 		if (cpup->phys_id < min_phys_id)
12466 			min_phys_id = cpup->phys_id;
12467 
12468 		if (cpup->core_id > max_core_id)
12469 			max_core_id = cpup->core_id;
12470 		if (cpup->core_id < min_core_id)
12471 			min_core_id = cpup->core_id;
12472 	}
12473 
12474 	/* After looking at each irq vector assigned to this pcidev, its
12475 	 * possible to see that not ALL CPUs have been accounted for.
12476 	 * Next we will set any unassigned (unaffinitized) cpu map
12477 	 * entries to a IRQ on the same phys_id.
12478 	 */
12479 	first_cpu = cpumask_first(cpu_present_mask);
12480 	start_cpu = first_cpu;
12481 
12482 	for_each_present_cpu(cpu) {
12483 		cpup = &phba->sli4_hba.cpu_map[cpu];
12484 
12485 		/* Is this CPU entry unassigned */
12486 		if (cpup->eq == LPFC_VECTOR_MAP_EMPTY) {
12487 			/* Mark CPU as IRQ not assigned by the kernel */
12488 			cpup->flag |= LPFC_CPU_MAP_UNASSIGN;
12489 
12490 			/* If so, find a new_cpup that is on the SAME
12491 			 * phys_id as cpup. start_cpu will start where we
12492 			 * left off so all unassigned entries don't get assigned
12493 			 * the IRQ of the first entry.
12494 			 */
12495 			new_cpu = start_cpu;
12496 			for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12497 				new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12498 				if (!(new_cpup->flag & LPFC_CPU_MAP_UNASSIGN) &&
12499 				    (new_cpup->eq != LPFC_VECTOR_MAP_EMPTY) &&
12500 				    (new_cpup->phys_id == cpup->phys_id))
12501 					goto found_same;
12502 				new_cpu = lpfc_next_present_cpu(new_cpu);
12503 			}
12504 			/* At this point, we leave the CPU as unassigned */
12505 			continue;
12506 found_same:
12507 			/* We found a matching phys_id, so copy the IRQ info */
12508 			cpup->eq = new_cpup->eq;
12509 
12510 			/* Bump start_cpu to the next slot to minmize the
12511 			 * chance of having multiple unassigned CPU entries
12512 			 * selecting the same IRQ.
12513 			 */
12514 			start_cpu = lpfc_next_present_cpu(new_cpu);
12515 
12516 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12517 					"3337 Set Affinity: CPU %d "
12518 					"eq %d from peer cpu %d same "
12519 					"phys_id (%d)\n",
12520 					cpu, cpup->eq, new_cpu,
12521 					cpup->phys_id);
12522 		}
12523 	}
12524 
12525 	/* Set any unassigned cpu map entries to a IRQ on any phys_id */
12526 	start_cpu = first_cpu;
12527 
12528 	for_each_present_cpu(cpu) {
12529 		cpup = &phba->sli4_hba.cpu_map[cpu];
12530 
12531 		/* Is this entry unassigned */
12532 		if (cpup->eq == LPFC_VECTOR_MAP_EMPTY) {
12533 			/* Mark it as IRQ not assigned by the kernel */
12534 			cpup->flag |= LPFC_CPU_MAP_UNASSIGN;
12535 
12536 			/* If so, find a new_cpup thats on ANY phys_id
12537 			 * as the cpup. start_cpu will start where we
12538 			 * left off so all unassigned entries don't get
12539 			 * assigned the IRQ of the first entry.
12540 			 */
12541 			new_cpu = start_cpu;
12542 			for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12543 				new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12544 				if (!(new_cpup->flag & LPFC_CPU_MAP_UNASSIGN) &&
12545 				    (new_cpup->eq != LPFC_VECTOR_MAP_EMPTY))
12546 					goto found_any;
12547 				new_cpu = lpfc_next_present_cpu(new_cpu);
12548 			}
12549 			/* We should never leave an entry unassigned */
12550 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12551 					"3339 Set Affinity: CPU %d "
12552 					"eq %d UNASSIGNED\n",
12553 					cpup->hdwq, cpup->eq);
12554 			continue;
12555 found_any:
12556 			/* We found an available entry, copy the IRQ info */
12557 			cpup->eq = new_cpup->eq;
12558 
12559 			/* Bump start_cpu to the next slot to minmize the
12560 			 * chance of having multiple unassigned CPU entries
12561 			 * selecting the same IRQ.
12562 			 */
12563 			start_cpu = lpfc_next_present_cpu(new_cpu);
12564 
12565 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12566 					"3338 Set Affinity: CPU %d "
12567 					"eq %d from peer cpu %d (%d/%d)\n",
12568 					cpu, cpup->eq, new_cpu,
12569 					new_cpup->phys_id, new_cpup->core_id);
12570 		}
12571 	}
12572 
12573 	/* Assign hdwq indices that are unique across all cpus in the map
12574 	 * that are also FIRST_CPUs.
12575 	 */
12576 	idx = 0;
12577 	for_each_present_cpu(cpu) {
12578 		cpup = &phba->sli4_hba.cpu_map[cpu];
12579 
12580 		/* Only FIRST IRQs get a hdwq index assignment. */
12581 		if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
12582 			continue;
12583 
12584 		/* 1 to 1, the first LPFC_CPU_FIRST_IRQ cpus to a unique hdwq */
12585 		cpup->hdwq = idx;
12586 		idx++;
12587 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12588 				"3333 Set Affinity: CPU %d (phys %d core %d): "
12589 				"hdwq %d eq %d flg x%x\n",
12590 				cpu, cpup->phys_id, cpup->core_id,
12591 				cpup->hdwq, cpup->eq, cpup->flag);
12592 	}
12593 	/* Associate a hdwq with each cpu_map entry
12594 	 * This will be 1 to 1 - hdwq to cpu, unless there are less
12595 	 * hardware queues then CPUs. For that case we will just round-robin
12596 	 * the available hardware queues as they get assigned to CPUs.
12597 	 * The next_idx is the idx from the FIRST_CPU loop above to account
12598 	 * for irq_chann < hdwq.  The idx is used for round-robin assignments
12599 	 * and needs to start at 0.
12600 	 */
12601 	next_idx = idx;
12602 	start_cpu = 0;
12603 	idx = 0;
12604 	for_each_present_cpu(cpu) {
12605 		cpup = &phba->sli4_hba.cpu_map[cpu];
12606 
12607 		/* FIRST cpus are already mapped. */
12608 		if (cpup->flag & LPFC_CPU_FIRST_IRQ)
12609 			continue;
12610 
12611 		/* If the cfg_irq_chann < cfg_hdw_queue, set the hdwq
12612 		 * of the unassigned cpus to the next idx so that all
12613 		 * hdw queues are fully utilized.
12614 		 */
12615 		if (next_idx < phba->cfg_hdw_queue) {
12616 			cpup->hdwq = next_idx;
12617 			next_idx++;
12618 			continue;
12619 		}
12620 
12621 		/* Not a First CPU and all hdw_queues are used.  Reuse a
12622 		 * Hardware Queue for another CPU, so be smart about it
12623 		 * and pick one that has its IRQ/EQ mapped to the same phys_id
12624 		 * (CPU package) and core_id.
12625 		 */
12626 		new_cpu = start_cpu;
12627 		for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12628 			new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12629 			if (new_cpup->hdwq != LPFC_VECTOR_MAP_EMPTY &&
12630 			    new_cpup->phys_id == cpup->phys_id &&
12631 			    new_cpup->core_id == cpup->core_id) {
12632 				goto found_hdwq;
12633 			}
12634 			new_cpu = lpfc_next_present_cpu(new_cpu);
12635 		}
12636 
12637 		/* If we can't match both phys_id and core_id,
12638 		 * settle for just a phys_id match.
12639 		 */
12640 		new_cpu = start_cpu;
12641 		for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12642 			new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12643 			if (new_cpup->hdwq != LPFC_VECTOR_MAP_EMPTY &&
12644 			    new_cpup->phys_id == cpup->phys_id)
12645 				goto found_hdwq;
12646 			new_cpu = lpfc_next_present_cpu(new_cpu);
12647 		}
12648 
12649 		/* Otherwise just round robin on cfg_hdw_queue */
12650 		cpup->hdwq = idx % phba->cfg_hdw_queue;
12651 		idx++;
12652 		goto logit;
12653  found_hdwq:
12654 		/* We found an available entry, copy the IRQ info */
12655 		start_cpu = lpfc_next_present_cpu(new_cpu);
12656 		cpup->hdwq = new_cpup->hdwq;
12657  logit:
12658 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12659 				"3335 Set Affinity: CPU %d (phys %d core %d): "
12660 				"hdwq %d eq %d flg x%x\n",
12661 				cpu, cpup->phys_id, cpup->core_id,
12662 				cpup->hdwq, cpup->eq, cpup->flag);
12663 	}
12664 
12665 	/*
12666 	 * Initialize the cpu_map slots for not-present cpus in case
12667 	 * a cpu is hot-added. Perform a simple hdwq round robin assignment.
12668 	 */
12669 	idx = 0;
12670 	for_each_possible_cpu(cpu) {
12671 		cpup = &phba->sli4_hba.cpu_map[cpu];
12672 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
12673 		c_stat = per_cpu_ptr(phba->sli4_hba.c_stat, cpu);
12674 		c_stat->hdwq_no = cpup->hdwq;
12675 #endif
12676 		if (cpup->hdwq != LPFC_VECTOR_MAP_EMPTY)
12677 			continue;
12678 
12679 		cpup->hdwq = idx++ % phba->cfg_hdw_queue;
12680 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
12681 		c_stat->hdwq_no = cpup->hdwq;
12682 #endif
12683 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12684 				"3340 Set Affinity: not present "
12685 				"CPU %d hdwq %d\n",
12686 				cpu, cpup->hdwq);
12687 	}
12688 
12689 	/* The cpu_map array will be used later during initialization
12690 	 * when EQ / CQ / WQs are allocated and configured.
12691 	 */
12692 	return;
12693 }
12694 
12695 /**
12696  * lpfc_cpuhp_get_eq
12697  *
12698  * @phba:   pointer to lpfc hba data structure.
12699  * @cpu:    cpu going offline
12700  * @eqlist: eq list to append to
12701  */
12702 static int
12703 lpfc_cpuhp_get_eq(struct lpfc_hba *phba, unsigned int cpu,
12704 		  struct list_head *eqlist)
12705 {
12706 	const struct cpumask *maskp;
12707 	struct lpfc_queue *eq;
12708 	struct cpumask *tmp;
12709 	u16 idx;
12710 
12711 	tmp = kzalloc(cpumask_size(), GFP_KERNEL);
12712 	if (!tmp)
12713 		return -ENOMEM;
12714 
12715 	for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
12716 		maskp = pci_irq_get_affinity(phba->pcidev, idx);
12717 		if (!maskp)
12718 			continue;
12719 		/*
12720 		 * if irq is not affinitized to the cpu going
12721 		 * then we don't need to poll the eq attached
12722 		 * to it.
12723 		 */
12724 		if (!cpumask_and(tmp, maskp, cpumask_of(cpu)))
12725 			continue;
12726 		/* get the cpus that are online and are affini-
12727 		 * tized to this irq vector.  If the count is
12728 		 * more than 1 then cpuhp is not going to shut-
12729 		 * down this vector.  Since this cpu has not
12730 		 * gone offline yet, we need >1.
12731 		 */
12732 		cpumask_and(tmp, maskp, cpu_online_mask);
12733 		if (cpumask_weight(tmp) > 1)
12734 			continue;
12735 
12736 		/* Now that we have an irq to shutdown, get the eq
12737 		 * mapped to this irq.  Note: multiple hdwq's in
12738 		 * the software can share an eq, but eventually
12739 		 * only eq will be mapped to this vector
12740 		 */
12741 		eq = phba->sli4_hba.hba_eq_hdl[idx].eq;
12742 		list_add(&eq->_poll_list, eqlist);
12743 	}
12744 	kfree(tmp);
12745 	return 0;
12746 }
12747 
12748 static void __lpfc_cpuhp_remove(struct lpfc_hba *phba)
12749 {
12750 	if (phba->sli_rev != LPFC_SLI_REV4)
12751 		return;
12752 
12753 	cpuhp_state_remove_instance_nocalls(lpfc_cpuhp_state,
12754 					    &phba->cpuhp);
12755 	/*
12756 	 * unregistering the instance doesn't stop the polling
12757 	 * timer. Wait for the poll timer to retire.
12758 	 */
12759 	synchronize_rcu();
12760 	timer_delete_sync(&phba->cpuhp_poll_timer);
12761 }
12762 
12763 static void lpfc_cpuhp_remove(struct lpfc_hba *phba)
12764 {
12765 	if (phba->pport &&
12766 	    test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag))
12767 		return;
12768 
12769 	__lpfc_cpuhp_remove(phba);
12770 }
12771 
12772 static void lpfc_cpuhp_add(struct lpfc_hba *phba)
12773 {
12774 	if (phba->sli_rev != LPFC_SLI_REV4)
12775 		return;
12776 
12777 	rcu_read_lock();
12778 
12779 	if (!list_empty(&phba->poll_list))
12780 		mod_timer(&phba->cpuhp_poll_timer,
12781 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
12782 
12783 	rcu_read_unlock();
12784 
12785 	cpuhp_state_add_instance_nocalls(lpfc_cpuhp_state,
12786 					 &phba->cpuhp);
12787 }
12788 
12789 static int __lpfc_cpuhp_checks(struct lpfc_hba *phba, int *retval)
12790 {
12791 	if (test_bit(FC_UNLOADING, &phba->pport->load_flag)) {
12792 		*retval = -EAGAIN;
12793 		return true;
12794 	}
12795 
12796 	if (phba->sli_rev != LPFC_SLI_REV4) {
12797 		*retval = 0;
12798 		return true;
12799 	}
12800 
12801 	/* proceed with the hotplug */
12802 	return false;
12803 }
12804 
12805 /**
12806  * lpfc_irq_set_aff - set IRQ affinity
12807  * @eqhdl: EQ handle
12808  * @cpu: cpu to set affinity
12809  *
12810  **/
12811 static inline void
12812 lpfc_irq_set_aff(struct lpfc_hba_eq_hdl *eqhdl, unsigned int cpu)
12813 {
12814 	cpumask_clear(&eqhdl->aff_mask);
12815 	cpumask_set_cpu(cpu, &eqhdl->aff_mask);
12816 	irq_set_status_flags(eqhdl->irq, IRQ_NO_BALANCING);
12817 	irq_set_affinity(eqhdl->irq, &eqhdl->aff_mask);
12818 }
12819 
12820 /**
12821  * lpfc_irq_clear_aff - clear IRQ affinity
12822  * @eqhdl: EQ handle
12823  *
12824  **/
12825 static inline void
12826 lpfc_irq_clear_aff(struct lpfc_hba_eq_hdl *eqhdl)
12827 {
12828 	cpumask_clear(&eqhdl->aff_mask);
12829 	irq_clear_status_flags(eqhdl->irq, IRQ_NO_BALANCING);
12830 }
12831 
12832 /**
12833  * lpfc_irq_rebalance - rebalances IRQ affinity according to cpuhp event
12834  * @phba: pointer to HBA context object.
12835  * @cpu: cpu going offline/online
12836  * @offline: true, cpu is going offline. false, cpu is coming online.
12837  *
12838  * If cpu is going offline, we'll try our best effort to find the next
12839  * online cpu on the phba's original_mask and migrate all offlining IRQ
12840  * affinities.
12841  *
12842  * If cpu is coming online, reaffinitize the IRQ back to the onlining cpu.
12843  *
12844  * Note: Call only if NUMA or NHT mode is enabled, otherwise rely on
12845  *	 PCI_IRQ_AFFINITY to auto-manage IRQ affinity.
12846  *
12847  **/
12848 static void
12849 lpfc_irq_rebalance(struct lpfc_hba *phba, unsigned int cpu, bool offline)
12850 {
12851 	struct lpfc_vector_map_info *cpup;
12852 	struct cpumask *aff_mask;
12853 	unsigned int cpu_select, cpu_next, idx;
12854 	const struct cpumask *orig_mask;
12855 
12856 	if (phba->irq_chann_mode == NORMAL_MODE)
12857 		return;
12858 
12859 	orig_mask = &phba->sli4_hba.irq_aff_mask;
12860 
12861 	if (!cpumask_test_cpu(cpu, orig_mask))
12862 		return;
12863 
12864 	cpup = &phba->sli4_hba.cpu_map[cpu];
12865 
12866 	if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
12867 		return;
12868 
12869 	if (offline) {
12870 		/* Find next online CPU on original mask */
12871 		cpu_next = cpumask_next_wrap(cpu, orig_mask);
12872 		cpu_select = lpfc_next_online_cpu(orig_mask, cpu_next);
12873 
12874 		/* Found a valid CPU */
12875 		if ((cpu_select < nr_cpu_ids) && (cpu_select != cpu)) {
12876 			/* Go through each eqhdl and ensure offlining
12877 			 * cpu aff_mask is migrated
12878 			 */
12879 			for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
12880 				aff_mask = lpfc_get_aff_mask(idx);
12881 
12882 				/* Migrate affinity */
12883 				if (cpumask_test_cpu(cpu, aff_mask))
12884 					lpfc_irq_set_aff(lpfc_get_eq_hdl(idx),
12885 							 cpu_select);
12886 			}
12887 		} else {
12888 			/* Rely on irqbalance if no online CPUs left on NUMA */
12889 			for (idx = 0; idx < phba->cfg_irq_chann; idx++)
12890 				lpfc_irq_clear_aff(lpfc_get_eq_hdl(idx));
12891 		}
12892 	} else {
12893 		/* Migrate affinity back to this CPU */
12894 		lpfc_irq_set_aff(lpfc_get_eq_hdl(cpup->eq), cpu);
12895 	}
12896 }
12897 
12898 static int lpfc_cpu_offline(unsigned int cpu, struct hlist_node *node)
12899 {
12900 	struct lpfc_hba *phba = hlist_entry_safe(node, struct lpfc_hba, cpuhp);
12901 	struct lpfc_queue *eq, *next;
12902 	LIST_HEAD(eqlist);
12903 	int retval;
12904 
12905 	if (!phba) {
12906 		WARN_ONCE(!phba, "cpu: %u. phba:NULL", raw_smp_processor_id());
12907 		return 0;
12908 	}
12909 
12910 	if (__lpfc_cpuhp_checks(phba, &retval))
12911 		return retval;
12912 
12913 	lpfc_irq_rebalance(phba, cpu, true);
12914 
12915 	retval = lpfc_cpuhp_get_eq(phba, cpu, &eqlist);
12916 	if (retval)
12917 		return retval;
12918 
12919 	/* start polling on these eq's */
12920 	list_for_each_entry_safe(eq, next, &eqlist, _poll_list) {
12921 		list_del_init(&eq->_poll_list);
12922 		lpfc_sli4_start_polling(eq);
12923 	}
12924 
12925 	return 0;
12926 }
12927 
12928 static int lpfc_cpu_online(unsigned int cpu, struct hlist_node *node)
12929 {
12930 	struct lpfc_hba *phba = hlist_entry_safe(node, struct lpfc_hba, cpuhp);
12931 	struct lpfc_queue *eq, *next;
12932 	unsigned int n;
12933 	int retval;
12934 
12935 	if (!phba) {
12936 		WARN_ONCE(!phba, "cpu: %u. phba:NULL", raw_smp_processor_id());
12937 		return 0;
12938 	}
12939 
12940 	if (__lpfc_cpuhp_checks(phba, &retval))
12941 		return retval;
12942 
12943 	lpfc_irq_rebalance(phba, cpu, false);
12944 
12945 	list_for_each_entry_safe(eq, next, &phba->poll_list, _poll_list) {
12946 		n = lpfc_find_cpu_handle(phba, eq->hdwq, LPFC_FIND_BY_HDWQ);
12947 		if (n == cpu)
12948 			lpfc_sli4_stop_polling(eq);
12949 	}
12950 
12951 	return 0;
12952 }
12953 
12954 /**
12955  * lpfc_sli4_enable_msix - Enable MSI-X interrupt mode to SLI-4 device
12956  * @phba: pointer to lpfc hba data structure.
12957  *
12958  * This routine is invoked to enable the MSI-X interrupt vectors to device
12959  * with SLI-4 interface spec.  It also allocates MSI-X vectors and maps them
12960  * to cpus on the system.
12961  *
12962  * When cfg_irq_numa is enabled, the adapter will only allocate vectors for
12963  * the number of cpus on the same numa node as this adapter.  The vectors are
12964  * allocated without requesting OS affinity mapping.  A vector will be
12965  * allocated and assigned to each online and offline cpu.  If the cpu is
12966  * online, then affinity will be set to that cpu.  If the cpu is offline, then
12967  * affinity will be set to the nearest peer cpu within the numa node that is
12968  * online.  If there are no online cpus within the numa node, affinity is not
12969  * assigned and the OS may do as it pleases. Note: cpu vector affinity mapping
12970  * is consistent with the way cpu online/offline is handled when cfg_irq_numa is
12971  * configured.
12972  *
12973  * If numa mode is not enabled and there is more than 1 vector allocated, then
12974  * the driver relies on the managed irq interface where the OS assigns vector to
12975  * cpu affinity.  The driver will then use that affinity mapping to setup its
12976  * cpu mapping table.
12977  *
12978  * Return codes
12979  * 0 - successful
12980  * other values - error
12981  **/
12982 static int
12983 lpfc_sli4_enable_msix(struct lpfc_hba *phba)
12984 {
12985 	int vectors, rc, index;
12986 	char *name;
12987 	const struct cpumask *aff_mask = NULL;
12988 	unsigned int cpu = 0, cpu_cnt = 0, cpu_select = nr_cpu_ids;
12989 	struct lpfc_vector_map_info *cpup;
12990 	struct lpfc_hba_eq_hdl *eqhdl;
12991 	const struct cpumask *maskp;
12992 	unsigned int flags = PCI_IRQ_MSIX;
12993 
12994 	/* Set up MSI-X multi-message vectors */
12995 	vectors = phba->cfg_irq_chann;
12996 
12997 	if (phba->irq_chann_mode != NORMAL_MODE)
12998 		aff_mask = &phba->sli4_hba.irq_aff_mask;
12999 
13000 	if (aff_mask) {
13001 		cpu_cnt = cpumask_weight(aff_mask);
13002 		vectors = min(phba->cfg_irq_chann, cpu_cnt);
13003 
13004 		/* cpu: iterates over aff_mask including offline or online
13005 		 * cpu_select: iterates over online aff_mask to set affinity
13006 		 */
13007 		cpu = cpumask_first(aff_mask);
13008 		cpu_select = lpfc_next_online_cpu(aff_mask, cpu);
13009 	} else {
13010 		flags |= PCI_IRQ_AFFINITY;
13011 	}
13012 
13013 	rc = pci_alloc_irq_vectors(phba->pcidev, 1, vectors, flags);
13014 	if (rc < 0) {
13015 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13016 				"0484 PCI enable MSI-X failed (%d)\n", rc);
13017 		goto vec_fail_out;
13018 	}
13019 	vectors = rc;
13020 
13021 	/* Assign MSI-X vectors to interrupt handlers */
13022 	for (index = 0; index < vectors; index++) {
13023 		eqhdl = lpfc_get_eq_hdl(index);
13024 		name = eqhdl->handler_name;
13025 		memset(name, 0, LPFC_SLI4_HANDLER_NAME_SZ);
13026 		snprintf(name, LPFC_SLI4_HANDLER_NAME_SZ,
13027 			 LPFC_DRIVER_HANDLER_NAME"%d", index);
13028 
13029 		eqhdl->idx = index;
13030 		rc = pci_irq_vector(phba->pcidev, index);
13031 		if (rc < 0) {
13032 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13033 					"0489 MSI-X fast-path (%d) "
13034 					"pci_irq_vec failed (%d)\n", index, rc);
13035 			goto cfg_fail_out;
13036 		}
13037 		eqhdl->irq = rc;
13038 
13039 		rc = request_threaded_irq(eqhdl->irq,
13040 					  &lpfc_sli4_hba_intr_handler,
13041 					  &lpfc_sli4_hba_intr_handler_th,
13042 					  0, name, eqhdl);
13043 		if (rc) {
13044 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13045 					"0486 MSI-X fast-path (%d) "
13046 					"request_irq failed (%d)\n", index, rc);
13047 			goto cfg_fail_out;
13048 		}
13049 
13050 		if (aff_mask) {
13051 			/* If found a neighboring online cpu, set affinity */
13052 			if (cpu_select < nr_cpu_ids)
13053 				lpfc_irq_set_aff(eqhdl, cpu_select);
13054 
13055 			/* Assign EQ to cpu_map */
13056 			lpfc_assign_eq_map_info(phba, index,
13057 						LPFC_CPU_FIRST_IRQ,
13058 						cpu);
13059 
13060 			/* Iterate to next offline or online cpu in aff_mask */
13061 			cpu = cpumask_next(cpu, aff_mask);
13062 
13063 			/* Reached the end of the aff_mask */
13064 			if (cpu >= nr_cpu_ids)
13065 				break;
13066 
13067 			/* Find next online cpu in aff_mask to set affinity */
13068 			cpu_select = lpfc_next_online_cpu(aff_mask, cpu);
13069 		} else if (vectors == 1) {
13070 			cpu = cpumask_first(cpu_present_mask);
13071 			lpfc_assign_eq_map_info(phba, index, LPFC_CPU_FIRST_IRQ,
13072 						cpu);
13073 		} else {
13074 			maskp = pci_irq_get_affinity(phba->pcidev, index);
13075 
13076 			/* Loop through all CPUs associated with vector index */
13077 			for_each_cpu_and(cpu, maskp, cpu_present_mask) {
13078 				cpup = &phba->sli4_hba.cpu_map[cpu];
13079 
13080 				/* If this is the first CPU thats assigned to
13081 				 * this vector, set LPFC_CPU_FIRST_IRQ.
13082 				 *
13083 				 * With certain platforms its possible that irq
13084 				 * vectors are affinitized to all the cpu's.
13085 				 * This can result in each cpu_map.eq to be set
13086 				 * to the last vector, resulting in overwrite
13087 				 * of all the previous cpu_map.eq.  Ensure that
13088 				 * each vector receives a place in cpu_map.
13089 				 * Later call to lpfc_cpu_affinity_check will
13090 				 * ensure we are nicely balanced out.
13091 				 */
13092 				if (cpup->eq != LPFC_VECTOR_MAP_EMPTY)
13093 					continue;
13094 				lpfc_assign_eq_map_info(phba, index,
13095 							LPFC_CPU_FIRST_IRQ,
13096 							cpu);
13097 				break;
13098 			}
13099 		}
13100 	}
13101 
13102 	if (vectors != phba->cfg_irq_chann) {
13103 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13104 				"3238 Reducing IO channels to match number of "
13105 				"MSI-X vectors, requested %d got %d\n",
13106 				phba->cfg_irq_chann, vectors);
13107 		if (phba->cfg_irq_chann > vectors)
13108 			phba->cfg_irq_chann = vectors;
13109 	}
13110 
13111 	return rc;
13112 
13113 cfg_fail_out:
13114 	/* free the irq already requested */
13115 	for (--index; index >= 0; index--) {
13116 		eqhdl = lpfc_get_eq_hdl(index);
13117 		lpfc_irq_clear_aff(eqhdl);
13118 		free_irq(eqhdl->irq, eqhdl);
13119 	}
13120 
13121 	/* Unconfigure MSI-X capability structure */
13122 	pci_free_irq_vectors(phba->pcidev);
13123 
13124 vec_fail_out:
13125 	return rc;
13126 }
13127 
13128 /**
13129  * lpfc_sli4_enable_msi - Enable MSI interrupt mode to SLI-4 device
13130  * @phba: pointer to lpfc hba data structure.
13131  *
13132  * This routine is invoked to enable the MSI interrupt mode to device with
13133  * SLI-4 interface spec. The kernel function pci_alloc_irq_vectors() is
13134  * called to enable the MSI vector. The device driver is responsible for
13135  * calling the request_irq() to register MSI vector with a interrupt the
13136  * handler, which is done in this function.
13137  *
13138  * Return codes
13139  * 	0 - successful
13140  * 	other values - error
13141  **/
13142 static int
13143 lpfc_sli4_enable_msi(struct lpfc_hba *phba)
13144 {
13145 	int rc, index;
13146 	unsigned int cpu;
13147 	struct lpfc_hba_eq_hdl *eqhdl;
13148 
13149 	rc = pci_alloc_irq_vectors(phba->pcidev, 1, 1,
13150 				   PCI_IRQ_MSI | PCI_IRQ_AFFINITY);
13151 	if (rc > 0)
13152 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13153 				"0487 PCI enable MSI mode success.\n");
13154 	else {
13155 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13156 				"0488 PCI enable MSI mode failed (%d)\n", rc);
13157 		return rc ? rc : -1;
13158 	}
13159 
13160 	rc = request_irq(phba->pcidev->irq, lpfc_sli4_intr_handler,
13161 			 0, LPFC_DRIVER_NAME, phba);
13162 	if (rc) {
13163 		pci_free_irq_vectors(phba->pcidev);
13164 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13165 				"0490 MSI request_irq failed (%d)\n", rc);
13166 		return rc;
13167 	}
13168 
13169 	eqhdl = lpfc_get_eq_hdl(0);
13170 	rc = pci_irq_vector(phba->pcidev, 0);
13171 	if (rc < 0) {
13172 		free_irq(phba->pcidev->irq, phba);
13173 		pci_free_irq_vectors(phba->pcidev);
13174 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13175 				"0496 MSI pci_irq_vec failed (%d)\n", rc);
13176 		return rc;
13177 	}
13178 	eqhdl->irq = rc;
13179 
13180 	cpu = cpumask_first(cpu_present_mask);
13181 	lpfc_assign_eq_map_info(phba, 0, LPFC_CPU_FIRST_IRQ, cpu);
13182 
13183 	for (index = 0; index < phba->cfg_irq_chann; index++) {
13184 		eqhdl = lpfc_get_eq_hdl(index);
13185 		eqhdl->idx = index;
13186 	}
13187 
13188 	return 0;
13189 }
13190 
13191 /**
13192  * lpfc_sli4_enable_intr - Enable device interrupt to SLI-4 device
13193  * @phba: pointer to lpfc hba data structure.
13194  * @cfg_mode: Interrupt configuration mode (INTx, MSI or MSI-X).
13195  *
13196  * This routine is invoked to enable device interrupt and associate driver's
13197  * interrupt handler(s) to interrupt vector(s) to device with SLI-4
13198  * interface spec. Depends on the interrupt mode configured to the driver,
13199  * the driver will try to fallback from the configured interrupt mode to an
13200  * interrupt mode which is supported by the platform, kernel, and device in
13201  * the order of:
13202  * MSI-X -> MSI -> IRQ.
13203  *
13204  * Return codes
13205  *	Interrupt mode (2, 1, 0) - successful
13206  *	LPFC_INTR_ERROR - error
13207  **/
13208 static uint32_t
13209 lpfc_sli4_enable_intr(struct lpfc_hba *phba, uint32_t cfg_mode)
13210 {
13211 	uint32_t intr_mode = LPFC_INTR_ERROR;
13212 	int retval, idx;
13213 
13214 	if (cfg_mode == 2) {
13215 		/* Preparation before conf_msi mbox cmd */
13216 		retval = 0;
13217 		if (!retval) {
13218 			/* Now, try to enable MSI-X interrupt mode */
13219 			retval = lpfc_sli4_enable_msix(phba);
13220 			if (!retval) {
13221 				/* Indicate initialization to MSI-X mode */
13222 				phba->intr_type = MSIX;
13223 				intr_mode = 2;
13224 			}
13225 		}
13226 	}
13227 
13228 	/* Fallback to MSI if MSI-X initialization failed */
13229 	if (cfg_mode >= 1 && phba->intr_type == NONE) {
13230 		retval = lpfc_sli4_enable_msi(phba);
13231 		if (!retval) {
13232 			/* Indicate initialization to MSI mode */
13233 			phba->intr_type = MSI;
13234 			intr_mode = 1;
13235 		}
13236 	}
13237 
13238 	/* Fallback to INTx if both MSI-X/MSI initalization failed */
13239 	if (phba->intr_type == NONE) {
13240 		retval = request_irq(phba->pcidev->irq, lpfc_sli4_intr_handler,
13241 				     IRQF_SHARED, LPFC_DRIVER_NAME, phba);
13242 		if (!retval) {
13243 			struct lpfc_hba_eq_hdl *eqhdl;
13244 			unsigned int cpu;
13245 
13246 			/* Indicate initialization to INTx mode */
13247 			phba->intr_type = INTx;
13248 			intr_mode = 0;
13249 
13250 			eqhdl = lpfc_get_eq_hdl(0);
13251 			retval = pci_irq_vector(phba->pcidev, 0);
13252 			if (retval < 0) {
13253 				free_irq(phba->pcidev->irq, phba);
13254 				lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13255 					"0502 INTR pci_irq_vec failed (%d)\n",
13256 					 retval);
13257 				return LPFC_INTR_ERROR;
13258 			}
13259 			eqhdl->irq = retval;
13260 
13261 			cpu = cpumask_first(cpu_present_mask);
13262 			lpfc_assign_eq_map_info(phba, 0, LPFC_CPU_FIRST_IRQ,
13263 						cpu);
13264 			for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
13265 				eqhdl = lpfc_get_eq_hdl(idx);
13266 				eqhdl->idx = idx;
13267 			}
13268 		}
13269 	}
13270 	return intr_mode;
13271 }
13272 
13273 /**
13274  * lpfc_sli4_disable_intr - Disable device interrupt to SLI-4 device
13275  * @phba: pointer to lpfc hba data structure.
13276  *
13277  * This routine is invoked to disable device interrupt and disassociate
13278  * the driver's interrupt handler(s) from interrupt vector(s) to device
13279  * with SLI-4 interface spec. Depending on the interrupt mode, the driver
13280  * will release the interrupt vector(s) for the message signaled interrupt.
13281  **/
13282 static void
13283 lpfc_sli4_disable_intr(struct lpfc_hba *phba)
13284 {
13285 	/* Disable the currently initialized interrupt mode */
13286 	if (phba->intr_type == MSIX) {
13287 		int index;
13288 		struct lpfc_hba_eq_hdl *eqhdl;
13289 
13290 		/* Free up MSI-X multi-message vectors */
13291 		for (index = 0; index < phba->cfg_irq_chann; index++) {
13292 			eqhdl = lpfc_get_eq_hdl(index);
13293 			lpfc_irq_clear_aff(eqhdl);
13294 			free_irq(eqhdl->irq, eqhdl);
13295 		}
13296 	} else {
13297 		free_irq(phba->pcidev->irq, phba);
13298 	}
13299 
13300 	pci_free_irq_vectors(phba->pcidev);
13301 
13302 	/* Reset interrupt management states */
13303 	phba->intr_type = NONE;
13304 	phba->sli.slistat.sli_intr = 0;
13305 }
13306 
13307 /**
13308  * lpfc_unset_hba - Unset SLI3 hba device initialization
13309  * @phba: pointer to lpfc hba data structure.
13310  *
13311  * This routine is invoked to unset the HBA device initialization steps to
13312  * a device with SLI-3 interface spec.
13313  **/
13314 static void
13315 lpfc_unset_hba(struct lpfc_hba *phba)
13316 {
13317 	set_bit(FC_UNLOADING, &phba->pport->load_flag);
13318 
13319 	kfree(phba->vpi_bmask);
13320 	kfree(phba->vpi_ids);
13321 
13322 	lpfc_stop_hba_timers(phba);
13323 
13324 	phba->pport->work_port_events = 0;
13325 
13326 	lpfc_sli_hba_down(phba);
13327 
13328 	lpfc_sli_brdrestart(phba);
13329 
13330 	lpfc_sli_disable_intr(phba);
13331 
13332 	return;
13333 }
13334 
13335 /**
13336  * lpfc_sli4_xri_exchange_busy_wait - Wait for device XRI exchange busy
13337  * @phba: Pointer to HBA context object.
13338  *
13339  * This function is called in the SLI4 code path to wait for completion
13340  * of device's XRIs exchange busy. It will check the XRI exchange busy
13341  * on outstanding FCP and ELS I/Os every 10ms for up to 10 seconds; after
13342  * that, it will check the XRI exchange busy on outstanding FCP and ELS
13343  * I/Os every 30 seconds, log error message, and wait forever. Only when
13344  * all XRI exchange busy complete, the driver unload shall proceed with
13345  * invoking the function reset ioctl mailbox command to the CNA and the
13346  * the rest of the driver unload resource release.
13347  **/
13348 static void
13349 lpfc_sli4_xri_exchange_busy_wait(struct lpfc_hba *phba)
13350 {
13351 	struct lpfc_sli4_hdw_queue *qp;
13352 	int idx, ccnt;
13353 	int wait_time = 0;
13354 	int io_xri_cmpl = 1;
13355 	int nvmet_xri_cmpl = 1;
13356 	int els_xri_cmpl = list_empty(&phba->sli4_hba.lpfc_abts_els_sgl_list);
13357 
13358 	/* Driver just aborted IOs during the hba_unset process.  Pause
13359 	 * here to give the HBA time to complete the IO and get entries
13360 	 * into the abts lists.
13361 	 */
13362 	msleep(LPFC_XRI_EXCH_BUSY_WAIT_T1 * 5);
13363 
13364 	/* Wait for NVME pending IO to flush back to transport. */
13365 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
13366 		lpfc_nvme_wait_for_io_drain(phba);
13367 
13368 	ccnt = 0;
13369 	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
13370 		qp = &phba->sli4_hba.hdwq[idx];
13371 		io_xri_cmpl = list_empty(&qp->lpfc_abts_io_buf_list);
13372 		if (!io_xri_cmpl) /* if list is NOT empty */
13373 			ccnt++;
13374 	}
13375 	if (ccnt)
13376 		io_xri_cmpl = 0;
13377 
13378 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13379 		nvmet_xri_cmpl =
13380 			list_empty(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
13381 	}
13382 
13383 	while (!els_xri_cmpl || !io_xri_cmpl || !nvmet_xri_cmpl) {
13384 		if (wait_time > LPFC_XRI_EXCH_BUSY_WAIT_TMO) {
13385 			if (!nvmet_xri_cmpl)
13386 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13387 						"6424 NVMET XRI exchange busy "
13388 						"wait time: %d seconds.\n",
13389 						wait_time/1000);
13390 			if (!io_xri_cmpl)
13391 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13392 						"6100 IO XRI exchange busy "
13393 						"wait time: %d seconds.\n",
13394 						wait_time/1000);
13395 			if (!els_xri_cmpl)
13396 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13397 						"2878 ELS XRI exchange busy "
13398 						"wait time: %d seconds.\n",
13399 						wait_time/1000);
13400 			msleep(LPFC_XRI_EXCH_BUSY_WAIT_T2);
13401 			wait_time += LPFC_XRI_EXCH_BUSY_WAIT_T2;
13402 		} else {
13403 			msleep(LPFC_XRI_EXCH_BUSY_WAIT_T1);
13404 			wait_time += LPFC_XRI_EXCH_BUSY_WAIT_T1;
13405 		}
13406 
13407 		ccnt = 0;
13408 		for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
13409 			qp = &phba->sli4_hba.hdwq[idx];
13410 			io_xri_cmpl = list_empty(
13411 			    &qp->lpfc_abts_io_buf_list);
13412 			if (!io_xri_cmpl) /* if list is NOT empty */
13413 				ccnt++;
13414 		}
13415 		if (ccnt)
13416 			io_xri_cmpl = 0;
13417 
13418 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13419 			nvmet_xri_cmpl = list_empty(
13420 				&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
13421 		}
13422 		els_xri_cmpl =
13423 			list_empty(&phba->sli4_hba.lpfc_abts_els_sgl_list);
13424 
13425 	}
13426 }
13427 
13428 /**
13429  * lpfc_sli4_hba_unset - Unset the fcoe hba
13430  * @phba: Pointer to HBA context object.
13431  *
13432  * This function is called in the SLI4 code path to reset the HBA's FCoE
13433  * function. The caller is not required to hold any lock. This routine
13434  * issues PCI function reset mailbox command to reset the FCoE function.
13435  * At the end of the function, it calls lpfc_hba_down_post function to
13436  * free any pending commands.
13437  **/
13438 static void
13439 lpfc_sli4_hba_unset(struct lpfc_hba *phba)
13440 {
13441 	int wait_cnt = 0;
13442 	LPFC_MBOXQ_t *mboxq;
13443 	struct pci_dev *pdev = phba->pcidev;
13444 
13445 	lpfc_stop_hba_timers(phba);
13446 	hrtimer_cancel(&phba->cmf_stats_timer);
13447 	hrtimer_cancel(&phba->cmf_timer);
13448 
13449 	if (phba->pport)
13450 		phba->sli4_hba.intr_enable = 0;
13451 
13452 	/*
13453 	 * Gracefully wait out the potential current outstanding asynchronous
13454 	 * mailbox command.
13455 	 */
13456 
13457 	/* First, block any pending async mailbox command from posted */
13458 	spin_lock_irq(&phba->hbalock);
13459 	phba->sli.sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
13460 	spin_unlock_irq(&phba->hbalock);
13461 	/* Now, trying to wait it out if we can */
13462 	while (phba->sli.sli_flag & LPFC_SLI_MBOX_ACTIVE) {
13463 		msleep(10);
13464 		if (++wait_cnt > LPFC_ACTIVE_MBOX_WAIT_CNT)
13465 			break;
13466 	}
13467 	/* Forcefully release the outstanding mailbox command if timed out */
13468 	if (phba->sli.sli_flag & LPFC_SLI_MBOX_ACTIVE) {
13469 		spin_lock_irq(&phba->hbalock);
13470 		mboxq = phba->sli.mbox_active;
13471 		mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
13472 		__lpfc_mbox_cmpl_put(phba, mboxq);
13473 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
13474 		phba->sli.mbox_active = NULL;
13475 		spin_unlock_irq(&phba->hbalock);
13476 	}
13477 
13478 	/* Abort all iocbs associated with the hba */
13479 	lpfc_sli_hba_iocb_abort(phba);
13480 
13481 	if (!pci_channel_offline(phba->pcidev))
13482 		/* Wait for completion of device XRI exchange busy */
13483 		lpfc_sli4_xri_exchange_busy_wait(phba);
13484 
13485 	/* per-phba callback de-registration for hotplug event */
13486 	if (phba->pport)
13487 		lpfc_cpuhp_remove(phba);
13488 
13489 	/* Disable PCI subsystem interrupt */
13490 	lpfc_sli4_disable_intr(phba);
13491 
13492 	/* Disable SR-IOV if enabled */
13493 	if (phba->cfg_sriov_nr_virtfn)
13494 		pci_disable_sriov(pdev);
13495 
13496 	/* Stop kthread signal shall trigger work_done one more time */
13497 	kthread_stop(phba->worker_thread);
13498 
13499 	/* Disable FW logging to host memory */
13500 	lpfc_ras_stop_fwlog(phba);
13501 
13502 	lpfc_sli4_queue_unset(phba);
13503 
13504 	/* Reset SLI4 HBA FCoE function */
13505 	lpfc_pci_function_reset(phba);
13506 
13507 	/* release all queue allocated resources. */
13508 	lpfc_sli4_queue_destroy(phba);
13509 
13510 	/* Free RAS DMA memory */
13511 	if (phba->ras_fwlog.ras_enabled)
13512 		lpfc_sli4_ras_dma_free(phba);
13513 
13514 	/* Stop the SLI4 device port */
13515 	if (phba->pport)
13516 		phba->pport->work_port_events = 0;
13517 }
13518 
13519 /*
13520  * The routine corresponds with the algorithm the HBA firmware
13521  * uses to validate the data integrity.
13522  */
13523 uint32_t
13524 lpfc_cgn_calc_crc32(const void *data, size_t size)
13525 {
13526 	return ~crc32c(~0, data, size);
13527 }
13528 
13529 void
13530 lpfc_init_congestion_buf(struct lpfc_hba *phba)
13531 {
13532 	struct lpfc_cgn_info *cp;
13533 	uint16_t size;
13534 	uint32_t crc;
13535 
13536 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
13537 			"6235 INIT Congestion Buffer %p\n", phba->cgn_i);
13538 
13539 	if (!phba->cgn_i)
13540 		return;
13541 	cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
13542 
13543 	atomic_set(&phba->cgn_fabric_warn_cnt, 0);
13544 	atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
13545 	atomic_set(&phba->cgn_sync_alarm_cnt, 0);
13546 	atomic_set(&phba->cgn_sync_warn_cnt, 0);
13547 
13548 	atomic_set(&phba->cgn_driver_evt_cnt, 0);
13549 	atomic_set(&phba->cgn_latency_evt_cnt, 0);
13550 	atomic64_set(&phba->cgn_latency_evt, 0);
13551 	phba->cgn_evt_minute = 0;
13552 
13553 	memset(cp, 0xff, offsetof(struct lpfc_cgn_info, cgn_stat));
13554 	cp->cgn_info_size = cpu_to_le16(LPFC_CGN_INFO_SZ);
13555 	cp->cgn_info_version = LPFC_CGN_INFO_V4;
13556 
13557 	/* cgn parameters */
13558 	cp->cgn_info_mode = phba->cgn_p.cgn_param_mode;
13559 	cp->cgn_info_level0 = phba->cgn_p.cgn_param_level0;
13560 	cp->cgn_info_level1 = phba->cgn_p.cgn_param_level1;
13561 	cp->cgn_info_level2 = phba->cgn_p.cgn_param_level2;
13562 
13563 	lpfc_cgn_update_tstamp(phba, &cp->base_time);
13564 
13565 	/* Fill in default LUN qdepth */
13566 	if (phba->pport) {
13567 		size = (uint16_t)(phba->pport->cfg_lun_queue_depth);
13568 		cp->cgn_lunq = cpu_to_le16(size);
13569 	}
13570 
13571 	/* last used Index initialized to 0xff already */
13572 
13573 	cp->cgn_warn_freq = cpu_to_le16(LPFC_FPIN_INIT_FREQ);
13574 	cp->cgn_alarm_freq = cpu_to_le16(LPFC_FPIN_INIT_FREQ);
13575 	crc = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ);
13576 	cp->cgn_info_crc = cpu_to_le32(crc);
13577 
13578 	phba->cgn_evt_timestamp = jiffies +
13579 		msecs_to_jiffies(LPFC_CGN_TIMER_TO_MIN);
13580 }
13581 
13582 void
13583 lpfc_init_congestion_stat(struct lpfc_hba *phba)
13584 {
13585 	struct lpfc_cgn_info *cp;
13586 	uint32_t crc;
13587 
13588 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
13589 			"6236 INIT Congestion Stat %p\n", phba->cgn_i);
13590 
13591 	if (!phba->cgn_i)
13592 		return;
13593 
13594 	cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
13595 	memset(&cp->cgn_stat, 0, sizeof(cp->cgn_stat));
13596 
13597 	lpfc_cgn_update_tstamp(phba, &cp->stat_start);
13598 	crc = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ);
13599 	cp->cgn_info_crc = cpu_to_le32(crc);
13600 }
13601 
13602 /**
13603  * __lpfc_reg_congestion_buf - register congestion info buffer with HBA
13604  * @phba: Pointer to hba context object.
13605  * @reg: flag to determine register or unregister.
13606  */
13607 static int
13608 __lpfc_reg_congestion_buf(struct lpfc_hba *phba, int reg)
13609 {
13610 	struct lpfc_mbx_reg_congestion_buf *reg_congestion_buf;
13611 	union  lpfc_sli4_cfg_shdr *shdr;
13612 	uint32_t shdr_status, shdr_add_status;
13613 	LPFC_MBOXQ_t *mboxq;
13614 	int length, rc;
13615 
13616 	if (!phba->cgn_i)
13617 		return -ENXIO;
13618 
13619 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
13620 	if (!mboxq) {
13621 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX,
13622 				"2641 REG_CONGESTION_BUF mbox allocation fail: "
13623 				"HBA state x%x reg %d\n",
13624 				phba->pport->port_state, reg);
13625 		return -ENOMEM;
13626 	}
13627 
13628 	length = (sizeof(struct lpfc_mbx_reg_congestion_buf) -
13629 		sizeof(struct lpfc_sli4_cfg_mhdr));
13630 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
13631 			 LPFC_MBOX_OPCODE_REG_CONGESTION_BUF, length,
13632 			 LPFC_SLI4_MBX_EMBED);
13633 	reg_congestion_buf = &mboxq->u.mqe.un.reg_congestion_buf;
13634 	bf_set(lpfc_mbx_reg_cgn_buf_type, reg_congestion_buf, 1);
13635 	if (reg > 0)
13636 		bf_set(lpfc_mbx_reg_cgn_buf_cnt, reg_congestion_buf, 1);
13637 	else
13638 		bf_set(lpfc_mbx_reg_cgn_buf_cnt, reg_congestion_buf, 0);
13639 	reg_congestion_buf->length = sizeof(struct lpfc_cgn_info);
13640 	reg_congestion_buf->addr_lo =
13641 		putPaddrLow(phba->cgn_i->phys);
13642 	reg_congestion_buf->addr_hi =
13643 		putPaddrHigh(phba->cgn_i->phys);
13644 
13645 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
13646 	shdr = (union lpfc_sli4_cfg_shdr *)
13647 		&mboxq->u.mqe.un.sli4_config.header.cfg_shdr;
13648 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13649 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
13650 				 &shdr->response);
13651 	mempool_free(mboxq, phba->mbox_mem_pool);
13652 	if (shdr_status || shdr_add_status || rc) {
13653 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13654 				"2642 REG_CONGESTION_BUF mailbox "
13655 				"failed with status x%x add_status x%x,"
13656 				" mbx status x%x reg %d\n",
13657 				shdr_status, shdr_add_status, rc, reg);
13658 		return -ENXIO;
13659 	}
13660 	return 0;
13661 }
13662 
13663 int
13664 lpfc_unreg_congestion_buf(struct lpfc_hba *phba)
13665 {
13666 	lpfc_cmf_stop(phba);
13667 	return __lpfc_reg_congestion_buf(phba, 0);
13668 }
13669 
13670 int
13671 lpfc_reg_congestion_buf(struct lpfc_hba *phba)
13672 {
13673 	return __lpfc_reg_congestion_buf(phba, 1);
13674 }
13675 
13676 /**
13677  * lpfc_get_sli4_parameters - Get the SLI4 Config PARAMETERS.
13678  * @phba: Pointer to HBA context object.
13679  * @mboxq: Pointer to the mailboxq memory for the mailbox command response.
13680  *
13681  * This function is called in the SLI4 code path to read the port's
13682  * sli4 capabilities.
13683  *
13684  * This function may be be called from any context that can block-wait
13685  * for the completion.  The expectation is that this routine is called
13686  * typically from probe_one or from the online routine.
13687  **/
13688 int
13689 lpfc_get_sli4_parameters(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
13690 {
13691 	int rc;
13692 	struct lpfc_mqe *mqe = &mboxq->u.mqe;
13693 	struct lpfc_pc_sli4_params *sli4_params;
13694 	uint32_t mbox_tmo;
13695 	int length;
13696 	bool exp_wqcq_pages = true;
13697 	struct lpfc_sli4_parameters *mbx_sli4_parameters;
13698 
13699 	/*
13700 	 * By default, the driver assumes the SLI4 port requires RPI
13701 	 * header postings.  The SLI4_PARAM response will correct this
13702 	 * assumption.
13703 	 */
13704 	phba->sli4_hba.rpi_hdrs_in_use = 1;
13705 
13706 	/* Read the port's SLI4 Config Parameters */
13707 	length = (sizeof(struct lpfc_mbx_get_sli4_parameters) -
13708 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13709 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
13710 			 LPFC_MBOX_OPCODE_GET_SLI4_PARAMETERS,
13711 			 length, LPFC_SLI4_MBX_EMBED);
13712 	if (!phba->sli4_hba.intr_enable)
13713 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
13714 	else {
13715 		mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
13716 		rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
13717 	}
13718 	if (unlikely(rc))
13719 		return rc;
13720 	sli4_params = &phba->sli4_hba.pc_sli4_params;
13721 	mbx_sli4_parameters = &mqe->un.get_sli4_parameters.sli4_parameters;
13722 	sli4_params->if_type = bf_get(cfg_if_type, mbx_sli4_parameters);
13723 	sli4_params->sli_rev = bf_get(cfg_sli_rev, mbx_sli4_parameters);
13724 	sli4_params->sli_family = bf_get(cfg_sli_family, mbx_sli4_parameters);
13725 	sli4_params->featurelevel_1 = bf_get(cfg_sli_hint_1,
13726 					     mbx_sli4_parameters);
13727 	sli4_params->featurelevel_2 = bf_get(cfg_sli_hint_2,
13728 					     mbx_sli4_parameters);
13729 	if (bf_get(cfg_phwq, mbx_sli4_parameters))
13730 		phba->sli3_options |= LPFC_SLI4_PHWQ_ENABLED;
13731 	else
13732 		phba->sli3_options &= ~LPFC_SLI4_PHWQ_ENABLED;
13733 	sli4_params->sge_supp_len = mbx_sli4_parameters->sge_supp_len;
13734 	sli4_params->loopbk_scope = bf_get(cfg_loopbk_scope,
13735 					   mbx_sli4_parameters);
13736 	sli4_params->oas_supported = bf_get(cfg_oas, mbx_sli4_parameters);
13737 	sli4_params->cqv = bf_get(cfg_cqv, mbx_sli4_parameters);
13738 	sli4_params->mqv = bf_get(cfg_mqv, mbx_sli4_parameters);
13739 	sli4_params->wqv = bf_get(cfg_wqv, mbx_sli4_parameters);
13740 	sli4_params->rqv =
13741 		(sli4_params->if_type < LPFC_SLI_INTF_IF_TYPE_2) ?
13742 			LPFC_Q_CREATE_VERSION_0 : LPFC_Q_CREATE_VERSION_1;
13743 	sli4_params->eqav = bf_get(cfg_eqav, mbx_sli4_parameters);
13744 	sli4_params->cqav = bf_get(cfg_cqav, mbx_sli4_parameters);
13745 	sli4_params->wqsize = bf_get(cfg_wqsize, mbx_sli4_parameters);
13746 	sli4_params->bv1s = bf_get(cfg_bv1s, mbx_sli4_parameters);
13747 	sli4_params->pls = bf_get(cfg_pvl, mbx_sli4_parameters);
13748 	sli4_params->sgl_pages_max = bf_get(cfg_sgl_page_cnt,
13749 					    mbx_sli4_parameters);
13750 	sli4_params->wqpcnt = bf_get(cfg_wqpcnt, mbx_sli4_parameters);
13751 	sli4_params->sgl_pp_align = bf_get(cfg_sgl_pp_align,
13752 					   mbx_sli4_parameters);
13753 	phba->sli4_hba.extents_in_use = bf_get(cfg_ext, mbx_sli4_parameters);
13754 	phba->sli4_hba.rpi_hdrs_in_use = bf_get(cfg_hdrr, mbx_sli4_parameters);
13755 	sli4_params->mi_cap = bf_get(cfg_mi_ver, mbx_sli4_parameters);
13756 
13757 	/* Check for Extended Pre-Registered SGL support */
13758 	phba->cfg_xpsgl = bf_get(cfg_xpsgl, mbx_sli4_parameters);
13759 
13760 	/* Check for firmware nvme support */
13761 	rc = (bf_get(cfg_nvme, mbx_sli4_parameters) &&
13762 		     bf_get(cfg_xib, mbx_sli4_parameters));
13763 
13764 	if (rc) {
13765 		/* Save this to indicate the Firmware supports NVME */
13766 		sli4_params->nvme = 1;
13767 
13768 		/* Firmware NVME support, check driver FC4 NVME support */
13769 		if (phba->cfg_enable_fc4_type == LPFC_ENABLE_FCP) {
13770 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_NVME,
13771 					"6133 Disabling NVME support: "
13772 					"FC4 type not supported: x%x\n",
13773 					phba->cfg_enable_fc4_type);
13774 			goto fcponly;
13775 		}
13776 	} else {
13777 		/* No firmware NVME support, check driver FC4 NVME support */
13778 		sli4_params->nvme = 0;
13779 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13780 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_NVME,
13781 					"6101 Disabling NVME support: Not "
13782 					"supported by firmware (%d %d) x%x\n",
13783 					bf_get(cfg_nvme, mbx_sli4_parameters),
13784 					bf_get(cfg_xib, mbx_sli4_parameters),
13785 					phba->cfg_enable_fc4_type);
13786 fcponly:
13787 			phba->nvmet_support = 0;
13788 			phba->cfg_nvmet_mrq = 0;
13789 			phba->cfg_nvme_seg_cnt = 0;
13790 
13791 			/* If no FC4 type support, move to just SCSI support */
13792 			if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP))
13793 				return -ENODEV;
13794 			phba->cfg_enable_fc4_type = LPFC_ENABLE_FCP;
13795 		}
13796 	}
13797 
13798 	/* If the NVME FC4 type is enabled, scale the sg_seg_cnt to
13799 	 * accommodate 512K and 1M IOs in a single nvme buf.
13800 	 */
13801 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
13802 		phba->cfg_sg_seg_cnt = LPFC_MAX_NVME_SEG_CNT;
13803 
13804 	/*
13805 	 * To support Suppress Response feature we must satisfy 3 conditions.
13806 	 * lpfc_suppress_rsp module parameter must be set (default).
13807 	 * In SLI4-Parameters Descriptor:
13808 	 * Extended Inline Buffers (XIB) must be supported.
13809 	 * Suppress Response IU Not Supported (SRIUNS) must NOT be supported
13810 	 * (double negative).
13811 	 */
13812 	if (phba->cfg_suppress_rsp && bf_get(cfg_xib, mbx_sli4_parameters) &&
13813 	    !(bf_get(cfg_nosr, mbx_sli4_parameters)))
13814 		phba->sli.sli_flag |= LPFC_SLI_SUPPRESS_RSP;
13815 	else
13816 		phba->cfg_suppress_rsp = 0;
13817 
13818 	if (bf_get(cfg_eqdr, mbx_sli4_parameters))
13819 		phba->sli.sli_flag |= LPFC_SLI_USE_EQDR;
13820 
13821 	/* Make sure that sge_supp_len can be handled by the driver */
13822 	if (sli4_params->sge_supp_len > LPFC_MAX_SGE_SIZE)
13823 		sli4_params->sge_supp_len = LPFC_MAX_SGE_SIZE;
13824 
13825 	dma_set_max_seg_size(&phba->pcidev->dev, sli4_params->sge_supp_len);
13826 
13827 	/*
13828 	 * Check whether the adapter supports an embedded copy of the
13829 	 * FCP CMD IU within the WQE for FCP_Ixxx commands. In order
13830 	 * to use this option, 128-byte WQEs must be used.
13831 	 */
13832 	if (bf_get(cfg_ext_embed_cb, mbx_sli4_parameters))
13833 		phba->fcp_embed_io = 1;
13834 	else
13835 		phba->fcp_embed_io = 0;
13836 
13837 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_NVME,
13838 			"6422 XIB %d: FCP %d NVME %d %d %d\n",
13839 			bf_get(cfg_xib, mbx_sli4_parameters),
13840 			phba->fcp_embed_io, sli4_params->nvme,
13841 			phba->cfg_nvme_embed_cmd, phba->cfg_suppress_rsp);
13842 
13843 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
13844 	    LPFC_SLI_INTF_IF_TYPE_2) &&
13845 	    (bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf) ==
13846 		 LPFC_SLI_INTF_FAMILY_LNCR_A0))
13847 		exp_wqcq_pages = false;
13848 
13849 	if ((bf_get(cfg_cqpsize, mbx_sli4_parameters) & LPFC_CQ_16K_PAGE_SZ) &&
13850 	    (bf_get(cfg_wqpsize, mbx_sli4_parameters) & LPFC_WQ_16K_PAGE_SZ) &&
13851 	    exp_wqcq_pages &&
13852 	    (sli4_params->wqsize & LPFC_WQ_SZ128_SUPPORT))
13853 		phba->enab_exp_wqcq_pages = 1;
13854 	else
13855 		phba->enab_exp_wqcq_pages = 0;
13856 	/*
13857 	 * Check if the SLI port supports MDS Diagnostics
13858 	 */
13859 	if (bf_get(cfg_mds_diags, mbx_sli4_parameters))
13860 		phba->mds_diags_support = 1;
13861 	else
13862 		phba->mds_diags_support = 0;
13863 
13864 	/*
13865 	 * Check if the SLI port supports NSLER
13866 	 */
13867 	if (bf_get(cfg_nsler, mbx_sli4_parameters))
13868 		phba->nsler = 1;
13869 	else
13870 		phba->nsler = 0;
13871 
13872 	return 0;
13873 }
13874 
13875 /**
13876  * lpfc_pci_probe_one_s3 - PCI probe func to reg SLI-3 device to PCI subsystem.
13877  * @pdev: pointer to PCI device
13878  * @pid: pointer to PCI device identifier
13879  *
13880  * This routine is to be called to attach a device with SLI-3 interface spec
13881  * to the PCI subsystem. When an Emulex HBA with SLI-3 interface spec is
13882  * presented on PCI bus, the kernel PCI subsystem looks at PCI device-specific
13883  * information of the device and driver to see if the driver state that it can
13884  * support this kind of device. If the match is successful, the driver core
13885  * invokes this routine. If this routine determines it can claim the HBA, it
13886  * does all the initialization that it needs to do to handle the HBA properly.
13887  *
13888  * Return code
13889  * 	0 - driver can claim the device
13890  * 	negative value - driver can not claim the device
13891  **/
13892 static int
13893 lpfc_pci_probe_one_s3(struct pci_dev *pdev, const struct pci_device_id *pid)
13894 {
13895 	struct lpfc_hba   *phba;
13896 	struct lpfc_vport *vport = NULL;
13897 	struct Scsi_Host  *shost = NULL;
13898 	int error;
13899 	uint32_t cfg_mode, intr_mode;
13900 
13901 	/* Allocate memory for HBA structure */
13902 	phba = lpfc_hba_alloc(pdev);
13903 	if (!phba)
13904 		return -ENOMEM;
13905 
13906 	/* Perform generic PCI device enabling operation */
13907 	error = lpfc_enable_pci_dev(phba);
13908 	if (error)
13909 		goto out_free_phba;
13910 
13911 	/* Set up SLI API function jump table for PCI-device group-0 HBAs */
13912 	error = lpfc_api_table_setup(phba, LPFC_PCI_DEV_LP);
13913 	if (error)
13914 		goto out_disable_pci_dev;
13915 
13916 	/* Set up SLI-3 specific device PCI memory space */
13917 	error = lpfc_sli_pci_mem_setup(phba);
13918 	if (error) {
13919 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13920 				"1402 Failed to set up pci memory space.\n");
13921 		goto out_disable_pci_dev;
13922 	}
13923 
13924 	/* Set up SLI-3 specific device driver resources */
13925 	error = lpfc_sli_driver_resource_setup(phba);
13926 	if (error) {
13927 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13928 				"1404 Failed to set up driver resource.\n");
13929 		goto out_unset_pci_mem_s3;
13930 	}
13931 
13932 	/* Initialize and populate the iocb list per host */
13933 
13934 	error = lpfc_init_iocb_list(phba, LPFC_IOCB_LIST_CNT);
13935 	if (error) {
13936 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13937 				"1405 Failed to initialize iocb list.\n");
13938 		goto out_unset_driver_resource_s3;
13939 	}
13940 
13941 	/* Set up common device driver resources */
13942 	error = lpfc_setup_driver_resource_phase2(phba);
13943 	if (error) {
13944 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13945 				"1406 Failed to set up driver resource.\n");
13946 		goto out_free_iocb_list;
13947 	}
13948 
13949 	/* Get the default values for Model Name and Description */
13950 	lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
13951 
13952 	/* Create SCSI host to the physical port */
13953 	error = lpfc_create_shost(phba);
13954 	if (error) {
13955 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13956 				"1407 Failed to create scsi host.\n");
13957 		goto out_unset_driver_resource;
13958 	}
13959 
13960 	/* Configure sysfs attributes */
13961 	vport = phba->pport;
13962 	error = lpfc_alloc_sysfs_attr(vport);
13963 	if (error) {
13964 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13965 				"1476 Failed to allocate sysfs attr\n");
13966 		goto out_destroy_shost;
13967 	}
13968 
13969 	shost = lpfc_shost_from_vport(vport); /* save shost for error cleanup */
13970 	/* Now, trying to enable interrupt and bring up the device */
13971 	cfg_mode = phba->cfg_use_msi;
13972 	while (true) {
13973 		/* Put device to a known state before enabling interrupt */
13974 		lpfc_stop_port(phba);
13975 		/* Configure and enable interrupt */
13976 		intr_mode = lpfc_sli_enable_intr(phba, cfg_mode);
13977 		if (intr_mode == LPFC_INTR_ERROR) {
13978 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13979 					"0431 Failed to enable interrupt.\n");
13980 			error = -ENODEV;
13981 			goto out_free_sysfs_attr;
13982 		}
13983 		/* SLI-3 HBA setup */
13984 		if (lpfc_sli_hba_setup(phba)) {
13985 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13986 					"1477 Failed to set up hba\n");
13987 			error = -ENODEV;
13988 			goto out_remove_device;
13989 		}
13990 
13991 		/* Wait 50ms for the interrupts of previous mailbox commands */
13992 		msleep(50);
13993 		/* Check active interrupts on message signaled interrupts */
13994 		if (intr_mode == 0 ||
13995 		    phba->sli.slistat.sli_intr > LPFC_MSIX_VECTORS) {
13996 			/* Log the current active interrupt mode */
13997 			phba->intr_mode = intr_mode;
13998 			lpfc_log_intr_mode(phba, intr_mode);
13999 			break;
14000 		} else {
14001 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
14002 					"0447 Configure interrupt mode (%d) "
14003 					"failed active interrupt test.\n",
14004 					intr_mode);
14005 			/* Disable the current interrupt mode */
14006 			lpfc_sli_disable_intr(phba);
14007 			/* Try next level of interrupt mode */
14008 			cfg_mode = --intr_mode;
14009 		}
14010 	}
14011 
14012 	/* Perform post initialization setup */
14013 	lpfc_post_init_setup(phba);
14014 
14015 	/* Check if there are static vports to be created. */
14016 	lpfc_create_static_vport(phba);
14017 
14018 	return 0;
14019 
14020 out_remove_device:
14021 	lpfc_unset_hba(phba);
14022 out_free_sysfs_attr:
14023 	lpfc_free_sysfs_attr(vport);
14024 out_destroy_shost:
14025 	lpfc_destroy_shost(phba);
14026 out_unset_driver_resource:
14027 	lpfc_unset_driver_resource_phase2(phba);
14028 out_free_iocb_list:
14029 	lpfc_free_iocb_list(phba);
14030 out_unset_driver_resource_s3:
14031 	lpfc_sli_driver_resource_unset(phba);
14032 out_unset_pci_mem_s3:
14033 	lpfc_sli_pci_mem_unset(phba);
14034 out_disable_pci_dev:
14035 	lpfc_disable_pci_dev(phba);
14036 	if (shost)
14037 		scsi_host_put(shost);
14038 out_free_phba:
14039 	lpfc_hba_free(phba);
14040 	return error;
14041 }
14042 
14043 /**
14044  * lpfc_pci_remove_one_s3 - PCI func to unreg SLI-3 device from PCI subsystem.
14045  * @pdev: pointer to PCI device
14046  *
14047  * This routine is to be called to disattach a device with SLI-3 interface
14048  * spec from PCI subsystem. When an Emulex HBA with SLI-3 interface spec is
14049  * removed from PCI bus, it performs all the necessary cleanup for the HBA
14050  * device to be removed from the PCI subsystem properly.
14051  **/
14052 static void
14053 lpfc_pci_remove_one_s3(struct pci_dev *pdev)
14054 {
14055 	struct Scsi_Host  *shost = pci_get_drvdata(pdev);
14056 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
14057 	struct lpfc_vport **vports;
14058 	struct lpfc_hba   *phba = vport->phba;
14059 	int i;
14060 
14061 	set_bit(FC_UNLOADING, &vport->load_flag);
14062 
14063 	lpfc_free_sysfs_attr(vport);
14064 
14065 	/* Release all the vports against this physical port */
14066 	vports = lpfc_create_vport_work_array(phba);
14067 	if (vports != NULL)
14068 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
14069 			if (vports[i]->port_type == LPFC_PHYSICAL_PORT)
14070 				continue;
14071 			fc_vport_terminate(vports[i]->fc_vport);
14072 		}
14073 	lpfc_destroy_vport_work_array(phba, vports);
14074 
14075 	/* Remove FC host with the physical port */
14076 	fc_remove_host(shost);
14077 	scsi_remove_host(shost);
14078 
14079 	/* Clean up all nodes, mailboxes and IOs. */
14080 	lpfc_cleanup(vport);
14081 
14082 	/*
14083 	 * Bring down the SLI Layer. This step disable all interrupts,
14084 	 * clears the rings, discards all mailbox commands, and resets
14085 	 * the HBA.
14086 	 */
14087 
14088 	/* HBA interrupt will be disabled after this call */
14089 	lpfc_sli_hba_down(phba);
14090 	/* Stop kthread signal shall trigger work_done one more time */
14091 	kthread_stop(phba->worker_thread);
14092 	/* Final cleanup of txcmplq and reset the HBA */
14093 	lpfc_sli_brdrestart(phba);
14094 
14095 	kfree(phba->vpi_bmask);
14096 	kfree(phba->vpi_ids);
14097 
14098 	lpfc_stop_hba_timers(phba);
14099 	spin_lock_irq(&phba->port_list_lock);
14100 	list_del_init(&vport->listentry);
14101 	spin_unlock_irq(&phba->port_list_lock);
14102 
14103 	lpfc_debugfs_terminate(vport);
14104 
14105 	/* Disable SR-IOV if enabled */
14106 	if (phba->cfg_sriov_nr_virtfn)
14107 		pci_disable_sriov(pdev);
14108 
14109 	/* Disable interrupt */
14110 	lpfc_sli_disable_intr(phba);
14111 
14112 	scsi_host_put(shost);
14113 
14114 	/*
14115 	 * Call scsi_free before mem_free since scsi bufs are released to their
14116 	 * corresponding pools here.
14117 	 */
14118 	lpfc_scsi_free(phba);
14119 	lpfc_free_iocb_list(phba);
14120 
14121 	lpfc_mem_free_all(phba);
14122 
14123 	dma_free_coherent(&pdev->dev, lpfc_sli_hbq_size(),
14124 			  phba->hbqslimp.virt, phba->hbqslimp.phys);
14125 
14126 	/* Free resources associated with SLI2 interface */
14127 	dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
14128 			  phba->slim2p.virt, phba->slim2p.phys);
14129 
14130 	/* unmap adapter SLIM and Control Registers */
14131 	iounmap(phba->ctrl_regs_memmap_p);
14132 	iounmap(phba->slim_memmap_p);
14133 
14134 	lpfc_hba_free(phba);
14135 
14136 	pci_release_mem_regions(pdev);
14137 	pci_disable_device(pdev);
14138 }
14139 
14140 /**
14141  * lpfc_pci_suspend_one_s3 - PCI func to suspend SLI-3 device for power mgmnt
14142  * @dev_d: pointer to device
14143  *
14144  * This routine is to be called from the kernel's PCI subsystem to support
14145  * system Power Management (PM) to device with SLI-3 interface spec. When
14146  * PM invokes this method, it quiesces the device by stopping the driver's
14147  * worker thread for the device, turning off device's interrupt and DMA,
14148  * and bring the device offline. Note that as the driver implements the
14149  * minimum PM requirements to a power-aware driver's PM support for the
14150  * suspend/resume -- all the possible PM messages (SUSPEND, HIBERNATE, FREEZE)
14151  * to the suspend() method call will be treated as SUSPEND and the driver will
14152  * fully reinitialize its device during resume() method call, the driver will
14153  * set device to PCI_D3hot state in PCI config space instead of setting it
14154  * according to the @msg provided by the PM.
14155  *
14156  * Return code
14157  * 	0 - driver suspended the device
14158  * 	Error otherwise
14159  **/
14160 static int __maybe_unused
14161 lpfc_pci_suspend_one_s3(struct device *dev_d)
14162 {
14163 	struct Scsi_Host *shost = dev_get_drvdata(dev_d);
14164 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14165 
14166 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
14167 			"0473 PCI device Power Management suspend.\n");
14168 
14169 	/* Bring down the device */
14170 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
14171 	lpfc_offline(phba);
14172 	kthread_stop(phba->worker_thread);
14173 
14174 	/* Disable interrupt from device */
14175 	lpfc_sli_disable_intr(phba);
14176 
14177 	return 0;
14178 }
14179 
14180 /**
14181  * lpfc_pci_resume_one_s3 - PCI func to resume SLI-3 device for power mgmnt
14182  * @dev_d: pointer to device
14183  *
14184  * This routine is to be called from the kernel's PCI subsystem to support
14185  * system Power Management (PM) to device with SLI-3 interface spec. When PM
14186  * invokes this method, it restores the device's PCI config space state and
14187  * fully reinitializes the device and brings it online. Note that as the
14188  * driver implements the minimum PM requirements to a power-aware driver's
14189  * PM for suspend/resume -- all the possible PM messages (SUSPEND, HIBERNATE,
14190  * FREEZE) to the suspend() method call will be treated as SUSPEND and the
14191  * driver will fully reinitialize its device during resume() method call,
14192  * the device will be set to PCI_D0 directly in PCI config space before
14193  * restoring the state.
14194  *
14195  * Return code
14196  * 	0 - driver suspended the device
14197  * 	Error otherwise
14198  **/
14199 static int __maybe_unused
14200 lpfc_pci_resume_one_s3(struct device *dev_d)
14201 {
14202 	struct Scsi_Host *shost = dev_get_drvdata(dev_d);
14203 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14204 	uint32_t intr_mode;
14205 	int error;
14206 
14207 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
14208 			"0452 PCI device Power Management resume.\n");
14209 
14210 	/* Startup the kernel thread for this host adapter. */
14211 	phba->worker_thread = kthread_run(lpfc_do_work, phba,
14212 					"lpfc_worker_%d", phba->brd_no);
14213 	if (IS_ERR(phba->worker_thread)) {
14214 		error = PTR_ERR(phba->worker_thread);
14215 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14216 				"0434 PM resume failed to start worker "
14217 				"thread: error=x%x.\n", error);
14218 		return error;
14219 	}
14220 
14221 	/* Init cpu_map array */
14222 	lpfc_cpu_map_array_init(phba);
14223 	/* Init hba_eq_hdl array */
14224 	lpfc_hba_eq_hdl_array_init(phba);
14225 	/* Configure and enable interrupt */
14226 	intr_mode = lpfc_sli_enable_intr(phba, phba->intr_mode);
14227 	if (intr_mode == LPFC_INTR_ERROR) {
14228 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14229 				"0430 PM resume Failed to enable interrupt\n");
14230 		return -EIO;
14231 	} else
14232 		phba->intr_mode = intr_mode;
14233 
14234 	/* Restart HBA and bring it online */
14235 	lpfc_sli_brdrestart(phba);
14236 	lpfc_online(phba);
14237 
14238 	/* Log the current active interrupt mode */
14239 	lpfc_log_intr_mode(phba, phba->intr_mode);
14240 
14241 	return 0;
14242 }
14243 
14244 /**
14245  * lpfc_sli_prep_dev_for_recover - Prepare SLI3 device for pci slot recover
14246  * @phba: pointer to lpfc hba data structure.
14247  *
14248  * This routine is called to prepare the SLI3 device for PCI slot recover. It
14249  * aborts all the outstanding SCSI I/Os to the pci device.
14250  **/
14251 static void
14252 lpfc_sli_prep_dev_for_recover(struct lpfc_hba *phba)
14253 {
14254 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14255 			"2723 PCI channel I/O abort preparing for recovery\n");
14256 
14257 	/*
14258 	 * There may be errored I/Os through HBA, abort all I/Os on txcmplq
14259 	 * and let the SCSI mid-layer to retry them to recover.
14260 	 */
14261 	lpfc_sli_abort_fcp_rings(phba);
14262 }
14263 
14264 /**
14265  * lpfc_sli_prep_dev_for_reset - Prepare SLI3 device for pci slot reset
14266  * @phba: pointer to lpfc hba data structure.
14267  *
14268  * This routine is called to prepare the SLI3 device for PCI slot reset. It
14269  * disables the device interrupt and pci device, and aborts the internal FCP
14270  * pending I/Os.
14271  **/
14272 static void
14273 lpfc_sli_prep_dev_for_reset(struct lpfc_hba *phba)
14274 {
14275 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14276 			"2710 PCI channel disable preparing for reset\n");
14277 
14278 	/* Block any management I/Os to the device */
14279 	lpfc_block_mgmt_io(phba, LPFC_MBX_WAIT);
14280 
14281 	/* Block all SCSI devices' I/Os on the host */
14282 	lpfc_scsi_dev_block(phba);
14283 
14284 	/* Flush all driver's outstanding SCSI I/Os as we are to reset */
14285 	lpfc_sli_flush_io_rings(phba);
14286 
14287 	/* stop all timers */
14288 	lpfc_stop_hba_timers(phba);
14289 
14290 	/* Disable interrupt and pci device */
14291 	lpfc_sli_disable_intr(phba);
14292 	pci_disable_device(phba->pcidev);
14293 }
14294 
14295 /**
14296  * lpfc_sli_prep_dev_for_perm_failure - Prepare SLI3 dev for pci slot disable
14297  * @phba: pointer to lpfc hba data structure.
14298  *
14299  * This routine is called to prepare the SLI3 device for PCI slot permanently
14300  * disabling. It blocks the SCSI transport layer traffic and flushes the FCP
14301  * pending I/Os.
14302  **/
14303 static void
14304 lpfc_sli_prep_dev_for_perm_failure(struct lpfc_hba *phba)
14305 {
14306 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14307 			"2711 PCI channel permanent disable for failure\n");
14308 	/* Block all SCSI devices' I/Os on the host */
14309 	lpfc_scsi_dev_block(phba);
14310 	lpfc_sli4_prep_dev_for_reset(phba);
14311 
14312 	/* stop all timers */
14313 	lpfc_stop_hba_timers(phba);
14314 
14315 	/* Clean up all driver's outstanding SCSI I/Os */
14316 	lpfc_sli_flush_io_rings(phba);
14317 }
14318 
14319 /**
14320  * lpfc_io_error_detected_s3 - Method for handling SLI-3 device PCI I/O error
14321  * @pdev: pointer to PCI device.
14322  * @state: the current PCI connection state.
14323  *
14324  * This routine is called from the PCI subsystem for I/O error handling to
14325  * device with SLI-3 interface spec. This function is called by the PCI
14326  * subsystem after a PCI bus error affecting this device has been detected.
14327  * When this function is invoked, it will need to stop all the I/Os and
14328  * interrupt(s) to the device. Once that is done, it will return
14329  * PCI_ERS_RESULT_NEED_RESET for the PCI subsystem to perform proper recovery
14330  * as desired.
14331  *
14332  * Return codes
14333  *	PCI_ERS_RESULT_CAN_RECOVER - can be recovered without reset
14334  * 	PCI_ERS_RESULT_NEED_RESET - need to reset before recovery
14335  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
14336  **/
14337 static pci_ers_result_t
14338 lpfc_io_error_detected_s3(struct pci_dev *pdev, pci_channel_state_t state)
14339 {
14340 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
14341 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14342 
14343 	switch (state) {
14344 	case pci_channel_io_normal:
14345 		/* Non-fatal error, prepare for recovery */
14346 		lpfc_sli_prep_dev_for_recover(phba);
14347 		return PCI_ERS_RESULT_CAN_RECOVER;
14348 	case pci_channel_io_frozen:
14349 		/* Fatal error, prepare for slot reset */
14350 		lpfc_sli_prep_dev_for_reset(phba);
14351 		return PCI_ERS_RESULT_NEED_RESET;
14352 	case pci_channel_io_perm_failure:
14353 		/* Permanent failure, prepare for device down */
14354 		lpfc_sli_prep_dev_for_perm_failure(phba);
14355 		return PCI_ERS_RESULT_DISCONNECT;
14356 	default:
14357 		/* Unknown state, prepare and request slot reset */
14358 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14359 				"0472 Unknown PCI error state: x%x\n", state);
14360 		lpfc_sli_prep_dev_for_reset(phba);
14361 		return PCI_ERS_RESULT_NEED_RESET;
14362 	}
14363 }
14364 
14365 /**
14366  * lpfc_io_slot_reset_s3 - Method for restarting PCI SLI-3 device from scratch.
14367  * @pdev: pointer to PCI device.
14368  *
14369  * This routine is called from the PCI subsystem for error handling to
14370  * device with SLI-3 interface spec. This is called after PCI bus has been
14371  * reset to restart the PCI card from scratch, as if from a cold-boot.
14372  * During the PCI subsystem error recovery, after driver returns
14373  * PCI_ERS_RESULT_NEED_RESET, the PCI subsystem will perform proper error
14374  * recovery and then call this routine before calling the .resume method
14375  * to recover the device. This function will initialize the HBA device,
14376  * enable the interrupt, but it will just put the HBA to offline state
14377  * without passing any I/O traffic.
14378  *
14379  * Return codes
14380  * 	PCI_ERS_RESULT_RECOVERED - the device has been recovered
14381  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
14382  */
14383 static pci_ers_result_t
14384 lpfc_io_slot_reset_s3(struct pci_dev *pdev)
14385 {
14386 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
14387 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14388 	struct lpfc_sli *psli = &phba->sli;
14389 	uint32_t intr_mode;
14390 
14391 	dev_printk(KERN_INFO, &pdev->dev, "recovering from a slot reset.\n");
14392 	if (pci_enable_device_mem(pdev)) {
14393 		printk(KERN_ERR "lpfc: Cannot re-enable "
14394 			"PCI device after reset.\n");
14395 		return PCI_ERS_RESULT_DISCONNECT;
14396 	}
14397 
14398 	pci_restore_state(pdev);
14399 
14400 	if (pdev->is_busmaster)
14401 		pci_set_master(pdev);
14402 
14403 	spin_lock_irq(&phba->hbalock);
14404 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
14405 	spin_unlock_irq(&phba->hbalock);
14406 
14407 	/* Configure and enable interrupt */
14408 	intr_mode = lpfc_sli_enable_intr(phba, phba->intr_mode);
14409 	if (intr_mode == LPFC_INTR_ERROR) {
14410 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14411 				"0427 Cannot re-enable interrupt after "
14412 				"slot reset.\n");
14413 		return PCI_ERS_RESULT_DISCONNECT;
14414 	} else
14415 		phba->intr_mode = intr_mode;
14416 
14417 	/* Take device offline, it will perform cleanup */
14418 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
14419 	lpfc_offline(phba);
14420 	lpfc_sli_brdrestart(phba);
14421 
14422 	/* Log the current active interrupt mode */
14423 	lpfc_log_intr_mode(phba, phba->intr_mode);
14424 
14425 	return PCI_ERS_RESULT_RECOVERED;
14426 }
14427 
14428 /**
14429  * lpfc_io_resume_s3 - Method for resuming PCI I/O operation on SLI-3 device.
14430  * @pdev: pointer to PCI device
14431  *
14432  * This routine is called from the PCI subsystem for error handling to device
14433  * with SLI-3 interface spec. It is called when kernel error recovery tells
14434  * the lpfc driver that it is ok to resume normal PCI operation after PCI bus
14435  * error recovery. After this call, traffic can start to flow from this device
14436  * again.
14437  */
14438 static void
14439 lpfc_io_resume_s3(struct pci_dev *pdev)
14440 {
14441 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
14442 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14443 
14444 	/* Bring device online, it will be no-op for non-fatal error resume */
14445 	lpfc_online(phba);
14446 }
14447 
14448 /**
14449  * lpfc_sli4_get_els_iocb_cnt - Calculate the # of ELS IOCBs to reserve
14450  * @phba: pointer to lpfc hba data structure.
14451  *
14452  * returns the number of ELS/CT IOCBs to reserve
14453  **/
14454 int
14455 lpfc_sli4_get_els_iocb_cnt(struct lpfc_hba *phba)
14456 {
14457 	int max_xri = phba->sli4_hba.max_cfg_param.max_xri;
14458 
14459 	if (phba->sli_rev == LPFC_SLI_REV4) {
14460 		if (max_xri <= 100)
14461 			return 10;
14462 		else if (max_xri <= 256)
14463 			return 25;
14464 		else if (max_xri <= 512)
14465 			return 50;
14466 		else if (max_xri <= 1024)
14467 			return 100;
14468 		else if (max_xri <= 1536)
14469 			return 150;
14470 		else if (max_xri <= 2048)
14471 			return 200;
14472 		else
14473 			return 250;
14474 	} else
14475 		return 0;
14476 }
14477 
14478 /**
14479  * lpfc_sli4_get_iocb_cnt - Calculate the # of total IOCBs to reserve
14480  * @phba: pointer to lpfc hba data structure.
14481  *
14482  * returns the number of ELS/CT + NVMET IOCBs to reserve
14483  **/
14484 int
14485 lpfc_sli4_get_iocb_cnt(struct lpfc_hba *phba)
14486 {
14487 	int max_xri = lpfc_sli4_get_els_iocb_cnt(phba);
14488 
14489 	if (phba->nvmet_support)
14490 		max_xri += LPFC_NVMET_BUF_POST;
14491 	return max_xri;
14492 }
14493 
14494 
14495 static int
14496 lpfc_log_write_firmware_error(struct lpfc_hba *phba, uint32_t offset,
14497 	uint32_t magic_number, uint32_t ftype, uint32_t fid, uint32_t fsize,
14498 	const struct firmware *fw)
14499 {
14500 	int rc;
14501 	u8 sli_family;
14502 
14503 	sli_family = bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf);
14504 
14505 	/* Refer to ASIC_ID register case */
14506 	if (sli_family == LPFC_SLI_INTF_ASIC_ID)
14507 		sli_family = bf_get(lpfc_asic_id_gen_num,
14508 				    &phba->sli4_hba.asic_id);
14509 
14510 	/* Three cases:  (1) FW was not supported on the detected adapter.
14511 	 * (2) FW update has been locked out administratively.
14512 	 * (3) Some other error during FW update.
14513 	 * In each case, an unmaskable message is written to the console
14514 	 * for admin diagnosis.
14515 	 */
14516 	if (offset == ADD_STATUS_FW_NOT_SUPPORTED ||
14517 	    (sli_family == LPFC_SLI_INTF_FAMILY_G6 &&
14518 	     magic_number != MAGIC_NUMBER_G6) ||
14519 	    (sli_family == LPFC_SLI_INTF_FAMILY_G7 &&
14520 	     magic_number != MAGIC_NUMBER_G7) ||
14521 	    (sli_family == LPFC_SLI_INTF_FAMILY_G7P &&
14522 	     magic_number != MAGIC_NUMBER_G7P) ||
14523 	    (sli_family == LPFC_SLI_INTF_FAMILY_G8 &&
14524 	     magic_number != MAGIC_NUMBER_G8)) {
14525 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14526 				"3030 This firmware version is not supported on"
14527 				" this HBA model. Device:%x Magic:%x Type:%x "
14528 				"ID:%x Size %d %zd\n",
14529 				phba->pcidev->device, magic_number, ftype, fid,
14530 				fsize, fw->size);
14531 		rc = -EINVAL;
14532 	} else if (offset == ADD_STATUS_FW_DOWNLOAD_HW_DISABLED) {
14533 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14534 				"3021 Firmware downloads have been prohibited "
14535 				"by a system configuration setting on "
14536 				"Device:%x Magic:%x Type:%x ID:%x Size %d "
14537 				"%zd\n",
14538 				phba->pcidev->device, magic_number, ftype, fid,
14539 				fsize, fw->size);
14540 		rc = -EACCES;
14541 	} else {
14542 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14543 				"3022 FW Download failed. Add Status x%x "
14544 				"Device:%x Magic:%x Type:%x ID:%x Size %d "
14545 				"%zd\n",
14546 				offset, phba->pcidev->device, magic_number,
14547 				ftype, fid, fsize, fw->size);
14548 		rc = -EIO;
14549 	}
14550 	return rc;
14551 }
14552 
14553 /**
14554  * lpfc_write_firmware - attempt to write a firmware image to the port
14555  * @fw: pointer to firmware image returned from request_firmware.
14556  * @context: pointer to firmware image returned from request_firmware.
14557  *
14558  **/
14559 static void
14560 lpfc_write_firmware(const struct firmware *fw, void *context)
14561 {
14562 	struct lpfc_hba *phba = (struct lpfc_hba *)context;
14563 	char fwrev[FW_REV_STR_SIZE];
14564 	struct lpfc_grp_hdr *image;
14565 	struct list_head dma_buffer_list;
14566 	int i, rc = 0;
14567 	struct lpfc_dmabuf *dmabuf, *next;
14568 	uint32_t offset = 0, temp_offset = 0;
14569 	uint32_t magic_number, ftype, fid, fsize;
14570 
14571 	/* It can be null in no-wait mode, sanity check */
14572 	if (!fw) {
14573 		rc = -ENXIO;
14574 		goto out;
14575 	}
14576 	image = (struct lpfc_grp_hdr *)fw->data;
14577 
14578 	magic_number = be32_to_cpu(image->magic_number);
14579 	ftype = bf_get_be32(lpfc_grp_hdr_file_type, image);
14580 	fid = bf_get_be32(lpfc_grp_hdr_id, image);
14581 	fsize = be32_to_cpu(image->size);
14582 
14583 	INIT_LIST_HEAD(&dma_buffer_list);
14584 	lpfc_decode_firmware_rev(phba, fwrev, 1);
14585 	if (strncmp(fwrev, image->revision, strnlen(image->revision, 16))) {
14586 		lpfc_log_msg(phba, KERN_NOTICE, LOG_INIT | LOG_SLI,
14587 			     "3023 Updating Firmware, Current Version:%s "
14588 			     "New Version:%s\n",
14589 			     fwrev, image->revision);
14590 		for (i = 0; i < LPFC_MBX_WR_CONFIG_MAX_BDE; i++) {
14591 			dmabuf = kzalloc_obj(struct lpfc_dmabuf);
14592 			if (!dmabuf) {
14593 				rc = -ENOMEM;
14594 				goto release_out;
14595 			}
14596 			dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
14597 							  SLI4_PAGE_SIZE,
14598 							  &dmabuf->phys,
14599 							  GFP_KERNEL);
14600 			if (!dmabuf->virt) {
14601 				kfree(dmabuf);
14602 				rc = -ENOMEM;
14603 				goto release_out;
14604 			}
14605 			list_add_tail(&dmabuf->list, &dma_buffer_list);
14606 		}
14607 		while (offset < fw->size) {
14608 			temp_offset = offset;
14609 			list_for_each_entry(dmabuf, &dma_buffer_list, list) {
14610 				if (temp_offset + SLI4_PAGE_SIZE > fw->size) {
14611 					memcpy(dmabuf->virt,
14612 					       fw->data + temp_offset,
14613 					       fw->size - temp_offset);
14614 					temp_offset = fw->size;
14615 					break;
14616 				}
14617 				memcpy(dmabuf->virt, fw->data + temp_offset,
14618 				       SLI4_PAGE_SIZE);
14619 				temp_offset += SLI4_PAGE_SIZE;
14620 			}
14621 			rc = lpfc_wr_object(phba, &dma_buffer_list,
14622 				    (fw->size - offset), &offset);
14623 			if (rc) {
14624 				rc = lpfc_log_write_firmware_error(phba, offset,
14625 								   magic_number,
14626 								   ftype,
14627 								   fid,
14628 								   fsize,
14629 								   fw);
14630 				goto release_out;
14631 			}
14632 		}
14633 		rc = offset;
14634 	} else
14635 		lpfc_log_msg(phba, KERN_NOTICE, LOG_INIT | LOG_SLI,
14636 			     "3029 Skipped Firmware update, Current "
14637 			     "Version:%s New Version:%s\n",
14638 			     fwrev, image->revision);
14639 
14640 release_out:
14641 	list_for_each_entry_safe(dmabuf, next, &dma_buffer_list, list) {
14642 		list_del(&dmabuf->list);
14643 		dma_free_coherent(&phba->pcidev->dev, SLI4_PAGE_SIZE,
14644 				  dmabuf->virt, dmabuf->phys);
14645 		kfree(dmabuf);
14646 	}
14647 	release_firmware(fw);
14648 out:
14649 	if (rc < 0)
14650 		lpfc_log_msg(phba, KERN_ERR, LOG_INIT | LOG_SLI,
14651 			     "3062 Firmware update error, status %d.\n", rc);
14652 	else
14653 		lpfc_log_msg(phba, KERN_NOTICE, LOG_INIT | LOG_SLI,
14654 			     "3024 Firmware update success: size %d.\n", rc);
14655 }
14656 
14657 /**
14658  * lpfc_sli4_request_firmware_update - Request linux generic firmware upgrade
14659  * @phba: pointer to lpfc hba data structure.
14660  * @fw_upgrade: which firmware to update.
14661  *
14662  * This routine is called to perform Linux generic firmware upgrade on device
14663  * that supports such feature.
14664  **/
14665 int
14666 lpfc_sli4_request_firmware_update(struct lpfc_hba *phba, uint8_t fw_upgrade)
14667 {
14668 	char file_name[ELX_FW_NAME_SIZE] = {0};
14669 	int ret;
14670 	const struct firmware *fw;
14671 
14672 	/* Only supported on SLI4 interface type 2 for now */
14673 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) <
14674 	    LPFC_SLI_INTF_IF_TYPE_2)
14675 		return -EPERM;
14676 
14677 	scnprintf(file_name, sizeof(file_name), "%s.grp", phba->ModelName);
14678 
14679 	if (fw_upgrade == INT_FW_UPGRADE) {
14680 		ret = request_firmware_nowait(THIS_MODULE, FW_ACTION_UEVENT,
14681 					file_name, &phba->pcidev->dev,
14682 					GFP_KERNEL, (void *)phba,
14683 					lpfc_write_firmware);
14684 	} else if (fw_upgrade == RUN_FW_UPGRADE) {
14685 		ret = request_firmware(&fw, file_name, &phba->pcidev->dev);
14686 		if (!ret)
14687 			lpfc_write_firmware(fw, (void *)phba);
14688 	} else {
14689 		ret = -EINVAL;
14690 	}
14691 
14692 	return ret;
14693 }
14694 
14695 /**
14696  * lpfc_pci_probe_one_s4 - PCI probe func to reg SLI-4 device to PCI subsys
14697  * @pdev: pointer to PCI device
14698  * @pid: pointer to PCI device identifier
14699  *
14700  * This routine is called from the kernel's PCI subsystem to device with
14701  * SLI-4 interface spec. When an Emulex HBA with SLI-4 interface spec is
14702  * presented on PCI bus, the kernel PCI subsystem looks at PCI device-specific
14703  * information of the device and driver to see if the driver state that it
14704  * can support this kind of device. If the match is successful, the driver
14705  * core invokes this routine. If this routine determines it can claim the HBA,
14706  * it does all the initialization that it needs to do to handle the HBA
14707  * properly.
14708  *
14709  * Return code
14710  * 	0 - driver can claim the device
14711  * 	negative value - driver can not claim the device
14712  **/
14713 static int
14714 lpfc_pci_probe_one_s4(struct pci_dev *pdev, const struct pci_device_id *pid)
14715 {
14716 	struct lpfc_hba   *phba;
14717 	struct lpfc_vport *vport = NULL;
14718 	struct Scsi_Host  *shost = NULL;
14719 	int error;
14720 	uint32_t cfg_mode, intr_mode;
14721 
14722 	/* Allocate memory for HBA structure */
14723 	phba = lpfc_hba_alloc(pdev);
14724 	if (!phba)
14725 		return -ENOMEM;
14726 
14727 	INIT_LIST_HEAD(&phba->poll_list);
14728 
14729 	/* Perform generic PCI device enabling operation */
14730 	error = lpfc_enable_pci_dev(phba);
14731 	if (error)
14732 		goto out_free_phba;
14733 
14734 	/* Set up SLI API function jump table for PCI-device group-1 HBAs */
14735 	error = lpfc_api_table_setup(phba, LPFC_PCI_DEV_OC);
14736 	if (error)
14737 		goto out_disable_pci_dev;
14738 
14739 	/* Set up SLI-4 specific device PCI memory space */
14740 	error = lpfc_sli4_pci_mem_setup(phba);
14741 	if (error) {
14742 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14743 				"1410 Failed to set up pci memory space.\n");
14744 		goto out_disable_pci_dev;
14745 	}
14746 
14747 	/* Set up SLI-4 Specific device driver resources */
14748 	error = lpfc_sli4_driver_resource_setup(phba);
14749 	if (error) {
14750 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14751 				"1412 Failed to set up driver resource.\n");
14752 		goto out_unset_pci_mem_s4;
14753 	}
14754 
14755 	spin_lock_init(&phba->rrq_list_lock);
14756 	INIT_LIST_HEAD(&phba->active_rrq_list);
14757 	INIT_LIST_HEAD(&phba->fcf.fcf_pri_list);
14758 
14759 	/* Set up common device driver resources */
14760 	error = lpfc_setup_driver_resource_phase2(phba);
14761 	if (error) {
14762 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14763 				"1414 Failed to set up driver resource.\n");
14764 		goto out_unset_driver_resource_s4;
14765 	}
14766 
14767 	/* Get the default values for Model Name and Description */
14768 	lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
14769 
14770 	/* Now, trying to enable interrupt and bring up the device */
14771 	cfg_mode = phba->cfg_use_msi;
14772 
14773 	/* Put device to a known state before enabling interrupt */
14774 	phba->pport = NULL;
14775 	lpfc_stop_port(phba);
14776 
14777 	/* Init cpu_map array */
14778 	lpfc_cpu_map_array_init(phba);
14779 
14780 	/* Init hba_eq_hdl array */
14781 	lpfc_hba_eq_hdl_array_init(phba);
14782 
14783 	/* Configure and enable interrupt */
14784 	intr_mode = lpfc_sli4_enable_intr(phba, cfg_mode);
14785 	if (intr_mode == LPFC_INTR_ERROR) {
14786 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14787 				"0426 Failed to enable interrupt.\n");
14788 		error = -ENODEV;
14789 		goto out_unset_driver_resource;
14790 	}
14791 	/* Default to single EQ for non-MSI-X */
14792 	if (phba->intr_type != MSIX) {
14793 		phba->cfg_irq_chann = 1;
14794 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
14795 			if (phba->nvmet_support)
14796 				phba->cfg_nvmet_mrq = 1;
14797 		}
14798 	}
14799 	lpfc_cpu_affinity_check(phba, phba->cfg_irq_chann);
14800 
14801 	/* Create SCSI host to the physical port */
14802 	error = lpfc_create_shost(phba);
14803 	if (error) {
14804 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14805 				"1415 Failed to create scsi host.\n");
14806 		goto out_disable_intr;
14807 	}
14808 	vport = phba->pport;
14809 	shost = lpfc_shost_from_vport(vport); /* save shost for error cleanup */
14810 
14811 	/* Configure sysfs attributes */
14812 	error = lpfc_alloc_sysfs_attr(vport);
14813 	if (error) {
14814 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14815 				"1416 Failed to allocate sysfs attr\n");
14816 		goto out_destroy_shost;
14817 	}
14818 
14819 	/* Set up SLI-4 HBA */
14820 	if (lpfc_sli4_hba_setup(phba)) {
14821 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14822 				"1421 Failed to set up hba\n");
14823 		error = -ENODEV;
14824 		goto out_free_sysfs_attr;
14825 	}
14826 
14827 	/* Log the current active interrupt mode */
14828 	phba->intr_mode = intr_mode;
14829 	lpfc_log_intr_mode(phba, intr_mode);
14830 
14831 	/* Perform post initialization setup */
14832 	lpfc_post_init_setup(phba);
14833 
14834 	/* NVME support in FW earlier in the driver load corrects the
14835 	 * FC4 type making a check for nvme_support unnecessary.
14836 	 */
14837 	if (phba->nvmet_support == 0) {
14838 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
14839 			/* Create NVME binding with nvme_fc_transport. This
14840 			 * ensures the vport is initialized.  If the localport
14841 			 * create fails, it should not unload the driver to
14842 			 * support field issues.
14843 			 */
14844 			error = lpfc_nvme_create_localport(vport);
14845 			if (error) {
14846 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14847 						"6004 NVME registration "
14848 						"failed, error x%x\n",
14849 						error);
14850 			}
14851 		}
14852 	}
14853 
14854 	/* check for firmware upgrade or downgrade */
14855 	if (phba->cfg_request_firmware_upgrade)
14856 		lpfc_sli4_request_firmware_update(phba, INT_FW_UPGRADE);
14857 
14858 	/* Check if there are static vports to be created. */
14859 	lpfc_create_static_vport(phba);
14860 
14861 	timer_setup(&phba->cpuhp_poll_timer, lpfc_sli4_poll_hbtimer, 0);
14862 	cpuhp_state_add_instance_nocalls(lpfc_cpuhp_state, &phba->cpuhp);
14863 
14864 	return 0;
14865 
14866 out_free_sysfs_attr:
14867 	lpfc_free_sysfs_attr(vport);
14868 out_destroy_shost:
14869 	lpfc_destroy_shost(phba);
14870 out_disable_intr:
14871 	lpfc_sli4_disable_intr(phba);
14872 out_unset_driver_resource:
14873 	lpfc_unset_driver_resource_phase2(phba);
14874 out_unset_driver_resource_s4:
14875 	lpfc_sli4_driver_resource_unset(phba);
14876 out_unset_pci_mem_s4:
14877 	lpfc_sli4_pci_mem_unset(phba);
14878 out_disable_pci_dev:
14879 	lpfc_disable_pci_dev(phba);
14880 	if (shost)
14881 		scsi_host_put(shost);
14882 out_free_phba:
14883 	lpfc_hba_free(phba);
14884 	return error;
14885 }
14886 
14887 /**
14888  * lpfc_pci_remove_one_s4 - PCI func to unreg SLI-4 device from PCI subsystem
14889  * @pdev: pointer to PCI device
14890  *
14891  * This routine is called from the kernel's PCI subsystem to device with
14892  * SLI-4 interface spec. When an Emulex HBA with SLI-4 interface spec is
14893  * removed from PCI bus, it performs all the necessary cleanup for the HBA
14894  * device to be removed from the PCI subsystem properly.
14895  **/
14896 static void
14897 lpfc_pci_remove_one_s4(struct pci_dev *pdev)
14898 {
14899 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
14900 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
14901 	struct lpfc_vport **vports;
14902 	struct lpfc_hba *phba = vport->phba;
14903 	int i;
14904 
14905 	/* Mark the device unloading flag */
14906 	set_bit(FC_UNLOADING, &vport->load_flag);
14907 	if (phba->cgn_i)
14908 		lpfc_unreg_congestion_buf(phba);
14909 
14910 	lpfc_free_sysfs_attr(vport);
14911 
14912 	/* Release all the vports against this physical port */
14913 	vports = lpfc_create_vport_work_array(phba);
14914 	if (vports != NULL)
14915 		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
14916 			if (vports[i]->port_type == LPFC_PHYSICAL_PORT)
14917 				continue;
14918 			fc_vport_terminate(vports[i]->fc_vport);
14919 		}
14920 	lpfc_destroy_vport_work_array(phba, vports);
14921 
14922 	/* Remove FC host with the physical port */
14923 	fc_remove_host(shost);
14924 	scsi_remove_host(shost);
14925 
14926 	/* Perform ndlp cleanup on the physical port.  The nvme and nvmet
14927 	 * localports are destroyed after to cleanup all transport memory.
14928 	 */
14929 	lpfc_cleanup(vport);
14930 	lpfc_nvmet_destroy_targetport(phba);
14931 	lpfc_nvme_destroy_localport(vport);
14932 
14933 	/* De-allocate multi-XRI pools */
14934 	if (phba->cfg_xri_rebalancing)
14935 		lpfc_destroy_multixri_pools(phba);
14936 
14937 	/*
14938 	 * Bring down the SLI Layer. This step disables all interrupts,
14939 	 * clears the rings, discards all mailbox commands, and resets
14940 	 * the HBA FCoE function.
14941 	 */
14942 	lpfc_debugfs_terminate(vport);
14943 
14944 	lpfc_stop_hba_timers(phba);
14945 	spin_lock_irq(&phba->port_list_lock);
14946 	list_del_init(&vport->listentry);
14947 	spin_unlock_irq(&phba->port_list_lock);
14948 
14949 	/* Perform scsi free before driver resource_unset since scsi
14950 	 * buffers are released to their corresponding pools here.
14951 	 */
14952 	lpfc_io_free(phba);
14953 	lpfc_free_iocb_list(phba);
14954 	lpfc_sli4_hba_unset(phba);
14955 
14956 	lpfc_unset_driver_resource_phase2(phba);
14957 	lpfc_sli4_driver_resource_unset(phba);
14958 
14959 	/* Unmap adapter Control and Doorbell registers */
14960 	lpfc_sli4_pci_mem_unset(phba);
14961 
14962 	/* Release PCI resources and disable device's PCI function */
14963 	scsi_host_put(shost);
14964 	lpfc_disable_pci_dev(phba);
14965 
14966 	/* Finally, free the driver's device data structure */
14967 	lpfc_hba_free(phba);
14968 
14969 	return;
14970 }
14971 
14972 /**
14973  * lpfc_pci_suspend_one_s4 - PCI func to suspend SLI-4 device for power mgmnt
14974  * @dev_d: pointer to device
14975  *
14976  * This routine is called from the kernel's PCI subsystem to support system
14977  * Power Management (PM) to device with SLI-4 interface spec. When PM invokes
14978  * this method, it quiesces the device by stopping the driver's worker
14979  * thread for the device, turning off device's interrupt and DMA, and bring
14980  * the device offline. Note that as the driver implements the minimum PM
14981  * requirements to a power-aware driver's PM support for suspend/resume -- all
14982  * the possible PM messages (SUSPEND, HIBERNATE, FREEZE) to the suspend()
14983  * method call will be treated as SUSPEND and the driver will fully
14984  * reinitialize its device during resume() method call, the driver will set
14985  * device to PCI_D3hot state in PCI config space instead of setting it
14986  * according to the @msg provided by the PM.
14987  *
14988  * Return code
14989  * 	0 - driver suspended the device
14990  * 	Error otherwise
14991  **/
14992 static int __maybe_unused
14993 lpfc_pci_suspend_one_s4(struct device *dev_d)
14994 {
14995 	struct Scsi_Host *shost = dev_get_drvdata(dev_d);
14996 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14997 
14998 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
14999 			"2843 PCI device Power Management suspend.\n");
15000 
15001 	/* Bring down the device */
15002 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
15003 	lpfc_offline(phba);
15004 	kthread_stop(phba->worker_thread);
15005 
15006 	/* Disable interrupt from device */
15007 	lpfc_sli4_disable_intr(phba);
15008 	lpfc_sli4_queue_destroy(phba);
15009 
15010 	return 0;
15011 }
15012 
15013 /**
15014  * lpfc_pci_resume_one_s4 - PCI func to resume SLI-4 device for power mgmnt
15015  * @dev_d: pointer to device
15016  *
15017  * This routine is called from the kernel's PCI subsystem to support system
15018  * Power Management (PM) to device with SLI-4 interface spac. When PM invokes
15019  * this method, it restores the device's PCI config space state and fully
15020  * reinitializes the device and brings it online. Note that as the driver
15021  * implements the minimum PM requirements to a power-aware driver's PM for
15022  * suspend/resume -- all the possible PM messages (SUSPEND, HIBERNATE, FREEZE)
15023  * to the suspend() method call will be treated as SUSPEND and the driver
15024  * will fully reinitialize its device during resume() method call, the device
15025  * will be set to PCI_D0 directly in PCI config space before restoring the
15026  * state.
15027  *
15028  * Return code
15029  * 	0 - driver suspended the device
15030  * 	Error otherwise
15031  **/
15032 static int __maybe_unused
15033 lpfc_pci_resume_one_s4(struct device *dev_d)
15034 {
15035 	struct Scsi_Host *shost = dev_get_drvdata(dev_d);
15036 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15037 	uint32_t intr_mode;
15038 	int error;
15039 
15040 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
15041 			"0292 PCI device Power Management resume.\n");
15042 
15043 	 /* Startup the kernel thread for this host adapter. */
15044 	phba->worker_thread = kthread_run(lpfc_do_work, phba,
15045 					"lpfc_worker_%d", phba->brd_no);
15046 	if (IS_ERR(phba->worker_thread)) {
15047 		error = PTR_ERR(phba->worker_thread);
15048 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15049 				"0293 PM resume failed to start worker "
15050 				"thread: error=x%x.\n", error);
15051 		return error;
15052 	}
15053 
15054 	/* Configure and enable interrupt */
15055 	intr_mode = lpfc_sli4_enable_intr(phba, phba->intr_mode);
15056 	if (intr_mode == LPFC_INTR_ERROR) {
15057 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15058 				"0294 PM resume Failed to enable interrupt\n");
15059 		return -EIO;
15060 	} else
15061 		phba->intr_mode = intr_mode;
15062 
15063 	/* Restart HBA and bring it online */
15064 	lpfc_sli_brdrestart(phba);
15065 	lpfc_online(phba);
15066 
15067 	/* Log the current active interrupt mode */
15068 	lpfc_log_intr_mode(phba, phba->intr_mode);
15069 
15070 	return 0;
15071 }
15072 
15073 /**
15074  * lpfc_sli4_prep_dev_for_recover - Prepare SLI4 device for pci slot recover
15075  * @phba: pointer to lpfc hba data structure.
15076  *
15077  * This routine is called to prepare the SLI4 device for PCI slot recover. It
15078  * aborts all the outstanding SCSI I/Os to the pci device.
15079  **/
15080 static void
15081 lpfc_sli4_prep_dev_for_recover(struct lpfc_hba *phba)
15082 {
15083 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15084 			"2828 PCI channel I/O abort preparing for recovery\n");
15085 	/*
15086 	 * There may be errored I/Os through HBA, abort all I/Os on txcmplq
15087 	 * and let the SCSI mid-layer to retry them to recover.
15088 	 */
15089 	lpfc_sli_abort_fcp_rings(phba);
15090 }
15091 
15092 /**
15093  * lpfc_sli4_prep_dev_for_reset - Prepare SLI4 device for pci slot reset
15094  * @phba: pointer to lpfc hba data structure.
15095  *
15096  * This routine is called to prepare the SLI4 device for PCI slot reset. It
15097  * disables the device interrupt and pci device, and aborts the internal FCP
15098  * pending I/Os.
15099  **/
15100 static void
15101 lpfc_sli4_prep_dev_for_reset(struct lpfc_hba *phba)
15102 {
15103 	int offline =  pci_channel_offline(phba->pcidev);
15104 
15105 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15106 			"2826 PCI channel disable preparing for reset offline"
15107 			" %d\n", offline);
15108 
15109 	/* Block any management I/Os to the device */
15110 	lpfc_block_mgmt_io(phba, LPFC_MBX_NO_WAIT);
15111 
15112 
15113 	/* HBA_PCI_ERR was set in io_error_detect */
15114 	lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
15115 	/* Flush all driver's outstanding I/Os as we are to reset */
15116 	lpfc_sli_flush_io_rings(phba);
15117 	lpfc_offline(phba);
15118 
15119 	/* stop all timers */
15120 	lpfc_stop_hba_timers(phba);
15121 
15122 	lpfc_sli4_queue_destroy(phba);
15123 	/* Disable interrupt and pci device */
15124 	lpfc_sli4_disable_intr(phba);
15125 	pci_disable_device(phba->pcidev);
15126 }
15127 
15128 /**
15129  * lpfc_sli4_prep_dev_for_perm_failure - Prepare SLI4 dev for pci slot disable
15130  * @phba: pointer to lpfc hba data structure.
15131  *
15132  * This routine is called to prepare the SLI4 device for PCI slot permanently
15133  * disabling. It blocks the SCSI transport layer traffic and flushes the FCP
15134  * pending I/Os.
15135  **/
15136 static void
15137 lpfc_sli4_prep_dev_for_perm_failure(struct lpfc_hba *phba)
15138 {
15139 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15140 			"2827 PCI channel permanent disable for failure\n");
15141 
15142 	/* Block all SCSI devices' I/Os on the host */
15143 	lpfc_scsi_dev_block(phba);
15144 
15145 	/* stop all timers */
15146 	lpfc_stop_hba_timers(phba);
15147 
15148 	/* Clean up all driver's outstanding I/Os */
15149 	lpfc_sli_flush_io_rings(phba);
15150 }
15151 
15152 /**
15153  * lpfc_io_error_detected_s4 - Method for handling PCI I/O error to SLI-4 device
15154  * @pdev: pointer to PCI device.
15155  * @state: the current PCI connection state.
15156  *
15157  * This routine is called from the PCI subsystem for error handling to device
15158  * with SLI-4 interface spec. This function is called by the PCI subsystem
15159  * after a PCI bus error affecting this device has been detected. When this
15160  * function is invoked, it will need to stop all the I/Os and interrupt(s)
15161  * to the device. Once that is done, it will return PCI_ERS_RESULT_NEED_RESET
15162  * for the PCI subsystem to perform proper recovery as desired.
15163  *
15164  * Return codes
15165  * 	PCI_ERS_RESULT_NEED_RESET - need to reset before recovery
15166  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15167  **/
15168 static pci_ers_result_t
15169 lpfc_io_error_detected_s4(struct pci_dev *pdev, pci_channel_state_t state)
15170 {
15171 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15172 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15173 	bool hba_pci_err;
15174 
15175 	switch (state) {
15176 	case pci_channel_io_normal:
15177 		/* Non-fatal error, prepare for recovery */
15178 		lpfc_sli4_prep_dev_for_recover(phba);
15179 		return PCI_ERS_RESULT_CAN_RECOVER;
15180 	case pci_channel_io_frozen:
15181 		hba_pci_err = test_and_set_bit(HBA_PCI_ERR, &phba->bit_flags);
15182 		/* Fatal error, prepare for slot reset */
15183 		if (!hba_pci_err)
15184 			lpfc_sli4_prep_dev_for_reset(phba);
15185 		else
15186 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15187 					"2832  Already handling PCI error "
15188 					"state: x%x\n", state);
15189 		return PCI_ERS_RESULT_NEED_RESET;
15190 	case pci_channel_io_perm_failure:
15191 		set_bit(HBA_PCI_ERR, &phba->bit_flags);
15192 		/* Permanent failure, prepare for device down */
15193 		lpfc_sli4_prep_dev_for_perm_failure(phba);
15194 		return PCI_ERS_RESULT_DISCONNECT;
15195 	default:
15196 		hba_pci_err = test_and_set_bit(HBA_PCI_ERR, &phba->bit_flags);
15197 		if (!hba_pci_err)
15198 			lpfc_sli4_prep_dev_for_reset(phba);
15199 		/* Unknown state, prepare and request slot reset */
15200 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15201 				"2825 Unknown PCI error state: x%x\n", state);
15202 		lpfc_sli4_prep_dev_for_reset(phba);
15203 		return PCI_ERS_RESULT_NEED_RESET;
15204 	}
15205 }
15206 
15207 /**
15208  * lpfc_io_slot_reset_s4 - Method for restart PCI SLI-4 device from scratch
15209  * @pdev: pointer to PCI device.
15210  *
15211  * This routine is called from the PCI subsystem for error handling to device
15212  * with SLI-4 interface spec. It is called after PCI bus has been reset to
15213  * restart the PCI card from scratch, as if from a cold-boot. During the
15214  * PCI subsystem error recovery, after the driver returns
15215  * PCI_ERS_RESULT_NEED_RESET, the PCI subsystem will perform proper error
15216  * recovery and then call this routine before calling the .resume method to
15217  * recover the device. This function will initialize the HBA device, enable
15218  * the interrupt, but it will just put the HBA to offline state without
15219  * passing any I/O traffic.
15220  *
15221  * Return codes
15222  * 	PCI_ERS_RESULT_RECOVERED - the device has been recovered
15223  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15224  */
15225 static pci_ers_result_t
15226 lpfc_io_slot_reset_s4(struct pci_dev *pdev)
15227 {
15228 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15229 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15230 	struct lpfc_sli *psli = &phba->sli;
15231 	uint32_t intr_mode;
15232 	bool hba_pci_err;
15233 
15234 	dev_printk(KERN_INFO, &pdev->dev, "recovering from a slot reset.\n");
15235 	if (pci_enable_device_mem(pdev)) {
15236 		printk(KERN_ERR "lpfc: Cannot re-enable "
15237 		       "PCI device after reset.\n");
15238 		return PCI_ERS_RESULT_DISCONNECT;
15239 	}
15240 
15241 	pci_restore_state(pdev);
15242 
15243 	hba_pci_err = test_and_clear_bit(HBA_PCI_ERR, &phba->bit_flags);
15244 	if (!hba_pci_err)
15245 		dev_info(&pdev->dev,
15246 			 "hba_pci_err was not set, recovering slot reset.\n");
15247 	/*
15248 	 * As the new kernel behavior of pci_restore_state() API call clears
15249 	 * device saved_state flag, need to save the restored state again.
15250 	 */
15251 	pci_save_state(pdev);
15252 
15253 	if (pdev->is_busmaster)
15254 		pci_set_master(pdev);
15255 
15256 	spin_lock_irq(&phba->hbalock);
15257 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
15258 	spin_unlock_irq(&phba->hbalock);
15259 
15260 	/* Init cpu_map array */
15261 	lpfc_cpu_map_array_init(phba);
15262 	/* Configure and enable interrupt */
15263 	intr_mode = lpfc_sli4_enable_intr(phba, phba->intr_mode);
15264 	if (intr_mode == LPFC_INTR_ERROR) {
15265 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15266 				"2824 Cannot re-enable interrupt after "
15267 				"slot reset.\n");
15268 		return PCI_ERS_RESULT_DISCONNECT;
15269 	} else
15270 		phba->intr_mode = intr_mode;
15271 	lpfc_cpu_affinity_check(phba, phba->cfg_irq_chann);
15272 
15273 	/* Log the current active interrupt mode */
15274 	lpfc_log_intr_mode(phba, phba->intr_mode);
15275 
15276 	return PCI_ERS_RESULT_RECOVERED;
15277 }
15278 
15279 /**
15280  * lpfc_io_resume_s4 - Method for resuming PCI I/O operation to SLI-4 device
15281  * @pdev: pointer to PCI device
15282  *
15283  * This routine is called from the PCI subsystem for error handling to device
15284  * with SLI-4 interface spec. It is called when kernel error recovery tells
15285  * the lpfc driver that it is ok to resume normal PCI operation after PCI bus
15286  * error recovery. After this call, traffic can start to flow from this device
15287  * again.
15288  **/
15289 static void
15290 lpfc_io_resume_s4(struct pci_dev *pdev)
15291 {
15292 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15293 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15294 
15295 	/*
15296 	 * In case of slot reset, as function reset is performed through
15297 	 * mailbox command which needs DMA to be enabled, this operation
15298 	 * has to be moved to the io resume phase. Taking device offline
15299 	 * will perform the necessary cleanup.
15300 	 */
15301 	if (!(phba->sli.sli_flag & LPFC_SLI_ACTIVE)) {
15302 		/* Perform device reset */
15303 		lpfc_sli_brdrestart(phba);
15304 		/* Bring the device back online */
15305 		lpfc_online(phba);
15306 	}
15307 }
15308 
15309 /**
15310  * lpfc_pci_probe_one - lpfc PCI probe func to reg dev to PCI subsystem
15311  * @pdev: pointer to PCI device
15312  * @pid: pointer to PCI device identifier
15313  *
15314  * This routine is to be registered to the kernel's PCI subsystem. When an
15315  * Emulex HBA device is presented on PCI bus, the kernel PCI subsystem looks
15316  * at PCI device-specific information of the device and driver to see if the
15317  * driver state that it can support this kind of device. If the match is
15318  * successful, the driver core invokes this routine. This routine dispatches
15319  * the action to the proper SLI-3 or SLI-4 device probing routine, which will
15320  * do all the initialization that it needs to do to handle the HBA device
15321  * properly.
15322  *
15323  * Return code
15324  * 	0 - driver can claim the device
15325  * 	negative value - driver can not claim the device
15326  **/
15327 static int
15328 lpfc_pci_probe_one(struct pci_dev *pdev, const struct pci_device_id *pid)
15329 {
15330 	int rc;
15331 	struct lpfc_sli_intf intf;
15332 
15333 	if (pci_read_config_dword(pdev, LPFC_SLI_INTF, &intf.word0))
15334 		return -ENODEV;
15335 
15336 	if ((bf_get(lpfc_sli_intf_valid, &intf) == LPFC_SLI_INTF_VALID) &&
15337 	    (bf_get(lpfc_sli_intf_slirev, &intf) == LPFC_SLI_INTF_REV_SLI4))
15338 		rc = lpfc_pci_probe_one_s4(pdev, pid);
15339 	else
15340 		rc = lpfc_pci_probe_one_s3(pdev, pid);
15341 
15342 	return rc;
15343 }
15344 
15345 /**
15346  * lpfc_pci_remove_one - lpfc PCI func to unreg dev from PCI subsystem
15347  * @pdev: pointer to PCI device
15348  *
15349  * This routine is to be registered to the kernel's PCI subsystem. When an
15350  * Emulex HBA is removed from PCI bus, the driver core invokes this routine.
15351  * This routine dispatches the action to the proper SLI-3 or SLI-4 device
15352  * remove routine, which will perform all the necessary cleanup for the
15353  * device to be removed from the PCI subsystem properly.
15354  **/
15355 static void
15356 lpfc_pci_remove_one(struct pci_dev *pdev)
15357 {
15358 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15359 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15360 
15361 	switch (phba->pci_dev_grp) {
15362 	case LPFC_PCI_DEV_LP:
15363 		lpfc_pci_remove_one_s3(pdev);
15364 		break;
15365 	case LPFC_PCI_DEV_OC:
15366 		lpfc_pci_remove_one_s4(pdev);
15367 		break;
15368 	default:
15369 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15370 				"1424 Invalid PCI device group: 0x%x\n",
15371 				phba->pci_dev_grp);
15372 		break;
15373 	}
15374 	return;
15375 }
15376 
15377 /**
15378  * lpfc_pci_suspend_one - lpfc PCI func to suspend dev for power management
15379  * @dev: pointer to device
15380  *
15381  * This routine is to be registered to the kernel's PCI subsystem to support
15382  * system Power Management (PM). When PM invokes this method, it dispatches
15383  * the action to the proper SLI-3 or SLI-4 device suspend routine, which will
15384  * suspend the device.
15385  *
15386  * Return code
15387  * 	0 - driver suspended the device
15388  * 	Error otherwise
15389  **/
15390 static int __maybe_unused
15391 lpfc_pci_suspend_one(struct device *dev)
15392 {
15393 	struct Scsi_Host *shost = dev_get_drvdata(dev);
15394 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15395 	int rc = -ENODEV;
15396 
15397 	switch (phba->pci_dev_grp) {
15398 	case LPFC_PCI_DEV_LP:
15399 		rc = lpfc_pci_suspend_one_s3(dev);
15400 		break;
15401 	case LPFC_PCI_DEV_OC:
15402 		rc = lpfc_pci_suspend_one_s4(dev);
15403 		break;
15404 	default:
15405 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15406 				"1425 Invalid PCI device group: 0x%x\n",
15407 				phba->pci_dev_grp);
15408 		break;
15409 	}
15410 	return rc;
15411 }
15412 
15413 /**
15414  * lpfc_pci_resume_one - lpfc PCI func to resume dev for power management
15415  * @dev: pointer to device
15416  *
15417  * This routine is to be registered to the kernel's PCI subsystem to support
15418  * system Power Management (PM). When PM invokes this method, it dispatches
15419  * the action to the proper SLI-3 or SLI-4 device resume routine, which will
15420  * resume the device.
15421  *
15422  * Return code
15423  * 	0 - driver suspended the device
15424  * 	Error otherwise
15425  **/
15426 static int __maybe_unused
15427 lpfc_pci_resume_one(struct device *dev)
15428 {
15429 	struct Scsi_Host *shost = dev_get_drvdata(dev);
15430 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15431 	int rc = -ENODEV;
15432 
15433 	switch (phba->pci_dev_grp) {
15434 	case LPFC_PCI_DEV_LP:
15435 		rc = lpfc_pci_resume_one_s3(dev);
15436 		break;
15437 	case LPFC_PCI_DEV_OC:
15438 		rc = lpfc_pci_resume_one_s4(dev);
15439 		break;
15440 	default:
15441 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15442 				"1426 Invalid PCI device group: 0x%x\n",
15443 				phba->pci_dev_grp);
15444 		break;
15445 	}
15446 	return rc;
15447 }
15448 
15449 /**
15450  * lpfc_io_error_detected - lpfc method for handling PCI I/O error
15451  * @pdev: pointer to PCI device.
15452  * @state: the current PCI connection state.
15453  *
15454  * This routine is registered to the PCI subsystem for error handling. This
15455  * function is called by the PCI subsystem after a PCI bus error affecting
15456  * this device has been detected. When this routine is invoked, it dispatches
15457  * the action to the proper SLI-3 or SLI-4 device error detected handling
15458  * routine, which will perform the proper error detected operation.
15459  *
15460  * Return codes
15461  * 	PCI_ERS_RESULT_NEED_RESET - need to reset before recovery
15462  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15463  **/
15464 static pci_ers_result_t
15465 lpfc_io_error_detected(struct pci_dev *pdev, pci_channel_state_t state)
15466 {
15467 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15468 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15469 	pci_ers_result_t rc = PCI_ERS_RESULT_DISCONNECT;
15470 
15471 	if (phba->link_state == LPFC_HBA_ERROR &&
15472 	    test_bit(HBA_IOQ_FLUSH, &phba->hba_flag))
15473 		return PCI_ERS_RESULT_NEED_RESET;
15474 
15475 	switch (phba->pci_dev_grp) {
15476 	case LPFC_PCI_DEV_LP:
15477 		rc = lpfc_io_error_detected_s3(pdev, state);
15478 		break;
15479 	case LPFC_PCI_DEV_OC:
15480 		rc = lpfc_io_error_detected_s4(pdev, state);
15481 		break;
15482 	default:
15483 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15484 				"1427 Invalid PCI device group: 0x%x\n",
15485 				phba->pci_dev_grp);
15486 		break;
15487 	}
15488 	return rc;
15489 }
15490 
15491 /**
15492  * lpfc_io_slot_reset - lpfc method for restart PCI dev from scratch
15493  * @pdev: pointer to PCI device.
15494  *
15495  * This routine is registered to the PCI subsystem for error handling. This
15496  * function is called after PCI bus has been reset to restart the PCI card
15497  * from scratch, as if from a cold-boot. When this routine is invoked, it
15498  * dispatches the action to the proper SLI-3 or SLI-4 device reset handling
15499  * routine, which will perform the proper device reset.
15500  *
15501  * Return codes
15502  * 	PCI_ERS_RESULT_RECOVERED - the device has been recovered
15503  * 	PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15504  **/
15505 static pci_ers_result_t
15506 lpfc_io_slot_reset(struct pci_dev *pdev)
15507 {
15508 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15509 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15510 	pci_ers_result_t rc = PCI_ERS_RESULT_DISCONNECT;
15511 
15512 	switch (phba->pci_dev_grp) {
15513 	case LPFC_PCI_DEV_LP:
15514 		rc = lpfc_io_slot_reset_s3(pdev);
15515 		break;
15516 	case LPFC_PCI_DEV_OC:
15517 		rc = lpfc_io_slot_reset_s4(pdev);
15518 		break;
15519 	default:
15520 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15521 				"1428 Invalid PCI device group: 0x%x\n",
15522 				phba->pci_dev_grp);
15523 		break;
15524 	}
15525 	return rc;
15526 }
15527 
15528 /**
15529  * lpfc_io_resume - lpfc method for resuming PCI I/O operation
15530  * @pdev: pointer to PCI device
15531  *
15532  * This routine is registered to the PCI subsystem for error handling. It
15533  * is called when kernel error recovery tells the lpfc driver that it is
15534  * OK to resume normal PCI operation after PCI bus error recovery. When
15535  * this routine is invoked, it dispatches the action to the proper SLI-3
15536  * or SLI-4 device io_resume routine, which will resume the device operation.
15537  **/
15538 static void
15539 lpfc_io_resume(struct pci_dev *pdev)
15540 {
15541 	struct Scsi_Host *shost = pci_get_drvdata(pdev);
15542 	struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15543 
15544 	switch (phba->pci_dev_grp) {
15545 	case LPFC_PCI_DEV_LP:
15546 		lpfc_io_resume_s3(pdev);
15547 		break;
15548 	case LPFC_PCI_DEV_OC:
15549 		lpfc_io_resume_s4(pdev);
15550 		break;
15551 	default:
15552 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15553 				"1429 Invalid PCI device group: 0x%x\n",
15554 				phba->pci_dev_grp);
15555 		break;
15556 	}
15557 	return;
15558 }
15559 
15560 /**
15561  * lpfc_sli4_oas_verify - Verify OAS is supported by this adapter
15562  * @phba: pointer to lpfc hba data structure.
15563  *
15564  * This routine checks to see if OAS is supported for this adapter. If
15565  * supported, the configure Flash Optimized Fabric flag is set.  Otherwise,
15566  * the enable oas flag is cleared and the pool created for OAS device data
15567  * is destroyed.
15568  *
15569  **/
15570 static void
15571 lpfc_sli4_oas_verify(struct lpfc_hba *phba)
15572 {
15573 
15574 	if (!phba->cfg_EnableXLane)
15575 		return;
15576 
15577 	if (phba->sli4_hba.pc_sli4_params.oas_supported) {
15578 		phba->cfg_fof = 1;
15579 	} else {
15580 		phba->cfg_fof = 0;
15581 		mempool_destroy(phba->device_data_mem_pool);
15582 		phba->device_data_mem_pool = NULL;
15583 	}
15584 
15585 	return;
15586 }
15587 
15588 /**
15589  * lpfc_sli4_ras_init - Verify RAS-FW log is supported by this adapter
15590  * @phba: pointer to lpfc hba data structure.
15591  *
15592  * This routine checks to see if RAS is supported by the adapter. Check the
15593  * function through which RAS support enablement is to be done.
15594  **/
15595 void
15596 lpfc_sli4_ras_init(struct lpfc_hba *phba)
15597 {
15598 	/* if ASIC_GEN_NUM >= 0xC) */
15599 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
15600 		    LPFC_SLI_INTF_IF_TYPE_6) ||
15601 	    (bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf) ==
15602 		    LPFC_SLI_INTF_FAMILY_G6)) {
15603 		phba->ras_fwlog.ras_hwsupport = true;
15604 		if (phba->cfg_ras_fwlog_func == PCI_FUNC(phba->pcidev->devfn) &&
15605 		    phba->cfg_ras_fwlog_buffsize)
15606 			phba->ras_fwlog.ras_enabled = true;
15607 		else
15608 			phba->ras_fwlog.ras_enabled = false;
15609 	} else {
15610 		phba->ras_fwlog.ras_hwsupport = false;
15611 	}
15612 }
15613 
15614 
15615 MODULE_DEVICE_TABLE(pci, lpfc_id_table);
15616 
15617 static const struct pci_error_handlers lpfc_err_handler = {
15618 	.error_detected = lpfc_io_error_detected,
15619 	.slot_reset = lpfc_io_slot_reset,
15620 	.resume = lpfc_io_resume,
15621 };
15622 
15623 static SIMPLE_DEV_PM_OPS(lpfc_pci_pm_ops_one,
15624 			 lpfc_pci_suspend_one,
15625 			 lpfc_pci_resume_one);
15626 
15627 static struct pci_driver lpfc_driver = {
15628 	.name		= LPFC_DRIVER_NAME,
15629 	.id_table	= lpfc_id_table,
15630 	.probe		= lpfc_pci_probe_one,
15631 	.remove		= lpfc_pci_remove_one,
15632 	.shutdown	= lpfc_pci_remove_one,
15633 	.driver.pm	= &lpfc_pci_pm_ops_one,
15634 	.err_handler    = &lpfc_err_handler,
15635 };
15636 
15637 static const struct file_operations lpfc_mgmt_fop = {
15638 	.owner = THIS_MODULE,
15639 };
15640 
15641 static struct miscdevice lpfc_mgmt_dev = {
15642 	.minor = MISC_DYNAMIC_MINOR,
15643 	.name = "lpfcmgmt",
15644 	.fops = &lpfc_mgmt_fop,
15645 };
15646 
15647 /**
15648  * lpfc_init - lpfc module initialization routine
15649  *
15650  * This routine is to be invoked when the lpfc module is loaded into the
15651  * kernel. The special kernel macro module_init() is used to indicate the
15652  * role of this routine to the kernel as lpfc module entry point.
15653  *
15654  * Return codes
15655  *   0 - successful
15656  *   -ENOMEM - FC attach transport failed
15657  *   all others - failed
15658  */
15659 static int __init
15660 lpfc_init(void)
15661 {
15662 	int error = 0;
15663 
15664 	pr_info(LPFC_MODULE_DESC "\n");
15665 	pr_info(LPFC_COPYRIGHT "\n");
15666 
15667 	error = misc_register(&lpfc_mgmt_dev);
15668 	if (error)
15669 		printk(KERN_ERR "Could not register lpfcmgmt device, "
15670 			"misc_register returned with status %d", error);
15671 
15672 	error = -ENOMEM;
15673 	lpfc_transport_functions.vport_create = lpfc_vport_create;
15674 	lpfc_transport_functions.vport_delete = lpfc_vport_delete;
15675 	lpfc_transport_template =
15676 				fc_attach_transport(&lpfc_transport_functions);
15677 	if (lpfc_transport_template == NULL)
15678 		goto unregister;
15679 	lpfc_vport_transport_template =
15680 		fc_attach_transport(&lpfc_vport_transport_functions);
15681 	if (lpfc_vport_transport_template == NULL) {
15682 		fc_release_transport(lpfc_transport_template);
15683 		goto unregister;
15684 	}
15685 	lpfc_wqe_cmd_template();
15686 	lpfc_nvmet_cmd_template();
15687 
15688 	/* Initialize in case vector mapping is needed */
15689 	lpfc_present_cpu = num_present_cpus();
15690 
15691 	lpfc_pldv_detect = false;
15692 
15693 	error = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN,
15694 					"lpfc/sli4:online",
15695 					lpfc_cpu_online, lpfc_cpu_offline);
15696 	if (error < 0)
15697 		goto cpuhp_failure;
15698 	lpfc_cpuhp_state = error;
15699 
15700 	error = pci_register_driver(&lpfc_driver);
15701 	if (error)
15702 		goto unwind;
15703 
15704 	return error;
15705 
15706 unwind:
15707 	cpuhp_remove_multi_state(lpfc_cpuhp_state);
15708 cpuhp_failure:
15709 	fc_release_transport(lpfc_transport_template);
15710 	fc_release_transport(lpfc_vport_transport_template);
15711 unregister:
15712 	misc_deregister(&lpfc_mgmt_dev);
15713 
15714 	return error;
15715 }
15716 
15717 void lpfc_dmp_dbg(struct lpfc_hba *phba)
15718 {
15719 	unsigned int start_idx;
15720 	unsigned int dbg_cnt;
15721 	unsigned int temp_idx;
15722 	int i;
15723 	int j = 0;
15724 	unsigned long rem_nsec;
15725 
15726 	if (atomic_cmpxchg(&phba->dbg_log_dmping, 0, 1) != 0)
15727 		return;
15728 
15729 	start_idx = (unsigned int)atomic_read(&phba->dbg_log_idx) % DBG_LOG_SZ;
15730 	dbg_cnt = (unsigned int)atomic_read(&phba->dbg_log_cnt);
15731 	if (!dbg_cnt)
15732 		goto out;
15733 	temp_idx = start_idx;
15734 	if (dbg_cnt >= DBG_LOG_SZ) {
15735 		dbg_cnt = DBG_LOG_SZ;
15736 		temp_idx -= 1;
15737 	} else {
15738 		if ((start_idx + dbg_cnt) > (DBG_LOG_SZ - 1)) {
15739 			temp_idx = (start_idx + dbg_cnt) % DBG_LOG_SZ;
15740 		} else {
15741 			if (start_idx < dbg_cnt)
15742 				start_idx = DBG_LOG_SZ - (dbg_cnt - start_idx);
15743 			else
15744 				start_idx -= dbg_cnt;
15745 		}
15746 	}
15747 	dev_info(&phba->pcidev->dev, "start %d end %d cnt %d\n",
15748 		 start_idx, temp_idx, dbg_cnt);
15749 
15750 	for (i = 0; i < dbg_cnt; i++) {
15751 		if ((start_idx + i) < DBG_LOG_SZ)
15752 			temp_idx = (start_idx + i) % DBG_LOG_SZ;
15753 		else
15754 			temp_idx = j++;
15755 		rem_nsec = do_div(phba->dbg_log[temp_idx].t_ns, NSEC_PER_SEC);
15756 		dev_info(&phba->pcidev->dev, "%d: [%5lu.%06lu] %s",
15757 			 temp_idx,
15758 			 (unsigned long)phba->dbg_log[temp_idx].t_ns,
15759 			 rem_nsec / 1000,
15760 			 phba->dbg_log[temp_idx].log);
15761 	}
15762 out:
15763 	atomic_set(&phba->dbg_log_cnt, 0);
15764 	atomic_set(&phba->dbg_log_dmping, 0);
15765 }
15766 
15767 __printf(2, 3)
15768 void lpfc_dbg_print(struct lpfc_hba *phba, const char *fmt, ...)
15769 {
15770 	unsigned int idx;
15771 	va_list args;
15772 	int dbg_dmping = atomic_read(&phba->dbg_log_dmping);
15773 	struct va_format vaf;
15774 
15775 
15776 	va_start(args, fmt);
15777 	if (unlikely(dbg_dmping)) {
15778 		vaf.fmt = fmt;
15779 		vaf.va = &args;
15780 		dev_info(&phba->pcidev->dev, "%pV", &vaf);
15781 		va_end(args);
15782 		return;
15783 	}
15784 	idx = (unsigned int)atomic_fetch_add(1, &phba->dbg_log_idx) %
15785 		DBG_LOG_SZ;
15786 
15787 	atomic_inc(&phba->dbg_log_cnt);
15788 
15789 	vscnprintf(phba->dbg_log[idx].log,
15790 		   sizeof(phba->dbg_log[idx].log), fmt, args);
15791 	va_end(args);
15792 
15793 	phba->dbg_log[idx].t_ns = local_clock();
15794 }
15795 
15796 /**
15797  * lpfc_exit - lpfc module removal routine
15798  *
15799  * This routine is invoked when the lpfc module is removed from the kernel.
15800  * The special kernel macro module_exit() is used to indicate the role of
15801  * this routine to the kernel as lpfc module exit point.
15802  */
15803 static void __exit
15804 lpfc_exit(void)
15805 {
15806 	misc_deregister(&lpfc_mgmt_dev);
15807 	pci_unregister_driver(&lpfc_driver);
15808 	cpuhp_remove_multi_state(lpfc_cpuhp_state);
15809 	fc_release_transport(lpfc_transport_template);
15810 	fc_release_transport(lpfc_vport_transport_template);
15811 	idr_destroy(&lpfc_hba_index);
15812 }
15813 
15814 module_init(lpfc_init);
15815 module_exit(lpfc_exit);
15816 MODULE_LICENSE("GPL");
15817 MODULE_DESCRIPTION(LPFC_MODULE_DESC);
15818 MODULE_AUTHOR("Broadcom");
15819 MODULE_VERSION("0:" LPFC_DRIVER_VERSION);
15820