xref: /linux/drivers/scsi/lpfc/lpfc_sli.c (revision bd5c762ac0519a8c62141751c893cd25a1ad8940)
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/pci.h>
26 #include <linux/interrupt.h>
27 #include <linux/delay.h>
28 #include <linux/seq_buf.h>
29 #include <linux/slab.h>
30 #include <linux/lockdep.h>
31 #include <linux/dmi.h>
32 #include <linux/of.h>
33 
34 #include <scsi/scsi.h>
35 #include <scsi/scsi_cmnd.h>
36 #include <scsi/scsi_device.h>
37 #include <scsi/scsi_host.h>
38 #include <scsi/scsi_transport_fc.h>
39 #include <scsi/fc/fc_fs.h>
40 #include <linux/crash_dump.h>
41 #ifdef CONFIG_X86
42 #include <asm/set_memory.h>
43 #endif
44 
45 #include "lpfc_hw4.h"
46 #include "lpfc_hw.h"
47 #include "lpfc_sli.h"
48 #include "lpfc_sli4.h"
49 #include "lpfc_nl.h"
50 #include "lpfc_disc.h"
51 #include "lpfc.h"
52 #include "lpfc_scsi.h"
53 #include "lpfc_nvme.h"
54 #include "lpfc_crtn.h"
55 #include "lpfc_logmsg.h"
56 #include "lpfc_compat.h"
57 #include "lpfc_debugfs.h"
58 #include "lpfc_vport.h"
59 #include "lpfc_version.h"
60 
61 /* There are only four IOCB completion types. */
62 typedef enum _lpfc_iocb_type {
63 	LPFC_UNKNOWN_IOCB,
64 	LPFC_UNSOL_IOCB,
65 	LPFC_SOL_IOCB,
66 	LPFC_ABORT_IOCB
67 } lpfc_iocb_type;
68 
69 
70 /* Provide function prototypes local to this module. */
71 static int lpfc_sli_issue_mbox_s4(struct lpfc_hba *, LPFC_MBOXQ_t *,
72 				  uint32_t);
73 static int lpfc_sli4_read_rev(struct lpfc_hba *, LPFC_MBOXQ_t *,
74 			      uint8_t *, uint32_t *);
75 static struct lpfc_iocbq *
76 lpfc_sli4_els_preprocess_rspiocbq(struct lpfc_hba *phba,
77 				  struct lpfc_iocbq *rspiocbq);
78 static void lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *,
79 				      struct hbq_dmabuf *);
80 static void lpfc_sli4_handle_mds_loopback(struct lpfc_vport *vport,
81 					  struct hbq_dmabuf *dmabuf);
82 static bool lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba,
83 				   struct lpfc_queue *cq, struct lpfc_cqe *cqe);
84 static int lpfc_sli4_post_sgl_list(struct lpfc_hba *, struct list_head *,
85 				       int);
86 static void lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba,
87 				     struct lpfc_queue *eq,
88 				     struct lpfc_eqe *eqe,
89 				     enum lpfc_poll_mode poll_mode);
90 static bool lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba);
91 static bool lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba);
92 static struct lpfc_cqe *lpfc_sli4_cq_get(struct lpfc_queue *q);
93 static void __lpfc_sli4_consume_cqe(struct lpfc_hba *phba,
94 				    struct lpfc_queue *cq,
95 				    struct lpfc_cqe *cqe);
96 static uint16_t lpfc_wqe_bpl2sgl(struct lpfc_hba *phba,
97 				 struct lpfc_iocbq *pwqeq,
98 				 struct lpfc_sglq *sglq);
99 
100 union lpfc_wqe128 lpfc_iread_cmd_template;
101 union lpfc_wqe128 lpfc_iwrite_cmd_template;
102 union lpfc_wqe128 lpfc_icmnd_cmd_template;
103 
104 /* Setup WQE templates for IOs */
105 void lpfc_wqe_cmd_template(void)
106 {
107 	union lpfc_wqe128 *wqe;
108 
109 	/* IREAD template */
110 	wqe = &lpfc_iread_cmd_template;
111 	memset(wqe, 0, sizeof(union lpfc_wqe128));
112 
113 	/* Word 0, 1, 2 - BDE is variable */
114 
115 	/* Word 3 - cmd_buff_len, payload_offset_len is zero */
116 
117 	/* Word 4 - total_xfer_len is variable */
118 
119 	/* Word 5 - is zero */
120 
121 	/* Word 6 - ctxt_tag, xri_tag is variable */
122 
123 	/* Word 7 */
124 	bf_set(wqe_cmnd, &wqe->fcp_iread.wqe_com, CMD_FCP_IREAD64_WQE);
125 	bf_set(wqe_pu, &wqe->fcp_iread.wqe_com, PARM_READ_CHECK);
126 	bf_set(wqe_class, &wqe->fcp_iread.wqe_com, CLASS3);
127 	bf_set(wqe_ct, &wqe->fcp_iread.wqe_com, SLI4_CT_RPI);
128 
129 	/* Word 8 - abort_tag is variable */
130 
131 	/* Word 9  - reqtag is variable */
132 
133 	/* Word 10 - dbde, wqes is variable */
134 	bf_set(wqe_qosd, &wqe->fcp_iread.wqe_com, 0);
135 	bf_set(wqe_iod, &wqe->fcp_iread.wqe_com, LPFC_WQE_IOD_READ);
136 	bf_set(wqe_lenloc, &wqe->fcp_iread.wqe_com, LPFC_WQE_LENLOC_WORD4);
137 	bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 0);
138 	bf_set(wqe_wqes, &wqe->fcp_iread.wqe_com, 1);
139 
140 	/* Word 11 */
141 	bf_set(wqe_cmd_type, &wqe->fcp_iread.wqe_com, COMMAND_DATA_IN);
142 	bf_set(wqe_cqid, &wqe->fcp_iread.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
143 
144 	/* Word 12 - is zero */
145 
146 	/* IWRITE template */
147 	wqe = &lpfc_iwrite_cmd_template;
148 	memset(wqe, 0, sizeof(union lpfc_wqe128));
149 
150 	/* Word 0, 1, 2 - BDE is variable */
151 
152 	/* Word 3 - cmd_buff_len, payload_offset_len is zero */
153 
154 	/* Word 4 - total_xfer_len is variable */
155 
156 	/* Word 5 - initial_xfer_len is variable */
157 
158 	/* Word 6 - ctxt_tag, xri_tag is variable */
159 
160 	/* Word 7 */
161 	bf_set(wqe_cmnd, &wqe->fcp_iwrite.wqe_com, CMD_FCP_IWRITE64_WQE);
162 	bf_set(wqe_pu, &wqe->fcp_iwrite.wqe_com, PARM_READ_CHECK);
163 	bf_set(wqe_class, &wqe->fcp_iwrite.wqe_com, CLASS3);
164 	bf_set(wqe_ct, &wqe->fcp_iwrite.wqe_com, SLI4_CT_RPI);
165 
166 	/* Word 8 - abort_tag is variable */
167 
168 	/* Word 9  - reqtag is variable */
169 
170 	/* Word 10 - dbde, wqes is variable */
171 	bf_set(wqe_qosd, &wqe->fcp_iwrite.wqe_com, 0);
172 	bf_set(wqe_iod, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_IOD_WRITE);
173 	bf_set(wqe_lenloc, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_LENLOC_WORD4);
174 	bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 0);
175 	bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
176 
177 	/* Word 11 */
178 	bf_set(wqe_cmd_type, &wqe->fcp_iwrite.wqe_com, COMMAND_DATA_OUT);
179 	bf_set(wqe_cqid, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
180 
181 	/* Word 12 - is zero */
182 
183 	/* ICMND template */
184 	wqe = &lpfc_icmnd_cmd_template;
185 	memset(wqe, 0, sizeof(union lpfc_wqe128));
186 
187 	/* Word 0, 1, 2 - BDE is variable */
188 
189 	/* Word 3 - payload_offset_len is variable */
190 
191 	/* Word 4, 5 - is zero */
192 
193 	/* Word 6 - ctxt_tag, xri_tag is variable */
194 
195 	/* Word 7 */
196 	bf_set(wqe_cmnd, &wqe->fcp_icmd.wqe_com, CMD_FCP_ICMND64_WQE);
197 	bf_set(wqe_pu, &wqe->fcp_icmd.wqe_com, 0);
198 	bf_set(wqe_class, &wqe->fcp_icmd.wqe_com, CLASS3);
199 	bf_set(wqe_ct, &wqe->fcp_icmd.wqe_com, SLI4_CT_RPI);
200 
201 	/* Word 8 - abort_tag is variable */
202 
203 	/* Word 9  - reqtag is variable */
204 
205 	/* Word 10 - dbde, wqes is variable */
206 	bf_set(wqe_qosd, &wqe->fcp_icmd.wqe_com, 1);
207 	bf_set(wqe_iod, &wqe->fcp_icmd.wqe_com, LPFC_WQE_IOD_NONE);
208 	bf_set(wqe_lenloc, &wqe->fcp_icmd.wqe_com, LPFC_WQE_LENLOC_NONE);
209 	bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 0);
210 	bf_set(wqe_wqes, &wqe->fcp_icmd.wqe_com, 1);
211 
212 	/* Word 11 */
213 	bf_set(wqe_cmd_type, &wqe->fcp_icmd.wqe_com, COMMAND_DATA_IN);
214 	bf_set(wqe_cqid, &wqe->fcp_icmd.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
215 
216 	/* Word 12, 13, 14, 15 - is zero */
217 }
218 
219 #if defined(CONFIG_64BIT) && defined(__LITTLE_ENDIAN)
220 /**
221  * lpfc_sli4_pcimem_bcopy - SLI4 memory copy function
222  * @srcp: Source memory pointer.
223  * @destp: Destination memory pointer.
224  * @cnt: Number of words required to be copied.
225  *       Must be a multiple of sizeof(uint64_t)
226  *
227  * This function is used for copying data between driver memory
228  * and the SLI WQ. This function also changes the endianness
229  * of each word if native endianness is different from SLI
230  * endianness. This function can be called with or without
231  * lock.
232  **/
233 static void
234 lpfc_sli4_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
235 {
236 	uint64_t *src = srcp;
237 	uint64_t *dest = destp;
238 	int i;
239 
240 	for (i = 0; i < (int)cnt; i += sizeof(uint64_t))
241 		*dest++ = *src++;
242 }
243 #else
244 #define lpfc_sli4_pcimem_bcopy(a, b, c) lpfc_sli_pcimem_bcopy(a, b, c)
245 #endif
246 
247 /**
248  * lpfc_sli4_wq_put - Put a Work Queue Entry on an Work Queue
249  * @q: The Work Queue to operate on.
250  * @wqe: The work Queue Entry to put on the Work queue.
251  *
252  * This routine will copy the contents of @wqe to the next available entry on
253  * the @q. This function will then ring the Work Queue Doorbell to signal the
254  * HBA to start processing the Work Queue Entry. This function returns 0 if
255  * successful. If no entries are available on @q then this function will return
256  * -ENOMEM.
257  * The caller is expected to hold the hbalock when calling this routine.
258  **/
259 static int
260 lpfc_sli4_wq_put(struct lpfc_queue *q, union lpfc_wqe128 *wqe)
261 {
262 	union lpfc_wqe *temp_wqe;
263 	struct lpfc_register doorbell;
264 	uint32_t host_index;
265 	uint32_t idx;
266 	uint32_t i = 0;
267 	uint8_t *tmp;
268 	u32 if_type;
269 
270 	/* sanity check on queue memory */
271 	if (unlikely(!q))
272 		return -ENOMEM;
273 
274 	temp_wqe = lpfc_sli4_qe(q, q->host_index);
275 
276 	/* If the host has not yet processed the next entry then we are done */
277 	idx = ((q->host_index + 1) % q->entry_count);
278 	if (idx == q->hba_index) {
279 		q->WQ_overflow++;
280 		return -EBUSY;
281 	}
282 	q->WQ_posted++;
283 	/* set consumption flag every once in a while */
284 	if (!((q->host_index + 1) % q->notify_interval))
285 		bf_set(wqe_wqec, &wqe->generic.wqe_com, 1);
286 	else
287 		bf_set(wqe_wqec, &wqe->generic.wqe_com, 0);
288 	if (q->phba->sli3_options & LPFC_SLI4_PHWQ_ENABLED)
289 		bf_set(wqe_wqid, &wqe->generic.wqe_com, q->queue_id);
290 	lpfc_sli4_pcimem_bcopy(wqe, temp_wqe, q->entry_size);
291 	if (q->dpp_enable && q->phba->cfg_enable_dpp) {
292 		/* write to DPP aperture taking advatage of Combined Writes */
293 		tmp = (uint8_t *)temp_wqe;
294 #ifdef __raw_writeq
295 		for (i = 0; i < q->entry_size; i += sizeof(uint64_t))
296 			__raw_writeq(*((uint64_t *)(tmp + i)),
297 					q->dpp_regaddr + i);
298 #else
299 		for (i = 0; i < q->entry_size; i += sizeof(uint32_t))
300 			__raw_writel(*((uint32_t *)(tmp + i)),
301 					q->dpp_regaddr + i);
302 #endif
303 	}
304 	/* ensure WQE bcopy and DPP flushed before doorbell write */
305 	wmb();
306 
307 	/* Update the host index before invoking device */
308 	host_index = q->host_index;
309 
310 	q->host_index = idx;
311 
312 	/* Ring Doorbell */
313 	doorbell.word0 = 0;
314 	if (q->db_format == LPFC_DB_LIST_FORMAT) {
315 		if (q->dpp_enable && q->phba->cfg_enable_dpp) {
316 			bf_set(lpfc_if6_wq_db_list_fm_num_posted, &doorbell, 1);
317 			bf_set(lpfc_if6_wq_db_list_fm_dpp, &doorbell, 1);
318 			bf_set(lpfc_if6_wq_db_list_fm_dpp_id, &doorbell,
319 			    q->dpp_id);
320 			bf_set(lpfc_if6_wq_db_list_fm_id, &doorbell,
321 			    q->queue_id);
322 		} else {
323 			bf_set(lpfc_wq_db_list_fm_num_posted, &doorbell, 1);
324 			bf_set(lpfc_wq_db_list_fm_id, &doorbell, q->queue_id);
325 
326 			/* Leave bits <23:16> clear for if_type 6 dpp */
327 			if_type = bf_get(lpfc_sli_intf_if_type,
328 					 &q->phba->sli4_hba.sli_intf);
329 			if (if_type != LPFC_SLI_INTF_IF_TYPE_6)
330 				bf_set(lpfc_wq_db_list_fm_index, &doorbell,
331 				       host_index);
332 		}
333 	} else if (q->db_format == LPFC_DB_RING_FORMAT) {
334 		bf_set(lpfc_wq_db_ring_fm_num_posted, &doorbell, 1);
335 		bf_set(lpfc_wq_db_ring_fm_id, &doorbell, q->queue_id);
336 	} else {
337 		return -EINVAL;
338 	}
339 	writel(doorbell.word0, q->db_regaddr);
340 
341 	return 0;
342 }
343 
344 /**
345  * lpfc_sli4_wq_release - Updates internal hba index for WQ
346  * @q: The Work Queue to operate on.
347  * @index: The index to advance the hba index to.
348  *
349  * This routine will update the HBA index of a queue to reflect consumption of
350  * Work Queue Entries by the HBA. When the HBA indicates that it has consumed
351  * an entry the host calls this function to update the queue's internal
352  * pointers.
353  **/
354 static void
355 lpfc_sli4_wq_release(struct lpfc_queue *q, uint32_t index)
356 {
357 	/* sanity check on queue memory */
358 	if (unlikely(!q))
359 		return;
360 
361 	q->hba_index = index;
362 }
363 
364 /**
365  * lpfc_sli4_mq_put - Put a Mailbox Queue Entry on an Mailbox Queue
366  * @q: The Mailbox Queue to operate on.
367  * @mqe: The Mailbox Queue Entry to put on the Work queue.
368  *
369  * This routine will copy the contents of @mqe to the next available entry on
370  * the @q. This function will then ring the Work Queue Doorbell to signal the
371  * HBA to start processing the Work Queue Entry. This function returns 0 if
372  * successful. If no entries are available on @q then this function will return
373  * -ENOMEM.
374  * The caller is expected to hold the hbalock when calling this routine.
375  **/
376 static uint32_t
377 lpfc_sli4_mq_put(struct lpfc_queue *q, struct lpfc_mqe *mqe)
378 {
379 	struct lpfc_mqe *temp_mqe;
380 	struct lpfc_register doorbell;
381 
382 	/* sanity check on queue memory */
383 	if (unlikely(!q))
384 		return -ENOMEM;
385 	temp_mqe = lpfc_sli4_qe(q, q->host_index);
386 
387 	/* If the host has not yet processed the next entry then we are done */
388 	if (((q->host_index + 1) % q->entry_count) == q->hba_index)
389 		return -ENOMEM;
390 	lpfc_sli4_pcimem_bcopy(mqe, temp_mqe, q->entry_size);
391 	/* Save off the mailbox pointer for completion */
392 	q->phba->mbox = (MAILBOX_t *)temp_mqe;
393 
394 	/* Update the host index before invoking device */
395 	q->host_index = ((q->host_index + 1) % q->entry_count);
396 
397 	/* Ring Doorbell */
398 	doorbell.word0 = 0;
399 	bf_set(lpfc_mq_doorbell_num_posted, &doorbell, 1);
400 	bf_set(lpfc_mq_doorbell_id, &doorbell, q->queue_id);
401 	writel(doorbell.word0, q->phba->sli4_hba.MQDBregaddr);
402 	return 0;
403 }
404 
405 /**
406  * lpfc_sli4_mq_release - Updates internal hba index for MQ
407  * @q: The Mailbox Queue to operate on.
408  *
409  * This routine will update the HBA index of a queue to reflect consumption of
410  * a Mailbox Queue Entry by the HBA. When the HBA indicates that it has consumed
411  * an entry the host calls this function to update the queue's internal
412  * pointers. This routine returns the number of entries that were consumed by
413  * the HBA.
414  **/
415 static uint32_t
416 lpfc_sli4_mq_release(struct lpfc_queue *q)
417 {
418 	/* sanity check on queue memory */
419 	if (unlikely(!q))
420 		return 0;
421 
422 	/* Clear the mailbox pointer for completion */
423 	q->phba->mbox = NULL;
424 	q->hba_index = ((q->hba_index + 1) % q->entry_count);
425 	return 1;
426 }
427 
428 /**
429  * lpfc_sli4_eq_get - Gets the next valid EQE from a EQ
430  * @q: The Event Queue to get the first valid EQE from
431  *
432  * This routine will get the first valid Event Queue Entry from @q, update
433  * the queue's internal hba index, and return the EQE. If no valid EQEs are in
434  * the Queue (no more work to do), or the Queue is full of EQEs that have been
435  * processed, but not popped back to the HBA then this routine will return NULL.
436  **/
437 static struct lpfc_eqe *
438 lpfc_sli4_eq_get(struct lpfc_queue *q)
439 {
440 	struct lpfc_eqe *eqe;
441 
442 	/* sanity check on queue memory */
443 	if (unlikely(!q))
444 		return NULL;
445 	eqe = lpfc_sli4_qe(q, q->host_index);
446 
447 	/* If the next EQE is not valid then we are done */
448 	if (bf_get_le32(lpfc_eqe_valid, eqe) != q->qe_valid)
449 		return NULL;
450 
451 	/*
452 	 * insert barrier for instruction interlock : data from the hardware
453 	 * must have the valid bit checked before it can be copied and acted
454 	 * upon. Speculative instructions were allowing a bcopy at the start
455 	 * of lpfc_sli4_fp_handle_wcqe(), which is called immediately
456 	 * after our return, to copy data before the valid bit check above
457 	 * was done. As such, some of the copied data was stale. The barrier
458 	 * ensures the check is before any data is copied.
459 	 */
460 	mb();
461 	return eqe;
462 }
463 
464 /**
465  * lpfc_sli4_eq_clr_intr - Turn off interrupts from this EQ
466  * @q: The Event Queue to disable interrupts
467  *
468  **/
469 void
470 lpfc_sli4_eq_clr_intr(struct lpfc_queue *q)
471 {
472 	struct lpfc_register doorbell;
473 
474 	doorbell.word0 = 0;
475 	bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
476 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
477 	bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
478 		(q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
479 	bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
480 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
481 }
482 
483 /**
484  * lpfc_sli4_if6_eq_clr_intr - Turn off interrupts from this EQ
485  * @q: The Event Queue to disable interrupts
486  *
487  **/
488 void
489 lpfc_sli4_if6_eq_clr_intr(struct lpfc_queue *q)
490 {
491 	struct lpfc_register doorbell;
492 
493 	doorbell.word0 = 0;
494 	bf_set(lpfc_if6_eq_doorbell_eqid, &doorbell, q->queue_id);
495 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
496 }
497 
498 /**
499  * lpfc_sli4_write_eq_db - write EQ DB for eqe's consumed or arm state
500  * @phba: adapter with EQ
501  * @q: The Event Queue that the host has completed processing for.
502  * @count: Number of elements that have been consumed
503  * @arm: Indicates whether the host wants to arms this CQ.
504  *
505  * This routine will notify the HBA, by ringing the doorbell, that count
506  * number of EQEs have been processed. The @arm parameter indicates whether
507  * the queue should be rearmed when ringing the doorbell.
508  **/
509 void
510 lpfc_sli4_write_eq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
511 		     uint32_t count, bool arm)
512 {
513 	struct lpfc_register doorbell;
514 
515 	/* sanity check on queue memory */
516 	if (unlikely(!q || (count == 0 && !arm)))
517 		return;
518 
519 	/* ring doorbell for number popped */
520 	doorbell.word0 = 0;
521 	if (arm) {
522 		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
523 		bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
524 	}
525 	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, count);
526 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
527 	bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
528 			(q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
529 	bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
530 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
531 	/* PCI read to flush PCI pipeline on re-arming for INTx mode */
532 	if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
533 		readl(q->phba->sli4_hba.EQDBregaddr);
534 }
535 
536 /**
537  * lpfc_sli4_if6_write_eq_db - write EQ DB for eqe's consumed or arm state
538  * @phba: adapter with EQ
539  * @q: The Event Queue that the host has completed processing for.
540  * @count: Number of elements that have been consumed
541  * @arm: Indicates whether the host wants to arms this CQ.
542  *
543  * This routine will notify the HBA, by ringing the doorbell, that count
544  * number of EQEs have been processed. The @arm parameter indicates whether
545  * the queue should be rearmed when ringing the doorbell.
546  **/
547 void
548 lpfc_sli4_if6_write_eq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
549 			  uint32_t count, bool arm)
550 {
551 	struct lpfc_register doorbell;
552 
553 	/* sanity check on queue memory */
554 	if (unlikely(!q || (count == 0 && !arm)))
555 		return;
556 
557 	/* ring doorbell for number popped */
558 	doorbell.word0 = 0;
559 	if (arm)
560 		bf_set(lpfc_if6_eq_doorbell_arm, &doorbell, 1);
561 	bf_set(lpfc_if6_eq_doorbell_num_released, &doorbell, count);
562 	bf_set(lpfc_if6_eq_doorbell_eqid, &doorbell, q->queue_id);
563 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
564 	/* PCI read to flush PCI pipeline on re-arming for INTx mode */
565 	if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
566 		readl(q->phba->sli4_hba.EQDBregaddr);
567 }
568 
569 static void
570 __lpfc_sli4_consume_eqe(struct lpfc_hba *phba, struct lpfc_queue *eq,
571 			struct lpfc_eqe *eqe)
572 {
573 	if (!phba->sli4_hba.pc_sli4_params.eqav)
574 		bf_set_le32(lpfc_eqe_valid, eqe, 0);
575 
576 	eq->host_index = ((eq->host_index + 1) % eq->entry_count);
577 
578 	/* if the index wrapped around, toggle the valid bit */
579 	if (phba->sli4_hba.pc_sli4_params.eqav && !eq->host_index)
580 		eq->qe_valid = (eq->qe_valid) ? 0 : 1;
581 }
582 
583 static void
584 lpfc_sli4_eqcq_flush(struct lpfc_hba *phba, struct lpfc_queue *eq)
585 {
586 	struct lpfc_eqe *eqe = NULL;
587 	u32 eq_count = 0, cq_count = 0;
588 	struct lpfc_cqe *cqe = NULL;
589 	struct lpfc_queue *cq = NULL, *childq = NULL;
590 	int cqid = 0;
591 
592 	/* walk all the EQ entries and drop on the floor */
593 	eqe = lpfc_sli4_eq_get(eq);
594 	while (eqe) {
595 		/* Get the reference to the corresponding CQ */
596 		cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
597 		cq = NULL;
598 
599 		list_for_each_entry(childq, &eq->child_list, list) {
600 			if (childq->queue_id == cqid) {
601 				cq = childq;
602 				break;
603 			}
604 		}
605 		/* If CQ is valid, iterate through it and drop all the CQEs */
606 		if (cq) {
607 			cqe = lpfc_sli4_cq_get(cq);
608 			while (cqe) {
609 				__lpfc_sli4_consume_cqe(phba, cq, cqe);
610 				cq_count++;
611 				cqe = lpfc_sli4_cq_get(cq);
612 			}
613 			/* Clear and re-arm the CQ */
614 			phba->sli4_hba.sli4_write_cq_db(phba, cq, cq_count,
615 			    LPFC_QUEUE_REARM);
616 			cq_count = 0;
617 		}
618 		__lpfc_sli4_consume_eqe(phba, eq, eqe);
619 		eq_count++;
620 		eqe = lpfc_sli4_eq_get(eq);
621 	}
622 
623 	/* Clear and re-arm the EQ */
624 	phba->sli4_hba.sli4_write_eq_db(phba, eq, eq_count, LPFC_QUEUE_REARM);
625 }
626 
627 static int
628 lpfc_sli4_process_eq(struct lpfc_hba *phba, struct lpfc_queue *eq,
629 		     u8 rearm, enum lpfc_poll_mode poll_mode)
630 {
631 	struct lpfc_eqe *eqe;
632 	int count = 0, consumed = 0;
633 
634 	if (cmpxchg(&eq->queue_claimed, 0, 1) != 0)
635 		goto rearm_and_exit;
636 
637 	eqe = lpfc_sli4_eq_get(eq);
638 	while (eqe) {
639 		lpfc_sli4_hba_handle_eqe(phba, eq, eqe, poll_mode);
640 		__lpfc_sli4_consume_eqe(phba, eq, eqe);
641 
642 		consumed++;
643 		if (!(++count % eq->max_proc_limit))
644 			break;
645 
646 		if (!(count % eq->notify_interval)) {
647 			phba->sli4_hba.sli4_write_eq_db(phba, eq, consumed,
648 							LPFC_QUEUE_NOARM);
649 			consumed = 0;
650 		}
651 
652 		eqe = lpfc_sli4_eq_get(eq);
653 	}
654 	eq->EQ_processed += count;
655 
656 	/* Track the max number of EQEs processed in 1 intr */
657 	if (count > eq->EQ_max_eqe)
658 		eq->EQ_max_eqe = count;
659 
660 	xchg(&eq->queue_claimed, 0);
661 
662 rearm_and_exit:
663 	/* Always clear the EQ. */
664 	phba->sli4_hba.sli4_write_eq_db(phba, eq, consumed, rearm);
665 
666 	return count;
667 }
668 
669 /**
670  * lpfc_sli4_cq_get - Gets the next valid CQE from a CQ
671  * @q: The Completion Queue to get the first valid CQE from
672  *
673  * This routine will get the first valid Completion Queue Entry from @q, update
674  * the queue's internal hba index, and return the CQE. If no valid CQEs are in
675  * the Queue (no more work to do), or the Queue is full of CQEs that have been
676  * processed, but not popped back to the HBA then this routine will return NULL.
677  **/
678 static struct lpfc_cqe *
679 lpfc_sli4_cq_get(struct lpfc_queue *q)
680 {
681 	struct lpfc_cqe *cqe;
682 
683 	/* sanity check on queue memory */
684 	if (unlikely(!q))
685 		return NULL;
686 	cqe = lpfc_sli4_qe(q, q->host_index);
687 
688 	/* If the next CQE is not valid then we are done */
689 	if (bf_get_le32(lpfc_cqe_valid, cqe) != q->qe_valid)
690 		return NULL;
691 
692 	/*
693 	 * insert barrier for instruction interlock : data from the hardware
694 	 * must have the valid bit checked before it can be copied and acted
695 	 * upon. Given what was seen in lpfc_sli4_cq_get() of speculative
696 	 * instructions allowing action on content before valid bit checked,
697 	 * add barrier here as well. May not be needed as "content" is a
698 	 * single 32-bit entity here (vs multi word structure for cq's).
699 	 */
700 	mb();
701 	return cqe;
702 }
703 
704 static void
705 __lpfc_sli4_consume_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
706 			struct lpfc_cqe *cqe)
707 {
708 	if (!phba->sli4_hba.pc_sli4_params.cqav)
709 		bf_set_le32(lpfc_cqe_valid, cqe, 0);
710 
711 	cq->host_index = ((cq->host_index + 1) % cq->entry_count);
712 
713 	/* if the index wrapped around, toggle the valid bit */
714 	if (phba->sli4_hba.pc_sli4_params.cqav && !cq->host_index)
715 		cq->qe_valid = (cq->qe_valid) ? 0 : 1;
716 }
717 
718 /**
719  * lpfc_sli4_write_cq_db - write cq DB for entries consumed or arm state.
720  * @phba: the adapter with the CQ
721  * @q: The Completion Queue that the host has completed processing for.
722  * @count: the number of elements that were consumed
723  * @arm: Indicates whether the host wants to arms this CQ.
724  *
725  * This routine will notify the HBA, by ringing the doorbell, that the
726  * CQEs have been processed. The @arm parameter specifies whether the
727  * queue should be rearmed when ringing the doorbell.
728  **/
729 void
730 lpfc_sli4_write_cq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
731 		     uint32_t count, bool arm)
732 {
733 	struct lpfc_register doorbell;
734 
735 	/* sanity check on queue memory */
736 	if (unlikely(!q || (count == 0 && !arm)))
737 		return;
738 
739 	/* ring doorbell for number popped */
740 	doorbell.word0 = 0;
741 	if (arm)
742 		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
743 	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, count);
744 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_COMPLETION);
745 	bf_set(lpfc_eqcq_doorbell_cqid_hi, &doorbell,
746 			(q->queue_id >> LPFC_CQID_HI_FIELD_SHIFT));
747 	bf_set(lpfc_eqcq_doorbell_cqid_lo, &doorbell, q->queue_id);
748 	writel(doorbell.word0, q->phba->sli4_hba.CQDBregaddr);
749 }
750 
751 /**
752  * lpfc_sli4_if6_write_cq_db - write cq DB for entries consumed or arm state.
753  * @phba: the adapter with the CQ
754  * @q: The Completion Queue that the host has completed processing for.
755  * @count: the number of elements that were consumed
756  * @arm: Indicates whether the host wants to arms this CQ.
757  *
758  * This routine will notify the HBA, by ringing the doorbell, that the
759  * CQEs have been processed. The @arm parameter specifies whether the
760  * queue should be rearmed when ringing the doorbell.
761  **/
762 void
763 lpfc_sli4_if6_write_cq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
764 			 uint32_t count, bool arm)
765 {
766 	struct lpfc_register doorbell;
767 
768 	/* sanity check on queue memory */
769 	if (unlikely(!q || (count == 0 && !arm)))
770 		return;
771 
772 	/* ring doorbell for number popped */
773 	doorbell.word0 = 0;
774 	if (arm)
775 		bf_set(lpfc_if6_cq_doorbell_arm, &doorbell, 1);
776 	bf_set(lpfc_if6_cq_doorbell_num_released, &doorbell, count);
777 	bf_set(lpfc_if6_cq_doorbell_cqid, &doorbell, q->queue_id);
778 	writel(doorbell.word0, q->phba->sli4_hba.CQDBregaddr);
779 }
780 
781 /*
782  * lpfc_sli4_rq_put - Put a Receive Buffer Queue Entry on a Receive Queue
783  *
784  * This routine will copy the contents of @wqe to the next available entry on
785  * the @q. This function will then ring the Receive Queue Doorbell to signal the
786  * HBA to start processing the Receive Queue Entry. This function returns the
787  * index that the rqe was copied to if successful. If no entries are available
788  * on @q then this function will return -ENOMEM.
789  * The caller is expected to hold the hbalock when calling this routine.
790  **/
791 int
792 lpfc_sli4_rq_put(struct lpfc_queue *hq, struct lpfc_queue *dq,
793 		 struct lpfc_rqe *hrqe, struct lpfc_rqe *drqe)
794 {
795 	struct lpfc_rqe *temp_hrqe;
796 	struct lpfc_rqe *temp_drqe;
797 	struct lpfc_register doorbell;
798 	int hq_put_index;
799 	int dq_put_index;
800 
801 	/* sanity check on queue memory */
802 	if (unlikely(!hq) || unlikely(!dq))
803 		return -ENOMEM;
804 	hq_put_index = hq->host_index;
805 	dq_put_index = dq->host_index;
806 	temp_hrqe = lpfc_sli4_qe(hq, hq_put_index);
807 	temp_drqe = lpfc_sli4_qe(dq, dq_put_index);
808 
809 	if (hq->type != LPFC_HRQ || dq->type != LPFC_DRQ)
810 		return -EINVAL;
811 	if (hq_put_index != dq_put_index)
812 		return -EINVAL;
813 	/* If the host has not yet processed the next entry then we are done */
814 	if (((hq_put_index + 1) % hq->entry_count) == hq->hba_index)
815 		return -EBUSY;
816 	lpfc_sli4_pcimem_bcopy(hrqe, temp_hrqe, hq->entry_size);
817 	lpfc_sli4_pcimem_bcopy(drqe, temp_drqe, dq->entry_size);
818 
819 	/* Update the host index to point to the next slot */
820 	hq->host_index = ((hq_put_index + 1) % hq->entry_count);
821 	dq->host_index = ((dq_put_index + 1) % dq->entry_count);
822 	hq->RQ_buf_posted++;
823 
824 	/* Ring The Header Receive Queue Doorbell */
825 	if (!(hq->host_index % hq->notify_interval)) {
826 		doorbell.word0 = 0;
827 		if (hq->db_format == LPFC_DB_RING_FORMAT) {
828 			bf_set(lpfc_rq_db_ring_fm_num_posted, &doorbell,
829 			       hq->notify_interval);
830 			bf_set(lpfc_rq_db_ring_fm_id, &doorbell, hq->queue_id);
831 		} else if (hq->db_format == LPFC_DB_LIST_FORMAT) {
832 			bf_set(lpfc_rq_db_list_fm_num_posted, &doorbell,
833 			       hq->notify_interval);
834 			bf_set(lpfc_rq_db_list_fm_index, &doorbell,
835 			       hq->host_index);
836 			bf_set(lpfc_rq_db_list_fm_id, &doorbell, hq->queue_id);
837 		} else {
838 			return -EINVAL;
839 		}
840 		writel(doorbell.word0, hq->db_regaddr);
841 	}
842 	return hq_put_index;
843 }
844 
845 /*
846  * lpfc_sli4_rq_release - Updates internal hba index for RQ
847  *
848  * This routine will update the HBA index of a queue to reflect consumption of
849  * one Receive Queue Entry by the HBA. When the HBA indicates that it has
850  * consumed an entry the host calls this function to update the queue's
851  * internal pointers. This routine returns the number of entries that were
852  * consumed by the HBA.
853  **/
854 static uint32_t
855 lpfc_sli4_rq_release(struct lpfc_queue *hq, struct lpfc_queue *dq)
856 {
857 	/* sanity check on queue memory */
858 	if (unlikely(!hq) || unlikely(!dq))
859 		return 0;
860 
861 	if ((hq->type != LPFC_HRQ) || (dq->type != LPFC_DRQ))
862 		return 0;
863 	hq->hba_index = ((hq->hba_index + 1) % hq->entry_count);
864 	dq->hba_index = ((dq->hba_index + 1) % dq->entry_count);
865 	return 1;
866 }
867 
868 /**
869  * lpfc_cmd_iocb - Get next command iocb entry in the ring
870  * @phba: Pointer to HBA context object.
871  * @pring: Pointer to driver SLI ring object.
872  *
873  * This function returns pointer to next command iocb entry
874  * in the command ring. The caller must hold hbalock to prevent
875  * other threads consume the next command iocb.
876  * SLI-2/SLI-3 provide different sized iocbs.
877  **/
878 static inline IOCB_t *
879 lpfc_cmd_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
880 {
881 	return (IOCB_t *) (((char *) pring->sli.sli3.cmdringaddr) +
882 			   pring->sli.sli3.cmdidx * phba->iocb_cmd_size);
883 }
884 
885 /**
886  * lpfc_resp_iocb - Get next response iocb entry in the ring
887  * @phba: Pointer to HBA context object.
888  * @pring: Pointer to driver SLI ring object.
889  *
890  * This function returns pointer to next response iocb entry
891  * in the response ring. The caller must hold hbalock to make sure
892  * that no other thread consume the next response iocb.
893  * SLI-2/SLI-3 provide different sized iocbs.
894  **/
895 static inline IOCB_t *
896 lpfc_resp_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
897 {
898 	return (IOCB_t *) (((char *) pring->sli.sli3.rspringaddr) +
899 			   pring->sli.sli3.rspidx * phba->iocb_rsp_size);
900 }
901 
902 /**
903  * __lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
904  * @phba: Pointer to HBA context object.
905  *
906  * This function is called with hbalock held. This function
907  * allocates a new driver iocb object from the iocb pool. If the
908  * allocation is successful, it returns pointer to the newly
909  * allocated iocb object else it returns NULL.
910  **/
911 struct lpfc_iocbq *
912 __lpfc_sli_get_iocbq(struct lpfc_hba *phba)
913 {
914 	struct list_head *lpfc_iocb_list = &phba->lpfc_iocb_list;
915 	struct lpfc_iocbq * iocbq = NULL;
916 
917 	lockdep_assert_held(&phba->hbalock);
918 
919 	list_remove_head(lpfc_iocb_list, iocbq, struct lpfc_iocbq, list);
920 	if (iocbq)
921 		phba->iocb_cnt++;
922 	if (phba->iocb_cnt > phba->iocb_max)
923 		phba->iocb_max = phba->iocb_cnt;
924 	return iocbq;
925 }
926 
927 /**
928  * __lpfc_clear_active_sglq - Remove the active sglq for this XRI.
929  * @phba: Pointer to HBA context object.
930  * @xritag: XRI value.
931  *
932  * This function clears the sglq pointer from the array of active
933  * sglq's. The xritag that is passed in is used to index into the
934  * array. Before the xritag can be used it needs to be adjusted
935  * by subtracting the xribase.
936  *
937  * Returns sglq ponter = success, NULL = Failure.
938  **/
939 struct lpfc_sglq *
940 __lpfc_clear_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
941 {
942 	struct lpfc_sglq *sglq;
943 
944 	sglq = phba->sli4_hba.lpfc_sglq_active_list[xritag];
945 	phba->sli4_hba.lpfc_sglq_active_list[xritag] = NULL;
946 	return sglq;
947 }
948 
949 /**
950  * __lpfc_get_active_sglq - Get the active sglq for this XRI.
951  * @phba: Pointer to HBA context object.
952  * @xritag: XRI value.
953  *
954  * This function returns the sglq pointer from the array of active
955  * sglq's. The xritag that is passed in is used to index into the
956  * array. Before the xritag can be used it needs to be adjusted
957  * by subtracting the xribase.
958  *
959  * Returns sglq ponter = success, NULL = Failure.
960  **/
961 struct lpfc_sglq *
962 __lpfc_get_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
963 {
964 	struct lpfc_sglq *sglq;
965 
966 	sglq =  phba->sli4_hba.lpfc_sglq_active_list[xritag];
967 	return sglq;
968 }
969 
970 /**
971  * lpfc_clr_rrq_active - Clears RRQ active bit in xri_bitmap.
972  * @phba: Pointer to HBA context object.
973  * @xritag: xri used in this exchange.
974  * @rrq: The RRQ to be cleared.
975  *
976  **/
977 void
978 lpfc_clr_rrq_active(struct lpfc_hba *phba,
979 		    uint16_t xritag,
980 		    struct lpfc_node_rrq *rrq)
981 {
982 	struct lpfc_nodelist *ndlp = NULL;
983 
984 	/* Lookup did to verify if did is still active on this vport */
985 	if (rrq->vport)
986 		ndlp = lpfc_findnode_did(rrq->vport, rrq->nlp_DID);
987 
988 	if (!ndlp)
989 		goto out;
990 
991 	if (test_and_clear_bit(xritag, ndlp->active_rrqs_xri_bitmap)) {
992 		rrq->send_rrq = 0;
993 		rrq->xritag = 0;
994 		rrq->rrq_stop_time = 0;
995 	}
996 out:
997 	mempool_free(rrq, phba->rrq_pool);
998 }
999 
1000 /**
1001  * lpfc_handle_rrq_active - Checks if RRQ has waithed RATOV.
1002  * @phba: Pointer to HBA context object.
1003  *
1004  * This function is called with hbalock held. This function
1005  * Checks if stop_time (ratov from setting rrq active) has
1006  * been reached, if it has and the send_rrq flag is set then
1007  * it will call lpfc_send_rrq. If the send_rrq flag is not set
1008  * then it will just call the routine to clear the rrq and
1009  * free the rrq resource.
1010  * The timer is set to the next rrq that is going to expire before
1011  * leaving the routine.
1012  *
1013  **/
1014 void
1015 lpfc_handle_rrq_active(struct lpfc_hba *phba)
1016 {
1017 	struct lpfc_node_rrq *rrq;
1018 	struct lpfc_node_rrq *nextrrq;
1019 	unsigned long next_time;
1020 	unsigned long iflags;
1021 	LIST_HEAD(send_rrq);
1022 
1023 	clear_bit(HBA_RRQ_ACTIVE, &phba->hba_flag);
1024 	next_time = jiffies + secs_to_jiffies(phba->fc_ratov + 1);
1025 	spin_lock_irqsave(&phba->rrq_list_lock, iflags);
1026 	list_for_each_entry_safe(rrq, nextrrq,
1027 				 &phba->active_rrq_list, list) {
1028 		if (time_after(jiffies, rrq->rrq_stop_time))
1029 			list_move(&rrq->list, &send_rrq);
1030 		else if (time_before(rrq->rrq_stop_time, next_time))
1031 			next_time = rrq->rrq_stop_time;
1032 	}
1033 	spin_unlock_irqrestore(&phba->rrq_list_lock, iflags);
1034 	if ((!list_empty(&phba->active_rrq_list)) &&
1035 	    (!test_bit(FC_UNLOADING, &phba->pport->load_flag)))
1036 		mod_timer(&phba->rrq_tmr, next_time);
1037 	list_for_each_entry_safe(rrq, nextrrq, &send_rrq, list) {
1038 		list_del(&rrq->list);
1039 		if (!rrq->send_rrq) {
1040 			/* this call will free the rrq */
1041 			lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
1042 		} else if (lpfc_send_rrq(phba, rrq)) {
1043 			/* if we send the rrq then the completion handler
1044 			*  will clear the bit in the xribitmap.
1045 			*/
1046 			lpfc_clr_rrq_active(phba, rrq->xritag,
1047 					    rrq);
1048 		}
1049 	}
1050 }
1051 
1052 /**
1053  * lpfc_get_active_rrq - Get the active RRQ for this exchange.
1054  * @vport: Pointer to vport context object.
1055  * @xri: The xri used in the exchange.
1056  * @did: The targets DID for this exchange.
1057  *
1058  * returns NULL = rrq not found in the phba->active_rrq_list.
1059  *         rrq = rrq for this xri and target.
1060  **/
1061 struct lpfc_node_rrq *
1062 lpfc_get_active_rrq(struct lpfc_vport *vport, uint16_t xri, uint32_t did)
1063 {
1064 	struct lpfc_hba *phba = vport->phba;
1065 	struct lpfc_node_rrq *rrq;
1066 	struct lpfc_node_rrq *nextrrq;
1067 	unsigned long iflags;
1068 
1069 	if (phba->sli_rev != LPFC_SLI_REV4)
1070 		return NULL;
1071 	spin_lock_irqsave(&phba->rrq_list_lock, iflags);
1072 	list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list) {
1073 		if (rrq->vport == vport && rrq->xritag == xri &&
1074 				rrq->nlp_DID == did){
1075 			list_del(&rrq->list);
1076 			spin_unlock_irqrestore(&phba->rrq_list_lock, iflags);
1077 			return rrq;
1078 		}
1079 	}
1080 	spin_unlock_irqrestore(&phba->rrq_list_lock, iflags);
1081 	return NULL;
1082 }
1083 
1084 /**
1085  * lpfc_cleanup_vports_rrqs - Remove and clear the active RRQ for this vport.
1086  * @vport: Pointer to vport context object.
1087  * @ndlp: Pointer to the lpfc_node_list structure.
1088  * If ndlp is NULL Remove all active RRQs for this vport from the
1089  * phba->active_rrq_list and clear the rrq.
1090  * If ndlp is not NULL then only remove rrqs for this vport & this ndlp.
1091  **/
1092 void
1093 lpfc_cleanup_vports_rrqs(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
1094 
1095 {
1096 	struct lpfc_hba *phba = vport->phba;
1097 	struct lpfc_node_rrq *rrq;
1098 	struct lpfc_node_rrq *nextrrq;
1099 	unsigned long iflags;
1100 	LIST_HEAD(rrq_list);
1101 
1102 	if (phba->sli_rev != LPFC_SLI_REV4)
1103 		return;
1104 	if (!ndlp) {
1105 		lpfc_sli4_vport_delete_els_xri_aborted(vport);
1106 		lpfc_sli4_vport_delete_fcp_xri_aborted(vport);
1107 	}
1108 	spin_lock_irqsave(&phba->rrq_list_lock, iflags);
1109 	list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list) {
1110 		if (rrq->vport != vport)
1111 			continue;
1112 
1113 		if (!ndlp || ndlp == lpfc_findnode_did(vport, rrq->nlp_DID))
1114 			list_move(&rrq->list, &rrq_list);
1115 
1116 	}
1117 	spin_unlock_irqrestore(&phba->rrq_list_lock, iflags);
1118 
1119 	list_for_each_entry_safe(rrq, nextrrq, &rrq_list, list) {
1120 		list_del(&rrq->list);
1121 		lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
1122 	}
1123 }
1124 
1125 /**
1126  * lpfc_test_rrq_active - Test RRQ bit in xri_bitmap.
1127  * @phba: Pointer to HBA context object.
1128  * @ndlp: Targets nodelist pointer for this exchange.
1129  * @xritag: the xri in the bitmap to test.
1130  *
1131  * This function returns:
1132  * 0 = rrq not active for this xri
1133  * 1 = rrq is valid for this xri.
1134  **/
1135 int
1136 lpfc_test_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
1137 			uint16_t  xritag)
1138 {
1139 	if (!ndlp)
1140 		return 0;
1141 	if (!ndlp->active_rrqs_xri_bitmap)
1142 		return 0;
1143 	if (test_bit(xritag, ndlp->active_rrqs_xri_bitmap))
1144 		return 1;
1145 	else
1146 		return 0;
1147 }
1148 
1149 /**
1150  * lpfc_set_rrq_active - set RRQ active bit in xri_bitmap.
1151  * @phba: Pointer to HBA context object.
1152  * @ndlp: nodelist pointer for this target.
1153  * @xritag: xri used in this exchange.
1154  * @rxid: Remote Exchange ID.
1155  * @send_rrq: Flag used to determine if we should send rrq els cmd.
1156  *
1157  * This function takes the hbalock.
1158  * The active bit is always set in the active rrq xri_bitmap even
1159  * if there is no slot available for the other rrq information.
1160  *
1161  * returns 0 rrq activated for this xri
1162  *         < 0 No memory or invalid ndlp.
1163  **/
1164 int
1165 lpfc_set_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
1166 		    uint16_t xritag, uint16_t rxid, uint16_t send_rrq)
1167 {
1168 	unsigned long iflags;
1169 	struct lpfc_node_rrq *rrq;
1170 	int empty;
1171 
1172 	if (!ndlp)
1173 		return -EINVAL;
1174 
1175 	if (!phba->cfg_enable_rrq)
1176 		return -EINVAL;
1177 
1178 	if (test_bit(FC_UNLOADING, &phba->pport->load_flag)) {
1179 		clear_bit(HBA_RRQ_ACTIVE, &phba->hba_flag);
1180 		goto outnl;
1181 	}
1182 
1183 	spin_lock_irqsave(&phba->hbalock, iflags);
1184 	if (ndlp->vport && test_bit(FC_UNLOADING, &ndlp->vport->load_flag))
1185 		goto out;
1186 
1187 	if (!ndlp->active_rrqs_xri_bitmap)
1188 		goto out;
1189 
1190 	if (test_and_set_bit(xritag, ndlp->active_rrqs_xri_bitmap))
1191 		goto out;
1192 
1193 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1194 	rrq = mempool_alloc(phba->rrq_pool, GFP_ATOMIC);
1195 	if (!rrq) {
1196 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
1197 				"3155 Unable to allocate RRQ xri:0x%x rxid:0x%x"
1198 				" DID:0x%x Send:%d\n",
1199 				xritag, rxid, ndlp->nlp_DID, send_rrq);
1200 		return -EINVAL;
1201 	}
1202 	if (phba->cfg_enable_rrq == 1)
1203 		rrq->send_rrq = send_rrq;
1204 	else
1205 		rrq->send_rrq = 0;
1206 	rrq->xritag = xritag;
1207 	rrq->rrq_stop_time = jiffies + secs_to_jiffies(phba->fc_ratov + 1);
1208 	rrq->nlp_DID = ndlp->nlp_DID;
1209 	rrq->vport = ndlp->vport;
1210 	rrq->rxid = rxid;
1211 
1212 	spin_lock_irqsave(&phba->rrq_list_lock, iflags);
1213 	empty = list_empty(&phba->active_rrq_list);
1214 	list_add_tail(&rrq->list, &phba->active_rrq_list);
1215 	spin_unlock_irqrestore(&phba->rrq_list_lock, iflags);
1216 	set_bit(HBA_RRQ_ACTIVE, &phba->hba_flag);
1217 	if (empty)
1218 		lpfc_worker_wake_up(phba);
1219 	return 0;
1220 out:
1221 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1222 outnl:
1223 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
1224 			"2921 Can't set rrq active xri:0x%x rxid:0x%x"
1225 			" DID:0x%x Send:%d\n",
1226 			xritag, rxid, ndlp->nlp_DID, send_rrq);
1227 	return -EINVAL;
1228 }
1229 
1230 /**
1231  * __lpfc_sli_get_els_sglq - Allocates an iocb object from sgl pool
1232  * @phba: Pointer to HBA context object.
1233  * @piocbq: Pointer to the iocbq.
1234  *
1235  * The driver calls this function with either the nvme ls ring lock
1236  * or the fc els ring lock held depending on the iocb usage.  This function
1237  * gets a new driver sglq object from the sglq list. If the list is not empty
1238  * then it is successful, it returns pointer to the newly allocated sglq
1239  * object else it returns NULL.
1240  **/
1241 static struct lpfc_sglq *
1242 __lpfc_sli_get_els_sglq(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq)
1243 {
1244 	struct list_head *lpfc_els_sgl_list = &phba->sli4_hba.lpfc_els_sgl_list;
1245 	struct lpfc_sglq *sglq = NULL;
1246 	struct lpfc_sglq *start_sglq = NULL;
1247 	struct lpfc_io_buf *lpfc_cmd;
1248 	struct lpfc_nodelist *ndlp;
1249 	int found = 0;
1250 	u8 cmnd;
1251 
1252 	cmnd = get_job_cmnd(phba, piocbq);
1253 
1254 	if (piocbq->cmd_flag & LPFC_IO_FCP) {
1255 		lpfc_cmd = piocbq->io_buf;
1256 		ndlp = lpfc_cmd->rdata->pnode;
1257 	} else  if ((cmnd == CMD_GEN_REQUEST64_CR) &&
1258 			!(piocbq->cmd_flag & LPFC_IO_LIBDFC)) {
1259 		ndlp = piocbq->ndlp;
1260 	} else  if (piocbq->cmd_flag & LPFC_IO_LIBDFC) {
1261 		if (piocbq->cmd_flag & LPFC_IO_LOOPBACK)
1262 			ndlp = NULL;
1263 		else
1264 			ndlp = piocbq->ndlp;
1265 	} else {
1266 		ndlp = piocbq->ndlp;
1267 	}
1268 
1269 	spin_lock(&phba->sli4_hba.sgl_list_lock);
1270 	list_remove_head(lpfc_els_sgl_list, sglq, struct lpfc_sglq, list);
1271 	start_sglq = sglq;
1272 	while (!found) {
1273 		if (!sglq)
1274 			break;
1275 		if (ndlp && ndlp->active_rrqs_xri_bitmap &&
1276 		    test_bit(sglq->sli4_lxritag,
1277 		    ndlp->active_rrqs_xri_bitmap)) {
1278 			/* This xri has an rrq outstanding for this DID.
1279 			 * put it back in the list and get another xri.
1280 			 */
1281 			list_add_tail(&sglq->list, lpfc_els_sgl_list);
1282 			sglq = NULL;
1283 			list_remove_head(lpfc_els_sgl_list, sglq,
1284 						struct lpfc_sglq, list);
1285 			if (sglq == start_sglq) {
1286 				list_add_tail(&sglq->list, lpfc_els_sgl_list);
1287 				sglq = NULL;
1288 				break;
1289 			} else
1290 				continue;
1291 		}
1292 		sglq->ndlp = ndlp;
1293 		found = 1;
1294 		phba->sli4_hba.lpfc_sglq_active_list[sglq->sli4_lxritag] = sglq;
1295 		sglq->state = SGL_ALLOCATED;
1296 	}
1297 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
1298 	return sglq;
1299 }
1300 
1301 /**
1302  * __lpfc_sli_get_nvmet_sglq - Allocates an iocb object from sgl pool
1303  * @phba: Pointer to HBA context object.
1304  * @piocbq: Pointer to the iocbq.
1305  *
1306  * This function is called with the sgl_list lock held. This function
1307  * gets a new driver sglq object from the sglq list. If the
1308  * list is not empty then it is successful, it returns pointer to the newly
1309  * allocated sglq object else it returns NULL.
1310  **/
1311 struct lpfc_sglq *
1312 __lpfc_sli_get_nvmet_sglq(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq)
1313 {
1314 	struct list_head *lpfc_nvmet_sgl_list;
1315 	struct lpfc_sglq *sglq = NULL;
1316 
1317 	lpfc_nvmet_sgl_list = &phba->sli4_hba.lpfc_nvmet_sgl_list;
1318 
1319 	lockdep_assert_held(&phba->sli4_hba.sgl_list_lock);
1320 
1321 	list_remove_head(lpfc_nvmet_sgl_list, sglq, struct lpfc_sglq, list);
1322 	if (!sglq)
1323 		return NULL;
1324 	phba->sli4_hba.lpfc_sglq_active_list[sglq->sli4_lxritag] = sglq;
1325 	sglq->state = SGL_ALLOCATED;
1326 	return sglq;
1327 }
1328 
1329 /**
1330  * lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
1331  * @phba: Pointer to HBA context object.
1332  *
1333  * This function is called with no lock held. This function
1334  * allocates a new driver iocb object from the iocb pool. If the
1335  * allocation is successful, it returns pointer to the newly
1336  * allocated iocb object else it returns NULL.
1337  **/
1338 struct lpfc_iocbq *
1339 lpfc_sli_get_iocbq(struct lpfc_hba *phba)
1340 {
1341 	struct lpfc_iocbq * iocbq = NULL;
1342 	unsigned long iflags;
1343 
1344 	spin_lock_irqsave(&phba->hbalock, iflags);
1345 	iocbq = __lpfc_sli_get_iocbq(phba);
1346 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1347 	return iocbq;
1348 }
1349 
1350 /**
1351  * __lpfc_sli_release_iocbq_s4 - Release iocb to the iocb pool
1352  * @phba: Pointer to HBA context object.
1353  * @iocbq: Pointer to driver iocb object.
1354  *
1355  * This function is called to release the driver iocb object
1356  * to the iocb pool. The iotag in the iocb object
1357  * does not change for each use of the iocb object. This function
1358  * clears all other fields of the iocb object when it is freed.
1359  * The sqlq structure that holds the xritag and phys and virtual
1360  * mappings for the scatter gather list is retrieved from the
1361  * active array of sglq. The get of the sglq pointer also clears
1362  * the entry in the array. If the status of the IO indiactes that
1363  * this IO was aborted then the sglq entry it put on the
1364  * lpfc_abts_els_sgl_list until the CQ_ABORTED_XRI is received. If the
1365  * IO has good status or fails for any other reason then the sglq
1366  * entry is added to the free list (lpfc_els_sgl_list). The hbalock is
1367  *  asserted held in the code path calling this routine.
1368  **/
1369 static void
1370 __lpfc_sli_release_iocbq_s4(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1371 {
1372 	struct lpfc_sglq *sglq;
1373 	unsigned long iflag = 0;
1374 	struct lpfc_sli_ring *pring;
1375 
1376 	if (iocbq->sli4_xritag == NO_XRI)
1377 		sglq = NULL;
1378 	else
1379 		sglq = __lpfc_clear_active_sglq(phba, iocbq->sli4_lxritag);
1380 
1381 
1382 	if (sglq)  {
1383 		if (iocbq->cmd_flag & LPFC_IO_NVMET) {
1384 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1385 					  iflag);
1386 			sglq->state = SGL_FREED;
1387 			sglq->ndlp = NULL;
1388 			list_add_tail(&sglq->list,
1389 				      &phba->sli4_hba.lpfc_nvmet_sgl_list);
1390 			spin_unlock_irqrestore(
1391 				&phba->sli4_hba.sgl_list_lock, iflag);
1392 			goto out;
1393 		}
1394 
1395 		if ((iocbq->cmd_flag & LPFC_EXCHANGE_BUSY) &&
1396 		    (!(unlikely(pci_channel_offline(phba->pcidev)))) &&
1397 		    sglq->state != SGL_XRI_ABORTED) {
1398 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1399 					  iflag);
1400 
1401 			/* Check if we can get a reference on ndlp */
1402 			if (sglq->ndlp && !lpfc_nlp_get(sglq->ndlp))
1403 				sglq->ndlp = NULL;
1404 
1405 			list_add(&sglq->list,
1406 				 &phba->sli4_hba.lpfc_abts_els_sgl_list);
1407 			spin_unlock_irqrestore(
1408 				&phba->sli4_hba.sgl_list_lock, iflag);
1409 		} else {
1410 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1411 					  iflag);
1412 			sglq->state = SGL_FREED;
1413 			sglq->ndlp = NULL;
1414 			list_add_tail(&sglq->list,
1415 				      &phba->sli4_hba.lpfc_els_sgl_list);
1416 			spin_unlock_irqrestore(
1417 				&phba->sli4_hba.sgl_list_lock, iflag);
1418 			pring = lpfc_phba_elsring(phba);
1419 			/* Check if TXQ queue needs to be serviced */
1420 			if (pring && (!list_empty(&pring->txq)))
1421 				lpfc_worker_wake_up(phba);
1422 		}
1423 	}
1424 
1425 out:
1426 	/*
1427 	 * Clean all volatile data fields, preserve iotag and node struct.
1428 	 */
1429 	memset_startat(iocbq, 0, wqe);
1430 	iocbq->sli4_lxritag = NO_XRI;
1431 	iocbq->sli4_xritag = NO_XRI;
1432 	iocbq->cmd_flag &= ~(LPFC_IO_NVME | LPFC_IO_NVMET | LPFC_IO_CMF |
1433 			      LPFC_IO_NVME_LS);
1434 	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1435 }
1436 
1437 
1438 /**
1439  * __lpfc_sli_release_iocbq_s3 - Release iocb to the iocb pool
1440  * @phba: Pointer to HBA context object.
1441  * @iocbq: Pointer to driver iocb object.
1442  *
1443  * This function is called to release the driver iocb object to the
1444  * iocb pool. The iotag in the iocb object does not change for each
1445  * use of the iocb object. This function clears all other fields of
1446  * the iocb object when it is freed. The hbalock is asserted held in
1447  * the code path calling this routine.
1448  **/
1449 static void
1450 __lpfc_sli_release_iocbq_s3(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1451 {
1452 
1453 	/*
1454 	 * Clean all volatile data fields, preserve iotag and node struct.
1455 	 */
1456 	memset_startat(iocbq, 0, iocb);
1457 	iocbq->sli4_xritag = NO_XRI;
1458 	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1459 }
1460 
1461 /**
1462  * __lpfc_sli_release_iocbq - Release iocb to the iocb pool
1463  * @phba: Pointer to HBA context object.
1464  * @iocbq: Pointer to driver iocb object.
1465  *
1466  * This function is called with hbalock held to release driver
1467  * iocb object to the iocb pool. The iotag in the iocb object
1468  * does not change for each use of the iocb object. This function
1469  * clears all other fields of the iocb object when it is freed.
1470  **/
1471 static void
1472 __lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1473 {
1474 	lockdep_assert_held(&phba->hbalock);
1475 
1476 	phba->__lpfc_sli_release_iocbq(phba, iocbq);
1477 	phba->iocb_cnt--;
1478 }
1479 
1480 /**
1481  * lpfc_sli_release_iocbq - Release iocb to the iocb pool
1482  * @phba: Pointer to HBA context object.
1483  * @iocbq: Pointer to driver iocb object.
1484  *
1485  * This function is called with no lock held to release the iocb to
1486  * iocb pool.
1487  **/
1488 void
1489 lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1490 {
1491 	unsigned long iflags;
1492 
1493 	/*
1494 	 * Clean all volatile data fields, preserve iotag and node struct.
1495 	 */
1496 	spin_lock_irqsave(&phba->hbalock, iflags);
1497 	__lpfc_sli_release_iocbq(phba, iocbq);
1498 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1499 }
1500 
1501 /**
1502  * lpfc_sli_cancel_iocbs - Cancel all iocbs from a list.
1503  * @phba: Pointer to HBA context object.
1504  * @iocblist: List of IOCBs.
1505  * @ulpstatus: ULP status in IOCB command field.
1506  * @ulpWord4: ULP word-4 in IOCB command field.
1507  *
1508  * This function is called with a list of IOCBs to cancel. It cancels the IOCB
1509  * on the list by invoking the complete callback function associated with the
1510  * IOCB with the provided @ulpstatus and @ulpword4 set to the IOCB commond
1511  * fields.
1512  **/
1513 void
1514 lpfc_sli_cancel_iocbs(struct lpfc_hba *phba, struct list_head *iocblist,
1515 		      uint32_t ulpstatus, uint32_t ulpWord4)
1516 {
1517 	struct lpfc_iocbq *piocb;
1518 
1519 	while (!list_empty(iocblist)) {
1520 		list_remove_head(iocblist, piocb, struct lpfc_iocbq, list);
1521 		if (piocb->cmd_cmpl) {
1522 			if (piocb->cmd_flag & LPFC_IO_NVME) {
1523 				lpfc_nvme_cancel_iocb(phba, piocb,
1524 						      ulpstatus, ulpWord4);
1525 			} else {
1526 				if (phba->sli_rev == LPFC_SLI_REV4) {
1527 					bf_set(lpfc_wcqe_c_status,
1528 					       &piocb->wcqe_cmpl, ulpstatus);
1529 					piocb->wcqe_cmpl.parameter = ulpWord4;
1530 				} else {
1531 					piocb->iocb.ulpStatus = ulpstatus;
1532 					piocb->iocb.un.ulpWord[4] = ulpWord4;
1533 				}
1534 				(piocb->cmd_cmpl) (phba, piocb, piocb);
1535 			}
1536 		} else {
1537 			lpfc_sli_release_iocbq(phba, piocb);
1538 		}
1539 	}
1540 	return;
1541 }
1542 
1543 /**
1544  * lpfc_sli_iocb_cmd_type - Get the iocb type
1545  * @iocb_cmnd: iocb command code.
1546  *
1547  * This function is called by ring event handler function to get the iocb type.
1548  * This function translates the iocb command to an iocb command type used to
1549  * decide the final disposition of each completed IOCB.
1550  * The function returns
1551  * LPFC_UNKNOWN_IOCB if it is an unsupported iocb
1552  * LPFC_SOL_IOCB     if it is a solicited iocb completion
1553  * LPFC_ABORT_IOCB   if it is an abort iocb
1554  * LPFC_UNSOL_IOCB   if it is an unsolicited iocb
1555  *
1556  * The caller is not required to hold any lock.
1557  **/
1558 static lpfc_iocb_type
1559 lpfc_sli_iocb_cmd_type(uint8_t iocb_cmnd)
1560 {
1561 	lpfc_iocb_type type = LPFC_UNKNOWN_IOCB;
1562 
1563 	if (iocb_cmnd > CMD_MAX_IOCB_CMD)
1564 		return 0;
1565 
1566 	switch (iocb_cmnd) {
1567 	case CMD_XMIT_SEQUENCE_CR:
1568 	case CMD_XMIT_SEQUENCE_CX:
1569 	case CMD_XMIT_BCAST_CN:
1570 	case CMD_XMIT_BCAST_CX:
1571 	case CMD_ELS_REQUEST_CR:
1572 	case CMD_ELS_REQUEST_CX:
1573 	case CMD_CREATE_XRI_CR:
1574 	case CMD_CREATE_XRI_CX:
1575 	case CMD_GET_RPI_CN:
1576 	case CMD_XMIT_ELS_RSP_CX:
1577 	case CMD_GET_RPI_CR:
1578 	case CMD_FCP_IWRITE_CR:
1579 	case CMD_FCP_IWRITE_CX:
1580 	case CMD_FCP_IREAD_CR:
1581 	case CMD_FCP_IREAD_CX:
1582 	case CMD_FCP_ICMND_CR:
1583 	case CMD_FCP_ICMND_CX:
1584 	case CMD_FCP_TSEND_CX:
1585 	case CMD_FCP_TRSP_CX:
1586 	case CMD_FCP_TRECEIVE_CX:
1587 	case CMD_FCP_AUTO_TRSP_CX:
1588 	case CMD_ADAPTER_MSG:
1589 	case CMD_ADAPTER_DUMP:
1590 	case CMD_XMIT_SEQUENCE64_CR:
1591 	case CMD_XMIT_SEQUENCE64_CX:
1592 	case CMD_XMIT_BCAST64_CN:
1593 	case CMD_XMIT_BCAST64_CX:
1594 	case CMD_ELS_REQUEST64_CR:
1595 	case CMD_ELS_REQUEST64_CX:
1596 	case CMD_FCP_IWRITE64_CR:
1597 	case CMD_FCP_IWRITE64_CX:
1598 	case CMD_FCP_IREAD64_CR:
1599 	case CMD_FCP_IREAD64_CX:
1600 	case CMD_FCP_ICMND64_CR:
1601 	case CMD_FCP_ICMND64_CX:
1602 	case CMD_FCP_TSEND64_CX:
1603 	case CMD_FCP_TRSP64_CX:
1604 	case CMD_FCP_TRECEIVE64_CX:
1605 	case CMD_GEN_REQUEST64_CR:
1606 	case CMD_GEN_REQUEST64_CX:
1607 	case CMD_XMIT_ELS_RSP64_CX:
1608 	case DSSCMD_IWRITE64_CR:
1609 	case DSSCMD_IWRITE64_CX:
1610 	case DSSCMD_IREAD64_CR:
1611 	case DSSCMD_IREAD64_CX:
1612 	case CMD_SEND_FRAME:
1613 		type = LPFC_SOL_IOCB;
1614 		break;
1615 	case CMD_ABORT_XRI_CN:
1616 	case CMD_ABORT_XRI_CX:
1617 	case CMD_CLOSE_XRI_CN:
1618 	case CMD_CLOSE_XRI_CX:
1619 	case CMD_XRI_ABORTED_CX:
1620 	case CMD_ABORT_MXRI64_CN:
1621 	case CMD_XMIT_BLS_RSP64_CX:
1622 		type = LPFC_ABORT_IOCB;
1623 		break;
1624 	case CMD_RCV_SEQUENCE_CX:
1625 	case CMD_RCV_ELS_REQ_CX:
1626 	case CMD_RCV_SEQUENCE64_CX:
1627 	case CMD_RCV_ELS_REQ64_CX:
1628 	case CMD_ASYNC_STATUS:
1629 	case CMD_IOCB_RCV_SEQ64_CX:
1630 	case CMD_IOCB_RCV_ELS64_CX:
1631 	case CMD_IOCB_RCV_CONT64_CX:
1632 	case CMD_IOCB_RET_XRI64_CX:
1633 		type = LPFC_UNSOL_IOCB;
1634 		break;
1635 	case CMD_IOCB_XMIT_MSEQ64_CR:
1636 	case CMD_IOCB_XMIT_MSEQ64_CX:
1637 	case CMD_IOCB_RCV_SEQ_LIST64_CX:
1638 	case CMD_IOCB_RCV_ELS_LIST64_CX:
1639 	case CMD_IOCB_CLOSE_EXTENDED_CN:
1640 	case CMD_IOCB_ABORT_EXTENDED_CN:
1641 	case CMD_IOCB_RET_HBQE64_CN:
1642 	case CMD_IOCB_FCP_IBIDIR64_CR:
1643 	case CMD_IOCB_FCP_IBIDIR64_CX:
1644 	case CMD_IOCB_FCP_ITASKMGT64_CX:
1645 	case CMD_IOCB_LOGENTRY_CN:
1646 	case CMD_IOCB_LOGENTRY_ASYNC_CN:
1647 		printk("%s - Unhandled SLI-3 Command x%x\n",
1648 				__func__, iocb_cmnd);
1649 		type = LPFC_UNKNOWN_IOCB;
1650 		break;
1651 	default:
1652 		type = LPFC_UNKNOWN_IOCB;
1653 		break;
1654 	}
1655 
1656 	return type;
1657 }
1658 
1659 /**
1660  * lpfc_sli_ring_map - Issue config_ring mbox for all rings
1661  * @phba: Pointer to HBA context object.
1662  *
1663  * This function is called from SLI initialization code
1664  * to configure every ring of the HBA's SLI interface. The
1665  * caller is not required to hold any lock. This function issues
1666  * a config_ring mailbox command for each ring.
1667  * This function returns zero if successful else returns a negative
1668  * error code.
1669  **/
1670 static int
1671 lpfc_sli_ring_map(struct lpfc_hba *phba)
1672 {
1673 	struct lpfc_sli *psli = &phba->sli;
1674 	LPFC_MBOXQ_t *pmb;
1675 	MAILBOX_t *pmbox;
1676 	int i, rc, ret = 0;
1677 
1678 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
1679 	if (!pmb)
1680 		return -ENOMEM;
1681 	pmbox = &pmb->u.mb;
1682 	phba->link_state = LPFC_INIT_MBX_CMDS;
1683 	for (i = 0; i < psli->num_rings; i++) {
1684 		lpfc_config_ring(phba, i, pmb);
1685 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
1686 		if (rc != MBX_SUCCESS) {
1687 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1688 					"0446 Adapter failed to init (%d), "
1689 					"mbxCmd x%x CFG_RING, mbxStatus x%x, "
1690 					"ring %d\n",
1691 					rc, pmbox->mbxCommand,
1692 					pmbox->mbxStatus, i);
1693 			phba->link_state = LPFC_HBA_ERROR;
1694 			ret = -ENXIO;
1695 			break;
1696 		}
1697 	}
1698 	mempool_free(pmb, phba->mbox_mem_pool);
1699 	return ret;
1700 }
1701 
1702 /**
1703  * lpfc_sli_ringtxcmpl_put - Adds new iocb to the txcmplq
1704  * @phba: Pointer to HBA context object.
1705  * @pring: Pointer to driver SLI ring object.
1706  * @piocb: Pointer to the driver iocb object.
1707  *
1708  * The driver calls this function with the hbalock held for SLI3 ports or
1709  * the ring lock held for SLI4 ports. The function adds the
1710  * new iocb to txcmplq of the given ring. This function always returns
1711  * 0. If this function is called for ELS ring, this function checks if
1712  * there is a vport associated with the ELS command. This function also
1713  * starts els_tmofunc timer if this is an ELS command.
1714  **/
1715 static int
1716 lpfc_sli_ringtxcmpl_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
1717 			struct lpfc_iocbq *piocb)
1718 {
1719 	u32 ulp_command = 0;
1720 
1721 	BUG_ON(!piocb);
1722 	ulp_command = get_job_cmnd(phba, piocb);
1723 
1724 	list_add_tail(&piocb->list, &pring->txcmplq);
1725 	piocb->cmd_flag |= LPFC_IO_ON_TXCMPLQ;
1726 	pring->txcmplq_cnt++;
1727 	if ((unlikely(pring->ringno == LPFC_ELS_RING)) &&
1728 	   (ulp_command != CMD_ABORT_XRI_WQE) &&
1729 	   (ulp_command != CMD_ABORT_XRI_CN) &&
1730 	   (ulp_command != CMD_CLOSE_XRI_CN)) {
1731 		BUG_ON(!piocb->vport);
1732 		if (!test_bit(FC_UNLOADING, &piocb->vport->load_flag))
1733 			mod_timer(&piocb->vport->els_tmofunc,
1734 				  jiffies + secs_to_jiffies(phba->fc_ratov << 1));
1735 	}
1736 
1737 	return 0;
1738 }
1739 
1740 /**
1741  * lpfc_sli_ringtx_get - Get first element of the txq
1742  * @phba: Pointer to HBA context object.
1743  * @pring: Pointer to driver SLI ring object.
1744  *
1745  * This function is called with hbalock held to get next
1746  * iocb in txq of the given ring. If there is any iocb in
1747  * the txq, the function returns first iocb in the list after
1748  * removing the iocb from the list, else it returns NULL.
1749  **/
1750 struct lpfc_iocbq *
1751 lpfc_sli_ringtx_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1752 {
1753 	struct lpfc_iocbq *cmd_iocb;
1754 
1755 	lockdep_assert_held(&phba->hbalock);
1756 
1757 	list_remove_head((&pring->txq), cmd_iocb, struct lpfc_iocbq, list);
1758 	return cmd_iocb;
1759 }
1760 
1761 /**
1762  * lpfc_cmf_sync_cmpl - Process a CMF_SYNC_WQE cmpl
1763  * @phba: Pointer to HBA context object.
1764  * @cmdiocb: Pointer to driver command iocb object.
1765  * @rspiocb: Pointer to driver response iocb object.
1766  *
1767  * This routine will inform the driver of any BW adjustments we need
1768  * to make. These changes will be picked up during the next CMF
1769  * timer interrupt. In addition, any BW changes will be logged
1770  * with LOG_CGN_MGMT.
1771  **/
1772 static void
1773 lpfc_cmf_sync_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
1774 		   struct lpfc_iocbq *rspiocb)
1775 {
1776 	union lpfc_wqe128 *wqe;
1777 	uint32_t status, info;
1778 	struct lpfc_wcqe_complete *wcqe = &rspiocb->wcqe_cmpl;
1779 	uint64_t bw, bwdif, slop;
1780 	uint64_t pcent, bwpcent;
1781 	int asig, afpin, sigcnt, fpincnt;
1782 	int wsigmax, wfpinmax, cg, tdp;
1783 	char *s;
1784 
1785 	/* First check for error */
1786 	status = bf_get(lpfc_wcqe_c_status, wcqe);
1787 	if (status) {
1788 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1789 				"6211 CMF_SYNC_WQE Error "
1790 				"req_tag x%x status x%x hwstatus x%x "
1791 				"tdatap x%x parm x%x\n",
1792 				bf_get(lpfc_wcqe_c_request_tag, wcqe),
1793 				bf_get(lpfc_wcqe_c_status, wcqe),
1794 				bf_get(lpfc_wcqe_c_hw_status, wcqe),
1795 				wcqe->total_data_placed,
1796 				wcqe->parameter);
1797 		goto out;
1798 	}
1799 
1800 	/* Gather congestion information on a successful cmpl */
1801 	info = wcqe->parameter;
1802 	phba->cmf_active_info = info;
1803 
1804 	/* See if firmware info count is valid or has changed */
1805 	if (info > LPFC_MAX_CMF_INFO || phba->cmf_info_per_interval == info)
1806 		info = 0;
1807 	else
1808 		phba->cmf_info_per_interval = info;
1809 
1810 	tdp = bf_get(lpfc_wcqe_c_cmf_bw, wcqe);
1811 	cg = bf_get(lpfc_wcqe_c_cmf_cg, wcqe);
1812 
1813 	/* Get BW requirement from firmware */
1814 	bw = (uint64_t)tdp * LPFC_CMF_BLK_SIZE;
1815 	if (!bw) {
1816 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1817 				"6212 CMF_SYNC_WQE x%x: NULL bw\n",
1818 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
1819 		goto out;
1820 	}
1821 
1822 	/* Gather information needed for logging if a BW change is required */
1823 	wqe = &cmdiocb->wqe;
1824 	asig = bf_get(cmf_sync_asig, &wqe->cmf_sync);
1825 	afpin = bf_get(cmf_sync_afpin, &wqe->cmf_sync);
1826 	fpincnt = bf_get(cmf_sync_wfpincnt, &wqe->cmf_sync);
1827 	sigcnt = bf_get(cmf_sync_wsigcnt, &wqe->cmf_sync);
1828 	if (phba->cmf_max_bytes_per_interval != bw ||
1829 	    (asig || afpin || sigcnt || fpincnt)) {
1830 		/* Are we increasing or decreasing BW */
1831 		if (phba->cmf_max_bytes_per_interval <  bw) {
1832 			bwdif = bw - phba->cmf_max_bytes_per_interval;
1833 			s = "Increase";
1834 		} else {
1835 			bwdif = phba->cmf_max_bytes_per_interval - bw;
1836 			s = "Decrease";
1837 		}
1838 
1839 		/* What is the change percentage */
1840 		slop = div_u64(phba->cmf_link_byte_count, 200); /*For rounding*/
1841 		pcent = div64_u64(bwdif * 100 + slop,
1842 				  phba->cmf_link_byte_count);
1843 		bwpcent = div64_u64(bw * 100 + slop,
1844 				    phba->cmf_link_byte_count);
1845 		/* Because of bytes adjustment due to shorter timer in
1846 		 * lpfc_cmf_timer() the cmf_link_byte_count can be shorter and
1847 		 * may seem like BW is above 100%.
1848 		 */
1849 		if (bwpcent > 100)
1850 			bwpcent = 100;
1851 
1852 		if (phba->cmf_max_bytes_per_interval < bw &&
1853 		    bwpcent > 95)
1854 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1855 					"6208 Congestion bandwidth "
1856 					"limits removed\n");
1857 		else if ((phba->cmf_max_bytes_per_interval > bw) &&
1858 			 ((bwpcent + pcent) <= 100) && ((bwpcent + pcent) > 95))
1859 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1860 					"6209 Congestion bandwidth "
1861 					"limits in effect\n");
1862 
1863 		if (asig) {
1864 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1865 					"6237 BW Threshold %lld%% (%lld): "
1866 					"%lld%% %s: Signal Alarm: cg:%d "
1867 					"Info:%u\n",
1868 					bwpcent, bw, pcent, s, cg,
1869 					phba->cmf_active_info);
1870 		} else if (afpin) {
1871 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1872 					"6238 BW Threshold %lld%% (%lld): "
1873 					"%lld%% %s: FPIN Alarm: cg:%d "
1874 					"Info:%u\n",
1875 					bwpcent, bw, pcent, s, cg,
1876 					phba->cmf_active_info);
1877 		} else if (sigcnt) {
1878 			wsigmax = bf_get(cmf_sync_wsigmax, &wqe->cmf_sync);
1879 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1880 					"6239 BW Threshold %lld%% (%lld): "
1881 					"%lld%% %s: Signal Warning: "
1882 					"Cnt %d Max %d: cg:%d Info:%u\n",
1883 					bwpcent, bw, pcent, s, sigcnt,
1884 					wsigmax, cg, phba->cmf_active_info);
1885 		} else if (fpincnt) {
1886 			wfpinmax = bf_get(cmf_sync_wfpinmax, &wqe->cmf_sync);
1887 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1888 					"6240 BW Threshold %lld%% (%lld): "
1889 					"%lld%% %s: FPIN Warning: "
1890 					"Cnt %d Max %d: cg:%d Info:%u\n",
1891 					bwpcent, bw, pcent, s, fpincnt,
1892 					wfpinmax, cg, phba->cmf_active_info);
1893 		} else {
1894 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1895 					"6241 BW Threshold %lld%% (%lld): "
1896 					"CMF %lld%% %s: cg:%d Info:%u\n",
1897 					bwpcent, bw, pcent, s, cg,
1898 					phba->cmf_active_info);
1899 		}
1900 	} else if (info) {
1901 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1902 				"6246 Info Threshold %u\n", info);
1903 	}
1904 
1905 	/* Save BW change to be picked up during next timer interrupt */
1906 	phba->cmf_last_sync_bw = bw;
1907 out:
1908 	lpfc_sli_release_iocbq(phba, cmdiocb);
1909 }
1910 
1911 /**
1912  * lpfc_issue_cmf_sync_wqe - Issue a CMF_SYNC_WQE
1913  * @phba: Pointer to HBA context object.
1914  * @ms:   ms to set in WQE interval, 0 means use init op
1915  * @total: Total rcv bytes for this interval
1916  *
1917  * This routine is called every CMF timer interrupt. Its purpose is
1918  * to issue a CMF_SYNC_WQE to the firmware to inform it of any events
1919  * that may indicate we have congestion (FPINs or Signals). Upon
1920  * completion, the firmware will indicate any BW restrictions the
1921  * driver may need to take.
1922  **/
1923 int
1924 lpfc_issue_cmf_sync_wqe(struct lpfc_hba *phba, u32 ms, u64 total)
1925 {
1926 	union lpfc_wqe128 *wqe;
1927 	struct lpfc_iocbq *sync_buf;
1928 	unsigned long iflags;
1929 	u32 ret_val, cgn_sig_freq;
1930 	u32 atot, wtot, max;
1931 	u8 warn_sync_period = 0;
1932 
1933 	/* First address any alarm / warning activity */
1934 	atot = atomic_xchg(&phba->cgn_sync_alarm_cnt, 0);
1935 	wtot = atomic_xchg(&phba->cgn_sync_warn_cnt, 0);
1936 
1937 	spin_lock_irqsave(&phba->hbalock, iflags);
1938 
1939 	/* ONLY Managed mode will send the CMF_SYNC_WQE to the HBA */
1940 	if (phba->cmf_active_mode != LPFC_CFG_MANAGED ||
1941 	    phba->link_state < LPFC_LINK_UP) {
1942 		ret_val = 0;
1943 		goto out_unlock;
1944 	}
1945 
1946 	sync_buf = __lpfc_sli_get_iocbq(phba);
1947 	if (!sync_buf) {
1948 		lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT,
1949 				"6244 No available WQEs for CMF_SYNC_WQE\n");
1950 		ret_val = ENOMEM;
1951 		goto out_unlock;
1952 	}
1953 
1954 	wqe = &sync_buf->wqe;
1955 
1956 	/* WQEs are reused.  Clear stale data and set key fields to zero */
1957 	memset(wqe, 0, sizeof(*wqe));
1958 
1959 	/* If this is the very first CMF_SYNC_WQE, issue an init operation */
1960 	if (!ms) {
1961 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1962 				"6441 CMF Init %d - CMF_SYNC_WQE\n",
1963 				phba->fc_eventTag);
1964 		bf_set(cmf_sync_op, &wqe->cmf_sync, 1); /* 1=init */
1965 		bf_set(cmf_sync_interval, &wqe->cmf_sync, LPFC_CMF_INTERVAL);
1966 		goto initpath;
1967 	}
1968 
1969 	bf_set(cmf_sync_op, &wqe->cmf_sync, 0); /* 0=recalc */
1970 	bf_set(cmf_sync_interval, &wqe->cmf_sync, ms);
1971 
1972 	/* Check for alarms / warnings */
1973 	if (atot) {
1974 		if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
1975 			/* We hit an Signal alarm condition */
1976 			bf_set(cmf_sync_asig, &wqe->cmf_sync, 1);
1977 		} else {
1978 			/* We hit a FPIN alarm condition */
1979 			bf_set(cmf_sync_afpin, &wqe->cmf_sync, 1);
1980 		}
1981 	} else if (wtot) {
1982 		if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY ||
1983 		    phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
1984 			cgn_sig_freq = phba->cgn_sig_freq ? phba->cgn_sig_freq :
1985 					lpfc_fabric_cgn_frequency;
1986 			/* We hit an Signal warning condition */
1987 			max = LPFC_SEC_TO_MSEC / cgn_sig_freq *
1988 				lpfc_acqe_cgn_frequency;
1989 			bf_set(cmf_sync_wsigmax, &wqe->cmf_sync, max);
1990 			bf_set(cmf_sync_wsigcnt, &wqe->cmf_sync, wtot);
1991 			warn_sync_period = lpfc_acqe_cgn_frequency;
1992 		} else {
1993 			/* We hit a FPIN warning condition */
1994 			bf_set(cmf_sync_wfpinmax, &wqe->cmf_sync, 1);
1995 			bf_set(cmf_sync_wfpincnt, &wqe->cmf_sync, 1);
1996 			if (phba->cgn_fpin_frequency != LPFC_FPIN_INIT_FREQ)
1997 				warn_sync_period =
1998 				LPFC_MSECS_TO_SECS(phba->cgn_fpin_frequency);
1999 		}
2000 	}
2001 
2002 	/* Update total read blocks during previous timer interval */
2003 	wqe->cmf_sync.read_bytes = (u32)(total / LPFC_CMF_BLK_SIZE);
2004 
2005 initpath:
2006 	bf_set(cmf_sync_ver, &wqe->cmf_sync, LPFC_CMF_SYNC_VER);
2007 	wqe->cmf_sync.event_tag = phba->fc_eventTag;
2008 	bf_set(cmf_sync_cmnd, &wqe->cmf_sync, CMD_CMF_SYNC_WQE);
2009 
2010 	/* Setup reqtag to match the wqe completion. */
2011 	bf_set(cmf_sync_reqtag, &wqe->cmf_sync, sync_buf->iotag);
2012 
2013 	bf_set(cmf_sync_qosd, &wqe->cmf_sync, 1);
2014 	bf_set(cmf_sync_period, &wqe->cmf_sync, warn_sync_period);
2015 
2016 	bf_set(cmf_sync_cmd_type, &wqe->cmf_sync, CMF_SYNC_COMMAND);
2017 	bf_set(cmf_sync_wqec, &wqe->cmf_sync, 1);
2018 	bf_set(cmf_sync_cqid, &wqe->cmf_sync, LPFC_WQE_CQ_ID_DEFAULT);
2019 
2020 	sync_buf->vport = phba->pport;
2021 	sync_buf->cmd_cmpl = lpfc_cmf_sync_cmpl;
2022 	sync_buf->cmd_dmabuf = NULL;
2023 	sync_buf->rsp_dmabuf = NULL;
2024 	sync_buf->bpl_dmabuf = NULL;
2025 	sync_buf->sli4_xritag = NO_XRI;
2026 
2027 	sync_buf->cmd_flag |= LPFC_IO_CMF;
2028 	ret_val = lpfc_sli4_issue_wqe(phba, &phba->sli4_hba.hdwq[0], sync_buf);
2029 	if (ret_val) {
2030 		lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
2031 				"6214 Cannot issue CMF_SYNC_WQE: x%x\n",
2032 				ret_val);
2033 		__lpfc_sli_release_iocbq(phba, sync_buf);
2034 	}
2035 out_unlock:
2036 	spin_unlock_irqrestore(&phba->hbalock, iflags);
2037 	return ret_val;
2038 }
2039 
2040 /**
2041  * lpfc_sli_next_iocb_slot - Get next iocb slot in the ring
2042  * @phba: Pointer to HBA context object.
2043  * @pring: Pointer to driver SLI ring object.
2044  *
2045  * This function is called with hbalock held and the caller must post the
2046  * iocb without releasing the lock. If the caller releases the lock,
2047  * iocb slot returned by the function is not guaranteed to be available.
2048  * The function returns pointer to the next available iocb slot if there
2049  * is available slot in the ring, else it returns NULL.
2050  * If the get index of the ring is ahead of the put index, the function
2051  * will post an error attention event to the worker thread to take the
2052  * HBA to offline state.
2053  **/
2054 static IOCB_t *
2055 lpfc_sli_next_iocb_slot (struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2056 {
2057 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
2058 	uint32_t  max_cmd_idx = pring->sli.sli3.numCiocb;
2059 
2060 	lockdep_assert_held(&phba->hbalock);
2061 
2062 	if ((pring->sli.sli3.next_cmdidx == pring->sli.sli3.cmdidx) &&
2063 	   (++pring->sli.sli3.next_cmdidx >= max_cmd_idx))
2064 		pring->sli.sli3.next_cmdidx = 0;
2065 
2066 	if (unlikely(pring->sli.sli3.local_getidx ==
2067 		pring->sli.sli3.next_cmdidx)) {
2068 
2069 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
2070 
2071 		if (unlikely(pring->sli.sli3.local_getidx >= max_cmd_idx)) {
2072 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2073 					"0315 Ring %d issue: portCmdGet %d "
2074 					"is bigger than cmd ring %d\n",
2075 					pring->ringno,
2076 					pring->sli.sli3.local_getidx,
2077 					max_cmd_idx);
2078 
2079 			phba->link_state = LPFC_HBA_ERROR;
2080 			/*
2081 			 * All error attention handlers are posted to
2082 			 * worker thread
2083 			 */
2084 			phba->work_ha |= HA_ERATT;
2085 			phba->work_hs = HS_FFER3;
2086 
2087 			lpfc_worker_wake_up(phba);
2088 
2089 			return NULL;
2090 		}
2091 
2092 		if (pring->sli.sli3.local_getidx == pring->sli.sli3.next_cmdidx)
2093 			return NULL;
2094 	}
2095 
2096 	return lpfc_cmd_iocb(phba, pring);
2097 }
2098 
2099 /**
2100  * lpfc_sli_next_iotag - Get an iotag for the iocb
2101  * @phba: Pointer to HBA context object.
2102  * @iocbq: Pointer to driver iocb object.
2103  *
2104  * This function gets an iotag for the iocb. If there is no unused iotag and
2105  * the iocbq_lookup_len < 0xffff, this function allocates a bigger iotag_lookup
2106  * array and assigns a new iotag.
2107  * The function returns the allocated iotag if successful, else returns zero.
2108  * Zero is not a valid iotag.
2109  * The caller is not required to hold any lock.
2110  **/
2111 uint16_t
2112 lpfc_sli_next_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
2113 {
2114 	struct lpfc_iocbq **new_arr;
2115 	struct lpfc_iocbq **old_arr;
2116 	size_t new_len;
2117 	struct lpfc_sli *psli = &phba->sli;
2118 	uint16_t iotag;
2119 
2120 	spin_lock_irq(&phba->hbalock);
2121 	iotag = psli->last_iotag;
2122 	if(++iotag < psli->iocbq_lookup_len) {
2123 		psli->last_iotag = iotag;
2124 		psli->iocbq_lookup[iotag] = iocbq;
2125 		spin_unlock_irq(&phba->hbalock);
2126 		iocbq->iotag = iotag;
2127 		return iotag;
2128 	} else if (psli->iocbq_lookup_len < (0xffff
2129 					   - LPFC_IOCBQ_LOOKUP_INCREMENT)) {
2130 		new_len = psli->iocbq_lookup_len + LPFC_IOCBQ_LOOKUP_INCREMENT;
2131 		spin_unlock_irq(&phba->hbalock);
2132 		new_arr = kzalloc_objs(struct lpfc_iocbq *, new_len);
2133 		if (new_arr) {
2134 			spin_lock_irq(&phba->hbalock);
2135 			old_arr = psli->iocbq_lookup;
2136 			if (new_len <= psli->iocbq_lookup_len) {
2137 				/* highly unprobable case */
2138 				kfree(new_arr);
2139 				iotag = psli->last_iotag;
2140 				if(++iotag < psli->iocbq_lookup_len) {
2141 					psli->last_iotag = iotag;
2142 					psli->iocbq_lookup[iotag] = iocbq;
2143 					spin_unlock_irq(&phba->hbalock);
2144 					iocbq->iotag = iotag;
2145 					return iotag;
2146 				}
2147 				spin_unlock_irq(&phba->hbalock);
2148 				return 0;
2149 			}
2150 			if (psli->iocbq_lookup)
2151 				memcpy(new_arr, old_arr,
2152 				       ((psli->last_iotag  + 1) *
2153 					sizeof (struct lpfc_iocbq *)));
2154 			psli->iocbq_lookup = new_arr;
2155 			psli->iocbq_lookup_len = new_len;
2156 			psli->last_iotag = iotag;
2157 			psli->iocbq_lookup[iotag] = iocbq;
2158 			spin_unlock_irq(&phba->hbalock);
2159 			iocbq->iotag = iotag;
2160 			kfree(old_arr);
2161 			return iotag;
2162 		}
2163 	} else
2164 		spin_unlock_irq(&phba->hbalock);
2165 
2166 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
2167 			"0318 Failed to allocate IOTAG.last IOTAG is %d\n",
2168 			psli->last_iotag);
2169 
2170 	return 0;
2171 }
2172 
2173 /**
2174  * lpfc_sli_submit_iocb - Submit an iocb to the firmware
2175  * @phba: Pointer to HBA context object.
2176  * @pring: Pointer to driver SLI ring object.
2177  * @iocb: Pointer to iocb slot in the ring.
2178  * @nextiocb: Pointer to driver iocb object which need to be
2179  *            posted to firmware.
2180  *
2181  * This function is called to post a new iocb to the firmware. This
2182  * function copies the new iocb to ring iocb slot and updates the
2183  * ring pointers. It adds the new iocb to txcmplq if there is
2184  * a completion call back for this iocb else the function will free the
2185  * iocb object.  The hbalock is asserted held in the code path calling
2186  * this routine.
2187  **/
2188 static void
2189 lpfc_sli_submit_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
2190 		IOCB_t *iocb, struct lpfc_iocbq *nextiocb)
2191 {
2192 	/*
2193 	 * Set up an iotag
2194 	 */
2195 	nextiocb->iocb.ulpIoTag = (nextiocb->cmd_cmpl) ? nextiocb->iotag : 0;
2196 
2197 
2198 	if (pring->ringno == LPFC_ELS_RING) {
2199 		lpfc_debugfs_slow_ring_trc(phba,
2200 			"IOCB cmd ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
2201 			*(((uint32_t *) &nextiocb->iocb) + 4),
2202 			*(((uint32_t *) &nextiocb->iocb) + 6),
2203 			*(((uint32_t *) &nextiocb->iocb) + 7));
2204 	}
2205 
2206 	/*
2207 	 * Issue iocb command to adapter
2208 	 */
2209 	lpfc_sli_pcimem_bcopy(&nextiocb->iocb, iocb, phba->iocb_cmd_size);
2210 	wmb();
2211 	pring->stats.iocb_cmd++;
2212 
2213 	/*
2214 	 * If there is no completion routine to call, we can release the
2215 	 * IOCB buffer back right now. For IOCBs, like QUE_RING_BUF,
2216 	 * that have no rsp ring completion, cmd_cmpl MUST be NULL.
2217 	 */
2218 	if (nextiocb->cmd_cmpl)
2219 		lpfc_sli_ringtxcmpl_put(phba, pring, nextiocb);
2220 	else
2221 		__lpfc_sli_release_iocbq(phba, nextiocb);
2222 
2223 	/*
2224 	 * Let the HBA know what IOCB slot will be the next one the
2225 	 * driver will put a command into.
2226 	 */
2227 	pring->sli.sli3.cmdidx = pring->sli.sli3.next_cmdidx;
2228 	writel(pring->sli.sli3.cmdidx, &phba->host_gp[pring->ringno].cmdPutInx);
2229 }
2230 
2231 /**
2232  * lpfc_sli_update_full_ring - Update the chip attention register
2233  * @phba: Pointer to HBA context object.
2234  * @pring: Pointer to driver SLI ring object.
2235  *
2236  * The caller is not required to hold any lock for calling this function.
2237  * This function updates the chip attention bits for the ring to inform firmware
2238  * that there are pending work to be done for this ring and requests an
2239  * interrupt when there is space available in the ring. This function is
2240  * called when the driver is unable to post more iocbs to the ring due
2241  * to unavailability of space in the ring.
2242  **/
2243 static void
2244 lpfc_sli_update_full_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2245 {
2246 	int ringno = pring->ringno;
2247 
2248 	pring->flag |= LPFC_CALL_RING_AVAILABLE;
2249 
2250 	wmb();
2251 
2252 	/*
2253 	 * Set ring 'ringno' to SET R0CE_REQ in Chip Att register.
2254 	 * The HBA will tell us when an IOCB entry is available.
2255 	 */
2256 	writel((CA_R0ATT|CA_R0CE_REQ) << (ringno*4), phba->CAregaddr);
2257 	readl(phba->CAregaddr); /* flush */
2258 
2259 	pring->stats.iocb_cmd_full++;
2260 }
2261 
2262 /**
2263  * lpfc_sli_update_ring - Update chip attention register
2264  * @phba: Pointer to HBA context object.
2265  * @pring: Pointer to driver SLI ring object.
2266  *
2267  * This function updates the chip attention register bit for the
2268  * given ring to inform HBA that there is more work to be done
2269  * in this ring. The caller is not required to hold any lock.
2270  **/
2271 static void
2272 lpfc_sli_update_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2273 {
2274 	int ringno = pring->ringno;
2275 
2276 	/*
2277 	 * Tell the HBA that there is work to do in this ring.
2278 	 */
2279 	if (!(phba->sli3_options & LPFC_SLI3_CRP_ENABLED)) {
2280 		wmb();
2281 		writel(CA_R0ATT << (ringno * 4), phba->CAregaddr);
2282 		readl(phba->CAregaddr); /* flush */
2283 	}
2284 }
2285 
2286 /**
2287  * lpfc_sli_resume_iocb - Process iocbs in the txq
2288  * @phba: Pointer to HBA context object.
2289  * @pring: Pointer to driver SLI ring object.
2290  *
2291  * This function is called with hbalock held to post pending iocbs
2292  * in the txq to the firmware. This function is called when driver
2293  * detects space available in the ring.
2294  **/
2295 static void
2296 lpfc_sli_resume_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2297 {
2298 	IOCB_t *iocb;
2299 	struct lpfc_iocbq *nextiocb;
2300 
2301 	lockdep_assert_held(&phba->hbalock);
2302 
2303 	/*
2304 	 * Check to see if:
2305 	 *  (a) there is anything on the txq to send
2306 	 *  (b) link is up
2307 	 *  (c) link attention events can be processed (fcp ring only)
2308 	 *  (d) IOCB processing is not blocked by the outstanding mbox command.
2309 	 */
2310 
2311 	if (lpfc_is_link_up(phba) &&
2312 	    (!list_empty(&pring->txq)) &&
2313 	    (pring->ringno != LPFC_FCP_RING ||
2314 	     phba->sli.sli_flag & LPFC_PROCESS_LA)) {
2315 
2316 		while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
2317 		       (nextiocb = lpfc_sli_ringtx_get(phba, pring)))
2318 			lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
2319 
2320 		if (iocb)
2321 			lpfc_sli_update_ring(phba, pring);
2322 		else
2323 			lpfc_sli_update_full_ring(phba, pring);
2324 	}
2325 
2326 	return;
2327 }
2328 
2329 /**
2330  * lpfc_sli_next_hbq_slot - Get next hbq entry for the HBQ
2331  * @phba: Pointer to HBA context object.
2332  * @hbqno: HBQ number.
2333  *
2334  * This function is called with hbalock held to get the next
2335  * available slot for the given HBQ. If there is free slot
2336  * available for the HBQ it will return pointer to the next available
2337  * HBQ entry else it will return NULL.
2338  **/
2339 static struct lpfc_hbq_entry *
2340 lpfc_sli_next_hbq_slot(struct lpfc_hba *phba, uint32_t hbqno)
2341 {
2342 	struct hbq_s *hbqp = &phba->hbqs[hbqno];
2343 
2344 	lockdep_assert_held(&phba->hbalock);
2345 
2346 	if (hbqp->next_hbqPutIdx == hbqp->hbqPutIdx &&
2347 	    ++hbqp->next_hbqPutIdx >= hbqp->entry_count)
2348 		hbqp->next_hbqPutIdx = 0;
2349 
2350 	if (unlikely(hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)) {
2351 		uint32_t raw_index = phba->hbq_get[hbqno];
2352 		uint32_t getidx = le32_to_cpu(raw_index);
2353 
2354 		hbqp->local_hbqGetIdx = getidx;
2355 
2356 		if (unlikely(hbqp->local_hbqGetIdx >= hbqp->entry_count)) {
2357 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2358 					"1802 HBQ %d: local_hbqGetIdx "
2359 					"%u is > than hbqp->entry_count %u\n",
2360 					hbqno, hbqp->local_hbqGetIdx,
2361 					hbqp->entry_count);
2362 
2363 			phba->link_state = LPFC_HBA_ERROR;
2364 			return NULL;
2365 		}
2366 
2367 		if (hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)
2368 			return NULL;
2369 	}
2370 
2371 	return (struct lpfc_hbq_entry *) phba->hbqs[hbqno].hbq_virt +
2372 			hbqp->hbqPutIdx;
2373 }
2374 
2375 /**
2376  * lpfc_sli_hbqbuf_free_all - Free all the hbq buffers
2377  * @phba: Pointer to HBA context object.
2378  *
2379  * This function is called with no lock held to free all the
2380  * hbq buffers while uninitializing the SLI interface. It also
2381  * frees the HBQ buffers returned by the firmware but not yet
2382  * processed by the upper layers.
2383  **/
2384 void
2385 lpfc_sli_hbqbuf_free_all(struct lpfc_hba *phba)
2386 {
2387 	struct lpfc_dmabuf *dmabuf, *next_dmabuf;
2388 	struct hbq_dmabuf *hbq_buf;
2389 	unsigned long flags;
2390 	int i, hbq_count;
2391 
2392 	hbq_count = lpfc_sli_hbq_count();
2393 	/* Return all memory used by all HBQs */
2394 	spin_lock_irqsave(&phba->hbalock, flags);
2395 	for (i = 0; i < hbq_count; ++i) {
2396 		list_for_each_entry_safe(dmabuf, next_dmabuf,
2397 				&phba->hbqs[i].hbq_buffer_list, list) {
2398 			hbq_buf = container_of(dmabuf, struct hbq_dmabuf, dbuf);
2399 			list_del(&hbq_buf->dbuf.list);
2400 			(phba->hbqs[i].hbq_free_buffer)(phba, hbq_buf);
2401 		}
2402 		phba->hbqs[i].buffer_count = 0;
2403 	}
2404 
2405 	/* Mark the HBQs not in use */
2406 	phba->hbq_in_use = 0;
2407 	spin_unlock_irqrestore(&phba->hbalock, flags);
2408 }
2409 
2410 /**
2411  * lpfc_sli_hbq_to_firmware - Post the hbq buffer to firmware
2412  * @phba: Pointer to HBA context object.
2413  * @hbqno: HBQ number.
2414  * @hbq_buf: Pointer to HBQ buffer.
2415  *
2416  * This function is called with the hbalock held to post a
2417  * hbq buffer to the firmware. If the function finds an empty
2418  * slot in the HBQ, it will post the buffer. The function will return
2419  * pointer to the hbq entry if it successfully post the buffer
2420  * else it will return NULL.
2421  **/
2422 static int
2423 lpfc_sli_hbq_to_firmware(struct lpfc_hba *phba, uint32_t hbqno,
2424 			 struct hbq_dmabuf *hbq_buf)
2425 {
2426 	lockdep_assert_held(&phba->hbalock);
2427 	return phba->lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buf);
2428 }
2429 
2430 /**
2431  * lpfc_sli_hbq_to_firmware_s3 - Post the hbq buffer to SLI3 firmware
2432  * @phba: Pointer to HBA context object.
2433  * @hbqno: HBQ number.
2434  * @hbq_buf: Pointer to HBQ buffer.
2435  *
2436  * This function is called with the hbalock held to post a hbq buffer to the
2437  * firmware. If the function finds an empty slot in the HBQ, it will post the
2438  * buffer and place it on the hbq_buffer_list. The function will return zero if
2439  * it successfully post the buffer else it will return an error.
2440  **/
2441 static int
2442 lpfc_sli_hbq_to_firmware_s3(struct lpfc_hba *phba, uint32_t hbqno,
2443 			    struct hbq_dmabuf *hbq_buf)
2444 {
2445 	struct lpfc_hbq_entry *hbqe;
2446 	dma_addr_t physaddr = hbq_buf->dbuf.phys;
2447 
2448 	lockdep_assert_held(&phba->hbalock);
2449 	/* Get next HBQ entry slot to use */
2450 	hbqe = lpfc_sli_next_hbq_slot(phba, hbqno);
2451 	if (hbqe) {
2452 		struct hbq_s *hbqp = &phba->hbqs[hbqno];
2453 
2454 		hbqe->bde.addrHigh = le32_to_cpu(putPaddrHigh(physaddr));
2455 		hbqe->bde.addrLow  = le32_to_cpu(putPaddrLow(physaddr));
2456 		hbqe->bde.tus.f.bdeSize = hbq_buf->total_size;
2457 		hbqe->bde.tus.f.bdeFlags = 0;
2458 		hbqe->bde.tus.w = le32_to_cpu(hbqe->bde.tus.w);
2459 		hbqe->buffer_tag = le32_to_cpu(hbq_buf->tag);
2460 				/* Sync SLIM */
2461 		hbqp->hbqPutIdx = hbqp->next_hbqPutIdx;
2462 		writel(hbqp->hbqPutIdx, phba->hbq_put + hbqno);
2463 				/* flush */
2464 		readl(phba->hbq_put + hbqno);
2465 		list_add_tail(&hbq_buf->dbuf.list, &hbqp->hbq_buffer_list);
2466 		return 0;
2467 	} else
2468 		return -ENOMEM;
2469 }
2470 
2471 /**
2472  * lpfc_sli_hbq_to_firmware_s4 - Post the hbq buffer to SLI4 firmware
2473  * @phba: Pointer to HBA context object.
2474  * @hbqno: HBQ number.
2475  * @hbq_buf: Pointer to HBQ buffer.
2476  *
2477  * This function is called with the hbalock held to post an RQE to the SLI4
2478  * firmware. If able to post the RQE to the RQ it will queue the hbq entry to
2479  * the hbq_buffer_list and return zero, otherwise it will return an error.
2480  **/
2481 static int
2482 lpfc_sli_hbq_to_firmware_s4(struct lpfc_hba *phba, uint32_t hbqno,
2483 			    struct hbq_dmabuf *hbq_buf)
2484 {
2485 	int rc;
2486 	struct lpfc_rqe hrqe;
2487 	struct lpfc_rqe drqe;
2488 	struct lpfc_queue *hrq;
2489 	struct lpfc_queue *drq;
2490 
2491 	if (hbqno != LPFC_ELS_HBQ)
2492 		return 1;
2493 	hrq = phba->sli4_hba.hdr_rq;
2494 	drq = phba->sli4_hba.dat_rq;
2495 
2496 	lockdep_assert_held(&phba->hbalock);
2497 	hrqe.address_lo = putPaddrLow(hbq_buf->hbuf.phys);
2498 	hrqe.address_hi = putPaddrHigh(hbq_buf->hbuf.phys);
2499 	drqe.address_lo = putPaddrLow(hbq_buf->dbuf.phys);
2500 	drqe.address_hi = putPaddrHigh(hbq_buf->dbuf.phys);
2501 	rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
2502 	if (rc < 0)
2503 		return rc;
2504 	hbq_buf->tag = (rc | (hbqno << 16));
2505 	list_add_tail(&hbq_buf->dbuf.list, &phba->hbqs[hbqno].hbq_buffer_list);
2506 	return 0;
2507 }
2508 
2509 /* HBQ for ELS and CT traffic. */
2510 static struct lpfc_hbq_init lpfc_els_hbq = {
2511 	.rn = 1,
2512 	.entry_count = 256,
2513 	.mask_count = 0,
2514 	.profile = 0,
2515 	.ring_mask = (1 << LPFC_ELS_RING),
2516 	.buffer_count = 0,
2517 	.init_count = 40,
2518 	.add_count = 40,
2519 };
2520 
2521 /* Array of HBQs */
2522 struct lpfc_hbq_init *lpfc_hbq_defs[] = {
2523 	&lpfc_els_hbq,
2524 };
2525 
2526 /**
2527  * lpfc_sli_hbqbuf_fill_hbqs - Post more hbq buffers to HBQ
2528  * @phba: Pointer to HBA context object.
2529  * @hbqno: HBQ number.
2530  * @count: Number of HBQ buffers to be posted.
2531  *
2532  * This function is called with no lock held to post more hbq buffers to the
2533  * given HBQ. The function returns the number of HBQ buffers successfully
2534  * posted.
2535  **/
2536 static int
2537 lpfc_sli_hbqbuf_fill_hbqs(struct lpfc_hba *phba, uint32_t hbqno, uint32_t count)
2538 {
2539 	uint32_t i, posted = 0;
2540 	unsigned long flags;
2541 	struct hbq_dmabuf *hbq_buffer;
2542 	LIST_HEAD(hbq_buf_list);
2543 	if (!phba->hbqs[hbqno].hbq_alloc_buffer)
2544 		return 0;
2545 
2546 	if ((phba->hbqs[hbqno].buffer_count + count) >
2547 	    lpfc_hbq_defs[hbqno]->entry_count)
2548 		count = lpfc_hbq_defs[hbqno]->entry_count -
2549 					phba->hbqs[hbqno].buffer_count;
2550 	if (!count)
2551 		return 0;
2552 	/* Allocate HBQ entries */
2553 	for (i = 0; i < count; i++) {
2554 		hbq_buffer = (phba->hbqs[hbqno].hbq_alloc_buffer)(phba);
2555 		if (!hbq_buffer)
2556 			break;
2557 		list_add_tail(&hbq_buffer->dbuf.list, &hbq_buf_list);
2558 	}
2559 	/* Check whether HBQ is still in use */
2560 	spin_lock_irqsave(&phba->hbalock, flags);
2561 	if (!phba->hbq_in_use)
2562 		goto err;
2563 	while (!list_empty(&hbq_buf_list)) {
2564 		list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
2565 				 dbuf.list);
2566 		hbq_buffer->tag = (phba->hbqs[hbqno].buffer_count |
2567 				      (hbqno << 16));
2568 		if (!lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer)) {
2569 			phba->hbqs[hbqno].buffer_count++;
2570 			posted++;
2571 		} else
2572 			(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2573 	}
2574 	spin_unlock_irqrestore(&phba->hbalock, flags);
2575 	return posted;
2576 err:
2577 	spin_unlock_irqrestore(&phba->hbalock, flags);
2578 	while (!list_empty(&hbq_buf_list)) {
2579 		list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
2580 				 dbuf.list);
2581 		(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2582 	}
2583 	return 0;
2584 }
2585 
2586 /**
2587  * lpfc_sli_hbqbuf_add_hbqs - Post more HBQ buffers to firmware
2588  * @phba: Pointer to HBA context object.
2589  * @qno: HBQ number.
2590  *
2591  * This function posts more buffers to the HBQ. This function
2592  * is called with no lock held. The function returns the number of HBQ entries
2593  * successfully allocated.
2594  **/
2595 int
2596 lpfc_sli_hbqbuf_add_hbqs(struct lpfc_hba *phba, uint32_t qno)
2597 {
2598 	if (phba->sli_rev == LPFC_SLI_REV4)
2599 		return 0;
2600 	else
2601 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2602 					 lpfc_hbq_defs[qno]->add_count);
2603 }
2604 
2605 /**
2606  * lpfc_sli_hbqbuf_init_hbqs - Post initial buffers to the HBQ
2607  * @phba: Pointer to HBA context object.
2608  * @qno:  HBQ queue number.
2609  *
2610  * This function is called from SLI initialization code path with
2611  * no lock held to post initial HBQ buffers to firmware. The
2612  * function returns the number of HBQ entries successfully allocated.
2613  **/
2614 static int
2615 lpfc_sli_hbqbuf_init_hbqs(struct lpfc_hba *phba, uint32_t qno)
2616 {
2617 	if (phba->sli_rev == LPFC_SLI_REV4)
2618 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2619 					lpfc_hbq_defs[qno]->entry_count);
2620 	else
2621 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2622 					 lpfc_hbq_defs[qno]->init_count);
2623 }
2624 
2625 /*
2626  * lpfc_sli_hbqbuf_get - Remove the first hbq off of an hbq list
2627  *
2628  * This function removes the first hbq buffer on an hbq list and returns a
2629  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
2630  **/
2631 static struct hbq_dmabuf *
2632 lpfc_sli_hbqbuf_get(struct list_head *rb_list)
2633 {
2634 	struct lpfc_dmabuf *d_buf;
2635 
2636 	list_remove_head(rb_list, d_buf, struct lpfc_dmabuf, list);
2637 	if (!d_buf)
2638 		return NULL;
2639 	return container_of(d_buf, struct hbq_dmabuf, dbuf);
2640 }
2641 
2642 /**
2643  * lpfc_sli_rqbuf_get - Remove the first dma buffer off of an RQ list
2644  * @phba: Pointer to HBA context object.
2645  * @hrq: HBQ number.
2646  *
2647  * This function removes the first RQ buffer on an RQ buffer list and returns a
2648  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
2649  **/
2650 static struct rqb_dmabuf *
2651 lpfc_sli_rqbuf_get(struct lpfc_hba *phba, struct lpfc_queue *hrq)
2652 {
2653 	struct lpfc_dmabuf *h_buf;
2654 	struct lpfc_rqb *rqbp;
2655 
2656 	rqbp = hrq->rqbp;
2657 	list_remove_head(&rqbp->rqb_buffer_list, h_buf,
2658 			 struct lpfc_dmabuf, list);
2659 	if (!h_buf)
2660 		return NULL;
2661 	rqbp->buffer_count--;
2662 	return container_of(h_buf, struct rqb_dmabuf, hbuf);
2663 }
2664 
2665 /**
2666  * lpfc_sli_hbqbuf_find - Find the hbq buffer associated with a tag
2667  * @phba: Pointer to HBA context object.
2668  * @tag: Tag of the hbq buffer.
2669  *
2670  * This function searches for the hbq buffer associated with the given tag in
2671  * the hbq buffer list. If it finds the hbq buffer, it returns the hbq_buffer
2672  * otherwise it returns NULL.
2673  **/
2674 static struct hbq_dmabuf *
2675 lpfc_sli_hbqbuf_find(struct lpfc_hba *phba, uint32_t tag)
2676 {
2677 	struct lpfc_dmabuf *d_buf;
2678 	struct hbq_dmabuf *hbq_buf;
2679 	uint32_t hbqno;
2680 
2681 	hbqno = tag >> 16;
2682 	if (hbqno >= LPFC_MAX_HBQS)
2683 		return NULL;
2684 
2685 	spin_lock_irq(&phba->hbalock);
2686 	list_for_each_entry(d_buf, &phba->hbqs[hbqno].hbq_buffer_list, list) {
2687 		hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
2688 		if (hbq_buf->tag == tag) {
2689 			spin_unlock_irq(&phba->hbalock);
2690 			return hbq_buf;
2691 		}
2692 	}
2693 	spin_unlock_irq(&phba->hbalock);
2694 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2695 			"1803 Bad hbq tag. Data: x%x x%x\n",
2696 			tag, phba->hbqs[tag >> 16].buffer_count);
2697 	return NULL;
2698 }
2699 
2700 /**
2701  * lpfc_sli_free_hbq - Give back the hbq buffer to firmware
2702  * @phba: Pointer to HBA context object.
2703  * @hbq_buffer: Pointer to HBQ buffer.
2704  *
2705  * This function is called with hbalock. This function gives back
2706  * the hbq buffer to firmware. If the HBQ does not have space to
2707  * post the buffer, it will free the buffer.
2708  **/
2709 void
2710 lpfc_sli_free_hbq(struct lpfc_hba *phba, struct hbq_dmabuf *hbq_buffer)
2711 {
2712 	uint32_t hbqno;
2713 
2714 	if (hbq_buffer) {
2715 		hbqno = hbq_buffer->tag >> 16;
2716 		if (lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer))
2717 			(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2718 	}
2719 }
2720 
2721 /**
2722  * lpfc_sli_chk_mbx_command - Check if the mailbox is a legitimate mailbox
2723  * @mbxCommand: mailbox command code.
2724  *
2725  * This function is called by the mailbox event handler function to verify
2726  * that the completed mailbox command is a legitimate mailbox command. If the
2727  * completed mailbox is not known to the function, it will return MBX_SHUTDOWN
2728  * and the mailbox event handler will take the HBA offline.
2729  **/
2730 static int
2731 lpfc_sli_chk_mbx_command(uint8_t mbxCommand)
2732 {
2733 	uint8_t ret;
2734 
2735 	switch (mbxCommand) {
2736 	case MBX_LOAD_SM:
2737 	case MBX_READ_NV:
2738 	case MBX_WRITE_NV:
2739 	case MBX_WRITE_VPARMS:
2740 	case MBX_RUN_BIU_DIAG:
2741 	case MBX_INIT_LINK:
2742 	case MBX_DOWN_LINK:
2743 	case MBX_CONFIG_LINK:
2744 	case MBX_CONFIG_RING:
2745 	case MBX_RESET_RING:
2746 	case MBX_READ_CONFIG:
2747 	case MBX_READ_RCONFIG:
2748 	case MBX_READ_SPARM:
2749 	case MBX_READ_STATUS:
2750 	case MBX_READ_RPI:
2751 	case MBX_READ_XRI:
2752 	case MBX_READ_REV:
2753 	case MBX_READ_LNK_STAT:
2754 	case MBX_REG_LOGIN:
2755 	case MBX_UNREG_LOGIN:
2756 	case MBX_CLEAR_LA:
2757 	case MBX_DUMP_MEMORY:
2758 	case MBX_DUMP_CONTEXT:
2759 	case MBX_RUN_DIAGS:
2760 	case MBX_RESTART:
2761 	case MBX_UPDATE_CFG:
2762 	case MBX_DOWN_LOAD:
2763 	case MBX_DEL_LD_ENTRY:
2764 	case MBX_RUN_PROGRAM:
2765 	case MBX_SET_MASK:
2766 	case MBX_SET_VARIABLE:
2767 	case MBX_UNREG_D_ID:
2768 	case MBX_KILL_BOARD:
2769 	case MBX_CONFIG_FARP:
2770 	case MBX_BEACON:
2771 	case MBX_LOAD_AREA:
2772 	case MBX_RUN_BIU_DIAG64:
2773 	case MBX_CONFIG_PORT:
2774 	case MBX_READ_SPARM64:
2775 	case MBX_READ_RPI64:
2776 	case MBX_REG_LOGIN64:
2777 	case MBX_READ_TOPOLOGY:
2778 	case MBX_WRITE_WWN:
2779 	case MBX_SET_DEBUG:
2780 	case MBX_LOAD_EXP_ROM:
2781 	case MBX_ASYNCEVT_ENABLE:
2782 	case MBX_REG_VPI:
2783 	case MBX_UNREG_VPI:
2784 	case MBX_HEARTBEAT:
2785 	case MBX_PORT_CAPABILITIES:
2786 	case MBX_PORT_IOV_CONTROL:
2787 	case MBX_SLI4_CONFIG:
2788 	case MBX_SLI4_REQ_FTRS:
2789 	case MBX_REG_FCFI:
2790 	case MBX_UNREG_FCFI:
2791 	case MBX_REG_VFI:
2792 	case MBX_UNREG_VFI:
2793 	case MBX_INIT_VPI:
2794 	case MBX_INIT_VFI:
2795 	case MBX_RESUME_RPI:
2796 	case MBX_READ_EVENT_LOG_STATUS:
2797 	case MBX_READ_EVENT_LOG:
2798 	case MBX_SECURITY_MGMT:
2799 	case MBX_AUTH_PORT:
2800 	case MBX_ACCESS_VDATA:
2801 		ret = mbxCommand;
2802 		break;
2803 	default:
2804 		ret = MBX_SHUTDOWN;
2805 		break;
2806 	}
2807 	return ret;
2808 }
2809 
2810 /**
2811  * lpfc_sli_wake_mbox_wait - lpfc_sli_issue_mbox_wait mbox completion handler
2812  * @phba: Pointer to HBA context object.
2813  * @pmboxq: Pointer to mailbox command.
2814  *
2815  * This is completion handler function for mailbox commands issued from
2816  * lpfc_sli_issue_mbox_wait function. This function is called by the
2817  * mailbox event handler function with no lock held. This function
2818  * will wake up thread waiting on the wait queue pointed by context1
2819  * of the mailbox.
2820  **/
2821 void
2822 lpfc_sli_wake_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
2823 {
2824 	unsigned long drvr_flag;
2825 	struct completion *pmbox_done;
2826 
2827 	/*
2828 	 * If pmbox_done is empty, the driver thread gave up waiting and
2829 	 * continued running.
2830 	 */
2831 	pmboxq->mbox_flag |= LPFC_MBX_WAKE;
2832 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
2833 	pmbox_done = pmboxq->ctx_u.mbox_wait;
2834 	if (pmbox_done)
2835 		complete(pmbox_done);
2836 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
2837 	return;
2838 }
2839 
2840 /**
2841  * lpfc_sli_def_mbox_cmpl - Default mailbox completion handler
2842  * @phba: Pointer to HBA context object.
2843  * @pmb: Pointer to mailbox object.
2844  *
2845  * This function is the default mailbox completion handler. It
2846  * frees the memory resources associated with the completed mailbox
2847  * command. If the completed command is a REG_LOGIN mailbox command,
2848  * this function will issue a UREG_LOGIN to re-claim the RPI.
2849  **/
2850 void
2851 lpfc_sli_def_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2852 {
2853 	struct lpfc_vport  *vport = pmb->vport;
2854 	struct lpfc_dmabuf *mp;
2855 	struct lpfc_nodelist *ndlp;
2856 	struct Scsi_Host *shost;
2857 	uint16_t rpi, vpi;
2858 	int rc;
2859 
2860 	/*
2861 	 * If a REG_LOGIN succeeded  after node is destroyed or node
2862 	 * is in re-discovery driver need to cleanup the RPI.
2863 	 */
2864 	if (!test_bit(FC_UNLOADING, &phba->pport->load_flag) &&
2865 	    pmb->u.mb.mbxCommand == MBX_REG_LOGIN64 &&
2866 	    !pmb->u.mb.mbxStatus) {
2867 		mp = pmb->ctx_buf;
2868 		if (mp) {
2869 			pmb->ctx_buf = NULL;
2870 			lpfc_mbuf_free(phba, mp->virt, mp->phys);
2871 			kfree(mp);
2872 		}
2873 		rpi = pmb->u.mb.un.varWords[0];
2874 		vpi = pmb->u.mb.un.varRegLogin.vpi;
2875 		if (phba->sli_rev == LPFC_SLI_REV4)
2876 			vpi -= phba->sli4_hba.max_cfg_param.vpi_base;
2877 		lpfc_unreg_login(phba, vpi, rpi, pmb);
2878 		pmb->vport = vport;
2879 		pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
2880 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
2881 		if (rc != MBX_NOT_FINISHED)
2882 			return;
2883 	}
2884 
2885 	if ((pmb->u.mb.mbxCommand == MBX_REG_VPI) &&
2886 		!test_bit(FC_UNLOADING, &phba->pport->load_flag) &&
2887 		!pmb->u.mb.mbxStatus) {
2888 		shost = lpfc_shost_from_vport(vport);
2889 		spin_lock_irq(&shost->host_lock);
2890 		vport->vpi_state |= LPFC_VPI_REGISTERED;
2891 		spin_unlock_irq(&shost->host_lock);
2892 		clear_bit(FC_VPORT_NEEDS_REG_VPI, &vport->fc_flag);
2893 	}
2894 
2895 	if (pmb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
2896 		ndlp = pmb->ctx_ndlp;
2897 		lpfc_nlp_put(ndlp);
2898 	}
2899 
2900 	if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2901 		ndlp = pmb->ctx_ndlp;
2902 
2903 		/* Check to see if there are any deferred events to process */
2904 		if (ndlp) {
2905 			lpfc_printf_vlog(
2906 				vport,
2907 				KERN_INFO, LOG_MBOX | LOG_DISCOVERY,
2908 				"1438 UNREG cmpl deferred mbox x%x "
2909 				"on NPort x%x Data: x%lx x%x x%px x%lx x%x\n",
2910 				ndlp->nlp_rpi, ndlp->nlp_DID,
2911 				ndlp->nlp_flag, ndlp->nlp_defer_did,
2912 				ndlp, vport->load_flag, kref_read(&ndlp->kref));
2913 
2914 			if (test_bit(NLP_UNREG_INP, &ndlp->nlp_flag) &&
2915 			    ndlp->nlp_defer_did != NLP_EVT_NOTHING_PENDING) {
2916 				clear_bit(NLP_UNREG_INP, &ndlp->nlp_flag);
2917 				ndlp->nlp_defer_did = NLP_EVT_NOTHING_PENDING;
2918 				lpfc_issue_els_plogi(vport, ndlp->nlp_DID, 0);
2919 			} else {
2920 				clear_bit(NLP_UNREG_INP, &ndlp->nlp_flag);
2921 			}
2922 
2923 			/* The unreg_login mailbox is complete and had a
2924 			 * reference that has to be released.  The PLOGI
2925 			 * got its own ref.
2926 			 */
2927 			lpfc_nlp_put(ndlp);
2928 			pmb->ctx_ndlp = NULL;
2929 		}
2930 	}
2931 
2932 	/* This nlp_put pairs with lpfc_sli4_resume_rpi */
2933 	if (pmb->u.mb.mbxCommand == MBX_RESUME_RPI) {
2934 		ndlp = pmb->ctx_ndlp;
2935 		lpfc_nlp_put(ndlp);
2936 	}
2937 
2938 	/* Check security permission status on INIT_LINK mailbox command */
2939 	if ((pmb->u.mb.mbxCommand == MBX_INIT_LINK) &&
2940 	    (pmb->u.mb.mbxStatus == MBXERR_SEC_NO_PERMISSION))
2941 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2942 				"2860 SLI authentication is required "
2943 				"for INIT_LINK but has not done yet\n");
2944 
2945 	if (bf_get(lpfc_mqe_command, &pmb->u.mqe) == MBX_SLI4_CONFIG)
2946 		lpfc_sli4_mbox_cmd_free(phba, pmb);
2947 	else
2948 		lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
2949 }
2950  /**
2951  * lpfc_sli4_unreg_rpi_cmpl_clr - mailbox completion handler
2952  * @phba: Pointer to HBA context object.
2953  * @pmb: Pointer to mailbox object.
2954  *
2955  * This function is the unreg rpi mailbox completion handler. It
2956  * frees the memory resources associated with the completed mailbox
2957  * command. An additional reference is put on the ndlp to prevent
2958  * lpfc_nlp_release from freeing the rpi bit in the bitmask before
2959  * the unreg mailbox command completes, this routine puts the
2960  * reference back.
2961  *
2962  **/
2963 void
2964 lpfc_sli4_unreg_rpi_cmpl_clr(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2965 {
2966 	struct lpfc_vport  *vport = pmb->vport;
2967 	struct lpfc_nodelist *ndlp;
2968 	bool unreg_inp;
2969 
2970 	ndlp = pmb->ctx_ndlp;
2971 	if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2972 		if (phba->sli_rev == LPFC_SLI_REV4 &&
2973 		    (bf_get(lpfc_sli_intf_if_type,
2974 		     &phba->sli4_hba.sli_intf) >=
2975 		     LPFC_SLI_INTF_IF_TYPE_2)) {
2976 			if (ndlp) {
2977 				lpfc_printf_vlog(
2978 					 vport, KERN_INFO,
2979 					 LOG_MBOX | LOG_SLI | LOG_NODE,
2980 					 "0010 UNREG_LOGIN vpi:x%x "
2981 					 "rpi:%x DID:%x defer x%x flg x%lx "
2982 					 "x%px\n",
2983 					 vport->vpi, ndlp->nlp_rpi,
2984 					 ndlp->nlp_DID, ndlp->nlp_defer_did,
2985 					 ndlp->nlp_flag,
2986 					 ndlp);
2987 
2988 				/* Cleanup the nlp_flag now that the UNREG RPI
2989 				 * has completed.
2990 				 */
2991 				unreg_inp = test_and_clear_bit(NLP_UNREG_INP,
2992 							       &ndlp->nlp_flag);
2993 				clear_bit(NLP_LOGO_ACC, &ndlp->nlp_flag);
2994 
2995 				/* Check to see if there are any deferred
2996 				 * events to process
2997 				 */
2998 				if (unreg_inp &&
2999 				    ndlp->nlp_defer_did !=
3000 				    NLP_EVT_NOTHING_PENDING) {
3001 					lpfc_printf_vlog(
3002 						vport, KERN_INFO,
3003 						LOG_MBOX | LOG_SLI | LOG_NODE,
3004 						"4111 UNREG cmpl deferred "
3005 						"clr x%x on "
3006 						"NPort x%x Data: x%x x%px\n",
3007 						ndlp->nlp_rpi, ndlp->nlp_DID,
3008 						ndlp->nlp_defer_did, ndlp);
3009 					ndlp->nlp_defer_did =
3010 						NLP_EVT_NOTHING_PENDING;
3011 					lpfc_issue_els_plogi(
3012 						vport, ndlp->nlp_DID, 0);
3013 				}
3014 
3015 				lpfc_nlp_put(ndlp);
3016 			}
3017 		}
3018 	}
3019 
3020 	mempool_free(pmb, phba->mbox_mem_pool);
3021 }
3022 
3023 /**
3024  * lpfc_sli_handle_mb_event - Handle mailbox completions from firmware
3025  * @phba: Pointer to HBA context object.
3026  *
3027  * This function is called with no lock held. This function processes all
3028  * the completed mailbox commands and gives it to upper layers. The interrupt
3029  * service routine processes mailbox completion interrupt and adds completed
3030  * mailbox commands to the mboxq_cmpl queue and signals the worker thread.
3031  * Worker thread call lpfc_sli_handle_mb_event, which will return the
3032  * completed mailbox commands in mboxq_cmpl queue to the upper layers. This
3033  * function returns the mailbox commands to the upper layer by calling the
3034  * completion handler function of each mailbox.
3035  **/
3036 int
3037 lpfc_sli_handle_mb_event(struct lpfc_hba *phba)
3038 {
3039 	MAILBOX_t *pmbox;
3040 	LPFC_MBOXQ_t *pmb;
3041 	int rc;
3042 	LIST_HEAD(cmplq);
3043 
3044 	phba->sli.slistat.mbox_event++;
3045 
3046 	/* Get all completed mailboxe buffers into the cmplq */
3047 	spin_lock_irq(&phba->hbalock);
3048 	list_splice_init(&phba->sli.mboxq_cmpl, &cmplq);
3049 	spin_unlock_irq(&phba->hbalock);
3050 
3051 	/* Get a Mailbox buffer to setup mailbox commands for callback */
3052 	do {
3053 		list_remove_head(&cmplq, pmb, LPFC_MBOXQ_t, list);
3054 		if (pmb == NULL)
3055 			break;
3056 
3057 		pmbox = &pmb->u.mb;
3058 
3059 		if (pmbox->mbxCommand != MBX_HEARTBEAT) {
3060 			if (pmb->vport) {
3061 				lpfc_debugfs_disc_trc(pmb->vport,
3062 					LPFC_DISC_TRC_MBOX_VPORT,
3063 					"MBOX cmpl vport: cmd:x%x mb:x%x x%x",
3064 					(uint32_t)pmbox->mbxCommand,
3065 					pmbox->un.varWords[0],
3066 					pmbox->un.varWords[1]);
3067 			}
3068 			else {
3069 				lpfc_debugfs_disc_trc(phba->pport,
3070 					LPFC_DISC_TRC_MBOX,
3071 					"MBOX cmpl:       cmd:x%x mb:x%x x%x",
3072 					(uint32_t)pmbox->mbxCommand,
3073 					pmbox->un.varWords[0],
3074 					pmbox->un.varWords[1]);
3075 			}
3076 		}
3077 
3078 		/*
3079 		 * It is a fatal error if unknown mbox command completion.
3080 		 */
3081 		if (lpfc_sli_chk_mbx_command(pmbox->mbxCommand) ==
3082 		    MBX_SHUTDOWN) {
3083 			/* Unknown mailbox command compl */
3084 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3085 					"(%d):0323 Unknown Mailbox command "
3086 					"x%x (x%x/x%x) Cmpl\n",
3087 					pmb->vport ? pmb->vport->vpi :
3088 					LPFC_VPORT_UNKNOWN,
3089 					pmbox->mbxCommand,
3090 					lpfc_sli_config_mbox_subsys_get(phba,
3091 									pmb),
3092 					lpfc_sli_config_mbox_opcode_get(phba,
3093 									pmb));
3094 			phba->link_state = LPFC_HBA_ERROR;
3095 			phba->work_hs = HS_FFER3;
3096 			lpfc_handle_eratt(phba);
3097 			continue;
3098 		}
3099 
3100 		if (pmbox->mbxStatus) {
3101 			phba->sli.slistat.mbox_stat_err++;
3102 			if (pmbox->mbxStatus == MBXERR_NO_RESOURCES) {
3103 				/* Mbox cmd cmpl error - RETRYing */
3104 				lpfc_printf_log(phba, KERN_INFO,
3105 					LOG_MBOX | LOG_SLI,
3106 					"(%d):0305 Mbox cmd cmpl "
3107 					"error - RETRYing Data: x%x "
3108 					"(x%x/x%x) x%x x%x x%x\n",
3109 					pmb->vport ? pmb->vport->vpi :
3110 					LPFC_VPORT_UNKNOWN,
3111 					pmbox->mbxCommand,
3112 					lpfc_sli_config_mbox_subsys_get(phba,
3113 									pmb),
3114 					lpfc_sli_config_mbox_opcode_get(phba,
3115 									pmb),
3116 					pmbox->mbxStatus,
3117 					pmbox->un.varWords[0],
3118 					pmb->vport ? pmb->vport->port_state :
3119 					LPFC_VPORT_UNKNOWN);
3120 				pmbox->mbxStatus = 0;
3121 				pmbox->mbxOwner = OWN_HOST;
3122 				rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
3123 				if (rc != MBX_NOT_FINISHED)
3124 					continue;
3125 			}
3126 		}
3127 
3128 		/* Mailbox cmd <cmd> Cmpl <cmpl> */
3129 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
3130 				"(%d):0307 Mailbox cmd x%x (x%x/x%x) Cmpl %ps "
3131 				"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
3132 				"x%x x%x x%x\n",
3133 				pmb->vport ? pmb->vport->vpi : 0,
3134 				pmbox->mbxCommand,
3135 				lpfc_sli_config_mbox_subsys_get(phba, pmb),
3136 				lpfc_sli_config_mbox_opcode_get(phba, pmb),
3137 				pmb->mbox_cmpl,
3138 				*((uint32_t *) pmbox),
3139 				pmbox->un.varWords[0],
3140 				pmbox->un.varWords[1],
3141 				pmbox->un.varWords[2],
3142 				pmbox->un.varWords[3],
3143 				pmbox->un.varWords[4],
3144 				pmbox->un.varWords[5],
3145 				pmbox->un.varWords[6],
3146 				pmbox->un.varWords[7],
3147 				pmbox->un.varWords[8],
3148 				pmbox->un.varWords[9],
3149 				pmbox->un.varWords[10]);
3150 
3151 		if (pmb->mbox_cmpl)
3152 			pmb->mbox_cmpl(phba,pmb);
3153 	} while (1);
3154 	return 0;
3155 }
3156 
3157 /**
3158  * lpfc_sli_get_buff - Get the buffer associated with the buffer tag
3159  * @phba: Pointer to HBA context object.
3160  * @pring: Pointer to driver SLI ring object.
3161  * @tag: buffer tag.
3162  *
3163  * This function is called with no lock held. When QUE_BUFTAG_BIT bit
3164  * is set in the tag the buffer is posted for a particular exchange,
3165  * the function will return the buffer without replacing the buffer.
3166  * If the buffer is for unsolicited ELS or CT traffic, this function
3167  * returns the buffer and also posts another buffer to the firmware.
3168  **/
3169 static struct lpfc_dmabuf *
3170 lpfc_sli_get_buff(struct lpfc_hba *phba,
3171 		  struct lpfc_sli_ring *pring,
3172 		  uint32_t tag)
3173 {
3174 	struct hbq_dmabuf *hbq_entry;
3175 
3176 	if (tag & QUE_BUFTAG_BIT)
3177 		return lpfc_sli_ring_taggedbuf_get(phba, pring, tag);
3178 	hbq_entry = lpfc_sli_hbqbuf_find(phba, tag);
3179 	if (!hbq_entry)
3180 		return NULL;
3181 	return &hbq_entry->dbuf;
3182 }
3183 
3184 /**
3185  * lpfc_nvme_unsol_ls_handler - Process an unsolicited event data buffer
3186  *                              containing a NVME LS request.
3187  * @phba: pointer to lpfc hba data structure.
3188  * @piocb: pointer to the iocbq struct representing the sequence starting
3189  *        frame.
3190  *
3191  * This routine initially validates the NVME LS, validates there is a login
3192  * with the port that sent the LS, and then calls the appropriate nvme host
3193  * or target LS request handler.
3194  **/
3195 static void
3196 lpfc_nvme_unsol_ls_handler(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
3197 {
3198 	struct lpfc_nodelist *ndlp;
3199 	struct lpfc_dmabuf *d_buf;
3200 	struct hbq_dmabuf *nvmebuf;
3201 	struct fc_frame_header *fc_hdr;
3202 	struct lpfc_async_xchg_ctx *axchg = NULL;
3203 	char *failwhy = NULL;
3204 	uint32_t oxid, sid, did, fctl, size;
3205 	int ret = 1;
3206 
3207 	d_buf = piocb->cmd_dmabuf;
3208 
3209 	nvmebuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
3210 	fc_hdr = nvmebuf->hbuf.virt;
3211 	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
3212 	sid = sli4_sid_from_fc_hdr(fc_hdr);
3213 	did = sli4_did_from_fc_hdr(fc_hdr);
3214 	fctl = (fc_hdr->fh_f_ctl[0] << 16 |
3215 		fc_hdr->fh_f_ctl[1] << 8 |
3216 		fc_hdr->fh_f_ctl[2]);
3217 	size = bf_get(lpfc_rcqe_length, &nvmebuf->cq_event.cqe.rcqe_cmpl);
3218 
3219 	lpfc_nvmeio_data(phba, "NVME LS    RCV: xri x%x sz %d from %06x\n",
3220 			 oxid, size, sid);
3221 
3222 	if (test_bit(FC_UNLOADING, &phba->pport->load_flag)) {
3223 		failwhy = "Driver Unloading";
3224 	} else if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)) {
3225 		failwhy = "NVME FC4 Disabled";
3226 	} else if (!phba->nvmet_support && !phba->pport->localport) {
3227 		failwhy = "No Localport";
3228 	} else if (phba->nvmet_support && !phba->targetport) {
3229 		failwhy = "No Targetport";
3230 	} else if (unlikely(fc_hdr->fh_r_ctl != FC_RCTL_ELS4_REQ)) {
3231 		failwhy = "Bad NVME LS R_CTL";
3232 	} else if (unlikely((fctl & 0x00FF0000) !=
3233 			(FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT))) {
3234 		failwhy = "Bad NVME LS F_CTL";
3235 	} else {
3236 		axchg = kzalloc_obj(*axchg, GFP_ATOMIC);
3237 		if (!axchg)
3238 			failwhy = "No CTX memory";
3239 	}
3240 
3241 	if (unlikely(failwhy)) {
3242 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3243 				"6154 Drop NVME LS: SID %06X OXID x%X: %s\n",
3244 				sid, oxid, failwhy);
3245 		goto out_fail;
3246 	}
3247 
3248 	/* validate the source of the LS is logged in */
3249 	ndlp = lpfc_findnode_did(phba->pport, sid);
3250 	if (!ndlp ||
3251 	    ((ndlp->nlp_state != NLP_STE_UNMAPPED_NODE) &&
3252 	     (ndlp->nlp_state != NLP_STE_MAPPED_NODE))) {
3253 		lpfc_printf_log(phba, KERN_ERR, LOG_NVME_DISC,
3254 				"6216 NVME Unsol rcv: No ndlp: "
3255 				"NPort_ID x%x oxid x%x\n",
3256 				sid, oxid);
3257 		goto out_fail;
3258 	}
3259 
3260 	axchg->phba = phba;
3261 	axchg->ndlp = ndlp;
3262 	axchg->size = size;
3263 	axchg->oxid = oxid;
3264 	axchg->sid = sid;
3265 	axchg->wqeq = NULL;
3266 	axchg->state = LPFC_NVME_STE_LS_RCV;
3267 	axchg->entry_cnt = 1;
3268 	axchg->rqb_buffer = (void *)nvmebuf;
3269 	axchg->hdwq = &phba->sli4_hba.hdwq[0];
3270 	axchg->payload = nvmebuf->dbuf.virt;
3271 	INIT_LIST_HEAD(&axchg->list);
3272 
3273 	if (phba->nvmet_support) {
3274 		ret = lpfc_nvmet_handle_lsreq(phba, axchg);
3275 		spin_lock_irq(&ndlp->lock);
3276 		if (!ret && !(ndlp->fc4_xpt_flags & NLP_XPT_HAS_HH)) {
3277 			ndlp->fc4_xpt_flags |= NLP_XPT_HAS_HH;
3278 			spin_unlock_irq(&ndlp->lock);
3279 
3280 			/* This reference is a single occurrence to hold the
3281 			 * node valid until the nvmet transport calls
3282 			 * host_release.
3283 			 */
3284 			if (!lpfc_nlp_get(ndlp))
3285 				goto out_fail;
3286 
3287 			lpfc_printf_log(phba, KERN_ERR, LOG_NODE,
3288 					"6206 NVMET unsol ls_req ndlp x%px "
3289 					"DID x%x xflags x%x refcnt %d\n",
3290 					ndlp, ndlp->nlp_DID,
3291 					ndlp->fc4_xpt_flags,
3292 					kref_read(&ndlp->kref));
3293 		} else {
3294 			spin_unlock_irq(&ndlp->lock);
3295 		}
3296 	} else {
3297 		ret = lpfc_nvme_handle_lsreq(phba, axchg);
3298 	}
3299 
3300 	/* if zero, LS was successfully handled. If non-zero, LS not handled */
3301 	if (!ret)
3302 		return;
3303 
3304 out_fail:
3305 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3306 			"6155 Drop NVME LS from DID %06X: SID %06X OXID x%X "
3307 			"NVMe%s handler failed %d\n",
3308 			did, sid, oxid,
3309 			(phba->nvmet_support) ? "T" : "I", ret);
3310 
3311 	/* recycle receive buffer */
3312 	lpfc_in_buf_free(phba, &nvmebuf->dbuf);
3313 
3314 	/* If start of new exchange, abort it */
3315 	if (axchg && (fctl & FC_FC_FIRST_SEQ && !(fctl & FC_FC_EX_CTX)))
3316 		ret = lpfc_nvme_unsol_ls_issue_abort(phba, axchg, sid, oxid);
3317 
3318 	if (ret)
3319 		kfree(axchg);
3320 }
3321 
3322 /**
3323  * lpfc_complete_unsol_iocb - Complete an unsolicited sequence
3324  * @phba: Pointer to HBA context object.
3325  * @pring: Pointer to driver SLI ring object.
3326  * @saveq: Pointer to the iocbq struct representing the sequence starting frame.
3327  * @fch_r_ctl: the r_ctl for the first frame of the sequence.
3328  * @fch_type: the type for the first frame of the sequence.
3329  *
3330  * This function is called with no lock held. This function uses the r_ctl and
3331  * type of the received sequence to find the correct callback function to call
3332  * to process the sequence.
3333  **/
3334 static int
3335 lpfc_complete_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3336 			 struct lpfc_iocbq *saveq, uint32_t fch_r_ctl,
3337 			 uint32_t fch_type)
3338 {
3339 	int i;
3340 
3341 	switch (fch_type) {
3342 	case FC_TYPE_NVME:
3343 		lpfc_nvme_unsol_ls_handler(phba, saveq);
3344 		return 1;
3345 	default:
3346 		break;
3347 	}
3348 
3349 	/* unSolicited Responses */
3350 	if (pring->prt[0].profile) {
3351 		if (pring->prt[0].lpfc_sli_rcv_unsol_event)
3352 			(pring->prt[0].lpfc_sli_rcv_unsol_event) (phba, pring,
3353 									saveq);
3354 		return 1;
3355 	}
3356 	/* We must search, based on rctl / type
3357 	   for the right routine */
3358 	for (i = 0; i < pring->num_mask; i++) {
3359 		if ((pring->prt[i].rctl == fch_r_ctl) &&
3360 		    (pring->prt[i].type == fch_type)) {
3361 			if (pring->prt[i].lpfc_sli_rcv_unsol_event)
3362 				(pring->prt[i].lpfc_sli_rcv_unsol_event)
3363 						(phba, pring, saveq);
3364 			return 1;
3365 		}
3366 	}
3367 	return 0;
3368 }
3369 
3370 static void
3371 lpfc_sli_prep_unsol_wqe(struct lpfc_hba *phba,
3372 			struct lpfc_iocbq *saveq)
3373 {
3374 	IOCB_t *irsp;
3375 	union lpfc_wqe128 *wqe;
3376 	u16 i = 0;
3377 
3378 	irsp = &saveq->iocb;
3379 	wqe = &saveq->wqe;
3380 
3381 	/* Fill wcqe with the IOCB status fields */
3382 	bf_set(lpfc_wcqe_c_status, &saveq->wcqe_cmpl, irsp->ulpStatus);
3383 	saveq->wcqe_cmpl.word3 = irsp->ulpBdeCount;
3384 	saveq->wcqe_cmpl.parameter = irsp->un.ulpWord[4];
3385 	saveq->wcqe_cmpl.total_data_placed = irsp->unsli3.rcvsli3.acc_len;
3386 
3387 	/* Source ID */
3388 	bf_set(els_rsp64_sid, &wqe->xmit_els_rsp, irsp->un.rcvels.parmRo);
3389 
3390 	/* rx-id of the response frame */
3391 	bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com, irsp->ulpContext);
3392 
3393 	/* ox-id of the frame */
3394 	bf_set(wqe_rcvoxid, &wqe->xmit_els_rsp.wqe_com,
3395 	       irsp->unsli3.rcvsli3.ox_id);
3396 
3397 	/* DID */
3398 	bf_set(wqe_els_did, &wqe->xmit_els_rsp.wqe_dest,
3399 	       irsp->un.rcvels.remoteID);
3400 
3401 	/* unsol data len */
3402 	for (i = 0; i < irsp->ulpBdeCount; i++) {
3403 		struct lpfc_hbq_entry *hbqe = NULL;
3404 
3405 		if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
3406 			if (i == 0) {
3407 				hbqe = (struct lpfc_hbq_entry *)
3408 					&irsp->un.ulpWord[0];
3409 				saveq->wqe.gen_req.bde.tus.f.bdeSize =
3410 					hbqe->bde.tus.f.bdeSize;
3411 			} else if (i == 1) {
3412 				hbqe = (struct lpfc_hbq_entry *)
3413 					&irsp->unsli3.sli3Words[4];
3414 				saveq->unsol_rcv_len = hbqe->bde.tus.f.bdeSize;
3415 			}
3416 		}
3417 	}
3418 }
3419 
3420 /**
3421  * lpfc_sli_process_unsol_iocb - Unsolicited iocb handler
3422  * @phba: Pointer to HBA context object.
3423  * @pring: Pointer to driver SLI ring object.
3424  * @saveq: Pointer to the unsolicited iocb.
3425  *
3426  * This function is called with no lock held by the ring event handler
3427  * when there is an unsolicited iocb posted to the response ring by the
3428  * firmware. This function gets the buffer associated with the iocbs
3429  * and calls the event handler for the ring. This function handles both
3430  * qring buffers and hbq buffers.
3431  * When the function returns 1 the caller can free the iocb object otherwise
3432  * upper layer functions will free the iocb objects.
3433  **/
3434 static int
3435 lpfc_sli_process_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3436 			    struct lpfc_iocbq *saveq)
3437 {
3438 	IOCB_t           * irsp;
3439 	WORD5            * w5p;
3440 	dma_addr_t	 paddr;
3441 	uint32_t           Rctl, Type;
3442 	struct lpfc_iocbq *iocbq;
3443 	struct lpfc_dmabuf *dmzbuf;
3444 
3445 	irsp = &saveq->iocb;
3446 	saveq->vport = phba->pport;
3447 
3448 	if (irsp->ulpCommand == CMD_ASYNC_STATUS) {
3449 		if (pring->lpfc_sli_rcv_async_status)
3450 			pring->lpfc_sli_rcv_async_status(phba, pring, saveq);
3451 		else
3452 			lpfc_printf_log(phba,
3453 					KERN_WARNING,
3454 					LOG_SLI,
3455 					"0316 Ring %d handler: unexpected "
3456 					"ASYNC_STATUS iocb received evt_code "
3457 					"0x%x\n",
3458 					pring->ringno,
3459 					irsp->un.asyncstat.evt_code);
3460 		return 1;
3461 	}
3462 
3463 	if ((irsp->ulpCommand == CMD_IOCB_RET_XRI64_CX) &&
3464 	    (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)) {
3465 		if (irsp->ulpBdeCount > 0) {
3466 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3467 						   irsp->un.ulpWord[3]);
3468 			lpfc_in_buf_free(phba, dmzbuf);
3469 		}
3470 
3471 		if (irsp->ulpBdeCount > 1) {
3472 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3473 						   irsp->unsli3.sli3Words[3]);
3474 			lpfc_in_buf_free(phba, dmzbuf);
3475 		}
3476 
3477 		if (irsp->ulpBdeCount > 2) {
3478 			dmzbuf = lpfc_sli_get_buff(phba, pring,
3479 						   irsp->unsli3.sli3Words[7]);
3480 			lpfc_in_buf_free(phba, dmzbuf);
3481 		}
3482 
3483 		return 1;
3484 	}
3485 
3486 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
3487 		if (irsp->ulpBdeCount != 0) {
3488 			saveq->cmd_dmabuf = lpfc_sli_get_buff(phba, pring,
3489 						irsp->un.ulpWord[3]);
3490 			if (!saveq->cmd_dmabuf)
3491 				lpfc_printf_log(phba,
3492 					KERN_ERR,
3493 					LOG_SLI,
3494 					"0341 Ring %d Cannot find buffer for "
3495 					"an unsolicited iocb. tag 0x%x\n",
3496 					pring->ringno,
3497 					irsp->un.ulpWord[3]);
3498 		}
3499 		if (irsp->ulpBdeCount == 2) {
3500 			saveq->bpl_dmabuf = lpfc_sli_get_buff(phba, pring,
3501 						irsp->unsli3.sli3Words[7]);
3502 			if (!saveq->bpl_dmabuf)
3503 				lpfc_printf_log(phba,
3504 					KERN_ERR,
3505 					LOG_SLI,
3506 					"0342 Ring %d Cannot find buffer for an"
3507 					" unsolicited iocb. tag 0x%x\n",
3508 					pring->ringno,
3509 					irsp->unsli3.sli3Words[7]);
3510 		}
3511 		list_for_each_entry(iocbq, &saveq->list, list) {
3512 			irsp = &iocbq->iocb;
3513 			if (irsp->ulpBdeCount != 0) {
3514 				iocbq->cmd_dmabuf = lpfc_sli_get_buff(phba,
3515 							pring,
3516 							irsp->un.ulpWord[3]);
3517 				if (!iocbq->cmd_dmabuf)
3518 					lpfc_printf_log(phba,
3519 						KERN_ERR,
3520 						LOG_SLI,
3521 						"0343 Ring %d Cannot find "
3522 						"buffer for an unsolicited iocb"
3523 						". tag 0x%x\n", pring->ringno,
3524 						irsp->un.ulpWord[3]);
3525 			}
3526 			if (irsp->ulpBdeCount == 2) {
3527 				iocbq->bpl_dmabuf = lpfc_sli_get_buff(phba,
3528 						pring,
3529 						irsp->unsli3.sli3Words[7]);
3530 				if (!iocbq->bpl_dmabuf)
3531 					lpfc_printf_log(phba,
3532 						KERN_ERR,
3533 						LOG_SLI,
3534 						"0344 Ring %d Cannot find "
3535 						"buffer for an unsolicited "
3536 						"iocb. tag 0x%x\n",
3537 						pring->ringno,
3538 						irsp->unsli3.sli3Words[7]);
3539 			}
3540 		}
3541 	} else {
3542 		paddr = getPaddr(irsp->un.cont64[0].addrHigh,
3543 				 irsp->un.cont64[0].addrLow);
3544 		saveq->cmd_dmabuf = lpfc_sli_ringpostbuf_get(phba, pring,
3545 							     paddr);
3546 		if (irsp->ulpBdeCount == 2) {
3547 			paddr = getPaddr(irsp->un.cont64[1].addrHigh,
3548 					 irsp->un.cont64[1].addrLow);
3549 			saveq->bpl_dmabuf = lpfc_sli_ringpostbuf_get(phba,
3550 								   pring,
3551 								   paddr);
3552 		}
3553 	}
3554 
3555 	if (irsp->ulpBdeCount != 0 &&
3556 	    (irsp->ulpCommand == CMD_IOCB_RCV_CONT64_CX ||
3557 	     irsp->ulpStatus == IOSTAT_INTERMED_RSP)) {
3558 		int found = 0;
3559 
3560 		/* search continue save q for same XRI */
3561 		list_for_each_entry(iocbq, &pring->iocb_continue_saveq, clist) {
3562 			if (iocbq->iocb.unsli3.rcvsli3.ox_id ==
3563 				saveq->iocb.unsli3.rcvsli3.ox_id) {
3564 				list_add_tail(&saveq->list, &iocbq->list);
3565 				found = 1;
3566 				break;
3567 			}
3568 		}
3569 		if (!found)
3570 			list_add_tail(&saveq->clist,
3571 				      &pring->iocb_continue_saveq);
3572 
3573 		if (saveq->iocb.ulpStatus != IOSTAT_INTERMED_RSP) {
3574 			list_del_init(&iocbq->clist);
3575 			saveq = iocbq;
3576 			irsp = &saveq->iocb;
3577 		} else {
3578 			return 0;
3579 		}
3580 	}
3581 	if ((irsp->ulpCommand == CMD_RCV_ELS_REQ64_CX) ||
3582 	    (irsp->ulpCommand == CMD_RCV_ELS_REQ_CX) ||
3583 	    (irsp->ulpCommand == CMD_IOCB_RCV_ELS64_CX)) {
3584 		Rctl = FC_RCTL_ELS_REQ;
3585 		Type = FC_TYPE_ELS;
3586 	} else {
3587 		w5p = (WORD5 *)&(saveq->iocb.un.ulpWord[5]);
3588 		Rctl = w5p->hcsw.Rctl;
3589 		Type = w5p->hcsw.Type;
3590 
3591 		/* Firmware Workaround */
3592 		if ((Rctl == 0) && (pring->ringno == LPFC_ELS_RING) &&
3593 			(irsp->ulpCommand == CMD_RCV_SEQUENCE64_CX ||
3594 			 irsp->ulpCommand == CMD_IOCB_RCV_SEQ64_CX)) {
3595 			Rctl = FC_RCTL_ELS_REQ;
3596 			Type = FC_TYPE_ELS;
3597 			w5p->hcsw.Rctl = Rctl;
3598 			w5p->hcsw.Type = Type;
3599 		}
3600 	}
3601 
3602 	if ((phba->sli3_options & LPFC_SLI3_NPIV_ENABLED) &&
3603 	    (irsp->ulpCommand == CMD_IOCB_RCV_ELS64_CX ||
3604 	    irsp->ulpCommand == CMD_IOCB_RCV_SEQ64_CX)) {
3605 		if (irsp->unsli3.rcvsli3.vpi == 0xffff)
3606 			saveq->vport = phba->pport;
3607 		else
3608 			saveq->vport = lpfc_find_vport_by_vpid(phba,
3609 					       irsp->unsli3.rcvsli3.vpi);
3610 	}
3611 
3612 	/* Prepare WQE with Unsol frame */
3613 	lpfc_sli_prep_unsol_wqe(phba, saveq);
3614 
3615 	if (!lpfc_complete_unsol_iocb(phba, pring, saveq, Rctl, Type))
3616 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3617 				"0313 Ring %d handler: unexpected Rctl x%x "
3618 				"Type x%x received\n",
3619 				pring->ringno, Rctl, Type);
3620 
3621 	return 1;
3622 }
3623 
3624 /**
3625  * lpfc_sli_iocbq_lookup - Find command iocb for the given response iocb
3626  * @phba: Pointer to HBA context object.
3627  * @pring: Pointer to driver SLI ring object.
3628  * @prspiocb: Pointer to response iocb object.
3629  *
3630  * This function looks up the iocb_lookup table to get the command iocb
3631  * corresponding to the given response iocb using the iotag of the
3632  * response iocb. The driver calls this function with the hbalock held
3633  * for SLI3 ports or the ring lock held for SLI4 ports.
3634  * This function returns the command iocb object if it finds the command
3635  * iocb else returns NULL.
3636  **/
3637 static struct lpfc_iocbq *
3638 lpfc_sli_iocbq_lookup(struct lpfc_hba *phba,
3639 		      struct lpfc_sli_ring *pring,
3640 		      struct lpfc_iocbq *prspiocb)
3641 {
3642 	struct lpfc_iocbq *cmd_iocb = NULL;
3643 	u16 iotag;
3644 
3645 	if (phba->sli_rev == LPFC_SLI_REV4)
3646 		iotag = get_wqe_reqtag(prspiocb);
3647 	else
3648 		iotag = prspiocb->iocb.ulpIoTag;
3649 
3650 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3651 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
3652 		if (cmd_iocb->cmd_flag & LPFC_IO_ON_TXCMPLQ) {
3653 			/* remove from txcmpl queue list */
3654 			list_del_init(&cmd_iocb->list);
3655 			cmd_iocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
3656 			pring->txcmplq_cnt--;
3657 			return cmd_iocb;
3658 		}
3659 	}
3660 
3661 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3662 			"0317 iotag x%x is out of "
3663 			"range: max iotag x%x\n",
3664 			iotag, phba->sli.last_iotag);
3665 	return NULL;
3666 }
3667 
3668 /**
3669  * lpfc_sli_iocbq_lookup_by_tag - Find command iocb for the iotag
3670  * @phba: Pointer to HBA context object.
3671  * @pring: Pointer to driver SLI ring object.
3672  * @iotag: IOCB tag.
3673  *
3674  * This function looks up the iocb_lookup table to get the command iocb
3675  * corresponding to the given iotag. The driver calls this function with
3676  * the ring lock held because this function is an SLI4 port only helper.
3677  * This function returns the command iocb object if it finds the command
3678  * iocb else returns NULL.
3679  **/
3680 static struct lpfc_iocbq *
3681 lpfc_sli_iocbq_lookup_by_tag(struct lpfc_hba *phba,
3682 			     struct lpfc_sli_ring *pring, uint16_t iotag)
3683 {
3684 	struct lpfc_iocbq *cmd_iocb = NULL;
3685 
3686 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3687 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
3688 		if (cmd_iocb->cmd_flag & LPFC_IO_ON_TXCMPLQ) {
3689 			/* remove from txcmpl queue list */
3690 			list_del_init(&cmd_iocb->list);
3691 			cmd_iocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
3692 			pring->txcmplq_cnt--;
3693 			return cmd_iocb;
3694 		}
3695 	}
3696 
3697 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3698 			"0372 iotag x%x lookup error: max iotag (x%x) "
3699 			"cmd_flag x%x\n",
3700 			iotag, phba->sli.last_iotag,
3701 			cmd_iocb ? cmd_iocb->cmd_flag : 0xffff);
3702 	return NULL;
3703 }
3704 
3705 /**
3706  * lpfc_sli_process_sol_iocb - process solicited iocb completion
3707  * @phba: Pointer to HBA context object.
3708  * @pring: Pointer to driver SLI ring object.
3709  * @saveq: Pointer to the response iocb to be processed.
3710  *
3711  * This function is called by the ring event handler for non-fcp
3712  * rings when there is a new response iocb in the response ring.
3713  * The caller is not required to hold any locks. This function
3714  * gets the command iocb associated with the response iocb and
3715  * calls the completion handler for the command iocb. If there
3716  * is no completion handler, the function will free the resources
3717  * associated with command iocb. If the response iocb is for
3718  * an already aborted command iocb, the status of the completion
3719  * is changed to IOSTAT_LOCAL_REJECT/IOERR_SLI_ABORTED.
3720  * This function always returns 1.
3721  **/
3722 static int
3723 lpfc_sli_process_sol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3724 			  struct lpfc_iocbq *saveq)
3725 	__context_unsafe(/*conditional locking*/)
3726 {
3727 	struct lpfc_iocbq *cmdiocbp;
3728 	unsigned long iflag;
3729 	u32 ulp_command, ulp_status, ulp_word4, ulp_context, iotag;
3730 
3731 	if (phba->sli_rev == LPFC_SLI_REV4)
3732 		spin_lock_irqsave(&pring->ring_lock, iflag);
3733 	else
3734 		spin_lock_irqsave(&phba->hbalock, iflag);
3735 	cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring, saveq);
3736 	if (phba->sli_rev == LPFC_SLI_REV4)
3737 		spin_unlock_irqrestore(&pring->ring_lock, iflag);
3738 	else
3739 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3740 
3741 	ulp_command = get_job_cmnd(phba, saveq);
3742 	ulp_status = get_job_ulpstatus(phba, saveq);
3743 	ulp_word4 = get_job_word4(phba, saveq);
3744 	ulp_context = get_job_ulpcontext(phba, saveq);
3745 	if (phba->sli_rev == LPFC_SLI_REV4)
3746 		iotag = get_wqe_reqtag(saveq);
3747 	else
3748 		iotag = saveq->iocb.ulpIoTag;
3749 
3750 	if (cmdiocbp) {
3751 		ulp_command = get_job_cmnd(phba, cmdiocbp);
3752 		if (cmdiocbp->cmd_cmpl) {
3753 			/*
3754 			 * If an ELS command failed send an event to mgmt
3755 			 * application.
3756 			 */
3757 			if (ulp_status &&
3758 			     (pring->ringno == LPFC_ELS_RING) &&
3759 			     (ulp_command == CMD_ELS_REQUEST64_CR))
3760 				lpfc_send_els_failure_event(phba,
3761 					cmdiocbp, saveq);
3762 
3763 			/*
3764 			 * Post all ELS completions to the worker thread.
3765 			 * All other are passed to the completion callback.
3766 			 */
3767 			if (pring->ringno == LPFC_ELS_RING) {
3768 				if ((phba->sli_rev < LPFC_SLI_REV4) &&
3769 				    (cmdiocbp->cmd_flag &
3770 							LPFC_DRIVER_ABORTED)) {
3771 					spin_lock_irqsave(&phba->hbalock,
3772 							  iflag);
3773 					cmdiocbp->cmd_flag &=
3774 						~LPFC_DRIVER_ABORTED;
3775 					spin_unlock_irqrestore(&phba->hbalock,
3776 							       iflag);
3777 					saveq->iocb.ulpStatus =
3778 						IOSTAT_LOCAL_REJECT;
3779 					saveq->iocb.un.ulpWord[4] =
3780 						IOERR_SLI_ABORTED;
3781 
3782 					/* Firmware could still be in progress
3783 					 * of DMAing payload, so don't free data
3784 					 * buffer till after a hbeat.
3785 					 */
3786 					spin_lock_irqsave(&phba->hbalock,
3787 							  iflag);
3788 					saveq->cmd_flag |= LPFC_DELAY_MEM_FREE;
3789 					spin_unlock_irqrestore(&phba->hbalock,
3790 							       iflag);
3791 				}
3792 				if (phba->sli_rev == LPFC_SLI_REV4) {
3793 					if (saveq->cmd_flag &
3794 					    LPFC_EXCHANGE_BUSY) {
3795 						/* Set cmdiocb flag for the
3796 						 * exchange busy so sgl (xri)
3797 						 * will not be released until
3798 						 * the abort xri is received
3799 						 * from hba.
3800 						 */
3801 						spin_lock_irqsave(
3802 							&phba->hbalock, iflag);
3803 						cmdiocbp->cmd_flag |=
3804 							LPFC_EXCHANGE_BUSY;
3805 						spin_unlock_irqrestore(
3806 							&phba->hbalock, iflag);
3807 					}
3808 					if (cmdiocbp->cmd_flag &
3809 					    LPFC_DRIVER_ABORTED) {
3810 						/*
3811 						 * Clear LPFC_DRIVER_ABORTED
3812 						 * bit in case it was driver
3813 						 * initiated abort.
3814 						 */
3815 						spin_lock_irqsave(
3816 							&phba->hbalock, iflag);
3817 						cmdiocbp->cmd_flag &=
3818 							~LPFC_DRIVER_ABORTED;
3819 						spin_unlock_irqrestore(
3820 							&phba->hbalock, iflag);
3821 						set_job_ulpstatus(cmdiocbp,
3822 								  IOSTAT_LOCAL_REJECT);
3823 						set_job_ulpword4(cmdiocbp,
3824 								 IOERR_ABORT_REQUESTED);
3825 						/*
3826 						 * For SLI4, irspiocb contains
3827 						 * NO_XRI in sli_xritag, it
3828 						 * shall not affect releasing
3829 						 * sgl (xri) process.
3830 						 */
3831 						set_job_ulpstatus(saveq,
3832 								  IOSTAT_LOCAL_REJECT);
3833 						set_job_ulpword4(saveq,
3834 								 IOERR_SLI_ABORTED);
3835 						spin_lock_irqsave(
3836 							&phba->hbalock, iflag);
3837 						saveq->cmd_flag |=
3838 							LPFC_DELAY_MEM_FREE;
3839 						spin_unlock_irqrestore(
3840 							&phba->hbalock, iflag);
3841 					}
3842 				}
3843 			}
3844 			cmdiocbp->cmd_cmpl(phba, cmdiocbp, saveq);
3845 		} else
3846 			lpfc_sli_release_iocbq(phba, cmdiocbp);
3847 	} else {
3848 		/*
3849 		 * Unknown initiating command based on the response iotag.
3850 		 * This could be the case on the ELS ring because of
3851 		 * lpfc_els_abort().
3852 		 */
3853 		if (pring->ringno != LPFC_ELS_RING) {
3854 			/*
3855 			 * Ring <ringno> handler: unexpected completion IoTag
3856 			 * <IoTag>
3857 			 */
3858 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3859 					 "0322 Ring %d handler: "
3860 					 "unexpected completion IoTag x%x "
3861 					 "Data: x%x x%x x%x x%x\n",
3862 					 pring->ringno, iotag, ulp_status,
3863 					 ulp_word4, ulp_command, ulp_context);
3864 		}
3865 	}
3866 
3867 	return 1;
3868 }
3869 
3870 /**
3871  * lpfc_sli_rsp_pointers_error - Response ring pointer error handler
3872  * @phba: Pointer to HBA context object.
3873  * @pring: Pointer to driver SLI ring object.
3874  *
3875  * This function is called from the iocb ring event handlers when
3876  * put pointer is ahead of the get pointer for a ring. This function signal
3877  * an error attention condition to the worker thread and the worker
3878  * thread will transition the HBA to offline state.
3879  **/
3880 static void
3881 lpfc_sli_rsp_pointers_error(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
3882 {
3883 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3884 	/*
3885 	 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
3886 	 * rsp ring <portRspMax>
3887 	 */
3888 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3889 			"0312 Ring %d handler: portRspPut %d "
3890 			"is bigger than rsp ring %d\n",
3891 			pring->ringno, le32_to_cpu(pgp->rspPutInx),
3892 			pring->sli.sli3.numRiocb);
3893 
3894 	phba->link_state = LPFC_HBA_ERROR;
3895 
3896 	/*
3897 	 * All error attention handlers are posted to
3898 	 * worker thread
3899 	 */
3900 	phba->work_ha |= HA_ERATT;
3901 	phba->work_hs = HS_FFER3;
3902 
3903 	lpfc_worker_wake_up(phba);
3904 
3905 	return;
3906 }
3907 
3908 /**
3909  * lpfc_poll_eratt - Error attention polling timer timeout handler
3910  * @t: Context to fetch pointer to address of HBA context object from.
3911  *
3912  * This function is invoked by the Error Attention polling timer when the
3913  * timer times out. It will check the SLI Error Attention register for
3914  * possible attention events. If so, it will post an Error Attention event
3915  * and wake up worker thread to process it. Otherwise, it will set up the
3916  * Error Attention polling timer for the next poll.
3917  **/
3918 void lpfc_poll_eratt(struct timer_list *t)
3919 {
3920 	struct lpfc_hba *phba;
3921 	uint32_t eratt = 0;
3922 	uint64_t sli_intr, cnt;
3923 
3924 	phba = timer_container_of(phba, t, eratt_poll);
3925 
3926 	if (test_bit(FC_UNLOADING, &phba->pport->load_flag))
3927 		return;
3928 
3929 	if (phba->sli_rev == LPFC_SLI_REV4 &&
3930 	    !test_bit(HBA_SETUP, &phba->hba_flag)) {
3931 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3932 				"0663 HBA still initializing 0x%lx, restart "
3933 				"timer\n",
3934 				phba->hba_flag);
3935 		goto restart_timer;
3936 	}
3937 
3938 	/* Here we will also keep track of interrupts per sec of the hba */
3939 	sli_intr = phba->sli.slistat.sli_intr;
3940 
3941 	if (phba->sli.slistat.sli_prev_intr > sli_intr)
3942 		cnt = (((uint64_t)(-1) - phba->sli.slistat.sli_prev_intr) +
3943 			sli_intr);
3944 	else
3945 		cnt = (sli_intr - phba->sli.slistat.sli_prev_intr);
3946 
3947 	/* 64-bit integer division not supported on 32-bit x86 - use do_div */
3948 	do_div(cnt, phba->eratt_poll_interval);
3949 	phba->sli.slistat.sli_ips = cnt;
3950 
3951 	phba->sli.slistat.sli_prev_intr = sli_intr;
3952 
3953 	/* Check chip HA register for error event */
3954 	eratt = lpfc_sli_check_eratt(phba);
3955 
3956 	if (eratt) {
3957 		/* Tell the worker thread there is work to do */
3958 		lpfc_worker_wake_up(phba);
3959 		return;
3960 	}
3961 
3962 restart_timer:
3963 	/* Restart the timer for next eratt poll */
3964 	mod_timer(&phba->eratt_poll,
3965 		  jiffies + secs_to_jiffies(phba->eratt_poll_interval));
3966 	return;
3967 }
3968 
3969 
3970 /**
3971  * lpfc_sli_handle_fast_ring_event - Handle ring events on FCP ring
3972  * @phba: Pointer to HBA context object.
3973  * @pring: Pointer to driver SLI ring object.
3974  * @mask: Host attention register mask for this ring.
3975  *
3976  * This function is called from the interrupt context when there is a ring
3977  * event for the fcp ring. The caller does not hold any lock.
3978  * The function processes each response iocb in the response ring until it
3979  * finds an iocb with LE bit set and chains all the iocbs up to the iocb with
3980  * LE bit set. The function will call the completion handler of the command iocb
3981  * if the response iocb indicates a completion for a command iocb or it is
3982  * an abort completion. The function will call lpfc_sli_process_unsol_iocb
3983  * function if this is an unsolicited iocb.
3984  * This routine presumes LPFC_FCP_RING handling and doesn't bother
3985  * to check it explicitly.
3986  */
3987 int
3988 lpfc_sli_handle_fast_ring_event(struct lpfc_hba *phba,
3989 				struct lpfc_sli_ring *pring, uint32_t mask)
3990 {
3991 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3992 	IOCB_t *irsp = NULL;
3993 	IOCB_t *entry = NULL;
3994 	struct lpfc_iocbq *cmdiocbq = NULL;
3995 	struct lpfc_iocbq rspiocbq;
3996 	uint32_t status;
3997 	uint32_t portRspPut, portRspMax;
3998 	int rc = 1;
3999 	lpfc_iocb_type type;
4000 	unsigned long iflag;
4001 	uint32_t rsp_cmpl = 0;
4002 
4003 	spin_lock_irqsave(&phba->hbalock, iflag);
4004 	pring->stats.iocb_event++;
4005 
4006 	/*
4007 	 * The next available response entry should never exceed the maximum
4008 	 * entries.  If it does, treat it as an adapter hardware error.
4009 	 */
4010 	portRspMax = pring->sli.sli3.numRiocb;
4011 	portRspPut = le32_to_cpu(pgp->rspPutInx);
4012 	if (unlikely(portRspPut >= portRspMax)) {
4013 		lpfc_sli_rsp_pointers_error(phba, pring);
4014 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4015 		return 1;
4016 	}
4017 	if (phba->fcp_ring_in_use) {
4018 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4019 		return 1;
4020 	} else
4021 		phba->fcp_ring_in_use = 1;
4022 
4023 	rmb();
4024 	while (pring->sli.sli3.rspidx != portRspPut) {
4025 		/*
4026 		 * Fetch an entry off the ring and copy it into a local data
4027 		 * structure.  The copy involves a byte-swap since the
4028 		 * network byte order and pci byte orders are different.
4029 		 */
4030 		entry = lpfc_resp_iocb(phba, pring);
4031 		phba->last_completion_time = jiffies;
4032 
4033 		if (++pring->sli.sli3.rspidx >= portRspMax)
4034 			pring->sli.sli3.rspidx = 0;
4035 
4036 		lpfc_sli_pcimem_bcopy((uint32_t *) entry,
4037 				      (uint32_t *) &rspiocbq.iocb,
4038 				      phba->iocb_rsp_size);
4039 		INIT_LIST_HEAD(&(rspiocbq.list));
4040 		irsp = &rspiocbq.iocb;
4041 
4042 		type = lpfc_sli_iocb_cmd_type(irsp->ulpCommand & CMD_IOCB_MASK);
4043 		pring->stats.iocb_rsp++;
4044 		rsp_cmpl++;
4045 
4046 		if (unlikely(irsp->ulpStatus)) {
4047 			/*
4048 			 * If resource errors reported from HBA, reduce
4049 			 * queuedepths of the SCSI device.
4050 			 */
4051 			if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
4052 			    ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
4053 			     IOERR_NO_RESOURCES)) {
4054 				spin_unlock_irqrestore(&phba->hbalock, iflag);
4055 				phba->lpfc_rampdown_queue_depth(phba);
4056 				spin_lock_irqsave(&phba->hbalock, iflag);
4057 			}
4058 
4059 			/* Rsp ring <ringno> error: IOCB */
4060 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
4061 					"0336 Rsp Ring %d error: IOCB Data: "
4062 					"x%x x%x x%x x%x x%x x%x x%x x%x\n",
4063 					pring->ringno,
4064 					irsp->un.ulpWord[0],
4065 					irsp->un.ulpWord[1],
4066 					irsp->un.ulpWord[2],
4067 					irsp->un.ulpWord[3],
4068 					irsp->un.ulpWord[4],
4069 					irsp->un.ulpWord[5],
4070 					*(uint32_t *)&irsp->un1,
4071 					*((uint32_t *)&irsp->un1 + 1));
4072 		}
4073 
4074 		switch (type) {
4075 		case LPFC_ABORT_IOCB:
4076 		case LPFC_SOL_IOCB:
4077 			/*
4078 			 * Idle exchange closed via ABTS from port.  No iocb
4079 			 * resources need to be recovered.
4080 			 */
4081 			if (unlikely(irsp->ulpCommand == CMD_XRI_ABORTED_CX)) {
4082 				lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4083 						"0333 IOCB cmd 0x%x"
4084 						" processed. Skipping"
4085 						" completion\n",
4086 						irsp->ulpCommand);
4087 				break;
4088 			}
4089 
4090 			cmdiocbq = lpfc_sli_iocbq_lookup(phba, pring,
4091 							 &rspiocbq);
4092 			if (unlikely(!cmdiocbq))
4093 				break;
4094 			if (cmdiocbq->cmd_flag & LPFC_DRIVER_ABORTED)
4095 				cmdiocbq->cmd_flag &= ~LPFC_DRIVER_ABORTED;
4096 			if (cmdiocbq->cmd_cmpl) {
4097 				spin_unlock_irqrestore(&phba->hbalock, iflag);
4098 				cmdiocbq->cmd_cmpl(phba, cmdiocbq, &rspiocbq);
4099 				spin_lock_irqsave(&phba->hbalock, iflag);
4100 			}
4101 			break;
4102 		case LPFC_UNSOL_IOCB:
4103 			spin_unlock_irqrestore(&phba->hbalock, iflag);
4104 			lpfc_sli_process_unsol_iocb(phba, pring, &rspiocbq);
4105 			spin_lock_irqsave(&phba->hbalock, iflag);
4106 			break;
4107 		default:
4108 			if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
4109 				char adaptermsg[LPFC_MAX_ADPTMSG];
4110 				memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
4111 				memcpy(&adaptermsg[0], (uint8_t *) irsp,
4112 				       MAX_MSG_DATA);
4113 				dev_warn(&((phba->pcidev)->dev),
4114 					 "lpfc%d: %s\n",
4115 					 phba->brd_no, adaptermsg);
4116 			} else {
4117 				/* Unknown IOCB command */
4118 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4119 						"0334 Unknown IOCB command "
4120 						"Data: x%x, x%x x%x x%x x%x\n",
4121 						type, irsp->ulpCommand,
4122 						irsp->ulpStatus,
4123 						irsp->ulpIoTag,
4124 						irsp->ulpContext);
4125 			}
4126 			break;
4127 		}
4128 
4129 		/*
4130 		 * The response IOCB has been processed.  Update the ring
4131 		 * pointer in SLIM.  If the port response put pointer has not
4132 		 * been updated, sync the pgp->rspPutInx and fetch the new port
4133 		 * response put pointer.
4134 		 */
4135 		writel(pring->sli.sli3.rspidx,
4136 			&phba->host_gp[pring->ringno].rspGetInx);
4137 
4138 		if (pring->sli.sli3.rspidx == portRspPut)
4139 			portRspPut = le32_to_cpu(pgp->rspPutInx);
4140 	}
4141 
4142 	if ((rsp_cmpl > 0) && (mask & HA_R0RE_REQ)) {
4143 		pring->stats.iocb_rsp_full++;
4144 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
4145 		writel(status, phba->CAregaddr);
4146 		readl(phba->CAregaddr);
4147 	}
4148 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
4149 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
4150 		pring->stats.iocb_cmd_empty++;
4151 
4152 		/* Force update of the local copy of cmdGetInx */
4153 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
4154 		lpfc_sli_resume_iocb(phba, pring);
4155 
4156 		if ((pring->lpfc_sli_cmd_available))
4157 			(pring->lpfc_sli_cmd_available) (phba, pring);
4158 
4159 	}
4160 
4161 	phba->fcp_ring_in_use = 0;
4162 	spin_unlock_irqrestore(&phba->hbalock, iflag);
4163 	return rc;
4164 }
4165 
4166 /**
4167  * lpfc_sli_sp_handle_rspiocb - Handle slow-path response iocb
4168  * @phba: Pointer to HBA context object.
4169  * @pring: Pointer to driver SLI ring object.
4170  * @rspiocbp: Pointer to driver response IOCB object.
4171  *
4172  * This function is called from the worker thread when there is a slow-path
4173  * response IOCB to process. This function chains all the response iocbs until
4174  * seeing the iocb with the LE bit set. The function will call
4175  * lpfc_sli_process_sol_iocb function if the response iocb indicates a
4176  * completion of a command iocb. The function will call the
4177  * lpfc_sli_process_unsol_iocb function if this is an unsolicited iocb.
4178  * The function frees the resources or calls the completion handler if this
4179  * iocb is an abort completion. The function returns NULL when the response
4180  * iocb has the LE bit set and all the chained iocbs are processed, otherwise
4181  * this function shall chain the iocb on to the iocb_continueq and return the
4182  * response iocb passed in.
4183  **/
4184 static struct lpfc_iocbq *
4185 lpfc_sli_sp_handle_rspiocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
4186 			struct lpfc_iocbq *rspiocbp)
4187 {
4188 	struct lpfc_iocbq *saveq;
4189 	struct lpfc_iocbq *cmdiocb;
4190 	struct lpfc_iocbq *next_iocb;
4191 	IOCB_t *irsp;
4192 	uint32_t free_saveq;
4193 	u8 cmd_type;
4194 	lpfc_iocb_type type;
4195 	unsigned long iflag;
4196 	u32 ulp_status = get_job_ulpstatus(phba, rspiocbp);
4197 	u32 ulp_word4 = get_job_word4(phba, rspiocbp);
4198 	u32 ulp_command = get_job_cmnd(phba, rspiocbp);
4199 	int rc;
4200 
4201 	spin_lock_irqsave(&phba->hbalock, iflag);
4202 	/* First add the response iocb to the countinueq list */
4203 	list_add_tail(&rspiocbp->list, &pring->iocb_continueq);
4204 	pring->iocb_continueq_cnt++;
4205 
4206 	/*
4207 	 * By default, the driver expects to free all resources
4208 	 * associated with this iocb completion.
4209 	 */
4210 	free_saveq = 1;
4211 	saveq = list_get_first(&pring->iocb_continueq,
4212 			       struct lpfc_iocbq, list);
4213 	list_del_init(&pring->iocb_continueq);
4214 	pring->iocb_continueq_cnt = 0;
4215 
4216 	pring->stats.iocb_rsp++;
4217 
4218 	/*
4219 	 * If resource errors reported from HBA, reduce
4220 	 * queuedepths of the SCSI device.
4221 	 */
4222 	if (ulp_status == IOSTAT_LOCAL_REJECT &&
4223 	    ((ulp_word4 & IOERR_PARAM_MASK) ==
4224 	     IOERR_NO_RESOURCES)) {
4225 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4226 		phba->lpfc_rampdown_queue_depth(phba);
4227 		spin_lock_irqsave(&phba->hbalock, iflag);
4228 	}
4229 
4230 	if (ulp_status) {
4231 		/* Rsp ring <ringno> error: IOCB */
4232 		if (phba->sli_rev < LPFC_SLI_REV4) {
4233 			irsp = &rspiocbp->iocb;
4234 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
4235 					"0328 Rsp Ring %d error: ulp_status x%x "
4236 					"IOCB Data: "
4237 					"x%08x x%08x x%08x x%08x "
4238 					"x%08x x%08x x%08x x%08x "
4239 					"x%08x x%08x x%08x x%08x "
4240 					"x%08x x%08x x%08x x%08x\n",
4241 					pring->ringno, ulp_status,
4242 					get_job_ulpword(rspiocbp, 0),
4243 					get_job_ulpword(rspiocbp, 1),
4244 					get_job_ulpword(rspiocbp, 2),
4245 					get_job_ulpword(rspiocbp, 3),
4246 					get_job_ulpword(rspiocbp, 4),
4247 					get_job_ulpword(rspiocbp, 5),
4248 					*(((uint32_t *)irsp) + 6),
4249 					*(((uint32_t *)irsp) + 7),
4250 					*(((uint32_t *)irsp) + 8),
4251 					*(((uint32_t *)irsp) + 9),
4252 					*(((uint32_t *)irsp) + 10),
4253 					*(((uint32_t *)irsp) + 11),
4254 					*(((uint32_t *)irsp) + 12),
4255 					*(((uint32_t *)irsp) + 13),
4256 					*(((uint32_t *)irsp) + 14),
4257 					*(((uint32_t *)irsp) + 15));
4258 		} else {
4259 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
4260 					"0321 Rsp Ring %d error: "
4261 					"IOCB Data: "
4262 					"x%x x%x x%x x%x\n",
4263 					pring->ringno,
4264 					rspiocbp->wcqe_cmpl.word0,
4265 					rspiocbp->wcqe_cmpl.total_data_placed,
4266 					rspiocbp->wcqe_cmpl.parameter,
4267 					rspiocbp->wcqe_cmpl.word3);
4268 		}
4269 	}
4270 
4271 
4272 	/*
4273 	 * Fetch the iocb command type and call the correct completion
4274 	 * routine. Solicited and Unsolicited IOCBs on the ELS ring
4275 	 * get freed back to the lpfc_iocb_list by the discovery
4276 	 * kernel thread.
4277 	 */
4278 	cmd_type = ulp_command & CMD_IOCB_MASK;
4279 	type = lpfc_sli_iocb_cmd_type(cmd_type);
4280 	switch (type) {
4281 	case LPFC_SOL_IOCB:
4282 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4283 		rc = lpfc_sli_process_sol_iocb(phba, pring, saveq);
4284 		spin_lock_irqsave(&phba->hbalock, iflag);
4285 		break;
4286 	case LPFC_UNSOL_IOCB:
4287 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4288 		rc = lpfc_sli_process_unsol_iocb(phba, pring, saveq);
4289 		spin_lock_irqsave(&phba->hbalock, iflag);
4290 		if (!rc)
4291 			free_saveq = 0;
4292 		break;
4293 	case LPFC_ABORT_IOCB:
4294 		cmdiocb = NULL;
4295 		if (ulp_command != CMD_XRI_ABORTED_CX)
4296 			cmdiocb = lpfc_sli_iocbq_lookup(phba, pring,
4297 							saveq);
4298 		if (cmdiocb) {
4299 			/* Call the specified completion routine */
4300 			if (cmdiocb->cmd_cmpl) {
4301 				spin_unlock_irqrestore(&phba->hbalock, iflag);
4302 				cmdiocb->cmd_cmpl(phba, cmdiocb, saveq);
4303 				spin_lock_irqsave(&phba->hbalock, iflag);
4304 			} else {
4305 				__lpfc_sli_release_iocbq(phba, cmdiocb);
4306 			}
4307 		}
4308 		break;
4309 	case LPFC_UNKNOWN_IOCB:
4310 		if (ulp_command == CMD_ADAPTER_MSG) {
4311 			char adaptermsg[LPFC_MAX_ADPTMSG];
4312 
4313 			memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
4314 			memcpy(&adaptermsg[0], (uint8_t *)&rspiocbp->wqe,
4315 			       MAX_MSG_DATA);
4316 			dev_warn(&((phba->pcidev)->dev),
4317 				 "lpfc%d: %s\n",
4318 				 phba->brd_no, adaptermsg);
4319 		} else {
4320 			/* Unknown command */
4321 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4322 					"0335 Unknown IOCB "
4323 					"command Data: x%x "
4324 					"x%x x%x x%x\n",
4325 					ulp_command,
4326 					ulp_status,
4327 					get_wqe_reqtag(rspiocbp),
4328 					get_job_ulpcontext(phba, rspiocbp));
4329 		}
4330 		break;
4331 	}
4332 
4333 	if (free_saveq) {
4334 		list_for_each_entry_safe(rspiocbp, next_iocb,
4335 					 &saveq->list, list) {
4336 			list_del_init(&rspiocbp->list);
4337 			__lpfc_sli_release_iocbq(phba, rspiocbp);
4338 		}
4339 		__lpfc_sli_release_iocbq(phba, saveq);
4340 	}
4341 	rspiocbp = NULL;
4342 	spin_unlock_irqrestore(&phba->hbalock, iflag);
4343 	return rspiocbp;
4344 }
4345 
4346 /**
4347  * lpfc_sli_handle_slow_ring_event - Wrapper func for handling slow-path iocbs
4348  * @phba: Pointer to HBA context object.
4349  * @pring: Pointer to driver SLI ring object.
4350  * @mask: Host attention register mask for this ring.
4351  *
4352  * This routine wraps the actual slow_ring event process routine from the
4353  * API jump table function pointer from the lpfc_hba struct.
4354  **/
4355 void
4356 lpfc_sli_handle_slow_ring_event(struct lpfc_hba *phba,
4357 				struct lpfc_sli_ring *pring, uint32_t mask)
4358 {
4359 	phba->lpfc_sli_handle_slow_ring_event(phba, pring, mask);
4360 }
4361 
4362 /**
4363  * lpfc_sli_handle_slow_ring_event_s3 - Handle SLI3 ring event for non-FCP rings
4364  * @phba: Pointer to HBA context object.
4365  * @pring: Pointer to driver SLI ring object.
4366  * @mask: Host attention register mask for this ring.
4367  *
4368  * This function is called from the worker thread when there is a ring event
4369  * for non-fcp rings. The caller does not hold any lock. The function will
4370  * remove each response iocb in the response ring and calls the handle
4371  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
4372  **/
4373 static void
4374 lpfc_sli_handle_slow_ring_event_s3(struct lpfc_hba *phba,
4375 				   struct lpfc_sli_ring *pring, uint32_t mask)
4376 {
4377 	struct lpfc_pgp *pgp;
4378 	IOCB_t *entry;
4379 	IOCB_t *irsp = NULL;
4380 	struct lpfc_iocbq *rspiocbp = NULL;
4381 	uint32_t portRspPut, portRspMax;
4382 	unsigned long iflag;
4383 	uint32_t status;
4384 
4385 	pgp = &phba->port_gp[pring->ringno];
4386 	spin_lock_irqsave(&phba->hbalock, iflag);
4387 	pring->stats.iocb_event++;
4388 
4389 	/*
4390 	 * The next available response entry should never exceed the maximum
4391 	 * entries.  If it does, treat it as an adapter hardware error.
4392 	 */
4393 	portRspMax = pring->sli.sli3.numRiocb;
4394 	portRspPut = le32_to_cpu(pgp->rspPutInx);
4395 	if (portRspPut >= portRspMax) {
4396 		/*
4397 		 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
4398 		 * rsp ring <portRspMax>
4399 		 */
4400 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4401 				"0303 Ring %d handler: portRspPut %d "
4402 				"is bigger than rsp ring %d\n",
4403 				pring->ringno, portRspPut, portRspMax);
4404 
4405 		phba->link_state = LPFC_HBA_ERROR;
4406 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4407 
4408 		phba->work_hs = HS_FFER3;
4409 		lpfc_handle_eratt(phba);
4410 
4411 		return;
4412 	}
4413 
4414 	rmb();
4415 	while (pring->sli.sli3.rspidx != portRspPut) {
4416 		/*
4417 		 * Build a completion list and call the appropriate handler.
4418 		 * The process is to get the next available response iocb, get
4419 		 * a free iocb from the list, copy the response data into the
4420 		 * free iocb, insert to the continuation list, and update the
4421 		 * next response index to slim.  This process makes response
4422 		 * iocb's in the ring available to DMA as fast as possible but
4423 		 * pays a penalty for a copy operation.  Since the iocb is
4424 		 * only 32 bytes, this penalty is considered small relative to
4425 		 * the PCI reads for register values and a slim write.  When
4426 		 * the ulpLe field is set, the entire Command has been
4427 		 * received.
4428 		 */
4429 		entry = lpfc_resp_iocb(phba, pring);
4430 
4431 		phba->last_completion_time = jiffies;
4432 		rspiocbp = __lpfc_sli_get_iocbq(phba);
4433 		if (rspiocbp == NULL) {
4434 			printk(KERN_ERR "%s: out of buffers! Failing "
4435 			       "completion.\n", __func__);
4436 			break;
4437 		}
4438 
4439 		lpfc_sli_pcimem_bcopy(entry, &rspiocbp->iocb,
4440 				      phba->iocb_rsp_size);
4441 		irsp = &rspiocbp->iocb;
4442 
4443 		if (++pring->sli.sli3.rspidx >= portRspMax)
4444 			pring->sli.sli3.rspidx = 0;
4445 
4446 		if (pring->ringno == LPFC_ELS_RING) {
4447 			lpfc_debugfs_slow_ring_trc(phba,
4448 			"IOCB rsp ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
4449 				*(((uint32_t *) irsp) + 4),
4450 				*(((uint32_t *) irsp) + 6),
4451 				*(((uint32_t *) irsp) + 7));
4452 		}
4453 
4454 		writel(pring->sli.sli3.rspidx,
4455 			&phba->host_gp[pring->ringno].rspGetInx);
4456 
4457 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4458 		/* Handle the response IOCB */
4459 		rspiocbp = lpfc_sli_sp_handle_rspiocb(phba, pring, rspiocbp);
4460 		spin_lock_irqsave(&phba->hbalock, iflag);
4461 
4462 		/*
4463 		 * If the port response put pointer has not been updated, sync
4464 		 * the pgp->rspPutInx in the MAILBOX_tand fetch the new port
4465 		 * response put pointer.
4466 		 */
4467 		if (pring->sli.sli3.rspidx == portRspPut) {
4468 			portRspPut = le32_to_cpu(pgp->rspPutInx);
4469 		}
4470 	} /* while (pring->sli.sli3.rspidx != portRspPut) */
4471 
4472 	if ((rspiocbp != NULL) && (mask & HA_R0RE_REQ)) {
4473 		/* At least one response entry has been freed */
4474 		pring->stats.iocb_rsp_full++;
4475 		/* SET RxRE_RSP in Chip Att register */
4476 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
4477 		writel(status, phba->CAregaddr);
4478 		readl(phba->CAregaddr); /* flush */
4479 	}
4480 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
4481 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
4482 		pring->stats.iocb_cmd_empty++;
4483 
4484 		/* Force update of the local copy of cmdGetInx */
4485 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
4486 		lpfc_sli_resume_iocb(phba, pring);
4487 
4488 		if ((pring->lpfc_sli_cmd_available))
4489 			(pring->lpfc_sli_cmd_available) (phba, pring);
4490 
4491 	}
4492 
4493 	spin_unlock_irqrestore(&phba->hbalock, iflag);
4494 	return;
4495 }
4496 
4497 /**
4498  * lpfc_sli_handle_slow_ring_event_s4 - Handle SLI4 slow-path els events
4499  * @phba: Pointer to HBA context object.
4500  * @pring: Pointer to driver SLI ring object.
4501  * @mask: Host attention register mask for this ring.
4502  *
4503  * This function is called from the worker thread when there is a pending
4504  * ELS response iocb on the driver internal slow-path response iocb worker
4505  * queue. The caller does not hold any lock. The function will remove each
4506  * response iocb from the response worker queue and calls the handle
4507  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
4508  **/
4509 static void
4510 lpfc_sli_handle_slow_ring_event_s4(struct lpfc_hba *phba,
4511 				   struct lpfc_sli_ring *pring, uint32_t mask)
4512 {
4513 	struct lpfc_iocbq *irspiocbq;
4514 	struct hbq_dmabuf *dmabuf;
4515 	struct lpfc_cq_event *cq_event;
4516 	unsigned long iflag;
4517 	int count = 0;
4518 
4519 	clear_bit(HBA_SP_QUEUE_EVT, &phba->hba_flag);
4520 	while (!list_empty(&phba->sli4_hba.sp_queue_event)) {
4521 		/* Get the response iocb from the head of work queue */
4522 		spin_lock_irqsave(&phba->hbalock, iflag);
4523 		list_remove_head(&phba->sli4_hba.sp_queue_event,
4524 				 cq_event, struct lpfc_cq_event, list);
4525 		spin_unlock_irqrestore(&phba->hbalock, iflag);
4526 
4527 		switch (bf_get(lpfc_wcqe_c_code, &cq_event->cqe.wcqe_cmpl)) {
4528 		case CQE_CODE_COMPL_WQE:
4529 			irspiocbq = container_of(cq_event, struct lpfc_iocbq,
4530 						 cq_event);
4531 			/* Translate ELS WCQE to response IOCBQ */
4532 			irspiocbq = lpfc_sli4_els_preprocess_rspiocbq(phba,
4533 								      irspiocbq);
4534 			if (irspiocbq)
4535 				lpfc_sli_sp_handle_rspiocb(phba, pring,
4536 							   irspiocbq);
4537 			count++;
4538 			break;
4539 		case CQE_CODE_RECEIVE:
4540 		case CQE_CODE_RECEIVE_V1:
4541 			dmabuf = container_of(cq_event, struct hbq_dmabuf,
4542 					      cq_event);
4543 			lpfc_sli4_handle_received_buffer(phba, dmabuf);
4544 			count++;
4545 			break;
4546 		default:
4547 			break;
4548 		}
4549 
4550 		/* Limit the number of events to 64 to avoid soft lockups */
4551 		if (count == 64)
4552 			break;
4553 	}
4554 }
4555 
4556 /**
4557  * lpfc_sli_abort_iocb_ring - Abort all iocbs in the ring
4558  * @phba: Pointer to HBA context object.
4559  * @pring: Pointer to driver SLI ring object.
4560  *
4561  * This function aborts all iocbs in the given ring and frees all the iocb
4562  * objects in txq. This function issues an abort iocb for all the iocb commands
4563  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
4564  * the return of this function. The caller is not required to hold any locks.
4565  **/
4566 void
4567 lpfc_sli_abort_iocb_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
4568 {
4569 	LIST_HEAD(tx_completions);
4570 	spinlock_t *plock;		/* for transmit queue access */
4571 	struct lpfc_iocbq *iocb, *next_iocb;
4572 	int offline;
4573 
4574 	if (phba->sli_rev >= LPFC_SLI_REV4)
4575 		plock = &pring->ring_lock;
4576 	else
4577 		plock = &phba->hbalock;
4578 
4579 	if (pring->ringno == LPFC_ELS_RING)
4580 		lpfc_fabric_abort_hba(phba);
4581 
4582 	offline = pci_channel_offline(phba->pcidev);
4583 
4584 	/* Cancel everything on txq */
4585 	spin_lock_irq(plock);
4586 	list_splice_init(&pring->txq, &tx_completions);
4587 	pring->txq_cnt = 0;
4588 
4589 	if (offline) {
4590 		/* Cancel everything on txcmplq */
4591 		list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
4592 			iocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
4593 		list_splice_init(&pring->txcmplq, &tx_completions);
4594 		pring->txcmplq_cnt = 0;
4595 	} else {
4596 		/* Issue ABTS for everything on the txcmplq */
4597 		list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
4598 			lpfc_sli_issue_abort_iotag(phba, pring, iocb, NULL);
4599 	}
4600 	spin_unlock_irq(plock);
4601 
4602 	if (!offline)
4603 		lpfc_issue_hb_tmo(phba);
4604 
4605 	/* Cancel all the IOCBs from the completions list */
4606 	lpfc_sli_cancel_iocbs(phba, &tx_completions, IOSTAT_LOCAL_REJECT,
4607 			      IOERR_SLI_ABORTED);
4608 }
4609 
4610 /**
4611  * lpfc_sli_abort_fcp_rings - Abort all iocbs in all FCP rings
4612  * @phba: Pointer to HBA context object.
4613  *
4614  * This function aborts all iocbs in FCP rings and frees all the iocb
4615  * objects in txq. This function issues an abort iocb for all the iocb commands
4616  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
4617  * the return of this function. The caller is not required to hold any locks.
4618  **/
4619 void
4620 lpfc_sli_abort_fcp_rings(struct lpfc_hba *phba)
4621 {
4622 	struct lpfc_sli *psli = &phba->sli;
4623 	struct lpfc_sli_ring  *pring;
4624 	uint32_t i;
4625 
4626 	/* Look on all the FCP Rings for the iotag */
4627 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4628 		for (i = 0; i < phba->cfg_hdw_queue; i++) {
4629 			pring = phba->sli4_hba.hdwq[i].io_wq->pring;
4630 			lpfc_sli_abort_iocb_ring(phba, pring);
4631 		}
4632 	} else {
4633 		pring = &psli->sli3_ring[LPFC_FCP_RING];
4634 		lpfc_sli_abort_iocb_ring(phba, pring);
4635 	}
4636 }
4637 
4638 /**
4639  * lpfc_sli_flush_io_rings - flush all iocbs in the IO ring
4640  * @phba: Pointer to HBA context object.
4641  *
4642  * This function flushes all iocbs in the IO ring and frees all the iocb
4643  * objects in txq and txcmplq. This function will not issue abort iocbs
4644  * for all the iocb commands in txcmplq, they will just be returned with
4645  * IOERR_SLI_DOWN. This function is invoked with EEH when device's PCI
4646  * slot has been permanently disabled.
4647  **/
4648 void
4649 lpfc_sli_flush_io_rings(struct lpfc_hba *phba)
4650 {
4651 	LIST_HEAD(txq);
4652 	LIST_HEAD(txcmplq);
4653 	struct lpfc_sli *psli = &phba->sli;
4654 	struct lpfc_sli_ring  *pring;
4655 	uint32_t i;
4656 	struct lpfc_iocbq *piocb, *next_iocb;
4657 
4658 	/* Indicate the I/O queues are flushed */
4659 	set_bit(HBA_IOQ_FLUSH, &phba->hba_flag);
4660 
4661 	/* Look on all the FCP Rings for the iotag */
4662 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4663 		for (i = 0; i < phba->cfg_hdw_queue; i++) {
4664 			if (!phba->sli4_hba.hdwq ||
4665 			    !phba->sli4_hba.hdwq[i].io_wq) {
4666 				lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
4667 						"7777 hdwq's deleted %lx "
4668 						"%lx %x %x\n",
4669 						phba->pport->load_flag,
4670 						phba->hba_flag,
4671 						phba->link_state,
4672 						phba->sli.sli_flag);
4673 				return;
4674 			}
4675 			pring = phba->sli4_hba.hdwq[i].io_wq->pring;
4676 
4677 			spin_lock_irq(&pring->ring_lock);
4678 			/* Retrieve everything on txq */
4679 			list_splice_init(&pring->txq, &txq);
4680 			list_for_each_entry_safe(piocb, next_iocb,
4681 						 &pring->txcmplq, list)
4682 				piocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
4683 			/* Retrieve everything on the txcmplq */
4684 			list_splice_init(&pring->txcmplq, &txcmplq);
4685 			pring->txq_cnt = 0;
4686 			pring->txcmplq_cnt = 0;
4687 			spin_unlock_irq(&pring->ring_lock);
4688 
4689 			/* Flush the txq */
4690 			lpfc_sli_cancel_iocbs(phba, &txq,
4691 					      IOSTAT_LOCAL_REJECT,
4692 					      IOERR_SLI_DOWN);
4693 			/* Flush the txcmplq */
4694 			lpfc_sli_cancel_iocbs(phba, &txcmplq,
4695 					      IOSTAT_LOCAL_REJECT,
4696 					      IOERR_SLI_DOWN);
4697 			if (unlikely(pci_channel_offline(phba->pcidev)))
4698 				lpfc_sli4_io_xri_aborted(phba, NULL, 0);
4699 		}
4700 	} else {
4701 		pring = &psli->sli3_ring[LPFC_FCP_RING];
4702 
4703 		spin_lock_irq(&phba->hbalock);
4704 		/* Retrieve everything on txq */
4705 		list_splice_init(&pring->txq, &txq);
4706 		list_for_each_entry_safe(piocb, next_iocb,
4707 					 &pring->txcmplq, list)
4708 			piocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
4709 		/* Retrieve everything on the txcmplq */
4710 		list_splice_init(&pring->txcmplq, &txcmplq);
4711 		pring->txq_cnt = 0;
4712 		pring->txcmplq_cnt = 0;
4713 		spin_unlock_irq(&phba->hbalock);
4714 
4715 		/* Flush the txq */
4716 		lpfc_sli_cancel_iocbs(phba, &txq, IOSTAT_LOCAL_REJECT,
4717 				      IOERR_SLI_DOWN);
4718 		/* Flush the txcmpq */
4719 		lpfc_sli_cancel_iocbs(phba, &txcmplq, IOSTAT_LOCAL_REJECT,
4720 				      IOERR_SLI_DOWN);
4721 	}
4722 }
4723 
4724 /**
4725  * lpfc_sli_brdready_s3 - Check for sli3 host ready status
4726  * @phba: Pointer to HBA context object.
4727  * @mask: Bit mask to be checked.
4728  *
4729  * This function reads the host status register and compares
4730  * with the provided bit mask to check if HBA completed
4731  * the restart. This function will wait in a loop for the
4732  * HBA to complete restart. If the HBA does not restart within
4733  * 15 iterations, the function will reset the HBA again. The
4734  * function returns 1 when HBA fail to restart otherwise returns
4735  * zero.
4736  **/
4737 static int
4738 lpfc_sli_brdready_s3(struct lpfc_hba *phba, uint32_t mask)
4739 {
4740 	uint32_t status;
4741 	int i = 0;
4742 	int retval = 0;
4743 
4744 	/* Read the HBA Host Status Register */
4745 	if (lpfc_readl(phba->HSregaddr, &status))
4746 		return 1;
4747 
4748 	set_bit(HBA_NEEDS_CFG_PORT, &phba->hba_flag);
4749 
4750 	/*
4751 	 * Check status register every 100ms for 5 retries, then every
4752 	 * 500ms for 5, then every 2.5 sec for 5, then reset board and
4753 	 * every 2.5 sec for 4.
4754 	 * Break our of the loop if errors occurred during init.
4755 	 */
4756 	while (((status & mask) != mask) &&
4757 	       !(status & HS_FFERM) &&
4758 	       i++ < 20) {
4759 
4760 		if (i <= 5)
4761 			msleep(10);
4762 		else if (i <= 10)
4763 			msleep(500);
4764 		else
4765 			msleep(2500);
4766 
4767 		if (i == 15) {
4768 				/* Do post */
4769 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4770 			lpfc_sli_brdrestart(phba);
4771 		}
4772 		/* Read the HBA Host Status Register */
4773 		if (lpfc_readl(phba->HSregaddr, &status)) {
4774 			retval = 1;
4775 			break;
4776 		}
4777 	}
4778 
4779 	/* Check to see if any errors occurred during init */
4780 	if ((status & HS_FFERM) || (i >= 20)) {
4781 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4782 				"2751 Adapter failed to restart, "
4783 				"status reg x%x, FW Data: A8 x%x AC x%x\n",
4784 				status,
4785 				readl(phba->MBslimaddr + 0xa8),
4786 				readl(phba->MBslimaddr + 0xac));
4787 		phba->link_state = LPFC_HBA_ERROR;
4788 		retval = 1;
4789 	}
4790 
4791 	return retval;
4792 }
4793 
4794 /**
4795  * lpfc_sli_brdready_s4 - Check for sli4 host ready status
4796  * @phba: Pointer to HBA context object.
4797  * @mask: Bit mask to be checked.
4798  *
4799  * This function checks the host status register to check if HBA is
4800  * ready. This function will wait in a loop for the HBA to be ready
4801  * If the HBA is not ready , the function will will reset the HBA PCI
4802  * function again. The function returns 1 when HBA fail to be ready
4803  * otherwise returns zero.
4804  **/
4805 static int
4806 lpfc_sli_brdready_s4(struct lpfc_hba *phba, uint32_t mask)
4807 {
4808 	uint32_t status;
4809 	int retval = 0;
4810 
4811 	/* Read the HBA Host Status Register */
4812 	status = lpfc_sli4_post_status_check(phba);
4813 
4814 	if (status) {
4815 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4816 		lpfc_sli_brdrestart(phba);
4817 		status = lpfc_sli4_post_status_check(phba);
4818 	}
4819 
4820 	/* Check to see if any errors occurred during init */
4821 	if (status) {
4822 		phba->link_state = LPFC_HBA_ERROR;
4823 		retval = 1;
4824 	} else
4825 		phba->sli4_hba.intr_enable = 0;
4826 
4827 	clear_bit(HBA_SETUP, &phba->hba_flag);
4828 	return retval;
4829 }
4830 
4831 /**
4832  * lpfc_sli_brdready - Wrapper func for checking the hba readiness
4833  * @phba: Pointer to HBA context object.
4834  * @mask: Bit mask to be checked.
4835  *
4836  * This routine wraps the actual SLI3 or SLI4 hba readiness check routine
4837  * from the API jump table function pointer from the lpfc_hba struct.
4838  **/
4839 int
4840 lpfc_sli_brdready(struct lpfc_hba *phba, uint32_t mask)
4841 {
4842 	return phba->lpfc_sli_brdready(phba, mask);
4843 }
4844 
4845 #define BARRIER_TEST_PATTERN (0xdeadbeef)
4846 
4847 /**
4848  * lpfc_reset_barrier - Make HBA ready for HBA reset
4849  * @phba: Pointer to HBA context object.
4850  *
4851  * This function is called before resetting an HBA. This function is called
4852  * with hbalock held and requests HBA to quiesce DMAs before a reset.
4853  **/
4854 void lpfc_reset_barrier(struct lpfc_hba *phba)
4855 {
4856 	uint32_t __iomem *resp_buf;
4857 	uint32_t __iomem *mbox_buf;
4858 	volatile struct MAILBOX_word0 mbox;
4859 	uint32_t hc_copy, ha_copy, resp_data;
4860 	int  i;
4861 	uint8_t hdrtype;
4862 
4863 	lockdep_assert_held(&phba->hbalock);
4864 
4865 	pci_read_config_byte(phba->pcidev, PCI_HEADER_TYPE, &hdrtype);
4866 	if (hdrtype != PCI_HEADER_TYPE_MFD ||
4867 	    (FC_JEDEC_ID(phba->vpd.rev.biuRev) != HELIOS_JEDEC_ID &&
4868 	     FC_JEDEC_ID(phba->vpd.rev.biuRev) != THOR_JEDEC_ID))
4869 		return;
4870 
4871 	/*
4872 	 * Tell the other part of the chip to suspend temporarily all
4873 	 * its DMA activity.
4874 	 */
4875 	resp_buf = phba->MBslimaddr;
4876 
4877 	/* Disable the error attention */
4878 	if (lpfc_readl(phba->HCregaddr, &hc_copy))
4879 		return;
4880 	writel((hc_copy & ~HC_ERINT_ENA), phba->HCregaddr);
4881 	readl(phba->HCregaddr); /* flush */
4882 	phba->link_flag |= LS_IGNORE_ERATT;
4883 
4884 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
4885 		return;
4886 	if (ha_copy & HA_ERATT) {
4887 		/* Clear Chip error bit */
4888 		writel(HA_ERATT, phba->HAregaddr);
4889 		phba->pport->stopped = 1;
4890 	}
4891 
4892 	mbox.word0 = 0;
4893 	mbox.mbxCommand = MBX_KILL_BOARD;
4894 	mbox.mbxOwner = OWN_CHIP;
4895 
4896 	writel(BARRIER_TEST_PATTERN, (resp_buf + 1));
4897 	mbox_buf = phba->MBslimaddr;
4898 	writel(mbox.word0, mbox_buf);
4899 
4900 	for (i = 0; i < 50; i++) {
4901 		if (lpfc_readl((resp_buf + 1), &resp_data))
4902 			return;
4903 		if (resp_data != ~(BARRIER_TEST_PATTERN))
4904 			mdelay(1);
4905 		else
4906 			break;
4907 	}
4908 	resp_data = 0;
4909 	if (lpfc_readl((resp_buf + 1), &resp_data))
4910 		return;
4911 	if (resp_data  != ~(BARRIER_TEST_PATTERN)) {
4912 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE ||
4913 		    phba->pport->stopped)
4914 			goto restore_hc;
4915 		else
4916 			goto clear_errat;
4917 	}
4918 
4919 	mbox.mbxOwner = OWN_HOST;
4920 	resp_data = 0;
4921 	for (i = 0; i < 500; i++) {
4922 		if (lpfc_readl(resp_buf, &resp_data))
4923 			return;
4924 		if (resp_data != mbox.word0)
4925 			mdelay(1);
4926 		else
4927 			break;
4928 	}
4929 
4930 clear_errat:
4931 
4932 	while (++i < 500) {
4933 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
4934 			return;
4935 		if (!(ha_copy & HA_ERATT))
4936 			mdelay(1);
4937 		else
4938 			break;
4939 	}
4940 
4941 	if (readl(phba->HAregaddr) & HA_ERATT) {
4942 		writel(HA_ERATT, phba->HAregaddr);
4943 		phba->pport->stopped = 1;
4944 	}
4945 
4946 restore_hc:
4947 	phba->link_flag &= ~LS_IGNORE_ERATT;
4948 	writel(hc_copy, phba->HCregaddr);
4949 	readl(phba->HCregaddr); /* flush */
4950 }
4951 
4952 /**
4953  * lpfc_sli_brdkill - Issue a kill_board mailbox command
4954  * @phba: Pointer to HBA context object.
4955  *
4956  * This function issues a kill_board mailbox command and waits for
4957  * the error attention interrupt. This function is called for stopping
4958  * the firmware processing. The caller is not required to hold any
4959  * locks. This function calls lpfc_hba_down_post function to free
4960  * any pending commands after the kill. The function will return 1 when it
4961  * fails to kill the board else will return 0.
4962  **/
4963 int
4964 lpfc_sli_brdkill(struct lpfc_hba *phba)
4965 {
4966 	struct lpfc_sli *psli;
4967 	LPFC_MBOXQ_t *pmb;
4968 	uint32_t status;
4969 	uint32_t ha_copy;
4970 	int retval;
4971 	int i = 0;
4972 
4973 	psli = &phba->sli;
4974 
4975 	/* Kill HBA */
4976 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4977 			"0329 Kill HBA Data: x%x x%x\n",
4978 			phba->pport->port_state, psli->sli_flag);
4979 
4980 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4981 	if (!pmb)
4982 		return 1;
4983 
4984 	/* Disable the error attention */
4985 	spin_lock_irq(&phba->hbalock);
4986 	if (lpfc_readl(phba->HCregaddr, &status)) {
4987 		spin_unlock_irq(&phba->hbalock);
4988 		mempool_free(pmb, phba->mbox_mem_pool);
4989 		return 1;
4990 	}
4991 	status &= ~HC_ERINT_ENA;
4992 	writel(status, phba->HCregaddr);
4993 	readl(phba->HCregaddr); /* flush */
4994 	phba->link_flag |= LS_IGNORE_ERATT;
4995 	spin_unlock_irq(&phba->hbalock);
4996 
4997 	lpfc_kill_board(phba, pmb);
4998 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
4999 	retval = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
5000 
5001 	if (retval != MBX_SUCCESS) {
5002 		if (retval != MBX_BUSY)
5003 			mempool_free(pmb, phba->mbox_mem_pool);
5004 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5005 				"2752 KILL_BOARD command failed retval %d\n",
5006 				retval);
5007 		spin_lock_irq(&phba->hbalock);
5008 		phba->link_flag &= ~LS_IGNORE_ERATT;
5009 		spin_unlock_irq(&phba->hbalock);
5010 		return 1;
5011 	}
5012 
5013 	spin_lock_irq(&phba->hbalock);
5014 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
5015 	spin_unlock_irq(&phba->hbalock);
5016 
5017 	mempool_free(pmb, phba->mbox_mem_pool);
5018 
5019 	/* There is no completion for a KILL_BOARD mbox cmd. Check for an error
5020 	 * attention every 100ms for 3 seconds. If we don't get ERATT after
5021 	 * 3 seconds we still set HBA_ERROR state because the status of the
5022 	 * board is now undefined.
5023 	 */
5024 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
5025 		return 1;
5026 	while ((i++ < 30) && !(ha_copy & HA_ERATT)) {
5027 		mdelay(100);
5028 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
5029 			return 1;
5030 	}
5031 
5032 	timer_delete_sync(&psli->mbox_tmo);
5033 	if (ha_copy & HA_ERATT) {
5034 		writel(HA_ERATT, phba->HAregaddr);
5035 		phba->pport->stopped = 1;
5036 	}
5037 	spin_lock_irq(&phba->hbalock);
5038 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
5039 	psli->mbox_active = NULL;
5040 	phba->link_flag &= ~LS_IGNORE_ERATT;
5041 	spin_unlock_irq(&phba->hbalock);
5042 
5043 	lpfc_hba_down_post(phba);
5044 	phba->link_state = LPFC_HBA_ERROR;
5045 
5046 	return ha_copy & HA_ERATT ? 0 : 1;
5047 }
5048 
5049 /**
5050  * lpfc_sli_brdreset - Reset a sli-2 or sli-3 HBA
5051  * @phba: Pointer to HBA context object.
5052  *
5053  * This function resets the HBA by writing HC_INITFF to the control
5054  * register. After the HBA resets, this function resets all the iocb ring
5055  * indices. This function disables PCI layer parity checking during
5056  * the reset.
5057  * This function returns 0 always.
5058  * The caller is not required to hold any locks.
5059  **/
5060 int
5061 lpfc_sli_brdreset(struct lpfc_hba *phba)
5062 {
5063 	struct lpfc_sli *psli;
5064 	struct lpfc_sli_ring *pring;
5065 	uint16_t cfg_value;
5066 	int i;
5067 
5068 	psli = &phba->sli;
5069 
5070 	/* Reset HBA */
5071 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5072 			"0325 Reset HBA Data: x%x x%x\n",
5073 			(phba->pport) ? phba->pport->port_state : 0,
5074 			psli->sli_flag);
5075 
5076 	/* perform board reset */
5077 	phba->fc_eventTag = 0;
5078 	phba->link_events = 0;
5079 	set_bit(HBA_NEEDS_CFG_PORT, &phba->hba_flag);
5080 	if (phba->pport) {
5081 		phba->pport->fc_myDID = 0;
5082 		phba->pport->fc_prevDID = 0;
5083 	}
5084 
5085 	/* Turn off parity checking and serr during the physical reset */
5086 	if (pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value))
5087 		return -EIO;
5088 
5089 	pci_write_config_word(phba->pcidev, PCI_COMMAND,
5090 			      (cfg_value &
5091 			       ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
5092 
5093 	psli->sli_flag &= ~(LPFC_SLI_ACTIVE | LPFC_PROCESS_LA);
5094 
5095 	/* Now toggle INITFF bit in the Host Control Register */
5096 	writel(HC_INITFF, phba->HCregaddr);
5097 	mdelay(1);
5098 	readl(phba->HCregaddr); /* flush */
5099 	writel(0, phba->HCregaddr);
5100 	readl(phba->HCregaddr); /* flush */
5101 
5102 	/* Restore PCI cmd register */
5103 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
5104 
5105 	/* Initialize relevant SLI info */
5106 	for (i = 0; i < psli->num_rings; i++) {
5107 		pring = &psli->sli3_ring[i];
5108 		pring->flag = 0;
5109 		pring->sli.sli3.rspidx = 0;
5110 		pring->sli.sli3.next_cmdidx  = 0;
5111 		pring->sli.sli3.local_getidx = 0;
5112 		pring->sli.sli3.cmdidx = 0;
5113 		pring->missbufcnt = 0;
5114 	}
5115 
5116 	phba->link_state = LPFC_WARM_START;
5117 	return 0;
5118 }
5119 
5120 /**
5121  * lpfc_sli4_brdreset - Reset a sli-4 HBA
5122  * @phba: Pointer to HBA context object.
5123  *
5124  * This function resets a SLI4 HBA. This function disables PCI layer parity
5125  * checking during resets the device. The caller is not required to hold
5126  * any locks.
5127  *
5128  * This function returns 0 on success else returns negative error code.
5129  **/
5130 int
5131 lpfc_sli4_brdreset(struct lpfc_hba *phba)
5132 {
5133 	struct lpfc_sli *psli = &phba->sli;
5134 	uint16_t cfg_value;
5135 	int rc = 0;
5136 
5137 	/* Reset HBA */
5138 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5139 			"0295 Reset HBA Data: x%x x%x x%lx\n",
5140 			phba->pport->port_state, psli->sli_flag,
5141 			phba->hba_flag);
5142 
5143 	/* perform board reset */
5144 	phba->fc_eventTag = 0;
5145 	phba->link_events = 0;
5146 	phba->pport->fc_myDID = 0;
5147 	phba->pport->fc_prevDID = 0;
5148 
5149 	spin_lock_irq(&phba->hbalock);
5150 	psli->sli_flag &= ~(LPFC_PROCESS_LA);
5151 	phba->fcf.fcf_flag = 0;
5152 	spin_unlock_irq(&phba->hbalock);
5153 
5154 	/* Now physically reset the device */
5155 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5156 			"0389 Performing PCI function reset!\n");
5157 
5158 	/* Turn off parity checking and serr during the physical reset */
5159 	if (pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value)) {
5160 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5161 				"3205 PCI read Config failed\n");
5162 		return -EIO;
5163 	}
5164 
5165 	pci_write_config_word(phba->pcidev, PCI_COMMAND, (cfg_value &
5166 			      ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
5167 
5168 	/* Perform FCoE PCI function reset before freeing queue memory */
5169 	rc = lpfc_pci_function_reset(phba);
5170 
5171 	/* Restore PCI cmd register */
5172 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
5173 
5174 	return rc;
5175 }
5176 
5177 /**
5178  * lpfc_sli_brdrestart_s3 - Restart a sli-3 hba
5179  * @phba: Pointer to HBA context object.
5180  *
5181  * This function is called in the SLI initialization code path to
5182  * restart the HBA. The caller is not required to hold any lock.
5183  * This function writes MBX_RESTART mailbox command to the SLIM and
5184  * resets the HBA. At the end of the function, it calls lpfc_hba_down_post
5185  * function to free any pending commands. The function enables
5186  * POST only during the first initialization. The function returns zero.
5187  * The function does not guarantee completion of MBX_RESTART mailbox
5188  * command before the return of this function.
5189  **/
5190 static int
5191 lpfc_sli_brdrestart_s3(struct lpfc_hba *phba)
5192 {
5193 	volatile struct MAILBOX_word0 mb;
5194 	struct lpfc_sli *psli;
5195 	void __iomem *to_slim;
5196 
5197 	spin_lock_irq(&phba->hbalock);
5198 
5199 	psli = &phba->sli;
5200 
5201 	/* Restart HBA */
5202 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5203 			"0337 Restart HBA Data: x%x x%x\n",
5204 			(phba->pport) ? phba->pport->port_state : 0,
5205 			psli->sli_flag);
5206 
5207 	mb.word0 = 0;
5208 	mb.mbxCommand = MBX_RESTART;
5209 	mb.mbxHc = 1;
5210 
5211 	lpfc_reset_barrier(phba);
5212 
5213 	to_slim = phba->MBslimaddr;
5214 	writel(mb.word0, to_slim);
5215 	readl(to_slim); /* flush */
5216 
5217 	/* Only skip post after fc_ffinit is completed */
5218 	if (phba->pport && phba->pport->port_state)
5219 		mb.word0 = 1;	/* This is really setting up word1 */
5220 	else
5221 		mb.word0 = 0;	/* This is really setting up word1 */
5222 	to_slim = phba->MBslimaddr + sizeof (uint32_t);
5223 	writel(mb.word0, to_slim);
5224 	readl(to_slim); /* flush */
5225 
5226 	lpfc_sli_brdreset(phba);
5227 	if (phba->pport)
5228 		phba->pport->stopped = 0;
5229 	phba->link_state = LPFC_INIT_START;
5230 	phba->hba_flag = 0;
5231 	spin_unlock_irq(&phba->hbalock);
5232 
5233 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
5234 	psli->stats_start = ktime_get_seconds();
5235 
5236 	/* Give the INITFF and Post time to settle. */
5237 	mdelay(100);
5238 
5239 	lpfc_hba_down_post(phba);
5240 
5241 	return 0;
5242 }
5243 
5244 /**
5245  * lpfc_sli_brdrestart_s4 - Restart the sli-4 hba
5246  * @phba: Pointer to HBA context object.
5247  *
5248  * This function is called in the SLI initialization code path to restart
5249  * a SLI4 HBA. The caller is not required to hold any lock.
5250  * At the end of the function, it calls lpfc_hba_down_post function to
5251  * free any pending commands.
5252  **/
5253 static int
5254 lpfc_sli_brdrestart_s4(struct lpfc_hba *phba)
5255 {
5256 	struct lpfc_sli *psli = &phba->sli;
5257 	int rc;
5258 
5259 	/* Restart HBA */
5260 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5261 			"0296 Restart HBA Data: x%x x%x\n",
5262 			phba->pport->port_state, psli->sli_flag);
5263 
5264 	clear_bit(HBA_SETUP, &phba->hba_flag);
5265 	lpfc_sli4_queue_unset(phba);
5266 
5267 	rc = lpfc_sli4_brdreset(phba);
5268 	if (rc) {
5269 		phba->link_state = LPFC_HBA_ERROR;
5270 		goto hba_down_queue;
5271 	}
5272 
5273 	spin_lock_irq(&phba->hbalock);
5274 	phba->pport->stopped = 0;
5275 	phba->link_state = LPFC_INIT_START;
5276 	phba->hba_flag = 0;
5277 	/* Preserve FA-PWWN expectation */
5278 	phba->sli4_hba.fawwpn_flag &= LPFC_FAWWPN_FABRIC;
5279 	spin_unlock_irq(&phba->hbalock);
5280 
5281 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
5282 	psli->stats_start = ktime_get_seconds();
5283 
5284 hba_down_queue:
5285 	lpfc_hba_down_post(phba);
5286 	lpfc_sli4_queue_destroy(phba);
5287 
5288 	return rc;
5289 }
5290 
5291 /**
5292  * lpfc_sli_brdrestart - Wrapper func for restarting hba
5293  * @phba: Pointer to HBA context object.
5294  *
5295  * This routine wraps the actual SLI3 or SLI4 hba restart routine from the
5296  * API jump table function pointer from the lpfc_hba struct.
5297 **/
5298 int
5299 lpfc_sli_brdrestart(struct lpfc_hba *phba)
5300 {
5301 	return phba->lpfc_sli_brdrestart(phba);
5302 }
5303 
5304 /**
5305  * lpfc_sli_chipset_init - Wait for the restart of the HBA after a restart
5306  * @phba: Pointer to HBA context object.
5307  *
5308  * This function is called after a HBA restart to wait for successful
5309  * restart of the HBA. Successful restart of the HBA is indicated by
5310  * HS_FFRDY and HS_MBRDY bits. If the HBA fails to restart even after 15
5311  * iteration, the function will restart the HBA again. The function returns
5312  * zero if HBA successfully restarted else returns negative error code.
5313  **/
5314 int
5315 lpfc_sli_chipset_init(struct lpfc_hba *phba)
5316 {
5317 	uint32_t status, i = 0;
5318 
5319 	/* Read the HBA Host Status Register */
5320 	if (lpfc_readl(phba->HSregaddr, &status))
5321 		return -EIO;
5322 
5323 	/* Check status register to see what current state is */
5324 	i = 0;
5325 	while ((status & (HS_FFRDY | HS_MBRDY)) != (HS_FFRDY | HS_MBRDY)) {
5326 
5327 		/* Check every 10ms for 10 retries, then every 100ms for 90
5328 		 * retries, then every 1 sec for 50 retires for a total of
5329 		 * ~60 seconds before reset the board again and check every
5330 		 * 1 sec for 50 retries. The up to 60 seconds before the
5331 		 * board ready is required by the Falcon FIPS zeroization
5332 		 * complete, and any reset the board in between shall cause
5333 		 * restart of zeroization, further delay the board ready.
5334 		 */
5335 		if (i++ >= 200) {
5336 			/* Adapter failed to init, timeout, status reg
5337 			   <status> */
5338 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5339 					"0436 Adapter failed to init, "
5340 					"timeout, status reg x%x, "
5341 					"FW Data: A8 x%x AC x%x\n", status,
5342 					readl(phba->MBslimaddr + 0xa8),
5343 					readl(phba->MBslimaddr + 0xac));
5344 			phba->link_state = LPFC_HBA_ERROR;
5345 			return -ETIMEDOUT;
5346 		}
5347 
5348 		/* Check to see if any errors occurred during init */
5349 		if (status & HS_FFERM) {
5350 			/* ERROR: During chipset initialization */
5351 			/* Adapter failed to init, chipset, status reg
5352 			   <status> */
5353 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5354 					"0437 Adapter failed to init, "
5355 					"chipset, status reg x%x, "
5356 					"FW Data: A8 x%x AC x%x\n", status,
5357 					readl(phba->MBslimaddr + 0xa8),
5358 					readl(phba->MBslimaddr + 0xac));
5359 			phba->link_state = LPFC_HBA_ERROR;
5360 			return -EIO;
5361 		}
5362 
5363 		if (i <= 10)
5364 			msleep(10);
5365 		else if (i <= 100)
5366 			msleep(100);
5367 		else
5368 			msleep(1000);
5369 
5370 		if (i == 150) {
5371 			/* Do post */
5372 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
5373 			lpfc_sli_brdrestart(phba);
5374 		}
5375 		/* Read the HBA Host Status Register */
5376 		if (lpfc_readl(phba->HSregaddr, &status))
5377 			return -EIO;
5378 	}
5379 
5380 	/* Check to see if any errors occurred during init */
5381 	if (status & HS_FFERM) {
5382 		/* ERROR: During chipset initialization */
5383 		/* Adapter failed to init, chipset, status reg <status> */
5384 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5385 				"0438 Adapter failed to init, chipset, "
5386 				"status reg x%x, "
5387 				"FW Data: A8 x%x AC x%x\n", status,
5388 				readl(phba->MBslimaddr + 0xa8),
5389 				readl(phba->MBslimaddr + 0xac));
5390 		phba->link_state = LPFC_HBA_ERROR;
5391 		return -EIO;
5392 	}
5393 
5394 	set_bit(HBA_NEEDS_CFG_PORT, &phba->hba_flag);
5395 
5396 	/* Clear all interrupt enable conditions */
5397 	writel(0, phba->HCregaddr);
5398 	readl(phba->HCregaddr); /* flush */
5399 
5400 	/* setup host attn register */
5401 	writel(0xffffffff, phba->HAregaddr);
5402 	readl(phba->HAregaddr); /* flush */
5403 	return 0;
5404 }
5405 
5406 /**
5407  * lpfc_sli_hbq_count - Get the number of HBQs to be configured
5408  *
5409  * This function calculates and returns the number of HBQs required to be
5410  * configured.
5411  **/
5412 int
5413 lpfc_sli_hbq_count(void)
5414 {
5415 	return ARRAY_SIZE(lpfc_hbq_defs);
5416 }
5417 
5418 /**
5419  * lpfc_sli_hbq_entry_count - Calculate total number of hbq entries
5420  *
5421  * This function adds the number of hbq entries in every HBQ to get
5422  * the total number of hbq entries required for the HBA and returns
5423  * the total count.
5424  **/
5425 static int
5426 lpfc_sli_hbq_entry_count(void)
5427 {
5428 	int  hbq_count = lpfc_sli_hbq_count();
5429 	int  count = 0;
5430 	int  i;
5431 
5432 	for (i = 0; i < hbq_count; ++i)
5433 		count += lpfc_hbq_defs[i]->entry_count;
5434 	return count;
5435 }
5436 
5437 /**
5438  * lpfc_sli_hbq_size - Calculate memory required for all hbq entries
5439  *
5440  * This function calculates amount of memory required for all hbq entries
5441  * to be configured and returns the total memory required.
5442  **/
5443 int
5444 lpfc_sli_hbq_size(void)
5445 {
5446 	return lpfc_sli_hbq_entry_count() * sizeof(struct lpfc_hbq_entry);
5447 }
5448 
5449 /**
5450  * lpfc_sli_hbq_setup - configure and initialize HBQs
5451  * @phba: Pointer to HBA context object.
5452  *
5453  * This function is called during the SLI initialization to configure
5454  * all the HBQs and post buffers to the HBQ. The caller is not
5455  * required to hold any locks. This function will return zero if successful
5456  * else it will return negative error code.
5457  **/
5458 static int
5459 lpfc_sli_hbq_setup(struct lpfc_hba *phba)
5460 {
5461 	int  hbq_count = lpfc_sli_hbq_count();
5462 	LPFC_MBOXQ_t *pmb;
5463 	MAILBOX_t *pmbox;
5464 	uint32_t hbqno;
5465 	uint32_t hbq_entry_index;
5466 
5467 				/* Get a Mailbox buffer to setup mailbox
5468 				 * commands for HBA initialization
5469 				 */
5470 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5471 
5472 	if (!pmb)
5473 		return -ENOMEM;
5474 
5475 	pmbox = &pmb->u.mb;
5476 
5477 	/* Initialize the struct lpfc_sli_hbq structure for each hbq */
5478 	phba->link_state = LPFC_INIT_MBX_CMDS;
5479 	phba->hbq_in_use = 1;
5480 
5481 	hbq_entry_index = 0;
5482 	for (hbqno = 0; hbqno < hbq_count; ++hbqno) {
5483 		phba->hbqs[hbqno].next_hbqPutIdx = 0;
5484 		phba->hbqs[hbqno].hbqPutIdx      = 0;
5485 		phba->hbqs[hbqno].local_hbqGetIdx   = 0;
5486 		phba->hbqs[hbqno].entry_count =
5487 			lpfc_hbq_defs[hbqno]->entry_count;
5488 		lpfc_config_hbq(phba, hbqno, lpfc_hbq_defs[hbqno],
5489 			hbq_entry_index, pmb);
5490 		hbq_entry_index += phba->hbqs[hbqno].entry_count;
5491 
5492 		if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
5493 			/* Adapter failed to init, mbxCmd <cmd> CFG_RING,
5494 			   mbxStatus <status>, ring <num> */
5495 
5496 			lpfc_printf_log(phba, KERN_ERR,
5497 					LOG_SLI | LOG_VPORT,
5498 					"1805 Adapter failed to init. "
5499 					"Data: x%x x%x x%x\n",
5500 					pmbox->mbxCommand,
5501 					pmbox->mbxStatus, hbqno);
5502 
5503 			phba->link_state = LPFC_HBA_ERROR;
5504 			mempool_free(pmb, phba->mbox_mem_pool);
5505 			return -ENXIO;
5506 		}
5507 	}
5508 	phba->hbq_count = hbq_count;
5509 
5510 	mempool_free(pmb, phba->mbox_mem_pool);
5511 
5512 	/* Initially populate or replenish the HBQs */
5513 	for (hbqno = 0; hbqno < hbq_count; ++hbqno)
5514 		lpfc_sli_hbqbuf_init_hbqs(phba, hbqno);
5515 	return 0;
5516 }
5517 
5518 /**
5519  * lpfc_sli4_rb_setup - Initialize and post RBs to HBA
5520  * @phba: Pointer to HBA context object.
5521  *
5522  * This function is called during the SLI initialization to configure
5523  * all the HBQs and post buffers to the HBQ. The caller is not
5524  * required to hold any locks. This function will return zero if successful
5525  * else it will return negative error code.
5526  **/
5527 static int
5528 lpfc_sli4_rb_setup(struct lpfc_hba *phba)
5529 {
5530 	phba->hbq_in_use = 1;
5531 	/**
5532 	 * Specific case when the MDS diagnostics is enabled and supported.
5533 	 * The receive buffer count is truncated to manage the incoming
5534 	 * traffic.
5535 	 **/
5536 	if (phba->cfg_enable_mds_diags && phba->mds_diags_support)
5537 		phba->hbqs[LPFC_ELS_HBQ].entry_count =
5538 			lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count >> 1;
5539 	else
5540 		phba->hbqs[LPFC_ELS_HBQ].entry_count =
5541 			lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count;
5542 	phba->hbq_count = 1;
5543 	lpfc_sli_hbqbuf_init_hbqs(phba, LPFC_ELS_HBQ);
5544 	/* Initially populate or replenish the HBQs */
5545 	return 0;
5546 }
5547 
5548 /**
5549  * lpfc_sli_config_port - Issue config port mailbox command
5550  * @phba: Pointer to HBA context object.
5551  * @sli_mode: sli mode - 2/3
5552  *
5553  * This function is called by the sli initialization code path
5554  * to issue config_port mailbox command. This function restarts the
5555  * HBA firmware and issues a config_port mailbox command to configure
5556  * the SLI interface in the sli mode specified by sli_mode
5557  * variable. The caller is not required to hold any locks.
5558  * The function returns 0 if successful, else returns negative error
5559  * code.
5560  **/
5561 int
5562 lpfc_sli_config_port(struct lpfc_hba *phba, int sli_mode)
5563 {
5564 	LPFC_MBOXQ_t *pmb;
5565 	uint32_t resetcount = 0, rc = 0, done = 0;
5566 
5567 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5568 	if (!pmb) {
5569 		phba->link_state = LPFC_HBA_ERROR;
5570 		return -ENOMEM;
5571 	}
5572 
5573 	phba->sli_rev = sli_mode;
5574 	while (resetcount < 2 && !done) {
5575 		spin_lock_irq(&phba->hbalock);
5576 		phba->sli.sli_flag |= LPFC_SLI_MBOX_ACTIVE;
5577 		spin_unlock_irq(&phba->hbalock);
5578 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
5579 		lpfc_sli_brdrestart(phba);
5580 		rc = lpfc_sli_chipset_init(phba);
5581 		if (rc)
5582 			break;
5583 
5584 		spin_lock_irq(&phba->hbalock);
5585 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
5586 		spin_unlock_irq(&phba->hbalock);
5587 		resetcount++;
5588 
5589 		/* Call pre CONFIG_PORT mailbox command initialization.  A
5590 		 * value of 0 means the call was successful.  Any other
5591 		 * nonzero value is a failure, but if ERESTART is returned,
5592 		 * the driver may reset the HBA and try again.
5593 		 */
5594 		rc = lpfc_config_port_prep(phba);
5595 		if (rc == -ERESTART) {
5596 			phba->link_state = LPFC_LINK_UNKNOWN;
5597 			continue;
5598 		} else if (rc)
5599 			break;
5600 
5601 		phba->link_state = LPFC_INIT_MBX_CMDS;
5602 		lpfc_config_port(phba, pmb);
5603 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
5604 		phba->sli3_options &= ~(LPFC_SLI3_NPIV_ENABLED |
5605 					LPFC_SLI3_HBQ_ENABLED |
5606 					LPFC_SLI3_CRP_ENABLED |
5607 					LPFC_SLI3_DSS_ENABLED);
5608 		if (rc != MBX_SUCCESS) {
5609 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5610 				"0442 Adapter failed to init, mbxCmd x%x "
5611 				"CONFIG_PORT, mbxStatus x%x Data: x%x\n",
5612 				pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus, 0);
5613 			spin_lock_irq(&phba->hbalock);
5614 			phba->sli.sli_flag &= ~LPFC_SLI_ACTIVE;
5615 			spin_unlock_irq(&phba->hbalock);
5616 			rc = -ENXIO;
5617 		} else {
5618 			/* Allow asynchronous mailbox command to go through */
5619 			spin_lock_irq(&phba->hbalock);
5620 			phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
5621 			spin_unlock_irq(&phba->hbalock);
5622 			done = 1;
5623 
5624 			if ((pmb->u.mb.un.varCfgPort.casabt == 1) &&
5625 			    (pmb->u.mb.un.varCfgPort.gasabt == 0))
5626 				lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
5627 					"3110 Port did not grant ASABT\n");
5628 		}
5629 	}
5630 	if (!done) {
5631 		rc = -EINVAL;
5632 		goto do_prep_failed;
5633 	}
5634 	if (pmb->u.mb.un.varCfgPort.sli_mode == 3) {
5635 		if (!pmb->u.mb.un.varCfgPort.cMA) {
5636 			rc = -ENXIO;
5637 			goto do_prep_failed;
5638 		}
5639 		if (phba->max_vpi && pmb->u.mb.un.varCfgPort.gmv) {
5640 			phba->sli3_options |= LPFC_SLI3_NPIV_ENABLED;
5641 			phba->max_vpi = pmb->u.mb.un.varCfgPort.max_vpi;
5642 			phba->max_vports = (phba->max_vpi > phba->max_vports) ?
5643 				phba->max_vpi : phba->max_vports;
5644 
5645 		} else
5646 			phba->max_vpi = 0;
5647 		if (pmb->u.mb.un.varCfgPort.gerbm)
5648 			phba->sli3_options |= LPFC_SLI3_HBQ_ENABLED;
5649 		if (pmb->u.mb.un.varCfgPort.gcrp)
5650 			phba->sli3_options |= LPFC_SLI3_CRP_ENABLED;
5651 
5652 		phba->hbq_get = phba->mbox->us.s3_pgp.hbq_get;
5653 		phba->port_gp = phba->mbox->us.s3_pgp.port;
5654 
5655 		if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
5656 			if (pmb->u.mb.un.varCfgPort.gbg == 0) {
5657 				phba->cfg_enable_bg = 0;
5658 				phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
5659 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5660 						"0443 Adapter did not grant "
5661 						"BlockGuard\n");
5662 			}
5663 		}
5664 	} else {
5665 		phba->hbq_get = NULL;
5666 		phba->port_gp = phba->mbox->us.s2.port;
5667 		phba->max_vpi = 0;
5668 	}
5669 do_prep_failed:
5670 	mempool_free(pmb, phba->mbox_mem_pool);
5671 	return rc;
5672 }
5673 
5674 
5675 /**
5676  * lpfc_sli_hba_setup - SLI initialization function
5677  * @phba: Pointer to HBA context object.
5678  *
5679  * This function is the main SLI initialization function. This function
5680  * is called by the HBA initialization code, HBA reset code and HBA
5681  * error attention handler code. Caller is not required to hold any
5682  * locks. This function issues config_port mailbox command to configure
5683  * the SLI, setup iocb rings and HBQ rings. In the end the function
5684  * calls the config_port_post function to issue init_link mailbox
5685  * command and to start the discovery. The function will return zero
5686  * if successful, else it will return negative error code.
5687  **/
5688 int
5689 lpfc_sli_hba_setup(struct lpfc_hba *phba)
5690 {
5691 	uint32_t rc;
5692 	int  i;
5693 	int longs;
5694 
5695 	/* Enable ISR already does config_port because of config_msi mbx */
5696 	if (test_bit(HBA_NEEDS_CFG_PORT, &phba->hba_flag)) {
5697 		rc = lpfc_sli_config_port(phba, LPFC_SLI_REV3);
5698 		if (rc)
5699 			return -EIO;
5700 		clear_bit(HBA_NEEDS_CFG_PORT, &phba->hba_flag);
5701 	}
5702 	phba->fcp_embed_io = 0;	/* SLI4 FC support only */
5703 
5704 	if (phba->sli_rev == 3) {
5705 		phba->iocb_cmd_size = SLI3_IOCB_CMD_SIZE;
5706 		phba->iocb_rsp_size = SLI3_IOCB_RSP_SIZE;
5707 	} else {
5708 		phba->iocb_cmd_size = SLI2_IOCB_CMD_SIZE;
5709 		phba->iocb_rsp_size = SLI2_IOCB_RSP_SIZE;
5710 		phba->sli3_options = 0;
5711 	}
5712 
5713 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5714 			"0444 Firmware in SLI %x mode. Max_vpi %d\n",
5715 			phba->sli_rev, phba->max_vpi);
5716 	rc = lpfc_sli_ring_map(phba);
5717 
5718 	if (rc)
5719 		goto lpfc_sli_hba_setup_error;
5720 
5721 	/* Initialize VPIs. */
5722 	if (phba->sli_rev == LPFC_SLI_REV3) {
5723 		/*
5724 		 * The VPI bitmask and physical ID array are allocated
5725 		 * and initialized once only - at driver load.  A port
5726 		 * reset doesn't need to reinitialize this memory.
5727 		 */
5728 		if ((phba->vpi_bmask == NULL) && (phba->vpi_ids == NULL)) {
5729 			longs = (phba->max_vpi + BITS_PER_LONG) / BITS_PER_LONG;
5730 			phba->vpi_bmask = kcalloc(longs,
5731 						  sizeof(unsigned long),
5732 						  GFP_KERNEL);
5733 			if (!phba->vpi_bmask) {
5734 				rc = -ENOMEM;
5735 				goto lpfc_sli_hba_setup_error;
5736 			}
5737 
5738 			phba->vpi_ids = kcalloc(phba->max_vpi + 1,
5739 						sizeof(uint16_t),
5740 						GFP_KERNEL);
5741 			if (!phba->vpi_ids) {
5742 				kfree(phba->vpi_bmask);
5743 				rc = -ENOMEM;
5744 				goto lpfc_sli_hba_setup_error;
5745 			}
5746 			for (i = 0; i < phba->max_vpi; i++)
5747 				phba->vpi_ids[i] = i;
5748 		}
5749 	}
5750 
5751 	/* Init HBQs */
5752 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
5753 		rc = lpfc_sli_hbq_setup(phba);
5754 		if (rc)
5755 			goto lpfc_sli_hba_setup_error;
5756 	}
5757 	spin_lock_irq(&phba->hbalock);
5758 	phba->sli.sli_flag |= LPFC_PROCESS_LA;
5759 	spin_unlock_irq(&phba->hbalock);
5760 
5761 	rc = lpfc_config_port_post(phba);
5762 	if (rc)
5763 		goto lpfc_sli_hba_setup_error;
5764 
5765 	return rc;
5766 
5767 lpfc_sli_hba_setup_error:
5768 	phba->link_state = LPFC_HBA_ERROR;
5769 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5770 			"0445 Firmware initialization failed\n");
5771 	return rc;
5772 }
5773 
5774 /**
5775  * lpfc_sli4_read_fcoe_params - Read fcoe params from conf region
5776  * @phba: Pointer to HBA context object.
5777  *
5778  * This function issue a dump mailbox command to read config region
5779  * 23 and parse the records in the region and populate driver
5780  * data structure.
5781  **/
5782 static int
5783 lpfc_sli4_read_fcoe_params(struct lpfc_hba *phba)
5784 {
5785 	LPFC_MBOXQ_t *mboxq;
5786 	struct lpfc_dmabuf *mp;
5787 	struct lpfc_mqe *mqe;
5788 	uint32_t data_length;
5789 	int rc;
5790 
5791 	/* Program the default value of vlan_id and fc_map */
5792 	phba->valid_vlan = 0;
5793 	phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
5794 	phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
5795 	phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
5796 
5797 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5798 	if (!mboxq)
5799 		return -ENOMEM;
5800 
5801 	mqe = &mboxq->u.mqe;
5802 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq)) {
5803 		rc = -ENOMEM;
5804 		goto out_free_mboxq;
5805 	}
5806 
5807 	mp = mboxq->ctx_buf;
5808 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5809 
5810 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
5811 			"(%d):2571 Mailbox cmd x%x Status x%x "
5812 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5813 			"x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5814 			"CQ: x%x x%x x%x x%x\n",
5815 			mboxq->vport ? mboxq->vport->vpi : 0,
5816 			bf_get(lpfc_mqe_command, mqe),
5817 			bf_get(lpfc_mqe_status, mqe),
5818 			mqe->un.mb_words[0], mqe->un.mb_words[1],
5819 			mqe->un.mb_words[2], mqe->un.mb_words[3],
5820 			mqe->un.mb_words[4], mqe->un.mb_words[5],
5821 			mqe->un.mb_words[6], mqe->un.mb_words[7],
5822 			mqe->un.mb_words[8], mqe->un.mb_words[9],
5823 			mqe->un.mb_words[10], mqe->un.mb_words[11],
5824 			mqe->un.mb_words[12], mqe->un.mb_words[13],
5825 			mqe->un.mb_words[14], mqe->un.mb_words[15],
5826 			mqe->un.mb_words[16], mqe->un.mb_words[50],
5827 			mboxq->mcqe.word0,
5828 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
5829 			mboxq->mcqe.trailer);
5830 
5831 	if (rc) {
5832 		rc = -EIO;
5833 		goto out_free_mboxq;
5834 	}
5835 	data_length = mqe->un.mb_words[5];
5836 	if (data_length > DMP_RGN23_SIZE) {
5837 		rc = -EIO;
5838 		goto out_free_mboxq;
5839 	}
5840 
5841 	lpfc_parse_fcoe_conf(phba, mp->virt, data_length);
5842 	rc = 0;
5843 
5844 out_free_mboxq:
5845 	lpfc_mbox_rsrc_cleanup(phba, mboxq, MBOX_THD_UNLOCKED);
5846 	return rc;
5847 }
5848 
5849 /**
5850  * lpfc_sli4_read_rev - Issue READ_REV and collect vpd data
5851  * @phba: pointer to lpfc hba data structure.
5852  * @mboxq: pointer to the LPFC_MBOXQ_t structure.
5853  * @vpd: pointer to the memory to hold resulting port vpd data.
5854  * @vpd_size: On input, the number of bytes allocated to @vpd.
5855  *	      On output, the number of data bytes in @vpd.
5856  *
5857  * This routine executes a READ_REV SLI4 mailbox command.  In
5858  * addition, this routine gets the port vpd data.
5859  *
5860  * Return codes
5861  * 	0 - successful
5862  * 	-ENOMEM - could not allocated memory.
5863  **/
5864 static int
5865 lpfc_sli4_read_rev(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
5866 		    uint8_t *vpd, uint32_t *vpd_size)
5867 {
5868 	int rc = 0;
5869 	uint32_t dma_size;
5870 	struct lpfc_dmabuf *dmabuf;
5871 	struct lpfc_mqe *mqe;
5872 
5873 	dmabuf = kzalloc_obj(struct lpfc_dmabuf);
5874 	if (!dmabuf)
5875 		return -ENOMEM;
5876 
5877 	/*
5878 	 * Get a DMA buffer for the vpd data resulting from the READ_REV
5879 	 * mailbox command.
5880 	 */
5881 	dma_size = *vpd_size;
5882 	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev, dma_size,
5883 					  &dmabuf->phys, GFP_KERNEL);
5884 	if (!dmabuf->virt) {
5885 		kfree(dmabuf);
5886 		return -ENOMEM;
5887 	}
5888 
5889 	/*
5890 	 * The SLI4 implementation of READ_REV conflicts at word1,
5891 	 * bits 31:16 and SLI4 adds vpd functionality not present
5892 	 * in SLI3.  This code corrects the conflicts.
5893 	 */
5894 	lpfc_read_rev(phba, mboxq);
5895 	mqe = &mboxq->u.mqe;
5896 	mqe->un.read_rev.vpd_paddr_high = putPaddrHigh(dmabuf->phys);
5897 	mqe->un.read_rev.vpd_paddr_low = putPaddrLow(dmabuf->phys);
5898 	mqe->un.read_rev.word1 &= 0x0000FFFF;
5899 	bf_set(lpfc_mbx_rd_rev_vpd, &mqe->un.read_rev, 1);
5900 	bf_set(lpfc_mbx_rd_rev_avail_len, &mqe->un.read_rev, dma_size);
5901 
5902 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5903 	if (rc) {
5904 		dma_free_coherent(&phba->pcidev->dev, dma_size,
5905 				  dmabuf->virt, dmabuf->phys);
5906 		kfree(dmabuf);
5907 		return -EIO;
5908 	}
5909 
5910 	/*
5911 	 * The available vpd length cannot be bigger than the
5912 	 * DMA buffer passed to the port.  Catch the less than
5913 	 * case and update the caller's size.
5914 	 */
5915 	if (mqe->un.read_rev.avail_vpd_len < *vpd_size)
5916 		*vpd_size = mqe->un.read_rev.avail_vpd_len;
5917 
5918 	memcpy(vpd, dmabuf->virt, *vpd_size);
5919 
5920 	dma_free_coherent(&phba->pcidev->dev, dma_size,
5921 			  dmabuf->virt, dmabuf->phys);
5922 	kfree(dmabuf);
5923 	return 0;
5924 }
5925 
5926 /**
5927  * lpfc_sli4_get_ctl_attr - Retrieve SLI4 device controller attributes
5928  * @phba: pointer to lpfc hba data structure.
5929  *
5930  * This routine retrieves SLI4 device physical port name this PCI function
5931  * is attached to.
5932  *
5933  * Return codes
5934  *      0 - successful
5935  *      otherwise - failed to retrieve controller attributes
5936  **/
5937 static int
5938 lpfc_sli4_get_ctl_attr(struct lpfc_hba *phba)
5939 {
5940 	LPFC_MBOXQ_t *mboxq;
5941 	struct lpfc_mbx_get_cntl_attributes *mbx_cntl_attr;
5942 	struct lpfc_controller_attribute *cntl_attr;
5943 	void *virtaddr = NULL;
5944 	uint32_t alloclen, reqlen;
5945 	uint32_t shdr_status, shdr_add_status;
5946 	union lpfc_sli4_cfg_shdr *shdr;
5947 	int rc;
5948 
5949 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5950 	if (!mboxq)
5951 		return -ENOMEM;
5952 
5953 	/* Send COMMON_GET_CNTL_ATTRIBUTES mbox cmd */
5954 	reqlen = sizeof(struct lpfc_mbx_get_cntl_attributes);
5955 	alloclen = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
5956 			LPFC_MBOX_OPCODE_GET_CNTL_ATTRIBUTES, reqlen,
5957 			LPFC_SLI4_MBX_NEMBED);
5958 
5959 	if (alloclen < reqlen) {
5960 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5961 				"3084 Allocated DMA memory size (%d) is "
5962 				"less than the requested DMA memory size "
5963 				"(%d)\n", alloclen, reqlen);
5964 		rc = -ENOMEM;
5965 		goto out_free_mboxq;
5966 	}
5967 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5968 	virtaddr = mboxq->sge_array->addr[0];
5969 	mbx_cntl_attr = (struct lpfc_mbx_get_cntl_attributes *)virtaddr;
5970 	shdr = &mbx_cntl_attr->cfg_shdr;
5971 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
5972 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
5973 	if (shdr_status || shdr_add_status || rc) {
5974 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5975 				"3085 Mailbox x%x (x%x/x%x) failed, "
5976 				"rc:x%x, status:x%x, add_status:x%x\n",
5977 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
5978 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
5979 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
5980 				rc, shdr_status, shdr_add_status);
5981 		rc = -ENXIO;
5982 		goto out_free_mboxq;
5983 	}
5984 
5985 	cntl_attr = &mbx_cntl_attr->cntl_attr;
5986 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL;
5987 	phba->sli4_hba.lnk_info.lnk_tp =
5988 		bf_get(lpfc_cntl_attr_lnk_type, cntl_attr);
5989 	phba->sli4_hba.lnk_info.lnk_no =
5990 		bf_get(lpfc_cntl_attr_lnk_numb, cntl_attr);
5991 	phba->sli4_hba.flash_id = bf_get(lpfc_cntl_attr_flash_id, cntl_attr);
5992 	phba->sli4_hba.asic_rev = bf_get(lpfc_cntl_attr_asic_rev, cntl_attr);
5993 
5994 	memcpy(phba->BIOSVersion, cntl_attr->bios_ver_str,
5995 		sizeof(phba->BIOSVersion));
5996 	phba->BIOSVersion[sizeof(phba->BIOSVersion) - 1] = '\0';
5997 
5998 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5999 			"3086 lnk_type:%d, lnk_numb:%d, bios_ver:%s, "
6000 			"flash_id: x%02x, asic_rev: x%02x\n",
6001 			phba->sli4_hba.lnk_info.lnk_tp,
6002 			phba->sli4_hba.lnk_info.lnk_no,
6003 			phba->BIOSVersion, phba->sli4_hba.flash_id,
6004 			phba->sli4_hba.asic_rev);
6005 out_free_mboxq:
6006 	if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
6007 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
6008 	else
6009 		mempool_free(mboxq, phba->mbox_mem_pool);
6010 	return rc;
6011 }
6012 
6013 /**
6014  * lpfc_sli4_retrieve_pport_name - Retrieve SLI4 device physical port name
6015  * @phba: pointer to lpfc hba data structure.
6016  *
6017  * This routine retrieves SLI4 device physical port name this PCI function
6018  * is attached to.
6019  *
6020  * Return codes
6021  *      0 - successful
6022  *      otherwise - failed to retrieve physical port name
6023  **/
6024 static int
6025 lpfc_sli4_retrieve_pport_name(struct lpfc_hba *phba)
6026 {
6027 	LPFC_MBOXQ_t *mboxq;
6028 	struct lpfc_mbx_get_port_name *get_port_name;
6029 	uint32_t shdr_status, shdr_add_status;
6030 	union lpfc_sli4_cfg_shdr *shdr;
6031 	char cport_name = 0;
6032 	int rc;
6033 
6034 	/* We assume nothing at this point */
6035 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
6036 	phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_NON;
6037 
6038 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6039 	if (!mboxq)
6040 		return -ENOMEM;
6041 	/* obtain link type and link number via READ_CONFIG */
6042 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
6043 	lpfc_sli4_read_config(phba);
6044 
6045 	if (phba->sli4_hba.fawwpn_flag & LPFC_FAWWPN_CONFIG)
6046 		phba->sli4_hba.fawwpn_flag |= LPFC_FAWWPN_FABRIC;
6047 
6048 	if (phba->sli4_hba.lnk_info.lnk_dv == LPFC_LNK_DAT_VAL)
6049 		goto retrieve_ppname;
6050 
6051 	/* obtain link type and link number via COMMON_GET_CNTL_ATTRIBUTES */
6052 	rc = lpfc_sli4_get_ctl_attr(phba);
6053 	if (rc)
6054 		goto out_free_mboxq;
6055 
6056 retrieve_ppname:
6057 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
6058 		LPFC_MBOX_OPCODE_GET_PORT_NAME,
6059 		sizeof(struct lpfc_mbx_get_port_name) -
6060 		sizeof(struct lpfc_sli4_cfg_mhdr),
6061 		LPFC_SLI4_MBX_EMBED);
6062 	get_port_name = &mboxq->u.mqe.un.get_port_name;
6063 	shdr = (union lpfc_sli4_cfg_shdr *)&get_port_name->header.cfg_shdr;
6064 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_OPCODE_VERSION_1);
6065 	bf_set(lpfc_mbx_get_port_name_lnk_type, &get_port_name->u.request,
6066 		phba->sli4_hba.lnk_info.lnk_tp);
6067 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6068 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
6069 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
6070 	if (shdr_status || shdr_add_status || rc) {
6071 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6072 				"3087 Mailbox x%x (x%x/x%x) failed: "
6073 				"rc:x%x, status:x%x, add_status:x%x\n",
6074 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
6075 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
6076 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
6077 				rc, shdr_status, shdr_add_status);
6078 		rc = -ENXIO;
6079 		goto out_free_mboxq;
6080 	}
6081 	switch (phba->sli4_hba.lnk_info.lnk_no) {
6082 	case LPFC_LINK_NUMBER_0:
6083 		cport_name = bf_get(lpfc_mbx_get_port_name_name0,
6084 				&get_port_name->u.response);
6085 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6086 		break;
6087 	case LPFC_LINK_NUMBER_1:
6088 		cport_name = bf_get(lpfc_mbx_get_port_name_name1,
6089 				&get_port_name->u.response);
6090 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6091 		break;
6092 	case LPFC_LINK_NUMBER_2:
6093 		cport_name = bf_get(lpfc_mbx_get_port_name_name2,
6094 				&get_port_name->u.response);
6095 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6096 		break;
6097 	case LPFC_LINK_NUMBER_3:
6098 		cport_name = bf_get(lpfc_mbx_get_port_name_name3,
6099 				&get_port_name->u.response);
6100 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6101 		break;
6102 	default:
6103 		break;
6104 	}
6105 
6106 	if (phba->sli4_hba.pport_name_sta == LPFC_SLI4_PPNAME_GET) {
6107 		phba->Port[0] = cport_name;
6108 		phba->Port[1] = '\0';
6109 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6110 				"3091 SLI get port name: %s\n", phba->Port);
6111 	}
6112 
6113 out_free_mboxq:
6114 	if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
6115 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
6116 	else
6117 		mempool_free(mboxq, phba->mbox_mem_pool);
6118 	return rc;
6119 }
6120 
6121 /**
6122  * lpfc_sli4_arm_cqeq_intr - Arm sli-4 device completion and event queues
6123  * @phba: pointer to lpfc hba data structure.
6124  *
6125  * This routine is called to explicitly arm the SLI4 device's completion and
6126  * event queues
6127  **/
6128 static void
6129 lpfc_sli4_arm_cqeq_intr(struct lpfc_hba *phba)
6130 {
6131 	int qidx;
6132 	struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
6133 	struct lpfc_sli4_hdw_queue *qp;
6134 	struct lpfc_queue *eq;
6135 
6136 	sli4_hba->sli4_write_cq_db(phba, sli4_hba->mbx_cq, 0, LPFC_QUEUE_REARM);
6137 	sli4_hba->sli4_write_cq_db(phba, sli4_hba->els_cq, 0, LPFC_QUEUE_REARM);
6138 	if (sli4_hba->nvmels_cq)
6139 		sli4_hba->sli4_write_cq_db(phba, sli4_hba->nvmels_cq, 0,
6140 					   LPFC_QUEUE_REARM);
6141 
6142 	if (sli4_hba->hdwq) {
6143 		/* Loop thru all Hardware Queues */
6144 		for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
6145 			qp = &sli4_hba->hdwq[qidx];
6146 			/* ARM the corresponding CQ */
6147 			sli4_hba->sli4_write_cq_db(phba, qp->io_cq, 0,
6148 						LPFC_QUEUE_REARM);
6149 		}
6150 
6151 		/* Loop thru all IRQ vectors */
6152 		for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
6153 			eq = sli4_hba->hba_eq_hdl[qidx].eq;
6154 			/* ARM the corresponding EQ */
6155 			sli4_hba->sli4_write_eq_db(phba, eq,
6156 						   0, LPFC_QUEUE_REARM);
6157 		}
6158 	}
6159 
6160 	if (phba->nvmet_support) {
6161 		for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++) {
6162 			sli4_hba->sli4_write_cq_db(phba,
6163 				sli4_hba->nvmet_cqset[qidx], 0,
6164 				LPFC_QUEUE_REARM);
6165 		}
6166 	}
6167 }
6168 
6169 /**
6170  * lpfc_sli4_get_avail_extnt_rsrc - Get available resource extent count.
6171  * @phba: Pointer to HBA context object.
6172  * @type: The resource extent type.
6173  * @extnt_count: buffer to hold port available extent count.
6174  * @extnt_size: buffer to hold element count per extent.
6175  *
6176  * This function calls the port and retrievs the number of available
6177  * extents and their size for a particular extent type.
6178  *
6179  * Returns: 0 if successful.  Nonzero otherwise.
6180  **/
6181 int
6182 lpfc_sli4_get_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type,
6183 			       uint16_t *extnt_count, uint16_t *extnt_size)
6184 {
6185 	int rc = 0;
6186 	uint32_t length;
6187 	uint32_t mbox_tmo;
6188 	struct lpfc_mbx_get_rsrc_extent_info *rsrc_info;
6189 	LPFC_MBOXQ_t *mbox;
6190 
6191 	*extnt_count = 0;
6192 	*extnt_size = 0;
6193 
6194 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6195 	if (!mbox)
6196 		return -ENOMEM;
6197 
6198 	/* Find out how many extents are available for this resource type */
6199 	length = (sizeof(struct lpfc_mbx_get_rsrc_extent_info) -
6200 		  sizeof(struct lpfc_sli4_cfg_mhdr));
6201 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6202 			 LPFC_MBOX_OPCODE_GET_RSRC_EXTENT_INFO,
6203 			 length, LPFC_SLI4_MBX_EMBED);
6204 
6205 	/* Send an extents count of 0 - the GET doesn't use it. */
6206 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
6207 					LPFC_SLI4_MBX_EMBED);
6208 	if (unlikely(rc)) {
6209 		rc = -EIO;
6210 		goto err_exit;
6211 	}
6212 
6213 	if (!phba->sli4_hba.intr_enable)
6214 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6215 	else {
6216 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6217 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6218 	}
6219 	if (unlikely(rc)) {
6220 		rc = -EIO;
6221 		goto err_exit;
6222 	}
6223 
6224 	rsrc_info = &mbox->u.mqe.un.rsrc_extent_info;
6225 	if (bf_get(lpfc_mbox_hdr_status,
6226 		   &rsrc_info->header.cfg_shdr.response)) {
6227 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6228 				"2930 Failed to get resource extents "
6229 				"Status 0x%x Add'l Status 0x%x\n",
6230 				bf_get(lpfc_mbox_hdr_status,
6231 				       &rsrc_info->header.cfg_shdr.response),
6232 				bf_get(lpfc_mbox_hdr_add_status,
6233 				       &rsrc_info->header.cfg_shdr.response));
6234 		rc = -EIO;
6235 		goto err_exit;
6236 	}
6237 
6238 	*extnt_count = bf_get(lpfc_mbx_get_rsrc_extent_info_cnt,
6239 			      &rsrc_info->u.rsp);
6240 	*extnt_size = bf_get(lpfc_mbx_get_rsrc_extent_info_size,
6241 			     &rsrc_info->u.rsp);
6242 
6243 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6244 			"3162 Retrieved extents type-%d from port: count:%d, "
6245 			"size:%d\n", type, *extnt_count, *extnt_size);
6246 
6247 err_exit:
6248 	mempool_free(mbox, phba->mbox_mem_pool);
6249 	return rc;
6250 }
6251 
6252 /**
6253  * lpfc_sli4_chk_avail_extnt_rsrc - Check for available SLI4 resource extents.
6254  * @phba: Pointer to HBA context object.
6255  * @type: The extent type to check.
6256  *
6257  * This function reads the current available extents from the port and checks
6258  * if the extent count or extent size has changed since the last access.
6259  * Callers use this routine post port reset to understand if there is a
6260  * extent reprovisioning requirement.
6261  *
6262  * Returns:
6263  *   -Error: error indicates problem.
6264  *   1: Extent count or size has changed.
6265  *   0: No changes.
6266  **/
6267 static int
6268 lpfc_sli4_chk_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type)
6269 {
6270 	uint16_t curr_ext_cnt, rsrc_ext_cnt;
6271 	uint16_t size_diff, rsrc_ext_size;
6272 	int rc = 0;
6273 	struct lpfc_rsrc_blks *rsrc_entry;
6274 	struct list_head *rsrc_blk_list = NULL;
6275 
6276 	size_diff = 0;
6277 	curr_ext_cnt = 0;
6278 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
6279 					    &rsrc_ext_cnt,
6280 					    &rsrc_ext_size);
6281 	if (unlikely(rc))
6282 		return -EIO;
6283 
6284 	switch (type) {
6285 	case LPFC_RSC_TYPE_FCOE_RPI:
6286 		rsrc_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
6287 		break;
6288 	case LPFC_RSC_TYPE_FCOE_VPI:
6289 		rsrc_blk_list = &phba->lpfc_vpi_blk_list;
6290 		break;
6291 	case LPFC_RSC_TYPE_FCOE_XRI:
6292 		rsrc_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
6293 		break;
6294 	case LPFC_RSC_TYPE_FCOE_VFI:
6295 		rsrc_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
6296 		break;
6297 	default:
6298 		break;
6299 	}
6300 
6301 	list_for_each_entry(rsrc_entry, rsrc_blk_list, list) {
6302 		curr_ext_cnt++;
6303 		if (rsrc_entry->rsrc_size != rsrc_ext_size)
6304 			size_diff++;
6305 	}
6306 
6307 	if (curr_ext_cnt != rsrc_ext_cnt || size_diff != 0)
6308 		rc = 1;
6309 
6310 	return rc;
6311 }
6312 
6313 /**
6314  * lpfc_sli4_cfg_post_extnts -
6315  * @phba: Pointer to HBA context object.
6316  * @extnt_cnt: number of available extents.
6317  * @type: the extent type (rpi, xri, vfi, vpi).
6318  * @emb: buffer to hold either MBX_EMBED or MBX_NEMBED operation.
6319  * @mbox: pointer to the caller's allocated mailbox structure.
6320  *
6321  * This function executes the extents allocation request.  It also
6322  * takes care of the amount of memory needed to allocate or get the
6323  * allocated extents. It is the caller's responsibility to evaluate
6324  * the response.
6325  *
6326  * Returns:
6327  *   -Error:  Error value describes the condition found.
6328  *   0: if successful
6329  **/
6330 static int
6331 lpfc_sli4_cfg_post_extnts(struct lpfc_hba *phba, uint16_t extnt_cnt,
6332 			  uint16_t type, bool *emb, LPFC_MBOXQ_t *mbox)
6333 {
6334 	int rc = 0;
6335 	uint32_t req_len;
6336 	uint32_t emb_len;
6337 	uint32_t alloc_len, mbox_tmo;
6338 
6339 	/* Calculate the total requested length of the dma memory */
6340 	req_len = extnt_cnt * sizeof(uint16_t);
6341 
6342 	/*
6343 	 * Calculate the size of an embedded mailbox.  The uint32_t
6344 	 * accounts for extents-specific word.
6345 	 */
6346 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
6347 		sizeof(uint32_t);
6348 
6349 	/*
6350 	 * Presume the allocation and response will fit into an embedded
6351 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
6352 	 */
6353 	*emb = LPFC_SLI4_MBX_EMBED;
6354 	if (req_len > emb_len) {
6355 		req_len = extnt_cnt * sizeof(uint16_t) +
6356 			sizeof(union lpfc_sli4_cfg_shdr) +
6357 			sizeof(uint32_t);
6358 		*emb = LPFC_SLI4_MBX_NEMBED;
6359 	}
6360 
6361 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6362 				     LPFC_MBOX_OPCODE_ALLOC_RSRC_EXTENT,
6363 				     req_len, *emb);
6364 	if (alloc_len < req_len) {
6365 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6366 			"2982 Allocated DMA memory size (x%x) is "
6367 			"less than the requested DMA memory "
6368 			"size (x%x)\n", alloc_len, req_len);
6369 		return -ENOMEM;
6370 	}
6371 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, extnt_cnt, type, *emb);
6372 	if (unlikely(rc))
6373 		return -EIO;
6374 
6375 	if (!phba->sli4_hba.intr_enable)
6376 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6377 	else {
6378 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6379 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6380 	}
6381 
6382 	if (unlikely(rc))
6383 		rc = -EIO;
6384 	return rc;
6385 }
6386 
6387 /**
6388  * lpfc_sli4_alloc_extent - Allocate an SLI4 resource extent.
6389  * @phba: Pointer to HBA context object.
6390  * @type:  The resource extent type to allocate.
6391  *
6392  * This function allocates the number of elements for the specified
6393  * resource type.
6394  **/
6395 static int
6396 lpfc_sli4_alloc_extent(struct lpfc_hba *phba, uint16_t type)
6397 {
6398 	bool emb = false;
6399 	uint16_t rsrc_id_cnt, rsrc_cnt, rsrc_size;
6400 	uint16_t rsrc_id, rsrc_start, j, k;
6401 	uint16_t *ids;
6402 	int i, rc;
6403 	unsigned long longs;
6404 	unsigned long *bmask;
6405 	struct lpfc_rsrc_blks *rsrc_blks;
6406 	LPFC_MBOXQ_t *mbox;
6407 	uint32_t length;
6408 	struct lpfc_id_range *id_array = NULL;
6409 	void *virtaddr = NULL;
6410 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
6411 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
6412 	struct list_head *ext_blk_list;
6413 
6414 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
6415 					    &rsrc_cnt,
6416 					    &rsrc_size);
6417 	if (unlikely(rc))
6418 		return -EIO;
6419 
6420 	if ((rsrc_cnt == 0) || (rsrc_size == 0)) {
6421 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6422 			"3009 No available Resource Extents "
6423 			"for resource type 0x%x: Count: 0x%x, "
6424 			"Size 0x%x\n", type, rsrc_cnt,
6425 			rsrc_size);
6426 		return -ENOMEM;
6427 	}
6428 
6429 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_INIT | LOG_SLI,
6430 			"2903 Post resource extents type-0x%x: "
6431 			"count:%d, size %d\n", type, rsrc_cnt, rsrc_size);
6432 
6433 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6434 	if (!mbox)
6435 		return -ENOMEM;
6436 
6437 	rc = lpfc_sli4_cfg_post_extnts(phba, rsrc_cnt, type, &emb, mbox);
6438 	if (unlikely(rc)) {
6439 		rc = -EIO;
6440 		goto err_exit;
6441 	}
6442 
6443 	/*
6444 	 * Figure out where the response is located.  Then get local pointers
6445 	 * to the response data.  The port does not guarantee to respond to
6446 	 * all extents counts request so update the local variable with the
6447 	 * allocated count from the port.
6448 	 */
6449 	if (emb == LPFC_SLI4_MBX_EMBED) {
6450 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
6451 		id_array = &rsrc_ext->u.rsp.id[0];
6452 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
6453 	} else {
6454 		virtaddr = mbox->sge_array->addr[0];
6455 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
6456 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
6457 		id_array = &n_rsrc->id;
6458 	}
6459 
6460 	longs = ((rsrc_cnt * rsrc_size) + BITS_PER_LONG - 1) / BITS_PER_LONG;
6461 	rsrc_id_cnt = rsrc_cnt * rsrc_size;
6462 
6463 	/*
6464 	 * Based on the resource size and count, correct the base and max
6465 	 * resource values.
6466 	 */
6467 	length = sizeof(struct lpfc_rsrc_blks);
6468 	switch (type) {
6469 	case LPFC_RSC_TYPE_FCOE_RPI:
6470 		phba->sli4_hba.rpi_bmask = kcalloc(longs,
6471 						   sizeof(unsigned long),
6472 						   GFP_KERNEL);
6473 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
6474 			rc = -ENOMEM;
6475 			goto err_exit;
6476 		}
6477 		phba->sli4_hba.rpi_ids = kcalloc(rsrc_id_cnt,
6478 						 sizeof(uint16_t),
6479 						 GFP_KERNEL);
6480 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
6481 			kfree(phba->sli4_hba.rpi_bmask);
6482 			rc = -ENOMEM;
6483 			goto err_exit;
6484 		}
6485 
6486 		/*
6487 		 * The next_rpi was initialized with the maximum available
6488 		 * count but the port may allocate a smaller number.  Catch
6489 		 * that case and update the next_rpi.
6490 		 */
6491 		phba->sli4_hba.next_rpi = rsrc_id_cnt;
6492 
6493 		/* Initialize local ptrs for common extent processing later. */
6494 		bmask = phba->sli4_hba.rpi_bmask;
6495 		ids = phba->sli4_hba.rpi_ids;
6496 		ext_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
6497 		break;
6498 	case LPFC_RSC_TYPE_FCOE_VPI:
6499 		phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
6500 					  GFP_KERNEL);
6501 		if (unlikely(!phba->vpi_bmask)) {
6502 			rc = -ENOMEM;
6503 			goto err_exit;
6504 		}
6505 		phba->vpi_ids = kcalloc(rsrc_id_cnt, sizeof(uint16_t),
6506 					 GFP_KERNEL);
6507 		if (unlikely(!phba->vpi_ids)) {
6508 			kfree(phba->vpi_bmask);
6509 			rc = -ENOMEM;
6510 			goto err_exit;
6511 		}
6512 
6513 		/* Initialize local ptrs for common extent processing later. */
6514 		bmask = phba->vpi_bmask;
6515 		ids = phba->vpi_ids;
6516 		ext_blk_list = &phba->lpfc_vpi_blk_list;
6517 		break;
6518 	case LPFC_RSC_TYPE_FCOE_XRI:
6519 		phba->sli4_hba.xri_bmask = kcalloc(longs,
6520 						   sizeof(unsigned long),
6521 						   GFP_KERNEL);
6522 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
6523 			rc = -ENOMEM;
6524 			goto err_exit;
6525 		}
6526 		phba->sli4_hba.max_cfg_param.xri_used = 0;
6527 		phba->sli4_hba.xri_ids = kcalloc(rsrc_id_cnt,
6528 						 sizeof(uint16_t),
6529 						 GFP_KERNEL);
6530 		if (unlikely(!phba->sli4_hba.xri_ids)) {
6531 			kfree(phba->sli4_hba.xri_bmask);
6532 			rc = -ENOMEM;
6533 			goto err_exit;
6534 		}
6535 
6536 		/* Initialize local ptrs for common extent processing later. */
6537 		bmask = phba->sli4_hba.xri_bmask;
6538 		ids = phba->sli4_hba.xri_ids;
6539 		ext_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
6540 		break;
6541 	case LPFC_RSC_TYPE_FCOE_VFI:
6542 		phba->sli4_hba.vfi_bmask = kcalloc(longs,
6543 						   sizeof(unsigned long),
6544 						   GFP_KERNEL);
6545 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
6546 			rc = -ENOMEM;
6547 			goto err_exit;
6548 		}
6549 		phba->sli4_hba.vfi_ids = kcalloc(rsrc_id_cnt,
6550 						 sizeof(uint16_t),
6551 						 GFP_KERNEL);
6552 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
6553 			kfree(phba->sli4_hba.vfi_bmask);
6554 			rc = -ENOMEM;
6555 			goto err_exit;
6556 		}
6557 
6558 		/* Initialize local ptrs for common extent processing later. */
6559 		bmask = phba->sli4_hba.vfi_bmask;
6560 		ids = phba->sli4_hba.vfi_ids;
6561 		ext_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
6562 		break;
6563 	default:
6564 		/* Unsupported Opcode.  Fail call. */
6565 		id_array = NULL;
6566 		bmask = NULL;
6567 		ids = NULL;
6568 		ext_blk_list = NULL;
6569 		goto err_exit;
6570 	}
6571 
6572 	/*
6573 	 * Complete initializing the extent configuration with the
6574 	 * allocated ids assigned to this function.  The bitmask serves
6575 	 * as an index into the array and manages the available ids.  The
6576 	 * array just stores the ids communicated to the port via the wqes.
6577 	 */
6578 	for (i = 0, j = 0, k = 0; i < rsrc_cnt; i++) {
6579 		if ((i % 2) == 0)
6580 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_0,
6581 					 &id_array[k]);
6582 		else
6583 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_1,
6584 					 &id_array[k]);
6585 
6586 		rsrc_blks = kzalloc(length, GFP_KERNEL);
6587 		if (unlikely(!rsrc_blks)) {
6588 			rc = -ENOMEM;
6589 			kfree(bmask);
6590 			kfree(ids);
6591 			goto err_exit;
6592 		}
6593 		rsrc_blks->rsrc_start = rsrc_id;
6594 		rsrc_blks->rsrc_size = rsrc_size;
6595 		list_add_tail(&rsrc_blks->list, ext_blk_list);
6596 		rsrc_start = rsrc_id;
6597 		if ((type == LPFC_RSC_TYPE_FCOE_XRI) && (j == 0)) {
6598 			phba->sli4_hba.io_xri_start = rsrc_start +
6599 				lpfc_sli4_get_iocb_cnt(phba);
6600 		}
6601 
6602 		while (rsrc_id < (rsrc_start + rsrc_size)) {
6603 			ids[j] = rsrc_id;
6604 			rsrc_id++;
6605 			j++;
6606 		}
6607 		/* Entire word processed.  Get next word.*/
6608 		if ((i % 2) == 1)
6609 			k++;
6610 	}
6611  err_exit:
6612 	lpfc_sli4_mbox_cmd_free(phba, mbox);
6613 	return rc;
6614 }
6615 
6616 
6617 
6618 /**
6619  * lpfc_sli4_dealloc_extent - Deallocate an SLI4 resource extent.
6620  * @phba: Pointer to HBA context object.
6621  * @type: the extent's type.
6622  *
6623  * This function deallocates all extents of a particular resource type.
6624  * SLI4 does not allow for deallocating a particular extent range.  It
6625  * is the caller's responsibility to release all kernel memory resources.
6626  **/
6627 static int
6628 lpfc_sli4_dealloc_extent(struct lpfc_hba *phba, uint16_t type)
6629 {
6630 	int rc;
6631 	uint32_t length, mbox_tmo = 0;
6632 	LPFC_MBOXQ_t *mbox;
6633 	struct lpfc_mbx_dealloc_rsrc_extents *dealloc_rsrc;
6634 	struct lpfc_rsrc_blks *rsrc_blk, *rsrc_blk_next;
6635 
6636 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6637 	if (!mbox)
6638 		return -ENOMEM;
6639 
6640 	/*
6641 	 * This function sends an embedded mailbox because it only sends the
6642 	 * the resource type.  All extents of this type are released by the
6643 	 * port.
6644 	 */
6645 	length = (sizeof(struct lpfc_mbx_dealloc_rsrc_extents) -
6646 		  sizeof(struct lpfc_sli4_cfg_mhdr));
6647 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6648 			 LPFC_MBOX_OPCODE_DEALLOC_RSRC_EXTENT,
6649 			 length, LPFC_SLI4_MBX_EMBED);
6650 
6651 	/* Send an extents count of 0 - the dealloc doesn't use it. */
6652 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
6653 					LPFC_SLI4_MBX_EMBED);
6654 	if (unlikely(rc)) {
6655 		rc = -EIO;
6656 		goto out_free_mbox;
6657 	}
6658 	if (!phba->sli4_hba.intr_enable)
6659 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6660 	else {
6661 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6662 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6663 	}
6664 	if (unlikely(rc)) {
6665 		rc = -EIO;
6666 		goto out_free_mbox;
6667 	}
6668 
6669 	dealloc_rsrc = &mbox->u.mqe.un.dealloc_rsrc_extents;
6670 	if (bf_get(lpfc_mbox_hdr_status,
6671 		   &dealloc_rsrc->header.cfg_shdr.response)) {
6672 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6673 				"2919 Failed to release resource extents "
6674 				"for type %d - Status 0x%x Add'l Status 0x%x. "
6675 				"Resource memory not released.\n",
6676 				type,
6677 				bf_get(lpfc_mbox_hdr_status,
6678 				    &dealloc_rsrc->header.cfg_shdr.response),
6679 				bf_get(lpfc_mbox_hdr_add_status,
6680 				    &dealloc_rsrc->header.cfg_shdr.response));
6681 		rc = -EIO;
6682 		goto out_free_mbox;
6683 	}
6684 
6685 	/* Release kernel memory resources for the specific type. */
6686 	switch (type) {
6687 	case LPFC_RSC_TYPE_FCOE_VPI:
6688 		kfree(phba->vpi_bmask);
6689 		kfree(phba->vpi_ids);
6690 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6691 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6692 				    &phba->lpfc_vpi_blk_list, list) {
6693 			list_del_init(&rsrc_blk->list);
6694 			kfree(rsrc_blk);
6695 		}
6696 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
6697 		break;
6698 	case LPFC_RSC_TYPE_FCOE_XRI:
6699 		kfree(phba->sli4_hba.xri_bmask);
6700 		kfree(phba->sli4_hba.xri_ids);
6701 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6702 				    &phba->sli4_hba.lpfc_xri_blk_list, list) {
6703 			list_del_init(&rsrc_blk->list);
6704 			kfree(rsrc_blk);
6705 		}
6706 		break;
6707 	case LPFC_RSC_TYPE_FCOE_VFI:
6708 		kfree(phba->sli4_hba.vfi_bmask);
6709 		kfree(phba->sli4_hba.vfi_ids);
6710 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6711 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6712 				    &phba->sli4_hba.lpfc_vfi_blk_list, list) {
6713 			list_del_init(&rsrc_blk->list);
6714 			kfree(rsrc_blk);
6715 		}
6716 		break;
6717 	case LPFC_RSC_TYPE_FCOE_RPI:
6718 		/* RPI bitmask and physical id array are cleaned up earlier. */
6719 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6720 				    &phba->sli4_hba.lpfc_rpi_blk_list, list) {
6721 			list_del_init(&rsrc_blk->list);
6722 			kfree(rsrc_blk);
6723 		}
6724 		break;
6725 	default:
6726 		break;
6727 	}
6728 
6729 	bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6730 
6731  out_free_mbox:
6732 	mempool_free(mbox, phba->mbox_mem_pool);
6733 	return rc;
6734 }
6735 
6736 static void
6737 lpfc_set_features(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox,
6738 		  uint32_t feature)
6739 {
6740 	uint32_t len;
6741 	u32 sig_freq = 0;
6742 
6743 	len = sizeof(struct lpfc_mbx_set_feature) -
6744 		sizeof(struct lpfc_sli4_cfg_mhdr);
6745 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6746 			 LPFC_MBOX_OPCODE_SET_FEATURES, len,
6747 			 LPFC_SLI4_MBX_EMBED);
6748 
6749 	switch (feature) {
6750 	case LPFC_SET_UE_RECOVERY:
6751 		bf_set(lpfc_mbx_set_feature_UER,
6752 		       &mbox->u.mqe.un.set_feature, 1);
6753 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_UE_RECOVERY;
6754 		mbox->u.mqe.un.set_feature.param_len = 8;
6755 		break;
6756 	case LPFC_SET_MDS_DIAGS:
6757 		bf_set(lpfc_mbx_set_feature_mds,
6758 		       &mbox->u.mqe.un.set_feature, 1);
6759 		bf_set(lpfc_mbx_set_feature_mds_deep_loopbk,
6760 		       &mbox->u.mqe.un.set_feature, 1);
6761 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_MDS_DIAGS;
6762 		mbox->u.mqe.un.set_feature.param_len = 8;
6763 		break;
6764 	case LPFC_SET_CGN_SIGNAL:
6765 		if (phba->cmf_active_mode == LPFC_CFG_OFF)
6766 			sig_freq = 0;
6767 		else
6768 			sig_freq = phba->cgn_sig_freq;
6769 
6770 		if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
6771 			bf_set(lpfc_mbx_set_feature_CGN_alarm_freq,
6772 			       &mbox->u.mqe.un.set_feature, sig_freq);
6773 			bf_set(lpfc_mbx_set_feature_CGN_warn_freq,
6774 			       &mbox->u.mqe.un.set_feature, sig_freq);
6775 		}
6776 
6777 		if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY)
6778 			bf_set(lpfc_mbx_set_feature_CGN_warn_freq,
6779 			       &mbox->u.mqe.un.set_feature, sig_freq);
6780 
6781 		if (phba->cmf_active_mode == LPFC_CFG_OFF ||
6782 		    phba->cgn_reg_signal == EDC_CG_SIG_NOTSUPPORTED)
6783 			sig_freq = 0;
6784 		else
6785 			sig_freq = lpfc_acqe_cgn_frequency;
6786 
6787 		bf_set(lpfc_mbx_set_feature_CGN_acqe_freq,
6788 		       &mbox->u.mqe.un.set_feature, sig_freq);
6789 
6790 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_CGN_SIGNAL;
6791 		mbox->u.mqe.un.set_feature.param_len = 12;
6792 		break;
6793 	case LPFC_SET_DUAL_DUMP:
6794 		bf_set(lpfc_mbx_set_feature_dd,
6795 		       &mbox->u.mqe.un.set_feature, LPFC_ENABLE_DUAL_DUMP);
6796 		bf_set(lpfc_mbx_set_feature_ddquery,
6797 		       &mbox->u.mqe.un.set_feature, 0);
6798 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_DUAL_DUMP;
6799 		mbox->u.mqe.un.set_feature.param_len = 4;
6800 		break;
6801 	case LPFC_SET_ENABLE_MI:
6802 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_ENABLE_MI;
6803 		mbox->u.mqe.un.set_feature.param_len = 4;
6804 		bf_set(lpfc_mbx_set_feature_milunq, &mbox->u.mqe.un.set_feature,
6805 		       phba->pport->cfg_lun_queue_depth);
6806 		bf_set(lpfc_mbx_set_feature_mi, &mbox->u.mqe.un.set_feature,
6807 		       phba->sli4_hba.pc_sli4_params.mi_ver);
6808 		break;
6809 	case LPFC_SET_LD_SIGNAL:
6810 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_LD_SIGNAL;
6811 		mbox->u.mqe.un.set_feature.param_len = 16;
6812 		bf_set(lpfc_mbx_set_feature_lds_qry,
6813 		       &mbox->u.mqe.un.set_feature, LPFC_QUERY_LDS_OP);
6814 		break;
6815 	case LPFC_SET_ENABLE_CMF:
6816 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_ENABLE_CMF;
6817 		mbox->u.mqe.un.set_feature.param_len = 4;
6818 		bf_set(lpfc_mbx_set_feature_cmf,
6819 		       &mbox->u.mqe.un.set_feature, 1);
6820 		break;
6821 	}
6822 	return;
6823 }
6824 
6825 /**
6826  * lpfc_ras_stop_fwlog: Disable FW logging by the adapter
6827  * @phba: Pointer to HBA context object.
6828  *
6829  * Disable FW logging into host memory on the adapter. To
6830  * be done before reading logs from the host memory.
6831  **/
6832 void
6833 lpfc_ras_stop_fwlog(struct lpfc_hba *phba)
6834 {
6835 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6836 
6837 	spin_lock_irq(&phba->ras_fwlog_lock);
6838 	ras_fwlog->state = INACTIVE;
6839 	spin_unlock_irq(&phba->ras_fwlog_lock);
6840 
6841 	/* Disable FW logging to host memory */
6842 	writel(LPFC_CTL_PDEV_CTL_DDL_RAS,
6843 	       phba->sli4_hba.conf_regs_memmap_p + LPFC_CTL_PDEV_CTL_OFFSET);
6844 
6845 	/* Wait 10ms for firmware to stop using DMA buffer */
6846 	usleep_range(10 * 1000, 20 * 1000);
6847 }
6848 
6849 /**
6850  * lpfc_sli4_ras_dma_free - Free memory allocated for FW logging.
6851  * @phba: Pointer to HBA context object.
6852  *
6853  * This function is called to free memory allocated for RAS FW logging
6854  * support in the driver.
6855  **/
6856 void
6857 lpfc_sli4_ras_dma_free(struct lpfc_hba *phba)
6858 {
6859 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6860 	struct lpfc_dmabuf *dmabuf, *next;
6861 
6862 	if (!list_empty(&ras_fwlog->fwlog_buff_list)) {
6863 		list_for_each_entry_safe(dmabuf, next,
6864 				    &ras_fwlog->fwlog_buff_list,
6865 				    list) {
6866 			list_del(&dmabuf->list);
6867 			dma_free_coherent(&phba->pcidev->dev,
6868 					  LPFC_RAS_MAX_ENTRY_SIZE,
6869 					  dmabuf->virt, dmabuf->phys);
6870 			kfree(dmabuf);
6871 		}
6872 	}
6873 
6874 	if (ras_fwlog->lwpd.virt) {
6875 		dma_free_coherent(&phba->pcidev->dev,
6876 				  sizeof(uint32_t) * 2,
6877 				  ras_fwlog->lwpd.virt,
6878 				  ras_fwlog->lwpd.phys);
6879 		ras_fwlog->lwpd.virt = NULL;
6880 	}
6881 
6882 	spin_lock_irq(&phba->ras_fwlog_lock);
6883 	ras_fwlog->state = INACTIVE;
6884 	spin_unlock_irq(&phba->ras_fwlog_lock);
6885 }
6886 
6887 /**
6888  * lpfc_sli4_ras_dma_alloc: Allocate memory for FW support
6889  * @phba: Pointer to HBA context object.
6890  * @fwlog_buff_count: Count of buffers to be created.
6891  *
6892  * This routine DMA memory for Log Write Position Data[LPWD] and buffer
6893  * to update FW log is posted to the adapter.
6894  * Buffer count is calculated based on module param ras_fwlog_buffsize
6895  * Size of each buffer posted to FW is 64K.
6896  **/
6897 
6898 static int
6899 lpfc_sli4_ras_dma_alloc(struct lpfc_hba *phba,
6900 			uint32_t fwlog_buff_count)
6901 {
6902 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6903 	struct lpfc_dmabuf *dmabuf;
6904 	int rc = 0, i = 0;
6905 
6906 	/* Initialize List */
6907 	INIT_LIST_HEAD(&ras_fwlog->fwlog_buff_list);
6908 
6909 	/* Allocate memory for the LWPD */
6910 	ras_fwlog->lwpd.virt = dma_alloc_coherent(&phba->pcidev->dev,
6911 					    sizeof(uint32_t) * 2,
6912 					    &ras_fwlog->lwpd.phys,
6913 					    GFP_KERNEL);
6914 	if (!ras_fwlog->lwpd.virt) {
6915 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6916 				"6185 LWPD Memory Alloc Failed\n");
6917 
6918 		return -ENOMEM;
6919 	}
6920 
6921 	ras_fwlog->fw_buffcount = fwlog_buff_count;
6922 	for (i = 0; i < ras_fwlog->fw_buffcount; i++) {
6923 		dmabuf = kzalloc_obj(struct lpfc_dmabuf);
6924 		if (!dmabuf) {
6925 			rc = -ENOMEM;
6926 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6927 					"6186 Memory Alloc failed FW logging");
6928 			goto free_mem;
6929 		}
6930 
6931 		dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
6932 						  LPFC_RAS_MAX_ENTRY_SIZE,
6933 						  &dmabuf->phys, GFP_KERNEL);
6934 		if (!dmabuf->virt) {
6935 			kfree(dmabuf);
6936 			rc = -ENOMEM;
6937 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6938 					"6187 DMA Alloc Failed FW logging");
6939 			goto free_mem;
6940 		}
6941 		dmabuf->buffer_tag = i;
6942 		list_add_tail(&dmabuf->list, &ras_fwlog->fwlog_buff_list);
6943 	}
6944 
6945 free_mem:
6946 	if (rc)
6947 		lpfc_sli4_ras_dma_free(phba);
6948 
6949 	return rc;
6950 }
6951 
6952 /**
6953  * lpfc_sli4_ras_mbox_cmpl: Completion handler for RAS MBX command
6954  * @phba: pointer to lpfc hba data structure.
6955  * @pmb: pointer to the driver internal queue element for mailbox command.
6956  *
6957  * Completion handler for driver's RAS MBX command to the device.
6958  **/
6959 static void
6960 lpfc_sli4_ras_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
6961 {
6962 	MAILBOX_t *mb;
6963 	union lpfc_sli4_cfg_shdr *shdr;
6964 	uint32_t shdr_status, shdr_add_status;
6965 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6966 
6967 	mb = &pmb->u.mb;
6968 
6969 	shdr = (union lpfc_sli4_cfg_shdr *)
6970 		&pmb->u.mqe.un.ras_fwlog.header.cfg_shdr;
6971 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
6972 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
6973 
6974 	if (mb->mbxStatus != MBX_SUCCESS || shdr_status) {
6975 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6976 				"6188 FW LOG mailbox "
6977 				"completed with status x%x add_status x%x,"
6978 				" mbx status x%x\n",
6979 				shdr_status, shdr_add_status, mb->mbxStatus);
6980 
6981 		ras_fwlog->ras_hwsupport = false;
6982 		goto disable_ras;
6983 	}
6984 
6985 	spin_lock_irq(&phba->ras_fwlog_lock);
6986 	ras_fwlog->state = ACTIVE;
6987 	spin_unlock_irq(&phba->ras_fwlog_lock);
6988 	mempool_free(pmb, phba->mbox_mem_pool);
6989 
6990 	return;
6991 
6992 disable_ras:
6993 	/* Free RAS DMA memory */
6994 	lpfc_sli4_ras_dma_free(phba);
6995 	mempool_free(pmb, phba->mbox_mem_pool);
6996 }
6997 
6998 /**
6999  * lpfc_sli4_ras_fwlog_init: Initialize memory and post RAS MBX command
7000  * @phba: pointer to lpfc hba data structure.
7001  * @fwlog_level: Logging verbosity level.
7002  * @fwlog_enable: Enable/Disable logging.
7003  *
7004  * Initialize memory and post mailbox command to enable FW logging in host
7005  * memory.
7006  **/
7007 int
7008 lpfc_sli4_ras_fwlog_init(struct lpfc_hba *phba,
7009 			 uint32_t fwlog_level,
7010 			 uint32_t fwlog_enable)
7011 {
7012 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
7013 	struct lpfc_mbx_set_ras_fwlog *mbx_fwlog = NULL;
7014 	struct lpfc_dmabuf *dmabuf;
7015 	LPFC_MBOXQ_t *mbox;
7016 	uint32_t len = 0, fwlog_buffsize, fwlog_entry_count;
7017 	int rc = 0;
7018 
7019 	spin_lock_irq(&phba->ras_fwlog_lock);
7020 	ras_fwlog->state = INACTIVE;
7021 	spin_unlock_irq(&phba->ras_fwlog_lock);
7022 
7023 	fwlog_buffsize = (LPFC_RAS_MIN_BUFF_POST_SIZE *
7024 			  phba->cfg_ras_fwlog_buffsize);
7025 	fwlog_entry_count = (fwlog_buffsize/LPFC_RAS_MAX_ENTRY_SIZE);
7026 
7027 	/*
7028 	 * If re-enabling FW logging support use earlier allocated
7029 	 * DMA buffers while posting MBX command.
7030 	 **/
7031 	if (!ras_fwlog->lwpd.virt) {
7032 		rc = lpfc_sli4_ras_dma_alloc(phba, fwlog_entry_count);
7033 		if (rc) {
7034 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7035 					"6189 FW Log Memory Allocation Failed");
7036 			return rc;
7037 		}
7038 	}
7039 
7040 	/* Setup Mailbox command */
7041 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7042 	if (!mbox) {
7043 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7044 				"6190 RAS MBX Alloc Failed");
7045 		rc = -ENOMEM;
7046 		goto mem_free;
7047 	}
7048 
7049 	ras_fwlog->fw_loglevel = fwlog_level;
7050 	len = (sizeof(struct lpfc_mbx_set_ras_fwlog) -
7051 		sizeof(struct lpfc_sli4_cfg_mhdr));
7052 
7053 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_LOWLEVEL,
7054 			 LPFC_MBOX_OPCODE_SET_DIAG_LOG_OPTION,
7055 			 len, LPFC_SLI4_MBX_EMBED);
7056 
7057 	mbx_fwlog = (struct lpfc_mbx_set_ras_fwlog *)&mbox->u.mqe.un.ras_fwlog;
7058 	bf_set(lpfc_fwlog_enable, &mbx_fwlog->u.request,
7059 	       fwlog_enable);
7060 	bf_set(lpfc_fwlog_loglvl, &mbx_fwlog->u.request,
7061 	       ras_fwlog->fw_loglevel);
7062 	bf_set(lpfc_fwlog_buffcnt, &mbx_fwlog->u.request,
7063 	       ras_fwlog->fw_buffcount);
7064 	bf_set(lpfc_fwlog_buffsz, &mbx_fwlog->u.request,
7065 	       LPFC_RAS_MAX_ENTRY_SIZE/SLI4_PAGE_SIZE);
7066 
7067 	/* Update DMA buffer address */
7068 	list_for_each_entry(dmabuf, &ras_fwlog->fwlog_buff_list, list) {
7069 		memset(dmabuf->virt, 0, LPFC_RAS_MAX_ENTRY_SIZE);
7070 
7071 		mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_lo =
7072 			putPaddrLow(dmabuf->phys);
7073 
7074 		mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_hi =
7075 			putPaddrHigh(dmabuf->phys);
7076 	}
7077 
7078 	/* Update LPWD address */
7079 	mbx_fwlog->u.request.lwpd.addr_lo = putPaddrLow(ras_fwlog->lwpd.phys);
7080 	mbx_fwlog->u.request.lwpd.addr_hi = putPaddrHigh(ras_fwlog->lwpd.phys);
7081 
7082 	spin_lock_irq(&phba->ras_fwlog_lock);
7083 	ras_fwlog->state = REG_INPROGRESS;
7084 	spin_unlock_irq(&phba->ras_fwlog_lock);
7085 	mbox->vport = phba->pport;
7086 	mbox->mbox_cmpl = lpfc_sli4_ras_mbox_cmpl;
7087 
7088 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
7089 
7090 	if (rc == MBX_NOT_FINISHED) {
7091 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7092 				"6191 FW-Log Mailbox failed. "
7093 				"status %d mbxStatus : x%x", rc,
7094 				bf_get(lpfc_mqe_status, &mbox->u.mqe));
7095 		mempool_free(mbox, phba->mbox_mem_pool);
7096 		rc = -EIO;
7097 		goto mem_free;
7098 	} else
7099 		rc = 0;
7100 mem_free:
7101 	if (rc)
7102 		lpfc_sli4_ras_dma_free(phba);
7103 
7104 	return rc;
7105 }
7106 
7107 /**
7108  * lpfc_sli4_ras_setup - Check if RAS supported on the adapter
7109  * @phba: Pointer to HBA context object.
7110  *
7111  * Check if RAS is supported on the adapter and initialize it.
7112  **/
7113 void
7114 lpfc_sli4_ras_setup(struct lpfc_hba *phba)
7115 {
7116 	/* Check RAS FW Log needs to be enabled or not */
7117 	if (lpfc_check_fwlog_support(phba))
7118 		return;
7119 
7120 	lpfc_sli4_ras_fwlog_init(phba, phba->cfg_ras_fwlog_level,
7121 				 LPFC_RAS_ENABLE_LOGGING);
7122 }
7123 
7124 /**
7125  * lpfc_sli4_alloc_resource_identifiers - Allocate all SLI4 resource extents.
7126  * @phba: Pointer to HBA context object.
7127  *
7128  * This function allocates all SLI4 resource identifiers.
7129  **/
7130 int
7131 lpfc_sli4_alloc_resource_identifiers(struct lpfc_hba *phba)
7132 {
7133 	int i, rc, error = 0;
7134 	uint16_t count, base;
7135 	unsigned long longs;
7136 
7137 	if (!phba->sli4_hba.rpi_hdrs_in_use)
7138 		phba->sli4_hba.next_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
7139 	if (phba->sli4_hba.extents_in_use) {
7140 		/*
7141 		 * The port supports resource extents. The XRI, VPI, VFI, RPI
7142 		 * resource extent count must be read and allocated before
7143 		 * provisioning the resource id arrays.
7144 		 */
7145 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
7146 		    LPFC_IDX_RSRC_RDY) {
7147 			/*
7148 			 * Extent-based resources are set - the driver could
7149 			 * be in a port reset. Figure out if any corrective
7150 			 * actions need to be taken.
7151 			 */
7152 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7153 						 LPFC_RSC_TYPE_FCOE_VFI);
7154 			if (rc != 0)
7155 				error++;
7156 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7157 						 LPFC_RSC_TYPE_FCOE_VPI);
7158 			if (rc != 0)
7159 				error++;
7160 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7161 						 LPFC_RSC_TYPE_FCOE_XRI);
7162 			if (rc != 0)
7163 				error++;
7164 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7165 						 LPFC_RSC_TYPE_FCOE_RPI);
7166 			if (rc != 0)
7167 				error++;
7168 
7169 			/*
7170 			 * It's possible that the number of resources
7171 			 * provided to this port instance changed between
7172 			 * resets.  Detect this condition and reallocate
7173 			 * resources.  Otherwise, there is no action.
7174 			 */
7175 			if (error) {
7176 				lpfc_printf_log(phba, KERN_INFO,
7177 						LOG_MBOX | LOG_INIT,
7178 						"2931 Detected extent resource "
7179 						"change.  Reallocating all "
7180 						"extents.\n");
7181 				rc = lpfc_sli4_dealloc_extent(phba,
7182 						 LPFC_RSC_TYPE_FCOE_VFI);
7183 				rc = lpfc_sli4_dealloc_extent(phba,
7184 						 LPFC_RSC_TYPE_FCOE_VPI);
7185 				rc = lpfc_sli4_dealloc_extent(phba,
7186 						 LPFC_RSC_TYPE_FCOE_XRI);
7187 				rc = lpfc_sli4_dealloc_extent(phba,
7188 						 LPFC_RSC_TYPE_FCOE_RPI);
7189 			} else
7190 				return 0;
7191 		}
7192 
7193 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
7194 		if (unlikely(rc))
7195 			goto err_exit;
7196 
7197 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
7198 		if (unlikely(rc))
7199 			goto err_exit;
7200 
7201 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
7202 		if (unlikely(rc))
7203 			goto err_exit;
7204 
7205 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
7206 		if (unlikely(rc))
7207 			goto err_exit;
7208 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
7209 		       LPFC_IDX_RSRC_RDY);
7210 		return rc;
7211 	} else {
7212 		/*
7213 		 * The port does not support resource extents.  The XRI, VPI,
7214 		 * VFI, RPI resource ids were determined from READ_CONFIG.
7215 		 * Just allocate the bitmasks and provision the resource id
7216 		 * arrays.  If a port reset is active, the resources don't
7217 		 * need any action - just exit.
7218 		 */
7219 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
7220 		    LPFC_IDX_RSRC_RDY) {
7221 			lpfc_sli4_dealloc_resource_identifiers(phba);
7222 			lpfc_sli4_remove_rpis(phba);
7223 		}
7224 		/* RPIs. */
7225 		count = phba->sli4_hba.max_cfg_param.max_rpi;
7226 		if (count <= 0) {
7227 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7228 					"3279 Invalid provisioning of "
7229 					"rpi:%d\n", count);
7230 			rc = -EINVAL;
7231 			goto err_exit;
7232 		}
7233 		base = phba->sli4_hba.max_cfg_param.rpi_base;
7234 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7235 		phba->sli4_hba.rpi_bmask = kcalloc(longs,
7236 						   sizeof(unsigned long),
7237 						   GFP_KERNEL);
7238 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
7239 			rc = -ENOMEM;
7240 			goto err_exit;
7241 		}
7242 		phba->sli4_hba.rpi_ids = kcalloc(count, sizeof(uint16_t),
7243 						 GFP_KERNEL);
7244 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
7245 			rc = -ENOMEM;
7246 			goto free_rpi_bmask;
7247 		}
7248 
7249 		for (i = 0; i < count; i++)
7250 			phba->sli4_hba.rpi_ids[i] = base + i;
7251 
7252 		/* VPIs. */
7253 		count = phba->sli4_hba.max_cfg_param.max_vpi;
7254 		if (count <= 0) {
7255 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7256 					"3280 Invalid provisioning of "
7257 					"vpi:%d\n", count);
7258 			rc = -EINVAL;
7259 			goto free_rpi_ids;
7260 		}
7261 		base = phba->sli4_hba.max_cfg_param.vpi_base;
7262 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7263 		phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
7264 					  GFP_KERNEL);
7265 		if (unlikely(!phba->vpi_bmask)) {
7266 			rc = -ENOMEM;
7267 			goto free_rpi_ids;
7268 		}
7269 		phba->vpi_ids = kcalloc(count, sizeof(uint16_t),
7270 					GFP_KERNEL);
7271 		if (unlikely(!phba->vpi_ids)) {
7272 			rc = -ENOMEM;
7273 			goto free_vpi_bmask;
7274 		}
7275 
7276 		for (i = 0; i < count; i++)
7277 			phba->vpi_ids[i] = base + i;
7278 
7279 		/* XRIs. */
7280 		count = phba->sli4_hba.max_cfg_param.max_xri;
7281 		if (count <= 0) {
7282 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7283 					"3281 Invalid provisioning of "
7284 					"xri:%d\n", count);
7285 			rc = -EINVAL;
7286 			goto free_vpi_ids;
7287 		}
7288 		base = phba->sli4_hba.max_cfg_param.xri_base;
7289 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7290 		phba->sli4_hba.xri_bmask = kcalloc(longs,
7291 						   sizeof(unsigned long),
7292 						   GFP_KERNEL);
7293 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
7294 			rc = -ENOMEM;
7295 			goto free_vpi_ids;
7296 		}
7297 		phba->sli4_hba.max_cfg_param.xri_used = 0;
7298 		phba->sli4_hba.xri_ids = kcalloc(count, sizeof(uint16_t),
7299 						 GFP_KERNEL);
7300 		if (unlikely(!phba->sli4_hba.xri_ids)) {
7301 			rc = -ENOMEM;
7302 			goto free_xri_bmask;
7303 		}
7304 
7305 		for (i = 0; i < count; i++)
7306 			phba->sli4_hba.xri_ids[i] = base + i;
7307 
7308 		/* VFIs. */
7309 		count = phba->sli4_hba.max_cfg_param.max_vfi;
7310 		if (count <= 0) {
7311 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7312 					"3282 Invalid provisioning of "
7313 					"vfi:%d\n", count);
7314 			rc = -EINVAL;
7315 			goto free_xri_ids;
7316 		}
7317 		base = phba->sli4_hba.max_cfg_param.vfi_base;
7318 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7319 		phba->sli4_hba.vfi_bmask = kcalloc(longs,
7320 						   sizeof(unsigned long),
7321 						   GFP_KERNEL);
7322 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
7323 			rc = -ENOMEM;
7324 			goto free_xri_ids;
7325 		}
7326 		phba->sli4_hba.vfi_ids = kcalloc(count, sizeof(uint16_t),
7327 						 GFP_KERNEL);
7328 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
7329 			rc = -ENOMEM;
7330 			goto free_vfi_bmask;
7331 		}
7332 
7333 		for (i = 0; i < count; i++)
7334 			phba->sli4_hba.vfi_ids[i] = base + i;
7335 
7336 		/*
7337 		 * Mark all resources ready.  An HBA reset doesn't need
7338 		 * to reset the initialization.
7339 		 */
7340 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
7341 		       LPFC_IDX_RSRC_RDY);
7342 		return 0;
7343 	}
7344 
7345  free_vfi_bmask:
7346 	kfree(phba->sli4_hba.vfi_bmask);
7347 	phba->sli4_hba.vfi_bmask = NULL;
7348  free_xri_ids:
7349 	kfree(phba->sli4_hba.xri_ids);
7350 	phba->sli4_hba.xri_ids = NULL;
7351  free_xri_bmask:
7352 	kfree(phba->sli4_hba.xri_bmask);
7353 	phba->sli4_hba.xri_bmask = NULL;
7354  free_vpi_ids:
7355 	kfree(phba->vpi_ids);
7356 	phba->vpi_ids = NULL;
7357  free_vpi_bmask:
7358 	kfree(phba->vpi_bmask);
7359 	phba->vpi_bmask = NULL;
7360  free_rpi_ids:
7361 	kfree(phba->sli4_hba.rpi_ids);
7362 	phba->sli4_hba.rpi_ids = NULL;
7363  free_rpi_bmask:
7364 	kfree(phba->sli4_hba.rpi_bmask);
7365 	phba->sli4_hba.rpi_bmask = NULL;
7366  err_exit:
7367 	return rc;
7368 }
7369 
7370 /**
7371  * lpfc_sli4_dealloc_resource_identifiers - Deallocate all SLI4 resource extents.
7372  * @phba: Pointer to HBA context object.
7373  *
7374  * This function allocates the number of elements for the specified
7375  * resource type.
7376  **/
7377 int
7378 lpfc_sli4_dealloc_resource_identifiers(struct lpfc_hba *phba)
7379 {
7380 	if (phba->sli4_hba.extents_in_use) {
7381 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
7382 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
7383 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
7384 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
7385 	} else {
7386 		kfree(phba->vpi_bmask);
7387 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
7388 		kfree(phba->vpi_ids);
7389 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7390 		kfree(phba->sli4_hba.xri_bmask);
7391 		kfree(phba->sli4_hba.xri_ids);
7392 		kfree(phba->sli4_hba.vfi_bmask);
7393 		kfree(phba->sli4_hba.vfi_ids);
7394 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7395 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7396 	}
7397 
7398 	return 0;
7399 }
7400 
7401 /**
7402  * lpfc_sli4_get_allocated_extnts - Get the port's allocated extents.
7403  * @phba: Pointer to HBA context object.
7404  * @type: The resource extent type.
7405  * @extnt_cnt: buffer to hold port extent count response
7406  * @extnt_size: buffer to hold port extent size response.
7407  *
7408  * This function calls the port to read the host allocated extents
7409  * for a particular type.
7410  **/
7411 int
7412 lpfc_sli4_get_allocated_extnts(struct lpfc_hba *phba, uint16_t type,
7413 			       uint16_t *extnt_cnt, uint16_t *extnt_size)
7414 {
7415 	bool emb;
7416 	int rc = 0;
7417 	uint16_t curr_blks = 0;
7418 	uint32_t req_len, emb_len;
7419 	uint32_t alloc_len, mbox_tmo;
7420 	struct list_head *blk_list_head;
7421 	struct lpfc_rsrc_blks *rsrc_blk;
7422 	LPFC_MBOXQ_t *mbox;
7423 	void *virtaddr = NULL;
7424 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
7425 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
7426 	union  lpfc_sli4_cfg_shdr *shdr;
7427 
7428 	switch (type) {
7429 	case LPFC_RSC_TYPE_FCOE_VPI:
7430 		blk_list_head = &phba->lpfc_vpi_blk_list;
7431 		break;
7432 	case LPFC_RSC_TYPE_FCOE_XRI:
7433 		blk_list_head = &phba->sli4_hba.lpfc_xri_blk_list;
7434 		break;
7435 	case LPFC_RSC_TYPE_FCOE_VFI:
7436 		blk_list_head = &phba->sli4_hba.lpfc_vfi_blk_list;
7437 		break;
7438 	case LPFC_RSC_TYPE_FCOE_RPI:
7439 		blk_list_head = &phba->sli4_hba.lpfc_rpi_blk_list;
7440 		break;
7441 	default:
7442 		return -EIO;
7443 	}
7444 
7445 	/* Count the number of extents currently allocatd for this type. */
7446 	list_for_each_entry(rsrc_blk, blk_list_head, list) {
7447 		if (curr_blks == 0) {
7448 			/*
7449 			 * The GET_ALLOCATED mailbox does not return the size,
7450 			 * just the count.  The size should be just the size
7451 			 * stored in the current allocated block and all sizes
7452 			 * for an extent type are the same so set the return
7453 			 * value now.
7454 			 */
7455 			*extnt_size = rsrc_blk->rsrc_size;
7456 		}
7457 		curr_blks++;
7458 	}
7459 
7460 	/*
7461 	 * Calculate the size of an embedded mailbox.  The uint32_t
7462 	 * accounts for extents-specific word.
7463 	 */
7464 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
7465 		sizeof(uint32_t);
7466 
7467 	/*
7468 	 * Presume the allocation and response will fit into an embedded
7469 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
7470 	 */
7471 	emb = LPFC_SLI4_MBX_EMBED;
7472 	req_len = emb_len;
7473 	if (req_len > emb_len) {
7474 		req_len = curr_blks * sizeof(uint16_t) +
7475 			sizeof(union lpfc_sli4_cfg_shdr) +
7476 			sizeof(uint32_t);
7477 		emb = LPFC_SLI4_MBX_NEMBED;
7478 	}
7479 
7480 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7481 	if (!mbox)
7482 		return -ENOMEM;
7483 	memset(mbox, 0, sizeof(LPFC_MBOXQ_t));
7484 
7485 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
7486 				     LPFC_MBOX_OPCODE_GET_ALLOC_RSRC_EXTENT,
7487 				     req_len, emb);
7488 	if (alloc_len < req_len) {
7489 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7490 			"2983 Allocated DMA memory size (x%x) is "
7491 			"less than the requested DMA memory "
7492 			"size (x%x)\n", alloc_len, req_len);
7493 		rc = -ENOMEM;
7494 		goto err_exit;
7495 	}
7496 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, curr_blks, type, emb);
7497 	if (unlikely(rc)) {
7498 		rc = -EIO;
7499 		goto err_exit;
7500 	}
7501 
7502 	if (!phba->sli4_hba.intr_enable)
7503 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
7504 	else {
7505 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
7506 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
7507 	}
7508 
7509 	if (unlikely(rc)) {
7510 		rc = -EIO;
7511 		goto err_exit;
7512 	}
7513 
7514 	/*
7515 	 * Figure out where the response is located.  Then get local pointers
7516 	 * to the response data.  The port does not guarantee to respond to
7517 	 * all extents counts request so update the local variable with the
7518 	 * allocated count from the port.
7519 	 */
7520 	if (emb == LPFC_SLI4_MBX_EMBED) {
7521 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
7522 		shdr = &rsrc_ext->header.cfg_shdr;
7523 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
7524 	} else {
7525 		virtaddr = mbox->sge_array->addr[0];
7526 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
7527 		shdr = &n_rsrc->cfg_shdr;
7528 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
7529 	}
7530 
7531 	if (bf_get(lpfc_mbox_hdr_status, &shdr->response)) {
7532 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7533 			"2984 Failed to read allocated resources "
7534 			"for type %d - Status 0x%x Add'l Status 0x%x.\n",
7535 			type,
7536 			bf_get(lpfc_mbox_hdr_status, &shdr->response),
7537 			bf_get(lpfc_mbox_hdr_add_status, &shdr->response));
7538 		rc = -EIO;
7539 		goto err_exit;
7540 	}
7541  err_exit:
7542 	lpfc_sli4_mbox_cmd_free(phba, mbox);
7543 	return rc;
7544 }
7545 
7546 /**
7547  * lpfc_sli4_repost_sgl_list - Repost the buffers sgl pages as block
7548  * @phba: pointer to lpfc hba data structure.
7549  * @sgl_list: linked link of sgl buffers to post
7550  * @cnt: number of linked list buffers
7551  *
7552  * This routine walks the list of buffers that have been allocated and
7553  * repost them to the port by using SGL block post. This is needed after a
7554  * pci_function_reset/warm_start or start. It attempts to construct blocks
7555  * of buffer sgls which contains contiguous xris and uses the non-embedded
7556  * SGL block post mailbox commands to post them to the port. For single
7557  * buffer sgl with non-contiguous xri, if any, it shall use embedded SGL post
7558  * mailbox command for posting.
7559  *
7560  * Returns: 0 = success, non-zero failure.
7561  **/
7562 static int
7563 lpfc_sli4_repost_sgl_list(struct lpfc_hba *phba,
7564 			  struct list_head *sgl_list, int cnt)
7565 {
7566 	struct lpfc_sglq *sglq_entry = NULL;
7567 	struct lpfc_sglq *sglq_entry_next = NULL;
7568 	struct lpfc_sglq *sglq_entry_first = NULL;
7569 	int status = 0, total_cnt;
7570 	int post_cnt = 0, num_posted = 0, block_cnt = 0;
7571 	int last_xritag = NO_XRI;
7572 	LIST_HEAD(prep_sgl_list);
7573 	LIST_HEAD(blck_sgl_list);
7574 	LIST_HEAD(allc_sgl_list);
7575 	LIST_HEAD(post_sgl_list);
7576 	LIST_HEAD(free_sgl_list);
7577 
7578 	spin_lock_irq(&phba->hbalock);
7579 	spin_lock(&phba->sli4_hba.sgl_list_lock);
7580 	list_splice_init(sgl_list, &allc_sgl_list);
7581 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
7582 	spin_unlock_irq(&phba->hbalock);
7583 
7584 	total_cnt = cnt;
7585 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
7586 				 &allc_sgl_list, list) {
7587 		list_del_init(&sglq_entry->list);
7588 		block_cnt++;
7589 		if ((last_xritag != NO_XRI) &&
7590 		    (sglq_entry->sli4_xritag != last_xritag + 1)) {
7591 			/* a hole in xri block, form a sgl posting block */
7592 			list_splice_init(&prep_sgl_list, &blck_sgl_list);
7593 			post_cnt = block_cnt - 1;
7594 			/* prepare list for next posting block */
7595 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
7596 			block_cnt = 1;
7597 		} else {
7598 			/* prepare list for next posting block */
7599 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
7600 			/* enough sgls for non-embed sgl mbox command */
7601 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
7602 				list_splice_init(&prep_sgl_list,
7603 						 &blck_sgl_list);
7604 				post_cnt = block_cnt;
7605 				block_cnt = 0;
7606 			}
7607 		}
7608 		num_posted++;
7609 
7610 		/* keep track of last sgl's xritag */
7611 		last_xritag = sglq_entry->sli4_xritag;
7612 
7613 		/* end of repost sgl list condition for buffers */
7614 		if (num_posted == total_cnt) {
7615 			if (post_cnt == 0) {
7616 				list_splice_init(&prep_sgl_list,
7617 						 &blck_sgl_list);
7618 				post_cnt = block_cnt;
7619 			} else if (block_cnt == 1) {
7620 				status = lpfc_sli4_post_sgl(phba,
7621 						sglq_entry->phys, 0,
7622 						sglq_entry->sli4_xritag);
7623 				if (!status) {
7624 					/* successful, put sgl to posted list */
7625 					list_add_tail(&sglq_entry->list,
7626 						      &post_sgl_list);
7627 				} else {
7628 					/* Failure, put sgl to free list */
7629 					lpfc_printf_log(phba, KERN_WARNING,
7630 						LOG_SLI,
7631 						"3159 Failed to post "
7632 						"sgl, xritag:x%x\n",
7633 						sglq_entry->sli4_xritag);
7634 					list_add_tail(&sglq_entry->list,
7635 						      &free_sgl_list);
7636 					total_cnt--;
7637 				}
7638 			}
7639 		}
7640 
7641 		/* continue until a nembed page worth of sgls */
7642 		if (post_cnt == 0)
7643 			continue;
7644 
7645 		/* post the buffer list sgls as a block */
7646 		status = lpfc_sli4_post_sgl_list(phba, &blck_sgl_list,
7647 						 post_cnt);
7648 
7649 		if (!status) {
7650 			/* success, put sgl list to posted sgl list */
7651 			list_splice_init(&blck_sgl_list, &post_sgl_list);
7652 		} else {
7653 			/* Failure, put sgl list to free sgl list */
7654 			sglq_entry_first = list_first_entry(&blck_sgl_list,
7655 							    struct lpfc_sglq,
7656 							    list);
7657 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
7658 					"3160 Failed to post sgl-list, "
7659 					"xritag:x%x-x%x\n",
7660 					sglq_entry_first->sli4_xritag,
7661 					(sglq_entry_first->sli4_xritag +
7662 					 post_cnt - 1));
7663 			list_splice_init(&blck_sgl_list, &free_sgl_list);
7664 			total_cnt -= post_cnt;
7665 		}
7666 
7667 		/* don't reset xirtag due to hole in xri block */
7668 		if (block_cnt == 0)
7669 			last_xritag = NO_XRI;
7670 
7671 		/* reset sgl post count for next round of posting */
7672 		post_cnt = 0;
7673 	}
7674 
7675 	/* free the sgls failed to post */
7676 	lpfc_free_sgl_list(phba, &free_sgl_list);
7677 
7678 	/* push sgls posted to the available list */
7679 	if (!list_empty(&post_sgl_list)) {
7680 		spin_lock_irq(&phba->hbalock);
7681 		spin_lock(&phba->sli4_hba.sgl_list_lock);
7682 		list_splice_init(&post_sgl_list, sgl_list);
7683 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
7684 		spin_unlock_irq(&phba->hbalock);
7685 	} else {
7686 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7687 				"3161 Failure to post sgl to port,status %x "
7688 				"blkcnt %d totalcnt %d postcnt %d\n",
7689 				status, block_cnt, total_cnt, post_cnt);
7690 		return -EIO;
7691 	}
7692 
7693 	/* return the number of XRIs actually posted */
7694 	return total_cnt;
7695 }
7696 
7697 /**
7698  * lpfc_sli4_repost_io_sgl_list - Repost all the allocated nvme buffer sgls
7699  * @phba: pointer to lpfc hba data structure.
7700  *
7701  * This routine walks the list of nvme buffers that have been allocated and
7702  * repost them to the port by using SGL block post. This is needed after a
7703  * pci_function_reset/warm_start or start. The lpfc_hba_down_post_s4 routine
7704  * is responsible for moving all nvme buffers on the lpfc_abts_nvme_sgl_list
7705  * to the lpfc_io_buf_list. If the repost fails, reject all nvme buffers.
7706  *
7707  * Returns: 0 = success, non-zero failure.
7708  **/
7709 static int
7710 lpfc_sli4_repost_io_sgl_list(struct lpfc_hba *phba)
7711 {
7712 	LIST_HEAD(post_nblist);
7713 	int num_posted, rc = 0;
7714 
7715 	/* get all NVME buffers need to repost to a local list */
7716 	lpfc_io_buf_flush(phba, &post_nblist);
7717 
7718 	/* post the list of nvme buffer sgls to port if available */
7719 	if (!list_empty(&post_nblist)) {
7720 		num_posted = lpfc_sli4_post_io_sgl_list(
7721 			phba, &post_nblist, phba->sli4_hba.io_xri_cnt);
7722 		/* failed to post any nvme buffer, return error */
7723 		if (num_posted == 0)
7724 			rc = -EIO;
7725 	}
7726 	return rc;
7727 }
7728 
7729 static void
7730 lpfc_set_host_data(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
7731 {
7732 	uint32_t len;
7733 
7734 	len = sizeof(struct lpfc_mbx_set_host_data) -
7735 		sizeof(struct lpfc_sli4_cfg_mhdr);
7736 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
7737 			 LPFC_MBOX_OPCODE_SET_HOST_DATA, len,
7738 			 LPFC_SLI4_MBX_EMBED);
7739 
7740 	mbox->u.mqe.un.set_host_data.param_id = LPFC_SET_HOST_OS_DRIVER_VERSION;
7741 	mbox->u.mqe.un.set_host_data.param_len =
7742 					LPFC_HOST_OS_DRIVER_VERSION_SIZE;
7743 	snprintf(mbox->u.mqe.un.set_host_data.un.data,
7744 		 LPFC_HOST_OS_DRIVER_VERSION_SIZE,
7745 		 "Linux %s v"LPFC_DRIVER_VERSION,
7746 		 test_bit(HBA_FCOE_MODE, &phba->hba_flag) ? "FCoE" : "FC");
7747 }
7748 
7749 int
7750 lpfc_post_rq_buffer(struct lpfc_hba *phba, struct lpfc_queue *hrq,
7751 		    struct lpfc_queue *drq, int count, int idx)
7752 {
7753 	int rc, i;
7754 	struct lpfc_rqe hrqe;
7755 	struct lpfc_rqe drqe;
7756 	struct lpfc_rqb *rqbp;
7757 	unsigned long flags;
7758 	struct rqb_dmabuf *rqb_buffer;
7759 	LIST_HEAD(rqb_buf_list);
7760 
7761 	rqbp = hrq->rqbp;
7762 	for (i = 0; i < count; i++) {
7763 		spin_lock_irqsave(&phba->hbalock, flags);
7764 		/* IF RQ is already full, don't bother */
7765 		if (rqbp->buffer_count + i >= rqbp->entry_count - 1) {
7766 			spin_unlock_irqrestore(&phba->hbalock, flags);
7767 			break;
7768 		}
7769 		spin_unlock_irqrestore(&phba->hbalock, flags);
7770 
7771 		rqb_buffer = rqbp->rqb_alloc_buffer(phba);
7772 		if (!rqb_buffer)
7773 			break;
7774 		rqb_buffer->hrq = hrq;
7775 		rqb_buffer->drq = drq;
7776 		rqb_buffer->idx = idx;
7777 		list_add_tail(&rqb_buffer->hbuf.list, &rqb_buf_list);
7778 	}
7779 
7780 	spin_lock_irqsave(&phba->hbalock, flags);
7781 	while (!list_empty(&rqb_buf_list)) {
7782 		list_remove_head(&rqb_buf_list, rqb_buffer, struct rqb_dmabuf,
7783 				 hbuf.list);
7784 
7785 		hrqe.address_lo = putPaddrLow(rqb_buffer->hbuf.phys);
7786 		hrqe.address_hi = putPaddrHigh(rqb_buffer->hbuf.phys);
7787 		drqe.address_lo = putPaddrLow(rqb_buffer->dbuf.phys);
7788 		drqe.address_hi = putPaddrHigh(rqb_buffer->dbuf.phys);
7789 		rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
7790 		if (rc < 0) {
7791 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7792 					"6421 Cannot post to HRQ %d: %x %x %x "
7793 					"DRQ %x %x\n",
7794 					hrq->queue_id,
7795 					hrq->host_index,
7796 					hrq->hba_index,
7797 					hrq->entry_count,
7798 					drq->host_index,
7799 					drq->hba_index);
7800 			rqbp->rqb_free_buffer(phba, rqb_buffer);
7801 		} else {
7802 			list_add_tail(&rqb_buffer->hbuf.list,
7803 				      &rqbp->rqb_buffer_list);
7804 			rqbp->buffer_count++;
7805 		}
7806 	}
7807 	spin_unlock_irqrestore(&phba->hbalock, flags);
7808 	return 1;
7809 }
7810 
7811 static void
7812 lpfc_mbx_cmpl_read_lds_params(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
7813 {
7814 	union lpfc_sli4_cfg_shdr *shdr;
7815 	u32 shdr_status, shdr_add_status;
7816 
7817 	shdr = (union lpfc_sli4_cfg_shdr *)
7818 		&pmb->u.mqe.un.sli4_config.header.cfg_shdr;
7819 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
7820 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
7821 	if (shdr_status || shdr_add_status || pmb->u.mb.mbxStatus) {
7822 		lpfc_printf_log(phba, KERN_INFO, LOG_LDS_EVENT | LOG_MBOX,
7823 				"4622 SET_FEATURE (x%x) mbox failed, "
7824 				"status x%x add_status x%x, mbx status x%x\n",
7825 				LPFC_SET_LD_SIGNAL, shdr_status,
7826 				shdr_add_status, pmb->u.mb.mbxStatus);
7827 		phba->degrade_activate_threshold = 0;
7828 		phba->degrade_deactivate_threshold = 0;
7829 		phba->fec_degrade_interval = 0;
7830 		goto out;
7831 	}
7832 
7833 	phba->degrade_activate_threshold = pmb->u.mqe.un.set_feature.word7;
7834 	phba->degrade_deactivate_threshold = pmb->u.mqe.un.set_feature.word8;
7835 	phba->fec_degrade_interval = pmb->u.mqe.un.set_feature.word10;
7836 
7837 	lpfc_printf_log(phba, KERN_INFO, LOG_LDS_EVENT,
7838 			"4624 Success: da x%x dd x%x interval x%x\n",
7839 			phba->degrade_activate_threshold,
7840 			phba->degrade_deactivate_threshold,
7841 			phba->fec_degrade_interval);
7842 out:
7843 	mempool_free(pmb, phba->mbox_mem_pool);
7844 }
7845 
7846 int
7847 lpfc_read_lds_params(struct lpfc_hba *phba)
7848 {
7849 	LPFC_MBOXQ_t *mboxq;
7850 	int rc;
7851 
7852 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7853 	if (!mboxq)
7854 		return -ENOMEM;
7855 
7856 	lpfc_set_features(phba, mboxq, LPFC_SET_LD_SIGNAL);
7857 	mboxq->vport = phba->pport;
7858 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_read_lds_params;
7859 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
7860 	if (rc == MBX_NOT_FINISHED) {
7861 		mempool_free(mboxq, phba->mbox_mem_pool);
7862 		return -EIO;
7863 	}
7864 	return 0;
7865 }
7866 
7867 static void
7868 lpfc_mbx_cmpl_cgn_set_ftrs(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
7869 {
7870 	struct lpfc_vport *vport = pmb->vport;
7871 	union lpfc_sli4_cfg_shdr *shdr;
7872 	u32 shdr_status, shdr_add_status;
7873 	u32 sig, acqe;
7874 
7875 	/* Two outcomes. (1) Set featurs was successul and EDC negotiation
7876 	 * is done. (2) Mailbox failed and send FPIN support only.
7877 	 */
7878 	shdr = (union lpfc_sli4_cfg_shdr *)
7879 		&pmb->u.mqe.un.sli4_config.header.cfg_shdr;
7880 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
7881 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
7882 	if (shdr_status || shdr_add_status || pmb->u.mb.mbxStatus) {
7883 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_CGN_MGMT,
7884 				"2516 CGN SET_FEATURE mbox failed with "
7885 				"status x%x add_status x%x, mbx status x%x "
7886 				"Reset Congestion to FPINs only\n",
7887 				shdr_status, shdr_add_status,
7888 				pmb->u.mb.mbxStatus);
7889 		/* If there is a mbox error, move on to RDF */
7890 		phba->cgn_reg_signal = EDC_CG_SIG_NOTSUPPORTED;
7891 		phba->cgn_reg_fpin = LPFC_CGN_FPIN_WARN | LPFC_CGN_FPIN_ALARM;
7892 		goto out;
7893 	}
7894 
7895 	/* Zero out Congestion Signal ACQE counter */
7896 	phba->cgn_acqe_cnt = 0;
7897 
7898 	acqe = bf_get(lpfc_mbx_set_feature_CGN_acqe_freq,
7899 		      &pmb->u.mqe.un.set_feature);
7900 	sig = bf_get(lpfc_mbx_set_feature_CGN_warn_freq,
7901 		     &pmb->u.mqe.un.set_feature);
7902 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
7903 			"4620 SET_FEATURES Success: Freq: %ds %dms "
7904 			" Reg: x%x x%x\n", acqe, sig,
7905 			phba->cgn_reg_signal, phba->cgn_reg_fpin);
7906 out:
7907 	mempool_free(pmb, phba->mbox_mem_pool);
7908 
7909 	/* Register for FPIN events from the fabric now that the
7910 	 * EDC common_set_features has completed.
7911 	 */
7912 	lpfc_issue_els_rdf(vport, 0);
7913 }
7914 
7915 int
7916 lpfc_config_cgn_signal(struct lpfc_hba *phba)
7917 {
7918 	LPFC_MBOXQ_t *mboxq;
7919 	u32 rc;
7920 
7921 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7922 	if (!mboxq)
7923 		goto out_rdf;
7924 
7925 	lpfc_set_features(phba, mboxq, LPFC_SET_CGN_SIGNAL);
7926 	mboxq->vport = phba->pport;
7927 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_cgn_set_ftrs;
7928 
7929 	lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
7930 			"4621 SET_FEATURES: FREQ sig x%x acqe x%x: "
7931 			"Reg: x%x x%x\n",
7932 			phba->cgn_sig_freq, lpfc_acqe_cgn_frequency,
7933 			phba->cgn_reg_signal, phba->cgn_reg_fpin);
7934 
7935 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
7936 	if (rc == MBX_NOT_FINISHED)
7937 		goto out;
7938 	return 0;
7939 
7940 out:
7941 	mempool_free(mboxq, phba->mbox_mem_pool);
7942 out_rdf:
7943 	/* If there is a mbox error, move on to RDF */
7944 	phba->cgn_reg_fpin = LPFC_CGN_FPIN_WARN | LPFC_CGN_FPIN_ALARM;
7945 	phba->cgn_reg_signal = EDC_CG_SIG_NOTSUPPORTED;
7946 	lpfc_issue_els_rdf(phba->pport, 0);
7947 	return -EIO;
7948 }
7949 
7950 /**
7951  * lpfc_init_idle_stat_hb - Initialize idle_stat tracking
7952  * @phba: pointer to lpfc hba data structure.
7953  *
7954  * This routine initializes the per-eq idle_stat to dynamically dictate
7955  * polling decisions.
7956  *
7957  * Return codes:
7958  *   None
7959  **/
7960 static void lpfc_init_idle_stat_hb(struct lpfc_hba *phba)
7961 {
7962 	int i;
7963 	struct lpfc_sli4_hdw_queue *hdwq;
7964 	struct lpfc_queue *eq;
7965 	struct lpfc_idle_stat *idle_stat;
7966 	u64 wall;
7967 
7968 	for_each_present_cpu(i) {
7969 		hdwq = &phba->sli4_hba.hdwq[phba->sli4_hba.cpu_map[i].hdwq];
7970 		eq = hdwq->hba_eq;
7971 
7972 		/* Skip if we've already handled this eq's primary CPU */
7973 		if (eq->chann != i)
7974 			continue;
7975 
7976 		idle_stat = &phba->sli4_hba.idle_stat[i];
7977 
7978 		idle_stat->prev_idle = get_cpu_idle_time(i, &wall, 1);
7979 		idle_stat->prev_wall = wall;
7980 
7981 		if (phba->nvmet_support ||
7982 		    phba->cmf_active_mode != LPFC_CFG_OFF ||
7983 		    phba->intr_type != MSIX)
7984 			eq->poll_mode = LPFC_QUEUE_WORK;
7985 		else
7986 			eq->poll_mode = LPFC_THREADED_IRQ;
7987 	}
7988 
7989 	if (!phba->nvmet_support && phba->intr_type == MSIX)
7990 		schedule_delayed_work(&phba->idle_stat_delay_work,
7991 				      msecs_to_jiffies(LPFC_IDLE_STAT_DELAY));
7992 }
7993 
7994 static void lpfc_sli4_dip(struct lpfc_hba *phba)
7995 {
7996 	uint32_t if_type;
7997 
7998 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
7999 	if (if_type == LPFC_SLI_INTF_IF_TYPE_2 ||
8000 	    if_type == LPFC_SLI_INTF_IF_TYPE_6) {
8001 		struct lpfc_register reg_data;
8002 
8003 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
8004 			       &reg_data.word0))
8005 			return;
8006 
8007 		if (bf_get(lpfc_sliport_status_dip, &reg_data))
8008 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8009 					"2904 Firmware Dump Image Present"
8010 					" on Adapter");
8011 	}
8012 }
8013 
8014 /**
8015  * lpfc_rx_monitor_create_ring - Initialize ring buffer for rx_monitor
8016  * @rx_monitor: Pointer to lpfc_rx_info_monitor object
8017  * @entries: Number of rx_info_entry objects to allocate in ring
8018  *
8019  * Return:
8020  * 0 - Success
8021  * ENOMEM - Failure to kmalloc
8022  **/
8023 int lpfc_rx_monitor_create_ring(struct lpfc_rx_info_monitor *rx_monitor,
8024 				u32 entries)
8025 {
8026 	rx_monitor->ring = kmalloc_objs(struct rx_info_entry, entries);
8027 	if (!rx_monitor->ring)
8028 		return -ENOMEM;
8029 
8030 	rx_monitor->head_idx = 0;
8031 	rx_monitor->tail_idx = 0;
8032 	spin_lock_init(&rx_monitor->lock);
8033 	rx_monitor->entries = entries;
8034 
8035 	return 0;
8036 }
8037 
8038 /**
8039  * lpfc_rx_monitor_destroy_ring - Free ring buffer for rx_monitor
8040  * @rx_monitor: Pointer to lpfc_rx_info_monitor object
8041  *
8042  * Called after cancellation of cmf_timer.
8043  **/
8044 void lpfc_rx_monitor_destroy_ring(struct lpfc_rx_info_monitor *rx_monitor)
8045 {
8046 	kfree(rx_monitor->ring);
8047 	rx_monitor->ring = NULL;
8048 	rx_monitor->entries = 0;
8049 	rx_monitor->head_idx = 0;
8050 	rx_monitor->tail_idx = 0;
8051 }
8052 
8053 /**
8054  * lpfc_rx_monitor_record - Insert an entry into rx_monitor's ring
8055  * @rx_monitor: Pointer to lpfc_rx_info_monitor object
8056  * @entry: Pointer to rx_info_entry
8057  *
8058  * Used to insert an rx_info_entry into rx_monitor's ring.  Note that this is a
8059  * deep copy of rx_info_entry not a shallow copy of the rx_info_entry ptr.
8060  *
8061  * This is called from lpfc_cmf_timer, which is in timer/softirq context.
8062  *
8063  * In cases of old data overflow, we do a best effort of FIFO order.
8064  **/
8065 void lpfc_rx_monitor_record(struct lpfc_rx_info_monitor *rx_monitor,
8066 			    struct rx_info_entry *entry)
8067 {
8068 	struct rx_info_entry *ring = rx_monitor->ring;
8069 	u32 *head_idx = &rx_monitor->head_idx;
8070 	u32 *tail_idx = &rx_monitor->tail_idx;
8071 	spinlock_t *ring_lock = &rx_monitor->lock;
8072 	u32 ring_size = rx_monitor->entries;
8073 
8074 	spin_lock(ring_lock);
8075 	memcpy(&ring[*tail_idx], entry, sizeof(*entry));
8076 	*tail_idx = (*tail_idx + 1) % ring_size;
8077 
8078 	/* Best effort of FIFO saved data */
8079 	if (*tail_idx == *head_idx)
8080 		*head_idx = (*head_idx + 1) % ring_size;
8081 
8082 	spin_unlock(ring_lock);
8083 }
8084 
8085 /**
8086  * lpfc_rx_monitor_report - Read out rx_monitor's ring
8087  * @phba: Pointer to lpfc_hba object
8088  * @rx_monitor: Pointer to lpfc_rx_info_monitor object
8089  * @buf: Pointer to char buffer that will contain rx monitor info data
8090  * @buf_len: Length buf including null char
8091  * @max_read_entries: Maximum number of entries to read out of ring
8092  *
8093  * Used to dump/read what's in rx_monitor's ring buffer.
8094  *
8095  * If buf is NULL || buf_len == 0, then it is implied that we want to log the
8096  * information to kmsg instead of filling out buf.
8097  *
8098  * Return:
8099  * Number of entries read out of the ring
8100  **/
8101 u32 lpfc_rx_monitor_report(struct lpfc_hba *phba,
8102 			   struct lpfc_rx_info_monitor *rx_monitor, char *buf,
8103 			   u32 buf_len, u32 max_read_entries)
8104 {
8105 	struct rx_info_entry *ring = rx_monitor->ring;
8106 	struct rx_info_entry *entry;
8107 	u32 *head_idx = &rx_monitor->head_idx;
8108 	u32 *tail_idx = &rx_monitor->tail_idx;
8109 	spinlock_t *ring_lock = &rx_monitor->lock;
8110 	u32 ring_size = rx_monitor->entries;
8111 	u32 cnt = 0;
8112 	bool log_to_kmsg = (!buf || !buf_len) ? true : false;
8113 	struct seq_buf s;
8114 
8115 	if (!log_to_kmsg) {
8116 		/* clear the buffer to be sure */
8117 		memset(buf, 0, buf_len);
8118 
8119 		seq_buf_init(&s, buf, buf_len);
8120 		seq_buf_printf(&s, "\t%-16s%-16s%-16s%-16s%-8s%-8s%-8s%-8s%-8s%-8s%-16s\n",
8121 			       "MaxBPI", "Tot_Data_CMF",
8122 			       "Tot_Data_Cmd", "Tot_Data_Cmpl",
8123 			       "Lat(us)", "Avg_IO", "Max_IO", "Bsy",
8124 			       "IO_cnt", "Info", "BWutil(ms)");
8125 	}
8126 
8127 	/* Needs to be _irq because record is called from timer interrupt
8128 	 * context
8129 	 */
8130 	spin_lock_irq(ring_lock);
8131 	while (*head_idx != *tail_idx) {
8132 		entry = &ring[*head_idx];
8133 
8134 		/* Read out this entry's data. */
8135 		if (!log_to_kmsg) {
8136 			unsigned int len;
8137 
8138 			/* A header that did not fit leaves no room. */
8139 			if (seq_buf_has_overflowed(&s))
8140 				break;
8141 			len = seq_buf_used(&s);
8142 
8143 			seq_buf_printf(&s,
8144 				       "%03d:\t%-16llu%-16llu%-16llu%-16llu%-8llu%-8llu%-8llu%-8u%-8u%-8u%u(%u)\n",
8145 				       *head_idx,
8146 				       entry->max_bytes_per_interval,
8147 				       entry->cmf_bytes,
8148 				       entry->total_bytes,
8149 				       entry->rcv_bytes,
8150 				       entry->avg_io_latency,
8151 				       entry->avg_io_size,
8152 				       entry->max_read_cnt,
8153 				       entry->cmf_busy, entry->io_cnt,
8154 				       entry->cmf_info,
8155 				       entry->timer_utilization,
8156 				       entry->timer_interval);
8157 
8158 			/*
8159 			 * Drop a record whole if it does not fit, without
8160 			 * consuming its ring entry: the reader takes the
8161 			 * string up to its NUL.
8162 			 */
8163 			if (seq_buf_has_overflowed(&s)) {
8164 				buf[len] = '\0';
8165 				break;
8166 			}
8167 		} else {
8168 			lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
8169 					"4410 %02u: MBPI %llu Xmit %llu "
8170 					"Cmpl %llu Lat %llu ASz %llu Info %02u "
8171 					"BWUtil %u Int %u slot %u\n",
8172 					cnt, entry->max_bytes_per_interval,
8173 					entry->total_bytes, entry->rcv_bytes,
8174 					entry->avg_io_latency,
8175 					entry->avg_io_size, entry->cmf_info,
8176 					entry->timer_utilization,
8177 					entry->timer_interval, *head_idx);
8178 		}
8179 
8180 		*head_idx = (*head_idx + 1) % ring_size;
8181 
8182 		/* Don't feed more than max_read_entries */
8183 		cnt++;
8184 		if (cnt >= max_read_entries)
8185 			break;
8186 	}
8187 	spin_unlock_irq(ring_lock);
8188 
8189 	return cnt;
8190 }
8191 
8192 /**
8193  * lpfc_cmf_setup - Initialize idle_stat tracking
8194  * @phba: Pointer to HBA context object.
8195  *
8196  * This is called from HBA setup during driver load or when the HBA
8197  * comes online. this does all the initialization to support CMF and MI.
8198  **/
8199 static int
8200 lpfc_cmf_setup(struct lpfc_hba *phba)
8201 {
8202 	LPFC_MBOXQ_t *mboxq;
8203 	struct lpfc_dmabuf *mp;
8204 	struct lpfc_pc_sli4_params *sli4_params;
8205 	int rc, cmf, mi_ver;
8206 
8207 	rc = lpfc_sli4_refresh_params(phba);
8208 	if (unlikely(rc))
8209 		return rc;
8210 
8211 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
8212 	if (!mboxq)
8213 		return -ENOMEM;
8214 
8215 	sli4_params = &phba->sli4_hba.pc_sli4_params;
8216 
8217 	/* Always try to enable MI feature if we can */
8218 	if (sli4_params->mi_ver) {
8219 		lpfc_set_features(phba, mboxq, LPFC_SET_ENABLE_MI);
8220 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8221 		mi_ver = bf_get(lpfc_mbx_set_feature_mi,
8222 				 &mboxq->u.mqe.un.set_feature);
8223 
8224 		if (rc == MBX_SUCCESS) {
8225 			if (mi_ver) {
8226 				lpfc_printf_log(phba,
8227 						KERN_WARNING, LOG_CGN_MGMT,
8228 						"6215 MI is enabled\n");
8229 				sli4_params->mi_ver = mi_ver;
8230 			} else {
8231 				lpfc_printf_log(phba,
8232 						KERN_WARNING, LOG_CGN_MGMT,
8233 						"6338 MI is disabled\n");
8234 				sli4_params->mi_ver = 0;
8235 			}
8236 		} else {
8237 			/* mi_ver is already set from GET_SLI4_PARAMETERS */
8238 			lpfc_printf_log(phba, KERN_INFO,
8239 					LOG_CGN_MGMT | LOG_INIT,
8240 					"6245 Enable MI Mailbox x%x (x%x/x%x) "
8241 					"failed, rc:x%x mi:x%x\n",
8242 					bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8243 					lpfc_sli_config_mbox_subsys_get
8244 						(phba, mboxq),
8245 					lpfc_sli_config_mbox_opcode_get
8246 						(phba, mboxq),
8247 					rc, sli4_params->mi_ver);
8248 		}
8249 	} else {
8250 		lpfc_printf_log(phba, KERN_WARNING, LOG_CGN_MGMT,
8251 				"6217 MI is disabled\n");
8252 	}
8253 
8254 	/* Ensure FDMI is enabled for MI if enable_mi is set */
8255 	if (sli4_params->mi_ver)
8256 		phba->cfg_fdmi_on = LPFC_FDMI_SUPPORT;
8257 
8258 	/* Always try to enable CMF feature if we can */
8259 	if (sli4_params->cmf) {
8260 		lpfc_set_features(phba, mboxq, LPFC_SET_ENABLE_CMF);
8261 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8262 		cmf = bf_get(lpfc_mbx_set_feature_cmf,
8263 			     &mboxq->u.mqe.un.set_feature);
8264 		if (rc == MBX_SUCCESS && cmf) {
8265 			lpfc_printf_log(phba, KERN_WARNING, LOG_CGN_MGMT,
8266 					"6218 CMF is enabled: mode %d\n",
8267 					phba->cmf_active_mode);
8268 		} else {
8269 			lpfc_printf_log(phba, KERN_WARNING,
8270 					LOG_CGN_MGMT | LOG_INIT,
8271 					"6219 Enable CMF Mailbox x%x (x%x/x%x) "
8272 					"failed, rc:x%x dd:x%x\n",
8273 					bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8274 					lpfc_sli_config_mbox_subsys_get
8275 						(phba, mboxq),
8276 					lpfc_sli_config_mbox_opcode_get
8277 						(phba, mboxq),
8278 					rc, cmf);
8279 			sli4_params->cmf = 0;
8280 			phba->cmf_active_mode = LPFC_CFG_OFF;
8281 			goto no_cmf;
8282 		}
8283 
8284 		/* Allocate Congestion Information Buffer */
8285 		if (!phba->cgn_i) {
8286 			mp = kmalloc_obj(*mp);
8287 			if (mp)
8288 				mp->virt = dma_alloc_coherent
8289 						(&phba->pcidev->dev,
8290 						sizeof(struct lpfc_cgn_info),
8291 						&mp->phys, GFP_KERNEL);
8292 			if (!mp || !mp->virt) {
8293 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8294 						"2640 Failed to alloc memory "
8295 						"for Congestion Info\n");
8296 				kfree(mp);
8297 				sli4_params->cmf = 0;
8298 				phba->cmf_active_mode = LPFC_CFG_OFF;
8299 				goto no_cmf;
8300 			}
8301 			phba->cgn_i = mp;
8302 
8303 			/* initialize congestion buffer info */
8304 			lpfc_init_congestion_buf(phba);
8305 			lpfc_init_congestion_stat(phba);
8306 
8307 			/* Zero out Congestion Signal counters */
8308 			atomic64_set(&phba->cgn_acqe_stat.alarm, 0);
8309 			atomic64_set(&phba->cgn_acqe_stat.warn, 0);
8310 		}
8311 
8312 		rc = lpfc_sli4_cgn_params_read(phba);
8313 		if (rc < 0) {
8314 			lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
8315 					"6242 Error reading Cgn Params (%d)\n",
8316 					rc);
8317 			/* Ensure CGN Mode is off */
8318 			sli4_params->cmf = 0;
8319 		} else if (!rc) {
8320 			lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
8321 					"6243 CGN Event empty object.\n");
8322 			/* Ensure CGN Mode is off */
8323 			sli4_params->cmf = 0;
8324 		}
8325 	} else {
8326 no_cmf:
8327 		lpfc_printf_log(phba, KERN_WARNING, LOG_CGN_MGMT,
8328 				"6220 CMF is disabled\n");
8329 	}
8330 
8331 	/* Only register congestion buffer with firmware if BOTH
8332 	 * CMF and E2E are enabled.
8333 	 */
8334 	if (sli4_params->cmf && sli4_params->mi_ver) {
8335 		rc = lpfc_reg_congestion_buf(phba);
8336 		if (rc) {
8337 			dma_free_coherent(&phba->pcidev->dev,
8338 					  sizeof(struct lpfc_cgn_info),
8339 					  phba->cgn_i->virt, phba->cgn_i->phys);
8340 			kfree(phba->cgn_i);
8341 			phba->cgn_i = NULL;
8342 			/* Ensure CGN Mode is off */
8343 			phba->cmf_active_mode = LPFC_CFG_OFF;
8344 			sli4_params->cmf = 0;
8345 			return 0;
8346 		}
8347 	}
8348 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8349 			"6470 Setup MI version %d CMF %d mode %d\n",
8350 			sli4_params->mi_ver, sli4_params->cmf,
8351 			phba->cmf_active_mode);
8352 
8353 	mempool_free(mboxq, phba->mbox_mem_pool);
8354 
8355 	/* Initialize atomic counters */
8356 	atomic_set(&phba->cgn_fabric_warn_cnt, 0);
8357 	atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
8358 	atomic_set(&phba->cgn_sync_alarm_cnt, 0);
8359 	atomic_set(&phba->cgn_sync_warn_cnt, 0);
8360 	atomic_set(&phba->cgn_driver_evt_cnt, 0);
8361 	atomic_set(&phba->cgn_latency_evt_cnt, 0);
8362 	atomic64_set(&phba->cgn_latency_evt, 0);
8363 
8364 	phba->cmf_interval_rate = LPFC_CMF_INTERVAL;
8365 
8366 	/* Allocate RX Monitor Buffer */
8367 	if (!phba->rx_monitor) {
8368 		phba->rx_monitor = kzalloc_obj(*phba->rx_monitor);
8369 
8370 		if (!phba->rx_monitor) {
8371 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8372 					"2644 Failed to alloc memory "
8373 					"for RX Monitor Buffer\n");
8374 			return -ENOMEM;
8375 		}
8376 
8377 		/* Instruct the rx_monitor object to instantiate its ring */
8378 		if (lpfc_rx_monitor_create_ring(phba->rx_monitor,
8379 						LPFC_MAX_RXMONITOR_ENTRY)) {
8380 			kfree(phba->rx_monitor);
8381 			phba->rx_monitor = NULL;
8382 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8383 					"2645 Failed to alloc memory "
8384 					"for RX Monitor's Ring\n");
8385 			return -ENOMEM;
8386 		}
8387 	}
8388 
8389 	return 0;
8390 }
8391 
8392 static int
8393 lpfc_set_host_tm(struct lpfc_hba *phba)
8394 {
8395 	LPFC_MBOXQ_t *mboxq;
8396 	uint32_t len, rc;
8397 	struct timespec64 cur_time;
8398 	struct tm broken;
8399 	uint32_t month, day, year;
8400 	uint32_t hour, minute, second;
8401 	struct lpfc_mbx_set_host_date_time *tm;
8402 
8403 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
8404 	if (!mboxq)
8405 		return -ENOMEM;
8406 
8407 	len = sizeof(struct lpfc_mbx_set_host_data) -
8408 		sizeof(struct lpfc_sli4_cfg_mhdr);
8409 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
8410 			 LPFC_MBOX_OPCODE_SET_HOST_DATA, len,
8411 			 LPFC_SLI4_MBX_EMBED);
8412 
8413 	mboxq->u.mqe.un.set_host_data.param_id = LPFC_SET_HOST_DATE_TIME;
8414 	mboxq->u.mqe.un.set_host_data.param_len =
8415 			sizeof(struct lpfc_mbx_set_host_date_time);
8416 	tm = &mboxq->u.mqe.un.set_host_data.un.tm;
8417 	ktime_get_real_ts64(&cur_time);
8418 	time64_to_tm(cur_time.tv_sec, 0, &broken);
8419 	month = broken.tm_mon + 1;
8420 	day = broken.tm_mday;
8421 	year = broken.tm_year - 100;
8422 	hour = broken.tm_hour;
8423 	minute = broken.tm_min;
8424 	second = broken.tm_sec;
8425 	bf_set(lpfc_mbx_set_host_month, tm, month);
8426 	bf_set(lpfc_mbx_set_host_day, tm, day);
8427 	bf_set(lpfc_mbx_set_host_year, tm, year);
8428 	bf_set(lpfc_mbx_set_host_hour, tm, hour);
8429 	bf_set(lpfc_mbx_set_host_min, tm, minute);
8430 	bf_set(lpfc_mbx_set_host_sec, tm, second);
8431 
8432 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8433 	mempool_free(mboxq, phba->mbox_mem_pool);
8434 	return rc;
8435 }
8436 
8437 /**
8438  * lpfc_get_platform_uuid - Attempts to extract a platform uuid
8439  * @phba: pointer to lpfc hba data structure.
8440  *
8441  * This routine attempts to first read SMBIOS DMI data for the System
8442  * Information structure offset 08h called System UUID.  Else, no platform
8443  * UUID will be advertised.
8444  **/
8445 static void
8446 lpfc_get_platform_uuid(struct lpfc_hba *phba)
8447 {
8448 	int rc;
8449 	const char *uuid;
8450 	char pni[17] = {0}; /* 16 characters + '\0' */
8451 	bool is_ff = true, is_00 = true;
8452 	u8 i;
8453 
8454 	/* First attempt SMBIOS DMI */
8455 	uuid = dmi_get_system_info(DMI_PRODUCT_UUID);
8456 	if (uuid) {
8457 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8458 				"2088 SMBIOS UUID %s\n",
8459 				uuid);
8460 	} else {
8461 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8462 				"2099 Could not extract UUID\n");
8463 	}
8464 
8465 	if (uuid && uuid_is_valid(uuid)) {
8466 		/* Generate PNI from UUID format.
8467 		 *
8468 		 * 1.) Extract lower 64 bits from UUID format.
8469 		 * 2.) Set 3h for NAA Locally Assigned Name Identifier format.
8470 		 *
8471 		 * e.g. xxxxxxxx-xxxx-xxxx-yyyy-yyyyyyyyyyyy
8472 		 *
8473 		 * extract the yyyy-yyyyyyyyyyyy portion
8474 		 * final PNI   3yyyyyyyyyyyyyyy
8475 		 */
8476 		scnprintf(pni, sizeof(pni), "3%c%c%c%s",
8477 			  uuid[20], uuid[21], uuid[22], &uuid[24]);
8478 
8479 		/* Sanitize the converted PNI */
8480 		for (i = 1; i < 16 && (is_ff || is_00); i++) {
8481 			if (pni[i] != '0')
8482 				is_00 = false;
8483 			if (pni[i] != 'f' && pni[i] != 'F')
8484 				is_ff = false;
8485 		}
8486 
8487 		/* Convert from char* to unsigned long */
8488 		rc = kstrtoul(pni, 16, &phba->pni);
8489 		if (!rc && !is_ff && !is_00) {
8490 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8491 					"2100 PNI 0x%016lx\n", phba->pni);
8492 		} else {
8493 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8494 					"2101 PNI %s generation status %d\n",
8495 					pni, rc);
8496 			phba->pni = 0;
8497 		}
8498 	}
8499 }
8500 
8501 /**
8502  * lpfc_sli4_hba_setup - SLI4 device initialization PCI function
8503  * @phba: Pointer to HBA context object.
8504  *
8505  * This function is the main SLI4 device initialization PCI function. This
8506  * function is called by the HBA initialization code, HBA reset code and
8507  * HBA error attention handler code. Caller is not required to hold any
8508  * locks.
8509  **/
8510 int
8511 lpfc_sli4_hba_setup(struct lpfc_hba *phba)
8512 {
8513 	int rc, i, cnt, len, dd;
8514 	LPFC_MBOXQ_t *mboxq;
8515 	struct lpfc_mqe *mqe;
8516 	uint8_t *vpd;
8517 	uint32_t vpd_size;
8518 	uint32_t ftr_rsp = 0;
8519 	struct Scsi_Host *shost = lpfc_shost_from_vport(phba->pport);
8520 	struct lpfc_vport *vport = phba->pport;
8521 	struct lpfc_dmabuf *mp;
8522 	struct lpfc_rqb *rqbp;
8523 	u32 flg;
8524 
8525 	/* Perform a PCI function reset to start from clean */
8526 	rc = lpfc_pci_function_reset(phba);
8527 	if (unlikely(rc))
8528 		return -ENODEV;
8529 
8530 	/* Check the HBA Host Status Register for readiness */
8531 	rc = lpfc_sli4_post_status_check(phba);
8532 	if (unlikely(rc))
8533 		return -ENODEV;
8534 	else {
8535 		spin_lock_irq(&phba->hbalock);
8536 		phba->sli.sli_flag |= LPFC_SLI_ACTIVE;
8537 		flg = phba->sli.sli_flag;
8538 		spin_unlock_irq(&phba->hbalock);
8539 		/* Allow a little time after setting SLI_ACTIVE for any polled
8540 		 * MBX commands to complete via BSG.
8541 		 */
8542 		for (i = 0; i < 50 && (flg & LPFC_SLI_MBOX_ACTIVE); i++) {
8543 			msleep(20);
8544 			spin_lock_irq(&phba->hbalock);
8545 			flg = phba->sli.sli_flag;
8546 			spin_unlock_irq(&phba->hbalock);
8547 		}
8548 	}
8549 	clear_bit(HBA_SETUP, &phba->hba_flag);
8550 
8551 	lpfc_sli4_dip(phba);
8552 
8553 	/*
8554 	 * Allocate a single mailbox container for initializing the
8555 	 * port.
8556 	 */
8557 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
8558 	if (!mboxq)
8559 		return -ENOMEM;
8560 
8561 	/* Issue READ_REV to collect vpd and FW information. */
8562 	vpd_size = SLI4_PAGE_SIZE;
8563 	vpd = kzalloc(vpd_size, GFP_KERNEL);
8564 	if (!vpd) {
8565 		rc = -ENOMEM;
8566 		goto out_free_mbox;
8567 	}
8568 
8569 	rc = lpfc_sli4_read_rev(phba, mboxq, vpd, &vpd_size);
8570 	if (unlikely(rc)) {
8571 		kfree(vpd);
8572 		goto out_free_mbox;
8573 	}
8574 
8575 	mqe = &mboxq->u.mqe;
8576 	phba->sli_rev = bf_get(lpfc_mbx_rd_rev_sli_lvl, &mqe->un.read_rev);
8577 	if (bf_get(lpfc_mbx_rd_rev_fcoe, &mqe->un.read_rev)) {
8578 		set_bit(HBA_FCOE_MODE, &phba->hba_flag);
8579 		phba->fcp_embed_io = 0;	/* SLI4 FC support only */
8580 	} else {
8581 		clear_bit(HBA_FCOE_MODE, &phba->hba_flag);
8582 	}
8583 
8584 	/* Obtain platform UUID, only for SLI4 FC adapters */
8585 	if (!test_bit(HBA_FCOE_MODE, &phba->hba_flag))
8586 		lpfc_get_platform_uuid(phba);
8587 
8588 	if (bf_get(lpfc_mbx_rd_rev_cee_ver, &mqe->un.read_rev) ==
8589 		LPFC_DCBX_CEE_MODE)
8590 		set_bit(HBA_FIP_SUPPORT, &phba->hba_flag);
8591 	else
8592 		clear_bit(HBA_FIP_SUPPORT, &phba->hba_flag);
8593 
8594 	clear_bit(HBA_IOQ_FLUSH, &phba->hba_flag);
8595 
8596 	if (phba->sli_rev != LPFC_SLI_REV4) {
8597 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8598 			"0376 READ_REV Error. SLI Level %d "
8599 			"FCoE enabled %d\n",
8600 			phba->sli_rev,
8601 			test_bit(HBA_FCOE_MODE, &phba->hba_flag) ? 1 : 0);
8602 		rc = -EIO;
8603 		kfree(vpd);
8604 		goto out_free_mbox;
8605 	}
8606 
8607 	rc = lpfc_set_host_tm(phba);
8608 	lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
8609 			"6468 Set host date / time: Status x%x:\n", rc);
8610 
8611 	/*
8612 	 * Continue initialization with default values even if driver failed
8613 	 * to read FCoE param config regions, only read parameters if the
8614 	 * board is FCoE
8615 	 */
8616 	if (test_bit(HBA_FCOE_MODE, &phba->hba_flag) &&
8617 	    lpfc_sli4_read_fcoe_params(phba))
8618 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_INIT,
8619 			"2570 Failed to read FCoE parameters\n");
8620 
8621 	/*
8622 	 * Retrieve sli4 device physical port name, failure of doing it
8623 	 * is considered as non-fatal.
8624 	 */
8625 	rc = lpfc_sli4_retrieve_pport_name(phba);
8626 	if (!rc)
8627 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8628 				"3080 Successful retrieving SLI4 device "
8629 				"physical port name: %s.\n", phba->Port);
8630 
8631 	rc = lpfc_sli4_get_ctl_attr(phba);
8632 	if (!rc)
8633 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8634 				"8351 Successful retrieving SLI4 device "
8635 				"CTL ATTR\n");
8636 
8637 	/*
8638 	 * Evaluate the read rev and vpd data. Populate the driver
8639 	 * state with the results. If this routine fails, the failure
8640 	 * is not fatal as the driver will use generic values.
8641 	 */
8642 	rc = lpfc_parse_vpd(phba, vpd, vpd_size);
8643 	if (unlikely(!rc))
8644 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8645 				"0377 Error %d parsing vpd. "
8646 				"Using defaults.\n", rc);
8647 	kfree(vpd);
8648 
8649 	/* Save information as VPD data */
8650 	phba->vpd.rev.biuRev = mqe->un.read_rev.first_hw_rev;
8651 	phba->vpd.rev.smRev = mqe->un.read_rev.second_hw_rev;
8652 
8653 	/*
8654 	 * This is because first G7 ASIC doesn't support the standard
8655 	 * 0x5a NVME cmd descriptor type/subtype
8656 	 */
8657 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
8658 			LPFC_SLI_INTF_IF_TYPE_6) &&
8659 	    (phba->vpd.rev.biuRev == LPFC_G7_ASIC_1) &&
8660 	    (phba->vpd.rev.smRev == 0) &&
8661 	    (phba->cfg_nvme_embed_cmd == 1))
8662 		phba->cfg_nvme_embed_cmd = 0;
8663 
8664 	phba->vpd.rev.endecRev = mqe->un.read_rev.third_hw_rev;
8665 	phba->vpd.rev.fcphHigh = bf_get(lpfc_mbx_rd_rev_fcph_high,
8666 					 &mqe->un.read_rev);
8667 	phba->vpd.rev.fcphLow = bf_get(lpfc_mbx_rd_rev_fcph_low,
8668 				       &mqe->un.read_rev);
8669 	phba->vpd.rev.feaLevelHigh = bf_get(lpfc_mbx_rd_rev_ftr_lvl_high,
8670 					    &mqe->un.read_rev);
8671 	phba->vpd.rev.feaLevelLow = bf_get(lpfc_mbx_rd_rev_ftr_lvl_low,
8672 					   &mqe->un.read_rev);
8673 	phba->vpd.rev.sli1FwRev = mqe->un.read_rev.fw_id_rev;
8674 	memcpy(phba->vpd.rev.sli1FwName, mqe->un.read_rev.fw_name, 16);
8675 	phba->vpd.rev.sli2FwRev = mqe->un.read_rev.ulp_fw_id_rev;
8676 	memcpy(phba->vpd.rev.sli2FwName, mqe->un.read_rev.ulp_fw_name, 16);
8677 	phba->vpd.rev.opFwRev = mqe->un.read_rev.fw_id_rev;
8678 	memcpy(phba->vpd.rev.opFwName, mqe->un.read_rev.fw_name, 16);
8679 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8680 			"(%d):0380 READ_REV Status x%x "
8681 			"fw_rev:%s fcphHi:%x fcphLo:%x flHi:%x flLo:%x\n",
8682 			mboxq->vport ? mboxq->vport->vpi : 0,
8683 			bf_get(lpfc_mqe_status, mqe),
8684 			phba->vpd.rev.opFwName,
8685 			phba->vpd.rev.fcphHigh, phba->vpd.rev.fcphLow,
8686 			phba->vpd.rev.feaLevelHigh, phba->vpd.rev.feaLevelLow);
8687 
8688 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
8689 	    LPFC_SLI_INTF_IF_TYPE_0) {
8690 		lpfc_set_features(phba, mboxq, LPFC_SET_UE_RECOVERY);
8691 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8692 		if (rc == MBX_SUCCESS) {
8693 			set_bit(HBA_RECOVERABLE_UE, &phba->hba_flag);
8694 			/* Set 1Sec interval to detect UE */
8695 			phba->eratt_poll_interval = 1;
8696 			phba->sli4_hba.ue_to_sr = bf_get(
8697 					lpfc_mbx_set_feature_UESR,
8698 					&mboxq->u.mqe.un.set_feature);
8699 			phba->sli4_hba.ue_to_rp = bf_get(
8700 					lpfc_mbx_set_feature_UERP,
8701 					&mboxq->u.mqe.un.set_feature);
8702 		}
8703 	}
8704 
8705 	if (phba->cfg_enable_mds_diags && phba->mds_diags_support) {
8706 		/* Enable MDS Diagnostics only if the SLI Port supports it */
8707 		lpfc_set_features(phba, mboxq, LPFC_SET_MDS_DIAGS);
8708 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8709 		if (rc != MBX_SUCCESS)
8710 			phba->mds_diags_support = 0;
8711 	}
8712 
8713 	/*
8714 	 * Discover the port's supported feature set and match it against the
8715 	 * hosts requests.
8716 	 */
8717 	lpfc_request_features(phba, mboxq);
8718 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8719 	if (unlikely(rc)) {
8720 		rc = -EIO;
8721 		goto out_free_mbox;
8722 	}
8723 
8724 	/* Disable VMID if app header is not supported */
8725 	if (phba->cfg_vmid_app_header && !(bf_get(lpfc_mbx_rq_ftr_rsp_ashdr,
8726 						  &mqe->un.req_ftrs))) {
8727 		bf_set(lpfc_ftr_ashdr, &phba->sli4_hba.sli4_flags, 0);
8728 		phba->cfg_vmid_app_header = 0;
8729 		lpfc_printf_log(phba, KERN_DEBUG, LOG_SLI,
8730 				"1242 vmid feature not supported\n");
8731 	}
8732 
8733 	/*
8734 	 * The port must support FCP initiator mode as this is the
8735 	 * only mode running in the host.
8736 	 */
8737 	if (!(bf_get(lpfc_mbx_rq_ftr_rsp_fcpi, &mqe->un.req_ftrs))) {
8738 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8739 				"0378 No support for fcpi mode.\n");
8740 		ftr_rsp++;
8741 	}
8742 
8743 	/*
8744 	 * If the port cannot support the host's requested features
8745 	 * then turn off the global config parameters to disable the
8746 	 * feature in the driver.  This is not a fatal error.
8747 	 */
8748 	if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
8749 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs))) {
8750 			phba->cfg_enable_bg = 0;
8751 			phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
8752 			ftr_rsp++;
8753 		}
8754 	}
8755 
8756 	if (phba->max_vpi && phba->cfg_enable_npiv &&
8757 	    !(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
8758 		ftr_rsp++;
8759 
8760 	if (ftr_rsp) {
8761 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8762 				"0379 Feature Mismatch Data: x%08x %08x "
8763 				"x%x x%x x%x\n", mqe->un.req_ftrs.word2,
8764 				mqe->un.req_ftrs.word3, phba->cfg_enable_bg,
8765 				phba->cfg_enable_npiv, phba->max_vpi);
8766 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs)))
8767 			phba->cfg_enable_bg = 0;
8768 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
8769 			phba->cfg_enable_npiv = 0;
8770 	}
8771 
8772 	/* These SLI3 features are assumed in SLI4 */
8773 	spin_lock_irq(&phba->hbalock);
8774 	phba->sli3_options |= (LPFC_SLI3_NPIV_ENABLED | LPFC_SLI3_HBQ_ENABLED);
8775 	spin_unlock_irq(&phba->hbalock);
8776 
8777 	/* Always try to enable dual dump feature if we can */
8778 	lpfc_set_features(phba, mboxq, LPFC_SET_DUAL_DUMP);
8779 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8780 	dd = bf_get(lpfc_mbx_set_feature_dd, &mboxq->u.mqe.un.set_feature);
8781 	if ((rc == MBX_SUCCESS) && (dd == LPFC_ENABLE_DUAL_DUMP))
8782 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8783 				"6448 Dual Dump is enabled\n");
8784 	else
8785 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI | LOG_INIT,
8786 				"6447 Dual Dump Mailbox x%x (x%x/x%x) failed, "
8787 				"rc:x%x dd:x%x\n",
8788 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8789 				lpfc_sli_config_mbox_subsys_get(
8790 					phba, mboxq),
8791 				lpfc_sli_config_mbox_opcode_get(
8792 					phba, mboxq),
8793 				rc, dd);
8794 
8795 	/*
8796 	 * Allocate all resources (xri,rpi,vpi,vfi) now.  Subsequent
8797 	 * calls depends on these resources to complete port setup.
8798 	 */
8799 	rc = lpfc_sli4_alloc_resource_identifiers(phba);
8800 	if (rc) {
8801 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8802 				"2920 Failed to alloc Resource IDs "
8803 				"rc = x%x\n", rc);
8804 		goto out_free_mbox;
8805 	}
8806 
8807 	lpfc_sli4_node_rpi_restore(phba);
8808 
8809 	lpfc_set_host_data(phba, mboxq);
8810 
8811 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8812 	if (rc) {
8813 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8814 				"2134 Failed to set host os driver version %x",
8815 				rc);
8816 	}
8817 
8818 	/* Read the port's service parameters. */
8819 	rc = lpfc_read_sparam(phba, mboxq, vport->vpi);
8820 	if (rc) {
8821 		phba->link_state = LPFC_HBA_ERROR;
8822 		rc = -ENOMEM;
8823 		goto out_free_mbox;
8824 	}
8825 
8826 	mboxq->vport = vport;
8827 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8828 	mp = mboxq->ctx_buf;
8829 	if (rc == MBX_SUCCESS) {
8830 		memcpy(&vport->fc_sparam, mp->virt, sizeof(struct serv_parm));
8831 		rc = 0;
8832 	}
8833 
8834 	/*
8835 	 * This memory was allocated by the lpfc_read_sparam routine but is
8836 	 * no longer needed.  It is released and ctx_buf NULLed to prevent
8837 	 * unintended pointer access as the mbox is reused.
8838 	 */
8839 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
8840 	kfree(mp);
8841 	mboxq->ctx_buf = NULL;
8842 	if (unlikely(rc)) {
8843 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8844 				"0382 READ_SPARAM command failed "
8845 				"status %d, mbxStatus x%x\n",
8846 				rc, bf_get(lpfc_mqe_status, mqe));
8847 		phba->link_state = LPFC_HBA_ERROR;
8848 		rc = -EIO;
8849 		goto out_free_mbox;
8850 	}
8851 
8852 	lpfc_update_vport_wwn(vport);
8853 
8854 	/* Update the fc_host data structures with new wwn. */
8855 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
8856 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
8857 
8858 	/* Create all the SLI4 queues */
8859 	rc = lpfc_sli4_queue_create(phba);
8860 	if (rc) {
8861 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8862 				"3089 Failed to allocate queues\n");
8863 		rc = -ENODEV;
8864 		goto out_free_mbox;
8865 	}
8866 	/* Set up all the queues to the device */
8867 	rc = lpfc_sli4_queue_setup(phba);
8868 	if (unlikely(rc)) {
8869 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8870 				"0381 Error %d during queue setup.\n", rc);
8871 		goto out_destroy_queue;
8872 	}
8873 	/* Initialize the driver internal SLI layer lists. */
8874 	lpfc_sli4_setup(phba);
8875 	lpfc_sli4_queue_init(phba);
8876 
8877 	/* update host els xri-sgl sizes and mappings */
8878 	rc = lpfc_sli4_els_sgl_update(phba);
8879 	if (unlikely(rc)) {
8880 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8881 				"1400 Failed to update xri-sgl size and "
8882 				"mapping: %d\n", rc);
8883 		goto out_destroy_queue;
8884 	}
8885 
8886 	/* register the els sgl pool to the port */
8887 	rc = lpfc_sli4_repost_sgl_list(phba, &phba->sli4_hba.lpfc_els_sgl_list,
8888 				       phba->sli4_hba.els_xri_cnt);
8889 	if (unlikely(rc < 0)) {
8890 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8891 				"0582 Error %d during els sgl post "
8892 				"operation\n", rc);
8893 		rc = -ENODEV;
8894 		goto out_destroy_queue;
8895 	}
8896 	phba->sli4_hba.els_xri_cnt = rc;
8897 
8898 	if (phba->nvmet_support) {
8899 		/* update host nvmet xri-sgl sizes and mappings */
8900 		rc = lpfc_sli4_nvmet_sgl_update(phba);
8901 		if (unlikely(rc)) {
8902 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8903 					"6308 Failed to update nvmet-sgl size "
8904 					"and mapping: %d\n", rc);
8905 			goto out_destroy_queue;
8906 		}
8907 
8908 		/* register the nvmet sgl pool to the port */
8909 		rc = lpfc_sli4_repost_sgl_list(
8910 			phba,
8911 			&phba->sli4_hba.lpfc_nvmet_sgl_list,
8912 			phba->sli4_hba.nvmet_xri_cnt);
8913 		if (unlikely(rc < 0)) {
8914 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8915 					"3117 Error %d during nvmet "
8916 					"sgl post\n", rc);
8917 			rc = -ENODEV;
8918 			goto out_destroy_queue;
8919 		}
8920 		phba->sli4_hba.nvmet_xri_cnt = rc;
8921 
8922 		/* We allocate an iocbq for every receive context SGL.
8923 		 * The additional allocation is for abort and ls handling.
8924 		 */
8925 		cnt = phba->sli4_hba.nvmet_xri_cnt +
8926 			phba->sli4_hba.max_cfg_param.max_xri;
8927 	} else {
8928 		/* update host common xri-sgl sizes and mappings */
8929 		rc = lpfc_sli4_io_sgl_update(phba);
8930 		if (unlikely(rc)) {
8931 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8932 					"6082 Failed to update nvme-sgl size "
8933 					"and mapping: %d\n", rc);
8934 			goto out_destroy_queue;
8935 		}
8936 
8937 		/* register the allocated common sgl pool to the port */
8938 		rc = lpfc_sli4_repost_io_sgl_list(phba);
8939 		if (unlikely(rc)) {
8940 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8941 					"6116 Error %d during nvme sgl post "
8942 					"operation\n", rc);
8943 			/* Some NVME buffers were moved to abort nvme list */
8944 			/* A pci function reset will repost them */
8945 			rc = -ENODEV;
8946 			goto out_destroy_queue;
8947 		}
8948 		/* Each lpfc_io_buf job structure has an iocbq element.
8949 		 * This cnt provides for abort, els, ct and ls requests.
8950 		 */
8951 		cnt = phba->sli4_hba.max_cfg_param.max_xri;
8952 	}
8953 
8954 	if (!phba->sli.iocbq_lookup) {
8955 		/* Initialize and populate the iocb list per host */
8956 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8957 				"2821 initialize iocb list with %d entries\n",
8958 				cnt);
8959 		rc = lpfc_init_iocb_list(phba, cnt);
8960 		if (rc) {
8961 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8962 					"1413 Failed to init iocb list.\n");
8963 			goto out_destroy_queue;
8964 		}
8965 	}
8966 
8967 	if (phba->nvmet_support)
8968 		lpfc_nvmet_create_targetport(phba);
8969 
8970 	if (phba->nvmet_support && phba->cfg_nvmet_mrq) {
8971 		/* Post initial buffers to all RQs created */
8972 		for (i = 0; i < phba->cfg_nvmet_mrq; i++) {
8973 			rqbp = phba->sli4_hba.nvmet_mrq_hdr[i]->rqbp;
8974 			INIT_LIST_HEAD(&rqbp->rqb_buffer_list);
8975 			rqbp->rqb_alloc_buffer = lpfc_sli4_nvmet_alloc;
8976 			rqbp->rqb_free_buffer = lpfc_sli4_nvmet_free;
8977 			rqbp->entry_count = LPFC_NVMET_RQE_DEF_COUNT;
8978 			rqbp->buffer_count = 0;
8979 
8980 			lpfc_post_rq_buffer(
8981 				phba, phba->sli4_hba.nvmet_mrq_hdr[i],
8982 				phba->sli4_hba.nvmet_mrq_data[i],
8983 				phba->cfg_nvmet_mrq_post, i);
8984 		}
8985 	}
8986 
8987 	/* Post the rpi header region to the device. */
8988 	rc = lpfc_sli4_post_all_rpi_hdrs(phba);
8989 	if (unlikely(rc)) {
8990 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8991 				"0393 Error %d during rpi post operation\n",
8992 				rc);
8993 		rc = -ENODEV;
8994 		goto out_free_iocblist;
8995 	}
8996 
8997 	if (!test_bit(HBA_FCOE_MODE, &phba->hba_flag)) {
8998 		if ((phba->nvmet_support == 0) || (phba->cfg_nvmet_mrq == 1)) {
8999 			/*
9000 			 * The FC Port needs to register FCFI (index 0)
9001 			 */
9002 			lpfc_reg_fcfi(phba, mboxq);
9003 			mboxq->vport = phba->pport;
9004 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
9005 			if (rc != MBX_SUCCESS)
9006 				goto out_unset_queue;
9007 			rc = 0;
9008 			phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_fcfi,
9009 						&mboxq->u.mqe.un.reg_fcfi);
9010 		} else {
9011 			/* We are a NVME Target mode with MRQ > 1 */
9012 
9013 			/* First register the FCFI */
9014 			lpfc_reg_fcfi_mrq(phba, mboxq, 0);
9015 			mboxq->vport = phba->pport;
9016 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
9017 			if (rc != MBX_SUCCESS)
9018 				goto out_unset_queue;
9019 			rc = 0;
9020 			phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_mrq_fcfi,
9021 						&mboxq->u.mqe.un.reg_fcfi_mrq);
9022 
9023 			/* Next register the MRQs */
9024 			lpfc_reg_fcfi_mrq(phba, mboxq, 1);
9025 			mboxq->vport = phba->pport;
9026 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
9027 			if (rc != MBX_SUCCESS)
9028 				goto out_unset_queue;
9029 			rc = 0;
9030 		}
9031 		/* Check if the port is configured to be disabled */
9032 		lpfc_sli_read_link_ste(phba);
9033 	}
9034 
9035 	/* Don't post more new bufs if repost already recovered
9036 	 * the nvme sgls.
9037 	 */
9038 	if (phba->nvmet_support == 0) {
9039 		if (phba->sli4_hba.io_xri_cnt == 0) {
9040 			len = lpfc_new_io_buf(
9041 					      phba, phba->sli4_hba.io_xri_max);
9042 			if (len == 0) {
9043 				rc = -ENOMEM;
9044 				goto out_unset_queue;
9045 			}
9046 
9047 			if (phba->cfg_xri_rebalancing)
9048 				lpfc_create_multixri_pools(phba);
9049 		}
9050 	} else {
9051 		phba->cfg_xri_rebalancing = 0;
9052 	}
9053 
9054 	/* Allow asynchronous mailbox command to go through */
9055 	spin_lock_irq(&phba->hbalock);
9056 	phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
9057 	spin_unlock_irq(&phba->hbalock);
9058 
9059 	/* Post receive buffers to the device */
9060 	lpfc_sli4_rb_setup(phba);
9061 
9062 	/* Reset HBA FCF states after HBA reset */
9063 	phba->fcf.fcf_flag = 0;
9064 	phba->fcf.current_rec.flag = 0;
9065 
9066 	/* Start the ELS watchdog timer */
9067 	mod_timer(&vport->els_tmofunc,
9068 			jiffies + secs_to_jiffies(phba->fc_ratov * 2));
9069 
9070 	/* Start heart beat timer */
9071 	mod_timer(&phba->hb_tmofunc,
9072 		  jiffies + secs_to_jiffies(LPFC_HB_MBOX_INTERVAL));
9073 	clear_bit(HBA_HBEAT_INP, &phba->hba_flag);
9074 	clear_bit(HBA_HBEAT_TMO, &phba->hba_flag);
9075 	phba->last_completion_time = jiffies;
9076 
9077 	/* start eq_delay heartbeat */
9078 	if (phba->cfg_auto_imax)
9079 		queue_delayed_work(phba->wq, &phba->eq_delay_work,
9080 				   msecs_to_jiffies(LPFC_EQ_DELAY_MSECS));
9081 
9082 	/* start per phba idle_stat_delay heartbeat */
9083 	lpfc_init_idle_stat_hb(phba);
9084 
9085 	/* Start error attention (ERATT) polling timer */
9086 	mod_timer(&phba->eratt_poll,
9087 		  jiffies + secs_to_jiffies(phba->eratt_poll_interval));
9088 
9089 	/*
9090 	 * The port is ready, set the host's link state to LINK_DOWN
9091 	 * in preparation for link interrupts.
9092 	 */
9093 	spin_lock_irq(&phba->hbalock);
9094 	phba->link_state = LPFC_LINK_DOWN;
9095 
9096 	/* Check if physical ports are trunked */
9097 	if (bf_get(lpfc_conf_trunk_port0, &phba->sli4_hba))
9098 		phba->trunk_link.link0.state = LPFC_LINK_DOWN;
9099 	if (bf_get(lpfc_conf_trunk_port1, &phba->sli4_hba))
9100 		phba->trunk_link.link1.state = LPFC_LINK_DOWN;
9101 	if (bf_get(lpfc_conf_trunk_port2, &phba->sli4_hba))
9102 		phba->trunk_link.link2.state = LPFC_LINK_DOWN;
9103 	if (bf_get(lpfc_conf_trunk_port3, &phba->sli4_hba))
9104 		phba->trunk_link.link3.state = LPFC_LINK_DOWN;
9105 	spin_unlock_irq(&phba->hbalock);
9106 
9107 	/* Arm the CQs and then EQs on device */
9108 	lpfc_sli4_arm_cqeq_intr(phba);
9109 
9110 	/* Indicate device interrupt mode */
9111 	phba->sli4_hba.intr_enable = 1;
9112 
9113 	/* Setup CMF after HBA is initialized */
9114 	lpfc_cmf_setup(phba);
9115 
9116 	if (!test_bit(HBA_FCOE_MODE, &phba->hba_flag) &&
9117 	    test_bit(LINK_DISABLED, &phba->hba_flag)) {
9118 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9119 				"3103 Adapter Link is disabled.\n");
9120 		lpfc_down_link(phba, mboxq);
9121 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
9122 		if (rc != MBX_SUCCESS) {
9123 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9124 					"3104 Adapter failed to issue "
9125 					"DOWN_LINK mbox cmd, rc:x%x\n", rc);
9126 			goto out_io_buff_free;
9127 		}
9128 	} else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
9129 		/* don't perform init_link on SLI4 FC port loopback test */
9130 		if (!(phba->link_flag & LS_LOOPBACK_MODE)) {
9131 			rc = phba->lpfc_hba_init_link(phba, MBX_NOWAIT);
9132 			if (rc)
9133 				goto out_io_buff_free;
9134 		}
9135 	}
9136 	mempool_free(mboxq, phba->mbox_mem_pool);
9137 
9138 	/* Enable RAS FW log support */
9139 	lpfc_sli4_ras_setup(phba);
9140 
9141 	set_bit(HBA_SETUP, &phba->hba_flag);
9142 	return rc;
9143 
9144 out_io_buff_free:
9145 	/* Free allocated IO Buffers */
9146 	lpfc_io_free(phba);
9147 out_unset_queue:
9148 	/* Unset all the queues set up in this routine when error out */
9149 	lpfc_sli4_queue_unset(phba);
9150 out_free_iocblist:
9151 	lpfc_free_iocb_list(phba);
9152 out_destroy_queue:
9153 	lpfc_sli4_queue_destroy(phba);
9154 	lpfc_stop_hba_timers(phba);
9155 out_free_mbox:
9156 	mempool_free(mboxq, phba->mbox_mem_pool);
9157 	return rc;
9158 }
9159 
9160 /**
9161  * lpfc_mbox_timeout - Timeout call back function for mbox timer
9162  * @t: Context to fetch pointer to hba structure from.
9163  *
9164  * This is the callback function for mailbox timer. The mailbox
9165  * timer is armed when a new mailbox command is issued and the timer
9166  * is deleted when the mailbox complete. The function is called by
9167  * the kernel timer code when a mailbox does not complete within
9168  * expected time. This function wakes up the worker thread to
9169  * process the mailbox timeout and returns. All the processing is
9170  * done by the worker thread function lpfc_mbox_timeout_handler.
9171  **/
9172 void
9173 lpfc_mbox_timeout(struct timer_list *t)
9174 {
9175 	struct lpfc_hba  *phba = timer_container_of(phba, t, sli.mbox_tmo);
9176 	unsigned long iflag;
9177 	uint32_t tmo_posted;
9178 
9179 	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
9180 	tmo_posted = phba->pport->work_port_events & WORKER_MBOX_TMO;
9181 	if (!tmo_posted)
9182 		phba->pport->work_port_events |= WORKER_MBOX_TMO;
9183 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
9184 
9185 	if (!tmo_posted)
9186 		lpfc_worker_wake_up(phba);
9187 	return;
9188 }
9189 
9190 /**
9191  * lpfc_sli4_mbox_completions_pending - check to see if any mailbox completions
9192  *                                    are pending
9193  * @phba: Pointer to HBA context object.
9194  *
9195  * This function checks if any mailbox completions are present on the mailbox
9196  * completion queue.
9197  **/
9198 static bool
9199 lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba)
9200 {
9201 
9202 	uint32_t idx;
9203 	struct lpfc_queue *mcq;
9204 	struct lpfc_mcqe *mcqe;
9205 	bool pending_completions = false;
9206 	uint8_t	qe_valid;
9207 
9208 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
9209 		return false;
9210 
9211 	/* Check for completions on mailbox completion queue */
9212 
9213 	mcq = phba->sli4_hba.mbx_cq;
9214 	idx = mcq->hba_index;
9215 	qe_valid = mcq->qe_valid;
9216 	while (bf_get_le32(lpfc_cqe_valid,
9217 	       (struct lpfc_cqe *)lpfc_sli4_qe(mcq, idx)) == qe_valid) {
9218 		mcqe = (struct lpfc_mcqe *)(lpfc_sli4_qe(mcq, idx));
9219 		if (bf_get_le32(lpfc_trailer_completed, mcqe) &&
9220 		    (!bf_get_le32(lpfc_trailer_async, mcqe))) {
9221 			pending_completions = true;
9222 			break;
9223 		}
9224 		idx = (idx + 1) % mcq->entry_count;
9225 		if (mcq->hba_index == idx)
9226 			break;
9227 
9228 		/* if the index wrapped around, toggle the valid bit */
9229 		if (phba->sli4_hba.pc_sli4_params.cqav && !idx)
9230 			qe_valid = (qe_valid) ? 0 : 1;
9231 	}
9232 	return pending_completions;
9233 
9234 }
9235 
9236 /**
9237  * lpfc_sli4_process_missed_mbox_completions - process mbox completions
9238  *					      that were missed.
9239  * @phba: Pointer to HBA context object.
9240  *
9241  * For sli4, it is possible to miss an interrupt. As such mbox completions
9242  * maybe missed causing erroneous mailbox timeouts to occur. This function
9243  * checks to see if mbox completions are on the mailbox completion queue
9244  * and will process all the completions associated with the eq for the
9245  * mailbox completion queue.
9246  **/
9247 static bool
9248 lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba)
9249 {
9250 	struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
9251 	uint32_t eqidx;
9252 	struct lpfc_queue *fpeq = NULL;
9253 	struct lpfc_queue *eq;
9254 	bool mbox_pending;
9255 
9256 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
9257 		return false;
9258 
9259 	/* Find the EQ associated with the mbox CQ */
9260 	if (sli4_hba->hdwq) {
9261 		for (eqidx = 0; eqidx < phba->cfg_irq_chann; eqidx++) {
9262 			eq = phba->sli4_hba.hba_eq_hdl[eqidx].eq;
9263 			if (eq && eq->queue_id == sli4_hba->mbx_cq->assoc_qid) {
9264 				fpeq = eq;
9265 				break;
9266 			}
9267 		}
9268 	}
9269 	if (!fpeq)
9270 		return false;
9271 
9272 	/* Turn off interrupts from this EQ */
9273 
9274 	sli4_hba->sli4_eq_clr_intr(fpeq);
9275 
9276 	/* Check to see if a mbox completion is pending */
9277 
9278 	mbox_pending = lpfc_sli4_mbox_completions_pending(phba);
9279 
9280 	/*
9281 	 * If a mbox completion is pending, process all the events on EQ
9282 	 * associated with the mbox completion queue (this could include
9283 	 * mailbox commands, async events, els commands, receive queue data
9284 	 * and fcp commands)
9285 	 */
9286 
9287 	if (mbox_pending)
9288 		/* process and rearm the EQ */
9289 		lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM,
9290 				     LPFC_QUEUE_WORK);
9291 	else
9292 		/* Always clear and re-arm the EQ */
9293 		sli4_hba->sli4_write_eq_db(phba, fpeq, 0, LPFC_QUEUE_REARM);
9294 
9295 	return mbox_pending;
9296 
9297 }
9298 
9299 /**
9300  * lpfc_mbox_timeout_handler - Worker thread function to handle mailbox timeout
9301  * @phba: Pointer to HBA context object.
9302  *
9303  * This function is called from worker thread when a mailbox command times out.
9304  * The caller is not required to hold any locks. This function will reset the
9305  * HBA and recover all the pending commands.
9306  **/
9307 void
9308 lpfc_mbox_timeout_handler(struct lpfc_hba *phba)
9309 {
9310 	LPFC_MBOXQ_t *pmbox = phba->sli.mbox_active;
9311 	MAILBOX_t *mb = NULL;
9312 
9313 	struct lpfc_sli *psli = &phba->sli;
9314 
9315 	/* If the mailbox completed, process the completion */
9316 	lpfc_sli4_process_missed_mbox_completions(phba);
9317 
9318 	if (!(psli->sli_flag & LPFC_SLI_ACTIVE))
9319 		return;
9320 
9321 	if (pmbox != NULL)
9322 		mb = &pmbox->u.mb;
9323 	/* Check the pmbox pointer first.  There is a race condition
9324 	 * between the mbox timeout handler getting executed in the
9325 	 * worklist and the mailbox actually completing. When this
9326 	 * race condition occurs, the mbox_active will be NULL.
9327 	 */
9328 	spin_lock_irq(&phba->hbalock);
9329 	if (pmbox == NULL) {
9330 		lpfc_printf_log(phba, KERN_WARNING,
9331 				LOG_MBOX | LOG_SLI,
9332 				"0353 Active Mailbox cleared - mailbox timeout "
9333 				"exiting\n");
9334 		spin_unlock_irq(&phba->hbalock);
9335 		return;
9336 	}
9337 
9338 	/* Mbox cmd <mbxCommand> timeout */
9339 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9340 			"0310 Mailbox command x%x timeout Data: x%x x%x x%px\n",
9341 			mb->mbxCommand,
9342 			phba->pport->port_state,
9343 			phba->sli.sli_flag,
9344 			phba->sli.mbox_active);
9345 	spin_unlock_irq(&phba->hbalock);
9346 
9347 	/* Setting state unknown so lpfc_sli_abort_iocb_ring
9348 	 * would get IOCB_ERROR from lpfc_sli_issue_iocb, allowing
9349 	 * it to fail all outstanding SCSI IO.
9350 	 */
9351 	set_bit(MBX_TMO_ERR, &phba->bit_flags);
9352 	spin_lock_irq(&phba->pport->work_port_lock);
9353 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
9354 	spin_unlock_irq(&phba->pport->work_port_lock);
9355 	spin_lock_irq(&phba->hbalock);
9356 	phba->link_state = LPFC_LINK_UNKNOWN;
9357 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
9358 	spin_unlock_irq(&phba->hbalock);
9359 
9360 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9361 			"0345 Resetting board due to mailbox timeout\n");
9362 
9363 	/* Reset the HBA device */
9364 	lpfc_reset_hba(phba);
9365 }
9366 
9367 /**
9368  * lpfc_sli_issue_mbox_s3 - Issue an SLI3 mailbox command to firmware
9369  * @phba: Pointer to HBA context object.
9370  * @pmbox: Pointer to mailbox object.
9371  * @flag: Flag indicating how the mailbox need to be processed.
9372  *
9373  * This function is called by discovery code and HBA management code
9374  * to submit a mailbox command to firmware with SLI-3 interface spec. This
9375  * function gets the hbalock to protect the data structures.
9376  * The mailbox command can be submitted in polling mode, in which case
9377  * this function will wait in a polling loop for the completion of the
9378  * mailbox.
9379  * If the mailbox is submitted in no_wait mode (not polling) the
9380  * function will submit the command and returns immediately without waiting
9381  * for the mailbox completion. The no_wait is supported only when HBA
9382  * is in SLI2/SLI3 mode - interrupts are enabled.
9383  * The SLI interface allows only one mailbox pending at a time. If the
9384  * mailbox is issued in polling mode and there is already a mailbox
9385  * pending, then the function will return an error. If the mailbox is issued
9386  * in NO_WAIT mode and there is a mailbox pending already, the function
9387  * will return MBX_BUSY after queuing the mailbox into mailbox queue.
9388  * The sli layer owns the mailbox object until the completion of mailbox
9389  * command if this function return MBX_BUSY or MBX_SUCCESS. For all other
9390  * return codes the caller owns the mailbox command after the return of
9391  * the function.
9392  **/
9393 static int
9394 lpfc_sli_issue_mbox_s3(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox,
9395 		       uint32_t flag)
9396 {
9397 	MAILBOX_t *mbx;
9398 	struct lpfc_sli *psli = &phba->sli;
9399 	uint32_t status, evtctr;
9400 	uint32_t ha_copy, hc_copy;
9401 	int i;
9402 	unsigned long timeout;
9403 	unsigned long drvr_flag = 0;
9404 	uint32_t word0, ldata;
9405 	void __iomem *to_slim;
9406 	int processing_queue = 0;
9407 
9408 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
9409 	if (!pmbox) {
9410 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9411 		/* processing mbox queue from intr_handler */
9412 		if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
9413 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9414 			return MBX_SUCCESS;
9415 		}
9416 		processing_queue = 1;
9417 		pmbox = lpfc_mbox_get(phba);
9418 		if (!pmbox) {
9419 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9420 			return MBX_SUCCESS;
9421 		}
9422 	}
9423 
9424 	if (pmbox->mbox_cmpl && pmbox->mbox_cmpl != lpfc_sli_def_mbox_cmpl &&
9425 		pmbox->mbox_cmpl != lpfc_sli_wake_mbox_wait) {
9426 		if(!pmbox->vport) {
9427 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9428 			lpfc_printf_log(phba, KERN_ERR,
9429 					LOG_MBOX | LOG_VPORT,
9430 					"1806 Mbox x%x failed. No vport\n",
9431 					pmbox->u.mb.mbxCommand);
9432 			dump_stack();
9433 			goto out_not_finished;
9434 		}
9435 	}
9436 
9437 	/* If the PCI channel is in offline state, do not post mbox. */
9438 	if (unlikely(pci_channel_offline(phba->pcidev))) {
9439 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9440 		goto out_not_finished;
9441 	}
9442 
9443 	/* If HBA has a deferred error attention, fail the iocb. */
9444 	if (unlikely(test_bit(DEFER_ERATT, &phba->hba_flag))) {
9445 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9446 		goto out_not_finished;
9447 	}
9448 
9449 	psli = &phba->sli;
9450 
9451 	mbx = &pmbox->u.mb;
9452 	status = MBX_SUCCESS;
9453 
9454 	if (phba->link_state == LPFC_HBA_ERROR) {
9455 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9456 
9457 		/* Mbox command <mbxCommand> cannot issue */
9458 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9459 				"(%d):0311 Mailbox command x%x cannot "
9460 				"issue Data: x%x x%x\n",
9461 				pmbox->vport ? pmbox->vport->vpi : 0,
9462 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
9463 		goto out_not_finished;
9464 	}
9465 
9466 	if (mbx->mbxCommand != MBX_KILL_BOARD && flag & MBX_NOWAIT) {
9467 		if (lpfc_readl(phba->HCregaddr, &hc_copy) ||
9468 			!(hc_copy & HC_MBINT_ENA)) {
9469 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9470 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9471 				"(%d):2528 Mailbox command x%x cannot "
9472 				"issue Data: x%x x%x\n",
9473 				pmbox->vport ? pmbox->vport->vpi : 0,
9474 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
9475 			goto out_not_finished;
9476 		}
9477 	}
9478 
9479 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
9480 		/* Polling for a mbox command when another one is already active
9481 		 * is not allowed in SLI. Also, the driver must have established
9482 		 * SLI2 mode to queue and process multiple mbox commands.
9483 		 */
9484 
9485 		if (flag & MBX_POLL) {
9486 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9487 
9488 			/* Mbox command <mbxCommand> cannot issue */
9489 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9490 					"(%d):2529 Mailbox command x%x "
9491 					"cannot issue Data: x%x x%x\n",
9492 					pmbox->vport ? pmbox->vport->vpi : 0,
9493 					pmbox->u.mb.mbxCommand,
9494 					psli->sli_flag, flag);
9495 			goto out_not_finished;
9496 		}
9497 
9498 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE)) {
9499 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9500 			/* Mbox command <mbxCommand> cannot issue */
9501 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9502 					"(%d):2530 Mailbox command x%x "
9503 					"cannot issue Data: x%x x%x\n",
9504 					pmbox->vport ? pmbox->vport->vpi : 0,
9505 					pmbox->u.mb.mbxCommand,
9506 					psli->sli_flag, flag);
9507 			goto out_not_finished;
9508 		}
9509 
9510 		/* Another mailbox command is still being processed, queue this
9511 		 * command to be processed later.
9512 		 */
9513 		lpfc_mbox_put(phba, pmbox);
9514 
9515 		/* Mbox cmd issue - BUSY */
9516 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9517 				"(%d):0308 Mbox cmd issue - BUSY Data: "
9518 				"x%x x%x x%x x%x\n",
9519 				pmbox->vport ? pmbox->vport->vpi : 0xffffff,
9520 				mbx->mbxCommand,
9521 				phba->pport ? phba->pport->port_state : 0xff,
9522 				psli->sli_flag, flag);
9523 
9524 		psli->slistat.mbox_busy++;
9525 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9526 
9527 		if (pmbox->vport) {
9528 			lpfc_debugfs_disc_trc(pmbox->vport,
9529 				LPFC_DISC_TRC_MBOX_VPORT,
9530 				"MBOX Bsy vport:  cmd:x%x mb:x%x x%x",
9531 				(uint32_t)mbx->mbxCommand,
9532 				mbx->un.varWords[0], mbx->un.varWords[1]);
9533 		}
9534 		else {
9535 			lpfc_debugfs_disc_trc(phba->pport,
9536 				LPFC_DISC_TRC_MBOX,
9537 				"MBOX Bsy:        cmd:x%x mb:x%x x%x",
9538 				(uint32_t)mbx->mbxCommand,
9539 				mbx->un.varWords[0], mbx->un.varWords[1]);
9540 		}
9541 
9542 		return MBX_BUSY;
9543 	}
9544 
9545 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
9546 
9547 	/* If we are not polling, we MUST be in SLI2 mode */
9548 	if (flag != MBX_POLL) {
9549 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE) &&
9550 		    (mbx->mbxCommand != MBX_KILL_BOARD)) {
9551 			psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9552 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9553 			/* Mbox command <mbxCommand> cannot issue */
9554 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9555 					"(%d):2531 Mailbox command x%x "
9556 					"cannot issue Data: x%x x%x\n",
9557 					pmbox->vport ? pmbox->vport->vpi : 0,
9558 					pmbox->u.mb.mbxCommand,
9559 					psli->sli_flag, flag);
9560 			goto out_not_finished;
9561 		}
9562 		/* timeout active mbox command */
9563 		timeout = secs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox));
9564 		mod_timer(&psli->mbox_tmo, jiffies + timeout);
9565 	}
9566 
9567 	/* Mailbox cmd <cmd> issue */
9568 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9569 			"(%d):0309 Mailbox cmd x%x issue Data: x%x x%x "
9570 			"x%x\n",
9571 			pmbox->vport ? pmbox->vport->vpi : 0,
9572 			mbx->mbxCommand,
9573 			phba->pport ? phba->pport->port_state : 0xff,
9574 			psli->sli_flag, flag);
9575 
9576 	if (mbx->mbxCommand != MBX_HEARTBEAT) {
9577 		if (pmbox->vport) {
9578 			lpfc_debugfs_disc_trc(pmbox->vport,
9579 				LPFC_DISC_TRC_MBOX_VPORT,
9580 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
9581 				(uint32_t)mbx->mbxCommand,
9582 				mbx->un.varWords[0], mbx->un.varWords[1]);
9583 		}
9584 		else {
9585 			lpfc_debugfs_disc_trc(phba->pport,
9586 				LPFC_DISC_TRC_MBOX,
9587 				"MBOX Send:       cmd:x%x mb:x%x x%x",
9588 				(uint32_t)mbx->mbxCommand,
9589 				mbx->un.varWords[0], mbx->un.varWords[1]);
9590 		}
9591 	}
9592 
9593 	psli->slistat.mbox_cmd++;
9594 	evtctr = psli->slistat.mbox_event;
9595 
9596 	/* next set own bit for the adapter and copy over command word */
9597 	mbx->mbxOwner = OWN_CHIP;
9598 
9599 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9600 		/* Populate mbox extension offset word. */
9601 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len) {
9602 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
9603 				= (uint8_t *)phba->mbox_ext
9604 				  - (uint8_t *)phba->mbox;
9605 		}
9606 
9607 		/* Copy the mailbox extension data */
9608 		if (pmbox->in_ext_byte_len && pmbox->ext_buf) {
9609 			lpfc_sli_pcimem_bcopy(pmbox->ext_buf,
9610 					      (uint8_t *)phba->mbox_ext,
9611 					      pmbox->in_ext_byte_len);
9612 		}
9613 		/* Copy command data to host SLIM area */
9614 		lpfc_sli_pcimem_bcopy(mbx, phba->mbox, MAILBOX_CMD_SIZE);
9615 	} else {
9616 		/* Populate mbox extension offset word. */
9617 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len)
9618 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
9619 				= MAILBOX_HBA_EXT_OFFSET;
9620 
9621 		/* Copy the mailbox extension data */
9622 		if (pmbox->in_ext_byte_len && pmbox->ext_buf)
9623 			lpfc_memcpy_to_slim(phba->MBslimaddr +
9624 				MAILBOX_HBA_EXT_OFFSET,
9625 				pmbox->ext_buf, pmbox->in_ext_byte_len);
9626 
9627 		if (mbx->mbxCommand == MBX_CONFIG_PORT)
9628 			/* copy command data into host mbox for cmpl */
9629 			lpfc_sli_pcimem_bcopy(mbx, phba->mbox,
9630 					      MAILBOX_CMD_SIZE);
9631 
9632 		/* First copy mbox command data to HBA SLIM, skip past first
9633 		   word */
9634 		to_slim = phba->MBslimaddr + sizeof (uint32_t);
9635 		lpfc_memcpy_to_slim(to_slim, &mbx->un.varWords[0],
9636 			    MAILBOX_CMD_SIZE - sizeof (uint32_t));
9637 
9638 		/* Next copy over first word, with mbxOwner set */
9639 		ldata = *((uint32_t *)mbx);
9640 		to_slim = phba->MBslimaddr;
9641 		writel(ldata, to_slim);
9642 		readl(to_slim); /* flush */
9643 
9644 		if (mbx->mbxCommand == MBX_CONFIG_PORT)
9645 			/* switch over to host mailbox */
9646 			psli->sli_flag |= LPFC_SLI_ACTIVE;
9647 	}
9648 
9649 	wmb();
9650 
9651 	switch (flag) {
9652 	case MBX_NOWAIT:
9653 		/* Set up reference to mailbox command */
9654 		psli->mbox_active = pmbox;
9655 		/* Interrupt board to do it */
9656 		writel(CA_MBATT, phba->CAregaddr);
9657 		readl(phba->CAregaddr); /* flush */
9658 		/* Don't wait for it to finish, just return */
9659 		break;
9660 
9661 	case MBX_POLL:
9662 		/* Set up null reference to mailbox command */
9663 		psli->mbox_active = NULL;
9664 		/* Interrupt board to do it */
9665 		writel(CA_MBATT, phba->CAregaddr);
9666 		readl(phba->CAregaddr); /* flush */
9667 
9668 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9669 			/* First read mbox status word */
9670 			word0 = *((uint32_t *)phba->mbox);
9671 			word0 = le32_to_cpu(word0);
9672 		} else {
9673 			/* First read mbox status word */
9674 			if (lpfc_readl(phba->MBslimaddr, &word0)) {
9675 				spin_unlock_irqrestore(&phba->hbalock,
9676 						       drvr_flag);
9677 				goto out_not_finished;
9678 			}
9679 		}
9680 
9681 		/* Read the HBA Host Attention Register */
9682 		if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
9683 			spin_unlock_irqrestore(&phba->hbalock,
9684 						       drvr_flag);
9685 			goto out_not_finished;
9686 		}
9687 		timeout = secs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox)) + jiffies;
9688 		i = 0;
9689 		/* Wait for command to complete */
9690 		while (((word0 & OWN_CHIP) == OWN_CHIP) ||
9691 		       (!(ha_copy & HA_MBATT) &&
9692 			(phba->link_state > LPFC_WARM_START))) {
9693 			if (time_after(jiffies, timeout)) {
9694 				psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9695 				spin_unlock_irqrestore(&phba->hbalock,
9696 						       drvr_flag);
9697 				goto out_not_finished;
9698 			}
9699 
9700 			/* Check if we took a mbox interrupt while we were
9701 			   polling */
9702 			if (((word0 & OWN_CHIP) != OWN_CHIP)
9703 			    && (evtctr != psli->slistat.mbox_event))
9704 				break;
9705 
9706 			if (i++ > 10) {
9707 				spin_unlock_irqrestore(&phba->hbalock,
9708 						       drvr_flag);
9709 				msleep(1);
9710 				spin_lock_irqsave(&phba->hbalock, drvr_flag);
9711 			}
9712 
9713 			if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9714 				/* First copy command data */
9715 				word0 = *((uint32_t *)phba->mbox);
9716 				word0 = le32_to_cpu(word0);
9717 				if (mbx->mbxCommand == MBX_CONFIG_PORT) {
9718 					MAILBOX_t *slimmb;
9719 					uint32_t slimword0;
9720 					/* Check real SLIM for any errors */
9721 					slimword0 = readl(phba->MBslimaddr);
9722 					slimmb = (MAILBOX_t *) & slimword0;
9723 					if (((slimword0 & OWN_CHIP) != OWN_CHIP)
9724 					    && slimmb->mbxStatus) {
9725 						psli->sli_flag &=
9726 						    ~LPFC_SLI_ACTIVE;
9727 						word0 = slimword0;
9728 					}
9729 				}
9730 			} else {
9731 				/* First copy command data */
9732 				word0 = readl(phba->MBslimaddr);
9733 			}
9734 			/* Read the HBA Host Attention Register */
9735 			if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
9736 				spin_unlock_irqrestore(&phba->hbalock,
9737 						       drvr_flag);
9738 				goto out_not_finished;
9739 			}
9740 		}
9741 
9742 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9743 			/* copy results back to user */
9744 			lpfc_sli_pcimem_bcopy(phba->mbox, mbx,
9745 						MAILBOX_CMD_SIZE);
9746 			/* Copy the mailbox extension data */
9747 			if (pmbox->out_ext_byte_len && pmbox->ext_buf) {
9748 				lpfc_sli_pcimem_bcopy(phba->mbox_ext,
9749 						      pmbox->ext_buf,
9750 						      pmbox->out_ext_byte_len);
9751 			}
9752 		} else {
9753 			/* First copy command data */
9754 			lpfc_memcpy_from_slim(mbx, phba->MBslimaddr,
9755 						MAILBOX_CMD_SIZE);
9756 			/* Copy the mailbox extension data */
9757 			if (pmbox->out_ext_byte_len && pmbox->ext_buf) {
9758 				lpfc_memcpy_from_slim(
9759 					pmbox->ext_buf,
9760 					phba->MBslimaddr +
9761 					MAILBOX_HBA_EXT_OFFSET,
9762 					pmbox->out_ext_byte_len);
9763 			}
9764 		}
9765 
9766 		writel(HA_MBATT, phba->HAregaddr);
9767 		readl(phba->HAregaddr); /* flush */
9768 
9769 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9770 		status = mbx->mbxStatus;
9771 	}
9772 
9773 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9774 	return status;
9775 
9776 out_not_finished:
9777 	if (processing_queue) {
9778 		pmbox->u.mb.mbxStatus = MBX_NOT_FINISHED;
9779 		lpfc_mbox_cmpl_put(phba, pmbox);
9780 	}
9781 	return MBX_NOT_FINISHED;
9782 }
9783 
9784 /**
9785  * lpfc_sli4_async_mbox_block - Block posting SLI4 asynchronous mailbox command
9786  * @phba: Pointer to HBA context object.
9787  *
9788  * The function blocks the posting of SLI4 asynchronous mailbox commands from
9789  * the driver internal pending mailbox queue. It will then try to wait out the
9790  * possible outstanding mailbox command before return.
9791  *
9792  * Returns:
9793  * 	0 - the outstanding mailbox command completed; otherwise, the wait for
9794  * 	the outstanding mailbox command timed out.
9795  **/
9796 static int
9797 lpfc_sli4_async_mbox_block(struct lpfc_hba *phba)
9798 {
9799 	struct lpfc_sli *psli = &phba->sli;
9800 	LPFC_MBOXQ_t *mboxq;
9801 	int rc = 0;
9802 	unsigned long timeout = 0;
9803 	u32 sli_flag;
9804 	u8 cmd, subsys, opcode;
9805 
9806 	/* Mark the asynchronous mailbox command posting as blocked */
9807 	spin_lock_irq(&phba->hbalock);
9808 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
9809 	/* Determine how long we might wait for the active mailbox
9810 	 * command to be gracefully completed by firmware.
9811 	 */
9812 	if (phba->sli.mbox_active)
9813 		timeout = secs_to_jiffies(lpfc_mbox_tmo_val(phba,
9814 						phba->sli.mbox_active)) + jiffies;
9815 	spin_unlock_irq(&phba->hbalock);
9816 
9817 	/* Make sure the mailbox is really active */
9818 	if (timeout)
9819 		lpfc_sli4_process_missed_mbox_completions(phba);
9820 
9821 	/* Wait for the outstanding mailbox command to complete */
9822 	while (phba->sli.mbox_active) {
9823 		/* Check active mailbox complete status every 2ms */
9824 		msleep(2);
9825 		if (time_after(jiffies, timeout)) {
9826 			/* Timeout, mark the outstanding cmd not complete */
9827 
9828 			/* Sanity check sli.mbox_active has not completed or
9829 			 * cancelled from another context during last 2ms sleep,
9830 			 * so take hbalock to be sure before logging.
9831 			 */
9832 			spin_lock_irq(&phba->hbalock);
9833 			if (phba->sli.mbox_active) {
9834 				mboxq = phba->sli.mbox_active;
9835 				cmd = mboxq->u.mb.mbxCommand;
9836 				subsys = lpfc_sli_config_mbox_subsys_get(phba,
9837 									 mboxq);
9838 				opcode = lpfc_sli_config_mbox_opcode_get(phba,
9839 									 mboxq);
9840 				sli_flag = psli->sli_flag;
9841 				spin_unlock_irq(&phba->hbalock);
9842 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9843 						"2352 Mailbox command x%x "
9844 						"(x%x/x%x) sli_flag x%x could "
9845 						"not complete\n",
9846 						cmd, subsys, opcode,
9847 						sli_flag);
9848 			} else {
9849 				spin_unlock_irq(&phba->hbalock);
9850 			}
9851 
9852 			rc = 1;
9853 			break;
9854 		}
9855 	}
9856 
9857 	/* Can not cleanly block async mailbox command, fails it */
9858 	if (rc) {
9859 		spin_lock_irq(&phba->hbalock);
9860 		psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
9861 		spin_unlock_irq(&phba->hbalock);
9862 	}
9863 	return rc;
9864 }
9865 
9866 /**
9867  * lpfc_sli4_async_mbox_unblock - Block posting SLI4 async mailbox command
9868  * @phba: Pointer to HBA context object.
9869  *
9870  * The function unblocks and resume posting of SLI4 asynchronous mailbox
9871  * commands from the driver internal pending mailbox queue. It makes sure
9872  * that there is no outstanding mailbox command before resuming posting
9873  * asynchronous mailbox commands. If, for any reason, there is outstanding
9874  * mailbox command, it will try to wait it out before resuming asynchronous
9875  * mailbox command posting.
9876  **/
9877 static void
9878 lpfc_sli4_async_mbox_unblock(struct lpfc_hba *phba)
9879 {
9880 	struct lpfc_sli *psli = &phba->sli;
9881 
9882 	spin_lock_irq(&phba->hbalock);
9883 	if (!(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
9884 		/* Asynchronous mailbox posting is not blocked, do nothing */
9885 		spin_unlock_irq(&phba->hbalock);
9886 		return;
9887 	}
9888 
9889 	/* Outstanding synchronous mailbox command is guaranteed to be done,
9890 	 * successful or timeout, after timing-out the outstanding mailbox
9891 	 * command shall always be removed, so just unblock posting async
9892 	 * mailbox command and resume
9893 	 */
9894 	psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
9895 	spin_unlock_irq(&phba->hbalock);
9896 
9897 	/* wake up worker thread to post asynchronous mailbox command */
9898 	lpfc_worker_wake_up(phba);
9899 }
9900 
9901 /**
9902  * lpfc_sli4_wait_bmbx_ready - Wait for bootstrap mailbox register ready
9903  * @phba: Pointer to HBA context object.
9904  * @mboxq: Pointer to mailbox object.
9905  *
9906  * The function waits for the bootstrap mailbox register ready bit from
9907  * port for twice the regular mailbox command timeout value.
9908  *
9909  *      0 - no timeout on waiting for bootstrap mailbox register ready.
9910  *      MBXERR_ERROR - wait for bootstrap mailbox register timed out or port
9911  *                     is in an unrecoverable state.
9912  **/
9913 static int
9914 lpfc_sli4_wait_bmbx_ready(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
9915 {
9916 	uint32_t db_ready;
9917 	unsigned long timeout;
9918 	struct lpfc_register bmbx_reg;
9919 	struct lpfc_register portstat_reg = {-1};
9920 
9921 	/* Sanity check - there is no point to wait if the port is in an
9922 	 * unrecoverable state.
9923 	 */
9924 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) >=
9925 	    LPFC_SLI_INTF_IF_TYPE_2) {
9926 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
9927 			       &portstat_reg.word0) ||
9928 		    lpfc_sli4_unrecoverable_port(&portstat_reg)) {
9929 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9930 					"3858 Skipping bmbx ready because "
9931 					"Port Status x%x\n",
9932 					portstat_reg.word0);
9933 			return MBXERR_ERROR;
9934 		}
9935 	}
9936 
9937 	timeout = secs_to_jiffies(lpfc_mbox_tmo_val(phba, mboxq)) + jiffies;
9938 
9939 	do {
9940 		bmbx_reg.word0 = readl(phba->sli4_hba.BMBXregaddr);
9941 		db_ready = bf_get(lpfc_bmbx_rdy, &bmbx_reg);
9942 		if (!db_ready)
9943 			mdelay(2);
9944 
9945 		if (time_after(jiffies, timeout))
9946 			return MBXERR_ERROR;
9947 	} while (!db_ready);
9948 
9949 	return 0;
9950 }
9951 
9952 /**
9953  * lpfc_sli4_post_sync_mbox - Post an SLI4 mailbox to the bootstrap mailbox
9954  * @phba: Pointer to HBA context object.
9955  * @mboxq: Pointer to mailbox object.
9956  *
9957  * The function posts a mailbox to the port.  The mailbox is expected
9958  * to be comletely filled in and ready for the port to operate on it.
9959  * This routine executes a synchronous completion operation on the
9960  * mailbox by polling for its completion.
9961  *
9962  * The caller must not be holding any locks when calling this routine.
9963  *
9964  * Returns:
9965  *	MBX_SUCCESS - mailbox posted successfully
9966  *	Any of the MBX error values.
9967  **/
9968 static int
9969 lpfc_sli4_post_sync_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
9970 {
9971 	int rc = MBX_SUCCESS;
9972 	unsigned long iflag;
9973 	uint32_t mcqe_status;
9974 	uint32_t mbx_cmnd;
9975 	struct lpfc_sli *psli = &phba->sli;
9976 	struct lpfc_mqe *mb = &mboxq->u.mqe;
9977 	struct lpfc_bmbx_create *mbox_rgn;
9978 	struct dma_address *dma_address;
9979 
9980 	/*
9981 	 * Only one mailbox can be active to the bootstrap mailbox region
9982 	 * at a time and there is no queueing provided.
9983 	 */
9984 	spin_lock_irqsave(&phba->hbalock, iflag);
9985 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
9986 		spin_unlock_irqrestore(&phba->hbalock, iflag);
9987 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9988 				"(%d):2532 Mailbox command x%x (x%x/x%x) "
9989 				"cannot issue Data: x%x x%x\n",
9990 				mboxq->vport ? mboxq->vport->vpi : 0,
9991 				mboxq->u.mb.mbxCommand,
9992 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9993 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9994 				psli->sli_flag, MBX_POLL);
9995 		return MBXERR_ERROR;
9996 	}
9997 	/* The server grabs the token and owns it until release */
9998 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
9999 	phba->sli.mbox_active = mboxq;
10000 	spin_unlock_irqrestore(&phba->hbalock, iflag);
10001 
10002 	/* wait for bootstrap mbox register for readiness */
10003 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
10004 	if (rc)
10005 		goto exit;
10006 	/*
10007 	 * Initialize the bootstrap memory region to avoid stale data areas
10008 	 * in the mailbox post.  Then copy the caller's mailbox contents to
10009 	 * the bmbx mailbox region.
10010 	 */
10011 	mbx_cmnd = bf_get(lpfc_mqe_command, mb);
10012 	memset(phba->sli4_hba.bmbx.avirt, 0, sizeof(struct lpfc_bmbx_create));
10013 	lpfc_sli4_pcimem_bcopy(mb, phba->sli4_hba.bmbx.avirt,
10014 			       sizeof(struct lpfc_mqe));
10015 
10016 	/* Post the high mailbox dma address to the port and wait for ready. */
10017 	dma_address = &phba->sli4_hba.bmbx.dma_address;
10018 	writel(dma_address->addr_hi, phba->sli4_hba.BMBXregaddr);
10019 
10020 	/* wait for bootstrap mbox register for hi-address write done */
10021 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
10022 	if (rc)
10023 		goto exit;
10024 
10025 	/* Post the low mailbox dma address to the port. */
10026 	writel(dma_address->addr_lo, phba->sli4_hba.BMBXregaddr);
10027 
10028 	/* wait for bootstrap mbox register for low address write done */
10029 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
10030 	if (rc)
10031 		goto exit;
10032 
10033 	/*
10034 	 * Read the CQ to ensure the mailbox has completed.
10035 	 * If so, update the mailbox status so that the upper layers
10036 	 * can complete the request normally.
10037 	 */
10038 	lpfc_sli4_pcimem_bcopy(phba->sli4_hba.bmbx.avirt, mb,
10039 			       sizeof(struct lpfc_mqe));
10040 	mbox_rgn = (struct lpfc_bmbx_create *) phba->sli4_hba.bmbx.avirt;
10041 	lpfc_sli4_pcimem_bcopy(&mbox_rgn->mcqe, &mboxq->mcqe,
10042 			       sizeof(struct lpfc_mcqe));
10043 	mcqe_status = bf_get(lpfc_mcqe_status, &mbox_rgn->mcqe);
10044 	/*
10045 	 * When the CQE status indicates a failure and the mailbox status
10046 	 * indicates success then copy the CQE status into the mailbox status
10047 	 * (and prefix it with x4000).
10048 	 */
10049 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
10050 		if (bf_get(lpfc_mqe_status, mb) == MBX_SUCCESS)
10051 			bf_set(lpfc_mqe_status, mb,
10052 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
10053 		rc = MBXERR_ERROR;
10054 	} else
10055 		lpfc_sli4_swap_str(phba, mboxq);
10056 
10057 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
10058 			"(%d):0356 Mailbox cmd x%x (x%x/x%x) Status x%x "
10059 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x"
10060 			" x%x x%x CQ: x%x x%x x%x x%x\n",
10061 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
10062 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10063 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10064 			bf_get(lpfc_mqe_status, mb),
10065 			mb->un.mb_words[0], mb->un.mb_words[1],
10066 			mb->un.mb_words[2], mb->un.mb_words[3],
10067 			mb->un.mb_words[4], mb->un.mb_words[5],
10068 			mb->un.mb_words[6], mb->un.mb_words[7],
10069 			mb->un.mb_words[8], mb->un.mb_words[9],
10070 			mb->un.mb_words[10], mb->un.mb_words[11],
10071 			mb->un.mb_words[12], mboxq->mcqe.word0,
10072 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
10073 			mboxq->mcqe.trailer);
10074 exit:
10075 	/* We are holding the token, no needed for lock when release */
10076 	spin_lock_irqsave(&phba->hbalock, iflag);
10077 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
10078 	phba->sli.mbox_active = NULL;
10079 	spin_unlock_irqrestore(&phba->hbalock, iflag);
10080 	return rc;
10081 }
10082 
10083 /**
10084  * lpfc_sli_issue_mbox_s4 - Issue an SLI4 mailbox command to firmware
10085  * @phba: Pointer to HBA context object.
10086  * @mboxq: Pointer to mailbox object.
10087  * @flag: Flag indicating how the mailbox need to be processed.
10088  *
10089  * This function is called by discovery code and HBA management code to submit
10090  * a mailbox command to firmware with SLI-4 interface spec.
10091  *
10092  * Return codes the caller owns the mailbox command after the return of the
10093  * function.
10094  **/
10095 static int
10096 lpfc_sli_issue_mbox_s4(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
10097 		       uint32_t flag)
10098 {
10099 	struct lpfc_sli *psli = &phba->sli;
10100 	unsigned long iflags;
10101 	int rc;
10102 
10103 	/* dump from issue mailbox command if setup */
10104 	lpfc_idiag_mbxacc_dump_issue_mbox(phba, &mboxq->u.mb);
10105 
10106 	rc = lpfc_mbox_dev_check(phba);
10107 	if (unlikely(rc)) {
10108 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10109 				"(%d):2544 Mailbox command x%x (x%x/x%x) "
10110 				"cannot issue Data: x%x x%x\n",
10111 				mboxq->vport ? mboxq->vport->vpi : 0,
10112 				mboxq->u.mb.mbxCommand,
10113 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10114 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10115 				psli->sli_flag, flag);
10116 		goto out_not_finished;
10117 	}
10118 
10119 	/* Detect polling mode and jump to a handler */
10120 	if (!phba->sli4_hba.intr_enable) {
10121 		if (flag == MBX_POLL)
10122 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
10123 		else
10124 			rc = -EIO;
10125 		if (rc != MBX_SUCCESS)
10126 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
10127 					"(%d):2541 Mailbox command x%x "
10128 					"(x%x/x%x) failure: "
10129 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
10130 					"Data: x%x x%x\n",
10131 					mboxq->vport ? mboxq->vport->vpi : 0,
10132 					mboxq->u.mb.mbxCommand,
10133 					lpfc_sli_config_mbox_subsys_get(phba,
10134 									mboxq),
10135 					lpfc_sli_config_mbox_opcode_get(phba,
10136 									mboxq),
10137 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
10138 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
10139 					bf_get(lpfc_mcqe_ext_status,
10140 					       &mboxq->mcqe),
10141 					psli->sli_flag, flag);
10142 		return rc;
10143 	} else if (flag == MBX_POLL) {
10144 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
10145 				"(%d):2542 Try to issue mailbox command "
10146 				"x%x (x%x/x%x) synchronously ahead of async "
10147 				"mailbox command queue: x%x x%x\n",
10148 				mboxq->vport ? mboxq->vport->vpi : 0,
10149 				mboxq->u.mb.mbxCommand,
10150 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10151 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10152 				psli->sli_flag, flag);
10153 		/* Try to block the asynchronous mailbox posting */
10154 		rc = lpfc_sli4_async_mbox_block(phba);
10155 		if (!rc) {
10156 			/* Successfully blocked, now issue sync mbox cmd */
10157 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
10158 			if (rc != MBX_SUCCESS)
10159 				lpfc_printf_log(phba, KERN_WARNING,
10160 					LOG_MBOX | LOG_SLI,
10161 					"(%d):2597 Sync Mailbox command "
10162 					"x%x (x%x/x%x) failure: "
10163 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
10164 					"Data: x%x x%x\n",
10165 					mboxq->vport ? mboxq->vport->vpi : 0,
10166 					mboxq->u.mb.mbxCommand,
10167 					lpfc_sli_config_mbox_subsys_get(phba,
10168 									mboxq),
10169 					lpfc_sli_config_mbox_opcode_get(phba,
10170 									mboxq),
10171 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
10172 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
10173 					bf_get(lpfc_mcqe_ext_status,
10174 					       &mboxq->mcqe),
10175 					psli->sli_flag, flag);
10176 			/* Unblock the async mailbox posting afterward */
10177 			lpfc_sli4_async_mbox_unblock(phba);
10178 		}
10179 		return rc;
10180 	}
10181 
10182 	/* Now, interrupt mode asynchronous mailbox command */
10183 	rc = lpfc_mbox_cmd_check(phba, mboxq);
10184 	if (rc) {
10185 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10186 				"(%d):2543 Mailbox command x%x (x%x/x%x) "
10187 				"cannot issue Data: x%x x%x\n",
10188 				mboxq->vport ? mboxq->vport->vpi : 0,
10189 				mboxq->u.mb.mbxCommand,
10190 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10191 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10192 				psli->sli_flag, flag);
10193 		goto out_not_finished;
10194 	}
10195 
10196 	/* Put the mailbox command to the driver internal FIFO */
10197 	psli->slistat.mbox_busy++;
10198 	spin_lock_irqsave(&phba->hbalock, iflags);
10199 	lpfc_mbox_put(phba, mboxq);
10200 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10201 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
10202 			"(%d):0354 Mbox cmd issue - Enqueue Data: "
10203 			"x%x (x%x/x%x) x%x x%x x%x x%x\n",
10204 			mboxq->vport ? mboxq->vport->vpi : 0xffffff,
10205 			bf_get(lpfc_mqe_command, &mboxq->u.mqe),
10206 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10207 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10208 			mboxq->u.mb.un.varUnregLogin.rpi,
10209 			phba->pport->port_state,
10210 			psli->sli_flag, MBX_NOWAIT);
10211 	/* Wake up worker thread to transport mailbox command from head */
10212 	lpfc_worker_wake_up(phba);
10213 
10214 	return MBX_BUSY;
10215 
10216 out_not_finished:
10217 	return MBX_NOT_FINISHED;
10218 }
10219 
10220 /**
10221  * lpfc_sli4_post_async_mbox - Post an SLI4 mailbox command to device
10222  * @phba: Pointer to HBA context object.
10223  *
10224  * This function is called by worker thread to send a mailbox command to
10225  * SLI4 HBA firmware.
10226  *
10227  **/
10228 int
10229 lpfc_sli4_post_async_mbox(struct lpfc_hba *phba)
10230 {
10231 	struct lpfc_sli *psli = &phba->sli;
10232 	LPFC_MBOXQ_t *mboxq;
10233 	int rc = MBX_SUCCESS;
10234 	unsigned long iflags;
10235 	struct lpfc_mqe *mqe;
10236 	uint32_t mbx_cmnd;
10237 
10238 	/* Check interrupt mode before post async mailbox command */
10239 	if (unlikely(!phba->sli4_hba.intr_enable))
10240 		return MBX_NOT_FINISHED;
10241 
10242 	/* Check for mailbox command service token */
10243 	spin_lock_irqsave(&phba->hbalock, iflags);
10244 	if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
10245 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10246 		return MBX_NOT_FINISHED;
10247 	}
10248 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
10249 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10250 		return MBX_NOT_FINISHED;
10251 	}
10252 	if (unlikely(phba->sli.mbox_active)) {
10253 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10254 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10255 				"0384 There is pending active mailbox cmd\n");
10256 		return MBX_NOT_FINISHED;
10257 	}
10258 	/* Take the mailbox command service token */
10259 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
10260 
10261 	/* Get the next mailbox command from head of queue */
10262 	mboxq = lpfc_mbox_get(phba);
10263 
10264 	/* If no more mailbox command waiting for post, we're done */
10265 	if (!mboxq) {
10266 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
10267 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10268 		return MBX_SUCCESS;
10269 	}
10270 	phba->sli.mbox_active = mboxq;
10271 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10272 
10273 	/* Check device readiness for posting mailbox command */
10274 	rc = lpfc_mbox_dev_check(phba);
10275 	if (unlikely(rc))
10276 		/* Driver clean routine will clean up pending mailbox */
10277 		goto out_not_finished;
10278 
10279 	/* Prepare the mbox command to be posted */
10280 	mqe = &mboxq->u.mqe;
10281 	mbx_cmnd = bf_get(lpfc_mqe_command, mqe);
10282 
10283 	/* Start timer for the mbox_tmo and log some mailbox post messages */
10284 	mod_timer(&psli->mbox_tmo, (jiffies +
10285 		  secs_to_jiffies(lpfc_mbox_tmo_val(phba, mboxq))));
10286 
10287 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
10288 			"(%d):0355 Mailbox cmd x%x (x%x/x%x) issue Data: "
10289 			"x%x x%x\n",
10290 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
10291 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10292 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10293 			phba->pport->port_state, psli->sli_flag);
10294 
10295 	if (mbx_cmnd != MBX_HEARTBEAT) {
10296 		if (mboxq->vport) {
10297 			lpfc_debugfs_disc_trc(mboxq->vport,
10298 				LPFC_DISC_TRC_MBOX_VPORT,
10299 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
10300 				mbx_cmnd, mqe->un.mb_words[0],
10301 				mqe->un.mb_words[1]);
10302 		} else {
10303 			lpfc_debugfs_disc_trc(phba->pport,
10304 				LPFC_DISC_TRC_MBOX,
10305 				"MBOX Send: cmd:x%x mb:x%x x%x",
10306 				mbx_cmnd, mqe->un.mb_words[0],
10307 				mqe->un.mb_words[1]);
10308 		}
10309 	}
10310 	psli->slistat.mbox_cmd++;
10311 
10312 	/* Post the mailbox command to the port */
10313 	rc = lpfc_sli4_mq_put(phba->sli4_hba.mbx_wq, mqe);
10314 	if (rc != MBX_SUCCESS) {
10315 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10316 				"(%d):2533 Mailbox command x%x (x%x/x%x) "
10317 				"cannot issue Data: x%x x%x\n",
10318 				mboxq->vport ? mboxq->vport->vpi : 0,
10319 				mboxq->u.mb.mbxCommand,
10320 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10321 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10322 				psli->sli_flag, MBX_NOWAIT);
10323 		goto out_not_finished;
10324 	}
10325 
10326 	return rc;
10327 
10328 out_not_finished:
10329 	spin_lock_irqsave(&phba->hbalock, iflags);
10330 	if (phba->sli.mbox_active) {
10331 		mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
10332 		__lpfc_mbox_cmpl_put(phba, mboxq);
10333 		/* Release the token */
10334 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
10335 		phba->sli.mbox_active = NULL;
10336 	}
10337 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10338 
10339 	return MBX_NOT_FINISHED;
10340 }
10341 
10342 /**
10343  * lpfc_sli_issue_mbox - Wrapper func for issuing mailbox command
10344  * @phba: Pointer to HBA context object.
10345  * @pmbox: Pointer to mailbox object.
10346  * @flag: Flag indicating how the mailbox need to be processed.
10347  *
10348  * This routine wraps the actual SLI3 or SLI4 mailbox issuing routine from
10349  * the API jump table function pointer from the lpfc_hba struct.
10350  *
10351  * Return codes the caller owns the mailbox command after the return of the
10352  * function.
10353  **/
10354 int
10355 lpfc_sli_issue_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox, uint32_t flag)
10356 {
10357 	return phba->lpfc_sli_issue_mbox(phba, pmbox, flag);
10358 }
10359 
10360 /**
10361  * lpfc_mbox_api_table_setup - Set up mbox api function jump table
10362  * @phba: The hba struct for which this call is being executed.
10363  * @dev_grp: The HBA PCI-Device group number.
10364  *
10365  * This routine sets up the mbox interface API function jump table in @phba
10366  * struct.
10367  * Returns: 0 - success, -ENODEV - failure.
10368  **/
10369 int
10370 lpfc_mbox_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
10371 {
10372 
10373 	switch (dev_grp) {
10374 	case LPFC_PCI_DEV_LP:
10375 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s3;
10376 		phba->lpfc_sli_handle_slow_ring_event =
10377 				lpfc_sli_handle_slow_ring_event_s3;
10378 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s3;
10379 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s3;
10380 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s3;
10381 		break;
10382 	case LPFC_PCI_DEV_OC:
10383 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s4;
10384 		phba->lpfc_sli_handle_slow_ring_event =
10385 				lpfc_sli_handle_slow_ring_event_s4;
10386 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s4;
10387 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s4;
10388 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s4;
10389 		break;
10390 	default:
10391 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10392 				"1420 Invalid HBA PCI-device group: 0x%x\n",
10393 				dev_grp);
10394 		return -ENODEV;
10395 	}
10396 	return 0;
10397 }
10398 
10399 /**
10400  * __lpfc_sli_ringtx_put - Add an iocb to the txq
10401  * @phba: Pointer to HBA context object.
10402  * @pring: Pointer to driver SLI ring object.
10403  * @piocb: Pointer to address of newly added command iocb.
10404  *
10405  * This function is called with hbalock held for SLI3 ports or
10406  * the ring lock held for SLI4 ports to add a command
10407  * iocb to the txq when SLI layer cannot submit the command iocb
10408  * to the ring.
10409  **/
10410 void
10411 __lpfc_sli_ringtx_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
10412 		    struct lpfc_iocbq *piocb)
10413 {
10414 	if (phba->sli_rev == LPFC_SLI_REV4)
10415 		lockdep_assert_held(&pring->ring_lock);
10416 	else
10417 		lockdep_assert_held(&phba->hbalock);
10418 	/* Insert the caller's iocb in the txq tail for later processing. */
10419 	list_add_tail(&piocb->list, &pring->txq);
10420 }
10421 
10422 /**
10423  * lpfc_sli_next_iocb - Get the next iocb in the txq
10424  * @phba: Pointer to HBA context object.
10425  * @pring: Pointer to driver SLI ring object.
10426  * @piocb: Pointer to address of newly added command iocb.
10427  *
10428  * This function is called with hbalock held before a new
10429  * iocb is submitted to the firmware. This function checks
10430  * txq to flush the iocbs in txq to Firmware before
10431  * submitting new iocbs to the Firmware.
10432  * If there are iocbs in the txq which need to be submitted
10433  * to firmware, lpfc_sli_next_iocb returns the first element
10434  * of the txq after dequeuing it from txq.
10435  * If there is no iocb in the txq then the function will return
10436  * *piocb and *piocb is set to NULL. Caller needs to check
10437  * *piocb to find if there are more commands in the txq.
10438  **/
10439 static struct lpfc_iocbq *
10440 lpfc_sli_next_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
10441 		   struct lpfc_iocbq **piocb)
10442 {
10443 	struct lpfc_iocbq * nextiocb;
10444 
10445 	lockdep_assert_held(&phba->hbalock);
10446 
10447 	nextiocb = lpfc_sli_ringtx_get(phba, pring);
10448 	if (!nextiocb) {
10449 		nextiocb = *piocb;
10450 		*piocb = NULL;
10451 	}
10452 
10453 	return nextiocb;
10454 }
10455 
10456 /**
10457  * __lpfc_sli_issue_iocb_s3 - SLI3 device lockless ver of lpfc_sli_issue_iocb
10458  * @phba: Pointer to HBA context object.
10459  * @ring_number: SLI ring number to issue iocb on.
10460  * @piocb: Pointer to command iocb.
10461  * @flag: Flag indicating if this command can be put into txq.
10462  *
10463  * __lpfc_sli_issue_iocb_s3 is used by other functions in the driver to issue
10464  * an iocb command to an HBA with SLI-3 interface spec. If the PCI slot is
10465  * recovering from error state, if HBA is resetting or if LPFC_STOP_IOCB_EVENT
10466  * flag is turned on, the function returns IOCB_ERROR. When the link is down,
10467  * this function allows only iocbs for posting buffers. This function finds
10468  * next available slot in the command ring and posts the command to the
10469  * available slot and writes the port attention register to request HBA start
10470  * processing new iocb. If there is no slot available in the ring and
10471  * flag & SLI_IOCB_RET_IOCB is set, the new iocb is added to the txq, otherwise
10472  * the function returns IOCB_BUSY.
10473  *
10474  * This function is called with hbalock held. The function will return success
10475  * after it successfully submit the iocb to firmware or after adding to the
10476  * txq.
10477  **/
10478 static int
10479 __lpfc_sli_issue_iocb_s3(struct lpfc_hba *phba, uint32_t ring_number,
10480 		    struct lpfc_iocbq *piocb, uint32_t flag)
10481 {
10482 	struct lpfc_iocbq *nextiocb;
10483 	IOCB_t *iocb;
10484 	struct lpfc_sli_ring *pring = &phba->sli.sli3_ring[ring_number];
10485 
10486 	lockdep_assert_held(&phba->hbalock);
10487 
10488 	if (piocb->cmd_cmpl && (!piocb->vport) &&
10489 	   (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
10490 	   (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
10491 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10492 				"1807 IOCB x%x failed. No vport\n",
10493 				piocb->iocb.ulpCommand);
10494 		dump_stack();
10495 		return IOCB_ERROR;
10496 	}
10497 
10498 
10499 	/* If the PCI channel is in offline state, do not post iocbs. */
10500 	if (unlikely(pci_channel_offline(phba->pcidev)))
10501 		return IOCB_ERROR;
10502 
10503 	/* If HBA has a deferred error attention, fail the iocb. */
10504 	if (unlikely(test_bit(DEFER_ERATT, &phba->hba_flag)))
10505 		return IOCB_ERROR;
10506 
10507 	/*
10508 	 * We should never get an IOCB if we are in a < LINK_DOWN state
10509 	 */
10510 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
10511 		return IOCB_ERROR;
10512 
10513 	/*
10514 	 * Check to see if we are blocking IOCB processing because of a
10515 	 * outstanding event.
10516 	 */
10517 	if (unlikely(pring->flag & LPFC_STOP_IOCB_EVENT))
10518 		goto iocb_busy;
10519 
10520 	if (unlikely(phba->link_state == LPFC_LINK_DOWN)) {
10521 		/*
10522 		 * Only CREATE_XRI, CLOSE_XRI, and QUE_RING_BUF
10523 		 * can be issued if the link is not up.
10524 		 */
10525 		switch (piocb->iocb.ulpCommand) {
10526 		case CMD_QUE_RING_BUF_CN:
10527 		case CMD_QUE_RING_BUF64_CN:
10528 			/*
10529 			 * For IOCBs, like QUE_RING_BUF, that have no rsp ring
10530 			 * completion, cmd_cmpl MUST be 0.
10531 			 */
10532 			if (piocb->cmd_cmpl)
10533 				piocb->cmd_cmpl = NULL;
10534 			fallthrough;
10535 		case CMD_CREATE_XRI_CR:
10536 		case CMD_CLOSE_XRI_CN:
10537 		case CMD_CLOSE_XRI_CX:
10538 			break;
10539 		default:
10540 			goto iocb_busy;
10541 		}
10542 
10543 	/*
10544 	 * For FCP commands, we must be in a state where we can process link
10545 	 * attention events.
10546 	 */
10547 	} else if (unlikely(pring->ringno == LPFC_FCP_RING &&
10548 			    !(phba->sli.sli_flag & LPFC_PROCESS_LA))) {
10549 		goto iocb_busy;
10550 	}
10551 
10552 	while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
10553 	       (nextiocb = lpfc_sli_next_iocb(phba, pring, &piocb)))
10554 		lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
10555 
10556 	if (iocb)
10557 		lpfc_sli_update_ring(phba, pring);
10558 	else
10559 		lpfc_sli_update_full_ring(phba, pring);
10560 
10561 	if (!piocb)
10562 		return IOCB_SUCCESS;
10563 
10564 	goto out_busy;
10565 
10566  iocb_busy:
10567 	pring->stats.iocb_cmd_delay++;
10568 
10569  out_busy:
10570 
10571 	if (!(flag & SLI_IOCB_RET_IOCB)) {
10572 		__lpfc_sli_ringtx_put(phba, pring, piocb);
10573 		return IOCB_SUCCESS;
10574 	}
10575 
10576 	return IOCB_BUSY;
10577 }
10578 
10579 /**
10580  * __lpfc_sli_issue_fcp_io_s3 - SLI3 device for sending fcp io iocb
10581  * @phba: Pointer to HBA context object.
10582  * @ring_number: SLI ring number to issue wqe on.
10583  * @piocb: Pointer to command iocb.
10584  * @flag: Flag indicating if this command can be put into txq.
10585  *
10586  * __lpfc_sli_issue_fcp_io_s3 is wrapper function to invoke lockless func to
10587  * send  an iocb command to an HBA with SLI-3 interface spec.
10588  *
10589  * This function takes the hbalock before invoking the lockless version.
10590  * The function will return success after it successfully submit the wqe to
10591  * firmware or after adding to the txq.
10592  **/
10593 static int
10594 __lpfc_sli_issue_fcp_io_s3(struct lpfc_hba *phba, uint32_t ring_number,
10595 			   struct lpfc_iocbq *piocb, uint32_t flag)
10596 {
10597 	unsigned long iflags;
10598 	int rc;
10599 
10600 	spin_lock_irqsave(&phba->hbalock, iflags);
10601 	rc = __lpfc_sli_issue_iocb_s3(phba, ring_number, piocb, flag);
10602 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10603 
10604 	return rc;
10605 }
10606 
10607 /**
10608  * __lpfc_sli_issue_fcp_io_s4 - SLI4 device for sending fcp io wqe
10609  * @phba: Pointer to HBA context object.
10610  * @ring_number: SLI ring number to issue wqe on.
10611  * @piocb: Pointer to command iocb.
10612  * @flag: Flag indicating if this command can be put into txq.
10613  *
10614  * __lpfc_sli_issue_fcp_io_s4 is used by other functions in the driver to issue
10615  * an wqe command to an HBA with SLI-4 interface spec.
10616  *
10617  * This function is a lockless version. The function will return success
10618  * after it successfully submit the wqe to firmware or after adding to the
10619  * txq.
10620  **/
10621 static int
10622 __lpfc_sli_issue_fcp_io_s4(struct lpfc_hba *phba, uint32_t ring_number,
10623 			   struct lpfc_iocbq *piocb, uint32_t flag)
10624 {
10625 	struct lpfc_io_buf *lpfc_cmd = piocb->io_buf;
10626 
10627 	lpfc_prep_embed_io(phba, lpfc_cmd);
10628 	return lpfc_sli4_issue_wqe(phba, lpfc_cmd->hdwq, piocb);
10629 }
10630 
10631 void
10632 lpfc_prep_embed_io(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_cmd)
10633 {
10634 	struct lpfc_iocbq *piocb = &lpfc_cmd->cur_iocbq;
10635 	union lpfc_wqe128 *wqe = &lpfc_cmd->cur_iocbq.wqe;
10636 	struct sli4_sge_le *sgl;
10637 	u32 type_size;
10638 
10639 	/* 128 byte wqe support here */
10640 	sgl = (struct sli4_sge_le *)lpfc_cmd->dma_sgl;
10641 
10642 	if (phba->fcp_embed_io) {
10643 		struct fcp_cmnd *fcp_cmnd;
10644 		u32 *ptr;
10645 
10646 		fcp_cmnd = lpfc_cmd->fcp_cmnd;
10647 
10648 		/* Word 0-2 - FCP_CMND */
10649 		type_size = le32_to_cpu(sgl->sge_len);
10650 		type_size |= ULP_BDE64_TYPE_BDE_IMMED;
10651 		wqe->generic.bde.tus.w = type_size;
10652 		wqe->generic.bde.addrHigh = 0;
10653 		wqe->generic.bde.addrLow =  72;  /* Word 18 */
10654 
10655 		bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
10656 		bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 0);
10657 
10658 		/* Word 18-29  FCP CMND Payload */
10659 		ptr = &wqe->words[18];
10660 		lpfc_sli_pcimem_bcopy(fcp_cmnd, ptr, le32_to_cpu(sgl->sge_len));
10661 	} else {
10662 		/* Word 0-2 - Inline BDE */
10663 		wqe->generic.bde.tus.f.bdeFlags =  BUFF_TYPE_BDE_64;
10664 		wqe->generic.bde.tus.f.bdeSize = le32_to_cpu(sgl->sge_len);
10665 		wqe->generic.bde.addrHigh = le32_to_cpu(sgl->addr_hi);
10666 		wqe->generic.bde.addrLow = le32_to_cpu(sgl->addr_lo);
10667 
10668 		/* Word 10 */
10669 		bf_set(wqe_dbde, &wqe->generic.wqe_com, 1);
10670 		bf_set(wqe_wqes, &wqe->generic.wqe_com, 0);
10671 	}
10672 
10673 	/* add the VMID tags as per switch response */
10674 	if (unlikely(piocb->cmd_flag & LPFC_IO_VMID)) {
10675 		if (phba->pport->vmid_flag & LPFC_VMID_TYPE_PRIO) {
10676 			bf_set(wqe_ccpe, &wqe->fcp_iwrite.wqe_com, 1);
10677 			bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
10678 					(piocb->vmid_tag.cs_ctl_vmid));
10679 		} else if (phba->cfg_vmid_app_header) {
10680 			bf_set(wqe_appid, &wqe->fcp_iwrite.wqe_com, 1);
10681 			bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
10682 			wqe->words[31] = piocb->vmid_tag.app_id;
10683 		}
10684 	}
10685 }
10686 
10687 /**
10688  * __lpfc_sli_issue_iocb_s4 - SLI4 device lockless ver of lpfc_sli_issue_iocb
10689  * @phba: Pointer to HBA context object.
10690  * @ring_number: SLI ring number to issue iocb on.
10691  * @piocb: Pointer to command iocb.
10692  * @flag: Flag indicating if this command can be put into txq.
10693  *
10694  * __lpfc_sli_issue_iocb_s4 is used by other functions in the driver to issue
10695  * an iocb command to an HBA with SLI-4 interface spec.
10696  *
10697  * This function is called with ringlock held. The function will return success
10698  * after it successfully submit the iocb to firmware or after adding to the
10699  * txq.
10700  **/
10701 static int
10702 __lpfc_sli_issue_iocb_s4(struct lpfc_hba *phba, uint32_t ring_number,
10703 			 struct lpfc_iocbq *piocb, uint32_t flag)
10704 {
10705 	struct lpfc_sglq *sglq;
10706 	union lpfc_wqe128 *wqe;
10707 	struct lpfc_queue *wq;
10708 	struct lpfc_sli_ring *pring;
10709 	u32 ulp_command = get_job_cmnd(phba, piocb);
10710 
10711 	/* Get the WQ */
10712 	if ((piocb->cmd_flag & LPFC_IO_FCP) ||
10713 	    (piocb->cmd_flag & LPFC_USE_FCPWQIDX)) {
10714 		wq = phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq;
10715 	} else {
10716 		wq = phba->sli4_hba.els_wq;
10717 	}
10718 
10719 	/* Get corresponding ring */
10720 	pring = wq->pring;
10721 
10722 	/*
10723 	 * The WQE can be either 64 or 128 bytes,
10724 	 */
10725 
10726 	lockdep_assert_held(&pring->ring_lock);
10727 	wqe = &piocb->wqe;
10728 	if (piocb->sli4_xritag == NO_XRI) {
10729 		if (ulp_command == CMD_ABORT_XRI_CX)
10730 			sglq = NULL;
10731 		else {
10732 			sglq = __lpfc_sli_get_els_sglq(phba, piocb);
10733 			if (!sglq) {
10734 				if (!(flag & SLI_IOCB_RET_IOCB)) {
10735 					__lpfc_sli_ringtx_put(phba,
10736 							pring,
10737 							piocb);
10738 					return IOCB_SUCCESS;
10739 				} else {
10740 					return IOCB_BUSY;
10741 				}
10742 			}
10743 		}
10744 	} else if (piocb->cmd_flag &  LPFC_IO_FCP) {
10745 		/* These IO's already have an XRI and a mapped sgl. */
10746 		sglq = NULL;
10747 	}
10748 	else {
10749 		/*
10750 		 * This is a continuation of a commandi,(CX) so this
10751 		 * sglq is on the active list
10752 		 */
10753 		sglq = __lpfc_get_active_sglq(phba, piocb->sli4_lxritag);
10754 		if (!sglq)
10755 			return IOCB_ERROR;
10756 	}
10757 
10758 	if (sglq) {
10759 		piocb->sli4_lxritag = sglq->sli4_lxritag;
10760 		piocb->sli4_xritag = sglq->sli4_xritag;
10761 
10762 		/* ABTS sent by initiator to CT exchange, the
10763 		 * RX_ID field will be filled with the newly
10764 		 * allocated responder XRI.
10765 		 */
10766 		if (ulp_command == CMD_XMIT_BLS_RSP64_CX &&
10767 		    piocb->abort_bls == LPFC_ABTS_UNSOL_INT)
10768 			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
10769 			       piocb->sli4_xritag);
10770 
10771 		bf_set(wqe_xri_tag, &wqe->generic.wqe_com,
10772 		       piocb->sli4_xritag);
10773 
10774 		if (lpfc_wqe_bpl2sgl(phba, piocb, sglq) == NO_XRI)
10775 			return IOCB_ERROR;
10776 	}
10777 
10778 	if (lpfc_sli4_wq_put(wq, wqe))
10779 		return IOCB_ERROR;
10780 
10781 	lpfc_sli_ringtxcmpl_put(phba, pring, piocb);
10782 
10783 	return 0;
10784 }
10785 
10786 /*
10787  * lpfc_sli_issue_fcp_io - Wrapper func for issuing fcp i/o
10788  *
10789  * This routine wraps the actual fcp i/o function for issusing WQE for sli-4
10790  * or IOCB for sli-3  function.
10791  * pointer from the lpfc_hba struct.
10792  *
10793  * Return codes:
10794  * IOCB_ERROR - Error
10795  * IOCB_SUCCESS - Success
10796  * IOCB_BUSY - Busy
10797  **/
10798 int
10799 lpfc_sli_issue_fcp_io(struct lpfc_hba *phba, uint32_t ring_number,
10800 		      struct lpfc_iocbq *piocb, uint32_t flag)
10801 {
10802 	return phba->__lpfc_sli_issue_fcp_io(phba, ring_number, piocb, flag);
10803 }
10804 
10805 /*
10806  * __lpfc_sli_issue_iocb - Wrapper func of lockless version for issuing iocb
10807  *
10808  * This routine wraps the actual lockless version for issusing IOCB function
10809  * pointer from the lpfc_hba struct.
10810  *
10811  * Return codes:
10812  * IOCB_ERROR - Error
10813  * IOCB_SUCCESS - Success
10814  * IOCB_BUSY - Busy
10815  **/
10816 int
10817 __lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
10818 		struct lpfc_iocbq *piocb, uint32_t flag)
10819 {
10820 	return phba->__lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
10821 }
10822 
10823 static void
10824 __lpfc_sli_prep_els_req_rsp_s3(struct lpfc_iocbq *cmdiocbq,
10825 			       struct lpfc_vport *vport,
10826 			       struct lpfc_dmabuf *bmp, u16 cmd_size, u32 did,
10827 			       u32 elscmd, u8 tmo, u8 expect_rsp)
10828 {
10829 	struct lpfc_hba *phba = vport->phba;
10830 	IOCB_t *cmd;
10831 
10832 	cmd = &cmdiocbq->iocb;
10833 	memset(cmd, 0, sizeof(*cmd));
10834 
10835 	cmd->un.elsreq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
10836 	cmd->un.elsreq64.bdl.addrLow = putPaddrLow(bmp->phys);
10837 	cmd->un.elsreq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
10838 
10839 	if (expect_rsp) {
10840 		cmd->un.elsreq64.bdl.bdeSize = (2 * sizeof(struct ulp_bde64));
10841 		cmd->un.elsreq64.remoteID = did; /* DID */
10842 		cmd->ulpCommand = CMD_ELS_REQUEST64_CR;
10843 		cmd->ulpTimeout = tmo;
10844 	} else {
10845 		cmd->un.elsreq64.bdl.bdeSize = sizeof(struct ulp_bde64);
10846 		cmd->un.genreq64.xmit_els_remoteID = did; /* DID */
10847 		cmd->ulpCommand = CMD_XMIT_ELS_RSP64_CX;
10848 		cmd->ulpPU = PARM_NPIV_DID;
10849 	}
10850 	cmd->ulpBdeCount = 1;
10851 	cmd->ulpLe = 1;
10852 	cmd->ulpClass = CLASS3;
10853 
10854 	/* If we have NPIV enabled, we want to send ELS traffic by VPI. */
10855 	if (phba->sli3_options & LPFC_SLI3_NPIV_ENABLED) {
10856 		if (expect_rsp) {
10857 			cmd->un.elsreq64.myID = vport->fc_myDID;
10858 
10859 			/* For ELS_REQUEST64_CR, use the VPI by default */
10860 			cmd->ulpContext = phba->vpi_ids[vport->vpi];
10861 		}
10862 
10863 		cmd->ulpCt_h = 0;
10864 		/* The CT field must be 0=INVALID_RPI for the ECHO cmd */
10865 		if (elscmd == ELS_CMD_ECHO)
10866 			cmd->ulpCt_l = 0; /* context = invalid RPI */
10867 		else
10868 			cmd->ulpCt_l = 1; /* context = VPI */
10869 	}
10870 }
10871 
10872 static void
10873 __lpfc_sli_prep_els_req_rsp_s4(struct lpfc_iocbq *cmdiocbq,
10874 			       struct lpfc_vport *vport,
10875 			       struct lpfc_dmabuf *bmp, u16 cmd_size, u32 did,
10876 			       u32 elscmd, u8 tmo, u8 expect_rsp)
10877 {
10878 	struct lpfc_hba  *phba = vport->phba;
10879 	union lpfc_wqe128 *wqe;
10880 	struct ulp_bde64_le *bde;
10881 	u8 els_id;
10882 
10883 	wqe = &cmdiocbq->wqe;
10884 	memset(wqe, 0, sizeof(*wqe));
10885 
10886 	/* Word 0 - 2 BDE */
10887 	bde = (struct ulp_bde64_le *)&wqe->generic.bde;
10888 	bde->addr_low = cpu_to_le32(putPaddrLow(bmp->phys));
10889 	bde->addr_high = cpu_to_le32(putPaddrHigh(bmp->phys));
10890 	bde->type_size = cpu_to_le32(cmd_size);
10891 	bde->type_size |= cpu_to_le32(ULP_BDE64_TYPE_BDE_64);
10892 
10893 	if (expect_rsp) {
10894 		bf_set(wqe_cmnd, &wqe->els_req.wqe_com, CMD_ELS_REQUEST64_WQE);
10895 
10896 		/* Transfer length */
10897 		wqe->els_req.payload_len = cmd_size;
10898 		wqe->els_req.max_response_payload_len = FCELSSIZE;
10899 
10900 		/* DID */
10901 		bf_set(wqe_els_did, &wqe->els_req.wqe_dest, did);
10902 
10903 		/* Word 11 - ELS_ID */
10904 		switch (elscmd) {
10905 		case ELS_CMD_PLOGI:
10906 			els_id = LPFC_ELS_ID_PLOGI;
10907 			break;
10908 		case ELS_CMD_FLOGI:
10909 			els_id = LPFC_ELS_ID_FLOGI;
10910 			break;
10911 		case ELS_CMD_LOGO:
10912 			els_id = LPFC_ELS_ID_LOGO;
10913 			break;
10914 		case ELS_CMD_FDISC:
10915 			if (!vport->fc_myDID) {
10916 				els_id = LPFC_ELS_ID_FDISC;
10917 				break;
10918 			}
10919 			fallthrough;
10920 		default:
10921 			els_id = LPFC_ELS_ID_DEFAULT;
10922 			break;
10923 		}
10924 
10925 		bf_set(wqe_els_id, &wqe->els_req.wqe_com, els_id);
10926 	} else {
10927 		/* DID */
10928 		bf_set(wqe_els_did, &wqe->xmit_els_rsp.wqe_dest, did);
10929 
10930 		/* Transfer length */
10931 		wqe->xmit_els_rsp.response_payload_len = cmd_size;
10932 
10933 		bf_set(wqe_cmnd, &wqe->xmit_els_rsp.wqe_com,
10934 		       CMD_XMIT_ELS_RSP64_WQE);
10935 	}
10936 
10937 	bf_set(wqe_tmo, &wqe->generic.wqe_com, tmo);
10938 	bf_set(wqe_reqtag, &wqe->generic.wqe_com, cmdiocbq->iotag);
10939 	bf_set(wqe_class, &wqe->generic.wqe_com, CLASS3);
10940 
10941 	/* If we have NPIV enabled, we want to send ELS traffic by VPI.
10942 	 * For SLI4, since the driver controls VPIs we also want to include
10943 	 * all ELS pt2pt protocol traffic as well.
10944 	 */
10945 	if ((phba->sli3_options & LPFC_SLI3_NPIV_ENABLED) ||
10946 	    test_bit(FC_PT2PT, &vport->fc_flag)) {
10947 		if (expect_rsp) {
10948 			bf_set(els_req64_sid, &wqe->els_req, vport->fc_myDID);
10949 
10950 			/* For ELS_REQUEST64_WQE, use the VPI by default */
10951 			bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
10952 			       phba->vpi_ids[vport->vpi]);
10953 		}
10954 
10955 		/* The CT field must be 0=INVALID_RPI for the ECHO cmd */
10956 		if (elscmd == ELS_CMD_ECHO)
10957 			bf_set(wqe_ct, &wqe->generic.wqe_com, 0);
10958 		else
10959 			bf_set(wqe_ct, &wqe->generic.wqe_com, 1);
10960 	}
10961 }
10962 
10963 void
10964 lpfc_sli_prep_els_req_rsp(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
10965 			  struct lpfc_vport *vport, struct lpfc_dmabuf *bmp,
10966 			  u16 cmd_size, u32 did, u32 elscmd, u8 tmo,
10967 			  u8 expect_rsp)
10968 {
10969 	phba->__lpfc_sli_prep_els_req_rsp(cmdiocbq, vport, bmp, cmd_size, did,
10970 					  elscmd, tmo, expect_rsp);
10971 }
10972 
10973 static void
10974 __lpfc_sli_prep_gen_req_s3(struct lpfc_iocbq *cmdiocbq, struct lpfc_dmabuf *bmp,
10975 			   u16 rpi, u32 num_entry, u8 tmo)
10976 {
10977 	IOCB_t *cmd;
10978 
10979 	cmd = &cmdiocbq->iocb;
10980 	memset(cmd, 0, sizeof(*cmd));
10981 
10982 	cmd->un.genreq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
10983 	cmd->un.genreq64.bdl.addrLow = putPaddrLow(bmp->phys);
10984 	cmd->un.genreq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
10985 	cmd->un.genreq64.bdl.bdeSize = num_entry * sizeof(struct ulp_bde64);
10986 
10987 	cmd->un.genreq64.w5.hcsw.Rctl = FC_RCTL_DD_UNSOL_CTL;
10988 	cmd->un.genreq64.w5.hcsw.Type = FC_TYPE_CT;
10989 	cmd->un.genreq64.w5.hcsw.Fctl = (SI | LA);
10990 
10991 	cmd->ulpContext = rpi;
10992 	cmd->ulpClass = CLASS3;
10993 	cmd->ulpCommand = CMD_GEN_REQUEST64_CR;
10994 	cmd->ulpBdeCount = 1;
10995 	cmd->ulpLe = 1;
10996 	cmd->ulpOwner = OWN_CHIP;
10997 	cmd->ulpTimeout = tmo;
10998 }
10999 
11000 static void
11001 __lpfc_sli_prep_gen_req_s4(struct lpfc_iocbq *cmdiocbq, struct lpfc_dmabuf *bmp,
11002 			   u16 rpi, u32 num_entry, u8 tmo)
11003 {
11004 	union lpfc_wqe128 *cmdwqe;
11005 	struct ulp_bde64_le *bde, *bpl;
11006 	u32 xmit_len = 0, total_len = 0, size, type, i;
11007 
11008 	cmdwqe = &cmdiocbq->wqe;
11009 	memset(cmdwqe, 0, sizeof(*cmdwqe));
11010 
11011 	/* Calculate total_len and xmit_len */
11012 	bpl = (struct ulp_bde64_le *)bmp->virt;
11013 	for (i = 0; i < num_entry; i++) {
11014 		size = le32_to_cpu(bpl[i].type_size) & ULP_BDE64_SIZE_MASK;
11015 		total_len += size;
11016 	}
11017 	for (i = 0; i < num_entry; i++) {
11018 		size = le32_to_cpu(bpl[i].type_size) & ULP_BDE64_SIZE_MASK;
11019 		type = le32_to_cpu(bpl[i].type_size) & ULP_BDE64_TYPE_MASK;
11020 		if (type != ULP_BDE64_TYPE_BDE_64)
11021 			break;
11022 		xmit_len += size;
11023 	}
11024 
11025 	/* Words 0 - 2 */
11026 	bde = (struct ulp_bde64_le *)&cmdwqe->generic.bde;
11027 	bde->addr_low = bpl->addr_low;
11028 	bde->addr_high = bpl->addr_high;
11029 	bde->type_size = cpu_to_le32(xmit_len);
11030 	bde->type_size |= cpu_to_le32(ULP_BDE64_TYPE_BDE_64);
11031 
11032 	/* Word 3 */
11033 	cmdwqe->gen_req.request_payload_len = xmit_len;
11034 
11035 	/* Word 5 */
11036 	bf_set(wqe_type, &cmdwqe->gen_req.wge_ctl, FC_TYPE_CT);
11037 	bf_set(wqe_rctl, &cmdwqe->gen_req.wge_ctl, FC_RCTL_DD_UNSOL_CTL);
11038 	bf_set(wqe_si, &cmdwqe->gen_req.wge_ctl, 1);
11039 	bf_set(wqe_la, &cmdwqe->gen_req.wge_ctl, 1);
11040 
11041 	/* Word 6 */
11042 	bf_set(wqe_ctxt_tag, &cmdwqe->gen_req.wqe_com, rpi);
11043 
11044 	/* Word 7 */
11045 	bf_set(wqe_tmo, &cmdwqe->gen_req.wqe_com, tmo);
11046 	bf_set(wqe_class, &cmdwqe->gen_req.wqe_com, CLASS3);
11047 	bf_set(wqe_cmnd, &cmdwqe->gen_req.wqe_com, CMD_GEN_REQUEST64_CR);
11048 	bf_set(wqe_ct, &cmdwqe->gen_req.wqe_com, SLI4_CT_RPI);
11049 
11050 	/* Word 12 */
11051 	cmdwqe->gen_req.max_response_payload_len = total_len - xmit_len;
11052 }
11053 
11054 void
11055 lpfc_sli_prep_gen_req(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
11056 		      struct lpfc_dmabuf *bmp, u16 rpi, u32 num_entry, u8 tmo)
11057 {
11058 	phba->__lpfc_sli_prep_gen_req(cmdiocbq, bmp, rpi, num_entry, tmo);
11059 }
11060 
11061 static void
11062 __lpfc_sli_prep_xmit_seq64_s3(struct lpfc_iocbq *cmdiocbq,
11063 			      struct lpfc_dmabuf *bmp, u16 rpi, u16 ox_id,
11064 			      u32 num_entry, u8 rctl, u8 last_seq, u8 cr_cx_cmd)
11065 {
11066 	IOCB_t *icmd;
11067 
11068 	icmd = &cmdiocbq->iocb;
11069 	memset(icmd, 0, sizeof(*icmd));
11070 
11071 	icmd->un.xseq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
11072 	icmd->un.xseq64.bdl.addrLow = putPaddrLow(bmp->phys);
11073 	icmd->un.xseq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
11074 	icmd->un.xseq64.bdl.bdeSize = (num_entry * sizeof(struct ulp_bde64));
11075 	icmd->un.xseq64.w5.hcsw.Fctl = LA;
11076 	if (last_seq)
11077 		icmd->un.xseq64.w5.hcsw.Fctl |= LS;
11078 	icmd->un.xseq64.w5.hcsw.Dfctl = 0;
11079 	icmd->un.xseq64.w5.hcsw.Rctl = rctl;
11080 	icmd->un.xseq64.w5.hcsw.Type = FC_TYPE_CT;
11081 
11082 	icmd->ulpBdeCount = 1;
11083 	icmd->ulpLe = 1;
11084 	icmd->ulpClass = CLASS3;
11085 
11086 	switch (cr_cx_cmd) {
11087 	case CMD_XMIT_SEQUENCE64_CR:
11088 		icmd->ulpContext = rpi;
11089 		icmd->ulpCommand = CMD_XMIT_SEQUENCE64_CR;
11090 		break;
11091 	case CMD_XMIT_SEQUENCE64_CX:
11092 		icmd->ulpContext = ox_id;
11093 		icmd->ulpCommand = CMD_XMIT_SEQUENCE64_CX;
11094 		break;
11095 	default:
11096 		break;
11097 	}
11098 }
11099 
11100 static void
11101 __lpfc_sli_prep_xmit_seq64_s4(struct lpfc_iocbq *cmdiocbq,
11102 			      struct lpfc_dmabuf *bmp, u16 rpi, u16 ox_id,
11103 			      u32 full_size, u8 rctl, u8 last_seq, u8 cr_cx_cmd)
11104 {
11105 	union lpfc_wqe128 *wqe;
11106 	struct ulp_bde64 *bpl;
11107 
11108 	wqe = &cmdiocbq->wqe;
11109 	memset(wqe, 0, sizeof(*wqe));
11110 
11111 	/* Words 0 - 2 */
11112 	bpl = (struct ulp_bde64 *)bmp->virt;
11113 	wqe->xmit_sequence.bde.addrHigh = bpl->addrHigh;
11114 	wqe->xmit_sequence.bde.addrLow = bpl->addrLow;
11115 	wqe->xmit_sequence.bde.tus.w = bpl->tus.w;
11116 
11117 	/* Word 5 */
11118 	bf_set(wqe_ls, &wqe->xmit_sequence.wge_ctl, last_seq);
11119 	bf_set(wqe_la, &wqe->xmit_sequence.wge_ctl, 1);
11120 	bf_set(wqe_dfctl, &wqe->xmit_sequence.wge_ctl, 0);
11121 	bf_set(wqe_rctl, &wqe->xmit_sequence.wge_ctl, rctl);
11122 	bf_set(wqe_type, &wqe->xmit_sequence.wge_ctl, FC_TYPE_CT);
11123 
11124 	/* Word 6 */
11125 	bf_set(wqe_ctxt_tag, &wqe->xmit_sequence.wqe_com, rpi);
11126 
11127 	bf_set(wqe_cmnd, &wqe->xmit_sequence.wqe_com,
11128 	       CMD_XMIT_SEQUENCE64_WQE);
11129 
11130 	/* Word 7 */
11131 	bf_set(wqe_class, &wqe->xmit_sequence.wqe_com, CLASS3);
11132 
11133 	/* Word 9 */
11134 	bf_set(wqe_rcvoxid, &wqe->xmit_sequence.wqe_com, ox_id);
11135 
11136 	if (cmdiocbq->cmd_flag & (LPFC_IO_LIBDFC | LPFC_IO_LOOPBACK)) {
11137 		/* Word 10 */
11138 		if (cmdiocbq->cmd_flag & LPFC_IO_VMID) {
11139 			bf_set(wqe_appid, &wqe->xmit_sequence.wqe_com, 1);
11140 			bf_set(wqe_wqes, &wqe->xmit_sequence.wqe_com, 1);
11141 			wqe->words[31] = LOOPBACK_SRC_APPID;
11142 		}
11143 
11144 		/* Word 12 */
11145 		wqe->xmit_sequence.xmit_len = full_size;
11146 	}
11147 	else
11148 		wqe->xmit_sequence.xmit_len =
11149 			wqe->xmit_sequence.bde.tus.f.bdeSize;
11150 }
11151 
11152 void
11153 lpfc_sli_prep_xmit_seq64(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
11154 			 struct lpfc_dmabuf *bmp, u16 rpi, u16 ox_id,
11155 			 u32 num_entry, u8 rctl, u8 last_seq, u8 cr_cx_cmd)
11156 {
11157 	phba->__lpfc_sli_prep_xmit_seq64(cmdiocbq, bmp, rpi, ox_id, num_entry,
11158 					 rctl, last_seq, cr_cx_cmd);
11159 }
11160 
11161 static void
11162 __lpfc_sli_prep_abort_xri_s3(struct lpfc_iocbq *cmdiocbq, u16 ulp_context,
11163 			     u16 iotag, u8 ulp_class, u16 cqid, bool ia,
11164 			     bool wqec)
11165 {
11166 	IOCB_t *icmd = NULL;
11167 
11168 	icmd = &cmdiocbq->iocb;
11169 	memset(icmd, 0, sizeof(*icmd));
11170 
11171 	/* Word 5 */
11172 	icmd->un.acxri.abortContextTag = ulp_context;
11173 	icmd->un.acxri.abortIoTag = iotag;
11174 
11175 	if (ia) {
11176 		/* Word 7 */
11177 		icmd->ulpCommand = CMD_CLOSE_XRI_CN;
11178 	} else {
11179 		/* Word 3 */
11180 		icmd->un.acxri.abortType = ABORT_TYPE_ABTS;
11181 
11182 		/* Word 7 */
11183 		icmd->ulpClass = ulp_class;
11184 		icmd->ulpCommand = CMD_ABORT_XRI_CN;
11185 	}
11186 
11187 	/* Word 7 */
11188 	icmd->ulpLe = 1;
11189 }
11190 
11191 static void
11192 __lpfc_sli_prep_abort_xri_s4(struct lpfc_iocbq *cmdiocbq, u16 ulp_context,
11193 			     u16 iotag, u8 ulp_class, u16 cqid, bool ia,
11194 			     bool wqec)
11195 {
11196 	union lpfc_wqe128 *wqe;
11197 
11198 	wqe = &cmdiocbq->wqe;
11199 	memset(wqe, 0, sizeof(*wqe));
11200 
11201 	/* Word 3 */
11202 	bf_set(abort_cmd_criteria, &wqe->abort_cmd, T_XRI_TAG);
11203 	if (ia)
11204 		bf_set(abort_cmd_ia, &wqe->abort_cmd, 1);
11205 	else
11206 		bf_set(abort_cmd_ia, &wqe->abort_cmd, 0);
11207 
11208 	/* Word 7 */
11209 	bf_set(wqe_cmnd, &wqe->abort_cmd.wqe_com, CMD_ABORT_XRI_WQE);
11210 
11211 	/* Word 8 */
11212 	wqe->abort_cmd.wqe_com.abort_tag = ulp_context;
11213 
11214 	/* Word 9 */
11215 	bf_set(wqe_reqtag, &wqe->abort_cmd.wqe_com, iotag);
11216 
11217 	/* Word 10 */
11218 	bf_set(wqe_qosd, &wqe->abort_cmd.wqe_com, 1);
11219 
11220 	/* Word 11 */
11221 	if (wqec)
11222 		bf_set(wqe_wqec, &wqe->abort_cmd.wqe_com, 1);
11223 	bf_set(wqe_cqid, &wqe->abort_cmd.wqe_com, cqid);
11224 	bf_set(wqe_cmd_type, &wqe->abort_cmd.wqe_com, OTHER_COMMAND);
11225 }
11226 
11227 void
11228 lpfc_sli_prep_abort_xri(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
11229 			u16 ulp_context, u16 iotag, u8 ulp_class, u16 cqid,
11230 			bool ia, bool wqec)
11231 {
11232 	phba->__lpfc_sli_prep_abort_xri(cmdiocbq, ulp_context, iotag, ulp_class,
11233 					cqid, ia, wqec);
11234 }
11235 
11236 /**
11237  * lpfc_sli_api_table_setup - Set up sli api function jump table
11238  * @phba: The hba struct for which this call is being executed.
11239  * @dev_grp: The HBA PCI-Device group number.
11240  *
11241  * This routine sets up the SLI interface API function jump table in @phba
11242  * struct.
11243  * Returns: 0 - success, -ENODEV - failure.
11244  **/
11245 int
11246 lpfc_sli_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
11247 {
11248 
11249 	switch (dev_grp) {
11250 	case LPFC_PCI_DEV_LP:
11251 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s3;
11252 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s3;
11253 		phba->__lpfc_sli_issue_fcp_io = __lpfc_sli_issue_fcp_io_s3;
11254 		phba->__lpfc_sli_prep_els_req_rsp = __lpfc_sli_prep_els_req_rsp_s3;
11255 		phba->__lpfc_sli_prep_gen_req = __lpfc_sli_prep_gen_req_s3;
11256 		phba->__lpfc_sli_prep_xmit_seq64 = __lpfc_sli_prep_xmit_seq64_s3;
11257 		phba->__lpfc_sli_prep_abort_xri = __lpfc_sli_prep_abort_xri_s3;
11258 		break;
11259 	case LPFC_PCI_DEV_OC:
11260 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s4;
11261 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s4;
11262 		phba->__lpfc_sli_issue_fcp_io = __lpfc_sli_issue_fcp_io_s4;
11263 		phba->__lpfc_sli_prep_els_req_rsp = __lpfc_sli_prep_els_req_rsp_s4;
11264 		phba->__lpfc_sli_prep_gen_req = __lpfc_sli_prep_gen_req_s4;
11265 		phba->__lpfc_sli_prep_xmit_seq64 = __lpfc_sli_prep_xmit_seq64_s4;
11266 		phba->__lpfc_sli_prep_abort_xri = __lpfc_sli_prep_abort_xri_s4;
11267 		break;
11268 	default:
11269 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11270 				"1419 Invalid HBA PCI-device group: 0x%x\n",
11271 				dev_grp);
11272 		return -ENODEV;
11273 	}
11274 	return 0;
11275 }
11276 
11277 /**
11278  * lpfc_sli4_calc_ring - Calculates which ring to use
11279  * @phba: Pointer to HBA context object.
11280  * @piocb: Pointer to command iocb.
11281  *
11282  * For SLI4 only, FCP IO can deferred to one fo many WQs, based on
11283  * hba_wqidx, thus we need to calculate the corresponding ring.
11284  * Since ABORTS must go on the same WQ of the command they are
11285  * aborting, we use command's hba_wqidx.
11286  */
11287 struct lpfc_sli_ring *
11288 lpfc_sli4_calc_ring(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
11289 {
11290 	struct lpfc_io_buf *lpfc_cmd;
11291 
11292 	if (piocb->cmd_flag & (LPFC_IO_FCP | LPFC_USE_FCPWQIDX)) {
11293 		if (unlikely(!phba->sli4_hba.hdwq))
11294 			return NULL;
11295 		/*
11296 		 * for abort iocb hba_wqidx should already
11297 		 * be setup based on what work queue we used.
11298 		 */
11299 		if (!(piocb->cmd_flag & LPFC_USE_FCPWQIDX)) {
11300 			lpfc_cmd = piocb->io_buf;
11301 			piocb->hba_wqidx = lpfc_cmd->hdwq_no;
11302 		}
11303 		return phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq->pring;
11304 	} else {
11305 		if (unlikely(!phba->sli4_hba.els_wq))
11306 			return NULL;
11307 		piocb->hba_wqidx = 0;
11308 		return phba->sli4_hba.els_wq->pring;
11309 	}
11310 }
11311 
11312 inline void lpfc_sli4_poll_eq(struct lpfc_queue *eq)
11313 {
11314 	struct lpfc_hba *phba = eq->phba;
11315 
11316 	/*
11317 	 * Unlocking an irq is one of the entry point to check
11318 	 * for re-schedule, but we are good for io submission
11319 	 * path as midlayer does a get_cpu to glue us in. Flush
11320 	 * out the invalidate queue so we can see the updated
11321 	 * value for flag.
11322 	 */
11323 	smp_rmb();
11324 
11325 	if (READ_ONCE(eq->mode) == LPFC_EQ_POLL)
11326 		/* We will not likely get the completion for the caller
11327 		 * during this iteration but i guess that's fine.
11328 		 * Future io's coming on this eq should be able to
11329 		 * pick it up.  As for the case of single io's, they
11330 		 * will be handled through a sched from polling timer
11331 		 * function which is currently triggered every 1msec.
11332 		 */
11333 		lpfc_sli4_process_eq(phba, eq, LPFC_QUEUE_NOARM,
11334 				     LPFC_QUEUE_WORK);
11335 }
11336 
11337 /**
11338  * lpfc_sli_issue_iocb - Wrapper function for __lpfc_sli_issue_iocb
11339  * @phba: Pointer to HBA context object.
11340  * @ring_number: Ring number
11341  * @piocb: Pointer to command iocb.
11342  * @flag: Flag indicating if this command can be put into txq.
11343  *
11344  * lpfc_sli_issue_iocb is a wrapper around __lpfc_sli_issue_iocb
11345  * function. This function gets the hbalock and calls
11346  * __lpfc_sli_issue_iocb function and will return the error returned
11347  * by __lpfc_sli_issue_iocb function. This wrapper is used by
11348  * functions which do not hold hbalock.
11349  **/
11350 int
11351 lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
11352 		    struct lpfc_iocbq *piocb, uint32_t flag)
11353 {
11354 	struct lpfc_sli_ring *pring;
11355 	struct lpfc_queue *eq;
11356 	unsigned long iflags;
11357 	int rc;
11358 
11359 	/* If the PCI channel is in offline state, do not post iocbs. */
11360 	if (unlikely(pci_channel_offline(phba->pcidev)))
11361 		return IOCB_ERROR;
11362 
11363 	if (phba->sli_rev == LPFC_SLI_REV4) {
11364 		lpfc_sli_prep_wqe(phba, piocb);
11365 
11366 		eq = phba->sli4_hba.hdwq[piocb->hba_wqidx].hba_eq;
11367 
11368 		pring = lpfc_sli4_calc_ring(phba, piocb);
11369 		if (unlikely(pring == NULL))
11370 			return IOCB_ERROR;
11371 
11372 		spin_lock_irqsave(&pring->ring_lock, iflags);
11373 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
11374 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
11375 
11376 		lpfc_sli4_poll_eq(eq);
11377 	} else {
11378 		/* For now, SLI2/3 will still use hbalock */
11379 		spin_lock_irqsave(&phba->hbalock, iflags);
11380 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
11381 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11382 	}
11383 	return rc;
11384 }
11385 
11386 /**
11387  * lpfc_extra_ring_setup - Extra ring setup function
11388  * @phba: Pointer to HBA context object.
11389  *
11390  * This function is called while driver attaches with the
11391  * HBA to setup the extra ring. The extra ring is used
11392  * only when driver needs to support target mode functionality
11393  * or IP over FC functionalities.
11394  *
11395  * This function is called with no lock held. SLI3 only.
11396  **/
11397 static int
11398 lpfc_extra_ring_setup( struct lpfc_hba *phba)
11399 {
11400 	struct lpfc_sli *psli;
11401 	struct lpfc_sli_ring *pring;
11402 
11403 	psli = &phba->sli;
11404 
11405 	/* Adjust cmd/rsp ring iocb entries more evenly */
11406 
11407 	/* Take some away from the FCP ring */
11408 	pring = &psli->sli3_ring[LPFC_FCP_RING];
11409 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R1XTRA_ENTRIES;
11410 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R1XTRA_ENTRIES;
11411 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R3XTRA_ENTRIES;
11412 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R3XTRA_ENTRIES;
11413 
11414 	/* and give them to the extra ring */
11415 	pring = &psli->sli3_ring[LPFC_EXTRA_RING];
11416 
11417 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R1XTRA_ENTRIES;
11418 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R1XTRA_ENTRIES;
11419 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R3XTRA_ENTRIES;
11420 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R3XTRA_ENTRIES;
11421 
11422 	/* Setup default profile for this ring */
11423 	pring->iotag_max = 4096;
11424 	pring->num_mask = 1;
11425 	pring->prt[0].profile = 0;      /* Mask 0 */
11426 	pring->prt[0].rctl = phba->cfg_multi_ring_rctl;
11427 	pring->prt[0].type = phba->cfg_multi_ring_type;
11428 	pring->prt[0].lpfc_sli_rcv_unsol_event = NULL;
11429 	return 0;
11430 }
11431 
11432 static void
11433 lpfc_sli_post_recovery_event(struct lpfc_hba *phba,
11434 			     struct lpfc_nodelist *ndlp)
11435 {
11436 	unsigned long iflags;
11437 	struct lpfc_work_evt  *evtp = &ndlp->recovery_evt;
11438 
11439 	/* Hold a node reference for outstanding queued work */
11440 	if (!lpfc_nlp_get(ndlp))
11441 		return;
11442 
11443 	spin_lock_irqsave(&phba->hbalock, iflags);
11444 	if (!list_empty(&evtp->evt_listp)) {
11445 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11446 		lpfc_nlp_put(ndlp);
11447 		return;
11448 	}
11449 
11450 	evtp->evt_arg1 = ndlp;
11451 	evtp->evt = LPFC_EVT_RECOVER_PORT;
11452 	list_add_tail(&evtp->evt_listp, &phba->work_list);
11453 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11454 
11455 	lpfc_worker_wake_up(phba);
11456 }
11457 
11458 /* lpfc_sli_abts_err_handler - handle a failed ABTS request from an SLI3 port.
11459  * @phba: Pointer to HBA context object.
11460  * @iocbq: Pointer to iocb object.
11461  *
11462  * The async_event handler calls this routine when it receives
11463  * an ASYNC_STATUS_CN event from the port.  The port generates
11464  * this event when an Abort Sequence request to an rport fails
11465  * twice in succession.  The abort could be originated by the
11466  * driver or by the port.  The ABTS could have been for an ELS
11467  * or FCP IO.  The port only generates this event when an ABTS
11468  * fails to complete after one retry.
11469  */
11470 static void
11471 lpfc_sli_abts_err_handler(struct lpfc_hba *phba,
11472 			  struct lpfc_iocbq *iocbq)
11473 {
11474 	struct lpfc_nodelist *ndlp = NULL;
11475 	uint16_t rpi = 0, vpi = 0;
11476 	struct lpfc_vport *vport = NULL;
11477 
11478 	/* The rpi in the ulpContext is vport-sensitive. */
11479 	vpi = iocbq->iocb.un.asyncstat.sub_ctxt_tag;
11480 	rpi = iocbq->iocb.ulpContext;
11481 
11482 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
11483 			"3092 Port generated ABTS async event "
11484 			"on vpi %d rpi %d status 0x%x\n",
11485 			vpi, rpi, iocbq->iocb.ulpStatus);
11486 
11487 	vport = lpfc_find_vport_by_vpid(phba, vpi);
11488 	if (!vport)
11489 		goto err_exit;
11490 	ndlp = lpfc_findnode_rpi(vport, rpi);
11491 	if (!ndlp)
11492 		goto err_exit;
11493 
11494 	if (iocbq->iocb.ulpStatus == IOSTAT_LOCAL_REJECT)
11495 		lpfc_sli_abts_recover_port(vport, ndlp);
11496 	return;
11497 
11498  err_exit:
11499 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11500 			"3095 Event Context not found, no "
11501 			"action on vpi %d rpi %d status 0x%x, reason 0x%x\n",
11502 			vpi, rpi, iocbq->iocb.ulpStatus,
11503 			iocbq->iocb.ulpContext);
11504 }
11505 
11506 /* lpfc_sli4_abts_err_handler - handle a failed ABTS request from an SLI4 port.
11507  * @phba: pointer to HBA context object.
11508  * @ndlp: nodelist pointer for the impacted rport.
11509  * @axri: pointer to the wcqe containing the failed exchange.
11510  *
11511  * The driver calls this routine when it receives an ABORT_XRI_FCP CQE from the
11512  * port.  The port generates this event when an abort exchange request to an
11513  * rport fails twice in succession with no reply.  The abort could be originated
11514  * by the driver or by the port.  The ABTS could have been for an ELS or FCP IO.
11515  */
11516 void
11517 lpfc_sli4_abts_err_handler(struct lpfc_hba *phba,
11518 			   struct lpfc_nodelist *ndlp,
11519 			   struct sli4_wcqe_xri_aborted *axri)
11520 {
11521 	uint32_t ext_status = 0;
11522 
11523 	if (!ndlp) {
11524 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11525 				"3115 Node Context not found, driver "
11526 				"ignoring abts err event\n");
11527 		return;
11528 	}
11529 
11530 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
11531 			"3116 Port generated FCP XRI ABORT event on "
11532 			"vpi %d rpi %d xri x%x status 0x%x parameter x%x\n",
11533 			ndlp->vport->vpi, phba->sli4_hba.rpi_ids[ndlp->nlp_rpi],
11534 			bf_get(lpfc_wcqe_xa_xri, axri),
11535 			bf_get(lpfc_wcqe_xa_status, axri),
11536 			axri->parameter);
11537 
11538 	/*
11539 	 * Catch the ABTS protocol failure case.  Older OCe FW releases returned
11540 	 * LOCAL_REJECT and 0 for a failed ABTS exchange and later OCe and
11541 	 * LPe FW releases returned LOCAL_REJECT and SEQUENCE_TIMEOUT.
11542 	 */
11543 	ext_status = axri->parameter & IOERR_PARAM_MASK;
11544 	if ((bf_get(lpfc_wcqe_xa_status, axri) == IOSTAT_LOCAL_REJECT) &&
11545 	    ((ext_status == IOERR_SEQUENCE_TIMEOUT) || (ext_status == 0)))
11546 		lpfc_sli_post_recovery_event(phba, ndlp);
11547 }
11548 
11549 /**
11550  * lpfc_sli_async_event_handler - ASYNC iocb handler function
11551  * @phba: Pointer to HBA context object.
11552  * @pring: Pointer to driver SLI ring object.
11553  * @iocbq: Pointer to iocb object.
11554  *
11555  * This function is called by the slow ring event handler
11556  * function when there is an ASYNC event iocb in the ring.
11557  * This function is called with no lock held.
11558  * Currently this function handles only temperature related
11559  * ASYNC events. The function decodes the temperature sensor
11560  * event message and posts events for the management applications.
11561  **/
11562 static void
11563 lpfc_sli_async_event_handler(struct lpfc_hba * phba,
11564 	struct lpfc_sli_ring * pring, struct lpfc_iocbq * iocbq)
11565 {
11566 	IOCB_t *icmd;
11567 	uint16_t evt_code;
11568 	struct temp_event temp_event_data;
11569 	struct Scsi_Host *shost;
11570 	uint32_t *iocb_w;
11571 
11572 	icmd = &iocbq->iocb;
11573 	evt_code = icmd->un.asyncstat.evt_code;
11574 
11575 	switch (evt_code) {
11576 	case ASYNC_TEMP_WARN:
11577 	case ASYNC_TEMP_SAFE:
11578 		temp_event_data.data = (uint32_t) icmd->ulpContext;
11579 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
11580 		if (evt_code == ASYNC_TEMP_WARN) {
11581 			temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
11582 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11583 				"0347 Adapter is very hot, please take "
11584 				"corrective action. temperature : %d Celsius\n",
11585 				(uint32_t) icmd->ulpContext);
11586 		} else {
11587 			temp_event_data.event_code = LPFC_NORMAL_TEMP;
11588 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11589 				"0340 Adapter temperature is OK now. "
11590 				"temperature : %d Celsius\n",
11591 				(uint32_t) icmd->ulpContext);
11592 		}
11593 
11594 		/* Send temperature change event to applications */
11595 		shost = lpfc_shost_from_vport(phba->pport);
11596 		fc_host_post_vendor_event(shost, fc_get_event_number(),
11597 			sizeof(temp_event_data), (char *) &temp_event_data,
11598 			LPFC_NL_VENDOR_ID);
11599 		break;
11600 	case ASYNC_STATUS_CN:
11601 		lpfc_sli_abts_err_handler(phba, iocbq);
11602 		break;
11603 	default:
11604 		iocb_w = (uint32_t *) icmd;
11605 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11606 			"0346 Ring %d handler: unexpected ASYNC_STATUS"
11607 			" evt_code 0x%x\n"
11608 			"W0  0x%08x W1  0x%08x W2  0x%08x W3  0x%08x\n"
11609 			"W4  0x%08x W5  0x%08x W6  0x%08x W7  0x%08x\n"
11610 			"W8  0x%08x W9  0x%08x W10 0x%08x W11 0x%08x\n"
11611 			"W12 0x%08x W13 0x%08x W14 0x%08x W15 0x%08x\n",
11612 			pring->ringno, icmd->un.asyncstat.evt_code,
11613 			iocb_w[0], iocb_w[1], iocb_w[2], iocb_w[3],
11614 			iocb_w[4], iocb_w[5], iocb_w[6], iocb_w[7],
11615 			iocb_w[8], iocb_w[9], iocb_w[10], iocb_w[11],
11616 			iocb_w[12], iocb_w[13], iocb_w[14], iocb_w[15]);
11617 
11618 		break;
11619 	}
11620 }
11621 
11622 
11623 /**
11624  * lpfc_sli4_setup - SLI ring setup function
11625  * @phba: Pointer to HBA context object.
11626  *
11627  * lpfc_sli_setup sets up rings of the SLI interface with
11628  * number of iocbs per ring and iotags. This function is
11629  * called while driver attach to the HBA and before the
11630  * interrupts are enabled. So there is no need for locking.
11631  *
11632  * This function always returns 0.
11633  **/
11634 int
11635 lpfc_sli4_setup(struct lpfc_hba *phba)
11636 {
11637 	struct lpfc_sli_ring *pring;
11638 
11639 	pring = phba->sli4_hba.els_wq->pring;
11640 	pring->num_mask = LPFC_MAX_RING_MASK;
11641 	pring->prt[0].profile = 0;	/* Mask 0 */
11642 	pring->prt[0].rctl = FC_RCTL_ELS_REQ;
11643 	pring->prt[0].type = FC_TYPE_ELS;
11644 	pring->prt[0].lpfc_sli_rcv_unsol_event =
11645 	    lpfc_els_unsol_event;
11646 	pring->prt[1].profile = 0;	/* Mask 1 */
11647 	pring->prt[1].rctl = FC_RCTL_ELS_REP;
11648 	pring->prt[1].type = FC_TYPE_ELS;
11649 	pring->prt[1].lpfc_sli_rcv_unsol_event =
11650 	    lpfc_els_unsol_event;
11651 	pring->prt[2].profile = 0;	/* Mask 2 */
11652 	/* NameServer Inquiry */
11653 	pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
11654 	/* NameServer */
11655 	pring->prt[2].type = FC_TYPE_CT;
11656 	pring->prt[2].lpfc_sli_rcv_unsol_event =
11657 	    lpfc_ct_unsol_event;
11658 	pring->prt[3].profile = 0;	/* Mask 3 */
11659 	/* NameServer response */
11660 	pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
11661 	/* NameServer */
11662 	pring->prt[3].type = FC_TYPE_CT;
11663 	pring->prt[3].lpfc_sli_rcv_unsol_event =
11664 	    lpfc_ct_unsol_event;
11665 	return 0;
11666 }
11667 
11668 /**
11669  * lpfc_sli_setup - SLI ring setup function
11670  * @phba: Pointer to HBA context object.
11671  *
11672  * lpfc_sli_setup sets up rings of the SLI interface with
11673  * number of iocbs per ring and iotags. This function is
11674  * called while driver attach to the HBA and before the
11675  * interrupts are enabled. So there is no need for locking.
11676  *
11677  * This function always returns 0. SLI3 only.
11678  **/
11679 int
11680 lpfc_sli_setup(struct lpfc_hba *phba)
11681 {
11682 	int i, totiocbsize = 0;
11683 	struct lpfc_sli *psli = &phba->sli;
11684 	struct lpfc_sli_ring *pring;
11685 
11686 	psli->num_rings = MAX_SLI3_CONFIGURED_RINGS;
11687 	psli->sli_flag = 0;
11688 
11689 	psli->iocbq_lookup = NULL;
11690 	psli->iocbq_lookup_len = 0;
11691 	psli->last_iotag = 0;
11692 
11693 	for (i = 0; i < psli->num_rings; i++) {
11694 		pring = &psli->sli3_ring[i];
11695 		switch (i) {
11696 		case LPFC_FCP_RING:	/* ring 0 - FCP */
11697 			/* numCiocb and numRiocb are used in config_port */
11698 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R0_ENTRIES;
11699 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R0_ENTRIES;
11700 			pring->sli.sli3.numCiocb +=
11701 				SLI2_IOCB_CMD_R1XTRA_ENTRIES;
11702 			pring->sli.sli3.numRiocb +=
11703 				SLI2_IOCB_RSP_R1XTRA_ENTRIES;
11704 			pring->sli.sli3.numCiocb +=
11705 				SLI2_IOCB_CMD_R3XTRA_ENTRIES;
11706 			pring->sli.sli3.numRiocb +=
11707 				SLI2_IOCB_RSP_R3XTRA_ENTRIES;
11708 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
11709 							SLI3_IOCB_CMD_SIZE :
11710 							SLI2_IOCB_CMD_SIZE;
11711 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
11712 							SLI3_IOCB_RSP_SIZE :
11713 							SLI2_IOCB_RSP_SIZE;
11714 			pring->iotag_ctr = 0;
11715 			pring->iotag_max =
11716 			    (phba->cfg_hba_queue_depth * 2);
11717 			pring->fast_iotag = pring->iotag_max;
11718 			pring->num_mask = 0;
11719 			break;
11720 		case LPFC_EXTRA_RING:	/* ring 1 - EXTRA */
11721 			/* numCiocb and numRiocb are used in config_port */
11722 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R1_ENTRIES;
11723 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R1_ENTRIES;
11724 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
11725 							SLI3_IOCB_CMD_SIZE :
11726 							SLI2_IOCB_CMD_SIZE;
11727 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
11728 							SLI3_IOCB_RSP_SIZE :
11729 							SLI2_IOCB_RSP_SIZE;
11730 			pring->iotag_max = phba->cfg_hba_queue_depth;
11731 			pring->num_mask = 0;
11732 			break;
11733 		case LPFC_ELS_RING:	/* ring 2 - ELS / CT */
11734 			/* numCiocb and numRiocb are used in config_port */
11735 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R2_ENTRIES;
11736 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R2_ENTRIES;
11737 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
11738 							SLI3_IOCB_CMD_SIZE :
11739 							SLI2_IOCB_CMD_SIZE;
11740 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
11741 							SLI3_IOCB_RSP_SIZE :
11742 							SLI2_IOCB_RSP_SIZE;
11743 			pring->fast_iotag = 0;
11744 			pring->iotag_ctr = 0;
11745 			pring->iotag_max = 4096;
11746 			pring->lpfc_sli_rcv_async_status =
11747 				lpfc_sli_async_event_handler;
11748 			pring->num_mask = LPFC_MAX_RING_MASK;
11749 			pring->prt[0].profile = 0;	/* Mask 0 */
11750 			pring->prt[0].rctl = FC_RCTL_ELS_REQ;
11751 			pring->prt[0].type = FC_TYPE_ELS;
11752 			pring->prt[0].lpfc_sli_rcv_unsol_event =
11753 			    lpfc_els_unsol_event;
11754 			pring->prt[1].profile = 0;	/* Mask 1 */
11755 			pring->prt[1].rctl = FC_RCTL_ELS_REP;
11756 			pring->prt[1].type = FC_TYPE_ELS;
11757 			pring->prt[1].lpfc_sli_rcv_unsol_event =
11758 			    lpfc_els_unsol_event;
11759 			pring->prt[2].profile = 0;	/* Mask 2 */
11760 			/* NameServer Inquiry */
11761 			pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
11762 			/* NameServer */
11763 			pring->prt[2].type = FC_TYPE_CT;
11764 			pring->prt[2].lpfc_sli_rcv_unsol_event =
11765 			    lpfc_ct_unsol_event;
11766 			pring->prt[3].profile = 0;	/* Mask 3 */
11767 			/* NameServer response */
11768 			pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
11769 			/* NameServer */
11770 			pring->prt[3].type = FC_TYPE_CT;
11771 			pring->prt[3].lpfc_sli_rcv_unsol_event =
11772 			    lpfc_ct_unsol_event;
11773 			break;
11774 		}
11775 		totiocbsize += (pring->sli.sli3.numCiocb *
11776 			pring->sli.sli3.sizeCiocb) +
11777 			(pring->sli.sli3.numRiocb * pring->sli.sli3.sizeRiocb);
11778 	}
11779 	if (totiocbsize > MAX_SLIM_IOCB_SIZE) {
11780 		/* Too many cmd / rsp ring entries in SLI2 SLIM */
11781 		printk(KERN_ERR "%d:0462 Too many cmd / rsp ring entries in "
11782 		       "SLI2 SLIM Data: x%x x%lx\n",
11783 		       phba->brd_no, totiocbsize,
11784 		       (unsigned long) MAX_SLIM_IOCB_SIZE);
11785 	}
11786 	if (phba->cfg_multi_ring_support == 2)
11787 		lpfc_extra_ring_setup(phba);
11788 
11789 	return 0;
11790 }
11791 
11792 /**
11793  * lpfc_sli4_queue_init - Queue initialization function
11794  * @phba: Pointer to HBA context object.
11795  *
11796  * lpfc_sli4_queue_init sets up mailbox queues and iocb queues for each
11797  * ring. This function also initializes ring indices of each ring.
11798  * This function is called during the initialization of the SLI
11799  * interface of an HBA.
11800  * This function is called with no lock held and always returns
11801  * 1.
11802  **/
11803 void
11804 lpfc_sli4_queue_init(struct lpfc_hba *phba)
11805 {
11806 	struct lpfc_sli *psli;
11807 	struct lpfc_sli_ring *pring;
11808 	int i;
11809 
11810 	psli = &phba->sli;
11811 	spin_lock_irq(&phba->hbalock);
11812 	INIT_LIST_HEAD(&psli->mboxq);
11813 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
11814 	/* Initialize list headers for txq and txcmplq as double linked lists */
11815 	for (i = 0; i < phba->cfg_hdw_queue; i++) {
11816 		pring = phba->sli4_hba.hdwq[i].io_wq->pring;
11817 		pring->flag = 0;
11818 		pring->ringno = LPFC_FCP_RING;
11819 		pring->txcmplq_cnt = 0;
11820 		INIT_LIST_HEAD(&pring->txq);
11821 		INIT_LIST_HEAD(&pring->txcmplq);
11822 		INIT_LIST_HEAD(&pring->iocb_continueq);
11823 		spin_lock_init(&pring->ring_lock);
11824 	}
11825 	pring = phba->sli4_hba.els_wq->pring;
11826 	pring->flag = 0;
11827 	pring->ringno = LPFC_ELS_RING;
11828 	pring->txcmplq_cnt = 0;
11829 	INIT_LIST_HEAD(&pring->txq);
11830 	INIT_LIST_HEAD(&pring->txcmplq);
11831 	INIT_LIST_HEAD(&pring->iocb_continueq);
11832 	spin_lock_init(&pring->ring_lock);
11833 
11834 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
11835 		pring = phba->sli4_hba.nvmels_wq->pring;
11836 		pring->flag = 0;
11837 		pring->ringno = LPFC_ELS_RING;
11838 		pring->txcmplq_cnt = 0;
11839 		INIT_LIST_HEAD(&pring->txq);
11840 		INIT_LIST_HEAD(&pring->txcmplq);
11841 		INIT_LIST_HEAD(&pring->iocb_continueq);
11842 		spin_lock_init(&pring->ring_lock);
11843 	}
11844 
11845 	spin_unlock_irq(&phba->hbalock);
11846 }
11847 
11848 /**
11849  * lpfc_sli_queue_init - Queue initialization function
11850  * @phba: Pointer to HBA context object.
11851  *
11852  * lpfc_sli_queue_init sets up mailbox queues and iocb queues for each
11853  * ring. This function also initializes ring indices of each ring.
11854  * This function is called during the initialization of the SLI
11855  * interface of an HBA.
11856  * This function is called with no lock held and always returns
11857  * 1.
11858  **/
11859 void
11860 lpfc_sli_queue_init(struct lpfc_hba *phba)
11861 {
11862 	struct lpfc_sli *psli;
11863 	struct lpfc_sli_ring *pring;
11864 	int i;
11865 
11866 	psli = &phba->sli;
11867 	spin_lock_irq(&phba->hbalock);
11868 	INIT_LIST_HEAD(&psli->mboxq);
11869 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
11870 	/* Initialize list headers for txq and txcmplq as double linked lists */
11871 	for (i = 0; i < psli->num_rings; i++) {
11872 		pring = &psli->sli3_ring[i];
11873 		pring->ringno = i;
11874 		pring->sli.sli3.next_cmdidx  = 0;
11875 		pring->sli.sli3.local_getidx = 0;
11876 		pring->sli.sli3.cmdidx = 0;
11877 		INIT_LIST_HEAD(&pring->iocb_continueq);
11878 		INIT_LIST_HEAD(&pring->iocb_continue_saveq);
11879 		INIT_LIST_HEAD(&pring->postbufq);
11880 		pring->flag = 0;
11881 		INIT_LIST_HEAD(&pring->txq);
11882 		INIT_LIST_HEAD(&pring->txcmplq);
11883 		spin_lock_init(&pring->ring_lock);
11884 	}
11885 	spin_unlock_irq(&phba->hbalock);
11886 }
11887 
11888 /**
11889  * lpfc_sli_mbox_sys_flush - Flush mailbox command sub-system
11890  * @phba: Pointer to HBA context object.
11891  *
11892  * This routine flushes the mailbox command subsystem. It will unconditionally
11893  * flush all the mailbox commands in the three possible stages in the mailbox
11894  * command sub-system: pending mailbox command queue; the outstanding mailbox
11895  * command; and completed mailbox command queue. It is caller's responsibility
11896  * to make sure that the driver is in the proper state to flush the mailbox
11897  * command sub-system. Namely, the posting of mailbox commands into the
11898  * pending mailbox command queue from the various clients must be stopped;
11899  * either the HBA is in a state that it will never works on the outstanding
11900  * mailbox command (such as in EEH or ERATT conditions) or the outstanding
11901  * mailbox command has been completed.
11902  **/
11903 static void
11904 lpfc_sli_mbox_sys_flush(struct lpfc_hba *phba)
11905 {
11906 	LIST_HEAD(completions);
11907 	struct lpfc_sli *psli = &phba->sli;
11908 	LPFC_MBOXQ_t *pmb;
11909 	unsigned long iflag;
11910 
11911 	/* Disable softirqs, including timers from obtaining phba->hbalock */
11912 	local_bh_disable();
11913 
11914 	/* Flush all the mailbox commands in the mbox system */
11915 	spin_lock_irqsave(&phba->hbalock, iflag);
11916 
11917 	/* The pending mailbox command queue */
11918 	list_splice_init(&phba->sli.mboxq, &completions);
11919 	/* The outstanding active mailbox command */
11920 	if (psli->mbox_active) {
11921 		list_add_tail(&psli->mbox_active->list, &completions);
11922 		psli->mbox_active = NULL;
11923 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
11924 	}
11925 	/* The completed mailbox command queue */
11926 	list_splice_init(&phba->sli.mboxq_cmpl, &completions);
11927 	spin_unlock_irqrestore(&phba->hbalock, iflag);
11928 
11929 	/* Enable softirqs again, done with phba->hbalock */
11930 	local_bh_enable();
11931 
11932 	/* Return all flushed mailbox commands with MBX_NOT_FINISHED status */
11933 	while (!list_empty(&completions)) {
11934 		list_remove_head(&completions, pmb, LPFC_MBOXQ_t, list);
11935 		pmb->u.mb.mbxStatus = MBX_NOT_FINISHED;
11936 		if (pmb->mbox_cmpl)
11937 			pmb->mbox_cmpl(phba, pmb);
11938 	}
11939 }
11940 
11941 /**
11942  * lpfc_sli_host_down - Vport cleanup function
11943  * @vport: Pointer to virtual port object.
11944  *
11945  * lpfc_sli_host_down is called to clean up the resources
11946  * associated with a vport before destroying virtual
11947  * port data structures.
11948  * This function does following operations:
11949  * - Free discovery resources associated with this virtual
11950  *   port.
11951  * - Free iocbs associated with this virtual port in
11952  *   the txq.
11953  * - Send abort for all iocb commands associated with this
11954  *   vport in txcmplq.
11955  *
11956  * This function is called with no lock held and always returns 1.
11957  **/
11958 int
11959 lpfc_sli_host_down(struct lpfc_vport *vport)
11960 {
11961 	LIST_HEAD(completions);
11962 	struct lpfc_hba *phba = vport->phba;
11963 	struct lpfc_sli *psli = &phba->sli;
11964 	struct lpfc_queue *qp = NULL;
11965 	struct lpfc_sli_ring *pring;
11966 	struct lpfc_iocbq *iocb, *next_iocb;
11967 	int i;
11968 	unsigned long flags = 0;
11969 	uint16_t prev_pring_flag;
11970 
11971 	lpfc_cleanup_discovery_resources(vport);
11972 
11973 	spin_lock_irqsave(&phba->hbalock, flags);
11974 
11975 	/*
11976 	 * Error everything on the txq since these iocbs
11977 	 * have not been given to the FW yet.
11978 	 * Also issue ABTS for everything on the txcmplq
11979 	 */
11980 	if (phba->sli_rev != LPFC_SLI_REV4) {
11981 		for (i = 0; i < psli->num_rings; i++) {
11982 			pring = &psli->sli3_ring[i];
11983 			prev_pring_flag = pring->flag;
11984 			/* Only slow rings */
11985 			if (pring->ringno == LPFC_ELS_RING) {
11986 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
11987 				/* Set the lpfc data pending flag */
11988 				set_bit(LPFC_DATA_READY, &phba->data_flags);
11989 			}
11990 			list_for_each_entry_safe(iocb, next_iocb,
11991 						 &pring->txq, list) {
11992 				if (iocb->vport != vport)
11993 					continue;
11994 				list_move_tail(&iocb->list, &completions);
11995 			}
11996 			list_for_each_entry_safe(iocb, next_iocb,
11997 						 &pring->txcmplq, list) {
11998 				if (iocb->vport != vport)
11999 					continue;
12000 				lpfc_sli_issue_abort_iotag(phba, pring, iocb,
12001 							   NULL);
12002 			}
12003 			pring->flag = prev_pring_flag;
12004 		}
12005 	} else {
12006 		list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
12007 			pring = qp->pring;
12008 			if (!pring)
12009 				continue;
12010 			if (pring == phba->sli4_hba.els_wq->pring) {
12011 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
12012 				/* Set the lpfc data pending flag */
12013 				set_bit(LPFC_DATA_READY, &phba->data_flags);
12014 			}
12015 			prev_pring_flag = pring->flag;
12016 			spin_lock(&pring->ring_lock);
12017 			list_for_each_entry_safe(iocb, next_iocb,
12018 						 &pring->txq, list) {
12019 				if (iocb->vport != vport)
12020 					continue;
12021 				list_move_tail(&iocb->list, &completions);
12022 			}
12023 			spin_unlock(&pring->ring_lock);
12024 			list_for_each_entry_safe(iocb, next_iocb,
12025 						 &pring->txcmplq, list) {
12026 				if (iocb->vport != vport)
12027 					continue;
12028 				lpfc_sli_issue_abort_iotag(phba, pring, iocb,
12029 							   NULL);
12030 			}
12031 			pring->flag = prev_pring_flag;
12032 		}
12033 	}
12034 	spin_unlock_irqrestore(&phba->hbalock, flags);
12035 
12036 	/* Make sure HBA is alive */
12037 	lpfc_issue_hb_tmo(phba);
12038 
12039 	/* Cancel all the IOCBs from the completions list */
12040 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
12041 			      IOERR_SLI_DOWN);
12042 	return 1;
12043 }
12044 
12045 /**
12046  * lpfc_sli_hba_down - Resource cleanup function for the HBA
12047  * @phba: Pointer to HBA context object.
12048  *
12049  * This function cleans up all iocb, buffers, mailbox commands
12050  * while shutting down the HBA. This function is called with no
12051  * lock held and always returns 1.
12052  * This function does the following to cleanup driver resources:
12053  * - Free discovery resources for each virtual port
12054  * - Cleanup any pending fabric iocbs
12055  * - Iterate through the iocb txq and free each entry
12056  *   in the list.
12057  * - Free up any buffer posted to the HBA
12058  * - Free mailbox commands in the mailbox queue.
12059  **/
12060 int
12061 lpfc_sli_hba_down(struct lpfc_hba *phba)
12062 {
12063 	LIST_HEAD(completions);
12064 	struct lpfc_sli *psli = &phba->sli;
12065 	struct lpfc_queue *qp = NULL;
12066 	struct lpfc_sli_ring *pring;
12067 	struct lpfc_dmabuf *buf_ptr;
12068 	unsigned long flags = 0;
12069 	int i;
12070 
12071 	/* Shutdown the mailbox command sub-system */
12072 	lpfc_sli_mbox_sys_shutdown(phba, LPFC_MBX_WAIT);
12073 
12074 	lpfc_hba_down_prep(phba);
12075 
12076 	/* Disable softirqs, including timers from obtaining phba->hbalock */
12077 	local_bh_disable();
12078 
12079 	lpfc_fabric_abort_hba(phba);
12080 
12081 	spin_lock_irqsave(&phba->hbalock, flags);
12082 
12083 	/*
12084 	 * Error everything on the txq since these iocbs
12085 	 * have not been given to the FW yet.
12086 	 */
12087 	if (phba->sli_rev != LPFC_SLI_REV4) {
12088 		for (i = 0; i < psli->num_rings; i++) {
12089 			pring = &psli->sli3_ring[i];
12090 			/* Only slow rings */
12091 			if (pring->ringno == LPFC_ELS_RING) {
12092 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
12093 				/* Set the lpfc data pending flag */
12094 				set_bit(LPFC_DATA_READY, &phba->data_flags);
12095 			}
12096 			list_splice_init(&pring->txq, &completions);
12097 		}
12098 	} else {
12099 		list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
12100 			pring = qp->pring;
12101 			if (!pring)
12102 				continue;
12103 			spin_lock(&pring->ring_lock);
12104 			list_splice_init(&pring->txq, &completions);
12105 			spin_unlock(&pring->ring_lock);
12106 			if (pring == phba->sli4_hba.els_wq->pring) {
12107 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
12108 				/* Set the lpfc data pending flag */
12109 				set_bit(LPFC_DATA_READY, &phba->data_flags);
12110 			}
12111 		}
12112 	}
12113 	spin_unlock_irqrestore(&phba->hbalock, flags);
12114 
12115 	/* Cancel all the IOCBs from the completions list */
12116 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
12117 			      IOERR_SLI_DOWN);
12118 
12119 	spin_lock_irqsave(&phba->hbalock, flags);
12120 	list_splice_init(&phba->elsbuf, &completions);
12121 	phba->elsbuf_cnt = 0;
12122 	phba->elsbuf_prev_cnt = 0;
12123 	spin_unlock_irqrestore(&phba->hbalock, flags);
12124 
12125 	while (!list_empty(&completions)) {
12126 		list_remove_head(&completions, buf_ptr,
12127 			struct lpfc_dmabuf, list);
12128 		lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
12129 		kfree(buf_ptr);
12130 	}
12131 
12132 	/* Enable softirqs again, done with phba->hbalock */
12133 	local_bh_enable();
12134 
12135 	/* Return any active mbox cmds */
12136 	timer_delete_sync(&psli->mbox_tmo);
12137 
12138 	spin_lock_irqsave(&phba->pport->work_port_lock, flags);
12139 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
12140 	spin_unlock_irqrestore(&phba->pport->work_port_lock, flags);
12141 
12142 	return 1;
12143 }
12144 
12145 /**
12146  * lpfc_sli_pcimem_bcopy - SLI memory copy function
12147  * @srcp: Source memory pointer.
12148  * @destp: Destination memory pointer.
12149  * @cnt: Number of words required to be copied.
12150  *
12151  * This function is used for copying data between driver memory
12152  * and the SLI memory. This function also changes the endianness
12153  * of each word if native endianness is different from SLI
12154  * endianness. This function can be called with or without
12155  * lock.
12156  **/
12157 void
12158 lpfc_sli_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
12159 {
12160 	uint32_t *src = srcp;
12161 	uint32_t *dest = destp;
12162 	uint32_t ldata;
12163 	int i;
12164 
12165 	for (i = 0; i < (int)cnt; i += sizeof (uint32_t)) {
12166 		ldata = *src;
12167 		ldata = le32_to_cpu(ldata);
12168 		*dest = ldata;
12169 		src++;
12170 		dest++;
12171 	}
12172 }
12173 
12174 
12175 /**
12176  * lpfc_sli_bemem_bcopy - SLI memory copy function
12177  * @srcp: Source memory pointer.
12178  * @destp: Destination memory pointer.
12179  * @cnt: Number of words required to be copied.
12180  *
12181  * This function is used for copying data between a data structure
12182  * with big endian representation to local endianness.
12183  * This function can be called with or without lock.
12184  **/
12185 void
12186 lpfc_sli_bemem_bcopy(void *srcp, void *destp, uint32_t cnt)
12187 {
12188 	uint32_t *src = srcp;
12189 	uint32_t *dest = destp;
12190 	uint32_t ldata;
12191 	int i;
12192 
12193 	for (i = 0; i < (int)cnt; i += sizeof(uint32_t)) {
12194 		ldata = *src;
12195 		ldata = be32_to_cpu(ldata);
12196 		*dest = ldata;
12197 		src++;
12198 		dest++;
12199 	}
12200 }
12201 
12202 /**
12203  * lpfc_sli_ringpostbuf_put - Function to add a buffer to postbufq
12204  * @phba: Pointer to HBA context object.
12205  * @pring: Pointer to driver SLI ring object.
12206  * @mp: Pointer to driver buffer object.
12207  *
12208  * This function is called with no lock held.
12209  * It always return zero after adding the buffer to the postbufq
12210  * buffer list.
12211  **/
12212 int
12213 lpfc_sli_ringpostbuf_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12214 			 struct lpfc_dmabuf *mp)
12215 {
12216 	/* Stick struct lpfc_dmabuf at end of postbufq so driver can look it up
12217 	   later */
12218 	spin_lock_irq(&phba->hbalock);
12219 	list_add_tail(&mp->list, &pring->postbufq);
12220 	pring->postbufq_cnt++;
12221 	spin_unlock_irq(&phba->hbalock);
12222 	return 0;
12223 }
12224 
12225 /**
12226  * lpfc_sli_get_buffer_tag - allocates a tag for a CMD_QUE_XRI64_CX buffer
12227  * @phba: Pointer to HBA context object.
12228  *
12229  * When HBQ is enabled, buffers are searched based on tags. This function
12230  * allocates a tag for buffer posted using CMD_QUE_XRI64_CX iocb. The
12231  * tag is bit wise or-ed with QUE_BUFTAG_BIT to make sure that the tag
12232  * does not conflict with tags of buffer posted for unsolicited events.
12233  * The function returns the allocated tag. The function is called with
12234  * no locks held.
12235  **/
12236 uint32_t
12237 lpfc_sli_get_buffer_tag(struct lpfc_hba *phba)
12238 {
12239 	spin_lock_irq(&phba->hbalock);
12240 	phba->buffer_tag_count++;
12241 	/*
12242 	 * Always set the QUE_BUFTAG_BIT to distiguish between
12243 	 * a tag assigned by HBQ.
12244 	 */
12245 	phba->buffer_tag_count |= QUE_BUFTAG_BIT;
12246 	spin_unlock_irq(&phba->hbalock);
12247 	return phba->buffer_tag_count;
12248 }
12249 
12250 /**
12251  * lpfc_sli_ring_taggedbuf_get - find HBQ buffer associated with given tag
12252  * @phba: Pointer to HBA context object.
12253  * @pring: Pointer to driver SLI ring object.
12254  * @tag: Buffer tag.
12255  *
12256  * Buffers posted using CMD_QUE_XRI64_CX iocb are in pring->postbufq
12257  * list. After HBA DMA data to these buffers, CMD_IOCB_RET_XRI64_CX
12258  * iocb is posted to the response ring with the tag of the buffer.
12259  * This function searches the pring->postbufq list using the tag
12260  * to find buffer associated with CMD_IOCB_RET_XRI64_CX
12261  * iocb. If the buffer is found then lpfc_dmabuf object of the
12262  * buffer is returned to the caller else NULL is returned.
12263  * This function is called with no lock held.
12264  **/
12265 struct lpfc_dmabuf *
12266 lpfc_sli_ring_taggedbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12267 			uint32_t tag)
12268 {
12269 	struct lpfc_dmabuf *mp, *next_mp;
12270 	struct list_head *slp = &pring->postbufq;
12271 
12272 	/* Search postbufq, from the beginning, looking for a match on tag */
12273 	spin_lock_irq(&phba->hbalock);
12274 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
12275 		if (mp->buffer_tag == tag) {
12276 			list_del_init(&mp->list);
12277 			pring->postbufq_cnt--;
12278 			spin_unlock_irq(&phba->hbalock);
12279 			return mp;
12280 		}
12281 	}
12282 
12283 	spin_unlock_irq(&phba->hbalock);
12284 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12285 			"0402 Cannot find virtual addr for buffer tag on "
12286 			"ring %d Data x%lx x%px x%px x%x\n",
12287 			pring->ringno, (unsigned long) tag,
12288 			slp->next, slp->prev, pring->postbufq_cnt);
12289 
12290 	return NULL;
12291 }
12292 
12293 /**
12294  * lpfc_sli_ringpostbuf_get - search buffers for unsolicited CT and ELS events
12295  * @phba: Pointer to HBA context object.
12296  * @pring: Pointer to driver SLI ring object.
12297  * @phys: DMA address of the buffer.
12298  *
12299  * This function searches the buffer list using the dma_address
12300  * of unsolicited event to find the driver's lpfc_dmabuf object
12301  * corresponding to the dma_address. The function returns the
12302  * lpfc_dmabuf object if a buffer is found else it returns NULL.
12303  * This function is called by the ct and els unsolicited event
12304  * handlers to get the buffer associated with the unsolicited
12305  * event.
12306  *
12307  * This function is called with no lock held.
12308  **/
12309 struct lpfc_dmabuf *
12310 lpfc_sli_ringpostbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12311 			 dma_addr_t phys)
12312 {
12313 	struct lpfc_dmabuf *mp, *next_mp;
12314 	struct list_head *slp = &pring->postbufq;
12315 
12316 	/* Search postbufq, from the beginning, looking for a match on phys */
12317 	spin_lock_irq(&phba->hbalock);
12318 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
12319 		if (mp->phys == phys) {
12320 			list_del_init(&mp->list);
12321 			pring->postbufq_cnt--;
12322 			spin_unlock_irq(&phba->hbalock);
12323 			return mp;
12324 		}
12325 	}
12326 
12327 	spin_unlock_irq(&phba->hbalock);
12328 	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12329 			"0410 Cannot find virtual addr for mapped buf on "
12330 			"ring %d Data x%llx x%px x%px x%x\n",
12331 			pring->ringno, (unsigned long long)phys,
12332 			slp->next, slp->prev, pring->postbufq_cnt);
12333 	return NULL;
12334 }
12335 
12336 /**
12337  * lpfc_sli_abort_els_cmpl - Completion handler for the els abort iocbs
12338  * @phba: Pointer to HBA context object.
12339  * @cmdiocb: Pointer to driver command iocb object.
12340  * @rspiocb: Pointer to driver response iocb object.
12341  *
12342  * This function is the completion handler for the abort iocbs for
12343  * ELS commands. This function is called from the ELS ring event
12344  * handler with no lock held. This function frees memory resources
12345  * associated with the abort iocb.
12346  **/
12347 static void
12348 lpfc_sli_abort_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12349 			struct lpfc_iocbq *rspiocb)
12350 {
12351 	u32 ulp_status = get_job_ulpstatus(phba, rspiocb);
12352 	u32 ulp_word4 = get_job_word4(phba, rspiocb);
12353 	u8 cmnd = get_job_cmnd(phba, cmdiocb);
12354 
12355 	if (ulp_status) {
12356 		/*
12357 		 * Assume that the port already completed and returned, or
12358 		 * will return the iocb. Just Log the message.
12359 		 */
12360 		if (phba->sli_rev < LPFC_SLI_REV4) {
12361 			if (cmnd == CMD_ABORT_XRI_CX &&
12362 			    ulp_status == IOSTAT_LOCAL_REJECT &&
12363 			    ulp_word4 == IOERR_ABORT_REQUESTED) {
12364 				goto release_iocb;
12365 			}
12366 		}
12367 	}
12368 
12369 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS | LOG_SLI,
12370 			"0327 Abort els iocb complete x%px with io cmd xri %x "
12371 			"abort tag x%x abort status %x abort code %x\n",
12372 			cmdiocb, get_job_abtsiotag(phba, cmdiocb),
12373 			(phba->sli_rev == LPFC_SLI_REV4) ?
12374 			get_wqe_reqtag(cmdiocb) :
12375 			cmdiocb->iocb.ulpIoTag,
12376 			ulp_status, ulp_word4);
12377 release_iocb:
12378 	lpfc_sli_release_iocbq(phba, cmdiocb);
12379 	return;
12380 }
12381 
12382 /**
12383  * lpfc_ignore_els_cmpl - Completion handler for aborted ELS command
12384  * @phba: Pointer to HBA context object.
12385  * @cmdiocb: Pointer to driver command iocb object.
12386  * @rspiocb: Pointer to driver response iocb object.
12387  *
12388  * The function is called from SLI ring event handler with no
12389  * lock held. This function is the completion handler for ELS commands
12390  * which are aborted. The function frees memory resources used for
12391  * the aborted ELS commands.
12392  **/
12393 void
12394 lpfc_ignore_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12395 		     struct lpfc_iocbq *rspiocb)
12396 {
12397 	struct lpfc_nodelist *ndlp = cmdiocb->ndlp;
12398 	IOCB_t *irsp;
12399 	LPFC_MBOXQ_t *mbox;
12400 	u32 ulp_command, ulp_status, ulp_word4, iotag;
12401 
12402 	ulp_command = get_job_cmnd(phba, cmdiocb);
12403 	ulp_status = get_job_ulpstatus(phba, rspiocb);
12404 	ulp_word4 = get_job_word4(phba, rspiocb);
12405 
12406 	if (phba->sli_rev == LPFC_SLI_REV4) {
12407 		iotag = get_wqe_reqtag(cmdiocb);
12408 	} else {
12409 		irsp = &rspiocb->iocb;
12410 		iotag = irsp->ulpIoTag;
12411 
12412 		/* It is possible a PLOGI_RJT for NPIV ports to get aborted.
12413 		 * The MBX_REG_LOGIN64 mbox command is freed back to the
12414 		 * mbox_mem_pool here.
12415 		 */
12416 		if (cmdiocb->context_un.mbox) {
12417 			mbox = cmdiocb->context_un.mbox;
12418 			lpfc_mbox_rsrc_cleanup(phba, mbox, MBOX_THD_UNLOCKED);
12419 			cmdiocb->context_un.mbox = NULL;
12420 		}
12421 	}
12422 
12423 	/* ELS cmd tag <ulpIoTag> completes */
12424 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
12425 			"0139 Ignoring ELS cmd code x%x ref cnt x%x Data: "
12426 			"x%x x%x x%x x%px\n",
12427 			ulp_command, kref_read(&cmdiocb->ndlp->kref),
12428 			ulp_status, ulp_word4, iotag, cmdiocb->ndlp);
12429 	/*
12430 	 * Deref the ndlp after free_iocb. sli_release_iocb will access the ndlp
12431 	 * if exchange is busy.
12432 	 */
12433 	if (ulp_command == CMD_GEN_REQUEST64_CR)
12434 		lpfc_ct_free_iocb(phba, cmdiocb);
12435 	else
12436 		lpfc_els_free_iocb(phba, cmdiocb);
12437 
12438 	lpfc_nlp_put(ndlp);
12439 }
12440 
12441 /**
12442  * lpfc_sli_issue_abort_iotag - Abort function for a command iocb
12443  * @phba: Pointer to HBA context object.
12444  * @pring: Pointer to driver SLI ring object.
12445  * @cmdiocb: Pointer to driver command iocb object.
12446  * @cmpl: completion function.
12447  *
12448  * This function issues an abort iocb for the provided command iocb. In case
12449  * of unloading, the abort iocb will not be issued to commands on the ELS
12450  * ring. Instead, the callback function shall be changed to those commands
12451  * so that nothing happens when them finishes. This function is called with
12452  * hbalock held andno ring_lock held (SLI4). The function returns IOCB_SUCCESS
12453  * when the command iocb is an abort request.
12454  *
12455  **/
12456 int
12457 lpfc_sli_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12458 			   struct lpfc_iocbq *cmdiocb, void *cmpl)
12459 {
12460 	struct lpfc_vport *vport = cmdiocb->vport;
12461 	struct lpfc_iocbq *abtsiocbp;
12462 	int retval = IOCB_ERROR;
12463 	unsigned long iflags;
12464 	struct lpfc_nodelist *ndlp = NULL;
12465 	u32 ulp_command = get_job_cmnd(phba, cmdiocb);
12466 	u16 ulp_context, iotag;
12467 	bool ia;
12468 
12469 	/*
12470 	 * There are certain command types we don't want to abort.  And we
12471 	 * don't want to abort commands that are already in the process of
12472 	 * being aborted.
12473 	 */
12474 	if (ulp_command == CMD_ABORT_XRI_WQE ||
12475 	    ulp_command == CMD_ABORT_XRI_CN ||
12476 	    ulp_command == CMD_CLOSE_XRI_CN ||
12477 	    cmdiocb->cmd_flag & LPFC_DRIVER_ABORTED)
12478 		return IOCB_ABORTING;
12479 
12480 	if (!pring) {
12481 		if (cmdiocb->cmd_flag & LPFC_IO_FABRIC)
12482 			cmdiocb->fabric_cmd_cmpl = lpfc_ignore_els_cmpl;
12483 		else
12484 			cmdiocb->cmd_cmpl = lpfc_ignore_els_cmpl;
12485 		return retval;
12486 	}
12487 
12488 	/*
12489 	 * Always abort the outstanding WQE and set the IA bit correctly
12490 	 * for the context.  This is necessary for correctly removing
12491 	 * outstanding ndlp reference counts when the CQE completes with
12492 	 * the XB bit set.
12493 	 */
12494 	abtsiocbp = __lpfc_sli_get_iocbq(phba);
12495 	if (abtsiocbp == NULL)
12496 		return IOCB_NORESOURCE;
12497 
12498 	/* This signals the response to set the correct status
12499 	 * before calling the completion handler
12500 	 */
12501 	cmdiocb->cmd_flag |= LPFC_DRIVER_ABORTED;
12502 
12503 	if (phba->sli_rev == LPFC_SLI_REV4) {
12504 		ulp_context = cmdiocb->sli4_xritag;
12505 		iotag = abtsiocbp->iotag;
12506 	} else {
12507 		iotag = cmdiocb->iocb.ulpIoTag;
12508 		if (pring->ringno == LPFC_ELS_RING) {
12509 			ndlp = cmdiocb->ndlp;
12510 			ulp_context = ndlp->nlp_rpi;
12511 		} else {
12512 			ulp_context = cmdiocb->iocb.ulpContext;
12513 		}
12514 	}
12515 
12516 	/* Just close the exchange under certain conditions. */
12517 	if (test_bit(FC_UNLOADING, &vport->load_flag) ||
12518 	    phba->link_state < LPFC_LINK_UP ||
12519 	    (phba->sli_rev == LPFC_SLI_REV4 &&
12520 	     phba->sli4_hba.link_state.status == LPFC_FC_LA_TYPE_LINK_DOWN) ||
12521 	    (phba->link_flag & LS_EXTERNAL_LOOPBACK))
12522 		ia = true;
12523 	else
12524 		ia = false;
12525 
12526 	lpfc_sli_prep_abort_xri(phba, abtsiocbp, ulp_context, iotag,
12527 				cmdiocb->iocb.ulpClass,
12528 				LPFC_WQE_CQ_ID_DEFAULT, ia, false);
12529 
12530 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
12531 	abtsiocbp->hba_wqidx = cmdiocb->hba_wqidx;
12532 	if (cmdiocb->cmd_flag & LPFC_IO_FCP)
12533 		abtsiocbp->cmd_flag |= (LPFC_IO_FCP | LPFC_USE_FCPWQIDX);
12534 
12535 	if (cmdiocb->cmd_flag & LPFC_IO_FOF)
12536 		abtsiocbp->cmd_flag |= LPFC_IO_FOF;
12537 
12538 	if (cmpl)
12539 		abtsiocbp->cmd_cmpl = cmpl;
12540 	else
12541 		abtsiocbp->cmd_cmpl = lpfc_sli_abort_els_cmpl;
12542 	abtsiocbp->vport = vport;
12543 
12544 	if (phba->sli_rev == LPFC_SLI_REV4) {
12545 		pring = lpfc_sli4_calc_ring(phba, abtsiocbp);
12546 		if (unlikely(pring == NULL))
12547 			goto abort_iotag_exit;
12548 		/* Note: both hbalock and ring_lock need to be set here */
12549 		spin_lock_irqsave(&pring->ring_lock, iflags);
12550 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
12551 			abtsiocbp, 0);
12552 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
12553 	} else {
12554 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
12555 			abtsiocbp, 0);
12556 	}
12557 
12558 abort_iotag_exit:
12559 
12560 	lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI,
12561 			 "0339 Abort IO XRI x%x, Original iotag x%x, "
12562 			 "abort tag x%x Cmdjob : x%px Abortjob : x%px "
12563 			 "retval x%x : IA %d cmd_cmpl %ps\n",
12564 			 ulp_context, (phba->sli_rev == LPFC_SLI_REV4) ?
12565 			 cmdiocb->iotag : iotag, iotag, cmdiocb, abtsiocbp,
12566 			 retval, ia, abtsiocbp->cmd_cmpl);
12567 	if (retval) {
12568 		cmdiocb->cmd_flag &= ~LPFC_DRIVER_ABORTED;
12569 		__lpfc_sli_release_iocbq(phba, abtsiocbp);
12570 	}
12571 
12572 	/*
12573 	 * Caller to this routine should check for IOCB_ERROR
12574 	 * and handle it properly.  This routine no longer removes
12575 	 * iocb off txcmplq and call compl in case of IOCB_ERROR.
12576 	 */
12577 	return retval;
12578 }
12579 
12580 /**
12581  * lpfc_sli_hba_iocb_abort - Abort all iocbs to an hba.
12582  * @phba: pointer to lpfc HBA data structure.
12583  *
12584  * This routine will abort all pending and outstanding iocbs to an HBA.
12585  **/
12586 void
12587 lpfc_sli_hba_iocb_abort(struct lpfc_hba *phba)
12588 {
12589 	struct lpfc_sli *psli = &phba->sli;
12590 	struct lpfc_sli_ring *pring;
12591 	struct lpfc_queue *qp = NULL;
12592 	int i;
12593 
12594 	if (phba->sli_rev != LPFC_SLI_REV4) {
12595 		for (i = 0; i < psli->num_rings; i++) {
12596 			pring = &psli->sli3_ring[i];
12597 			lpfc_sli_abort_iocb_ring(phba, pring);
12598 		}
12599 		return;
12600 	}
12601 	list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
12602 		pring = qp->pring;
12603 		if (!pring)
12604 			continue;
12605 		lpfc_sli_abort_iocb_ring(phba, pring);
12606 	}
12607 }
12608 
12609 /**
12610  * lpfc_sli_validate_fcp_iocb_for_abort - filter iocbs appropriate for FCP aborts
12611  * @iocbq: Pointer to iocb object.
12612  * @vport: Pointer to driver virtual port object.
12613  *
12614  * This function acts as an iocb filter for functions which abort FCP iocbs.
12615  *
12616  * Return values
12617  * -ENODEV, if a null iocb or vport ptr is encountered
12618  * -EINVAL, if the iocb is not an FCP I/O, not on the TX cmpl queue, premarked as
12619  *          driver already started the abort process, or is an abort iocb itself
12620  * 0, passes criteria for aborting the FCP I/O iocb
12621  **/
12622 static int
12623 lpfc_sli_validate_fcp_iocb_for_abort(struct lpfc_iocbq *iocbq,
12624 				     struct lpfc_vport *vport)
12625 {
12626 	u8 ulp_command;
12627 
12628 	/* No null ptr vports */
12629 	if (!iocbq || iocbq->vport != vport)
12630 		return -ENODEV;
12631 
12632 	/* iocb must be for FCP IO, already exists on the TX cmpl queue,
12633 	 * can't be premarked as driver aborted, nor be an ABORT iocb itself
12634 	 */
12635 	ulp_command = get_job_cmnd(vport->phba, iocbq);
12636 	if (!(iocbq->cmd_flag & LPFC_IO_FCP) ||
12637 	    !(iocbq->cmd_flag & LPFC_IO_ON_TXCMPLQ) ||
12638 	    (iocbq->cmd_flag & LPFC_DRIVER_ABORTED) ||
12639 	    (ulp_command == CMD_ABORT_XRI_CN ||
12640 	     ulp_command == CMD_CLOSE_XRI_CN ||
12641 	     ulp_command == CMD_ABORT_XRI_WQE))
12642 		return -EINVAL;
12643 
12644 	return 0;
12645 }
12646 
12647 /**
12648  * lpfc_sli_validate_fcp_iocb - validate commands associated with a SCSI target
12649  * @iocbq: Pointer to driver iocb object.
12650  * @vport: Pointer to driver virtual port object.
12651  * @tgt_id: SCSI ID of the target.
12652  * @lun_id: LUN ID of the scsi device.
12653  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST
12654  *
12655  * This function acts as an iocb filter for validating a lun/SCSI target/SCSI
12656  * host.
12657  *
12658  * It will return
12659  * 0 if the filtering criteria is met for the given iocb and will return
12660  * 1 if the filtering criteria is not met.
12661  * If ctx_cmd == LPFC_CTX_LUN, the function returns 0 only if the
12662  * given iocb is for the SCSI device specified by vport, tgt_id and
12663  * lun_id parameter.
12664  * If ctx_cmd == LPFC_CTX_TGT,  the function returns 0 only if the
12665  * given iocb is for the SCSI target specified by vport and tgt_id
12666  * parameters.
12667  * If ctx_cmd == LPFC_CTX_HOST, the function returns 0 only if the
12668  * given iocb is for the SCSI host associated with the given vport.
12669  * This function is called with no locks held.
12670  **/
12671 static int
12672 lpfc_sli_validate_fcp_iocb(struct lpfc_iocbq *iocbq, struct lpfc_vport *vport,
12673 			   uint16_t tgt_id, uint64_t lun_id,
12674 			   lpfc_ctx_cmd ctx_cmd)
12675 {
12676 	struct lpfc_io_buf *lpfc_cmd;
12677 	int rc = 1;
12678 
12679 	lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
12680 
12681 	if (lpfc_cmd->pCmd == NULL)
12682 		return rc;
12683 
12684 	switch (ctx_cmd) {
12685 	case LPFC_CTX_LUN:
12686 		if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
12687 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id) &&
12688 		    (scsilun_to_int(&lpfc_cmd->fcp_cmnd->fcp_lun) == lun_id))
12689 			rc = 0;
12690 		break;
12691 	case LPFC_CTX_TGT:
12692 		if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
12693 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id))
12694 			rc = 0;
12695 		break;
12696 	case LPFC_CTX_HOST:
12697 		rc = 0;
12698 		break;
12699 	default:
12700 		printk(KERN_ERR "%s: Unknown context cmd type, value %d\n",
12701 			__func__, ctx_cmd);
12702 		break;
12703 	}
12704 
12705 	return rc;
12706 }
12707 
12708 /**
12709  * lpfc_sli_sum_iocb - Function to count the number of FCP iocbs pending
12710  * @vport: Pointer to virtual port.
12711  * @tgt_id: SCSI ID of the target.
12712  * @lun_id: LUN ID of the scsi device.
12713  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12714  *
12715  * This function returns number of FCP commands pending for the vport.
12716  * When ctx_cmd == LPFC_CTX_LUN, the function returns number of FCP
12717  * commands pending on the vport associated with SCSI device specified
12718  * by tgt_id and lun_id parameters.
12719  * When ctx_cmd == LPFC_CTX_TGT, the function returns number of FCP
12720  * commands pending on the vport associated with SCSI target specified
12721  * by tgt_id parameter.
12722  * When ctx_cmd == LPFC_CTX_HOST, the function returns number of FCP
12723  * commands pending on the vport.
12724  * This function returns the number of iocbs which satisfy the filter.
12725  * This function is called without any lock held.
12726  **/
12727 int
12728 lpfc_sli_sum_iocb(struct lpfc_vport *vport, uint16_t tgt_id, uint64_t lun_id,
12729 		  lpfc_ctx_cmd ctx_cmd)
12730 {
12731 	struct lpfc_hba *phba = vport->phba;
12732 	struct lpfc_iocbq *iocbq;
12733 	int sum, i;
12734 	unsigned long iflags;
12735 	u8 ulp_command;
12736 
12737 	spin_lock_irqsave(&phba->hbalock, iflags);
12738 	for (i = 1, sum = 0; i <= phba->sli.last_iotag; i++) {
12739 		iocbq = phba->sli.iocbq_lookup[i];
12740 
12741 		if (!iocbq || iocbq->vport != vport)
12742 			continue;
12743 		/* Only count FCP i/o */
12744 		if (!(iocbq->cmd_flag & LPFC_IO_FCP))
12745 			continue;
12746 		/* Count i/o whilst LLDD retains an interest in the scsi_cmnd */
12747 		if (!(iocbq->cmd_flag &
12748 				(LPFC_IO_ON_TXCMPLQ | LPFC_DRIVER_ABORTED)))
12749 			continue;
12750 
12751 		/* Include counting outstanding aborts */
12752 		ulp_command = get_job_cmnd(phba, iocbq);
12753 		if (ulp_command == CMD_ABORT_XRI_CN ||
12754 		    ulp_command == CMD_CLOSE_XRI_CN ||
12755 		    ulp_command == CMD_ABORT_XRI_WQE) {
12756 			sum++;
12757 			continue;
12758 		}
12759 
12760 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12761 					       ctx_cmd) == 0)
12762 			sum++;
12763 	}
12764 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12765 
12766 	return sum;
12767 }
12768 
12769 /**
12770  * lpfc_sli_abort_fcp_cmpl - Completion handler function for aborted FCP IOCBs
12771  * @phba: Pointer to HBA context object
12772  * @cmdiocb: Pointer to command iocb object.
12773  * @rspiocb: Pointer to response iocb object.
12774  *
12775  * This function is called when an aborted FCP iocb completes. This
12776  * function is called by the ring event handler with no lock held.
12777  * This function frees the iocb.
12778  **/
12779 void
12780 lpfc_sli_abort_fcp_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12781 			struct lpfc_iocbq *rspiocb)
12782 {
12783 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12784 			"3096 ABORT_XRI_CX completing on rpi x%x "
12785 			"original iotag x%x, abort cmd iotag x%x "
12786 			"status 0x%x, reason 0x%x\n",
12787 			(phba->sli_rev == LPFC_SLI_REV4) ?
12788 			cmdiocb->sli4_xritag :
12789 			cmdiocb->iocb.un.acxri.abortContextTag,
12790 			get_job_abtsiotag(phba, cmdiocb),
12791 			cmdiocb->iotag, get_job_ulpstatus(phba, rspiocb),
12792 			get_job_word4(phba, rspiocb));
12793 	lpfc_sli_release_iocbq(phba, cmdiocb);
12794 	return;
12795 }
12796 
12797 /**
12798  * lpfc_sli_abort_iocb - issue abort for all commands on a host/target/LUN
12799  * @vport: Pointer to virtual port.
12800  * @tgt_id: SCSI ID of the target.
12801  * @lun_id: LUN ID of the scsi device.
12802  * @abort_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12803  *
12804  * This function sends an abort command for every SCSI command
12805  * associated with the given virtual port pending on the ring
12806  * filtered by lpfc_sli_validate_fcp_iocb_for_abort and then
12807  * lpfc_sli_validate_fcp_iocb function.  The ordering for validation before
12808  * submitting abort iocbs must be lpfc_sli_validate_fcp_iocb_for_abort
12809  * followed by lpfc_sli_validate_fcp_iocb.
12810  *
12811  * When abort_cmd == LPFC_CTX_LUN, the function sends abort only to the
12812  * FCP iocbs associated with lun specified by tgt_id and lun_id
12813  * parameters
12814  * When abort_cmd == LPFC_CTX_TGT, the function sends abort only to the
12815  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
12816  * When abort_cmd == LPFC_CTX_HOST, the function sends abort to all
12817  * FCP iocbs associated with virtual port.
12818  * The pring used for SLI3 is sli3_ring[LPFC_FCP_RING], for SLI4
12819  * lpfc_sli4_calc_ring is used.
12820  * This function returns number of iocbs it failed to abort.
12821  * This function is called with no locks held.
12822  **/
12823 int
12824 lpfc_sli_abort_iocb(struct lpfc_vport *vport, u16 tgt_id, u64 lun_id,
12825 		    lpfc_ctx_cmd abort_cmd)
12826 {
12827 	struct lpfc_hba *phba = vport->phba;
12828 	struct lpfc_sli_ring *pring = NULL;
12829 	struct lpfc_iocbq *iocbq;
12830 	int errcnt = 0, ret_val = 0;
12831 	unsigned long iflags;
12832 	int i;
12833 
12834 	/* all I/Os are in process of being flushed */
12835 	if (test_bit(HBA_IOQ_FLUSH, &phba->hba_flag))
12836 		return errcnt;
12837 
12838 	for (i = 1; i <= phba->sli.last_iotag; i++) {
12839 		iocbq = phba->sli.iocbq_lookup[i];
12840 
12841 		if (lpfc_sli_validate_fcp_iocb_for_abort(iocbq, vport))
12842 			continue;
12843 
12844 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12845 					       abort_cmd) != 0)
12846 			continue;
12847 
12848 		spin_lock_irqsave(&phba->hbalock, iflags);
12849 		if (phba->sli_rev == LPFC_SLI_REV3) {
12850 			pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
12851 		} else if (phba->sli_rev == LPFC_SLI_REV4) {
12852 			pring = lpfc_sli4_calc_ring(phba, iocbq);
12853 		}
12854 		ret_val = lpfc_sli_issue_abort_iotag(phba, pring, iocbq,
12855 						     lpfc_sli_abort_fcp_cmpl);
12856 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12857 		if (ret_val != IOCB_SUCCESS)
12858 			errcnt++;
12859 	}
12860 
12861 	return errcnt;
12862 }
12863 
12864 /**
12865  * lpfc_sli_abort_taskmgmt - issue abort for all commands on a host/target/LUN
12866  * @vport: Pointer to virtual port.
12867  * @pring: Pointer to driver SLI ring object.
12868  * @tgt_id: SCSI ID of the target.
12869  * @lun_id: LUN ID of the scsi device.
12870  * @cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12871  *
12872  * This function sends an abort command for every SCSI command
12873  * associated with the given virtual port pending on the ring
12874  * filtered by lpfc_sli_validate_fcp_iocb_for_abort and then
12875  * lpfc_sli_validate_fcp_iocb function.  The ordering for validation before
12876  * submitting abort iocbs must be lpfc_sli_validate_fcp_iocb_for_abort
12877  * followed by lpfc_sli_validate_fcp_iocb.
12878  *
12879  * When taskmgmt_cmd == LPFC_CTX_LUN, the function sends abort only to the
12880  * FCP iocbs associated with lun specified by tgt_id and lun_id
12881  * parameters
12882  * When taskmgmt_cmd == LPFC_CTX_TGT, the function sends abort only to the
12883  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
12884  * When taskmgmt_cmd == LPFC_CTX_HOST, the function sends abort to all
12885  * FCP iocbs associated with virtual port.
12886  * This function returns number of iocbs it aborted .
12887  * This function is called with no locks held right after a taskmgmt
12888  * command is sent.
12889  **/
12890 int
12891 lpfc_sli_abort_taskmgmt(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
12892 			uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd cmd)
12893 	__context_unsafe(/*conditional locking*/)
12894 {
12895 	struct lpfc_hba *phba = vport->phba;
12896 	struct lpfc_io_buf *lpfc_cmd;
12897 	struct lpfc_iocbq *abtsiocbq;
12898 	struct lpfc_nodelist *ndlp = NULL;
12899 	struct lpfc_iocbq *iocbq;
12900 	int sum, i, ret_val;
12901 	unsigned long iflags;
12902 	struct lpfc_sli_ring *pring_s4 = NULL;
12903 	u16 ulp_context, iotag, cqid = LPFC_WQE_CQ_ID_DEFAULT;
12904 	bool ia;
12905 
12906 	/* all I/Os are in process of being flushed */
12907 	if (test_bit(HBA_IOQ_FLUSH, &phba->hba_flag))
12908 		return 0;
12909 
12910 	sum = 0;
12911 
12912 	spin_lock_irqsave(&phba->hbalock, iflags);
12913 	for (i = 1; i <= phba->sli.last_iotag; i++) {
12914 		iocbq = phba->sli.iocbq_lookup[i];
12915 
12916 		if (lpfc_sli_validate_fcp_iocb_for_abort(iocbq, vport))
12917 			continue;
12918 
12919 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12920 					       cmd) != 0)
12921 			continue;
12922 
12923 		/* Guard against IO completion being called at same time */
12924 		lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
12925 		spin_lock(&lpfc_cmd->buf_lock);
12926 
12927 		if (!lpfc_cmd->pCmd) {
12928 			spin_unlock(&lpfc_cmd->buf_lock);
12929 			continue;
12930 		}
12931 
12932 		if (phba->sli_rev == LPFC_SLI_REV4) {
12933 			pring_s4 =
12934 			    phba->sli4_hba.hdwq[iocbq->hba_wqidx].io_wq->pring;
12935 			if (!pring_s4) {
12936 				spin_unlock(&lpfc_cmd->buf_lock);
12937 				continue;
12938 			}
12939 			/* Note: both hbalock and ring_lock must be set here */
12940 			spin_lock(&pring_s4->ring_lock);
12941 		}
12942 
12943 		/*
12944 		 * If the iocbq is already being aborted, don't take a second
12945 		 * action, but do count it.
12946 		 */
12947 		if ((iocbq->cmd_flag & LPFC_DRIVER_ABORTED) ||
12948 		    !(iocbq->cmd_flag & LPFC_IO_ON_TXCMPLQ)) {
12949 			if (phba->sli_rev == LPFC_SLI_REV4)
12950 				spin_unlock(&pring_s4->ring_lock);
12951 			spin_unlock(&lpfc_cmd->buf_lock);
12952 			continue;
12953 		}
12954 
12955 		/* issue ABTS for this IOCB based on iotag */
12956 		abtsiocbq = __lpfc_sli_get_iocbq(phba);
12957 		if (!abtsiocbq) {
12958 			if (phba->sli_rev == LPFC_SLI_REV4)
12959 				spin_unlock(&pring_s4->ring_lock);
12960 			spin_unlock(&lpfc_cmd->buf_lock);
12961 			continue;
12962 		}
12963 
12964 		if (phba->sli_rev == LPFC_SLI_REV4) {
12965 			iotag = abtsiocbq->iotag;
12966 			ulp_context = iocbq->sli4_xritag;
12967 			cqid = lpfc_cmd->hdwq->io_cq_map;
12968 		} else {
12969 			iotag = iocbq->iocb.ulpIoTag;
12970 			if (pring->ringno == LPFC_ELS_RING) {
12971 				ndlp = iocbq->ndlp;
12972 				ulp_context = ndlp->nlp_rpi;
12973 			} else {
12974 				ulp_context = iocbq->iocb.ulpContext;
12975 			}
12976 		}
12977 
12978 		ndlp = lpfc_cmd->rdata->pnode;
12979 
12980 		if (lpfc_is_link_up(phba) &&
12981 		    (ndlp && ndlp->nlp_state == NLP_STE_MAPPED_NODE) &&
12982 		    !(phba->link_flag & LS_EXTERNAL_LOOPBACK))
12983 			ia = false;
12984 		else
12985 			ia = true;
12986 
12987 		lpfc_sli_prep_abort_xri(phba, abtsiocbq, ulp_context, iotag,
12988 					iocbq->iocb.ulpClass, cqid,
12989 					ia, false);
12990 
12991 		abtsiocbq->vport = vport;
12992 
12993 		/* ABTS WQE must go to the same WQ as the WQE to be aborted */
12994 		abtsiocbq->hba_wqidx = iocbq->hba_wqidx;
12995 		if (iocbq->cmd_flag & LPFC_IO_FCP)
12996 			abtsiocbq->cmd_flag |= LPFC_USE_FCPWQIDX;
12997 		if (iocbq->cmd_flag & LPFC_IO_FOF)
12998 			abtsiocbq->cmd_flag |= LPFC_IO_FOF;
12999 
13000 		/* Setup callback routine and issue the command. */
13001 		abtsiocbq->cmd_cmpl = lpfc_sli_abort_fcp_cmpl;
13002 
13003 		/*
13004 		 * Indicate the IO is being aborted by the driver and set
13005 		 * the caller's flag into the aborted IO.
13006 		 */
13007 		iocbq->cmd_flag |= LPFC_DRIVER_ABORTED;
13008 
13009 		if (phba->sli_rev == LPFC_SLI_REV4) {
13010 			ret_val = __lpfc_sli_issue_iocb(phba, pring_s4->ringno,
13011 							abtsiocbq, 0);
13012 			spin_unlock(&pring_s4->ring_lock);
13013 		} else {
13014 			ret_val = __lpfc_sli_issue_iocb(phba, pring->ringno,
13015 							abtsiocbq, 0);
13016 		}
13017 
13018 		spin_unlock(&lpfc_cmd->buf_lock);
13019 
13020 		if (ret_val == IOCB_ERROR)
13021 			__lpfc_sli_release_iocbq(phba, abtsiocbq);
13022 		else
13023 			sum++;
13024 	}
13025 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13026 	return sum;
13027 }
13028 
13029 /**
13030  * lpfc_sli_wake_iocb_wait - lpfc_sli_issue_iocb_wait's completion handler
13031  * @phba: Pointer to HBA context object.
13032  * @cmdiocbq: Pointer to command iocb.
13033  * @rspiocbq: Pointer to response iocb.
13034  *
13035  * This function is the completion handler for iocbs issued using
13036  * lpfc_sli_issue_iocb_wait function. This function is called by the
13037  * ring event handler function without any lock held. This function
13038  * can be called from both worker thread context and interrupt
13039  * context. This function also can be called from other thread which
13040  * cleans up the SLI layer objects.
13041  * This function copy the contents of the response iocb to the
13042  * response iocb memory object provided by the caller of
13043  * lpfc_sli_issue_iocb_wait and then wakes up the thread which
13044  * sleeps for the iocb completion.
13045  **/
13046 static void
13047 lpfc_sli_wake_iocb_wait(struct lpfc_hba *phba,
13048 			struct lpfc_iocbq *cmdiocbq,
13049 			struct lpfc_iocbq *rspiocbq)
13050 {
13051 	wait_queue_head_t *pdone_q;
13052 	unsigned long iflags;
13053 	struct lpfc_io_buf *lpfc_cmd;
13054 	size_t offset = offsetof(struct lpfc_iocbq, wqe);
13055 
13056 	spin_lock_irqsave(&phba->hbalock, iflags);
13057 	if (cmdiocbq->cmd_flag & LPFC_IO_WAKE_TMO) {
13058 
13059 		/*
13060 		 * A time out has occurred for the iocb.  If a time out
13061 		 * completion handler has been supplied, call it.  Otherwise,
13062 		 * just free the iocbq.
13063 		 */
13064 
13065 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13066 		cmdiocbq->cmd_cmpl = cmdiocbq->wait_cmd_cmpl;
13067 		cmdiocbq->wait_cmd_cmpl = NULL;
13068 		if (cmdiocbq->cmd_cmpl)
13069 			cmdiocbq->cmd_cmpl(phba, cmdiocbq, NULL);
13070 		else
13071 			lpfc_sli_release_iocbq(phba, cmdiocbq);
13072 		return;
13073 	}
13074 
13075 	/* Copy the contents of the local rspiocb into the caller's buffer. */
13076 	cmdiocbq->cmd_flag |= LPFC_IO_WAKE;
13077 	if (cmdiocbq->rsp_iocb && rspiocbq)
13078 		memcpy((char *)cmdiocbq->rsp_iocb + offset,
13079 		       (char *)rspiocbq + offset, sizeof(*rspiocbq) - offset);
13080 
13081 	/* Set the exchange busy flag for task management commands */
13082 	if ((cmdiocbq->cmd_flag & LPFC_IO_FCP) &&
13083 	    !(cmdiocbq->cmd_flag & LPFC_IO_LIBDFC)) {
13084 		lpfc_cmd = container_of(cmdiocbq, struct lpfc_io_buf,
13085 					cur_iocbq);
13086 		if (rspiocbq && (rspiocbq->cmd_flag & LPFC_EXCHANGE_BUSY))
13087 			lpfc_cmd->flags |= LPFC_SBUF_XBUSY;
13088 		else
13089 			lpfc_cmd->flags &= ~LPFC_SBUF_XBUSY;
13090 	}
13091 
13092 	pdone_q = cmdiocbq->context_un.wait_queue;
13093 	if (pdone_q)
13094 		wake_up(pdone_q);
13095 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13096 	return;
13097 }
13098 
13099 /**
13100  * lpfc_chk_iocb_flg - Test IOCB flag with lock held.
13101  * @phba: Pointer to HBA context object..
13102  * @piocbq: Pointer to command iocb.
13103  * @flag: Flag to test.
13104  *
13105  * This routine grabs the hbalock and then test the cmd_flag to
13106  * see if the passed in flag is set.
13107  * Returns:
13108  * 1 if flag is set.
13109  * 0 if flag is not set.
13110  **/
13111 static int
13112 lpfc_chk_iocb_flg(struct lpfc_hba *phba,
13113 		 struct lpfc_iocbq *piocbq, uint32_t flag)
13114 {
13115 	unsigned long iflags;
13116 	int ret;
13117 
13118 	spin_lock_irqsave(&phba->hbalock, iflags);
13119 	ret = piocbq->cmd_flag & flag;
13120 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13121 	return ret;
13122 
13123 }
13124 
13125 /**
13126  * lpfc_sli_issue_iocb_wait - Synchronous function to issue iocb commands
13127  * @phba: Pointer to HBA context object..
13128  * @ring_number: Ring number
13129  * @piocb: Pointer to command iocb.
13130  * @prspiocbq: Pointer to response iocb.
13131  * @timeout: Timeout in number of seconds.
13132  *
13133  * This function issues the iocb to firmware and waits for the
13134  * iocb to complete. The cmd_cmpl field of the shall be used
13135  * to handle iocbs which time out. If the field is NULL, the
13136  * function shall free the iocbq structure.  If more clean up is
13137  * needed, the caller is expected to provide a completion function
13138  * that will provide the needed clean up.  If the iocb command is
13139  * not completed within timeout seconds, the function will either
13140  * free the iocbq structure (if cmd_cmpl == NULL) or execute the
13141  * completion function set in the cmd_cmpl field and then return
13142  * a status of IOCB_TIMEDOUT.  The caller should not free the iocb
13143  * resources if this function returns IOCB_TIMEDOUT.
13144  * The function waits for the iocb completion using an
13145  * non-interruptible wait.
13146  * This function will sleep while waiting for iocb completion.
13147  * So, this function should not be called from any context which
13148  * does not allow sleeping. Due to the same reason, this function
13149  * cannot be called with interrupt disabled.
13150  * This function assumes that the iocb completions occur while
13151  * this function sleep. So, this function cannot be called from
13152  * the thread which process iocb completion for this ring.
13153  * This function clears the cmd_flag of the iocb object before
13154  * issuing the iocb and the iocb completion handler sets this
13155  * flag and wakes this thread when the iocb completes.
13156  * The contents of the response iocb will be copied to prspiocbq
13157  * by the completion handler when the command completes.
13158  * This function returns IOCB_SUCCESS when success.
13159  * This function is called with no lock held.
13160  **/
13161 int
13162 lpfc_sli_issue_iocb_wait(struct lpfc_hba *phba,
13163 			 uint32_t ring_number,
13164 			 struct lpfc_iocbq *piocb,
13165 			 struct lpfc_iocbq *prspiocbq,
13166 			 uint32_t timeout)
13167 {
13168 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(done_q);
13169 	long timeleft, timeout_req = 0;
13170 	int retval = IOCB_SUCCESS;
13171 	uint32_t creg_val;
13172 	struct lpfc_iocbq *iocb;
13173 	int txq_cnt = 0;
13174 	int txcmplq_cnt = 0;
13175 	struct lpfc_sli_ring *pring;
13176 	unsigned long iflags;
13177 	bool iocb_completed = true;
13178 
13179 	if (phba->sli_rev >= LPFC_SLI_REV4) {
13180 		lpfc_sli_prep_wqe(phba, piocb);
13181 
13182 		pring = lpfc_sli4_calc_ring(phba, piocb);
13183 	} else
13184 		pring = &phba->sli.sli3_ring[ring_number];
13185 	/*
13186 	 * If the caller has provided a response iocbq buffer, then rsp_iocb
13187 	 * is NULL or its an error.
13188 	 */
13189 	if (prspiocbq) {
13190 		if (piocb->rsp_iocb)
13191 			return IOCB_ERROR;
13192 		piocb->rsp_iocb = prspiocbq;
13193 	}
13194 
13195 	piocb->wait_cmd_cmpl = piocb->cmd_cmpl;
13196 	piocb->cmd_cmpl = lpfc_sli_wake_iocb_wait;
13197 	piocb->context_un.wait_queue = &done_q;
13198 	piocb->cmd_flag &= ~(LPFC_IO_WAKE | LPFC_IO_WAKE_TMO);
13199 
13200 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
13201 		if (lpfc_readl(phba->HCregaddr, &creg_val))
13202 			return IOCB_ERROR;
13203 		creg_val |= (HC_R0INT_ENA << LPFC_FCP_RING);
13204 		writel(creg_val, phba->HCregaddr);
13205 		readl(phba->HCregaddr); /* flush */
13206 	}
13207 
13208 	retval = lpfc_sli_issue_iocb(phba, ring_number, piocb,
13209 				     SLI_IOCB_RET_IOCB);
13210 	if (retval == IOCB_SUCCESS) {
13211 		timeout_req = secs_to_jiffies(timeout);
13212 		timeleft = wait_event_timeout(done_q,
13213 				lpfc_chk_iocb_flg(phba, piocb, LPFC_IO_WAKE),
13214 				timeout_req);
13215 		spin_lock_irqsave(&phba->hbalock, iflags);
13216 		if (!(piocb->cmd_flag & LPFC_IO_WAKE)) {
13217 
13218 			/*
13219 			 * IOCB timed out.  Inform the wake iocb wait
13220 			 * completion function and set local status
13221 			 */
13222 
13223 			iocb_completed = false;
13224 			piocb->cmd_flag |= LPFC_IO_WAKE_TMO;
13225 		}
13226 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13227 		if (iocb_completed) {
13228 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13229 					"0331 IOCB wake signaled\n");
13230 			/* Note: we are not indicating if the IOCB has a success
13231 			 * status or not - that's for the caller to check.
13232 			 * IOCB_SUCCESS means just that the command was sent and
13233 			 * completed. Not that it completed successfully.
13234 			 * */
13235 		} else if (timeleft == 0) {
13236 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13237 					"0338 IOCB wait timeout error - no "
13238 					"wake response Data x%x\n", timeout);
13239 			retval = IOCB_TIMEDOUT;
13240 		} else {
13241 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13242 					"0330 IOCB wake NOT set, "
13243 					"Data x%x x%lx\n",
13244 					timeout, (timeleft / jiffies));
13245 			retval = IOCB_TIMEDOUT;
13246 		}
13247 	} else if (retval == IOCB_BUSY) {
13248 		if (phba->cfg_log_verbose & LOG_SLI) {
13249 			list_for_each_entry(iocb, &pring->txq, list) {
13250 				txq_cnt++;
13251 			}
13252 			list_for_each_entry(iocb, &pring->txcmplq, list) {
13253 				txcmplq_cnt++;
13254 			}
13255 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13256 				"2818 Max IOCBs %d txq cnt %d txcmplq cnt %d\n",
13257 				phba->iocb_cnt, txq_cnt, txcmplq_cnt);
13258 		}
13259 		return retval;
13260 	} else {
13261 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13262 				"0332 IOCB wait issue failed, Data x%x\n",
13263 				retval);
13264 		retval = IOCB_ERROR;
13265 	}
13266 
13267 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
13268 		if (lpfc_readl(phba->HCregaddr, &creg_val))
13269 			return IOCB_ERROR;
13270 		creg_val &= ~(HC_R0INT_ENA << LPFC_FCP_RING);
13271 		writel(creg_val, phba->HCregaddr);
13272 		readl(phba->HCregaddr); /* flush */
13273 	}
13274 
13275 	if (prspiocbq)
13276 		piocb->rsp_iocb = NULL;
13277 
13278 	piocb->context_un.wait_queue = NULL;
13279 	piocb->cmd_cmpl = NULL;
13280 	return retval;
13281 }
13282 
13283 /**
13284  * lpfc_sli_issue_mbox_wait - Synchronous function to issue mailbox
13285  * @phba: Pointer to HBA context object.
13286  * @pmboxq: Pointer to driver mailbox object.
13287  * @timeout: Timeout in number of seconds.
13288  *
13289  * This function issues the mailbox to firmware and waits for the
13290  * mailbox command to complete. If the mailbox command is not
13291  * completed within timeout seconds, it returns MBX_TIMEOUT.
13292  * The function waits for the mailbox completion using an
13293  * interruptible wait. If the thread is woken up due to a
13294  * signal, MBX_TIMEOUT error is returned to the caller. Caller
13295  * should not free the mailbox resources, if this function returns
13296  * MBX_TIMEOUT.
13297  * This function will sleep while waiting for mailbox completion.
13298  * So, this function should not be called from any context which
13299  * does not allow sleeping. Due to the same reason, this function
13300  * cannot be called with interrupt disabled.
13301  * This function assumes that the mailbox completion occurs while
13302  * this function sleep. So, this function cannot be called from
13303  * the worker thread which processes mailbox completion.
13304  * This function is called in the context of HBA management
13305  * applications.
13306  * This function returns MBX_SUCCESS when successful.
13307  * This function is called with no lock held.
13308  **/
13309 int
13310 lpfc_sli_issue_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq,
13311 			 uint32_t timeout)
13312 {
13313 	struct completion mbox_done;
13314 	int retval;
13315 	unsigned long flag;
13316 
13317 	pmboxq->mbox_flag &= ~LPFC_MBX_WAKE;
13318 	/* setup wake call as IOCB callback */
13319 	pmboxq->mbox_cmpl = lpfc_sli_wake_mbox_wait;
13320 
13321 	/* setup ctx_u field to pass wait_queue pointer to wake function  */
13322 	init_completion(&mbox_done);
13323 	pmboxq->ctx_u.mbox_wait = &mbox_done;
13324 	/* now issue the command */
13325 	retval = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
13326 	if (retval == MBX_BUSY || retval == MBX_SUCCESS) {
13327 		wait_for_completion_timeout(&mbox_done, secs_to_jiffies(timeout));
13328 
13329 		spin_lock_irqsave(&phba->hbalock, flag);
13330 		pmboxq->ctx_u.mbox_wait = NULL;
13331 		/*
13332 		 * if LPFC_MBX_WAKE flag is set the mailbox is completed
13333 		 * else do not free the resources.
13334 		 */
13335 		if (pmboxq->mbox_flag & LPFC_MBX_WAKE) {
13336 			retval = MBX_SUCCESS;
13337 		} else {
13338 			retval = MBX_TIMEOUT;
13339 			pmboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
13340 		}
13341 		spin_unlock_irqrestore(&phba->hbalock, flag);
13342 	}
13343 	return retval;
13344 }
13345 
13346 /**
13347  * lpfc_sli_mbox_sys_shutdown - shutdown mailbox command sub-system
13348  * @phba: Pointer to HBA context.
13349  * @mbx_action: Mailbox shutdown options.
13350  *
13351  * This function is called to shutdown the driver's mailbox sub-system.
13352  * It first marks the mailbox sub-system is in a block state to prevent
13353  * the asynchronous mailbox command from issued off the pending mailbox
13354  * command queue. If the mailbox command sub-system shutdown is due to
13355  * HBA error conditions such as EEH or ERATT, this routine shall invoke
13356  * the mailbox sub-system flush routine to forcefully bring down the
13357  * mailbox sub-system. Otherwise, if it is due to normal condition (such
13358  * as with offline or HBA function reset), this routine will wait for the
13359  * outstanding mailbox command to complete before invoking the mailbox
13360  * sub-system flush routine to gracefully bring down mailbox sub-system.
13361  **/
13362 void
13363 lpfc_sli_mbox_sys_shutdown(struct lpfc_hba *phba, int mbx_action)
13364 {
13365 	struct lpfc_sli *psli = &phba->sli;
13366 	unsigned long timeout;
13367 
13368 	if (mbx_action == LPFC_MBX_NO_WAIT) {
13369 		/* delay 100ms for port state */
13370 		msleep(100);
13371 		lpfc_sli_mbox_sys_flush(phba);
13372 		return;
13373 	}
13374 	timeout = secs_to_jiffies(LPFC_MBOX_TMO) + jiffies;
13375 
13376 	/* Disable softirqs, including timers from obtaining phba->hbalock */
13377 	local_bh_disable();
13378 
13379 	spin_lock_irq(&phba->hbalock);
13380 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
13381 
13382 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
13383 		/* Determine how long we might wait for the active mailbox
13384 		 * command to be gracefully completed by firmware.
13385 		 */
13386 		if (phba->sli.mbox_active)
13387 			timeout = secs_to_jiffies(lpfc_mbox_tmo_val(phba,
13388 						phba->sli.mbox_active)) + jiffies;
13389 		spin_unlock_irq(&phba->hbalock);
13390 
13391 		/* Enable softirqs again, done with phba->hbalock */
13392 		local_bh_enable();
13393 
13394 		while (phba->sli.mbox_active) {
13395 			/* Check active mailbox complete status every 2ms */
13396 			msleep(2);
13397 			if (time_after(jiffies, timeout))
13398 				/* Timeout, let the mailbox flush routine to
13399 				 * forcefully release active mailbox command
13400 				 */
13401 				break;
13402 		}
13403 	} else {
13404 		spin_unlock_irq(&phba->hbalock);
13405 
13406 		/* Enable softirqs again, done with phba->hbalock */
13407 		local_bh_enable();
13408 	}
13409 
13410 	lpfc_sli_mbox_sys_flush(phba);
13411 }
13412 
13413 /**
13414  * lpfc_sli_eratt_read - read sli-3 error attention events
13415  * @phba: Pointer to HBA context.
13416  *
13417  * This function is called to read the SLI3 device error attention registers
13418  * for possible error attention events. The caller must hold the hostlock
13419  * with spin_lock_irq().
13420  *
13421  * This function returns 1 when there is Error Attention in the Host Attention
13422  * Register and returns 0 otherwise.
13423  **/
13424 static int
13425 lpfc_sli_eratt_read(struct lpfc_hba *phba)
13426 {
13427 	uint32_t ha_copy;
13428 
13429 	/* Read chip Host Attention (HA) register */
13430 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
13431 		goto unplug_err;
13432 
13433 	if (ha_copy & HA_ERATT) {
13434 		/* Read host status register to retrieve error event */
13435 		if (lpfc_sli_read_hs(phba))
13436 			goto unplug_err;
13437 
13438 		/* Check if there is a deferred error condition is active */
13439 		if ((HS_FFER1 & phba->work_hs) &&
13440 		    ((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
13441 		      HS_FFER6 | HS_FFER7 | HS_FFER8) & phba->work_hs)) {
13442 			set_bit(DEFER_ERATT, &phba->hba_flag);
13443 			/* Clear all interrupt enable conditions */
13444 			writel(0, phba->HCregaddr);
13445 			readl(phba->HCregaddr);
13446 		}
13447 
13448 		/* Set the driver HA work bitmap */
13449 		phba->work_ha |= HA_ERATT;
13450 		/* Indicate polling handles this ERATT */
13451 		set_bit(HBA_ERATT_HANDLED, &phba->hba_flag);
13452 		return 1;
13453 	}
13454 	return 0;
13455 
13456 unplug_err:
13457 	/* Set the driver HS work bitmap */
13458 	phba->work_hs |= UNPLUG_ERR;
13459 	/* Set the driver HA work bitmap */
13460 	phba->work_ha |= HA_ERATT;
13461 	/* Indicate polling handles this ERATT */
13462 	set_bit(HBA_ERATT_HANDLED, &phba->hba_flag);
13463 	return 1;
13464 }
13465 
13466 /**
13467  * lpfc_sli4_eratt_read - read sli-4 error attention events
13468  * @phba: Pointer to HBA context.
13469  *
13470  * This function is called to read the SLI4 device error attention registers
13471  * for possible error attention events. The caller must hold the hostlock
13472  * with spin_lock_irq().
13473  *
13474  * This function returns 1 when there is Error Attention in the Host Attention
13475  * Register and returns 0 otherwise.
13476  **/
13477 static int
13478 lpfc_sli4_eratt_read(struct lpfc_hba *phba)
13479 {
13480 	uint32_t uerr_sta_hi, uerr_sta_lo;
13481 	uint32_t if_type, portsmphr;
13482 	struct lpfc_register portstat_reg;
13483 	u32 logmask;
13484 
13485 	/*
13486 	 * For now, use the SLI4 device internal unrecoverable error
13487 	 * registers for error attention. This can be changed later.
13488 	 */
13489 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
13490 	switch (if_type) {
13491 	case LPFC_SLI_INTF_IF_TYPE_0:
13492 		if (lpfc_readl(phba->sli4_hba.u.if_type0.UERRLOregaddr,
13493 			&uerr_sta_lo) ||
13494 			lpfc_readl(phba->sli4_hba.u.if_type0.UERRHIregaddr,
13495 			&uerr_sta_hi)) {
13496 			phba->work_hs |= UNPLUG_ERR;
13497 			phba->work_ha |= HA_ERATT;
13498 			set_bit(HBA_ERATT_HANDLED, &phba->hba_flag);
13499 			return 1;
13500 		}
13501 		if ((~phba->sli4_hba.ue_mask_lo & uerr_sta_lo) ||
13502 		    (~phba->sli4_hba.ue_mask_hi & uerr_sta_hi)) {
13503 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13504 					"1423 HBA Unrecoverable error: "
13505 					"uerr_lo_reg=0x%x, uerr_hi_reg=0x%x, "
13506 					"ue_mask_lo_reg=0x%x, "
13507 					"ue_mask_hi_reg=0x%x\n",
13508 					uerr_sta_lo, uerr_sta_hi,
13509 					phba->sli4_hba.ue_mask_lo,
13510 					phba->sli4_hba.ue_mask_hi);
13511 			phba->work_status[0] = uerr_sta_lo;
13512 			phba->work_status[1] = uerr_sta_hi;
13513 			phba->work_ha |= HA_ERATT;
13514 			set_bit(HBA_ERATT_HANDLED, &phba->hba_flag);
13515 			return 1;
13516 		}
13517 		break;
13518 	case LPFC_SLI_INTF_IF_TYPE_2:
13519 	case LPFC_SLI_INTF_IF_TYPE_6:
13520 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
13521 			&portstat_reg.word0) ||
13522 			lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
13523 			&portsmphr)){
13524 			phba->work_hs |= UNPLUG_ERR;
13525 			phba->work_ha |= HA_ERATT;
13526 			set_bit(HBA_ERATT_HANDLED, &phba->hba_flag);
13527 			return 1;
13528 		}
13529 		if (bf_get(lpfc_sliport_status_err, &portstat_reg)) {
13530 			phba->work_status[0] =
13531 				readl(phba->sli4_hba.u.if_type2.ERR1regaddr);
13532 			phba->work_status[1] =
13533 				readl(phba->sli4_hba.u.if_type2.ERR2regaddr);
13534 			logmask = LOG_TRACE_EVENT;
13535 			if (phba->work_status[0] ==
13536 				SLIPORT_ERR1_REG_ERR_CODE_2 &&
13537 			    phba->work_status[1] == SLIPORT_ERR2_REG_FW_RESTART)
13538 				logmask = LOG_SLI;
13539 			lpfc_printf_log(phba, KERN_ERR, logmask,
13540 					"2885 Port Status Event: "
13541 					"port status reg 0x%x, "
13542 					"port smphr reg 0x%x, "
13543 					"error 1=0x%x, error 2=0x%x\n",
13544 					portstat_reg.word0,
13545 					portsmphr,
13546 					phba->work_status[0],
13547 					phba->work_status[1]);
13548 			phba->work_ha |= HA_ERATT;
13549 			set_bit(HBA_ERATT_HANDLED, &phba->hba_flag);
13550 			return 1;
13551 		}
13552 		break;
13553 	case LPFC_SLI_INTF_IF_TYPE_1:
13554 	default:
13555 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13556 				"2886 HBA Error Attention on unsupported "
13557 				"if type %d.", if_type);
13558 		return 1;
13559 	}
13560 
13561 	return 0;
13562 }
13563 
13564 /**
13565  * lpfc_sli_check_eratt - check error attention events
13566  * @phba: Pointer to HBA context.
13567  *
13568  * This function is called from timer soft interrupt context to check HBA's
13569  * error attention register bit for error attention events.
13570  *
13571  * This function returns 1 when there is Error Attention in the Host Attention
13572  * Register and returns 0 otherwise.
13573  **/
13574 int
13575 lpfc_sli_check_eratt(struct lpfc_hba *phba)
13576 {
13577 	uint32_t ha_copy;
13578 
13579 	/* If somebody is waiting to handle an eratt, don't process it
13580 	 * here. The brdkill function will do this.
13581 	 */
13582 	if (phba->link_flag & LS_IGNORE_ERATT)
13583 		return 0;
13584 
13585 	/* Check if interrupt handler handles this ERATT */
13586 	if (test_bit(HBA_ERATT_HANDLED, &phba->hba_flag))
13587 		/* Interrupt handler has handled ERATT */
13588 		return 0;
13589 
13590 	/*
13591 	 * If there is deferred error attention, do not check for error
13592 	 * attention
13593 	 */
13594 	if (unlikely(test_bit(DEFER_ERATT, &phba->hba_flag)))
13595 		return 0;
13596 
13597 	spin_lock_irq(&phba->hbalock);
13598 	/* If PCI channel is offline, don't process it */
13599 	if (unlikely(pci_channel_offline(phba->pcidev))) {
13600 		spin_unlock_irq(&phba->hbalock);
13601 		return 0;
13602 	}
13603 
13604 	switch (phba->sli_rev) {
13605 	case LPFC_SLI_REV2:
13606 	case LPFC_SLI_REV3:
13607 		/* Read chip Host Attention (HA) register */
13608 		ha_copy = lpfc_sli_eratt_read(phba);
13609 		break;
13610 	case LPFC_SLI_REV4:
13611 		/* Read device Uncoverable Error (UERR) registers */
13612 		ha_copy = lpfc_sli4_eratt_read(phba);
13613 		break;
13614 	default:
13615 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13616 				"0299 Invalid SLI revision (%d)\n",
13617 				phba->sli_rev);
13618 		ha_copy = 0;
13619 		break;
13620 	}
13621 	spin_unlock_irq(&phba->hbalock);
13622 
13623 	return ha_copy;
13624 }
13625 
13626 /**
13627  * lpfc_intr_state_check - Check device state for interrupt handling
13628  * @phba: Pointer to HBA context.
13629  *
13630  * This inline routine checks whether a device or its PCI slot is in a state
13631  * that the interrupt should be handled.
13632  *
13633  * This function returns 0 if the device or the PCI slot is in a state that
13634  * interrupt should be handled, otherwise -EIO.
13635  */
13636 static inline int
13637 lpfc_intr_state_check(struct lpfc_hba *phba)
13638 {
13639 	/* If the pci channel is offline, ignore all the interrupts */
13640 	if (unlikely(pci_channel_offline(phba->pcidev)))
13641 		return -EIO;
13642 
13643 	/* Update device level interrupt statistics */
13644 	phba->sli.slistat.sli_intr++;
13645 
13646 	/* Ignore all interrupts during initialization. */
13647 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
13648 		return -EIO;
13649 
13650 	return 0;
13651 }
13652 
13653 /**
13654  * lpfc_sli_sp_intr_handler - Slow-path interrupt handler to SLI-3 device
13655  * @irq: Interrupt number.
13656  * @dev_id: The device context pointer.
13657  *
13658  * This function is directly called from the PCI layer as an interrupt
13659  * service routine when device with SLI-3 interface spec is enabled with
13660  * MSI-X multi-message interrupt mode and there are slow-path events in
13661  * the HBA. However, when the device is enabled with either MSI or Pin-IRQ
13662  * interrupt mode, this function is called as part of the device-level
13663  * interrupt handler. When the PCI slot is in error recovery or the HBA
13664  * is undergoing initialization, the interrupt handler will not process
13665  * the interrupt. The link attention and ELS ring attention events are
13666  * handled by the worker thread. The interrupt handler signals the worker
13667  * thread and returns for these events. This function is called without
13668  * any lock held. It gets the hbalock to access and update SLI data
13669  * structures.
13670  *
13671  * This function returns IRQ_HANDLED when interrupt is handled else it
13672  * returns IRQ_NONE.
13673  **/
13674 irqreturn_t
13675 lpfc_sli_sp_intr_handler(int irq, void *dev_id)
13676 {
13677 	struct lpfc_hba  *phba;
13678 	uint32_t ha_copy, hc_copy;
13679 	uint32_t work_ha_copy;
13680 	unsigned long status;
13681 	unsigned long iflag;
13682 	uint32_t control;
13683 
13684 	MAILBOX_t *mbox, *pmbox;
13685 	struct lpfc_vport *vport;
13686 	struct lpfc_nodelist *ndlp;
13687 	struct lpfc_dmabuf *mp;
13688 	LPFC_MBOXQ_t *pmb;
13689 	int rc;
13690 
13691 	/*
13692 	 * Get the driver's phba structure from the dev_id and
13693 	 * assume the HBA is not interrupting.
13694 	 */
13695 	phba = (struct lpfc_hba *)dev_id;
13696 
13697 	if (unlikely(!phba))
13698 		return IRQ_NONE;
13699 
13700 	/*
13701 	 * Stuff needs to be attented to when this function is invoked as an
13702 	 * individual interrupt handler in MSI-X multi-message interrupt mode
13703 	 */
13704 	if (phba->intr_type == MSIX) {
13705 		/* Check device state for handling interrupt */
13706 		if (lpfc_intr_state_check(phba))
13707 			return IRQ_NONE;
13708 		/* Need to read HA REG for slow-path events */
13709 		spin_lock_irqsave(&phba->hbalock, iflag);
13710 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
13711 			goto unplug_error;
13712 		/* If somebody is waiting to handle an eratt don't process it
13713 		 * here. The brdkill function will do this.
13714 		 */
13715 		if (phba->link_flag & LS_IGNORE_ERATT)
13716 			ha_copy &= ~HA_ERATT;
13717 		/* Check the need for handling ERATT in interrupt handler */
13718 		if (ha_copy & HA_ERATT) {
13719 			if (test_and_set_bit(HBA_ERATT_HANDLED,
13720 					     &phba->hba_flag))
13721 				/* ERATT polling has handled ERATT */
13722 				ha_copy &= ~HA_ERATT;
13723 		}
13724 
13725 		/*
13726 		 * If there is deferred error attention, do not check for any
13727 		 * interrupt.
13728 		 */
13729 		if (unlikely(test_bit(DEFER_ERATT, &phba->hba_flag))) {
13730 			spin_unlock_irqrestore(&phba->hbalock, iflag);
13731 			return IRQ_NONE;
13732 		}
13733 
13734 		/* Clear up only attention source related to slow-path */
13735 		if (lpfc_readl(phba->HCregaddr, &hc_copy))
13736 			goto unplug_error;
13737 
13738 		writel(hc_copy & ~(HC_MBINT_ENA | HC_R2INT_ENA |
13739 			HC_LAINT_ENA | HC_ERINT_ENA),
13740 			phba->HCregaddr);
13741 		writel((ha_copy & (HA_MBATT | HA_R2_CLR_MSK)),
13742 			phba->HAregaddr);
13743 		writel(hc_copy, phba->HCregaddr);
13744 		readl(phba->HAregaddr); /* flush */
13745 		spin_unlock_irqrestore(&phba->hbalock, iflag);
13746 	} else
13747 		ha_copy = phba->ha_copy;
13748 
13749 	work_ha_copy = ha_copy & phba->work_ha_mask;
13750 
13751 	if (work_ha_copy) {
13752 		if (work_ha_copy & HA_LATT) {
13753 			if (phba->sli.sli_flag & LPFC_PROCESS_LA) {
13754 				/*
13755 				 * Turn off Link Attention interrupts
13756 				 * until CLEAR_LA done
13757 				 */
13758 				spin_lock_irqsave(&phba->hbalock, iflag);
13759 				phba->sli.sli_flag &= ~LPFC_PROCESS_LA;
13760 				if (lpfc_readl(phba->HCregaddr, &control))
13761 					goto unplug_error;
13762 				control &= ~HC_LAINT_ENA;
13763 				writel(control, phba->HCregaddr);
13764 				readl(phba->HCregaddr); /* flush */
13765 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13766 			}
13767 			else
13768 				work_ha_copy &= ~HA_LATT;
13769 		}
13770 
13771 		if (work_ha_copy & ~(HA_ERATT | HA_MBATT | HA_LATT)) {
13772 			/*
13773 			 * Turn off Slow Rings interrupts, LPFC_ELS_RING is
13774 			 * the only slow ring.
13775 			 */
13776 			status = (work_ha_copy &
13777 				(HA_RXMASK  << (4*LPFC_ELS_RING)));
13778 			status >>= (4*LPFC_ELS_RING);
13779 			if (status & HA_RXMASK) {
13780 				spin_lock_irqsave(&phba->hbalock, iflag);
13781 				if (lpfc_readl(phba->HCregaddr, &control))
13782 					goto unplug_error;
13783 
13784 				lpfc_debugfs_slow_ring_trc(phba,
13785 				"ISR slow ring:   ctl:x%x stat:x%x isrcnt:x%x",
13786 				control, status,
13787 				(uint32_t)phba->sli.slistat.sli_intr);
13788 
13789 				if (control & (HC_R0INT_ENA << LPFC_ELS_RING)) {
13790 					lpfc_debugfs_slow_ring_trc(phba,
13791 						"ISR Disable ring:"
13792 						"pwork:x%x hawork:x%x wait:x%x",
13793 						phba->work_ha, work_ha_copy,
13794 						(uint32_t)((unsigned long)
13795 						&phba->work_waitq));
13796 
13797 					control &=
13798 					    ~(HC_R0INT_ENA << LPFC_ELS_RING);
13799 					writel(control, phba->HCregaddr);
13800 					readl(phba->HCregaddr); /* flush */
13801 				}
13802 				else {
13803 					lpfc_debugfs_slow_ring_trc(phba,
13804 						"ISR slow ring:   pwork:"
13805 						"x%x hawork:x%x wait:x%x",
13806 						phba->work_ha, work_ha_copy,
13807 						(uint32_t)((unsigned long)
13808 						&phba->work_waitq));
13809 				}
13810 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13811 			}
13812 		}
13813 		spin_lock_irqsave(&phba->hbalock, iflag);
13814 		if (work_ha_copy & HA_ERATT) {
13815 			if (lpfc_sli_read_hs(phba))
13816 				goto unplug_error;
13817 			/*
13818 			 * Check if there is a deferred error condition
13819 			 * is active
13820 			 */
13821 			if ((HS_FFER1 & phba->work_hs) &&
13822 				((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
13823 				  HS_FFER6 | HS_FFER7 | HS_FFER8) &
13824 				  phba->work_hs)) {
13825 				set_bit(DEFER_ERATT, &phba->hba_flag);
13826 				/* Clear all interrupt enable conditions */
13827 				writel(0, phba->HCregaddr);
13828 				readl(phba->HCregaddr);
13829 			}
13830 		}
13831 
13832 		if ((work_ha_copy & HA_MBATT) && (phba->sli.mbox_active)) {
13833 			pmb = phba->sli.mbox_active;
13834 			pmbox = &pmb->u.mb;
13835 			mbox = phba->mbox;
13836 			vport = pmb->vport;
13837 
13838 			/* First check out the status word */
13839 			lpfc_sli_pcimem_bcopy(mbox, pmbox, sizeof(uint32_t));
13840 			if (pmbox->mbxOwner != OWN_HOST) {
13841 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13842 				/*
13843 				 * Stray Mailbox Interrupt, mbxCommand <cmd>
13844 				 * mbxStatus <status>
13845 				 */
13846 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13847 						"(%d):0304 Stray Mailbox "
13848 						"Interrupt mbxCommand x%x "
13849 						"mbxStatus x%x\n",
13850 						(vport ? vport->vpi : 0),
13851 						pmbox->mbxCommand,
13852 						pmbox->mbxStatus);
13853 				/* clear mailbox attention bit */
13854 				work_ha_copy &= ~HA_MBATT;
13855 			} else {
13856 				phba->sli.mbox_active = NULL;
13857 				spin_unlock_irqrestore(&phba->hbalock, iflag);
13858 				phba->last_completion_time = jiffies;
13859 				timer_delete(&phba->sli.mbox_tmo);
13860 				if (pmb->mbox_cmpl) {
13861 					lpfc_sli_pcimem_bcopy(mbox, pmbox,
13862 							MAILBOX_CMD_SIZE);
13863 					if (pmb->out_ext_byte_len &&
13864 						pmb->ext_buf)
13865 						lpfc_sli_pcimem_bcopy(
13866 						phba->mbox_ext,
13867 						pmb->ext_buf,
13868 						pmb->out_ext_byte_len);
13869 				}
13870 				if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
13871 					pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
13872 
13873 					lpfc_debugfs_disc_trc(vport,
13874 						LPFC_DISC_TRC_MBOX_VPORT,
13875 						"MBOX dflt rpi: : "
13876 						"status:x%x rpi:x%x",
13877 						(uint32_t)pmbox->mbxStatus,
13878 						pmbox->un.varWords[0], 0);
13879 
13880 					if (!pmbox->mbxStatus) {
13881 						mp = pmb->ctx_buf;
13882 						ndlp = pmb->ctx_ndlp;
13883 
13884 						/* Reg_LOGIN of dflt RPI was
13885 						 * successful. new lets get
13886 						 * rid of the RPI using the
13887 						 * same mbox buffer.
13888 						 */
13889 						lpfc_unreg_login(phba,
13890 							vport->vpi,
13891 							pmbox->un.varWords[0],
13892 							pmb);
13893 						pmb->mbox_cmpl =
13894 							lpfc_mbx_cmpl_dflt_rpi;
13895 						pmb->ctx_buf = mp;
13896 						pmb->ctx_ndlp = ndlp;
13897 						pmb->vport = vport;
13898 						rc = lpfc_sli_issue_mbox(phba,
13899 								pmb,
13900 								MBX_NOWAIT);
13901 						if (rc != MBX_BUSY)
13902 							lpfc_printf_log(phba,
13903 							KERN_ERR,
13904 							LOG_TRACE_EVENT,
13905 							"0350 rc should have"
13906 							"been MBX_BUSY\n");
13907 						if (rc != MBX_NOT_FINISHED)
13908 							goto send_current_mbox;
13909 					}
13910 				}
13911 				spin_lock_irqsave(
13912 						&phba->pport->work_port_lock,
13913 						iflag);
13914 				phba->pport->work_port_events &=
13915 					~WORKER_MBOX_TMO;
13916 				spin_unlock_irqrestore(
13917 						&phba->pport->work_port_lock,
13918 						iflag);
13919 
13920 				/* Do NOT queue MBX_HEARTBEAT to the worker
13921 				 * thread for processing.
13922 				 */
13923 				if (pmbox->mbxCommand == MBX_HEARTBEAT) {
13924 					/* Process mbox now */
13925 					phba->sli.mbox_active = NULL;
13926 					phba->sli.sli_flag &=
13927 						~LPFC_SLI_MBOX_ACTIVE;
13928 					if (pmb->mbox_cmpl)
13929 						pmb->mbox_cmpl(phba, pmb);
13930 				} else {
13931 					/* Queue to worker thread to process */
13932 					lpfc_mbox_cmpl_put(phba, pmb);
13933 				}
13934 			}
13935 		} else
13936 			spin_unlock_irqrestore(&phba->hbalock, iflag);
13937 
13938 		if ((work_ha_copy & HA_MBATT) &&
13939 		    (phba->sli.mbox_active == NULL)) {
13940 send_current_mbox:
13941 			/* Process next mailbox command if there is one */
13942 			do {
13943 				rc = lpfc_sli_issue_mbox(phba, NULL,
13944 							 MBX_NOWAIT);
13945 			} while (rc == MBX_NOT_FINISHED);
13946 			if (rc != MBX_SUCCESS)
13947 				lpfc_printf_log(phba, KERN_ERR,
13948 						LOG_TRACE_EVENT,
13949 						"0349 rc should be "
13950 						"MBX_SUCCESS\n");
13951 		}
13952 
13953 		spin_lock_irqsave(&phba->hbalock, iflag);
13954 		phba->work_ha |= work_ha_copy;
13955 		spin_unlock_irqrestore(&phba->hbalock, iflag);
13956 		lpfc_worker_wake_up(phba);
13957 	}
13958 	return IRQ_HANDLED;
13959 unplug_error:
13960 	spin_unlock_irqrestore(&phba->hbalock, iflag);
13961 	return IRQ_HANDLED;
13962 
13963 } /* lpfc_sli_sp_intr_handler */
13964 
13965 /**
13966  * lpfc_sli_fp_intr_handler - Fast-path interrupt handler to SLI-3 device.
13967  * @irq: Interrupt number.
13968  * @dev_id: The device context pointer.
13969  *
13970  * This function is directly called from the PCI layer as an interrupt
13971  * service routine when device with SLI-3 interface spec is enabled with
13972  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
13973  * ring event in the HBA. However, when the device is enabled with either
13974  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
13975  * device-level interrupt handler. When the PCI slot is in error recovery
13976  * or the HBA is undergoing initialization, the interrupt handler will not
13977  * process the interrupt. The SCSI FCP fast-path ring event are handled in
13978  * the interrupt context. This function is called without any lock held.
13979  * It gets the hbalock to access and update SLI data structures.
13980  *
13981  * This function returns IRQ_HANDLED when interrupt is handled else it
13982  * returns IRQ_NONE.
13983  **/
13984 irqreturn_t
13985 lpfc_sli_fp_intr_handler(int irq, void *dev_id)
13986 {
13987 	struct lpfc_hba  *phba;
13988 	uint32_t ha_copy;
13989 	unsigned long status;
13990 	unsigned long iflag;
13991 	struct lpfc_sli_ring *pring;
13992 
13993 	/* Get the driver's phba structure from the dev_id and
13994 	 * assume the HBA is not interrupting.
13995 	 */
13996 	phba = (struct lpfc_hba *) dev_id;
13997 
13998 	if (unlikely(!phba))
13999 		return IRQ_NONE;
14000 
14001 	/*
14002 	 * Stuff needs to be attented to when this function is invoked as an
14003 	 * individual interrupt handler in MSI-X multi-message interrupt mode
14004 	 */
14005 	if (phba->intr_type == MSIX) {
14006 		/* Check device state for handling interrupt */
14007 		if (lpfc_intr_state_check(phba))
14008 			return IRQ_NONE;
14009 		/* Need to read HA REG for FCP ring and other ring events */
14010 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
14011 			return IRQ_HANDLED;
14012 
14013 		/*
14014 		 * If there is deferred error attention, do not check for
14015 		 * any interrupt.
14016 		 */
14017 		if (unlikely(test_bit(DEFER_ERATT, &phba->hba_flag)))
14018 			return IRQ_NONE;
14019 
14020 		/* Clear up only attention source related to fast-path */
14021 		spin_lock_irqsave(&phba->hbalock, iflag);
14022 		writel((ha_copy & (HA_R0_CLR_MSK | HA_R1_CLR_MSK)),
14023 			phba->HAregaddr);
14024 		readl(phba->HAregaddr); /* flush */
14025 		spin_unlock_irqrestore(&phba->hbalock, iflag);
14026 	} else
14027 		ha_copy = phba->ha_copy;
14028 
14029 	/*
14030 	 * Process all events on FCP ring. Take the optimized path for FCP IO.
14031 	 */
14032 	ha_copy &= ~(phba->work_ha_mask);
14033 
14034 	status = (ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
14035 	status >>= (4*LPFC_FCP_RING);
14036 	pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
14037 	if (status & HA_RXMASK)
14038 		lpfc_sli_handle_fast_ring_event(phba, pring, status);
14039 
14040 	if (phba->cfg_multi_ring_support == 2) {
14041 		/*
14042 		 * Process all events on extra ring. Take the optimized path
14043 		 * for extra ring IO.
14044 		 */
14045 		status = (ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
14046 		status >>= (4*LPFC_EXTRA_RING);
14047 		if (status & HA_RXMASK) {
14048 			lpfc_sli_handle_fast_ring_event(phba,
14049 					&phba->sli.sli3_ring[LPFC_EXTRA_RING],
14050 					status);
14051 		}
14052 	}
14053 	return IRQ_HANDLED;
14054 }  /* lpfc_sli_fp_intr_handler */
14055 
14056 /**
14057  * lpfc_sli_intr_handler - Device-level interrupt handler to SLI-3 device
14058  * @irq: Interrupt number.
14059  * @dev_id: The device context pointer.
14060  *
14061  * This function is the HBA device-level interrupt handler to device with
14062  * SLI-3 interface spec, called from the PCI layer when either MSI or
14063  * Pin-IRQ interrupt mode is enabled and there is an event in the HBA which
14064  * requires driver attention. This function invokes the slow-path interrupt
14065  * attention handling function and fast-path interrupt attention handling
14066  * function in turn to process the relevant HBA attention events. This
14067  * function is called without any lock held. It gets the hbalock to access
14068  * and update SLI data structures.
14069  *
14070  * This function returns IRQ_HANDLED when interrupt is handled, else it
14071  * returns IRQ_NONE.
14072  **/
14073 irqreturn_t
14074 lpfc_sli_intr_handler(int irq, void *dev_id)
14075 {
14076 	struct lpfc_hba  *phba;
14077 	irqreturn_t sp_irq_rc, fp_irq_rc;
14078 	unsigned long status1, status2;
14079 	uint32_t hc_copy;
14080 
14081 	/*
14082 	 * Get the driver's phba structure from the dev_id and
14083 	 * assume the HBA is not interrupting.
14084 	 */
14085 	phba = (struct lpfc_hba *) dev_id;
14086 
14087 	if (unlikely(!phba))
14088 		return IRQ_NONE;
14089 
14090 	/* Check device state for handling interrupt */
14091 	if (lpfc_intr_state_check(phba))
14092 		return IRQ_NONE;
14093 
14094 	spin_lock(&phba->hbalock);
14095 	if (lpfc_readl(phba->HAregaddr, &phba->ha_copy)) {
14096 		spin_unlock(&phba->hbalock);
14097 		return IRQ_HANDLED;
14098 	}
14099 
14100 	if (unlikely(!phba->ha_copy)) {
14101 		spin_unlock(&phba->hbalock);
14102 		return IRQ_NONE;
14103 	} else if (phba->ha_copy & HA_ERATT) {
14104 		if (test_and_set_bit(HBA_ERATT_HANDLED, &phba->hba_flag))
14105 			/* ERATT polling has handled ERATT */
14106 			phba->ha_copy &= ~HA_ERATT;
14107 	}
14108 
14109 	/*
14110 	 * If there is deferred error attention, do not check for any interrupt.
14111 	 */
14112 	if (unlikely(test_bit(DEFER_ERATT, &phba->hba_flag))) {
14113 		spin_unlock(&phba->hbalock);
14114 		return IRQ_NONE;
14115 	}
14116 
14117 	/* Clear attention sources except link and error attentions */
14118 	if (lpfc_readl(phba->HCregaddr, &hc_copy)) {
14119 		spin_unlock(&phba->hbalock);
14120 		return IRQ_HANDLED;
14121 	}
14122 	writel(hc_copy & ~(HC_MBINT_ENA | HC_R0INT_ENA | HC_R1INT_ENA
14123 		| HC_R2INT_ENA | HC_LAINT_ENA | HC_ERINT_ENA),
14124 		phba->HCregaddr);
14125 	writel((phba->ha_copy & ~(HA_LATT | HA_ERATT)), phba->HAregaddr);
14126 	writel(hc_copy, phba->HCregaddr);
14127 	readl(phba->HAregaddr); /* flush */
14128 	spin_unlock(&phba->hbalock);
14129 
14130 	/*
14131 	 * Invokes slow-path host attention interrupt handling as appropriate.
14132 	 */
14133 
14134 	/* status of events with mailbox and link attention */
14135 	status1 = phba->ha_copy & (HA_MBATT | HA_LATT | HA_ERATT);
14136 
14137 	/* status of events with ELS ring */
14138 	status2 = (phba->ha_copy & (HA_RXMASK  << (4*LPFC_ELS_RING)));
14139 	status2 >>= (4*LPFC_ELS_RING);
14140 
14141 	if (status1 || (status2 & HA_RXMASK))
14142 		sp_irq_rc = lpfc_sli_sp_intr_handler(irq, dev_id);
14143 	else
14144 		sp_irq_rc = IRQ_NONE;
14145 
14146 	/*
14147 	 * Invoke fast-path host attention interrupt handling as appropriate.
14148 	 */
14149 
14150 	/* status of events with FCP ring */
14151 	status1 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
14152 	status1 >>= (4*LPFC_FCP_RING);
14153 
14154 	/* status of events with extra ring */
14155 	if (phba->cfg_multi_ring_support == 2) {
14156 		status2 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
14157 		status2 >>= (4*LPFC_EXTRA_RING);
14158 	} else
14159 		status2 = 0;
14160 
14161 	if ((status1 & HA_RXMASK) || (status2 & HA_RXMASK))
14162 		fp_irq_rc = lpfc_sli_fp_intr_handler(irq, dev_id);
14163 	else
14164 		fp_irq_rc = IRQ_NONE;
14165 
14166 	/* Return device-level interrupt handling status */
14167 	return (sp_irq_rc == IRQ_HANDLED) ? sp_irq_rc : fp_irq_rc;
14168 }  /* lpfc_sli_intr_handler */
14169 
14170 /**
14171  * lpfc_sli4_els_xri_abort_event_proc - Process els xri abort event
14172  * @phba: pointer to lpfc hba data structure.
14173  *
14174  * This routine is invoked by the worker thread to process all the pending
14175  * SLI4 els abort xri events.
14176  **/
14177 void lpfc_sli4_els_xri_abort_event_proc(struct lpfc_hba *phba)
14178 {
14179 	struct lpfc_cq_event *cq_event;
14180 	unsigned long iflags;
14181 
14182 	/* First, declare the els xri abort event has been handled */
14183 	clear_bit(ELS_XRI_ABORT_EVENT, &phba->hba_flag);
14184 
14185 	/* Now, handle all the els xri abort events */
14186 	spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
14187 	while (!list_empty(&phba->sli4_hba.sp_els_xri_aborted_work_queue)) {
14188 		/* Get the first event from the head of the event queue */
14189 		list_remove_head(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
14190 				 cq_event, struct lpfc_cq_event, list);
14191 		spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock,
14192 				       iflags);
14193 		/* Notify aborted XRI for ELS work queue */
14194 		lpfc_sli4_els_xri_aborted(phba, &cq_event->cqe.wcqe_axri);
14195 
14196 		/* Free the event processed back to the free pool */
14197 		lpfc_sli4_cq_event_release(phba, cq_event);
14198 		spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock,
14199 				  iflags);
14200 	}
14201 	spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
14202 }
14203 
14204 /**
14205  * lpfc_sli4_els_preprocess_rspiocbq - Get response iocbq from els wcqe
14206  * @phba: Pointer to HBA context object.
14207  * @irspiocbq: Pointer to work-queue completion queue entry.
14208  *
14209  * This routine handles an ELS work-queue completion event and construct
14210  * a pseudo response ELS IOCBQ from the SLI4 ELS WCQE for the common
14211  * discovery engine to handle.
14212  *
14213  * Return: Pointer to the receive IOCBQ, NULL otherwise.
14214  **/
14215 static struct lpfc_iocbq *
14216 lpfc_sli4_els_preprocess_rspiocbq(struct lpfc_hba *phba,
14217 				  struct lpfc_iocbq *irspiocbq)
14218 {
14219 	struct lpfc_sli_ring *pring;
14220 	struct lpfc_iocbq *cmdiocbq;
14221 	struct lpfc_wcqe_complete *wcqe;
14222 	unsigned long iflags;
14223 
14224 	pring = lpfc_phba_elsring(phba);
14225 	if (unlikely(!pring))
14226 		return NULL;
14227 
14228 	wcqe = &irspiocbq->cq_event.cqe.wcqe_cmpl;
14229 	spin_lock_irqsave(&pring->ring_lock, iflags);
14230 	pring->stats.iocb_event++;
14231 	/* Look up the ELS command IOCB and create pseudo response IOCB */
14232 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
14233 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
14234 	if (unlikely(!cmdiocbq)) {
14235 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
14236 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14237 				"0386 ELS complete with no corresponding "
14238 				"cmdiocb: 0x%x 0x%x 0x%x 0x%x\n",
14239 				wcqe->word0, wcqe->total_data_placed,
14240 				wcqe->parameter, wcqe->word3);
14241 		lpfc_sli_release_iocbq(phba, irspiocbq);
14242 		return NULL;
14243 	}
14244 
14245 	memcpy(&irspiocbq->wqe, &cmdiocbq->wqe, sizeof(union lpfc_wqe128));
14246 	memcpy(&irspiocbq->wcqe_cmpl, wcqe, sizeof(*wcqe));
14247 
14248 	/* Put the iocb back on the txcmplq */
14249 	lpfc_sli_ringtxcmpl_put(phba, pring, cmdiocbq);
14250 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
14251 
14252 	if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
14253 		spin_lock_irqsave(&phba->hbalock, iflags);
14254 		irspiocbq->cmd_flag |= LPFC_EXCHANGE_BUSY;
14255 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14256 	}
14257 
14258 	return irspiocbq;
14259 }
14260 
14261 inline struct lpfc_cq_event *
14262 lpfc_cq_event_setup(struct lpfc_hba *phba, void *entry, int size)
14263 {
14264 	struct lpfc_cq_event *cq_event;
14265 
14266 	/* Allocate a new internal CQ_EVENT entry */
14267 	cq_event = lpfc_sli4_cq_event_alloc(phba);
14268 	if (!cq_event) {
14269 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14270 				"0602 Failed to alloc CQ_EVENT entry\n");
14271 		return NULL;
14272 	}
14273 
14274 	/* Move the CQE into the event */
14275 	memcpy(&cq_event->cqe, entry, size);
14276 	return cq_event;
14277 }
14278 
14279 /**
14280  * lpfc_sli4_sp_handle_async_event - Handle an asynchronous event
14281  * @phba: Pointer to HBA context object.
14282  * @mcqe: Pointer to mailbox completion queue entry.
14283  *
14284  * This routine process a mailbox completion queue entry with asynchronous
14285  * event.
14286  *
14287  * Return: true if work posted to worker thread, otherwise false.
14288  **/
14289 static bool
14290 lpfc_sli4_sp_handle_async_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
14291 {
14292 	struct lpfc_cq_event *cq_event;
14293 	unsigned long iflags;
14294 
14295 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14296 			"0392 Async Event: word0:x%x, word1:x%x, "
14297 			"word2:x%x, word3:x%x\n", mcqe->word0,
14298 			mcqe->mcqe_tag0, mcqe->mcqe_tag1, mcqe->trailer);
14299 
14300 	cq_event = lpfc_cq_event_setup(phba, mcqe, sizeof(struct lpfc_mcqe));
14301 	if (!cq_event)
14302 		return false;
14303 
14304 	spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
14305 	list_add_tail(&cq_event->list, &phba->sli4_hba.sp_asynce_work_queue);
14306 	spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock, iflags);
14307 
14308 	/* Set the async event flag */
14309 	set_bit(ASYNC_EVENT, &phba->hba_flag);
14310 
14311 	return true;
14312 }
14313 
14314 /**
14315  * lpfc_sli4_sp_handle_mbox_event - Handle a mailbox completion event
14316  * @phba: Pointer to HBA context object.
14317  * @mcqe: Pointer to mailbox completion queue entry.
14318  *
14319  * This routine process a mailbox completion queue entry with mailbox
14320  * completion event.
14321  *
14322  * Return: true if work posted to worker thread, otherwise false.
14323  **/
14324 static bool
14325 lpfc_sli4_sp_handle_mbox_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
14326 {
14327 	uint32_t mcqe_status;
14328 	MAILBOX_t *mbox, *pmbox;
14329 	struct lpfc_mqe *mqe;
14330 	struct lpfc_vport *vport;
14331 	struct lpfc_nodelist *ndlp;
14332 	struct lpfc_dmabuf *mp;
14333 	unsigned long iflags;
14334 	LPFC_MBOXQ_t *pmb;
14335 	bool workposted = false;
14336 	int rc;
14337 
14338 	/* If not a mailbox complete MCQE, out by checking mailbox consume */
14339 	if (!bf_get(lpfc_trailer_completed, mcqe))
14340 		goto out_no_mqe_complete;
14341 
14342 	/* Get the reference to the active mbox command */
14343 	spin_lock_irqsave(&phba->hbalock, iflags);
14344 	pmb = phba->sli.mbox_active;
14345 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14346 	if (unlikely(!pmb)) {
14347 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14348 				"1832 No pending MBOX command to handle, "
14349 				"mcqe: x%08x x%08x x%08x x%08x\n",
14350 				mcqe->word0, mcqe->mcqe_tag0,
14351 				mcqe->mcqe_tag1, mcqe->trailer);
14352 		goto out_no_mqe_complete;
14353 	}
14354 	mqe = &pmb->u.mqe;
14355 	pmbox = (MAILBOX_t *)&pmb->u.mqe;
14356 	mbox = phba->mbox;
14357 	vport = pmb->vport;
14358 
14359 	/* Reset heartbeat timer */
14360 	phba->last_completion_time = jiffies;
14361 	timer_delete(&phba->sli.mbox_tmo);
14362 
14363 	/* Move mbox data to caller's mailbox region, do endian swapping */
14364 	if (pmb->mbox_cmpl && mbox)
14365 		lpfc_sli4_pcimem_bcopy(mbox, mqe, sizeof(struct lpfc_mqe));
14366 
14367 	/*
14368 	 * For mcqe errors, conditionally move a modified error code to
14369 	 * the mbox so that the error will not be missed.
14370 	 */
14371 	mcqe_status = bf_get(lpfc_mcqe_status, mcqe);
14372 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
14373 		if (bf_get(lpfc_mqe_status, mqe) == MBX_SUCCESS)
14374 			bf_set(lpfc_mqe_status, mqe,
14375 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
14376 	}
14377 	if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
14378 		pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
14379 		lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_MBOX_VPORT,
14380 				      "MBOX dflt rpi: status:x%x rpi:x%x",
14381 				      mcqe_status,
14382 				      pmbox->un.varWords[0], 0);
14383 		if (mcqe_status == MB_CQE_STATUS_SUCCESS) {
14384 			mp = pmb->ctx_buf;
14385 			ndlp = pmb->ctx_ndlp;
14386 
14387 			/* Reg_LOGIN of dflt RPI was successful. Mark the
14388 			 * node as having an UNREG_LOGIN in progress to stop
14389 			 * an unsolicited PLOGI from the same NPortId from
14390 			 * starting another mailbox transaction.
14391 			 */
14392 			set_bit(NLP_UNREG_INP, &ndlp->nlp_flag);
14393 			lpfc_unreg_login(phba, vport->vpi,
14394 					 pmbox->un.varWords[0], pmb);
14395 			pmb->mbox_cmpl = lpfc_mbx_cmpl_dflt_rpi;
14396 			pmb->ctx_buf = mp;
14397 
14398 			/* No reference taken here.  This is a default
14399 			 * RPI reg/immediate unreg cycle. The reference was
14400 			 * taken in the reg rpi path and is released when
14401 			 * this mailbox completes.
14402 			 */
14403 			pmb->ctx_ndlp = ndlp;
14404 			pmb->vport = vport;
14405 			rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
14406 			if (rc != MBX_BUSY)
14407 				lpfc_printf_log(phba, KERN_ERR,
14408 						LOG_TRACE_EVENT,
14409 						"0385 rc should "
14410 						"have been MBX_BUSY\n");
14411 			if (rc != MBX_NOT_FINISHED)
14412 				goto send_current_mbox;
14413 		}
14414 	}
14415 	spin_lock_irqsave(&phba->pport->work_port_lock, iflags);
14416 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
14417 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflags);
14418 
14419 	/* Do NOT queue MBX_HEARTBEAT to the worker thread for processing. */
14420 	if (pmbox->mbxCommand == MBX_HEARTBEAT) {
14421 		spin_lock_irqsave(&phba->hbalock, iflags);
14422 		/* Release the mailbox command posting token */
14423 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
14424 		phba->sli.mbox_active = NULL;
14425 		if (bf_get(lpfc_trailer_consumed, mcqe))
14426 			lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
14427 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14428 
14429 		/* Post the next mbox command, if there is one */
14430 		lpfc_sli4_post_async_mbox(phba);
14431 
14432 		/* Process cmpl now */
14433 		if (pmb->mbox_cmpl)
14434 			pmb->mbox_cmpl(phba, pmb);
14435 		return false;
14436 	}
14437 
14438 	/* There is mailbox completion work to queue to the worker thread */
14439 	spin_lock_irqsave(&phba->hbalock, iflags);
14440 	__lpfc_mbox_cmpl_put(phba, pmb);
14441 	phba->work_ha |= HA_MBATT;
14442 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14443 	workposted = true;
14444 
14445 send_current_mbox:
14446 	spin_lock_irqsave(&phba->hbalock, iflags);
14447 	/* Release the mailbox command posting token */
14448 	phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
14449 	/* Setting active mailbox pointer need to be in sync to flag clear */
14450 	phba->sli.mbox_active = NULL;
14451 	if (bf_get(lpfc_trailer_consumed, mcqe))
14452 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
14453 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14454 	/* Wake up worker thread to post the next pending mailbox command */
14455 	lpfc_worker_wake_up(phba);
14456 	return workposted;
14457 
14458 out_no_mqe_complete:
14459 	spin_lock_irqsave(&phba->hbalock, iflags);
14460 	if (bf_get(lpfc_trailer_consumed, mcqe))
14461 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
14462 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14463 	return false;
14464 }
14465 
14466 /**
14467  * lpfc_sli4_sp_handle_mcqe - Process a mailbox completion queue entry
14468  * @phba: Pointer to HBA context object.
14469  * @cq: Pointer to associated CQ
14470  * @cqe: Pointer to mailbox completion queue entry.
14471  *
14472  * This routine process a mailbox completion queue entry, it invokes the
14473  * proper mailbox complete handling or asynchronous event handling routine
14474  * according to the MCQE's async bit.
14475  *
14476  * Return: true if work posted to worker thread, otherwise false.
14477  **/
14478 static bool
14479 lpfc_sli4_sp_handle_mcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14480 			 struct lpfc_cqe *cqe)
14481 {
14482 	struct lpfc_mcqe mcqe;
14483 	bool workposted;
14484 
14485 	cq->CQ_mbox++;
14486 
14487 	/* Copy the mailbox MCQE and convert endian order as needed */
14488 	lpfc_sli4_pcimem_bcopy(cqe, &mcqe, sizeof(struct lpfc_mcqe));
14489 
14490 	/* Invoke the proper event handling routine */
14491 	if (!bf_get(lpfc_trailer_async, &mcqe))
14492 		workposted = lpfc_sli4_sp_handle_mbox_event(phba, &mcqe);
14493 	else
14494 		workposted = lpfc_sli4_sp_handle_async_event(phba, &mcqe);
14495 	return workposted;
14496 }
14497 
14498 /**
14499  * lpfc_sli4_sp_handle_els_wcqe - Handle els work-queue completion event
14500  * @phba: Pointer to HBA context object.
14501  * @cq: Pointer to associated CQ
14502  * @wcqe: Pointer to work-queue completion queue entry.
14503  *
14504  * This routine handles an ELS work-queue completion event.
14505  *
14506  * Return: true if work posted to worker thread, otherwise false.
14507  **/
14508 static bool
14509 lpfc_sli4_sp_handle_els_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14510 			     struct lpfc_wcqe_complete *wcqe)
14511 {
14512 	struct lpfc_iocbq *irspiocbq;
14513 	unsigned long iflags;
14514 	struct lpfc_sli_ring *pring = cq->pring;
14515 	int txq_cnt = 0;
14516 	int txcmplq_cnt = 0;
14517 
14518 	/* Check for response status */
14519 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
14520 		/* Log the error status */
14521 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14522 				"0357 ELS CQE error: status=x%x: "
14523 				"CQE: %08x %08x %08x %08x\n",
14524 				bf_get(lpfc_wcqe_c_status, wcqe),
14525 				wcqe->word0, wcqe->total_data_placed,
14526 				wcqe->parameter, wcqe->word3);
14527 	}
14528 
14529 	/* Get an irspiocbq for later ELS response processing use */
14530 	irspiocbq = lpfc_sli_get_iocbq(phba);
14531 	if (!irspiocbq) {
14532 		if (!list_empty(&pring->txq))
14533 			txq_cnt++;
14534 		if (!list_empty(&pring->txcmplq))
14535 			txcmplq_cnt++;
14536 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14537 			"0387 NO IOCBQ data: txq_cnt=%d iocb_cnt=%d "
14538 			"els_txcmplq_cnt=%d\n",
14539 			txq_cnt, phba->iocb_cnt,
14540 			txcmplq_cnt);
14541 		return false;
14542 	}
14543 
14544 	/* Save off the slow-path queue event for work thread to process */
14545 	memcpy(&irspiocbq->cq_event.cqe.wcqe_cmpl, wcqe, sizeof(*wcqe));
14546 	spin_lock_irqsave(&phba->hbalock, iflags);
14547 	list_add_tail(&irspiocbq->cq_event.list,
14548 		      &phba->sli4_hba.sp_queue_event);
14549 	spin_unlock_irqrestore(&phba->hbalock, iflags);
14550 	set_bit(HBA_SP_QUEUE_EVT, &phba->hba_flag);
14551 
14552 	return true;
14553 }
14554 
14555 /**
14556  * lpfc_sli4_sp_handle_rel_wcqe - Handle slow-path WQ entry consumed event
14557  * @phba: Pointer to HBA context object.
14558  * @wcqe: Pointer to work-queue completion queue entry.
14559  *
14560  * This routine handles slow-path WQ entry consumed event by invoking the
14561  * proper WQ release routine to the slow-path WQ.
14562  **/
14563 static void
14564 lpfc_sli4_sp_handle_rel_wcqe(struct lpfc_hba *phba,
14565 			     struct lpfc_wcqe_release *wcqe)
14566 {
14567 	/* sanity check on queue memory */
14568 	if (unlikely(!phba->sli4_hba.els_wq))
14569 		return;
14570 	/* Check for the slow-path ELS work queue */
14571 	if (bf_get(lpfc_wcqe_r_wq_id, wcqe) == phba->sli4_hba.els_wq->queue_id)
14572 		lpfc_sli4_wq_release(phba->sli4_hba.els_wq,
14573 				     bf_get(lpfc_wcqe_r_wqe_index, wcqe));
14574 	else
14575 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14576 				"2579 Slow-path wqe consume event carries "
14577 				"miss-matched qid: wcqe-qid=x%x, sp-qid=x%x\n",
14578 				bf_get(lpfc_wcqe_r_wqe_index, wcqe),
14579 				phba->sli4_hba.els_wq->queue_id);
14580 }
14581 
14582 /**
14583  * lpfc_sli4_sp_handle_abort_xri_wcqe - Handle a xri abort event
14584  * @phba: Pointer to HBA context object.
14585  * @cq: Pointer to a WQ completion queue.
14586  * @wcqe: Pointer to work-queue completion queue entry.
14587  *
14588  * This routine handles an XRI abort event.
14589  *
14590  * Return: true if work posted to worker thread, otherwise false.
14591  **/
14592 static bool
14593 lpfc_sli4_sp_handle_abort_xri_wcqe(struct lpfc_hba *phba,
14594 				   struct lpfc_queue *cq,
14595 				   struct sli4_wcqe_xri_aborted *wcqe)
14596 {
14597 	bool workposted = false;
14598 	struct lpfc_cq_event *cq_event;
14599 	unsigned long iflags;
14600 
14601 	switch (cq->subtype) {
14602 	case LPFC_IO:
14603 		lpfc_sli4_io_xri_aborted(phba, wcqe, cq->hdwq);
14604 		if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
14605 			/* Notify aborted XRI for NVME work queue */
14606 			if (phba->nvmet_support)
14607 				lpfc_sli4_nvmet_xri_aborted(phba, wcqe);
14608 		}
14609 		workposted = false;
14610 		break;
14611 	case LPFC_NVME_LS: /* NVME LS uses ELS resources */
14612 	case LPFC_ELS:
14613 		cq_event = lpfc_cq_event_setup(phba, wcqe, sizeof(*wcqe));
14614 		if (!cq_event) {
14615 			workposted = false;
14616 			break;
14617 		}
14618 		cq_event->hdwq = cq->hdwq;
14619 		spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock,
14620 				  iflags);
14621 		list_add_tail(&cq_event->list,
14622 			      &phba->sli4_hba.sp_els_xri_aborted_work_queue);
14623 		/* Set the els xri abort event flag */
14624 		set_bit(ELS_XRI_ABORT_EVENT, &phba->hba_flag);
14625 		spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock,
14626 				       iflags);
14627 		workposted = true;
14628 		break;
14629 	default:
14630 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14631 				"0603 Invalid CQ subtype %d: "
14632 				"%08x %08x %08x %08x\n",
14633 				cq->subtype, wcqe->word0, wcqe->parameter,
14634 				wcqe->word2, wcqe->word3);
14635 		workposted = false;
14636 		break;
14637 	}
14638 	return workposted;
14639 }
14640 
14641 #define FC_RCTL_MDS_DIAGS	0xF4
14642 
14643 /**
14644  * lpfc_sli4_sp_handle_rcqe - Process a receive-queue completion queue entry
14645  * @phba: Pointer to HBA context object.
14646  * @rcqe: Pointer to receive-queue completion queue entry.
14647  *
14648  * This routine process a receive-queue completion queue entry.
14649  *
14650  * Return: true if work posted to worker thread, otherwise false.
14651  **/
14652 static bool
14653 lpfc_sli4_sp_handle_rcqe(struct lpfc_hba *phba, struct lpfc_rcqe *rcqe)
14654 {
14655 	bool workposted = false;
14656 	struct fc_frame_header *fc_hdr;
14657 	struct lpfc_queue *hrq = phba->sli4_hba.hdr_rq;
14658 	struct lpfc_queue *drq = phba->sli4_hba.dat_rq;
14659 	struct lpfc_nvmet_tgtport *tgtp;
14660 	struct hbq_dmabuf *dma_buf;
14661 	uint32_t status, rq_id;
14662 	unsigned long iflags;
14663 
14664 	/* sanity check on queue memory */
14665 	if (unlikely(!hrq) || unlikely(!drq))
14666 		return workposted;
14667 
14668 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
14669 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
14670 	else
14671 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
14672 	if (rq_id != hrq->queue_id)
14673 		goto out;
14674 
14675 	status = bf_get(lpfc_rcqe_status, rcqe);
14676 	switch (status) {
14677 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
14678 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14679 				"2537 Receive Frame Truncated!!\n");
14680 		fallthrough;
14681 	case FC_STATUS_RQ_SUCCESS:
14682 		spin_lock_irqsave(&phba->hbalock, iflags);
14683 		lpfc_sli4_rq_release(hrq, drq);
14684 		dma_buf = lpfc_sli_hbqbuf_get(&phba->hbqs[0].hbq_buffer_list);
14685 		if (!dma_buf) {
14686 			hrq->RQ_no_buf_found++;
14687 			spin_unlock_irqrestore(&phba->hbalock, iflags);
14688 			goto out;
14689 		}
14690 		hrq->RQ_rcv_buf++;
14691 		hrq->RQ_buf_posted--;
14692 		memcpy(&dma_buf->cq_event.cqe.rcqe_cmpl, rcqe, sizeof(*rcqe));
14693 
14694 		fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
14695 
14696 		if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
14697 		    fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
14698 			spin_unlock_irqrestore(&phba->hbalock, iflags);
14699 			/* Handle MDS Loopback frames */
14700 			if  (!test_bit(FC_UNLOADING, &phba->pport->load_flag))
14701 				lpfc_sli4_handle_mds_loopback(phba->pport,
14702 							      dma_buf);
14703 			else
14704 				lpfc_in_buf_free(phba, &dma_buf->dbuf);
14705 			break;
14706 		}
14707 
14708 		/* save off the frame for the work thread to process */
14709 		list_add_tail(&dma_buf->cq_event.list,
14710 			      &phba->sli4_hba.sp_queue_event);
14711 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14712 		/* Frame received */
14713 		set_bit(HBA_SP_QUEUE_EVT, &phba->hba_flag);
14714 		workposted = true;
14715 		break;
14716 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
14717 		if (phba->nvmet_support) {
14718 			tgtp = phba->targetport->private;
14719 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14720 					"6402 RQE Error x%x, posted %d err_cnt "
14721 					"%d: %x %x %x\n",
14722 					status, hrq->RQ_buf_posted,
14723 					hrq->RQ_no_posted_buf,
14724 					atomic_read(&tgtp->rcv_fcp_cmd_in),
14725 					atomic_read(&tgtp->rcv_fcp_cmd_out),
14726 					atomic_read(&tgtp->xmt_fcp_release));
14727 		}
14728 		hrq->RQ_discard_frm++;
14729 		fallthrough;
14730 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
14731 		/* Unexpected event - bump the counter for support. */
14732 		hrq->RQ_no_posted_buf++;
14733 
14734 		lpfc_log_msg(phba, KERN_WARNING,
14735 			     LOG_ELS | LOG_DISCOVERY | LOG_SLI,
14736 			     "6423 RQE completion Status x%x, needed x%x "
14737 			     "discarded x%x\n", status,
14738 			     hrq->RQ_no_posted_buf - hrq->RQ_discard_frm,
14739 			     hrq->RQ_discard_frm);
14740 
14741 		/* For SLI3, post more buffers if possible. No action for SLI4.
14742 		 * SLI4 is reposting immediately after processing the RQE.
14743 		 */
14744 		set_bit(HBA_POST_RECEIVE_BUFFER, &phba->hba_flag);
14745 		workposted = true;
14746 		break;
14747 	case FC_STATUS_RQ_DMA_FAILURE:
14748 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14749 				"2564 RQE DMA Error x%x, x%08x x%08x x%08x "
14750 				"x%08x\n",
14751 				status, rcqe->word0, rcqe->word1,
14752 				rcqe->word2, rcqe->word3);
14753 
14754 		/* If IV set, no further recovery */
14755 		if (bf_get(lpfc_rcqe_iv, rcqe))
14756 			break;
14757 
14758 		/* recycle consumed resource */
14759 		spin_lock_irqsave(&phba->hbalock, iflags);
14760 		lpfc_sli4_rq_release(hrq, drq);
14761 		dma_buf = lpfc_sli_hbqbuf_get(&phba->hbqs[0].hbq_buffer_list);
14762 		if (!dma_buf) {
14763 			hrq->RQ_no_buf_found++;
14764 			spin_unlock_irqrestore(&phba->hbalock, iflags);
14765 			break;
14766 		}
14767 		hrq->RQ_rcv_buf++;
14768 		hrq->RQ_buf_posted--;
14769 		spin_unlock_irqrestore(&phba->hbalock, iflags);
14770 		lpfc_in_buf_free(phba, &dma_buf->dbuf);
14771 		break;
14772 	default:
14773 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14774 				"2565 Unexpected RQE Status x%x, w0-3 x%08x "
14775 				"x%08x x%08x x%08x\n",
14776 				status, rcqe->word0, rcqe->word1,
14777 				rcqe->word2, rcqe->word3);
14778 		break;
14779 	}
14780 out:
14781 	return workposted;
14782 }
14783 
14784 /**
14785  * lpfc_sli4_sp_handle_cqe - Process a slow path completion queue entry
14786  * @phba: Pointer to HBA context object.
14787  * @cq: Pointer to the completion queue.
14788  * @cqe: Pointer to a completion queue entry.
14789  *
14790  * This routine process a slow-path work-queue or receive queue completion queue
14791  * entry.
14792  *
14793  * Return: true if work posted to worker thread, otherwise false.
14794  **/
14795 static bool
14796 lpfc_sli4_sp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14797 			 struct lpfc_cqe *cqe)
14798 {
14799 	struct lpfc_cqe cqevt;
14800 	bool workposted = false;
14801 
14802 	/* Copy the work queue CQE and convert endian order if needed */
14803 	lpfc_sli4_pcimem_bcopy(cqe, &cqevt, sizeof(struct lpfc_cqe));
14804 
14805 	/* Check and process for different type of WCQE and dispatch */
14806 	switch (bf_get(lpfc_cqe_code, &cqevt)) {
14807 	case CQE_CODE_COMPL_WQE:
14808 		/* Process the WQ/RQ complete event */
14809 		phba->last_completion_time = jiffies;
14810 		workposted = lpfc_sli4_sp_handle_els_wcqe(phba, cq,
14811 				(struct lpfc_wcqe_complete *)&cqevt);
14812 		break;
14813 	case CQE_CODE_RELEASE_WQE:
14814 		/* Process the WQ release event */
14815 		lpfc_sli4_sp_handle_rel_wcqe(phba,
14816 				(struct lpfc_wcqe_release *)&cqevt);
14817 		break;
14818 	case CQE_CODE_XRI_ABORTED:
14819 		/* Process the WQ XRI abort event */
14820 		phba->last_completion_time = jiffies;
14821 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
14822 				(struct sli4_wcqe_xri_aborted *)&cqevt);
14823 		break;
14824 	case CQE_CODE_RECEIVE:
14825 	case CQE_CODE_RECEIVE_V1:
14826 		/* Process the RQ event */
14827 		phba->last_completion_time = jiffies;
14828 		workposted = lpfc_sli4_sp_handle_rcqe(phba,
14829 				(struct lpfc_rcqe *)&cqevt);
14830 		break;
14831 	default:
14832 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14833 				"0388 Not a valid WCQE code: x%x\n",
14834 				bf_get(lpfc_cqe_code, &cqevt));
14835 		break;
14836 	}
14837 	return workposted;
14838 }
14839 
14840 /**
14841  * lpfc_sli4_sp_handle_eqe - Process a slow-path event queue entry
14842  * @phba: Pointer to HBA context object.
14843  * @eqe: Pointer to fast-path event queue entry.
14844  * @speq: Pointer to slow-path event queue.
14845  *
14846  * This routine process a event queue entry from the slow-path event queue.
14847  * It will check the MajorCode and MinorCode to determine this is for a
14848  * completion event on a completion queue, if not, an error shall be logged
14849  * and just return. Otherwise, it will get to the corresponding completion
14850  * queue and process all the entries on that completion queue, rearm the
14851  * completion queue, and then return.
14852  *
14853  **/
14854 static void
14855 lpfc_sli4_sp_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe,
14856 	struct lpfc_queue *speq)
14857 {
14858 	struct lpfc_queue *cq = NULL, *childq;
14859 	uint16_t cqid;
14860 	int ret = 0;
14861 
14862 	/* Get the reference to the corresponding CQ */
14863 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
14864 
14865 	list_for_each_entry(childq, &speq->child_list, list) {
14866 		if (childq->queue_id == cqid) {
14867 			cq = childq;
14868 			break;
14869 		}
14870 	}
14871 	if (unlikely(!cq)) {
14872 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
14873 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14874 					"0365 Slow-path CQ identifier "
14875 					"(%d) does not exist\n", cqid);
14876 		return;
14877 	}
14878 
14879 	/* Save EQ associated with this CQ */
14880 	cq->assoc_qp = speq;
14881 
14882 	if (is_kdump_kernel())
14883 		ret = queue_work(phba->wq, &cq->spwork);
14884 	else
14885 		ret = queue_work_on(cq->chann, phba->wq, &cq->spwork);
14886 
14887 	if (!ret)
14888 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14889 				"0390 Cannot schedule queue work "
14890 				"for CQ eqcqid=%d, cqid=%d on CPU %d\n",
14891 				cqid, cq->queue_id, raw_smp_processor_id());
14892 }
14893 
14894 /**
14895  * __lpfc_sli4_process_cq - Process elements of a CQ
14896  * @phba: Pointer to HBA context object.
14897  * @cq: Pointer to CQ to be processed
14898  * @handler: Routine to process each cqe
14899  * @delay: Pointer to usdelay to set in case of rescheduling of the handler
14900  *
14901  * This routine processes completion queue entries in a CQ. While a valid
14902  * queue element is found, the handler is called. During processing checks
14903  * are made for periodic doorbell writes to let the hardware know of
14904  * element consumption.
14905  *
14906  * If the max limit on cqes to process is hit, or there are no more valid
14907  * entries, the loop stops. If we processed a sufficient number of elements,
14908  * meaning there is sufficient load, rather than rearming and generating
14909  * another interrupt, a cq rescheduling delay will be set. A delay of 0
14910  * indicates no rescheduling.
14911  *
14912  * Returns True if work scheduled, False otherwise.
14913  **/
14914 static bool
14915 __lpfc_sli4_process_cq(struct lpfc_hba *phba, struct lpfc_queue *cq,
14916 	bool (*handler)(struct lpfc_hba *, struct lpfc_queue *,
14917 			struct lpfc_cqe *), unsigned long *delay)
14918 {
14919 	struct lpfc_cqe *cqe;
14920 	bool workposted = false;
14921 	int count = 0, consumed = 0;
14922 	bool arm = true;
14923 
14924 	/* default - no reschedule */
14925 	*delay = 0;
14926 
14927 	if (cmpxchg(&cq->queue_claimed, 0, 1) != 0)
14928 		goto rearm_and_exit;
14929 
14930 	/* Process all the entries to the CQ */
14931 	cq->q_flag = 0;
14932 	cqe = lpfc_sli4_cq_get(cq);
14933 	while (cqe) {
14934 		workposted |= handler(phba, cq, cqe);
14935 		__lpfc_sli4_consume_cqe(phba, cq, cqe);
14936 
14937 		consumed++;
14938 		if (!(++count % cq->max_proc_limit))
14939 			break;
14940 
14941 		if (!(count % cq->notify_interval)) {
14942 			phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
14943 						LPFC_QUEUE_NOARM);
14944 			consumed = 0;
14945 			cq->assoc_qp->q_flag |= HBA_EQ_DELAY_CHK;
14946 		}
14947 
14948 		if (count == LPFC_NVMET_CQ_NOTIFY)
14949 			cq->q_flag |= HBA_NVMET_CQ_NOTIFY;
14950 
14951 		cqe = lpfc_sli4_cq_get(cq);
14952 	}
14953 	if (count >= phba->cfg_cq_poll_threshold) {
14954 		*delay = 1;
14955 		arm = false;
14956 	}
14957 
14958 	/* Track the max number of CQEs processed in 1 EQ */
14959 	if (count > cq->CQ_max_cqe)
14960 		cq->CQ_max_cqe = count;
14961 
14962 	cq->assoc_qp->EQ_cqe_cnt += count;
14963 
14964 	/* Catch the no cq entry condition */
14965 	if (unlikely(count == 0))
14966 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14967 				"0369 No entry from completion queue "
14968 				"qid=%d\n", cq->queue_id);
14969 
14970 	xchg(&cq->queue_claimed, 0);
14971 
14972 rearm_and_exit:
14973 	phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
14974 			arm ?  LPFC_QUEUE_REARM : LPFC_QUEUE_NOARM);
14975 
14976 	return workposted;
14977 }
14978 
14979 /**
14980  * __lpfc_sli4_sp_process_cq - Process a slow-path event queue entry
14981  * @cq: pointer to CQ to process
14982  *
14983  * This routine calls the cq processing routine with a handler specific
14984  * to the type of queue bound to it.
14985  *
14986  * The CQ routine returns two values: the first is the calling status,
14987  * which indicates whether work was queued to the  background discovery
14988  * thread. If true, the routine should wakeup the discovery thread;
14989  * the second is the delay parameter. If non-zero, rather than rearming
14990  * the CQ and yet another interrupt, the CQ handler should be queued so
14991  * that it is processed in a subsequent polling action. The value of
14992  * the delay indicates when to reschedule it.
14993  **/
14994 static void
14995 __lpfc_sli4_sp_process_cq(struct lpfc_queue *cq)
14996 {
14997 	struct lpfc_hba *phba = cq->phba;
14998 	unsigned long delay;
14999 	bool workposted = false;
15000 	int ret = 0;
15001 
15002 	/* Process and rearm the CQ */
15003 	switch (cq->type) {
15004 	case LPFC_MCQ:
15005 		workposted |= __lpfc_sli4_process_cq(phba, cq,
15006 						lpfc_sli4_sp_handle_mcqe,
15007 						&delay);
15008 		break;
15009 	case LPFC_WCQ:
15010 		if (cq->subtype == LPFC_IO)
15011 			workposted |= __lpfc_sli4_process_cq(phba, cq,
15012 						lpfc_sli4_fp_handle_cqe,
15013 						&delay);
15014 		else
15015 			workposted |= __lpfc_sli4_process_cq(phba, cq,
15016 						lpfc_sli4_sp_handle_cqe,
15017 						&delay);
15018 		break;
15019 	default:
15020 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15021 				"0370 Invalid completion queue type (%d)\n",
15022 				cq->type);
15023 		return;
15024 	}
15025 
15026 	if (delay) {
15027 		if (is_kdump_kernel())
15028 			ret = queue_delayed_work(phba->wq, &cq->sched_spwork,
15029 						delay);
15030 		else
15031 			ret = queue_delayed_work_on(cq->chann, phba->wq,
15032 						&cq->sched_spwork, delay);
15033 		if (!ret)
15034 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15035 				"0394 Cannot schedule queue work "
15036 				"for cqid=%d on CPU %d\n",
15037 				cq->queue_id, cq->chann);
15038 	}
15039 
15040 	/* wake up worker thread if there are works to be done */
15041 	if (workposted)
15042 		lpfc_worker_wake_up(phba);
15043 }
15044 
15045 /**
15046  * lpfc_sli4_sp_process_cq - slow-path work handler when started by
15047  *   interrupt
15048  * @work: pointer to work element
15049  *
15050  * translates from the work handler and calls the slow-path handler.
15051  **/
15052 static void
15053 lpfc_sli4_sp_process_cq(struct work_struct *work)
15054 {
15055 	struct lpfc_queue *cq = container_of(work, struct lpfc_queue, spwork);
15056 
15057 	__lpfc_sli4_sp_process_cq(cq);
15058 }
15059 
15060 /**
15061  * lpfc_sli4_dly_sp_process_cq - slow-path work handler when started by timer
15062  * @work: pointer to work element
15063  *
15064  * translates from the work handler and calls the slow-path handler.
15065  **/
15066 static void
15067 lpfc_sli4_dly_sp_process_cq(struct work_struct *work)
15068 {
15069 	struct lpfc_queue *cq = container_of(to_delayed_work(work),
15070 					struct lpfc_queue, sched_spwork);
15071 
15072 	__lpfc_sli4_sp_process_cq(cq);
15073 }
15074 
15075 /**
15076  * lpfc_sli4_fp_handle_fcp_wcqe - Process fast-path work queue completion entry
15077  * @phba: Pointer to HBA context object.
15078  * @cq: Pointer to associated CQ
15079  * @wcqe: Pointer to work-queue completion queue entry.
15080  *
15081  * This routine process a fast-path work queue completion entry from fast-path
15082  * event queue for FCP command response completion.
15083  **/
15084 static void
15085 lpfc_sli4_fp_handle_fcp_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15086 			     struct lpfc_wcqe_complete *wcqe)
15087 {
15088 	struct lpfc_sli_ring *pring = cq->pring;
15089 	struct lpfc_iocbq *cmdiocbq;
15090 	unsigned long iflags;
15091 
15092 	/* Check for response status */
15093 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
15094 		/* If resource errors reported from HBA, reduce queue
15095 		 * depth of the SCSI device.
15096 		 */
15097 		if (((bf_get(lpfc_wcqe_c_status, wcqe) ==
15098 		     IOSTAT_LOCAL_REJECT)) &&
15099 		    ((wcqe->parameter & IOERR_PARAM_MASK) ==
15100 		     IOERR_NO_RESOURCES))
15101 			phba->lpfc_rampdown_queue_depth(phba);
15102 
15103 		/* Log the cmpl status */
15104 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
15105 				"0373 FCP CQE cmpl: status=x%x: "
15106 				"CQE: %08x %08x %08x %08x\n",
15107 				bf_get(lpfc_wcqe_c_status, wcqe),
15108 				wcqe->word0, wcqe->total_data_placed,
15109 				wcqe->parameter, wcqe->word3);
15110 	}
15111 
15112 	/* Look up the FCP command IOCB and create pseudo response IOCB */
15113 	spin_lock_irqsave(&pring->ring_lock, iflags);
15114 	pring->stats.iocb_event++;
15115 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
15116 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
15117 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
15118 	if (unlikely(!cmdiocbq)) {
15119 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15120 				"0374 FCP complete with no corresponding "
15121 				"cmdiocb: iotag (%d)\n",
15122 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
15123 		return;
15124 	}
15125 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
15126 	cmdiocbq->isr_timestamp = cq->isr_timestamp;
15127 #endif
15128 	if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
15129 		spin_lock_irqsave(&phba->hbalock, iflags);
15130 		cmdiocbq->cmd_flag |= LPFC_EXCHANGE_BUSY;
15131 		spin_unlock_irqrestore(&phba->hbalock, iflags);
15132 	}
15133 
15134 	if (cmdiocbq->cmd_cmpl) {
15135 		/* For FCP the flag is cleared in cmd_cmpl */
15136 		if (!(cmdiocbq->cmd_flag & LPFC_IO_FCP) &&
15137 		    cmdiocbq->cmd_flag & LPFC_DRIVER_ABORTED) {
15138 			spin_lock_irqsave(&phba->hbalock, iflags);
15139 			cmdiocbq->cmd_flag &= ~LPFC_DRIVER_ABORTED;
15140 			spin_unlock_irqrestore(&phba->hbalock, iflags);
15141 		}
15142 
15143 		/* Pass the cmd_iocb and the wcqe to the upper layer */
15144 		memcpy(&cmdiocbq->wcqe_cmpl, wcqe,
15145 		       sizeof(struct lpfc_wcqe_complete));
15146 		cmdiocbq->cmd_cmpl(phba, cmdiocbq, cmdiocbq);
15147 	} else {
15148 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15149 				"0375 FCP cmdiocb not callback function "
15150 				"iotag: (%d)\n",
15151 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
15152 	}
15153 }
15154 
15155 /**
15156  * lpfc_sli4_fp_handle_rel_wcqe - Handle fast-path WQ entry consumed event
15157  * @phba: Pointer to HBA context object.
15158  * @cq: Pointer to completion queue.
15159  * @wcqe: Pointer to work-queue completion queue entry.
15160  *
15161  * This routine handles an fast-path WQ entry consumed event by invoking the
15162  * proper WQ release routine to the slow-path WQ.
15163  **/
15164 static void
15165 lpfc_sli4_fp_handle_rel_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15166 			     struct lpfc_wcqe_release *wcqe)
15167 {
15168 	struct lpfc_queue *childwq;
15169 	bool wqid_matched = false;
15170 	uint16_t hba_wqid;
15171 
15172 	/* Check for fast-path FCP work queue release */
15173 	hba_wqid = bf_get(lpfc_wcqe_r_wq_id, wcqe);
15174 	list_for_each_entry(childwq, &cq->child_list, list) {
15175 		if (childwq->queue_id == hba_wqid) {
15176 			lpfc_sli4_wq_release(childwq,
15177 					bf_get(lpfc_wcqe_r_wqe_index, wcqe));
15178 			if (childwq->q_flag & HBA_NVMET_WQFULL)
15179 				lpfc_nvmet_wqfull_process(phba, childwq);
15180 			wqid_matched = true;
15181 			break;
15182 		}
15183 	}
15184 	/* Report warning log message if no match found */
15185 	if (wqid_matched != true)
15186 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15187 				"2580 Fast-path wqe consume event carries "
15188 				"miss-matched qid: wcqe-qid=x%x\n", hba_wqid);
15189 }
15190 
15191 /**
15192  * lpfc_sli4_nvmet_handle_rcqe - Process a receive-queue completion queue entry
15193  * @phba: Pointer to HBA context object.
15194  * @cq: Pointer to completion queue.
15195  * @rcqe: Pointer to receive-queue completion queue entry.
15196  *
15197  * This routine process a receive-queue completion queue entry.
15198  *
15199  * Return: true if work posted to worker thread, otherwise false.
15200  **/
15201 static bool
15202 lpfc_sli4_nvmet_handle_rcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15203 			    struct lpfc_rcqe *rcqe)
15204 {
15205 	bool workposted = false;
15206 	struct lpfc_queue *hrq;
15207 	struct lpfc_queue *drq;
15208 	struct rqb_dmabuf *dma_buf;
15209 	struct fc_frame_header *fc_hdr;
15210 	struct lpfc_nvmet_tgtport *tgtp;
15211 	uint32_t status, rq_id;
15212 	unsigned long iflags;
15213 	uint32_t fctl, idx;
15214 
15215 	if ((phba->nvmet_support == 0) ||
15216 	    (phba->sli4_hba.nvmet_cqset == NULL))
15217 		return workposted;
15218 
15219 	idx = cq->queue_id - phba->sli4_hba.nvmet_cqset[0]->queue_id;
15220 	hrq = phba->sli4_hba.nvmet_mrq_hdr[idx];
15221 	drq = phba->sli4_hba.nvmet_mrq_data[idx];
15222 
15223 	/* sanity check on queue memory */
15224 	if (unlikely(!hrq) || unlikely(!drq))
15225 		return workposted;
15226 
15227 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
15228 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
15229 	else
15230 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
15231 
15232 	if ((phba->nvmet_support == 0) ||
15233 	    (rq_id != hrq->queue_id))
15234 		return workposted;
15235 
15236 	status = bf_get(lpfc_rcqe_status, rcqe);
15237 	switch (status) {
15238 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
15239 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15240 				"6126 Receive Frame Truncated!!\n");
15241 		fallthrough;
15242 	case FC_STATUS_RQ_SUCCESS:
15243 		spin_lock_irqsave(&phba->hbalock, iflags);
15244 		lpfc_sli4_rq_release(hrq, drq);
15245 		dma_buf = lpfc_sli_rqbuf_get(phba, hrq);
15246 		if (!dma_buf) {
15247 			hrq->RQ_no_buf_found++;
15248 			spin_unlock_irqrestore(&phba->hbalock, iflags);
15249 			goto out;
15250 		}
15251 		spin_unlock_irqrestore(&phba->hbalock, iflags);
15252 		hrq->RQ_rcv_buf++;
15253 		hrq->RQ_buf_posted--;
15254 		fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
15255 
15256 		/* Just some basic sanity checks on FCP Command frame */
15257 		fctl = (fc_hdr->fh_f_ctl[0] << 16 |
15258 			fc_hdr->fh_f_ctl[1] << 8 |
15259 			fc_hdr->fh_f_ctl[2]);
15260 		if (((fctl &
15261 		    (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) !=
15262 		    (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) ||
15263 		    (fc_hdr->fh_seq_cnt != 0)) /* 0 byte swapped is still 0 */
15264 			goto drop;
15265 
15266 		if (fc_hdr->fh_type == FC_TYPE_FCP) {
15267 			dma_buf->bytes_recv = bf_get(lpfc_rcqe_length, rcqe);
15268 			lpfc_nvmet_unsol_fcp_event(
15269 				phba, idx, dma_buf, cq->isr_timestamp,
15270 				cq->q_flag & HBA_NVMET_CQ_NOTIFY);
15271 			return false;
15272 		}
15273 drop:
15274 		lpfc_rq_buf_free(phba, &dma_buf->hbuf);
15275 		break;
15276 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
15277 		if (phba->nvmet_support) {
15278 			tgtp = phba->targetport->private;
15279 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15280 					"6401 RQE Error x%x, posted %d err_cnt "
15281 					"%d: %x %x %x\n",
15282 					status, hrq->RQ_buf_posted,
15283 					hrq->RQ_no_posted_buf,
15284 					atomic_read(&tgtp->rcv_fcp_cmd_in),
15285 					atomic_read(&tgtp->rcv_fcp_cmd_out),
15286 					atomic_read(&tgtp->xmt_fcp_release));
15287 		}
15288 		fallthrough;
15289 
15290 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
15291 		hrq->RQ_no_posted_buf++;
15292 		/* Post more buffers if possible */
15293 		break;
15294 	case FC_STATUS_RQ_DMA_FAILURE:
15295 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15296 				"2575 RQE DMA Error x%x, x%08x x%08x x%08x "
15297 				"x%08x\n",
15298 				status, rcqe->word0, rcqe->word1,
15299 				rcqe->word2, rcqe->word3);
15300 
15301 		/* If IV set, no further recovery */
15302 		if (bf_get(lpfc_rcqe_iv, rcqe))
15303 			break;
15304 
15305 		/* recycle consumed resource */
15306 		spin_lock_irqsave(&phba->hbalock, iflags);
15307 		lpfc_sli4_rq_release(hrq, drq);
15308 		dma_buf = lpfc_sli_rqbuf_get(phba, hrq);
15309 		if (!dma_buf) {
15310 			hrq->RQ_no_buf_found++;
15311 			spin_unlock_irqrestore(&phba->hbalock, iflags);
15312 			break;
15313 		}
15314 		hrq->RQ_rcv_buf++;
15315 		hrq->RQ_buf_posted--;
15316 		spin_unlock_irqrestore(&phba->hbalock, iflags);
15317 		lpfc_rq_buf_free(phba, &dma_buf->hbuf);
15318 		break;
15319 	default:
15320 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15321 				"2576 Unexpected RQE Status x%x, w0-3 x%08x "
15322 				"x%08x x%08x x%08x\n",
15323 				status, rcqe->word0, rcqe->word1,
15324 				rcqe->word2, rcqe->word3);
15325 		break;
15326 	}
15327 out:
15328 	return workposted;
15329 }
15330 
15331 /**
15332  * lpfc_sli4_fp_handle_cqe - Process fast-path work queue completion entry
15333  * @phba: adapter with cq
15334  * @cq: Pointer to the completion queue.
15335  * @cqe: Pointer to fast-path completion queue entry.
15336  *
15337  * This routine process a fast-path work queue completion entry from fast-path
15338  * event queue for FCP command response completion.
15339  *
15340  * Return: true if work posted to worker thread, otherwise false.
15341  **/
15342 static bool
15343 lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15344 			 struct lpfc_cqe *cqe)
15345 {
15346 	struct lpfc_wcqe_release wcqe;
15347 	bool workposted = false;
15348 
15349 	/* Copy the work queue CQE and convert endian order if needed */
15350 	lpfc_sli4_pcimem_bcopy(cqe, &wcqe, sizeof(struct lpfc_cqe));
15351 
15352 	/* Check and process for different type of WCQE and dispatch */
15353 	switch (bf_get(lpfc_wcqe_c_code, &wcqe)) {
15354 	case CQE_CODE_COMPL_WQE:
15355 	case CQE_CODE_NVME_ERSP:
15356 		cq->CQ_wq++;
15357 		/* Process the WQ complete event */
15358 		phba->last_completion_time = jiffies;
15359 		if (cq->subtype == LPFC_IO || cq->subtype == LPFC_NVME_LS)
15360 			lpfc_sli4_fp_handle_fcp_wcqe(phba, cq,
15361 				(struct lpfc_wcqe_complete *)&wcqe);
15362 		break;
15363 	case CQE_CODE_RELEASE_WQE:
15364 		cq->CQ_release_wqe++;
15365 		/* Process the WQ release event */
15366 		lpfc_sli4_fp_handle_rel_wcqe(phba, cq,
15367 				(struct lpfc_wcqe_release *)&wcqe);
15368 		break;
15369 	case CQE_CODE_XRI_ABORTED:
15370 		cq->CQ_xri_aborted++;
15371 		/* Process the WQ XRI abort event */
15372 		phba->last_completion_time = jiffies;
15373 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
15374 				(struct sli4_wcqe_xri_aborted *)&wcqe);
15375 		break;
15376 	case CQE_CODE_RECEIVE_V1:
15377 	case CQE_CODE_RECEIVE:
15378 		phba->last_completion_time = jiffies;
15379 		if (cq->subtype == LPFC_NVMET) {
15380 			workposted = lpfc_sli4_nvmet_handle_rcqe(
15381 				phba, cq, (struct lpfc_rcqe *)&wcqe);
15382 		}
15383 		break;
15384 	default:
15385 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15386 				"0144 Not a valid CQE code: x%x\n",
15387 				bf_get(lpfc_wcqe_c_code, &wcqe));
15388 		break;
15389 	}
15390 	return workposted;
15391 }
15392 
15393 /**
15394  * __lpfc_sli4_hba_process_cq - Process a fast-path event queue entry
15395  * @cq: Pointer to CQ to be processed
15396  *
15397  * This routine calls the cq processing routine with the handler for
15398  * fast path CQEs.
15399  *
15400  * The CQ routine returns two values: the first is the calling status,
15401  * which indicates whether work was queued to the  background discovery
15402  * thread. If true, the routine should wakeup the discovery thread;
15403  * the second is the delay parameter. If non-zero, rather than rearming
15404  * the CQ and yet another interrupt, the CQ handler should be queued so
15405  * that it is processed in a subsequent polling action. The value of
15406  * the delay indicates when to reschedule it.
15407  **/
15408 static void
15409 __lpfc_sli4_hba_process_cq(struct lpfc_queue *cq)
15410 {
15411 	struct lpfc_hba *phba = cq->phba;
15412 	unsigned long delay;
15413 	bool workposted = false;
15414 	int ret;
15415 
15416 	/* process and rearm the CQ */
15417 	workposted |= __lpfc_sli4_process_cq(phba, cq, lpfc_sli4_fp_handle_cqe,
15418 					     &delay);
15419 
15420 	if (delay) {
15421 		if (is_kdump_kernel())
15422 			ret = queue_delayed_work(phba->wq, &cq->sched_irqwork,
15423 						delay);
15424 		else
15425 			ret = queue_delayed_work_on(cq->chann, phba->wq,
15426 						&cq->sched_irqwork, delay);
15427 		if (!ret)
15428 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15429 					"0367 Cannot schedule queue work "
15430 					"for cqid=%d on CPU %d\n",
15431 					cq->queue_id, cq->chann);
15432 	}
15433 
15434 	/* wake up worker thread if there are works to be done */
15435 	if (workposted)
15436 		lpfc_worker_wake_up(phba);
15437 }
15438 
15439 /**
15440  * lpfc_sli4_hba_process_cq - fast-path work handler when started by
15441  *   interrupt
15442  * @work: pointer to work element
15443  *
15444  * translates from the work handler and calls the fast-path handler.
15445  **/
15446 static void
15447 lpfc_sli4_hba_process_cq(struct work_struct *work)
15448 {
15449 	struct lpfc_queue *cq = container_of(work, struct lpfc_queue, irqwork);
15450 
15451 	__lpfc_sli4_hba_process_cq(cq);
15452 }
15453 
15454 /**
15455  * lpfc_sli4_hba_handle_eqe - Process a fast-path event queue entry
15456  * @phba: Pointer to HBA context object.
15457  * @eq: Pointer to the queue structure.
15458  * @eqe: Pointer to fast-path event queue entry.
15459  * @poll_mode: poll_mode to execute processing the cq.
15460  *
15461  * This routine process a event queue entry from the fast-path event queue.
15462  * It will check the MajorCode and MinorCode to determine this is for a
15463  * completion event on a completion queue, if not, an error shall be logged
15464  * and just return. Otherwise, it will get to the corresponding completion
15465  * queue and process all the entries on the completion queue, rearm the
15466  * completion queue, and then return.
15467  **/
15468 static void
15469 lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba, struct lpfc_queue *eq,
15470 			 struct lpfc_eqe *eqe, enum lpfc_poll_mode poll_mode)
15471 {
15472 	struct lpfc_queue *cq = NULL;
15473 	uint32_t qidx = eq->hdwq;
15474 	uint16_t cqid, id;
15475 	int ret;
15476 
15477 	if (unlikely(bf_get_le32(lpfc_eqe_major_code, eqe) != 0)) {
15478 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15479 				"0366 Not a valid completion "
15480 				"event: majorcode=x%x, minorcode=x%x\n",
15481 				bf_get_le32(lpfc_eqe_major_code, eqe),
15482 				bf_get_le32(lpfc_eqe_minor_code, eqe));
15483 		return;
15484 	}
15485 
15486 	/* Get the reference to the corresponding CQ */
15487 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
15488 
15489 	/* Use the fast lookup method first */
15490 	if (cqid <= phba->sli4_hba.cq_max) {
15491 		cq = phba->sli4_hba.cq_lookup[cqid];
15492 		if (cq)
15493 			goto  work_cq;
15494 	}
15495 
15496 	/* Next check for NVMET completion */
15497 	if (phba->cfg_nvmet_mrq && phba->sli4_hba.nvmet_cqset) {
15498 		id = phba->sli4_hba.nvmet_cqset[0]->queue_id;
15499 		if ((cqid >= id) && (cqid < (id + phba->cfg_nvmet_mrq))) {
15500 			/* Process NVMET unsol rcv */
15501 			cq = phba->sli4_hba.nvmet_cqset[cqid - id];
15502 			goto  process_cq;
15503 		}
15504 	}
15505 
15506 	if (phba->sli4_hba.nvmels_cq &&
15507 	    (cqid == phba->sli4_hba.nvmels_cq->queue_id)) {
15508 		/* Process NVME unsol rcv */
15509 		cq = phba->sli4_hba.nvmels_cq;
15510 	}
15511 
15512 	/* Otherwise this is a Slow path event */
15513 	if (cq == NULL) {
15514 		lpfc_sli4_sp_handle_eqe(phba, eqe,
15515 					phba->sli4_hba.hdwq[qidx].hba_eq);
15516 		return;
15517 	}
15518 
15519 process_cq:
15520 	if (unlikely(cqid != cq->queue_id)) {
15521 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15522 				"0368 Miss-matched fast-path completion "
15523 				"queue identifier: eqcqid=%d, fcpcqid=%d\n",
15524 				cqid, cq->queue_id);
15525 		return;
15526 	}
15527 
15528 work_cq:
15529 #if defined(CONFIG_SCSI_LPFC_DEBUG_FS)
15530 	if (phba->ktime_on)
15531 		cq->isr_timestamp = ktime_get_ns();
15532 	else
15533 		cq->isr_timestamp = 0;
15534 #endif
15535 
15536 	switch (poll_mode) {
15537 	case LPFC_THREADED_IRQ:
15538 		__lpfc_sli4_hba_process_cq(cq);
15539 		break;
15540 	case LPFC_QUEUE_WORK:
15541 	default:
15542 		if (is_kdump_kernel())
15543 			ret = queue_work(phba->wq, &cq->irqwork);
15544 		else
15545 			ret = queue_work_on(cq->chann, phba->wq, &cq->irqwork);
15546 		if (!ret)
15547 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15548 					"0383 Cannot schedule queue work "
15549 					"for CQ eqcqid=%d, cqid=%d on CPU %d\n",
15550 					cqid, cq->queue_id,
15551 					raw_smp_processor_id());
15552 		break;
15553 	}
15554 }
15555 
15556 /**
15557  * lpfc_sli4_dly_hba_process_cq - fast-path work handler when started by timer
15558  * @work: pointer to work element
15559  *
15560  * translates from the work handler and calls the fast-path handler.
15561  **/
15562 static void
15563 lpfc_sli4_dly_hba_process_cq(struct work_struct *work)
15564 {
15565 	struct lpfc_queue *cq = container_of(to_delayed_work(work),
15566 					struct lpfc_queue, sched_irqwork);
15567 
15568 	__lpfc_sli4_hba_process_cq(cq);
15569 }
15570 
15571 /**
15572  * lpfc_sli4_hba_intr_handler - HBA interrupt handler to SLI-4 device
15573  * @irq: Interrupt number.
15574  * @dev_id: The device context pointer.
15575  *
15576  * This function is directly called from the PCI layer as an interrupt
15577  * service routine when device with SLI-4 interface spec is enabled with
15578  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
15579  * ring event in the HBA. However, when the device is enabled with either
15580  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
15581  * device-level interrupt handler. When the PCI slot is in error recovery
15582  * or the HBA is undergoing initialization, the interrupt handler will not
15583  * process the interrupt. The SCSI FCP fast-path ring event are handled in
15584  * the interrupt context. This function is called without any lock held.
15585  * It gets the hbalock to access and update SLI data structures. Note that,
15586  * the FCP EQ to FCP CQ are one-to-one map such that the FCP EQ index is
15587  * equal to that of FCP CQ index.
15588  *
15589  * The link attention and ELS ring attention events are handled
15590  * by the worker thread. The interrupt handler signals the worker thread
15591  * and returns for these events. This function is called without any lock
15592  * held. It gets the hbalock to access and update SLI data structures.
15593  *
15594  * This function returns IRQ_HANDLED when interrupt is handled, IRQ_WAKE_THREAD
15595  * when interrupt is scheduled to be handled from a threaded irq context, or
15596  * else returns IRQ_NONE.
15597  **/
15598 irqreturn_t
15599 lpfc_sli4_hba_intr_handler(int irq, void *dev_id)
15600 {
15601 	struct lpfc_hba *phba;
15602 	struct lpfc_hba_eq_hdl *hba_eq_hdl;
15603 	struct lpfc_queue *fpeq;
15604 	unsigned long iflag;
15605 	int hba_eqidx;
15606 	int ecount = 0;
15607 	struct lpfc_eq_intr_info *eqi;
15608 
15609 	/* Get the driver's phba structure from the dev_id */
15610 	hba_eq_hdl = (struct lpfc_hba_eq_hdl *)dev_id;
15611 	phba = hba_eq_hdl->phba;
15612 	hba_eqidx = hba_eq_hdl->idx;
15613 
15614 	if (unlikely(!phba))
15615 		return IRQ_NONE;
15616 	if (unlikely(!phba->sli4_hba.hdwq))
15617 		return IRQ_NONE;
15618 
15619 	/* Get to the EQ struct associated with this vector */
15620 	fpeq = phba->sli4_hba.hba_eq_hdl[hba_eqidx].eq;
15621 	if (unlikely(!fpeq))
15622 		return IRQ_NONE;
15623 
15624 	/* Check device state for handling interrupt */
15625 	if (unlikely(lpfc_intr_state_check(phba))) {
15626 		/* Check again for link_state with lock held */
15627 		spin_lock_irqsave(&phba->hbalock, iflag);
15628 		if (phba->link_state < LPFC_LINK_DOWN)
15629 			/* Flush, clear interrupt, and rearm the EQ */
15630 			lpfc_sli4_eqcq_flush(phba, fpeq);
15631 		spin_unlock_irqrestore(&phba->hbalock, iflag);
15632 		return IRQ_NONE;
15633 	}
15634 
15635 	switch (fpeq->poll_mode) {
15636 	case LPFC_THREADED_IRQ:
15637 		/* CGN mgmt is mutually exclusive from irq processing */
15638 		if (phba->cmf_active_mode == LPFC_CFG_OFF)
15639 			return IRQ_WAKE_THREAD;
15640 		fallthrough;
15641 	case LPFC_QUEUE_WORK:
15642 	default:
15643 		eqi = this_cpu_ptr(phba->sli4_hba.eq_info);
15644 		eqi->icnt++;
15645 
15646 		fpeq->last_cpu = raw_smp_processor_id();
15647 
15648 		if (eqi->icnt > LPFC_EQD_ISR_TRIGGER &&
15649 		    fpeq->q_flag & HBA_EQ_DELAY_CHK &&
15650 		    phba->cfg_auto_imax &&
15651 		    fpeq->q_mode != LPFC_MAX_AUTO_EQ_DELAY &&
15652 		    phba->sli.sli_flag & LPFC_SLI_USE_EQDR)
15653 			lpfc_sli4_mod_hba_eq_delay(phba, fpeq,
15654 						   LPFC_MAX_AUTO_EQ_DELAY);
15655 
15656 		/* process and rearm the EQ */
15657 		ecount = lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM,
15658 					      LPFC_QUEUE_WORK);
15659 
15660 		if (unlikely(ecount == 0)) {
15661 			fpeq->EQ_no_entry++;
15662 			if (phba->intr_type == MSIX)
15663 				/* MSI-X treated interrupt served as no EQ share INT */
15664 				lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15665 						"0358 MSI-X interrupt with no EQE\n");
15666 			else
15667 				/* Non MSI-X treated on interrupt as EQ share INT */
15668 				return IRQ_NONE;
15669 		}
15670 	}
15671 
15672 	return IRQ_HANDLED;
15673 } /* lpfc_sli4_hba_intr_handler */
15674 
15675 /**
15676  * lpfc_sli4_intr_handler - Device-level interrupt handler for SLI-4 device
15677  * @irq: Interrupt number.
15678  * @dev_id: The device context pointer.
15679  *
15680  * This function is the device-level interrupt handler to device with SLI-4
15681  * interface spec, called from the PCI layer when either MSI or Pin-IRQ
15682  * interrupt mode is enabled and there is an event in the HBA which requires
15683  * driver attention. This function invokes the slow-path interrupt attention
15684  * handling function and fast-path interrupt attention handling function in
15685  * turn to process the relevant HBA attention events. This function is called
15686  * without any lock held. It gets the hbalock to access and update SLI data
15687  * structures.
15688  *
15689  * This function returns IRQ_HANDLED when interrupt is handled, else it
15690  * returns IRQ_NONE.
15691  **/
15692 irqreturn_t
15693 lpfc_sli4_intr_handler(int irq, void *dev_id)
15694 {
15695 	struct lpfc_hba  *phba;
15696 	irqreturn_t hba_irq_rc;
15697 	bool hba_handled = false;
15698 	int qidx;
15699 
15700 	/* Get the driver's phba structure from the dev_id */
15701 	phba = (struct lpfc_hba *)dev_id;
15702 
15703 	if (unlikely(!phba))
15704 		return IRQ_NONE;
15705 
15706 	/*
15707 	 * Invoke fast-path host attention interrupt handling as appropriate.
15708 	 */
15709 	for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
15710 		hba_irq_rc = lpfc_sli4_hba_intr_handler(irq,
15711 					&phba->sli4_hba.hba_eq_hdl[qidx]);
15712 		if (hba_irq_rc == IRQ_HANDLED)
15713 			hba_handled |= true;
15714 	}
15715 
15716 	return (hba_handled == true) ? IRQ_HANDLED : IRQ_NONE;
15717 } /* lpfc_sli4_intr_handler */
15718 
15719 void lpfc_sli4_poll_hbtimer(struct timer_list *t)
15720 {
15721 	struct lpfc_hba *phba = timer_container_of(phba, t, cpuhp_poll_timer);
15722 	struct lpfc_queue *eq;
15723 
15724 	rcu_read_lock();
15725 
15726 	list_for_each_entry_rcu(eq, &phba->poll_list, _poll_list)
15727 		lpfc_sli4_poll_eq(eq);
15728 	if (!list_empty(&phba->poll_list))
15729 		mod_timer(&phba->cpuhp_poll_timer,
15730 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
15731 
15732 	rcu_read_unlock();
15733 }
15734 
15735 static inline void lpfc_sli4_add_to_poll_list(struct lpfc_queue *eq)
15736 {
15737 	struct lpfc_hba *phba = eq->phba;
15738 
15739 	/* kickstart slowpath processing if needed */
15740 	if (list_empty(&phba->poll_list))
15741 		mod_timer(&phba->cpuhp_poll_timer,
15742 			  jiffies + msecs_to_jiffies(LPFC_POLL_HB));
15743 
15744 	list_add_rcu(&eq->_poll_list, &phba->poll_list);
15745 	synchronize_rcu();
15746 }
15747 
15748 static inline void lpfc_sli4_remove_from_poll_list(struct lpfc_queue *eq)
15749 {
15750 	struct lpfc_hba *phba = eq->phba;
15751 
15752 	/* Disable slowpath processing for this eq.  Kick start the eq
15753 	 * by RE-ARMING the eq's ASAP
15754 	 */
15755 	list_del_rcu(&eq->_poll_list);
15756 	synchronize_rcu();
15757 
15758 	if (list_empty(&phba->poll_list))
15759 		timer_delete_sync(&phba->cpuhp_poll_timer);
15760 }
15761 
15762 void lpfc_sli4_cleanup_poll_list(struct lpfc_hba *phba)
15763 {
15764 	struct lpfc_queue *eq, *next;
15765 
15766 	list_for_each_entry_safe(eq, next, &phba->poll_list, _poll_list)
15767 		list_del(&eq->_poll_list);
15768 
15769 	INIT_LIST_HEAD(&phba->poll_list);
15770 	synchronize_rcu();
15771 }
15772 
15773 static inline void
15774 __lpfc_sli4_switch_eqmode(struct lpfc_queue *eq, uint8_t mode)
15775 {
15776 	if (mode == eq->mode)
15777 		return;
15778 	/*
15779 	 * currently this function is only called during a hotplug
15780 	 * event and the cpu on which this function is executing
15781 	 * is going offline.  By now the hotplug has instructed
15782 	 * the scheduler to remove this cpu from cpu active mask.
15783 	 * So we don't need to work about being put aside by the
15784 	 * scheduler for a high priority process.  Yes, the inte-
15785 	 * rrupts could come but they are known to retire ASAP.
15786 	 */
15787 
15788 	/* Disable polling in the fastpath */
15789 	WRITE_ONCE(eq->mode, mode);
15790 	/* flush out the store buffer */
15791 	smp_wmb();
15792 
15793 	/*
15794 	 * Add this eq to the polling list and start polling. For
15795 	 * a grace period both interrupt handler and poller will
15796 	 * try to process the eq _but_ that's fine.  We have a
15797 	 * synchronization mechanism in place (queue_claimed) to
15798 	 * deal with it.  This is just a draining phase for int-
15799 	 * errupt handler (not eq's) as we have guranteed through
15800 	 * barrier that all the CPUs have seen the new CQ_POLLED
15801 	 * state. which will effectively disable the REARMING of
15802 	 * the EQ.  The whole idea is eq's die off eventually as
15803 	 * we are not rearming EQ's anymore.
15804 	 */
15805 	mode ? lpfc_sli4_add_to_poll_list(eq) :
15806 	       lpfc_sli4_remove_from_poll_list(eq);
15807 }
15808 
15809 void lpfc_sli4_start_polling(struct lpfc_queue *eq)
15810 {
15811 	__lpfc_sli4_switch_eqmode(eq, LPFC_EQ_POLL);
15812 }
15813 
15814 void lpfc_sli4_stop_polling(struct lpfc_queue *eq)
15815 {
15816 	struct lpfc_hba *phba = eq->phba;
15817 
15818 	__lpfc_sli4_switch_eqmode(eq, LPFC_EQ_INTERRUPT);
15819 
15820 	/* Kick start for the pending io's in h/w.
15821 	 * Once we switch back to interrupt processing on a eq
15822 	 * the io path completion will only arm eq's when it
15823 	 * receives a completion.  But since eq's are in disa-
15824 	 * rmed state it doesn't receive a completion.  This
15825 	 * creates a deadlock scenaro.
15826 	 */
15827 	phba->sli4_hba.sli4_write_eq_db(phba, eq, 0, LPFC_QUEUE_REARM);
15828 }
15829 
15830 /**
15831  * lpfc_sli4_queue_free - free a queue structure and associated memory
15832  * @queue: The queue structure to free.
15833  *
15834  * This function frees a queue structure and the DMAable memory used for
15835  * the host resident queue. This function must be called after destroying the
15836  * queue on the HBA.
15837  **/
15838 void
15839 lpfc_sli4_queue_free(struct lpfc_queue *queue)
15840 {
15841 	struct lpfc_dmabuf *dmabuf;
15842 
15843 	if (!queue)
15844 		return;
15845 
15846 	if (!list_empty(&queue->wq_list))
15847 		list_del(&queue->wq_list);
15848 
15849 	while (!list_empty(&queue->page_list)) {
15850 		list_remove_head(&queue->page_list, dmabuf, struct lpfc_dmabuf,
15851 				 list);
15852 		dma_free_coherent(&queue->phba->pcidev->dev, queue->page_size,
15853 				  dmabuf->virt, dmabuf->phys);
15854 		kfree(dmabuf);
15855 	}
15856 	if (queue->rqbp) {
15857 		lpfc_free_rq_buffer(queue->phba, queue);
15858 		kfree(queue->rqbp);
15859 	}
15860 
15861 	if (!list_empty(&queue->cpu_list))
15862 		list_del(&queue->cpu_list);
15863 
15864 	kfree(queue);
15865 	return;
15866 }
15867 
15868 /**
15869  * lpfc_sli4_queue_alloc - Allocate and initialize a queue structure
15870  * @phba: The HBA that this queue is being created on.
15871  * @page_size: The size of a queue page
15872  * @entry_size: The size of each queue entry for this queue.
15873  * @entry_count: The number of entries that this queue will handle.
15874  * @cpu: The cpu that will primarily utilize this queue.
15875  *
15876  * This function allocates a queue structure and the DMAable memory used for
15877  * the host resident queue. This function must be called before creating the
15878  * queue on the HBA.
15879  **/
15880 struct lpfc_queue *
15881 lpfc_sli4_queue_alloc(struct lpfc_hba *phba, uint32_t page_size,
15882 		      uint32_t entry_size, uint32_t entry_count, int cpu)
15883 {
15884 	struct lpfc_queue *queue;
15885 	struct lpfc_dmabuf *dmabuf;
15886 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15887 	uint16_t x, pgcnt;
15888 
15889 	if (!phba->sli4_hba.pc_sli4_params.supported)
15890 		hw_page_size = page_size;
15891 
15892 	pgcnt = ALIGN(entry_size * entry_count, hw_page_size) / hw_page_size;
15893 
15894 	/* If needed, Adjust page count to match the max the adapter supports */
15895 	if (pgcnt > phba->sli4_hba.pc_sli4_params.wqpcnt)
15896 		pgcnt = phba->sli4_hba.pc_sli4_params.wqpcnt;
15897 
15898 	queue = kzalloc_node(struct_size(queue, q_pgs, pgcnt),
15899 			     GFP_KERNEL, cpu_to_node(cpu));
15900 	if (!queue)
15901 		return NULL;
15902 
15903 	INIT_LIST_HEAD(&queue->list);
15904 	INIT_LIST_HEAD(&queue->_poll_list);
15905 	INIT_LIST_HEAD(&queue->wq_list);
15906 	INIT_LIST_HEAD(&queue->wqfull_list);
15907 	INIT_LIST_HEAD(&queue->page_list);
15908 	INIT_LIST_HEAD(&queue->child_list);
15909 	INIT_LIST_HEAD(&queue->cpu_list);
15910 
15911 	/* Set queue parameters now.  If the system cannot provide memory
15912 	 * resources, the free routine needs to know what was allocated.
15913 	 */
15914 	queue->page_count = pgcnt;
15915 	queue->entry_cnt_per_pg = hw_page_size / entry_size;
15916 	queue->entry_size = entry_size;
15917 	queue->entry_count = entry_count;
15918 	queue->page_size = hw_page_size;
15919 	queue->phba = phba;
15920 
15921 	for (x = 0; x < queue->page_count; x++) {
15922 		dmabuf = kzalloc_node(sizeof(*dmabuf), GFP_KERNEL,
15923 				      dev_to_node(&phba->pcidev->dev));
15924 		if (!dmabuf)
15925 			goto out_fail;
15926 		dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
15927 						  hw_page_size, &dmabuf->phys,
15928 						  GFP_KERNEL);
15929 		if (!dmabuf->virt) {
15930 			kfree(dmabuf);
15931 			goto out_fail;
15932 		}
15933 		dmabuf->buffer_tag = x;
15934 		list_add_tail(&dmabuf->list, &queue->page_list);
15935 		/* use lpfc_sli4_qe to index a paritcular entry in this page */
15936 		queue->q_pgs[x] = dmabuf->virt;
15937 	}
15938 	INIT_WORK(&queue->irqwork, lpfc_sli4_hba_process_cq);
15939 	INIT_WORK(&queue->spwork, lpfc_sli4_sp_process_cq);
15940 	INIT_DELAYED_WORK(&queue->sched_irqwork, lpfc_sli4_dly_hba_process_cq);
15941 	INIT_DELAYED_WORK(&queue->sched_spwork, lpfc_sli4_dly_sp_process_cq);
15942 
15943 	/* notify_interval will be set during q creation */
15944 
15945 	return queue;
15946 out_fail:
15947 	lpfc_sli4_queue_free(queue);
15948 	return NULL;
15949 }
15950 
15951 /**
15952  * lpfc_dual_chute_pci_bar_map - Map pci base address register to host memory
15953  * @phba: HBA structure that indicates port to create a queue on.
15954  * @pci_barset: PCI BAR set flag.
15955  *
15956  * This function shall perform iomap of the specified PCI BAR address to host
15957  * memory address if not already done so and return it. The returned host
15958  * memory address can be NULL.
15959  */
15960 static void __iomem *
15961 lpfc_dual_chute_pci_bar_map(struct lpfc_hba *phba, uint16_t pci_barset)
15962 {
15963 	if (!phba->pcidev)
15964 		return NULL;
15965 
15966 	switch (pci_barset) {
15967 	case WQ_PCI_BAR_0_AND_1:
15968 		return phba->pci_bar0_memmap_p;
15969 	case WQ_PCI_BAR_2_AND_3:
15970 		return phba->pci_bar2_memmap_p;
15971 	case WQ_PCI_BAR_4_AND_5:
15972 		return phba->pci_bar4_memmap_p;
15973 	default:
15974 		break;
15975 	}
15976 	return NULL;
15977 }
15978 
15979 static __maybe_unused void __iomem *
15980 lpfc_dpp_wc_map(struct lpfc_hba *phba, uint8_t dpp_barset)
15981 {
15982 
15983 	/* DPP region is supposed to cover 64-bit BAR2 */
15984 	if (dpp_barset != WQ_PCI_BAR_4_AND_5) {
15985 		lpfc_log_msg(phba, KERN_WARNING, LOG_INIT,
15986 			     "3273 dpp_barset x%x != WQ_PCI_BAR_4_AND_5\n",
15987 			     dpp_barset);
15988 		return NULL;
15989 	}
15990 
15991 	if (!phba->sli4_hba.dpp_regs_memmap_wc_p) {
15992 		void __iomem *dpp_map;
15993 
15994 		dpp_map = ioremap_wc(phba->pci_bar2_map,
15995 				     pci_resource_len(phba->pcidev,
15996 						      PCI_64BIT_BAR4));
15997 
15998 		if (dpp_map)
15999 			phba->sli4_hba.dpp_regs_memmap_wc_p = dpp_map;
16000 	}
16001 
16002 	return phba->sli4_hba.dpp_regs_memmap_wc_p;
16003 }
16004 
16005 /**
16006  * lpfc_modify_hba_eq_delay - Modify Delay Multiplier on EQs
16007  * @phba: HBA structure that EQs are on.
16008  * @startq: The starting EQ index to modify
16009  * @numq: The number of EQs (consecutive indexes) to modify
16010  * @usdelay: amount of delay
16011  *
16012  * This function revises the EQ delay on 1 or more EQs. The EQ delay
16013  * is set either by writing to a register (if supported by the SLI Port)
16014  * or by mailbox command. The mailbox command allows several EQs to be
16015  * updated at once.
16016  *
16017  * The @phba struct is used to send a mailbox command to HBA. The @startq
16018  * is used to get the starting EQ index to change. The @numq value is
16019  * used to specify how many consecutive EQ indexes, starting at EQ index,
16020  * are to be changed. This function is asynchronous and will wait for any
16021  * mailbox commands to finish before returning.
16022  *
16023  * On success this function will return a zero. If unable to allocate
16024  * enough memory this function will return -ENOMEM. If a mailbox command
16025  * fails this function will return -ENXIO. Note: on ENXIO, some EQs may
16026  * have had their delay multiplier changed.
16027  **/
16028 void
16029 lpfc_modify_hba_eq_delay(struct lpfc_hba *phba, uint32_t startq,
16030 			 uint32_t numq, uint32_t usdelay)
16031 {
16032 	struct lpfc_mbx_modify_eq_delay *eq_delay;
16033 	LPFC_MBOXQ_t *mbox;
16034 	struct lpfc_queue *eq;
16035 	int cnt = 0, rc, length;
16036 	uint32_t shdr_status, shdr_add_status;
16037 	uint32_t dmult;
16038 	int qidx;
16039 	union lpfc_sli4_cfg_shdr *shdr;
16040 
16041 	if (startq >= phba->cfg_irq_chann)
16042 		return;
16043 
16044 	if (usdelay > 0xFFFF) {
16045 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP | LOG_NVME,
16046 				"6429 usdelay %d too large. Scaled down to "
16047 				"0xFFFF.\n", usdelay);
16048 		usdelay = 0xFFFF;
16049 	}
16050 
16051 	/* set values by EQ_DELAY register if supported */
16052 	if (phba->sli.sli_flag & LPFC_SLI_USE_EQDR) {
16053 		for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
16054 			eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
16055 			if (!eq)
16056 				continue;
16057 
16058 			lpfc_sli4_mod_hba_eq_delay(phba, eq, usdelay);
16059 
16060 			if (++cnt >= numq)
16061 				break;
16062 		}
16063 		return;
16064 	}
16065 
16066 	/* Otherwise, set values by mailbox cmd */
16067 
16068 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16069 	if (!mbox) {
16070 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16071 				"6428 Failed allocating mailbox cmd buffer."
16072 				" EQ delay was not set.\n");
16073 		return;
16074 	}
16075 	length = (sizeof(struct lpfc_mbx_modify_eq_delay) -
16076 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16077 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16078 			 LPFC_MBOX_OPCODE_MODIFY_EQ_DELAY,
16079 			 length, LPFC_SLI4_MBX_EMBED);
16080 	eq_delay = &mbox->u.mqe.un.eq_delay;
16081 
16082 	/* Calculate delay multiper from maximum interrupt per second */
16083 	dmult = (usdelay * LPFC_DMULT_CONST) / LPFC_SEC_TO_USEC;
16084 	if (dmult)
16085 		dmult--;
16086 	if (dmult > LPFC_DMULT_MAX)
16087 		dmult = LPFC_DMULT_MAX;
16088 
16089 	for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
16090 		eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
16091 		if (!eq)
16092 			continue;
16093 		eq->q_mode = usdelay;
16094 		eq_delay->u.request.eq[cnt].eq_id = eq->queue_id;
16095 		eq_delay->u.request.eq[cnt].phase = 0;
16096 		eq_delay->u.request.eq[cnt].delay_multi = dmult;
16097 
16098 		if (++cnt >= numq)
16099 			break;
16100 	}
16101 	eq_delay->u.request.num_eq = cnt;
16102 
16103 	mbox->vport = phba->pport;
16104 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16105 	mbox->ctx_ndlp = NULL;
16106 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16107 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_delay->header.cfg_shdr;
16108 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16109 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16110 	if (shdr_status || shdr_add_status || rc) {
16111 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16112 				"2512 MODIFY_EQ_DELAY mailbox failed with "
16113 				"status x%x add_status x%x, mbx status x%x\n",
16114 				shdr_status, shdr_add_status, rc);
16115 	}
16116 	mempool_free(mbox, phba->mbox_mem_pool);
16117 	return;
16118 }
16119 
16120 /**
16121  * lpfc_eq_create - Create an Event Queue on the HBA
16122  * @phba: HBA structure that indicates port to create a queue on.
16123  * @eq: The queue structure to use to create the event queue.
16124  * @imax: The maximum interrupt per second limit.
16125  *
16126  * This function creates an event queue, as detailed in @eq, on a port,
16127  * described by @phba by sending an EQ_CREATE mailbox command to the HBA.
16128  *
16129  * The @phba struct is used to send mailbox command to HBA. The @eq struct
16130  * is used to get the entry count and entry size that are necessary to
16131  * determine the number of pages to allocate and use for this queue. This
16132  * function will send the EQ_CREATE mailbox command to the HBA to setup the
16133  * event queue. This function is asynchronous and will wait for the mailbox
16134  * command to finish before continuing.
16135  *
16136  * On success this function will return a zero. If unable to allocate enough
16137  * memory this function will return -ENOMEM. If the queue create mailbox command
16138  * fails this function will return -ENXIO.
16139  **/
16140 int
16141 lpfc_eq_create(struct lpfc_hba *phba, struct lpfc_queue *eq, uint32_t imax)
16142 {
16143 	struct lpfc_mbx_eq_create *eq_create;
16144 	LPFC_MBOXQ_t *mbox;
16145 	int rc, length, status = 0;
16146 	struct lpfc_dmabuf *dmabuf;
16147 	uint32_t shdr_status, shdr_add_status;
16148 	union lpfc_sli4_cfg_shdr *shdr;
16149 	uint16_t dmult;
16150 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16151 
16152 	/* sanity check on queue memory */
16153 	if (!eq)
16154 		return -ENODEV;
16155 	if (!phba->sli4_hba.pc_sli4_params.supported)
16156 		hw_page_size = SLI4_PAGE_SIZE;
16157 
16158 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16159 	if (!mbox)
16160 		return -ENOMEM;
16161 	length = (sizeof(struct lpfc_mbx_eq_create) -
16162 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16163 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16164 			 LPFC_MBOX_OPCODE_EQ_CREATE,
16165 			 length, LPFC_SLI4_MBX_EMBED);
16166 	eq_create = &mbox->u.mqe.un.eq_create;
16167 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_create->header.cfg_shdr;
16168 	bf_set(lpfc_mbx_eq_create_num_pages, &eq_create->u.request,
16169 	       eq->page_count);
16170 	bf_set(lpfc_eq_context_size, &eq_create->u.request.context,
16171 	       LPFC_EQE_SIZE);
16172 	bf_set(lpfc_eq_context_valid, &eq_create->u.request.context, 1);
16173 
16174 	/* Use version 2 of CREATE_EQ if eqav is set */
16175 	if (phba->sli4_hba.pc_sli4_params.eqav) {
16176 		bf_set(lpfc_mbox_hdr_version, &shdr->request,
16177 		       LPFC_Q_CREATE_VERSION_2);
16178 		bf_set(lpfc_eq_context_autovalid, &eq_create->u.request.context,
16179 		       phba->sli4_hba.pc_sli4_params.eqav);
16180 	}
16181 
16182 	/* don't setup delay multiplier using EQ_CREATE */
16183 	dmult = 0;
16184 	bf_set(lpfc_eq_context_delay_multi, &eq_create->u.request.context,
16185 	       dmult);
16186 	switch (eq->entry_count) {
16187 	default:
16188 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16189 				"0360 Unsupported EQ count. (%d)\n",
16190 				eq->entry_count);
16191 		if (eq->entry_count < 256) {
16192 			status = -EINVAL;
16193 			goto out;
16194 		}
16195 		fallthrough;	/* otherwise default to smallest count */
16196 	case 256:
16197 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16198 		       LPFC_EQ_CNT_256);
16199 		break;
16200 	case 512:
16201 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16202 		       LPFC_EQ_CNT_512);
16203 		break;
16204 	case 1024:
16205 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16206 		       LPFC_EQ_CNT_1024);
16207 		break;
16208 	case 2048:
16209 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16210 		       LPFC_EQ_CNT_2048);
16211 		break;
16212 	case 4096:
16213 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16214 		       LPFC_EQ_CNT_4096);
16215 		break;
16216 	}
16217 	list_for_each_entry(dmabuf, &eq->page_list, list) {
16218 		memset(dmabuf->virt, 0, hw_page_size);
16219 		eq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16220 					putPaddrLow(dmabuf->phys);
16221 		eq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16222 					putPaddrHigh(dmabuf->phys);
16223 	}
16224 	mbox->vport = phba->pport;
16225 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16226 	mbox->ctx_buf = NULL;
16227 	mbox->ctx_ndlp = NULL;
16228 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16229 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16230 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16231 	if (shdr_status || shdr_add_status || rc) {
16232 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16233 				"2500 EQ_CREATE mailbox failed with "
16234 				"status x%x add_status x%x, mbx status x%x\n",
16235 				shdr_status, shdr_add_status, rc);
16236 		status = -ENXIO;
16237 	}
16238 	eq->type = LPFC_EQ;
16239 	eq->subtype = LPFC_NONE;
16240 	eq->queue_id = bf_get(lpfc_mbx_eq_create_q_id, &eq_create->u.response);
16241 	if (eq->queue_id == 0xFFFF)
16242 		status = -ENXIO;
16243 	eq->host_index = 0;
16244 	eq->notify_interval = LPFC_EQ_NOTIFY_INTRVL;
16245 	eq->max_proc_limit = LPFC_EQ_MAX_PROC_LIMIT;
16246 out:
16247 	mempool_free(mbox, phba->mbox_mem_pool);
16248 	return status;
16249 }
16250 
16251 /**
16252  * lpfc_sli4_hba_intr_handler_th - SLI4 HBA threaded interrupt handler
16253  * @irq: Interrupt number.
16254  * @dev_id: The device context pointer.
16255  *
16256  * This routine is a mirror of lpfc_sli4_hba_intr_handler, but executed within
16257  * threaded irq context.
16258  *
16259  * Returns
16260  * IRQ_HANDLED - interrupt is handled
16261  * IRQ_NONE - otherwise
16262  **/
16263 irqreturn_t lpfc_sli4_hba_intr_handler_th(int irq, void *dev_id)
16264 {
16265 	struct lpfc_hba *phba;
16266 	struct lpfc_hba_eq_hdl *hba_eq_hdl;
16267 	struct lpfc_queue *fpeq;
16268 	int ecount = 0;
16269 	int hba_eqidx;
16270 	struct lpfc_eq_intr_info *eqi;
16271 
16272 	/* Get the driver's phba structure from the dev_id */
16273 	hba_eq_hdl = (struct lpfc_hba_eq_hdl *)dev_id;
16274 	phba = hba_eq_hdl->phba;
16275 	hba_eqidx = hba_eq_hdl->idx;
16276 
16277 	if (unlikely(!phba))
16278 		return IRQ_NONE;
16279 	if (unlikely(!phba->sli4_hba.hdwq))
16280 		return IRQ_NONE;
16281 
16282 	/* Get to the EQ struct associated with this vector */
16283 	fpeq = phba->sli4_hba.hba_eq_hdl[hba_eqidx].eq;
16284 	if (unlikely(!fpeq))
16285 		return IRQ_NONE;
16286 
16287 	eqi = per_cpu_ptr(phba->sli4_hba.eq_info, raw_smp_processor_id());
16288 	eqi->icnt++;
16289 
16290 	fpeq->last_cpu = raw_smp_processor_id();
16291 
16292 	if (eqi->icnt > LPFC_EQD_ISR_TRIGGER &&
16293 	    fpeq->q_flag & HBA_EQ_DELAY_CHK &&
16294 	    phba->cfg_auto_imax &&
16295 	    fpeq->q_mode != LPFC_MAX_AUTO_EQ_DELAY &&
16296 	    phba->sli.sli_flag & LPFC_SLI_USE_EQDR)
16297 		lpfc_sli4_mod_hba_eq_delay(phba, fpeq, LPFC_MAX_AUTO_EQ_DELAY);
16298 
16299 	/* process and rearm the EQ */
16300 	ecount = lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM,
16301 				      LPFC_THREADED_IRQ);
16302 
16303 	if (unlikely(ecount == 0)) {
16304 		fpeq->EQ_no_entry++;
16305 		if (phba->intr_type == MSIX)
16306 			/* MSI-X treated interrupt served as no EQ share INT */
16307 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
16308 					"3358 MSI-X interrupt with no EQE\n");
16309 		else
16310 			/* Non MSI-X treated on interrupt as EQ share INT */
16311 			return IRQ_NONE;
16312 	}
16313 	return IRQ_HANDLED;
16314 }
16315 
16316 /**
16317  * lpfc_cq_create - Create a Completion Queue on the HBA
16318  * @phba: HBA structure that indicates port to create a queue on.
16319  * @cq: The queue structure to use to create the completion queue.
16320  * @eq: The event queue to bind this completion queue to.
16321  * @type: Type of queue (EQ, GCQ, MCQ, WCQ, etc).
16322  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
16323  *
16324  * This function creates a completion queue, as detailed in @wq, on a port,
16325  * described by @phba by sending a CQ_CREATE mailbox command to the HBA.
16326  *
16327  * The @phba struct is used to send mailbox command to HBA. The @cq struct
16328  * is used to get the entry count and entry size that are necessary to
16329  * determine the number of pages to allocate and use for this queue. The @eq
16330  * is used to indicate which event queue to bind this completion queue to. This
16331  * function will send the CQ_CREATE mailbox command to the HBA to setup the
16332  * completion queue. This function is asynchronous and will wait for the mailbox
16333  * command to finish before continuing.
16334  *
16335  * On success this function will return a zero. If unable to allocate enough
16336  * memory this function will return -ENOMEM. If the queue create mailbox command
16337  * fails this function will return -ENXIO.
16338  **/
16339 int
16340 lpfc_cq_create(struct lpfc_hba *phba, struct lpfc_queue *cq,
16341 	       struct lpfc_queue *eq, uint32_t type, uint32_t subtype)
16342 {
16343 	struct lpfc_mbx_cq_create *cq_create;
16344 	struct lpfc_dmabuf *dmabuf;
16345 	LPFC_MBOXQ_t *mbox;
16346 	int rc, length, status = 0;
16347 	uint32_t shdr_status, shdr_add_status;
16348 	union lpfc_sli4_cfg_shdr *shdr;
16349 
16350 	/* sanity check on queue memory */
16351 	if (!cq || !eq)
16352 		return -ENODEV;
16353 
16354 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16355 	if (!mbox)
16356 		return -ENOMEM;
16357 	length = (sizeof(struct lpfc_mbx_cq_create) -
16358 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16359 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16360 			 LPFC_MBOX_OPCODE_CQ_CREATE,
16361 			 length, LPFC_SLI4_MBX_EMBED);
16362 	cq_create = &mbox->u.mqe.un.cq_create;
16363 	shdr = (union lpfc_sli4_cfg_shdr *) &cq_create->header.cfg_shdr;
16364 	bf_set(lpfc_mbx_cq_create_num_pages, &cq_create->u.request,
16365 		    cq->page_count);
16366 	bf_set(lpfc_cq_context_event, &cq_create->u.request.context, 1);
16367 	bf_set(lpfc_cq_context_valid, &cq_create->u.request.context, 1);
16368 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16369 	       phba->sli4_hba.pc_sli4_params.cqv);
16370 	if (phba->sli4_hba.pc_sli4_params.cqv == LPFC_Q_CREATE_VERSION_2) {
16371 		bf_set(lpfc_mbx_cq_create_page_size, &cq_create->u.request,
16372 		       (cq->page_size / SLI4_PAGE_SIZE));
16373 		bf_set(lpfc_cq_eq_id_2, &cq_create->u.request.context,
16374 		       eq->queue_id);
16375 		bf_set(lpfc_cq_context_autovalid, &cq_create->u.request.context,
16376 		       phba->sli4_hba.pc_sli4_params.cqav);
16377 	} else {
16378 		bf_set(lpfc_cq_eq_id, &cq_create->u.request.context,
16379 		       eq->queue_id);
16380 	}
16381 	switch (cq->entry_count) {
16382 	case 2048:
16383 	case 4096:
16384 		if (phba->sli4_hba.pc_sli4_params.cqv ==
16385 		    LPFC_Q_CREATE_VERSION_2) {
16386 			cq_create->u.request.context.lpfc_cq_context_count =
16387 				cq->entry_count;
16388 			bf_set(lpfc_cq_context_count,
16389 			       &cq_create->u.request.context,
16390 			       LPFC_CQ_CNT_WORD7);
16391 			break;
16392 		}
16393 		fallthrough;
16394 	default:
16395 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16396 				"0361 Unsupported CQ count: "
16397 				"entry cnt %d sz %d pg cnt %d\n",
16398 				cq->entry_count, cq->entry_size,
16399 				cq->page_count);
16400 		if (cq->entry_count < 256) {
16401 			status = -EINVAL;
16402 			goto out;
16403 		}
16404 		fallthrough;	/* otherwise default to smallest count */
16405 	case 256:
16406 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
16407 		       LPFC_CQ_CNT_256);
16408 		break;
16409 	case 512:
16410 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
16411 		       LPFC_CQ_CNT_512);
16412 		break;
16413 	case 1024:
16414 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
16415 		       LPFC_CQ_CNT_1024);
16416 		break;
16417 	}
16418 	list_for_each_entry(dmabuf, &cq->page_list, list) {
16419 		memset(dmabuf->virt, 0, cq->page_size);
16420 		cq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16421 					putPaddrLow(dmabuf->phys);
16422 		cq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16423 					putPaddrHigh(dmabuf->phys);
16424 	}
16425 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16426 
16427 	/* The IOCTL status is embedded in the mailbox subheader. */
16428 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16429 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16430 	if (shdr_status || shdr_add_status || rc) {
16431 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16432 				"2501 CQ_CREATE mailbox failed with "
16433 				"status x%x add_status x%x, mbx status x%x\n",
16434 				shdr_status, shdr_add_status, rc);
16435 		status = -ENXIO;
16436 		goto out;
16437 	}
16438 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
16439 	if (cq->queue_id == 0xFFFF) {
16440 		status = -ENXIO;
16441 		goto out;
16442 	}
16443 	/* link the cq onto the parent eq child list */
16444 	list_add_tail(&cq->list, &eq->child_list);
16445 	/* Set up completion queue's type and subtype */
16446 	cq->type = type;
16447 	cq->subtype = subtype;
16448 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
16449 	cq->assoc_qid = eq->queue_id;
16450 	cq->assoc_qp = eq;
16451 	cq->host_index = 0;
16452 	cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
16453 	cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit, cq->entry_count);
16454 
16455 	if (cq->queue_id > phba->sli4_hba.cq_max)
16456 		phba->sli4_hba.cq_max = cq->queue_id;
16457 out:
16458 	mempool_free(mbox, phba->mbox_mem_pool);
16459 	return status;
16460 }
16461 
16462 /**
16463  * lpfc_cq_create_set - Create a set of Completion Queues on the HBA for MRQ
16464  * @phba: HBA structure that indicates port to create a queue on.
16465  * @cqp: The queue structure array to use to create the completion queues.
16466  * @hdwq: The hardware queue array  with the EQ to bind completion queues to.
16467  * @type: Type of queue (EQ, GCQ, MCQ, WCQ, etc).
16468  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
16469  *
16470  * This function creates a set of  completion queue, s to support MRQ
16471  * as detailed in @cqp, on a port,
16472  * described by @phba by sending a CREATE_CQ_SET mailbox command to the HBA.
16473  *
16474  * The @phba struct is used to send mailbox command to HBA. The @cq struct
16475  * is used to get the entry count and entry size that are necessary to
16476  * determine the number of pages to allocate and use for this queue. The @eq
16477  * is used to indicate which event queue to bind this completion queue to. This
16478  * function will send the CREATE_CQ_SET mailbox command to the HBA to setup the
16479  * completion queue. This function is asynchronous and will wait for the mailbox
16480  * command to finish before continuing.
16481  *
16482  * On success this function will return a zero. If unable to allocate enough
16483  * memory this function will return -ENOMEM. If the queue create mailbox command
16484  * fails this function will return -ENXIO.
16485  **/
16486 int
16487 lpfc_cq_create_set(struct lpfc_hba *phba, struct lpfc_queue **cqp,
16488 		   struct lpfc_sli4_hdw_queue *hdwq, uint32_t type,
16489 		   uint32_t subtype)
16490 {
16491 	struct lpfc_queue *cq;
16492 	struct lpfc_queue *eq;
16493 	struct lpfc_mbx_cq_create_set *cq_set;
16494 	struct lpfc_dmabuf *dmabuf;
16495 	LPFC_MBOXQ_t *mbox;
16496 	int rc, length, alloclen, status = 0;
16497 	int cnt, idx, numcq, page_idx = 0;
16498 	uint32_t shdr_status, shdr_add_status;
16499 	union lpfc_sli4_cfg_shdr *shdr;
16500 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16501 
16502 	/* sanity check on queue memory */
16503 	numcq = phba->cfg_nvmet_mrq;
16504 	if (!cqp || !hdwq || !numcq)
16505 		return -ENODEV;
16506 
16507 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16508 	if (!mbox)
16509 		return -ENOMEM;
16510 
16511 	length = sizeof(struct lpfc_mbx_cq_create_set);
16512 	length += ((numcq * cqp[0]->page_count) *
16513 		   sizeof(struct dma_address));
16514 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16515 			LPFC_MBOX_OPCODE_FCOE_CQ_CREATE_SET, length,
16516 			LPFC_SLI4_MBX_NEMBED);
16517 	if (alloclen < length) {
16518 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16519 				"3098 Allocated DMA memory size (%d) is "
16520 				"less than the requested DMA memory size "
16521 				"(%d)\n", alloclen, length);
16522 		status = -ENOMEM;
16523 		goto out;
16524 	}
16525 	cq_set = mbox->sge_array->addr[0];
16526 	shdr = (union lpfc_sli4_cfg_shdr *)&cq_set->cfg_shdr;
16527 	bf_set(lpfc_mbox_hdr_version, &shdr->request, 0);
16528 
16529 	for (idx = 0; idx < numcq; idx++) {
16530 		cq = cqp[idx];
16531 		eq = hdwq[idx].hba_eq;
16532 		if (!cq || !eq) {
16533 			status = -ENOMEM;
16534 			goto out;
16535 		}
16536 		if (!phba->sli4_hba.pc_sli4_params.supported)
16537 			hw_page_size = cq->page_size;
16538 
16539 		switch (idx) {
16540 		case 0:
16541 			bf_set(lpfc_mbx_cq_create_set_page_size,
16542 			       &cq_set->u.request,
16543 			       (hw_page_size / SLI4_PAGE_SIZE));
16544 			bf_set(lpfc_mbx_cq_create_set_num_pages,
16545 			       &cq_set->u.request, cq->page_count);
16546 			bf_set(lpfc_mbx_cq_create_set_evt,
16547 			       &cq_set->u.request, 1);
16548 			bf_set(lpfc_mbx_cq_create_set_valid,
16549 			       &cq_set->u.request, 1);
16550 			bf_set(lpfc_mbx_cq_create_set_cqe_size,
16551 			       &cq_set->u.request, 0);
16552 			bf_set(lpfc_mbx_cq_create_set_num_cq,
16553 			       &cq_set->u.request, numcq);
16554 			bf_set(lpfc_mbx_cq_create_set_autovalid,
16555 			       &cq_set->u.request,
16556 			       phba->sli4_hba.pc_sli4_params.cqav);
16557 			switch (cq->entry_count) {
16558 			case 2048:
16559 			case 4096:
16560 				if (phba->sli4_hba.pc_sli4_params.cqv ==
16561 				    LPFC_Q_CREATE_VERSION_2) {
16562 					bf_set(lpfc_mbx_cq_create_set_cqe_cnt_lo,
16563 					       &cq_set->u.request,
16564 					       cq->entry_count);
16565 					bf_set(lpfc_mbx_cq_create_set_cqecnt,
16566 					       &cq_set->u.request,
16567 					       LPFC_CQ_CNT_WORD7);
16568 					break;
16569 				}
16570 				fallthrough;
16571 			default:
16572 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16573 						"3118 Bad CQ count. (%d)\n",
16574 						cq->entry_count);
16575 				if (cq->entry_count < 256) {
16576 					status = -EINVAL;
16577 					goto out;
16578 				}
16579 				fallthrough;	/* otherwise default to smallest */
16580 			case 256:
16581 				bf_set(lpfc_mbx_cq_create_set_cqecnt,
16582 				       &cq_set->u.request, LPFC_CQ_CNT_256);
16583 				break;
16584 			case 512:
16585 				bf_set(lpfc_mbx_cq_create_set_cqecnt,
16586 				       &cq_set->u.request, LPFC_CQ_CNT_512);
16587 				break;
16588 			case 1024:
16589 				bf_set(lpfc_mbx_cq_create_set_cqecnt,
16590 				       &cq_set->u.request, LPFC_CQ_CNT_1024);
16591 				break;
16592 			}
16593 			bf_set(lpfc_mbx_cq_create_set_eq_id0,
16594 			       &cq_set->u.request, eq->queue_id);
16595 			break;
16596 		case 1:
16597 			bf_set(lpfc_mbx_cq_create_set_eq_id1,
16598 			       &cq_set->u.request, eq->queue_id);
16599 			break;
16600 		case 2:
16601 			bf_set(lpfc_mbx_cq_create_set_eq_id2,
16602 			       &cq_set->u.request, eq->queue_id);
16603 			break;
16604 		case 3:
16605 			bf_set(lpfc_mbx_cq_create_set_eq_id3,
16606 			       &cq_set->u.request, eq->queue_id);
16607 			break;
16608 		case 4:
16609 			bf_set(lpfc_mbx_cq_create_set_eq_id4,
16610 			       &cq_set->u.request, eq->queue_id);
16611 			break;
16612 		case 5:
16613 			bf_set(lpfc_mbx_cq_create_set_eq_id5,
16614 			       &cq_set->u.request, eq->queue_id);
16615 			break;
16616 		case 6:
16617 			bf_set(lpfc_mbx_cq_create_set_eq_id6,
16618 			       &cq_set->u.request, eq->queue_id);
16619 			break;
16620 		case 7:
16621 			bf_set(lpfc_mbx_cq_create_set_eq_id7,
16622 			       &cq_set->u.request, eq->queue_id);
16623 			break;
16624 		case 8:
16625 			bf_set(lpfc_mbx_cq_create_set_eq_id8,
16626 			       &cq_set->u.request, eq->queue_id);
16627 			break;
16628 		case 9:
16629 			bf_set(lpfc_mbx_cq_create_set_eq_id9,
16630 			       &cq_set->u.request, eq->queue_id);
16631 			break;
16632 		case 10:
16633 			bf_set(lpfc_mbx_cq_create_set_eq_id10,
16634 			       &cq_set->u.request, eq->queue_id);
16635 			break;
16636 		case 11:
16637 			bf_set(lpfc_mbx_cq_create_set_eq_id11,
16638 			       &cq_set->u.request, eq->queue_id);
16639 			break;
16640 		case 12:
16641 			bf_set(lpfc_mbx_cq_create_set_eq_id12,
16642 			       &cq_set->u.request, eq->queue_id);
16643 			break;
16644 		case 13:
16645 			bf_set(lpfc_mbx_cq_create_set_eq_id13,
16646 			       &cq_set->u.request, eq->queue_id);
16647 			break;
16648 		case 14:
16649 			bf_set(lpfc_mbx_cq_create_set_eq_id14,
16650 			       &cq_set->u.request, eq->queue_id);
16651 			break;
16652 		case 15:
16653 			bf_set(lpfc_mbx_cq_create_set_eq_id15,
16654 			       &cq_set->u.request, eq->queue_id);
16655 			break;
16656 		}
16657 
16658 		/* link the cq onto the parent eq child list */
16659 		list_add_tail(&cq->list, &eq->child_list);
16660 		/* Set up completion queue's type and subtype */
16661 		cq->type = type;
16662 		cq->subtype = subtype;
16663 		cq->assoc_qid = eq->queue_id;
16664 		cq->assoc_qp = eq;
16665 		cq->host_index = 0;
16666 		cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
16667 		cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit,
16668 					 cq->entry_count);
16669 		cq->chann = idx;
16670 
16671 		rc = 0;
16672 		list_for_each_entry(dmabuf, &cq->page_list, list) {
16673 			memset(dmabuf->virt, 0, hw_page_size);
16674 			cnt = page_idx + dmabuf->buffer_tag;
16675 			cq_set->u.request.page[cnt].addr_lo =
16676 					putPaddrLow(dmabuf->phys);
16677 			cq_set->u.request.page[cnt].addr_hi =
16678 					putPaddrHigh(dmabuf->phys);
16679 			rc++;
16680 		}
16681 		page_idx += rc;
16682 	}
16683 
16684 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16685 
16686 	/* The IOCTL status is embedded in the mailbox subheader. */
16687 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16688 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16689 	if (shdr_status || shdr_add_status || rc) {
16690 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16691 				"3119 CQ_CREATE_SET mailbox failed with "
16692 				"status x%x add_status x%x, mbx status x%x\n",
16693 				shdr_status, shdr_add_status, rc);
16694 		status = -ENXIO;
16695 		goto out;
16696 	}
16697 	rc = bf_get(lpfc_mbx_cq_create_set_base_id, &cq_set->u.response);
16698 	if (rc == 0xFFFF) {
16699 		status = -ENXIO;
16700 		goto out;
16701 	}
16702 
16703 	for (idx = 0; idx < numcq; idx++) {
16704 		cq = cqp[idx];
16705 		cq->queue_id = rc + idx;
16706 		if (cq->queue_id > phba->sli4_hba.cq_max)
16707 			phba->sli4_hba.cq_max = cq->queue_id;
16708 	}
16709 
16710 out:
16711 	lpfc_sli4_mbox_cmd_free(phba, mbox);
16712 	return status;
16713 }
16714 
16715 /**
16716  * lpfc_mq_create_fb_init - Send MCC_CREATE without async events registration
16717  * @phba: HBA structure that indicates port to create a queue on.
16718  * @mq: The queue structure to use to create the mailbox queue.
16719  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
16720  * @cq: The completion queue to associate with this cq.
16721  *
16722  * This function provides failback (fb) functionality when the
16723  * mq_create_ext fails on older FW generations.  It's purpose is identical
16724  * to mq_create_ext otherwise.
16725  *
16726  * This routine cannot fail as all attributes were previously accessed and
16727  * initialized in mq_create_ext.
16728  **/
16729 static void
16730 lpfc_mq_create_fb_init(struct lpfc_hba *phba, struct lpfc_queue *mq,
16731 		       LPFC_MBOXQ_t *mbox, struct lpfc_queue *cq)
16732 {
16733 	struct lpfc_mbx_mq_create *mq_create;
16734 	struct lpfc_dmabuf *dmabuf;
16735 	int length;
16736 
16737 	length = (sizeof(struct lpfc_mbx_mq_create) -
16738 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16739 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16740 			 LPFC_MBOX_OPCODE_MQ_CREATE,
16741 			 length, LPFC_SLI4_MBX_EMBED);
16742 	mq_create = &mbox->u.mqe.un.mq_create;
16743 	bf_set(lpfc_mbx_mq_create_num_pages, &mq_create->u.request,
16744 	       mq->page_count);
16745 	bf_set(lpfc_mq_context_cq_id, &mq_create->u.request.context,
16746 	       cq->queue_id);
16747 	bf_set(lpfc_mq_context_valid, &mq_create->u.request.context, 1);
16748 	switch (mq->entry_count) {
16749 	case 16:
16750 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16751 		       LPFC_MQ_RING_SIZE_16);
16752 		break;
16753 	case 32:
16754 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16755 		       LPFC_MQ_RING_SIZE_32);
16756 		break;
16757 	case 64:
16758 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16759 		       LPFC_MQ_RING_SIZE_64);
16760 		break;
16761 	case 128:
16762 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16763 		       LPFC_MQ_RING_SIZE_128);
16764 		break;
16765 	}
16766 	list_for_each_entry(dmabuf, &mq->page_list, list) {
16767 		mq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16768 			putPaddrLow(dmabuf->phys);
16769 		mq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16770 			putPaddrHigh(dmabuf->phys);
16771 	}
16772 }
16773 
16774 /**
16775  * lpfc_mq_create - Create a mailbox Queue on the HBA
16776  * @phba: HBA structure that indicates port to create a queue on.
16777  * @mq: The queue structure to use to create the mailbox queue.
16778  * @cq: The completion queue to associate with this cq.
16779  * @subtype: The queue's subtype.
16780  *
16781  * This function creates a mailbox queue, as detailed in @mq, on a port,
16782  * described by @phba by sending a MQ_CREATE mailbox command to the HBA.
16783  *
16784  * The @phba struct is used to send mailbox command to HBA. The @cq struct
16785  * is used to get the entry count and entry size that are necessary to
16786  * determine the number of pages to allocate and use for this queue. This
16787  * function will send the MQ_CREATE mailbox command to the HBA to setup the
16788  * mailbox queue. This function is asynchronous and will wait for the mailbox
16789  * command to finish before continuing.
16790  *
16791  * On success this function will return a zero. If unable to allocate enough
16792  * memory this function will return -ENOMEM. If the queue create mailbox command
16793  * fails this function will return -ENXIO.
16794  **/
16795 int32_t
16796 lpfc_mq_create(struct lpfc_hba *phba, struct lpfc_queue *mq,
16797 	       struct lpfc_queue *cq, uint32_t subtype)
16798 {
16799 	struct lpfc_mbx_mq_create *mq_create;
16800 	struct lpfc_mbx_mq_create_ext *mq_create_ext;
16801 	struct lpfc_dmabuf *dmabuf;
16802 	LPFC_MBOXQ_t *mbox;
16803 	int rc, length, status = 0;
16804 	uint32_t shdr_status, shdr_add_status;
16805 	union lpfc_sli4_cfg_shdr *shdr;
16806 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16807 
16808 	/* sanity check on queue memory */
16809 	if (!mq || !cq)
16810 		return -ENODEV;
16811 	if (!phba->sli4_hba.pc_sli4_params.supported)
16812 		hw_page_size = SLI4_PAGE_SIZE;
16813 
16814 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16815 	if (!mbox)
16816 		return -ENOMEM;
16817 	length = (sizeof(struct lpfc_mbx_mq_create_ext) -
16818 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16819 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16820 			 LPFC_MBOX_OPCODE_MQ_CREATE_EXT,
16821 			 length, LPFC_SLI4_MBX_EMBED);
16822 
16823 	mq_create_ext = &mbox->u.mqe.un.mq_create_ext;
16824 	shdr = (union lpfc_sli4_cfg_shdr *) &mq_create_ext->header.cfg_shdr;
16825 	bf_set(lpfc_mbx_mq_create_ext_num_pages,
16826 	       &mq_create_ext->u.request, mq->page_count);
16827 	bf_set(lpfc_mbx_mq_create_ext_async_evt_link,
16828 	       &mq_create_ext->u.request, 1);
16829 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fip,
16830 	       &mq_create_ext->u.request, 1);
16831 	bf_set(lpfc_mbx_mq_create_ext_async_evt_group5,
16832 	       &mq_create_ext->u.request, 1);
16833 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fc,
16834 	       &mq_create_ext->u.request, 1);
16835 	bf_set(lpfc_mbx_mq_create_ext_async_evt_sli,
16836 	       &mq_create_ext->u.request, 1);
16837 	bf_set(lpfc_mq_context_valid, &mq_create_ext->u.request.context, 1);
16838 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16839 	       phba->sli4_hba.pc_sli4_params.mqv);
16840 	if (phba->sli4_hba.pc_sli4_params.mqv == LPFC_Q_CREATE_VERSION_1)
16841 		bf_set(lpfc_mbx_mq_create_ext_cq_id, &mq_create_ext->u.request,
16842 		       cq->queue_id);
16843 	else
16844 		bf_set(lpfc_mq_context_cq_id, &mq_create_ext->u.request.context,
16845 		       cq->queue_id);
16846 	switch (mq->entry_count) {
16847 	default:
16848 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16849 				"0362 Unsupported MQ count. (%d)\n",
16850 				mq->entry_count);
16851 		if (mq->entry_count < 16) {
16852 			status = -EINVAL;
16853 			goto out;
16854 		}
16855 		fallthrough;	/* otherwise default to smallest count */
16856 	case 16:
16857 		bf_set(lpfc_mq_context_ring_size,
16858 		       &mq_create_ext->u.request.context,
16859 		       LPFC_MQ_RING_SIZE_16);
16860 		break;
16861 	case 32:
16862 		bf_set(lpfc_mq_context_ring_size,
16863 		       &mq_create_ext->u.request.context,
16864 		       LPFC_MQ_RING_SIZE_32);
16865 		break;
16866 	case 64:
16867 		bf_set(lpfc_mq_context_ring_size,
16868 		       &mq_create_ext->u.request.context,
16869 		       LPFC_MQ_RING_SIZE_64);
16870 		break;
16871 	case 128:
16872 		bf_set(lpfc_mq_context_ring_size,
16873 		       &mq_create_ext->u.request.context,
16874 		       LPFC_MQ_RING_SIZE_128);
16875 		break;
16876 	}
16877 	list_for_each_entry(dmabuf, &mq->page_list, list) {
16878 		memset(dmabuf->virt, 0, hw_page_size);
16879 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_lo =
16880 					putPaddrLow(dmabuf->phys);
16881 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_hi =
16882 					putPaddrHigh(dmabuf->phys);
16883 	}
16884 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16885 	mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
16886 			      &mq_create_ext->u.response);
16887 	if (rc != MBX_SUCCESS) {
16888 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16889 				"2795 MQ_CREATE_EXT failed with "
16890 				"status x%x. Failback to MQ_CREATE.\n",
16891 				rc);
16892 		lpfc_mq_create_fb_init(phba, mq, mbox, cq);
16893 		mq_create = &mbox->u.mqe.un.mq_create;
16894 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16895 		shdr = (union lpfc_sli4_cfg_shdr *) &mq_create->header.cfg_shdr;
16896 		mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
16897 				      &mq_create->u.response);
16898 	}
16899 
16900 	/* The IOCTL status is embedded in the mailbox subheader. */
16901 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16902 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16903 	if (shdr_status || shdr_add_status || rc) {
16904 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16905 				"2502 MQ_CREATE mailbox failed with "
16906 				"status x%x add_status x%x, mbx status x%x\n",
16907 				shdr_status, shdr_add_status, rc);
16908 		status = -ENXIO;
16909 		goto out;
16910 	}
16911 	if (mq->queue_id == 0xFFFF) {
16912 		status = -ENXIO;
16913 		goto out;
16914 	}
16915 	mq->type = LPFC_MQ;
16916 	mq->assoc_qid = cq->queue_id;
16917 	mq->subtype = subtype;
16918 	mq->host_index = 0;
16919 	mq->hba_index = 0;
16920 
16921 	/* link the mq onto the parent cq child list */
16922 	list_add_tail(&mq->list, &cq->child_list);
16923 out:
16924 	mempool_free(mbox, phba->mbox_mem_pool);
16925 	return status;
16926 }
16927 
16928 /**
16929  * lpfc_wq_create - Create a Work Queue on the HBA
16930  * @phba: HBA structure that indicates port to create a queue on.
16931  * @wq: The queue structure to use to create the work queue.
16932  * @cq: The completion queue to bind this work queue to.
16933  * @subtype: The subtype of the work queue indicating its functionality.
16934  *
16935  * This function creates a work queue, as detailed in @wq, on a port, described
16936  * by @phba by sending a WQ_CREATE mailbox command to the HBA.
16937  *
16938  * The @phba struct is used to send mailbox command to HBA. The @wq struct
16939  * is used to get the entry count and entry size that are necessary to
16940  * determine the number of pages to allocate and use for this queue. The @cq
16941  * is used to indicate which completion queue to bind this work queue to. This
16942  * function will send the WQ_CREATE mailbox command to the HBA to setup the
16943  * work queue. This function is asynchronous and will wait for the mailbox
16944  * command to finish before continuing.
16945  *
16946  * On success this function will return a zero. If unable to allocate enough
16947  * memory this function will return -ENOMEM. If the queue create mailbox command
16948  * fails this function will return -ENXIO.
16949  **/
16950 int
16951 lpfc_wq_create(struct lpfc_hba *phba, struct lpfc_queue *wq,
16952 	       struct lpfc_queue *cq, uint32_t subtype)
16953 {
16954 	struct lpfc_mbx_wq_create *wq_create;
16955 	struct lpfc_dmabuf *dmabuf;
16956 	LPFC_MBOXQ_t *mbox;
16957 	int rc, length, status = 0;
16958 	uint32_t shdr_status, shdr_add_status;
16959 	union lpfc_sli4_cfg_shdr *shdr;
16960 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16961 	struct dma_address *page;
16962 	void __iomem *bar_memmap_p;
16963 	uint32_t db_offset;
16964 	uint16_t pci_barset;
16965 	uint8_t dpp_barset;
16966 	uint32_t dpp_offset;
16967 	uint8_t wq_create_version;
16968 
16969 	/* sanity check on queue memory */
16970 	if (!wq || !cq)
16971 		return -ENODEV;
16972 	if (!phba->sli4_hba.pc_sli4_params.supported)
16973 		hw_page_size = wq->page_size;
16974 
16975 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16976 	if (!mbox)
16977 		return -ENOMEM;
16978 	length = (sizeof(struct lpfc_mbx_wq_create) -
16979 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16980 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16981 			 LPFC_MBOX_OPCODE_FCOE_WQ_CREATE,
16982 			 length, LPFC_SLI4_MBX_EMBED);
16983 	wq_create = &mbox->u.mqe.un.wq_create;
16984 	shdr = (union lpfc_sli4_cfg_shdr *) &wq_create->header.cfg_shdr;
16985 	bf_set(lpfc_mbx_wq_create_num_pages, &wq_create->u.request,
16986 		    wq->page_count);
16987 	bf_set(lpfc_mbx_wq_create_cq_id, &wq_create->u.request,
16988 		    cq->queue_id);
16989 
16990 	/* wqv is the earliest version supported, NOT the latest */
16991 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
16992 	       phba->sli4_hba.pc_sli4_params.wqv);
16993 
16994 	if ((phba->sli4_hba.pc_sli4_params.wqsize & LPFC_WQ_SZ128_SUPPORT) ||
16995 	    (wq->page_size > SLI4_PAGE_SIZE))
16996 		wq_create_version = LPFC_Q_CREATE_VERSION_1;
16997 	else
16998 		wq_create_version = LPFC_Q_CREATE_VERSION_0;
16999 
17000 	switch (wq_create_version) {
17001 	case LPFC_Q_CREATE_VERSION_1:
17002 		bf_set(lpfc_mbx_wq_create_wqe_count, &wq_create->u.request_1,
17003 		       wq->entry_count);
17004 		bf_set(lpfc_mbox_hdr_version, &shdr->request,
17005 		       LPFC_Q_CREATE_VERSION_1);
17006 
17007 		switch (wq->entry_size) {
17008 		default:
17009 		case 64:
17010 			bf_set(lpfc_mbx_wq_create_wqe_size,
17011 			       &wq_create->u.request_1,
17012 			       LPFC_WQ_WQE_SIZE_64);
17013 			break;
17014 		case 128:
17015 			bf_set(lpfc_mbx_wq_create_wqe_size,
17016 			       &wq_create->u.request_1,
17017 			       LPFC_WQ_WQE_SIZE_128);
17018 			break;
17019 		}
17020 		/* Request DPP by default */
17021 		bf_set(lpfc_mbx_wq_create_dpp_req, &wq_create->u.request_1, 1);
17022 		bf_set(lpfc_mbx_wq_create_page_size,
17023 		       &wq_create->u.request_1,
17024 		       (wq->page_size / SLI4_PAGE_SIZE));
17025 		page = wq_create->u.request_1.page;
17026 		break;
17027 	default:
17028 		page = wq_create->u.request.page;
17029 		break;
17030 	}
17031 
17032 	list_for_each_entry(dmabuf, &wq->page_list, list) {
17033 		memset(dmabuf->virt, 0, hw_page_size);
17034 		page[dmabuf->buffer_tag].addr_lo = putPaddrLow(dmabuf->phys);
17035 		page[dmabuf->buffer_tag].addr_hi = putPaddrHigh(dmabuf->phys);
17036 	}
17037 
17038 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
17039 		bf_set(lpfc_mbx_wq_create_dua, &wq_create->u.request, 1);
17040 
17041 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17042 	/* The IOCTL status is embedded in the mailbox subheader. */
17043 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17044 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17045 	if (shdr_status || shdr_add_status || rc) {
17046 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17047 				"2503 WQ_CREATE mailbox failed with "
17048 				"status x%x add_status x%x, mbx status x%x\n",
17049 				shdr_status, shdr_add_status, rc);
17050 		status = -ENXIO;
17051 		goto out;
17052 	}
17053 
17054 	if (wq_create_version == LPFC_Q_CREATE_VERSION_0)
17055 		wq->queue_id = bf_get(lpfc_mbx_wq_create_q_id,
17056 					&wq_create->u.response);
17057 	else
17058 		wq->queue_id = bf_get(lpfc_mbx_wq_create_v1_q_id,
17059 					&wq_create->u.response_1);
17060 
17061 	if (wq->queue_id == 0xFFFF) {
17062 		status = -ENXIO;
17063 		goto out;
17064 	}
17065 
17066 	wq->db_format = LPFC_DB_LIST_FORMAT;
17067 	if (wq_create_version == LPFC_Q_CREATE_VERSION_0) {
17068 		if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
17069 			wq->db_format = bf_get(lpfc_mbx_wq_create_db_format,
17070 					       &wq_create->u.response);
17071 			if ((wq->db_format != LPFC_DB_LIST_FORMAT) &&
17072 			    (wq->db_format != LPFC_DB_RING_FORMAT)) {
17073 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17074 						"3265 WQ[%d] doorbell format "
17075 						"not supported: x%x\n",
17076 						wq->queue_id, wq->db_format);
17077 				status = -EINVAL;
17078 				goto out;
17079 			}
17080 			pci_barset = bf_get(lpfc_mbx_wq_create_bar_set,
17081 					    &wq_create->u.response);
17082 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
17083 								   pci_barset);
17084 			if (!bar_memmap_p) {
17085 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17086 						"3263 WQ[%d] failed to memmap "
17087 						"pci barset:x%x\n",
17088 						wq->queue_id, pci_barset);
17089 				status = -ENOMEM;
17090 				goto out;
17091 			}
17092 			db_offset = wq_create->u.response.doorbell_offset;
17093 			if ((db_offset != LPFC_ULP0_WQ_DOORBELL) &&
17094 			    (db_offset != LPFC_ULP1_WQ_DOORBELL)) {
17095 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17096 						"3252 WQ[%d] doorbell offset "
17097 						"not supported: x%x\n",
17098 						wq->queue_id, db_offset);
17099 				status = -EINVAL;
17100 				goto out;
17101 			}
17102 			wq->db_regaddr = bar_memmap_p + db_offset;
17103 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
17104 					"3264 WQ[%d]: barset:x%x, offset:x%x, "
17105 					"format:x%x\n", wq->queue_id,
17106 					pci_barset, db_offset, wq->db_format);
17107 		} else
17108 			wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
17109 	} else {
17110 		/* Check if DPP was honored by the firmware */
17111 		wq->dpp_enable = bf_get(lpfc_mbx_wq_create_dpp_rsp,
17112 				    &wq_create->u.response_1);
17113 		if (wq->dpp_enable) {
17114 			pci_barset = bf_get(lpfc_mbx_wq_create_v1_bar_set,
17115 					    &wq_create->u.response_1);
17116 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
17117 								   pci_barset);
17118 			if (!bar_memmap_p) {
17119 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17120 						"3267 WQ[%d] failed to memmap "
17121 						"pci barset:x%x\n",
17122 						wq->queue_id, pci_barset);
17123 				status = -ENOMEM;
17124 				goto out;
17125 			}
17126 			db_offset = wq_create->u.response_1.doorbell_offset;
17127 			wq->db_regaddr = bar_memmap_p + db_offset;
17128 			wq->dpp_id = bf_get(lpfc_mbx_wq_create_dpp_id,
17129 					    &wq_create->u.response_1);
17130 			dpp_barset = bf_get(lpfc_mbx_wq_create_dpp_bar,
17131 					    &wq_create->u.response_1);
17132 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
17133 								   dpp_barset);
17134 			if (!bar_memmap_p) {
17135 				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17136 						"3268 WQ[%d] failed to memmap "
17137 						"pci barset:x%x\n",
17138 						wq->queue_id, dpp_barset);
17139 				status = -ENOMEM;
17140 				goto out;
17141 			}
17142 			dpp_offset = wq_create->u.response_1.dpp_offset;
17143 			wq->dpp_regaddr = bar_memmap_p + dpp_offset;
17144 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
17145 					"3271 WQ[%d]: barset:x%x, offset:x%x, "
17146 					"dpp_id:x%x dpp_barset:x%x "
17147 					"dpp_offset:x%x\n",
17148 					wq->queue_id, pci_barset, db_offset,
17149 					wq->dpp_id, dpp_barset, dpp_offset);
17150 
17151 #ifdef CONFIG_X86
17152 			/* Enable combined writes for DPP aperture */
17153 			bar_memmap_p = lpfc_dpp_wc_map(phba, dpp_barset);
17154 			if (!bar_memmap_p) {
17155 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
17156 					"3272 Cannot setup Combined "
17157 					"Write on WQ[%d] - disable DPP\n",
17158 					wq->queue_id);
17159 				phba->cfg_enable_dpp = 0;
17160 			} else {
17161 				wq->dpp_regaddr = bar_memmap_p + dpp_offset;
17162 			}
17163 #else
17164 			phba->cfg_enable_dpp = 0;
17165 #endif
17166 		} else
17167 			wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
17168 	}
17169 	wq->pring = kzalloc_obj(struct lpfc_sli_ring);
17170 	if (wq->pring == NULL) {
17171 		status = -ENOMEM;
17172 		goto out;
17173 	}
17174 	wq->type = LPFC_WQ;
17175 	wq->assoc_qid = cq->queue_id;
17176 	wq->subtype = subtype;
17177 	wq->host_index = 0;
17178 	wq->hba_index = 0;
17179 	wq->notify_interval = LPFC_WQ_NOTIFY_INTRVL;
17180 
17181 	/* link the wq onto the parent cq child list */
17182 	list_add_tail(&wq->list, &cq->child_list);
17183 out:
17184 	mempool_free(mbox, phba->mbox_mem_pool);
17185 	return status;
17186 }
17187 
17188 /**
17189  * lpfc_rq_create - Create a Receive Queue on the HBA
17190  * @phba: HBA structure that indicates port to create a queue on.
17191  * @hrq: The queue structure to use to create the header receive queue.
17192  * @drq: The queue structure to use to create the data receive queue.
17193  * @cq: The completion queue to bind this work queue to.
17194  * @subtype: The subtype of the work queue indicating its functionality.
17195  *
17196  * This function creates a receive buffer queue pair , as detailed in @hrq and
17197  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
17198  * to the HBA.
17199  *
17200  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
17201  * struct is used to get the entry count that is necessary to determine the
17202  * number of pages to use for this queue. The @cq is used to indicate which
17203  * completion queue to bind received buffers that are posted to these queues to.
17204  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
17205  * receive queue pair. This function is asynchronous and will wait for the
17206  * mailbox command to finish before continuing.
17207  *
17208  * On success this function will return a zero. If unable to allocate enough
17209  * memory this function will return -ENOMEM. If the queue create mailbox command
17210  * fails this function will return -ENXIO.
17211  **/
17212 int
17213 lpfc_rq_create(struct lpfc_hba *phba, struct lpfc_queue *hrq,
17214 	       struct lpfc_queue *drq, struct lpfc_queue *cq, uint32_t subtype)
17215 {
17216 	struct lpfc_mbx_rq_create *rq_create;
17217 	struct lpfc_dmabuf *dmabuf;
17218 	LPFC_MBOXQ_t *mbox;
17219 	int rc, length, status = 0;
17220 	uint32_t shdr_status, shdr_add_status;
17221 	union lpfc_sli4_cfg_shdr *shdr;
17222 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
17223 	void __iomem *bar_memmap_p;
17224 	uint32_t db_offset;
17225 	uint16_t pci_barset;
17226 
17227 	/* sanity check on queue memory */
17228 	if (!hrq || !drq || !cq)
17229 		return -ENODEV;
17230 	if (!phba->sli4_hba.pc_sli4_params.supported)
17231 		hw_page_size = SLI4_PAGE_SIZE;
17232 
17233 	if (hrq->entry_count != drq->entry_count)
17234 		return -EINVAL;
17235 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17236 	if (!mbox)
17237 		return -ENOMEM;
17238 	length = (sizeof(struct lpfc_mbx_rq_create) -
17239 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17240 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17241 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
17242 			 length, LPFC_SLI4_MBX_EMBED);
17243 	rq_create = &mbox->u.mqe.un.rq_create;
17244 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
17245 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
17246 	       phba->sli4_hba.pc_sli4_params.rqv);
17247 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
17248 		bf_set(lpfc_rq_context_rqe_count_1,
17249 		       &rq_create->u.request.context,
17250 		       hrq->entry_count);
17251 		rq_create->u.request.context.buffer_size = LPFC_HDR_BUF_SIZE;
17252 		bf_set(lpfc_rq_context_rqe_size,
17253 		       &rq_create->u.request.context,
17254 		       LPFC_RQE_SIZE_8);
17255 		bf_set(lpfc_rq_context_page_size,
17256 		       &rq_create->u.request.context,
17257 		       LPFC_RQ_PAGE_SIZE_4096);
17258 	} else {
17259 		switch (hrq->entry_count) {
17260 		default:
17261 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17262 					"2535 Unsupported RQ count. (%d)\n",
17263 					hrq->entry_count);
17264 			if (hrq->entry_count < 512) {
17265 				status = -EINVAL;
17266 				goto out;
17267 			}
17268 			fallthrough;	/* otherwise default to smallest count */
17269 		case 512:
17270 			bf_set(lpfc_rq_context_rqe_count,
17271 			       &rq_create->u.request.context,
17272 			       LPFC_RQ_RING_SIZE_512);
17273 			break;
17274 		case 1024:
17275 			bf_set(lpfc_rq_context_rqe_count,
17276 			       &rq_create->u.request.context,
17277 			       LPFC_RQ_RING_SIZE_1024);
17278 			break;
17279 		case 2048:
17280 			bf_set(lpfc_rq_context_rqe_count,
17281 			       &rq_create->u.request.context,
17282 			       LPFC_RQ_RING_SIZE_2048);
17283 			break;
17284 		case 4096:
17285 			bf_set(lpfc_rq_context_rqe_count,
17286 			       &rq_create->u.request.context,
17287 			       LPFC_RQ_RING_SIZE_4096);
17288 			break;
17289 		}
17290 		bf_set(lpfc_rq_context_buf_size, &rq_create->u.request.context,
17291 		       LPFC_HDR_BUF_SIZE);
17292 	}
17293 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
17294 	       cq->queue_id);
17295 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
17296 	       hrq->page_count);
17297 	list_for_each_entry(dmabuf, &hrq->page_list, list) {
17298 		memset(dmabuf->virt, 0, hw_page_size);
17299 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
17300 					putPaddrLow(dmabuf->phys);
17301 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
17302 					putPaddrHigh(dmabuf->phys);
17303 	}
17304 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
17305 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
17306 
17307 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17308 	/* The IOCTL status is embedded in the mailbox subheader. */
17309 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17310 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17311 	if (shdr_status || shdr_add_status || rc) {
17312 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17313 				"2504 RQ_CREATE mailbox failed with "
17314 				"status x%x add_status x%x, mbx status x%x\n",
17315 				shdr_status, shdr_add_status, rc);
17316 		status = -ENXIO;
17317 		goto out;
17318 	}
17319 	hrq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
17320 	if (hrq->queue_id == 0xFFFF) {
17321 		status = -ENXIO;
17322 		goto out;
17323 	}
17324 
17325 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
17326 		hrq->db_format = bf_get(lpfc_mbx_rq_create_db_format,
17327 					&rq_create->u.response);
17328 		if ((hrq->db_format != LPFC_DB_LIST_FORMAT) &&
17329 		    (hrq->db_format != LPFC_DB_RING_FORMAT)) {
17330 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17331 					"3262 RQ [%d] doorbell format not "
17332 					"supported: x%x\n", hrq->queue_id,
17333 					hrq->db_format);
17334 			status = -EINVAL;
17335 			goto out;
17336 		}
17337 
17338 		pci_barset = bf_get(lpfc_mbx_rq_create_bar_set,
17339 				    &rq_create->u.response);
17340 		bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba, pci_barset);
17341 		if (!bar_memmap_p) {
17342 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17343 					"3269 RQ[%d] failed to memmap pci "
17344 					"barset:x%x\n", hrq->queue_id,
17345 					pci_barset);
17346 			status = -ENOMEM;
17347 			goto out;
17348 		}
17349 
17350 		db_offset = rq_create->u.response.doorbell_offset;
17351 		if ((db_offset != LPFC_ULP0_RQ_DOORBELL) &&
17352 		    (db_offset != LPFC_ULP1_RQ_DOORBELL)) {
17353 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17354 					"3270 RQ[%d] doorbell offset not "
17355 					"supported: x%x\n", hrq->queue_id,
17356 					db_offset);
17357 			status = -EINVAL;
17358 			goto out;
17359 		}
17360 		hrq->db_regaddr = bar_memmap_p + db_offset;
17361 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
17362 				"3266 RQ[qid:%d]: barset:x%x, offset:x%x, "
17363 				"format:x%x\n", hrq->queue_id, pci_barset,
17364 				db_offset, hrq->db_format);
17365 	} else {
17366 		hrq->db_format = LPFC_DB_RING_FORMAT;
17367 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
17368 	}
17369 	hrq->type = LPFC_HRQ;
17370 	hrq->assoc_qid = cq->queue_id;
17371 	hrq->subtype = subtype;
17372 	hrq->host_index = 0;
17373 	hrq->hba_index = 0;
17374 	hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17375 
17376 	/* now create the data queue */
17377 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17378 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
17379 			 length, LPFC_SLI4_MBX_EMBED);
17380 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
17381 	       phba->sli4_hba.pc_sli4_params.rqv);
17382 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
17383 		bf_set(lpfc_rq_context_rqe_count_1,
17384 		       &rq_create->u.request.context, hrq->entry_count);
17385 		if (subtype == LPFC_NVMET)
17386 			rq_create->u.request.context.buffer_size =
17387 				LPFC_NVMET_DATA_BUF_SIZE;
17388 		else
17389 			rq_create->u.request.context.buffer_size =
17390 				LPFC_DATA_BUF_SIZE;
17391 		bf_set(lpfc_rq_context_rqe_size, &rq_create->u.request.context,
17392 		       LPFC_RQE_SIZE_8);
17393 		bf_set(lpfc_rq_context_page_size, &rq_create->u.request.context,
17394 		       (PAGE_SIZE/SLI4_PAGE_SIZE));
17395 	} else {
17396 		switch (drq->entry_count) {
17397 		default:
17398 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17399 					"2536 Unsupported RQ count. (%d)\n",
17400 					drq->entry_count);
17401 			if (drq->entry_count < 512) {
17402 				status = -EINVAL;
17403 				goto out;
17404 			}
17405 			fallthrough;	/* otherwise default to smallest count */
17406 		case 512:
17407 			bf_set(lpfc_rq_context_rqe_count,
17408 			       &rq_create->u.request.context,
17409 			       LPFC_RQ_RING_SIZE_512);
17410 			break;
17411 		case 1024:
17412 			bf_set(lpfc_rq_context_rqe_count,
17413 			       &rq_create->u.request.context,
17414 			       LPFC_RQ_RING_SIZE_1024);
17415 			break;
17416 		case 2048:
17417 			bf_set(lpfc_rq_context_rqe_count,
17418 			       &rq_create->u.request.context,
17419 			       LPFC_RQ_RING_SIZE_2048);
17420 			break;
17421 		case 4096:
17422 			bf_set(lpfc_rq_context_rqe_count,
17423 			       &rq_create->u.request.context,
17424 			       LPFC_RQ_RING_SIZE_4096);
17425 			break;
17426 		}
17427 		if (subtype == LPFC_NVMET)
17428 			bf_set(lpfc_rq_context_buf_size,
17429 			       &rq_create->u.request.context,
17430 			       LPFC_NVMET_DATA_BUF_SIZE);
17431 		else
17432 			bf_set(lpfc_rq_context_buf_size,
17433 			       &rq_create->u.request.context,
17434 			       LPFC_DATA_BUF_SIZE);
17435 	}
17436 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
17437 	       cq->queue_id);
17438 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
17439 	       drq->page_count);
17440 	list_for_each_entry(dmabuf, &drq->page_list, list) {
17441 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
17442 					putPaddrLow(dmabuf->phys);
17443 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
17444 					putPaddrHigh(dmabuf->phys);
17445 	}
17446 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
17447 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
17448 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17449 	/* The IOCTL status is embedded in the mailbox subheader. */
17450 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
17451 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17452 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17453 	if (shdr_status || shdr_add_status || rc) {
17454 		status = -ENXIO;
17455 		goto out;
17456 	}
17457 	drq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
17458 	if (drq->queue_id == 0xFFFF) {
17459 		status = -ENXIO;
17460 		goto out;
17461 	}
17462 	drq->type = LPFC_DRQ;
17463 	drq->assoc_qid = cq->queue_id;
17464 	drq->subtype = subtype;
17465 	drq->host_index = 0;
17466 	drq->hba_index = 0;
17467 	drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17468 
17469 	/* link the header and data RQs onto the parent cq child list */
17470 	list_add_tail(&hrq->list, &cq->child_list);
17471 	list_add_tail(&drq->list, &cq->child_list);
17472 
17473 out:
17474 	mempool_free(mbox, phba->mbox_mem_pool);
17475 	return status;
17476 }
17477 
17478 /**
17479  * lpfc_mrq_create - Create MRQ Receive Queues on the HBA
17480  * @phba: HBA structure that indicates port to create a queue on.
17481  * @hrqp: The queue structure array to use to create the header receive queues.
17482  * @drqp: The queue structure array to use to create the data receive queues.
17483  * @cqp: The completion queue array to bind these receive queues to.
17484  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
17485  *
17486  * This function creates a receive buffer queue pair , as detailed in @hrq and
17487  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
17488  * to the HBA.
17489  *
17490  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
17491  * struct is used to get the entry count that is necessary to determine the
17492  * number of pages to use for this queue. The @cq is used to indicate which
17493  * completion queue to bind received buffers that are posted to these queues to.
17494  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
17495  * receive queue pair. This function is asynchronous and will wait for the
17496  * mailbox command to finish before continuing.
17497  *
17498  * On success this function will return a zero. If unable to allocate enough
17499  * memory this function will return -ENOMEM. If the queue create mailbox command
17500  * fails this function will return -ENXIO.
17501  **/
17502 int
17503 lpfc_mrq_create(struct lpfc_hba *phba, struct lpfc_queue **hrqp,
17504 		struct lpfc_queue **drqp, struct lpfc_queue **cqp,
17505 		uint32_t subtype)
17506 {
17507 	struct lpfc_queue *hrq, *drq, *cq;
17508 	struct lpfc_mbx_rq_create_v2 *rq_create;
17509 	struct lpfc_dmabuf *dmabuf;
17510 	LPFC_MBOXQ_t *mbox;
17511 	int rc, length, alloclen, status = 0;
17512 	int cnt, idx, numrq, page_idx = 0;
17513 	uint32_t shdr_status, shdr_add_status;
17514 	union lpfc_sli4_cfg_shdr *shdr;
17515 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
17516 
17517 	numrq = phba->cfg_nvmet_mrq;
17518 	/* sanity check on array memory */
17519 	if (!hrqp || !drqp || !cqp || !numrq)
17520 		return -ENODEV;
17521 	if (!phba->sli4_hba.pc_sli4_params.supported)
17522 		hw_page_size = SLI4_PAGE_SIZE;
17523 
17524 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17525 	if (!mbox)
17526 		return -ENOMEM;
17527 
17528 	length = sizeof(struct lpfc_mbx_rq_create_v2);
17529 	length += ((2 * numrq * hrqp[0]->page_count) *
17530 		   sizeof(struct dma_address));
17531 
17532 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17533 				    LPFC_MBOX_OPCODE_FCOE_RQ_CREATE, length,
17534 				    LPFC_SLI4_MBX_NEMBED);
17535 	if (alloclen < length) {
17536 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17537 				"3099 Allocated DMA memory size (%d) is "
17538 				"less than the requested DMA memory size "
17539 				"(%d)\n", alloclen, length);
17540 		status = -ENOMEM;
17541 		goto out;
17542 	}
17543 
17544 
17545 
17546 	rq_create = mbox->sge_array->addr[0];
17547 	shdr = (union lpfc_sli4_cfg_shdr *)&rq_create->cfg_shdr;
17548 
17549 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_Q_CREATE_VERSION_2);
17550 	cnt = 0;
17551 
17552 	for (idx = 0; idx < numrq; idx++) {
17553 		hrq = hrqp[idx];
17554 		drq = drqp[idx];
17555 		cq  = cqp[idx];
17556 
17557 		/* sanity check on queue memory */
17558 		if (!hrq || !drq || !cq) {
17559 			status = -ENODEV;
17560 			goto out;
17561 		}
17562 
17563 		if (hrq->entry_count != drq->entry_count) {
17564 			status = -EINVAL;
17565 			goto out;
17566 		}
17567 
17568 		if (idx == 0) {
17569 			bf_set(lpfc_mbx_rq_create_num_pages,
17570 			       &rq_create->u.request,
17571 			       hrq->page_count);
17572 			bf_set(lpfc_mbx_rq_create_rq_cnt,
17573 			       &rq_create->u.request, (numrq * 2));
17574 			bf_set(lpfc_mbx_rq_create_dnb, &rq_create->u.request,
17575 			       1);
17576 			bf_set(lpfc_rq_context_base_cq,
17577 			       &rq_create->u.request.context,
17578 			       cq->queue_id);
17579 			bf_set(lpfc_rq_context_data_size,
17580 			       &rq_create->u.request.context,
17581 			       LPFC_NVMET_DATA_BUF_SIZE);
17582 			bf_set(lpfc_rq_context_hdr_size,
17583 			       &rq_create->u.request.context,
17584 			       LPFC_HDR_BUF_SIZE);
17585 			bf_set(lpfc_rq_context_rqe_count_1,
17586 			       &rq_create->u.request.context,
17587 			       hrq->entry_count);
17588 			bf_set(lpfc_rq_context_rqe_size,
17589 			       &rq_create->u.request.context,
17590 			       LPFC_RQE_SIZE_8);
17591 			bf_set(lpfc_rq_context_page_size,
17592 			       &rq_create->u.request.context,
17593 			       (PAGE_SIZE/SLI4_PAGE_SIZE));
17594 		}
17595 		rc = 0;
17596 		list_for_each_entry(dmabuf, &hrq->page_list, list) {
17597 			memset(dmabuf->virt, 0, hw_page_size);
17598 			cnt = page_idx + dmabuf->buffer_tag;
17599 			rq_create->u.request.page[cnt].addr_lo =
17600 					putPaddrLow(dmabuf->phys);
17601 			rq_create->u.request.page[cnt].addr_hi =
17602 					putPaddrHigh(dmabuf->phys);
17603 			rc++;
17604 		}
17605 		page_idx += rc;
17606 
17607 		rc = 0;
17608 		list_for_each_entry(dmabuf, &drq->page_list, list) {
17609 			memset(dmabuf->virt, 0, hw_page_size);
17610 			cnt = page_idx + dmabuf->buffer_tag;
17611 			rq_create->u.request.page[cnt].addr_lo =
17612 					putPaddrLow(dmabuf->phys);
17613 			rq_create->u.request.page[cnt].addr_hi =
17614 					putPaddrHigh(dmabuf->phys);
17615 			rc++;
17616 		}
17617 		page_idx += rc;
17618 
17619 		hrq->db_format = LPFC_DB_RING_FORMAT;
17620 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
17621 		hrq->type = LPFC_HRQ;
17622 		hrq->assoc_qid = cq->queue_id;
17623 		hrq->subtype = subtype;
17624 		hrq->host_index = 0;
17625 		hrq->hba_index = 0;
17626 		hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17627 
17628 		drq->db_format = LPFC_DB_RING_FORMAT;
17629 		drq->db_regaddr = phba->sli4_hba.RQDBregaddr;
17630 		drq->type = LPFC_DRQ;
17631 		drq->assoc_qid = cq->queue_id;
17632 		drq->subtype = subtype;
17633 		drq->host_index = 0;
17634 		drq->hba_index = 0;
17635 		drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17636 
17637 		list_add_tail(&hrq->list, &cq->child_list);
17638 		list_add_tail(&drq->list, &cq->child_list);
17639 	}
17640 
17641 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17642 	/* The IOCTL status is embedded in the mailbox subheader. */
17643 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17644 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17645 	if (shdr_status || shdr_add_status || rc) {
17646 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17647 				"3120 RQ_CREATE mailbox failed with "
17648 				"status x%x add_status x%x, mbx status x%x\n",
17649 				shdr_status, shdr_add_status, rc);
17650 		status = -ENXIO;
17651 		goto out;
17652 	}
17653 	rc = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
17654 	if (rc == 0xFFFF) {
17655 		status = -ENXIO;
17656 		goto out;
17657 	}
17658 
17659 	/* Initialize all RQs with associated queue id */
17660 	for (idx = 0; idx < numrq; idx++) {
17661 		hrq = hrqp[idx];
17662 		hrq->queue_id = rc + (2 * idx);
17663 		drq = drqp[idx];
17664 		drq->queue_id = rc + (2 * idx) + 1;
17665 	}
17666 
17667 out:
17668 	lpfc_sli4_mbox_cmd_free(phba, mbox);
17669 	return status;
17670 }
17671 
17672 /**
17673  * lpfc_eq_destroy - Destroy an event Queue on the HBA
17674  * @phba: HBA structure that indicates port to destroy a queue on.
17675  * @eq: The queue structure associated with the queue to destroy.
17676  *
17677  * This function destroys a queue, as detailed in @eq by sending an mailbox
17678  * command, specific to the type of queue, to the HBA.
17679  *
17680  * The @eq struct is used to get the queue ID of the queue to destroy.
17681  *
17682  * On success this function will return a zero. If the queue destroy mailbox
17683  * command fails this function will return -ENXIO.
17684  **/
17685 int
17686 lpfc_eq_destroy(struct lpfc_hba *phba, struct lpfc_queue *eq)
17687 {
17688 	LPFC_MBOXQ_t *mbox;
17689 	int rc, length, status = 0;
17690 	uint32_t shdr_status, shdr_add_status;
17691 	union lpfc_sli4_cfg_shdr *shdr;
17692 
17693 	/* sanity check on queue memory */
17694 	if (!eq)
17695 		return -ENODEV;
17696 
17697 	if (!(phba->sli.sli_flag & LPFC_SLI_ACTIVE))
17698 		goto list_remove;
17699 
17700 	mbox = mempool_alloc(eq->phba->mbox_mem_pool, GFP_KERNEL);
17701 	if (!mbox)
17702 		return -ENOMEM;
17703 	length = (sizeof(struct lpfc_mbx_eq_destroy) -
17704 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17705 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17706 			 LPFC_MBOX_OPCODE_EQ_DESTROY,
17707 			 length, LPFC_SLI4_MBX_EMBED);
17708 	bf_set(lpfc_mbx_eq_destroy_q_id, &mbox->u.mqe.un.eq_destroy.u.request,
17709 	       eq->queue_id);
17710 	mbox->vport = eq->phba->pport;
17711 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17712 
17713 	rc = lpfc_sli_issue_mbox(eq->phba, mbox, MBX_POLL);
17714 	/* The IOCTL status is embedded in the mailbox subheader. */
17715 	shdr = (union lpfc_sli4_cfg_shdr *)
17716 		&mbox->u.mqe.un.eq_destroy.header.cfg_shdr;
17717 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17718 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17719 	if (shdr_status || shdr_add_status || rc) {
17720 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17721 				"2505 EQ_DESTROY mailbox failed with "
17722 				"status x%x add_status x%x, mbx status x%x\n",
17723 				shdr_status, shdr_add_status, rc);
17724 		status = -ENXIO;
17725 	}
17726 	mempool_free(mbox, eq->phba->mbox_mem_pool);
17727 
17728 list_remove:
17729 	/* Remove eq from any list */
17730 	list_del_init(&eq->list);
17731 
17732 	return status;
17733 }
17734 
17735 /**
17736  * lpfc_cq_destroy - Destroy a Completion Queue on the HBA
17737  * @phba: HBA structure that indicates port to destroy a queue on.
17738  * @cq: The queue structure associated with the queue to destroy.
17739  *
17740  * This function destroys a queue, as detailed in @cq by sending an mailbox
17741  * command, specific to the type of queue, to the HBA.
17742  *
17743  * The @cq struct is used to get the queue ID of the queue to destroy.
17744  *
17745  * On success this function will return a zero. If the queue destroy mailbox
17746  * command fails this function will return -ENXIO.
17747  **/
17748 int
17749 lpfc_cq_destroy(struct lpfc_hba *phba, struct lpfc_queue *cq)
17750 {
17751 	LPFC_MBOXQ_t *mbox;
17752 	int rc, length, status = 0;
17753 	uint32_t shdr_status, shdr_add_status;
17754 	union lpfc_sli4_cfg_shdr *shdr;
17755 
17756 	/* sanity check on queue memory */
17757 	if (!cq)
17758 		return -ENODEV;
17759 
17760 	if (!(phba->sli.sli_flag & LPFC_SLI_ACTIVE))
17761 		goto list_remove;
17762 
17763 	mbox = mempool_alloc(cq->phba->mbox_mem_pool, GFP_KERNEL);
17764 	if (!mbox)
17765 		return -ENOMEM;
17766 	length = (sizeof(struct lpfc_mbx_cq_destroy) -
17767 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17768 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17769 			 LPFC_MBOX_OPCODE_CQ_DESTROY,
17770 			 length, LPFC_SLI4_MBX_EMBED);
17771 	bf_set(lpfc_mbx_cq_destroy_q_id, &mbox->u.mqe.un.cq_destroy.u.request,
17772 	       cq->queue_id);
17773 	mbox->vport = cq->phba->pport;
17774 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17775 	rc = lpfc_sli_issue_mbox(cq->phba, mbox, MBX_POLL);
17776 	/* The IOCTL status is embedded in the mailbox subheader. */
17777 	shdr = (union lpfc_sli4_cfg_shdr *)
17778 		&mbox->u.mqe.un.wq_create.header.cfg_shdr;
17779 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17780 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17781 	if (shdr_status || shdr_add_status || rc) {
17782 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17783 				"2506 CQ_DESTROY mailbox failed with "
17784 				"status x%x add_status x%x, mbx status x%x\n",
17785 				shdr_status, shdr_add_status, rc);
17786 		status = -ENXIO;
17787 	}
17788 	mempool_free(mbox, cq->phba->mbox_mem_pool);
17789 
17790 list_remove:
17791 	/* Remove cq from any list */
17792 	list_del_init(&cq->list);
17793 	return status;
17794 }
17795 
17796 /**
17797  * lpfc_mq_destroy - Destroy a Mailbox Queue on the HBA
17798  * @phba: HBA structure that indicates port to destroy a queue on.
17799  * @mq: The queue structure associated with the queue to destroy.
17800  *
17801  * This function destroys a queue, as detailed in @mq by sending an mailbox
17802  * command, specific to the type of queue, to the HBA.
17803  *
17804  * The @mq struct is used to get the queue ID of the queue to destroy.
17805  *
17806  * On success this function will return a zero. If the queue destroy mailbox
17807  * command fails this function will return -ENXIO.
17808  **/
17809 int
17810 lpfc_mq_destroy(struct lpfc_hba *phba, struct lpfc_queue *mq)
17811 {
17812 	LPFC_MBOXQ_t *mbox;
17813 	int rc, length, status = 0;
17814 	uint32_t shdr_status, shdr_add_status;
17815 	union lpfc_sli4_cfg_shdr *shdr;
17816 
17817 	/* sanity check on queue memory */
17818 	if (!mq)
17819 		return -ENODEV;
17820 
17821 	if (!(phba->sli.sli_flag & LPFC_SLI_ACTIVE))
17822 		goto list_remove;
17823 
17824 	mbox = mempool_alloc(mq->phba->mbox_mem_pool, GFP_KERNEL);
17825 	if (!mbox)
17826 		return -ENOMEM;
17827 	length = (sizeof(struct lpfc_mbx_mq_destroy) -
17828 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17829 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17830 			 LPFC_MBOX_OPCODE_MQ_DESTROY,
17831 			 length, LPFC_SLI4_MBX_EMBED);
17832 	bf_set(lpfc_mbx_mq_destroy_q_id, &mbox->u.mqe.un.mq_destroy.u.request,
17833 	       mq->queue_id);
17834 	mbox->vport = mq->phba->pport;
17835 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17836 	rc = lpfc_sli_issue_mbox(mq->phba, mbox, MBX_POLL);
17837 	/* The IOCTL status is embedded in the mailbox subheader. */
17838 	shdr = (union lpfc_sli4_cfg_shdr *)
17839 		&mbox->u.mqe.un.mq_destroy.header.cfg_shdr;
17840 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17841 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17842 	if (shdr_status || shdr_add_status || rc) {
17843 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17844 				"2507 MQ_DESTROY mailbox failed with "
17845 				"status x%x add_status x%x, mbx status x%x\n",
17846 				shdr_status, shdr_add_status, rc);
17847 		status = -ENXIO;
17848 	}
17849 	mempool_free(mbox, mq->phba->mbox_mem_pool);
17850 
17851 list_remove:
17852 	/* Remove mq from any list */
17853 	list_del_init(&mq->list);
17854 	return status;
17855 }
17856 
17857 /**
17858  * lpfc_wq_destroy - Destroy a Work Queue on the HBA
17859  * @phba: HBA structure that indicates port to destroy a queue on.
17860  * @wq: The queue structure associated with the queue to destroy.
17861  *
17862  * This function destroys a queue, as detailed in @wq by sending an mailbox
17863  * command, specific to the type of queue, to the HBA.
17864  *
17865  * The @wq struct is used to get the queue ID of the queue to destroy.
17866  *
17867  * On success this function will return a zero. If the queue destroy mailbox
17868  * command fails this function will return -ENXIO.
17869  **/
17870 int
17871 lpfc_wq_destroy(struct lpfc_hba *phba, struct lpfc_queue *wq)
17872 {
17873 	LPFC_MBOXQ_t *mbox;
17874 	int rc, length, status = 0;
17875 	uint32_t shdr_status, shdr_add_status;
17876 	union lpfc_sli4_cfg_shdr *shdr;
17877 
17878 	/* sanity check on queue memory */
17879 	if (!wq)
17880 		return -ENODEV;
17881 
17882 	if (!(phba->sli.sli_flag & LPFC_SLI_ACTIVE))
17883 		goto list_remove;
17884 
17885 	mbox = mempool_alloc(wq->phba->mbox_mem_pool, GFP_KERNEL);
17886 	if (!mbox)
17887 		return -ENOMEM;
17888 	length = (sizeof(struct lpfc_mbx_wq_destroy) -
17889 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17890 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17891 			 LPFC_MBOX_OPCODE_FCOE_WQ_DESTROY,
17892 			 length, LPFC_SLI4_MBX_EMBED);
17893 	bf_set(lpfc_mbx_wq_destroy_q_id, &mbox->u.mqe.un.wq_destroy.u.request,
17894 	       wq->queue_id);
17895 	mbox->vport = wq->phba->pport;
17896 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17897 	rc = lpfc_sli_issue_mbox(wq->phba, mbox, MBX_POLL);
17898 	shdr = (union lpfc_sli4_cfg_shdr *)
17899 		&mbox->u.mqe.un.wq_destroy.header.cfg_shdr;
17900 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17901 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17902 	if (shdr_status || shdr_add_status || rc) {
17903 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17904 				"2508 WQ_DESTROY mailbox failed with "
17905 				"status x%x add_status x%x, mbx status x%x\n",
17906 				shdr_status, shdr_add_status, rc);
17907 		status = -ENXIO;
17908 	}
17909 	mempool_free(mbox, wq->phba->mbox_mem_pool);
17910 
17911 list_remove:
17912 	/* Remove wq from any list */
17913 	list_del_init(&wq->list);
17914 	kfree(wq->pring);
17915 	wq->pring = NULL;
17916 	return status;
17917 }
17918 
17919 /**
17920  * lpfc_rq_destroy - Destroy a Receive Queue on the HBA
17921  * @phba: HBA structure that indicates port to destroy a queue on.
17922  * @hrq: The queue structure associated with the queue to destroy.
17923  * @drq: The queue structure associated with the queue to destroy.
17924  *
17925  * This function destroys a queue, as detailed in @rq by sending an mailbox
17926  * command, specific to the type of queue, to the HBA.
17927  *
17928  * The @rq struct is used to get the queue ID of the queue to destroy.
17929  *
17930  * On success this function will return a zero. If the queue destroy mailbox
17931  * command fails this function will return -ENXIO.
17932  **/
17933 int
17934 lpfc_rq_destroy(struct lpfc_hba *phba, struct lpfc_queue *hrq,
17935 		struct lpfc_queue *drq)
17936 {
17937 	LPFC_MBOXQ_t *mbox;
17938 	int rc, length, status = 0;
17939 	uint32_t shdr_status, shdr_add_status;
17940 	union lpfc_sli4_cfg_shdr *shdr;
17941 
17942 	/* sanity check on queue memory */
17943 	if (!hrq || !drq)
17944 		return -ENODEV;
17945 
17946 	if (!(phba->sli.sli_flag & LPFC_SLI_ACTIVE))
17947 		goto list_remove;
17948 
17949 	mbox = mempool_alloc(hrq->phba->mbox_mem_pool, GFP_KERNEL);
17950 	if (!mbox)
17951 		return -ENOMEM;
17952 	length = (sizeof(struct lpfc_mbx_rq_destroy) -
17953 		  sizeof(struct lpfc_sli4_cfg_mhdr));
17954 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17955 			 LPFC_MBOX_OPCODE_FCOE_RQ_DESTROY,
17956 			 length, LPFC_SLI4_MBX_EMBED);
17957 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
17958 	       hrq->queue_id);
17959 	mbox->vport = hrq->phba->pport;
17960 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17961 	rc = lpfc_sli_issue_mbox(hrq->phba, mbox, MBX_POLL);
17962 	/* The IOCTL status is embedded in the mailbox subheader. */
17963 	shdr = (union lpfc_sli4_cfg_shdr *)
17964 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
17965 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17966 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17967 	if (shdr_status || shdr_add_status || rc) {
17968 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17969 				"2509 RQ_DESTROY mailbox failed with "
17970 				"status x%x add_status x%x, mbx status x%x\n",
17971 				shdr_status, shdr_add_status, rc);
17972 		mempool_free(mbox, hrq->phba->mbox_mem_pool);
17973 		return -ENXIO;
17974 	}
17975 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
17976 	       drq->queue_id);
17977 	rc = lpfc_sli_issue_mbox(drq->phba, mbox, MBX_POLL);
17978 	shdr = (union lpfc_sli4_cfg_shdr *)
17979 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
17980 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17981 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17982 	if (shdr_status || shdr_add_status || rc) {
17983 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17984 				"2510 RQ_DESTROY mailbox failed with "
17985 				"status x%x add_status x%x, mbx status x%x\n",
17986 				shdr_status, shdr_add_status, rc);
17987 		status = -ENXIO;
17988 	}
17989 	mempool_free(mbox, hrq->phba->mbox_mem_pool);
17990 
17991 list_remove:
17992 	list_del_init(&hrq->list);
17993 	list_del_init(&drq->list);
17994 	return status;
17995 }
17996 
17997 /**
17998  * lpfc_sli4_post_sgl - Post scatter gather list for an XRI to HBA
17999  * @phba: The virtual port for which this call being executed.
18000  * @pdma_phys_addr0: Physical address of the 1st SGL page.
18001  * @pdma_phys_addr1: Physical address of the 2nd SGL page.
18002  * @xritag: the xritag that ties this io to the SGL pages.
18003  *
18004  * This routine will post the sgl pages for the IO that has the xritag
18005  * that is in the iocbq structure. The xritag is assigned during iocbq
18006  * creation and persists for as long as the driver is loaded.
18007  * if the caller has fewer than 256 scatter gather segments to map then
18008  * pdma_phys_addr1 should be 0.
18009  * If the caller needs to map more than 256 scatter gather segment then
18010  * pdma_phys_addr1 should be a valid physical address.
18011  * physical address for SGLs must be 64 byte aligned.
18012  * If you are going to map 2 SGL's then the first one must have 256 entries
18013  * the second sgl can have between 1 and 256 entries.
18014  *
18015  * Return codes:
18016  * 	0 - Success
18017  * 	-ENXIO, -ENOMEM - Failure
18018  **/
18019 int
18020 lpfc_sli4_post_sgl(struct lpfc_hba *phba,
18021 		dma_addr_t pdma_phys_addr0,
18022 		dma_addr_t pdma_phys_addr1,
18023 		uint16_t xritag)
18024 {
18025 	struct lpfc_mbx_post_sgl_pages *post_sgl_pages;
18026 	LPFC_MBOXQ_t *mbox;
18027 	int rc;
18028 	uint32_t shdr_status, shdr_add_status;
18029 	uint32_t mbox_tmo;
18030 	union lpfc_sli4_cfg_shdr *shdr;
18031 
18032 	if (xritag == NO_XRI) {
18033 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18034 				"0364 Invalid param:\n");
18035 		return -EINVAL;
18036 	}
18037 
18038 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18039 	if (!mbox)
18040 		return -ENOMEM;
18041 
18042 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
18043 			LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
18044 			sizeof(struct lpfc_mbx_post_sgl_pages) -
18045 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
18046 
18047 	post_sgl_pages = (struct lpfc_mbx_post_sgl_pages *)
18048 				&mbox->u.mqe.un.post_sgl_pages;
18049 	bf_set(lpfc_post_sgl_pages_xri, post_sgl_pages, xritag);
18050 	bf_set(lpfc_post_sgl_pages_xricnt, post_sgl_pages, 1);
18051 
18052 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_lo	=
18053 				cpu_to_le32(putPaddrLow(pdma_phys_addr0));
18054 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_hi =
18055 				cpu_to_le32(putPaddrHigh(pdma_phys_addr0));
18056 
18057 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_lo	=
18058 				cpu_to_le32(putPaddrLow(pdma_phys_addr1));
18059 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_hi =
18060 				cpu_to_le32(putPaddrHigh(pdma_phys_addr1));
18061 	if (!phba->sli4_hba.intr_enable)
18062 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
18063 	else {
18064 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
18065 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
18066 	}
18067 	/* The IOCTL status is embedded in the mailbox subheader. */
18068 	shdr = (union lpfc_sli4_cfg_shdr *) &post_sgl_pages->header.cfg_shdr;
18069 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18070 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18071 	if (!phba->sli4_hba.intr_enable)
18072 		mempool_free(mbox, phba->mbox_mem_pool);
18073 	else if (rc != MBX_TIMEOUT)
18074 		mempool_free(mbox, phba->mbox_mem_pool);
18075 	if (shdr_status || shdr_add_status || rc) {
18076 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18077 				"2511 POST_SGL mailbox failed with "
18078 				"status x%x add_status x%x, mbx status x%x\n",
18079 				shdr_status, shdr_add_status, rc);
18080 	}
18081 	return 0;
18082 }
18083 
18084 /**
18085  * lpfc_sli4_alloc_xri - Get an available rpi in the device's range
18086  * @phba: pointer to lpfc hba data structure.
18087  *
18088  * This routine is invoked to post rpi header templates to the
18089  * HBA consistent with the SLI-4 interface spec.  This routine
18090  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
18091  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
18092  *
18093  * Returns
18094  *	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
18095  *	LPFC_RPI_ALLOC_ERROR if no rpis are available.
18096  **/
18097 static uint16_t
18098 lpfc_sli4_alloc_xri(struct lpfc_hba *phba)
18099 {
18100 	unsigned long xri;
18101 
18102 	/*
18103 	 * Fetch the next logical xri.  Because this index is logical,
18104 	 * the driver starts at 0 each time.
18105 	 */
18106 	spin_lock_irq(&phba->hbalock);
18107 	xri = find_first_zero_bit(phba->sli4_hba.xri_bmask,
18108 				 phba->sli4_hba.max_cfg_param.max_xri);
18109 	if (xri >= phba->sli4_hba.max_cfg_param.max_xri) {
18110 		spin_unlock_irq(&phba->hbalock);
18111 		return NO_XRI;
18112 	} else {
18113 		set_bit(xri, phba->sli4_hba.xri_bmask);
18114 		phba->sli4_hba.max_cfg_param.xri_used++;
18115 	}
18116 	spin_unlock_irq(&phba->hbalock);
18117 	return xri;
18118 }
18119 
18120 /**
18121  * __lpfc_sli4_free_xri - Release an xri for reuse.
18122  * @phba: pointer to lpfc hba data structure.
18123  * @xri: xri to release.
18124  *
18125  * This routine is invoked to release an xri to the pool of
18126  * available rpis maintained by the driver.
18127  **/
18128 static void
18129 __lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
18130 {
18131 	if (test_and_clear_bit(xri, phba->sli4_hba.xri_bmask)) {
18132 		phba->sli4_hba.max_cfg_param.xri_used--;
18133 	}
18134 }
18135 
18136 /**
18137  * lpfc_sli4_free_xri - Release an xri for reuse.
18138  * @phba: pointer to lpfc hba data structure.
18139  * @xri: xri to release.
18140  *
18141  * This routine is invoked to release an xri to the pool of
18142  * available rpis maintained by the driver.
18143  **/
18144 void
18145 lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
18146 {
18147 	spin_lock_irq(&phba->hbalock);
18148 	__lpfc_sli4_free_xri(phba, xri);
18149 	spin_unlock_irq(&phba->hbalock);
18150 }
18151 
18152 /**
18153  * lpfc_sli4_next_xritag - Get an xritag for the io
18154  * @phba: Pointer to HBA context object.
18155  *
18156  * This function gets an xritag for the iocb. If there is no unused xritag
18157  * it will return 0xffff.
18158  * The function returns the allocated xritag if successful, else returns zero.
18159  * Zero is not a valid xritag.
18160  * The caller is not required to hold any lock.
18161  **/
18162 uint16_t
18163 lpfc_sli4_next_xritag(struct lpfc_hba *phba)
18164 {
18165 	uint16_t xri_index;
18166 
18167 	xri_index = lpfc_sli4_alloc_xri(phba);
18168 	if (xri_index == NO_XRI)
18169 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
18170 				"2004 Failed to allocate XRI.last XRITAG is %d"
18171 				" Max XRI is %d, Used XRI is %d\n",
18172 				xri_index,
18173 				phba->sli4_hba.max_cfg_param.max_xri,
18174 				phba->sli4_hba.max_cfg_param.xri_used);
18175 	return xri_index;
18176 }
18177 
18178 /**
18179  * lpfc_sli4_post_sgl_list - post a block of ELS sgls to the port.
18180  * @phba: pointer to lpfc hba data structure.
18181  * @post_sgl_list: pointer to els sgl entry list.
18182  * @post_cnt: number of els sgl entries on the list.
18183  *
18184  * This routine is invoked to post a block of driver's sgl pages to the
18185  * HBA using non-embedded mailbox command. No Lock is held. This routine
18186  * is only called when the driver is loading and after all IO has been
18187  * stopped.
18188  **/
18189 static int
18190 lpfc_sli4_post_sgl_list(struct lpfc_hba *phba,
18191 			    struct list_head *post_sgl_list,
18192 			    int post_cnt)
18193 {
18194 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
18195 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
18196 	struct sgl_page_pairs *sgl_pg_pairs;
18197 	void *viraddr;
18198 	LPFC_MBOXQ_t *mbox;
18199 	uint32_t reqlen, alloclen, pg_pairs;
18200 	uint32_t mbox_tmo;
18201 	uint16_t xritag_start = 0;
18202 	int rc = 0;
18203 	uint32_t shdr_status, shdr_add_status;
18204 	union lpfc_sli4_cfg_shdr *shdr;
18205 
18206 	reqlen = post_cnt * sizeof(struct sgl_page_pairs) +
18207 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
18208 	if (reqlen > SLI4_PAGE_SIZE) {
18209 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18210 				"2559 Block sgl registration required DMA "
18211 				"size (%d) great than a page\n", reqlen);
18212 		return -ENOMEM;
18213 	}
18214 
18215 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18216 	if (!mbox)
18217 		return -ENOMEM;
18218 
18219 	/* Allocate DMA memory and set up the non-embedded mailbox command */
18220 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
18221 			 LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES, reqlen,
18222 			 LPFC_SLI4_MBX_NEMBED);
18223 
18224 	if (alloclen < reqlen) {
18225 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18226 				"0285 Allocated DMA memory size (%d) is "
18227 				"less than the requested DMA memory "
18228 				"size (%d)\n", alloclen, reqlen);
18229 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18230 		return -ENOMEM;
18231 	}
18232 	/* Set up the SGL pages in the non-embedded DMA pages */
18233 	viraddr = mbox->sge_array->addr[0];
18234 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
18235 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
18236 
18237 	pg_pairs = 0;
18238 	list_for_each_entry_safe(sglq_entry, sglq_next, post_sgl_list, list) {
18239 		/* Set up the sge entry */
18240 		sgl_pg_pairs->sgl_pg0_addr_lo =
18241 				cpu_to_le32(putPaddrLow(sglq_entry->phys));
18242 		sgl_pg_pairs->sgl_pg0_addr_hi =
18243 				cpu_to_le32(putPaddrHigh(sglq_entry->phys));
18244 		sgl_pg_pairs->sgl_pg1_addr_lo =
18245 				cpu_to_le32(putPaddrLow(0));
18246 		sgl_pg_pairs->sgl_pg1_addr_hi =
18247 				cpu_to_le32(putPaddrHigh(0));
18248 
18249 		/* Keep the first xritag on the list */
18250 		if (pg_pairs == 0)
18251 			xritag_start = sglq_entry->sli4_xritag;
18252 		sgl_pg_pairs++;
18253 		pg_pairs++;
18254 	}
18255 
18256 	/* Complete initialization and perform endian conversion. */
18257 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
18258 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, post_cnt);
18259 	sgl->word0 = cpu_to_le32(sgl->word0);
18260 
18261 	if (!phba->sli4_hba.intr_enable)
18262 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
18263 	else {
18264 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
18265 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
18266 	}
18267 	shdr = (union lpfc_sli4_cfg_shdr *) &sgl->cfg_shdr;
18268 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18269 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18270 	if (!phba->sli4_hba.intr_enable)
18271 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18272 	else if (rc != MBX_TIMEOUT)
18273 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18274 	if (shdr_status || shdr_add_status || rc) {
18275 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18276 				"2513 POST_SGL_BLOCK mailbox command failed "
18277 				"status x%x add_status x%x mbx status x%x\n",
18278 				shdr_status, shdr_add_status, rc);
18279 		rc = -ENXIO;
18280 	}
18281 	return rc;
18282 }
18283 
18284 /**
18285  * lpfc_sli4_post_io_sgl_block - post a block of nvme sgl list to firmware
18286  * @phba: pointer to lpfc hba data structure.
18287  * @nblist: pointer to nvme buffer list.
18288  * @count: number of scsi buffers on the list.
18289  *
18290  * This routine is invoked to post a block of @count scsi sgl pages from a
18291  * SCSI buffer list @nblist to the HBA using non-embedded mailbox command.
18292  * No Lock is held.
18293  *
18294  **/
18295 static int
18296 lpfc_sli4_post_io_sgl_block(struct lpfc_hba *phba, struct list_head *nblist,
18297 			    int count)
18298 {
18299 	struct lpfc_io_buf *lpfc_ncmd;
18300 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
18301 	struct sgl_page_pairs *sgl_pg_pairs;
18302 	void *viraddr;
18303 	LPFC_MBOXQ_t *mbox;
18304 	uint32_t reqlen, alloclen, pg_pairs;
18305 	uint32_t mbox_tmo;
18306 	uint16_t xritag_start = 0;
18307 	int rc = 0;
18308 	uint32_t shdr_status, shdr_add_status;
18309 	dma_addr_t pdma_phys_bpl1;
18310 	union lpfc_sli4_cfg_shdr *shdr;
18311 
18312 	/* Calculate the requested length of the dma memory */
18313 	reqlen = count * sizeof(struct sgl_page_pairs) +
18314 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
18315 	if (reqlen > SLI4_PAGE_SIZE) {
18316 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
18317 				"6118 Block sgl registration required DMA "
18318 				"size (%d) great than a page\n", reqlen);
18319 		return -ENOMEM;
18320 	}
18321 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18322 	if (!mbox) {
18323 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18324 				"6119 Failed to allocate mbox cmd memory\n");
18325 		return -ENOMEM;
18326 	}
18327 
18328 	/* Allocate DMA memory and set up the non-embedded mailbox command */
18329 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
18330 				    LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
18331 				    reqlen, LPFC_SLI4_MBX_NEMBED);
18332 
18333 	if (alloclen < reqlen) {
18334 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18335 				"6120 Allocated DMA memory size (%d) is "
18336 				"less than the requested DMA memory "
18337 				"size (%d)\n", alloclen, reqlen);
18338 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18339 		return -ENOMEM;
18340 	}
18341 
18342 	/* Get the first SGE entry from the non-embedded DMA memory */
18343 	viraddr = mbox->sge_array->addr[0];
18344 
18345 	/* Set up the SGL pages in the non-embedded DMA pages */
18346 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
18347 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
18348 
18349 	pg_pairs = 0;
18350 	list_for_each_entry(lpfc_ncmd, nblist, list) {
18351 		/* Set up the sge entry */
18352 		sgl_pg_pairs->sgl_pg0_addr_lo =
18353 			cpu_to_le32(putPaddrLow(lpfc_ncmd->dma_phys_sgl));
18354 		sgl_pg_pairs->sgl_pg0_addr_hi =
18355 			cpu_to_le32(putPaddrHigh(lpfc_ncmd->dma_phys_sgl));
18356 		if (phba->cfg_sg_dma_buf_size > SGL_PAGE_SIZE)
18357 			pdma_phys_bpl1 = lpfc_ncmd->dma_phys_sgl +
18358 						SGL_PAGE_SIZE;
18359 		else
18360 			pdma_phys_bpl1 = 0;
18361 		sgl_pg_pairs->sgl_pg1_addr_lo =
18362 			cpu_to_le32(putPaddrLow(pdma_phys_bpl1));
18363 		sgl_pg_pairs->sgl_pg1_addr_hi =
18364 			cpu_to_le32(putPaddrHigh(pdma_phys_bpl1));
18365 		/* Keep the first xritag on the list */
18366 		if (pg_pairs == 0)
18367 			xritag_start = lpfc_ncmd->cur_iocbq.sli4_xritag;
18368 		sgl_pg_pairs++;
18369 		pg_pairs++;
18370 	}
18371 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
18372 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, pg_pairs);
18373 	/* Perform endian conversion if necessary */
18374 	sgl->word0 = cpu_to_le32(sgl->word0);
18375 
18376 	if (!phba->sli4_hba.intr_enable) {
18377 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
18378 	} else {
18379 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
18380 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
18381 	}
18382 	shdr = (union lpfc_sli4_cfg_shdr *)&sgl->cfg_shdr;
18383 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18384 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18385 	if (!phba->sli4_hba.intr_enable)
18386 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18387 	else if (rc != MBX_TIMEOUT)
18388 		lpfc_sli4_mbox_cmd_free(phba, mbox);
18389 	if (shdr_status || shdr_add_status || rc) {
18390 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18391 				"6125 POST_SGL_BLOCK mailbox command failed "
18392 				"status x%x add_status x%x mbx status x%x\n",
18393 				shdr_status, shdr_add_status, rc);
18394 		rc = -ENXIO;
18395 	}
18396 	return rc;
18397 }
18398 
18399 /**
18400  * lpfc_sli4_post_io_sgl_list - Post blocks of nvme buffer sgls from a list
18401  * @phba: pointer to lpfc hba data structure.
18402  * @post_nblist: pointer to the nvme buffer list.
18403  * @sb_count: number of nvme buffers.
18404  *
18405  * This routine walks a list of nvme buffers that was passed in. It attempts
18406  * to construct blocks of nvme buffer sgls which contains contiguous xris and
18407  * uses the non-embedded SGL block post mailbox commands to post to the port.
18408  * For single NVME buffer sgl with non-contiguous xri, if any, it shall use
18409  * embedded SGL post mailbox command for posting. The @post_nblist passed in
18410  * must be local list, thus no lock is needed when manipulate the list.
18411  *
18412  * Returns: 0 = failure, non-zero number of successfully posted buffers.
18413  **/
18414 int
18415 lpfc_sli4_post_io_sgl_list(struct lpfc_hba *phba,
18416 			   struct list_head *post_nblist, int sb_count)
18417 {
18418 	struct lpfc_io_buf *lpfc_ncmd, *lpfc_ncmd_next;
18419 	int status, sgl_size;
18420 	int post_cnt = 0, block_cnt = 0, num_posting = 0, num_posted = 0;
18421 	dma_addr_t pdma_phys_sgl1;
18422 	int last_xritag = NO_XRI;
18423 	int cur_xritag;
18424 	LIST_HEAD(prep_nblist);
18425 	LIST_HEAD(blck_nblist);
18426 	LIST_HEAD(nvme_nblist);
18427 
18428 	/* sanity check */
18429 	if (sb_count <= 0)
18430 		return -EINVAL;
18431 
18432 	sgl_size = phba->cfg_sg_dma_buf_size;
18433 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next, post_nblist, list) {
18434 		list_del_init(&lpfc_ncmd->list);
18435 		block_cnt++;
18436 		if ((last_xritag != NO_XRI) &&
18437 		    (lpfc_ncmd->cur_iocbq.sli4_xritag != last_xritag + 1)) {
18438 			/* a hole in xri block, form a sgl posting block */
18439 			list_splice_init(&prep_nblist, &blck_nblist);
18440 			post_cnt = block_cnt - 1;
18441 			/* prepare list for next posting block */
18442 			list_add_tail(&lpfc_ncmd->list, &prep_nblist);
18443 			block_cnt = 1;
18444 		} else {
18445 			/* prepare list for next posting block */
18446 			list_add_tail(&lpfc_ncmd->list, &prep_nblist);
18447 			/* enough sgls for non-embed sgl mbox command */
18448 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
18449 				list_splice_init(&prep_nblist, &blck_nblist);
18450 				post_cnt = block_cnt;
18451 				block_cnt = 0;
18452 			}
18453 		}
18454 		num_posting++;
18455 		last_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
18456 
18457 		/* end of repost sgl list condition for NVME buffers */
18458 		if (num_posting == sb_count) {
18459 			if (post_cnt == 0) {
18460 				/* last sgl posting block */
18461 				list_splice_init(&prep_nblist, &blck_nblist);
18462 				post_cnt = block_cnt;
18463 			} else if (block_cnt == 1) {
18464 				/* last single sgl with non-contiguous xri */
18465 				if (sgl_size > SGL_PAGE_SIZE)
18466 					pdma_phys_sgl1 =
18467 						lpfc_ncmd->dma_phys_sgl +
18468 						SGL_PAGE_SIZE;
18469 				else
18470 					pdma_phys_sgl1 = 0;
18471 				cur_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
18472 				status = lpfc_sli4_post_sgl(
18473 						phba, lpfc_ncmd->dma_phys_sgl,
18474 						pdma_phys_sgl1, cur_xritag);
18475 				if (status) {
18476 					/* Post error.  Buffer unavailable. */
18477 					lpfc_ncmd->flags |=
18478 						LPFC_SBUF_NOT_POSTED;
18479 				} else {
18480 					/* Post success. Bffer available. */
18481 					lpfc_ncmd->flags &=
18482 						~LPFC_SBUF_NOT_POSTED;
18483 					lpfc_ncmd->status = IOSTAT_SUCCESS;
18484 					num_posted++;
18485 				}
18486 				/* success, put on NVME buffer sgl list */
18487 				list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
18488 			}
18489 		}
18490 
18491 		/* continue until a nembed page worth of sgls */
18492 		if (post_cnt == 0)
18493 			continue;
18494 
18495 		/* post block of NVME buffer list sgls */
18496 		status = lpfc_sli4_post_io_sgl_block(phba, &blck_nblist,
18497 						     post_cnt);
18498 
18499 		/* don't reset xirtag due to hole in xri block */
18500 		if (block_cnt == 0)
18501 			last_xritag = NO_XRI;
18502 
18503 		/* reset NVME buffer post count for next round of posting */
18504 		post_cnt = 0;
18505 
18506 		/* put posted NVME buffer-sgl posted on NVME buffer sgl list */
18507 		while (!list_empty(&blck_nblist)) {
18508 			list_remove_head(&blck_nblist, lpfc_ncmd,
18509 					 struct lpfc_io_buf, list);
18510 			if (status) {
18511 				/* Post error.  Mark buffer unavailable. */
18512 				lpfc_ncmd->flags |= LPFC_SBUF_NOT_POSTED;
18513 			} else {
18514 				/* Post success, Mark buffer available. */
18515 				lpfc_ncmd->flags &= ~LPFC_SBUF_NOT_POSTED;
18516 				lpfc_ncmd->status = IOSTAT_SUCCESS;
18517 				num_posted++;
18518 			}
18519 			list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
18520 		}
18521 	}
18522 	/* Push NVME buffers with sgl posted to the available list */
18523 	lpfc_io_buf_replenish(phba, &nvme_nblist);
18524 
18525 	return num_posted;
18526 }
18527 
18528 /**
18529  * lpfc_fc_frame_check - Check that this frame is a valid frame to handle
18530  * @phba: pointer to lpfc_hba struct that the frame was received on
18531  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
18532  *
18533  * This function checks the fields in the @fc_hdr to see if the FC frame is a
18534  * valid type of frame that the LPFC driver will handle. This function will
18535  * return a zero if the frame is a valid frame or a non zero value when the
18536  * frame does not pass the check.
18537  **/
18538 static int
18539 lpfc_fc_frame_check(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr)
18540 {
18541 	/*  make rctl_names static to save stack space */
18542 	struct fc_vft_header *fc_vft_hdr;
18543 	struct fc_app_header *fc_app_hdr;
18544 	uint32_t *header = (uint32_t *) fc_hdr;
18545 
18546 #define FC_RCTL_MDS_DIAGS	0xF4
18547 
18548 	switch (fc_hdr->fh_r_ctl) {
18549 	case FC_RCTL_DD_UNCAT:		/* uncategorized information */
18550 	case FC_RCTL_DD_SOL_DATA:	/* solicited data */
18551 	case FC_RCTL_DD_UNSOL_CTL:	/* unsolicited control */
18552 	case FC_RCTL_DD_SOL_CTL:	/* solicited control or reply */
18553 	case FC_RCTL_DD_UNSOL_DATA:	/* unsolicited data */
18554 	case FC_RCTL_DD_DATA_DESC:	/* data descriptor */
18555 	case FC_RCTL_DD_UNSOL_CMD:	/* unsolicited command */
18556 	case FC_RCTL_DD_CMD_STATUS:	/* command status */
18557 	case FC_RCTL_ELS_REQ:	/* extended link services request */
18558 	case FC_RCTL_ELS_REP:	/* extended link services reply */
18559 	case FC_RCTL_ELS4_REQ:	/* FC-4 ELS request */
18560 	case FC_RCTL_ELS4_REP:	/* FC-4 ELS reply */
18561 	case FC_RCTL_BA_ABTS: 	/* basic link service abort */
18562 	case FC_RCTL_BA_RMC: 	/* remove connection */
18563 	case FC_RCTL_BA_ACC:	/* basic accept */
18564 	case FC_RCTL_BA_RJT:	/* basic reject */
18565 	case FC_RCTL_BA_PRMT:
18566 	case FC_RCTL_ACK_1:	/* acknowledge_1 */
18567 	case FC_RCTL_ACK_0:	/* acknowledge_0 */
18568 	case FC_RCTL_P_RJT:	/* port reject */
18569 	case FC_RCTL_F_RJT:	/* fabric reject */
18570 	case FC_RCTL_P_BSY:	/* port busy */
18571 	case FC_RCTL_F_BSY:	/* fabric busy to data frame */
18572 	case FC_RCTL_F_BSYL:	/* fabric busy to link control frame */
18573 	case FC_RCTL_LCR:	/* link credit reset */
18574 	case FC_RCTL_MDS_DIAGS: /* MDS Diagnostics */
18575 	case FC_RCTL_END:	/* end */
18576 		break;
18577 	case FC_RCTL_VFTH:	/* Virtual Fabric tagging Header */
18578 		fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
18579 		fc_hdr = &((struct fc_frame_header *)fc_vft_hdr)[1];
18580 		return lpfc_fc_frame_check(phba, fc_hdr);
18581 	case FC_RCTL_BA_NOP:	/* basic link service NOP */
18582 	default:
18583 		goto drop;
18584 	}
18585 
18586 	switch (fc_hdr->fh_type) {
18587 	case FC_TYPE_BLS:
18588 	case FC_TYPE_ELS:
18589 	case FC_TYPE_FCP:
18590 	case FC_TYPE_CT:
18591 	case FC_TYPE_NVME:
18592 		break;
18593 	case FC_TYPE_IP:
18594 	case FC_TYPE_ILS:
18595 	default:
18596 		goto drop;
18597 	}
18598 
18599 	if (unlikely(phba->link_flag == LS_LOOPBACK_MODE &&
18600 				phba->cfg_vmid_app_header)) {
18601 		/* Application header is 16B device header */
18602 		if (fc_hdr->fh_df_ctl & LPFC_FC_16B_DEVICE_HEADER) {
18603 			fc_app_hdr = (struct fc_app_header *) (fc_hdr + 1);
18604 			if (be32_to_cpu(fc_app_hdr->src_app_id) !=
18605 					LOOPBACK_SRC_APPID) {
18606 				lpfc_printf_log(phba, KERN_WARNING,
18607 						LOG_ELS | LOG_LIBDFC,
18608 						"1932 Loopback src app id "
18609 						"not matched, app_id:x%x\n",
18610 						be32_to_cpu(fc_app_hdr->src_app_id));
18611 
18612 				goto drop;
18613 			}
18614 		} else {
18615 			lpfc_printf_log(phba, KERN_WARNING,
18616 					LOG_ELS | LOG_LIBDFC,
18617 					"1933 Loopback df_ctl bit not set, "
18618 					"df_ctl:x%x\n",
18619 					fc_hdr->fh_df_ctl);
18620 
18621 			goto drop;
18622 		}
18623 	}
18624 
18625 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
18626 			"2538 Received frame rctl:x%x, type:x%x, "
18627 			"frame Data:%08x %08x %08x %08x %08x %08x %08x\n",
18628 			fc_hdr->fh_r_ctl, fc_hdr->fh_type,
18629 			be32_to_cpu(header[0]), be32_to_cpu(header[1]),
18630 			be32_to_cpu(header[2]), be32_to_cpu(header[3]),
18631 			be32_to_cpu(header[4]), be32_to_cpu(header[5]),
18632 			be32_to_cpu(header[6]));
18633 	return 0;
18634 drop:
18635 	lpfc_printf_log(phba, KERN_WARNING, LOG_ELS,
18636 			"2539 Dropped frame rctl:x%x type:x%x\n",
18637 			fc_hdr->fh_r_ctl, fc_hdr->fh_type);
18638 	return 1;
18639 }
18640 
18641 /**
18642  * lpfc_fc_hdr_get_vfi - Get the VFI from an FC frame
18643  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
18644  *
18645  * This function processes the FC header to retrieve the VFI from the VF
18646  * header, if one exists. This function will return the VFI if one exists
18647  * or 0 if no VSAN Header exists.
18648  **/
18649 static uint32_t
18650 lpfc_fc_hdr_get_vfi(struct fc_frame_header *fc_hdr)
18651 {
18652 	struct fc_vft_header *fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
18653 
18654 	if (fc_hdr->fh_r_ctl != FC_RCTL_VFTH)
18655 		return 0;
18656 	return bf_get(fc_vft_hdr_vf_id, fc_vft_hdr);
18657 }
18658 
18659 /**
18660  * lpfc_fc_frame_to_vport - Finds the vport that a frame is destined to
18661  * @phba: Pointer to the HBA structure to search for the vport on
18662  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
18663  * @fcfi: The FC Fabric ID that the frame came from
18664  * @did: Destination ID to match against
18665  *
18666  * This function searches the @phba for a vport that matches the content of the
18667  * @fc_hdr passed in and the @fcfi. This function uses the @fc_hdr to fetch the
18668  * VFI, if the Virtual Fabric Tagging Header exists, and the DID. This function
18669  * returns the matching vport pointer or NULL if unable to match frame to a
18670  * vport.
18671  **/
18672 static struct lpfc_vport *
18673 lpfc_fc_frame_to_vport(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr,
18674 		       uint16_t fcfi, uint32_t did)
18675 {
18676 	struct lpfc_vport **vports;
18677 	struct lpfc_vport *vport = NULL;
18678 	int i;
18679 
18680 	if (did == Fabric_DID)
18681 		return phba->pport;
18682 	if (test_bit(FC_PT2PT, &phba->pport->fc_flag) &&
18683 	    phba->link_state != LPFC_HBA_READY)
18684 		return phba->pport;
18685 
18686 	vports = lpfc_create_vport_work_array(phba);
18687 	if (vports != NULL) {
18688 		for (i = 0; i <= phba->max_vpi && vports[i] != NULL; i++) {
18689 			if (phba->fcf.fcfi == fcfi &&
18690 			    vports[i]->vfi == lpfc_fc_hdr_get_vfi(fc_hdr) &&
18691 			    vports[i]->fc_myDID == did) {
18692 				vport = vports[i];
18693 				break;
18694 			}
18695 		}
18696 	}
18697 	lpfc_destroy_vport_work_array(phba, vports);
18698 	return vport;
18699 }
18700 
18701 /**
18702  * lpfc_update_rcv_time_stamp - Update vport's rcv seq time stamp
18703  * @vport: The vport to work on.
18704  *
18705  * This function updates the receive sequence time stamp for this vport. The
18706  * receive sequence time stamp indicates the time that the last frame of the
18707  * the sequence that has been idle for the longest amount of time was received.
18708  * the driver uses this time stamp to indicate if any received sequences have
18709  * timed out.
18710  **/
18711 static void
18712 lpfc_update_rcv_time_stamp(struct lpfc_vport *vport)
18713 {
18714 	struct lpfc_dmabuf *h_buf;
18715 	struct hbq_dmabuf *dmabuf = NULL;
18716 
18717 	/* get the oldest sequence on the rcv list */
18718 	h_buf = list_get_first(&vport->rcv_buffer_list,
18719 			       struct lpfc_dmabuf, list);
18720 	if (!h_buf)
18721 		return;
18722 	dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18723 	vport->rcv_buffer_time_stamp = dmabuf->time_stamp;
18724 }
18725 
18726 /**
18727  * lpfc_cleanup_rcv_buffers - Cleans up all outstanding receive sequences.
18728  * @vport: The vport that the received sequences were sent to.
18729  *
18730  * This function cleans up all outstanding received sequences. This is called
18731  * by the driver when a link event or user action invalidates all the received
18732  * sequences.
18733  **/
18734 void
18735 lpfc_cleanup_rcv_buffers(struct lpfc_vport *vport)
18736 {
18737 	struct lpfc_dmabuf *h_buf, *hnext;
18738 	struct lpfc_dmabuf *d_buf, *dnext;
18739 	struct hbq_dmabuf *dmabuf = NULL;
18740 
18741 	/* start with the oldest sequence on the rcv list */
18742 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
18743 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18744 		list_del_init(&dmabuf->hbuf.list);
18745 		list_for_each_entry_safe(d_buf, dnext,
18746 					 &dmabuf->dbuf.list, list) {
18747 			list_del_init(&d_buf->list);
18748 			lpfc_in_buf_free(vport->phba, d_buf);
18749 		}
18750 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
18751 	}
18752 }
18753 
18754 /**
18755  * lpfc_rcv_seq_check_edtov - Cleans up timed out receive sequences.
18756  * @vport: The vport that the received sequences were sent to.
18757  *
18758  * This function determines whether any received sequences have timed out by
18759  * first checking the vport's rcv_buffer_time_stamp. If this time_stamp
18760  * indicates that there is at least one timed out sequence this routine will
18761  * go through the received sequences one at a time from most inactive to most
18762  * active to determine which ones need to be cleaned up. Once it has determined
18763  * that a sequence needs to be cleaned up it will simply free up the resources
18764  * without sending an abort.
18765  **/
18766 void
18767 lpfc_rcv_seq_check_edtov(struct lpfc_vport *vport)
18768 {
18769 	struct lpfc_dmabuf *h_buf, *hnext;
18770 	struct lpfc_dmabuf *d_buf, *dnext;
18771 	struct hbq_dmabuf *dmabuf = NULL;
18772 	unsigned long timeout;
18773 	int abort_count = 0;
18774 
18775 	timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
18776 		   vport->rcv_buffer_time_stamp);
18777 	if (list_empty(&vport->rcv_buffer_list) ||
18778 	    time_before(jiffies, timeout))
18779 		return;
18780 	/* start with the oldest sequence on the rcv list */
18781 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
18782 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18783 		timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
18784 			   dmabuf->time_stamp);
18785 		if (time_before(jiffies, timeout))
18786 			break;
18787 		abort_count++;
18788 		list_del_init(&dmabuf->hbuf.list);
18789 		list_for_each_entry_safe(d_buf, dnext,
18790 					 &dmabuf->dbuf.list, list) {
18791 			list_del_init(&d_buf->list);
18792 			lpfc_in_buf_free(vport->phba, d_buf);
18793 		}
18794 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
18795 	}
18796 	if (abort_count)
18797 		lpfc_update_rcv_time_stamp(vport);
18798 }
18799 
18800 /**
18801  * lpfc_fc_frame_add - Adds a frame to the vport's list of received sequences
18802  * @vport: pointer to a vitural port
18803  * @dmabuf: pointer to a dmabuf that describes the hdr and data of the FC frame
18804  *
18805  * This function searches through the existing incomplete sequences that have
18806  * been sent to this @vport. If the frame matches one of the incomplete
18807  * sequences then the dbuf in the @dmabuf is added to the list of frames that
18808  * make up that sequence. If no sequence is found that matches this frame then
18809  * the function will add the hbuf in the @dmabuf to the @vport's rcv_buffer_list
18810  * This function returns a pointer to the first dmabuf in the sequence list that
18811  * the frame was linked to.
18812  **/
18813 static struct hbq_dmabuf *
18814 lpfc_fc_frame_add(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
18815 {
18816 	struct fc_frame_header *new_hdr;
18817 	struct fc_frame_header *temp_hdr;
18818 	struct lpfc_dmabuf *d_buf;
18819 	struct lpfc_dmabuf *h_buf;
18820 	struct hbq_dmabuf *seq_dmabuf = NULL;
18821 	struct hbq_dmabuf *temp_dmabuf = NULL;
18822 	uint8_t	found = 0;
18823 
18824 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
18825 	dmabuf->time_stamp = jiffies;
18826 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18827 
18828 	/* Use the hdr_buf to find the sequence that this frame belongs to */
18829 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
18830 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
18831 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
18832 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
18833 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
18834 			continue;
18835 		/* found a pending sequence that matches this frame */
18836 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18837 		break;
18838 	}
18839 	if (!seq_dmabuf) {
18840 		/*
18841 		 * This indicates first frame received for this sequence.
18842 		 * Queue the buffer on the vport's rcv_buffer_list.
18843 		 */
18844 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
18845 		lpfc_update_rcv_time_stamp(vport);
18846 		return dmabuf;
18847 	}
18848 	temp_hdr = seq_dmabuf->hbuf.virt;
18849 	if (be16_to_cpu(new_hdr->fh_seq_cnt) <
18850 		be16_to_cpu(temp_hdr->fh_seq_cnt)) {
18851 		list_del_init(&seq_dmabuf->hbuf.list);
18852 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
18853 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
18854 		lpfc_update_rcv_time_stamp(vport);
18855 		return dmabuf;
18856 	}
18857 	/* move this sequence to the tail to indicate a young sequence */
18858 	list_move_tail(&seq_dmabuf->hbuf.list, &vport->rcv_buffer_list);
18859 	seq_dmabuf->time_stamp = jiffies;
18860 	lpfc_update_rcv_time_stamp(vport);
18861 	if (list_empty(&seq_dmabuf->dbuf.list)) {
18862 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
18863 		return seq_dmabuf;
18864 	}
18865 	/* find the correct place in the sequence to insert this frame */
18866 	d_buf = list_entry(seq_dmabuf->dbuf.list.prev, typeof(*d_buf), list);
18867 	while (!found) {
18868 		temp_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
18869 		temp_hdr = (struct fc_frame_header *)temp_dmabuf->hbuf.virt;
18870 		/*
18871 		 * If the frame's sequence count is greater than the frame on
18872 		 * the list then insert the frame right after this frame
18873 		 */
18874 		if (be16_to_cpu(new_hdr->fh_seq_cnt) >
18875 			be16_to_cpu(temp_hdr->fh_seq_cnt)) {
18876 			list_add(&dmabuf->dbuf.list, &temp_dmabuf->dbuf.list);
18877 			found = 1;
18878 			break;
18879 		}
18880 
18881 		if (&d_buf->list == &seq_dmabuf->dbuf.list)
18882 			break;
18883 		d_buf = list_entry(d_buf->list.prev, typeof(*d_buf), list);
18884 	}
18885 
18886 	if (found)
18887 		return seq_dmabuf;
18888 	return NULL;
18889 }
18890 
18891 /**
18892  * lpfc_sli4_abort_partial_seq - Abort partially assembled unsol sequence
18893  * @vport: pointer to a vitural port
18894  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18895  *
18896  * This function tries to abort from the partially assembed sequence, described
18897  * by the information from basic abbort @dmabuf. It checks to see whether such
18898  * partially assembled sequence held by the driver. If so, it shall free up all
18899  * the frames from the partially assembled sequence.
18900  *
18901  * Return
18902  * true  -- if there is matching partially assembled sequence present and all
18903  *          the frames freed with the sequence;
18904  * false -- if there is no matching partially assembled sequence present so
18905  *          nothing got aborted in the lower layer driver
18906  **/
18907 static bool
18908 lpfc_sli4_abort_partial_seq(struct lpfc_vport *vport,
18909 			    struct hbq_dmabuf *dmabuf)
18910 {
18911 	struct fc_frame_header *new_hdr;
18912 	struct fc_frame_header *temp_hdr;
18913 	struct lpfc_dmabuf *d_buf, *n_buf, *h_buf;
18914 	struct hbq_dmabuf *seq_dmabuf = NULL;
18915 
18916 	/* Use the hdr_buf to find the sequence that matches this frame */
18917 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
18918 	INIT_LIST_HEAD(&dmabuf->hbuf.list);
18919 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18920 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
18921 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
18922 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
18923 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
18924 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
18925 			continue;
18926 		/* found a pending sequence that matches this frame */
18927 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18928 		break;
18929 	}
18930 
18931 	/* Free up all the frames from the partially assembled sequence */
18932 	if (seq_dmabuf) {
18933 		list_for_each_entry_safe(d_buf, n_buf,
18934 					 &seq_dmabuf->dbuf.list, list) {
18935 			list_del_init(&d_buf->list);
18936 			lpfc_in_buf_free(vport->phba, d_buf);
18937 		}
18938 		return true;
18939 	}
18940 	return false;
18941 }
18942 
18943 /**
18944  * lpfc_sli4_abort_ulp_seq - Abort assembled unsol sequence from ulp
18945  * @vport: pointer to a vitural port
18946  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18947  *
18948  * This function tries to abort from the assembed sequence from upper level
18949  * protocol, described by the information from basic abbort @dmabuf. It
18950  * checks to see whether such pending context exists at upper level protocol.
18951  * If so, it shall clean up the pending context.
18952  *
18953  * Return
18954  * true  -- if there is matching pending context of the sequence cleaned
18955  *          at ulp;
18956  * false -- if there is no matching pending context of the sequence present
18957  *          at ulp.
18958  **/
18959 static bool
18960 lpfc_sli4_abort_ulp_seq(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
18961 {
18962 	struct lpfc_hba *phba = vport->phba;
18963 	int handled;
18964 
18965 	/* Accepting abort at ulp with SLI4 only */
18966 	if (phba->sli_rev < LPFC_SLI_REV4)
18967 		return false;
18968 
18969 	/* Register all caring upper level protocols to attend abort */
18970 	handled = lpfc_ct_handle_unsol_abort(phba, dmabuf);
18971 	if (handled)
18972 		return true;
18973 
18974 	return false;
18975 }
18976 
18977 /**
18978  * lpfc_sli4_seq_abort_rsp_cmpl - BLS ABORT RSP seq abort iocb complete handler
18979  * @phba: Pointer to HBA context object.
18980  * @cmd_iocbq: pointer to the command iocbq structure.
18981  * @rsp_iocbq: pointer to the response iocbq structure.
18982  *
18983  * This function handles the sequence abort response iocb command complete
18984  * event. It properly releases the memory allocated to the sequence abort
18985  * accept iocb.
18986  **/
18987 static void
18988 lpfc_sli4_seq_abort_rsp_cmpl(struct lpfc_hba *phba,
18989 			     struct lpfc_iocbq *cmd_iocbq,
18990 			     struct lpfc_iocbq *rsp_iocbq)
18991 {
18992 	if (cmd_iocbq) {
18993 		lpfc_nlp_put(cmd_iocbq->ndlp);
18994 		lpfc_sli_release_iocbq(phba, cmd_iocbq);
18995 	}
18996 
18997 	/* Failure means BLS ABORT RSP did not get delivered to remote node*/
18998 	if (rsp_iocbq && rsp_iocbq->iocb.ulpStatus)
18999 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19000 			"3154 BLS ABORT RSP failed, data:  x%x/x%x\n",
19001 			get_job_ulpstatus(phba, rsp_iocbq),
19002 			get_job_word4(phba, rsp_iocbq));
19003 }
19004 
19005 /**
19006  * lpfc_sli4_xri_inrange - check xri is in range of xris owned by driver.
19007  * @phba: Pointer to HBA context object.
19008  * @xri: xri id in transaction.
19009  *
19010  * This function validates the xri maps to the known range of XRIs allocated an
19011  * used by the driver.
19012  **/
19013 uint16_t
19014 lpfc_sli4_xri_inrange(struct lpfc_hba *phba,
19015 		      uint16_t xri)
19016 {
19017 	uint16_t i;
19018 
19019 	for (i = 0; i < phba->sli4_hba.max_cfg_param.max_xri; i++) {
19020 		if (xri == phba->sli4_hba.xri_ids[i])
19021 			return i;
19022 	}
19023 	return NO_XRI;
19024 }
19025 
19026 /**
19027  * lpfc_sli4_seq_abort_rsp - bls rsp to sequence abort
19028  * @vport: pointer to a virtual port.
19029  * @fc_hdr: pointer to a FC frame header.
19030  * @aborted: was the partially assembled receive sequence successfully aborted
19031  *
19032  * This function sends a basic response to a previous unsol sequence abort
19033  * event after aborting the sequence handling.
19034  **/
19035 void
19036 lpfc_sli4_seq_abort_rsp(struct lpfc_vport *vport,
19037 			struct fc_frame_header *fc_hdr, bool aborted)
19038 {
19039 	struct lpfc_hba *phba = vport->phba;
19040 	struct lpfc_iocbq *ctiocb = NULL;
19041 	struct lpfc_nodelist *ndlp;
19042 	uint16_t oxid, rxid, xri, lxri;
19043 	uint32_t sid, fctl;
19044 	union lpfc_wqe128 *icmd;
19045 	int rc;
19046 
19047 	if (!lpfc_is_link_up(phba))
19048 		return;
19049 
19050 	sid = sli4_sid_from_fc_hdr(fc_hdr);
19051 	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
19052 	rxid = be16_to_cpu(fc_hdr->fh_rx_id);
19053 
19054 	ndlp = lpfc_findnode_did(vport, sid);
19055 	if (!ndlp) {
19056 		ndlp = lpfc_nlp_init(vport, sid);
19057 		if (!ndlp) {
19058 			lpfc_printf_vlog(vport, KERN_WARNING, LOG_ELS,
19059 					 "1268 Failed to allocate ndlp for "
19060 					 "oxid:x%x SID:x%x\n", oxid, sid);
19061 			return;
19062 		}
19063 		/* Put ndlp onto vport node list */
19064 		lpfc_enqueue_node(vport, ndlp);
19065 	}
19066 
19067 	/* Allocate buffer for rsp iocb */
19068 	ctiocb = lpfc_sli_get_iocbq(phba);
19069 	if (!ctiocb)
19070 		return;
19071 
19072 	icmd = &ctiocb->wqe;
19073 
19074 	/* Extract the F_CTL field from FC_HDR */
19075 	fctl = sli4_fctl_from_fc_hdr(fc_hdr);
19076 
19077 	ctiocb->ndlp = lpfc_nlp_get(ndlp);
19078 	if (!ctiocb->ndlp) {
19079 		lpfc_sli_release_iocbq(phba, ctiocb);
19080 		return;
19081 	}
19082 
19083 	ctiocb->vport = vport;
19084 	ctiocb->cmd_cmpl = lpfc_sli4_seq_abort_rsp_cmpl;
19085 	ctiocb->sli4_lxritag = NO_XRI;
19086 	ctiocb->sli4_xritag = NO_XRI;
19087 	ctiocb->abort_rctl = FC_RCTL_BA_ACC;
19088 
19089 	if (fctl & FC_FC_EX_CTX)
19090 		/* Exchange responder sent the abort so we
19091 		 * own the oxid.
19092 		 */
19093 		xri = oxid;
19094 	else
19095 		xri = rxid;
19096 	lxri = lpfc_sli4_xri_inrange(phba, xri);
19097 	if (lxri != NO_XRI)
19098 		lpfc_set_rrq_active(phba, ndlp, lxri,
19099 			(xri == oxid) ? rxid : oxid, 0);
19100 	/* For BA_ABTS from exchange responder, if the logical xri with
19101 	 * the oxid maps to the FCP XRI range, the port no longer has
19102 	 * that exchange context, send a BLS_RJT. Override the IOCB for
19103 	 * a BA_RJT.
19104 	 */
19105 	if ((fctl & FC_FC_EX_CTX) &&
19106 	    (lxri > lpfc_sli4_get_iocb_cnt(phba))) {
19107 		ctiocb->abort_rctl = FC_RCTL_BA_RJT;
19108 		bf_set(xmit_bls_rsp64_rjt_vspec, &icmd->xmit_bls_rsp, 0);
19109 		bf_set(xmit_bls_rsp64_rjt_expc, &icmd->xmit_bls_rsp,
19110 		       FC_BA_RJT_INV_XID);
19111 		bf_set(xmit_bls_rsp64_rjt_rsnc, &icmd->xmit_bls_rsp,
19112 		       FC_BA_RJT_UNABLE);
19113 	}
19114 
19115 	/* If BA_ABTS failed to abort a partially assembled receive sequence,
19116 	 * the driver no longer has that exchange, send a BLS_RJT. Override
19117 	 * the IOCB for a BA_RJT.
19118 	 */
19119 	if (aborted == false) {
19120 		ctiocb->abort_rctl = FC_RCTL_BA_RJT;
19121 		bf_set(xmit_bls_rsp64_rjt_vspec, &icmd->xmit_bls_rsp, 0);
19122 		bf_set(xmit_bls_rsp64_rjt_expc, &icmd->xmit_bls_rsp,
19123 		       FC_BA_RJT_INV_XID);
19124 		bf_set(xmit_bls_rsp64_rjt_rsnc, &icmd->xmit_bls_rsp,
19125 		       FC_BA_RJT_UNABLE);
19126 	}
19127 
19128 	if (fctl & FC_FC_EX_CTX) {
19129 		/* ABTS sent by responder to CT exchange, construction
19130 		 * of BA_ACC will use OX_ID from ABTS for the XRI_TAG
19131 		 * field and RX_ID from ABTS for RX_ID field.
19132 		 */
19133 		ctiocb->abort_bls = LPFC_ABTS_UNSOL_RSP;
19134 		bf_set(xmit_bls_rsp64_rxid, &icmd->xmit_bls_rsp, rxid);
19135 	} else {
19136 		/* ABTS sent by initiator to CT exchange, construction
19137 		 * of BA_ACC will need to allocate a new XRI as for the
19138 		 * XRI_TAG field.
19139 		 */
19140 		ctiocb->abort_bls = LPFC_ABTS_UNSOL_INT;
19141 	}
19142 
19143 	/* OX_ID is invariable to who sent ABTS to CT exchange */
19144 	bf_set(xmit_bls_rsp64_oxid, &icmd->xmit_bls_rsp, oxid);
19145 	bf_set(xmit_bls_rsp64_oxid, &icmd->xmit_bls_rsp, rxid);
19146 
19147 	/* Use CT=VPI */
19148 	bf_set(wqe_els_did, &icmd->xmit_bls_rsp.wqe_dest,
19149 	       ndlp->nlp_DID);
19150 	bf_set(xmit_bls_rsp64_temprpi, &icmd->xmit_bls_rsp,
19151 	       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
19152 	bf_set(wqe_cmnd, &icmd->generic.wqe_com, CMD_XMIT_BLS_RSP64_CX);
19153 
19154 	/* Xmit CT abts response on exchange <xid> */
19155 	lpfc_printf_vlog(vport, KERN_INFO, LOG_ELS,
19156 			 "1200 Send BLS cmd x%x on oxid x%x Data: x%x\n",
19157 			 ctiocb->abort_rctl, oxid, phba->link_state);
19158 
19159 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, ctiocb, 0);
19160 	if (rc == IOCB_ERROR) {
19161 		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
19162 				 "2925 Failed to issue CT ABTS RSP x%x on "
19163 				 "xri x%x, Data x%x\n",
19164 				 ctiocb->abort_rctl, oxid,
19165 				 phba->link_state);
19166 		lpfc_nlp_put(ndlp);
19167 		ctiocb->ndlp = NULL;
19168 		lpfc_sli_release_iocbq(phba, ctiocb);
19169 	}
19170 
19171 	/* if only usage of this nodelist is BLS response, release initial ref
19172 	 * to free ndlp when transmit completes
19173 	 */
19174 	if (ndlp->nlp_state == NLP_STE_UNUSED_NODE &&
19175 	    !test_bit(NLP_DROPPED, &ndlp->nlp_flag) &&
19176 	    !(ndlp->fc4_xpt_flags & (NVME_XPT_REGD | SCSI_XPT_REGD))) {
19177 		set_bit(NLP_DROPPED, &ndlp->nlp_flag);
19178 		lpfc_nlp_put(ndlp);
19179 	}
19180 }
19181 
19182 /**
19183  * lpfc_sli4_handle_unsol_abort - Handle sli-4 unsolicited abort event
19184  * @vport: Pointer to the vport on which this sequence was received
19185  * @dmabuf: pointer to a dmabuf that describes the FC sequence
19186  *
19187  * This function handles an SLI-4 unsolicited abort event. If the unsolicited
19188  * receive sequence is only partially assembed by the driver, it shall abort
19189  * the partially assembled frames for the sequence. Otherwise, if the
19190  * unsolicited receive sequence has been completely assembled and passed to
19191  * the Upper Layer Protocol (ULP), it then mark the per oxid status for the
19192  * unsolicited sequence has been aborted. After that, it will issue a basic
19193  * accept to accept the abort.
19194  **/
19195 static void
19196 lpfc_sli4_handle_unsol_abort(struct lpfc_vport *vport,
19197 			     struct hbq_dmabuf *dmabuf)
19198 {
19199 	struct lpfc_hba *phba = vport->phba;
19200 	struct fc_frame_header fc_hdr;
19201 	uint32_t fctl;
19202 	bool aborted;
19203 
19204 	/* Make a copy of fc_hdr before the dmabuf being released */
19205 	memcpy(&fc_hdr, dmabuf->hbuf.virt, sizeof(struct fc_frame_header));
19206 	fctl = sli4_fctl_from_fc_hdr(&fc_hdr);
19207 
19208 	if (fctl & FC_FC_EX_CTX) {
19209 		/* ABTS by responder to exchange, no cleanup needed */
19210 		aborted = true;
19211 	} else {
19212 		/* ABTS by initiator to exchange, need to do cleanup */
19213 		aborted = lpfc_sli4_abort_partial_seq(vport, dmabuf);
19214 		if (aborted == false)
19215 			aborted = lpfc_sli4_abort_ulp_seq(vport, dmabuf);
19216 	}
19217 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
19218 
19219 	if (phba->nvmet_support) {
19220 		lpfc_nvmet_rcv_unsol_abort(vport, &fc_hdr);
19221 		return;
19222 	}
19223 
19224 	/* Respond with BA_ACC or BA_RJT accordingly */
19225 	lpfc_sli4_seq_abort_rsp(vport, &fc_hdr, aborted);
19226 }
19227 
19228 /**
19229  * lpfc_seq_complete - Indicates if a sequence is complete
19230  * @dmabuf: pointer to a dmabuf that describes the FC sequence
19231  *
19232  * This function checks the sequence, starting with the frame described by
19233  * @dmabuf, to see if all the frames associated with this sequence are present.
19234  * the frames associated with this sequence are linked to the @dmabuf using the
19235  * dbuf list. This function looks for two major things. 1) That the first frame
19236  * has a sequence count of zero. 2) There is a frame with last frame of sequence
19237  * set. 3) That there are no holes in the sequence count. The function will
19238  * return 1 when the sequence is complete, otherwise it will return 0.
19239  **/
19240 static int
19241 lpfc_seq_complete(struct hbq_dmabuf *dmabuf)
19242 {
19243 	struct fc_frame_header *hdr;
19244 	struct lpfc_dmabuf *d_buf;
19245 	struct hbq_dmabuf *seq_dmabuf;
19246 	uint32_t fctl;
19247 	int seq_count = 0;
19248 
19249 	hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
19250 	/* make sure first fame of sequence has a sequence count of zero */
19251 	if (hdr->fh_seq_cnt != seq_count)
19252 		return 0;
19253 	fctl = (hdr->fh_f_ctl[0] << 16 |
19254 		hdr->fh_f_ctl[1] << 8 |
19255 		hdr->fh_f_ctl[2]);
19256 	/* If last frame of sequence we can return success. */
19257 	if (fctl & FC_FC_END_SEQ)
19258 		return 1;
19259 	list_for_each_entry(d_buf, &dmabuf->dbuf.list, list) {
19260 		seq_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
19261 		hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
19262 		/* If there is a hole in the sequence count then fail. */
19263 		if (++seq_count != be16_to_cpu(hdr->fh_seq_cnt))
19264 			return 0;
19265 		fctl = (hdr->fh_f_ctl[0] << 16 |
19266 			hdr->fh_f_ctl[1] << 8 |
19267 			hdr->fh_f_ctl[2]);
19268 		/* If last frame of sequence we can return success. */
19269 		if (fctl & FC_FC_END_SEQ)
19270 			return 1;
19271 	}
19272 	return 0;
19273 }
19274 
19275 /**
19276  * lpfc_prep_seq - Prep sequence for ULP processing
19277  * @vport: Pointer to the vport on which this sequence was received
19278  * @seq_dmabuf: pointer to a dmabuf that describes the FC sequence
19279  *
19280  * This function takes a sequence, described by a list of frames, and creates
19281  * a list of iocbq structures to describe the sequence. This iocbq list will be
19282  * used to issue to the generic unsolicited sequence handler. This routine
19283  * returns a pointer to the first iocbq in the list. If the function is unable
19284  * to allocate an iocbq then it throw out the received frames that were not
19285  * able to be described and return a pointer to the first iocbq. If unable to
19286  * allocate any iocbqs (including the first) this function will return NULL.
19287  **/
19288 static struct lpfc_iocbq *
19289 lpfc_prep_seq(struct lpfc_vport *vport, struct hbq_dmabuf *seq_dmabuf)
19290 {
19291 	struct hbq_dmabuf *hbq_buf;
19292 	struct lpfc_dmabuf *d_buf, *n_buf;
19293 	struct lpfc_iocbq *first_iocbq, *iocbq;
19294 	struct fc_frame_header *fc_hdr;
19295 	uint32_t sid;
19296 	uint32_t len, tot_len;
19297 
19298 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
19299 	/* remove from receive buffer list */
19300 	list_del_init(&seq_dmabuf->hbuf.list);
19301 	lpfc_update_rcv_time_stamp(vport);
19302 	/* get the Remote Port's SID */
19303 	sid = sli4_sid_from_fc_hdr(fc_hdr);
19304 	tot_len = 0;
19305 	/* Get an iocbq struct to fill in. */
19306 	first_iocbq = lpfc_sli_get_iocbq(vport->phba);
19307 	if (first_iocbq) {
19308 		/* Initialize the first IOCB. */
19309 		first_iocbq->wcqe_cmpl.total_data_placed = 0;
19310 		bf_set(lpfc_wcqe_c_status, &first_iocbq->wcqe_cmpl,
19311 		       IOSTAT_SUCCESS);
19312 		first_iocbq->vport = vport;
19313 
19314 		/* Check FC Header to see what TYPE of frame we are rcv'ing */
19315 		if (sli4_type_from_fc_hdr(fc_hdr) == FC_TYPE_ELS) {
19316 			bf_set(els_rsp64_sid, &first_iocbq->wqe.xmit_els_rsp,
19317 			       sli4_did_from_fc_hdr(fc_hdr));
19318 		}
19319 
19320 		bf_set(wqe_ctxt_tag, &first_iocbq->wqe.xmit_els_rsp.wqe_com,
19321 		       NO_XRI);
19322 		bf_set(wqe_rcvoxid, &first_iocbq->wqe.xmit_els_rsp.wqe_com,
19323 		       be16_to_cpu(fc_hdr->fh_ox_id));
19324 
19325 		/* put the first buffer into the first iocb */
19326 		tot_len = bf_get(lpfc_rcqe_length,
19327 				 &seq_dmabuf->cq_event.cqe.rcqe_cmpl);
19328 
19329 		first_iocbq->cmd_dmabuf = &seq_dmabuf->dbuf;
19330 		first_iocbq->bpl_dmabuf = NULL;
19331 		/* Keep track of the BDE count */
19332 		first_iocbq->wcqe_cmpl.word3 = 1;
19333 
19334 		if (tot_len > LPFC_DATA_BUF_SIZE)
19335 			first_iocbq->wqe.gen_req.bde.tus.f.bdeSize =
19336 				LPFC_DATA_BUF_SIZE;
19337 		else
19338 			first_iocbq->wqe.gen_req.bde.tus.f.bdeSize = tot_len;
19339 
19340 		first_iocbq->wcqe_cmpl.total_data_placed = tot_len;
19341 		bf_set(wqe_els_did, &first_iocbq->wqe.xmit_els_rsp.wqe_dest,
19342 		       sid);
19343 	}
19344 	iocbq = first_iocbq;
19345 	/*
19346 	 * Each IOCBq can have two Buffers assigned, so go through the list
19347 	 * of buffers for this sequence and save two buffers in each IOCBq
19348 	 */
19349 	list_for_each_entry_safe(d_buf, n_buf, &seq_dmabuf->dbuf.list, list) {
19350 		if (!iocbq) {
19351 			lpfc_in_buf_free(vport->phba, d_buf);
19352 			continue;
19353 		}
19354 		if (!iocbq->bpl_dmabuf) {
19355 			iocbq->bpl_dmabuf = d_buf;
19356 			iocbq->wcqe_cmpl.word3++;
19357 			/* We need to get the size out of the right CQE */
19358 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
19359 			len = bf_get(lpfc_rcqe_length,
19360 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
19361 			iocbq->unsol_rcv_len = len;
19362 			iocbq->wcqe_cmpl.total_data_placed += len;
19363 			tot_len += len;
19364 		} else {
19365 			iocbq = lpfc_sli_get_iocbq(vport->phba);
19366 			if (!iocbq) {
19367 				if (first_iocbq) {
19368 					bf_set(lpfc_wcqe_c_status,
19369 					       &first_iocbq->wcqe_cmpl,
19370 					       IOSTAT_SUCCESS);
19371 					first_iocbq->wcqe_cmpl.parameter =
19372 						IOERR_NO_RESOURCES;
19373 				}
19374 				lpfc_in_buf_free(vport->phba, d_buf);
19375 				continue;
19376 			}
19377 			/* We need to get the size out of the right CQE */
19378 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
19379 			len = bf_get(lpfc_rcqe_length,
19380 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
19381 			iocbq->cmd_dmabuf = d_buf;
19382 			iocbq->bpl_dmabuf = NULL;
19383 			iocbq->wcqe_cmpl.word3 = 1;
19384 
19385 			if (len > LPFC_DATA_BUF_SIZE)
19386 				iocbq->wqe.xmit_els_rsp.bde.tus.f.bdeSize =
19387 					LPFC_DATA_BUF_SIZE;
19388 			else
19389 				iocbq->wqe.xmit_els_rsp.bde.tus.f.bdeSize =
19390 					len;
19391 
19392 			tot_len += len;
19393 			iocbq->wcqe_cmpl.total_data_placed = tot_len;
19394 			bf_set(wqe_els_did, &iocbq->wqe.xmit_els_rsp.wqe_dest,
19395 			       sid);
19396 			list_add_tail(&iocbq->list, &first_iocbq->list);
19397 		}
19398 	}
19399 	/* Free the sequence's header buffer */
19400 	if (!first_iocbq)
19401 		lpfc_in_buf_free(vport->phba, &seq_dmabuf->dbuf);
19402 
19403 	return first_iocbq;
19404 }
19405 
19406 static void
19407 lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *vport,
19408 			  struct hbq_dmabuf *seq_dmabuf)
19409 {
19410 	struct fc_frame_header *fc_hdr;
19411 	struct lpfc_iocbq *iocbq, *curr_iocb, *next_iocb;
19412 	struct lpfc_hba *phba = vport->phba;
19413 
19414 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
19415 	iocbq = lpfc_prep_seq(vport, seq_dmabuf);
19416 	if (!iocbq) {
19417 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19418 				"2707 Ring %d handler: Failed to allocate "
19419 				"iocb Rctl x%x Type x%x received\n",
19420 				LPFC_ELS_RING,
19421 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
19422 		return;
19423 	}
19424 	if (!lpfc_complete_unsol_iocb(phba,
19425 				      phba->sli4_hba.els_wq->pring,
19426 				      iocbq, fc_hdr->fh_r_ctl,
19427 				      fc_hdr->fh_type)) {
19428 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19429 				"2540 Ring %d handler: unexpected Rctl "
19430 				"x%x Type x%x received\n",
19431 				LPFC_ELS_RING,
19432 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
19433 		lpfc_in_buf_free(phba, &seq_dmabuf->dbuf);
19434 	}
19435 
19436 	/* Free iocb created in lpfc_prep_seq */
19437 	list_for_each_entry_safe(curr_iocb, next_iocb,
19438 				 &iocbq->list, list) {
19439 		list_del_init(&curr_iocb->list);
19440 		lpfc_sli_release_iocbq(phba, curr_iocb);
19441 	}
19442 	lpfc_sli_release_iocbq(phba, iocbq);
19443 }
19444 
19445 static void
19446 lpfc_sli4_mds_loopback_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
19447 			    struct lpfc_iocbq *rspiocb)
19448 {
19449 	struct lpfc_dmabuf *pcmd = cmdiocb->cmd_dmabuf;
19450 
19451 	if (pcmd && pcmd->virt)
19452 		dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
19453 	kfree(pcmd);
19454 	lpfc_sli_release_iocbq(phba, cmdiocb);
19455 	lpfc_drain_txq(phba);
19456 }
19457 
19458 static void
19459 lpfc_sli4_handle_mds_loopback(struct lpfc_vport *vport,
19460 			      struct hbq_dmabuf *dmabuf)
19461 {
19462 	struct fc_frame_header *fc_hdr;
19463 	struct lpfc_hba *phba = vport->phba;
19464 	struct lpfc_iocbq *iocbq = NULL;
19465 	union  lpfc_wqe128 *pwqe;
19466 	struct lpfc_dmabuf *pcmd = NULL;
19467 	uint32_t frame_len;
19468 	int rc;
19469 	unsigned long iflags;
19470 
19471 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
19472 	frame_len = bf_get(lpfc_rcqe_length, &dmabuf->cq_event.cqe.rcqe_cmpl);
19473 
19474 	/* Send the received frame back */
19475 	iocbq = lpfc_sli_get_iocbq(phba);
19476 	if (!iocbq) {
19477 		/* Queue cq event and wakeup worker thread to process it */
19478 		spin_lock_irqsave(&phba->hbalock, iflags);
19479 		list_add_tail(&dmabuf->cq_event.list,
19480 			      &phba->sli4_hba.sp_queue_event);
19481 		spin_unlock_irqrestore(&phba->hbalock, iflags);
19482 		set_bit(HBA_SP_QUEUE_EVT, &phba->hba_flag);
19483 		lpfc_worker_wake_up(phba);
19484 		return;
19485 	}
19486 
19487 	/* Allocate buffer for command payload */
19488 	pcmd = kmalloc_obj(struct lpfc_dmabuf);
19489 	if (pcmd)
19490 		pcmd->virt = dma_pool_alloc(phba->lpfc_drb_pool, GFP_KERNEL,
19491 					    &pcmd->phys);
19492 	if (!pcmd || !pcmd->virt)
19493 		goto exit;
19494 
19495 	INIT_LIST_HEAD(&pcmd->list);
19496 
19497 	/* copyin the payload */
19498 	memcpy(pcmd->virt, dmabuf->dbuf.virt, frame_len);
19499 
19500 	iocbq->cmd_dmabuf = pcmd;
19501 	iocbq->vport = vport;
19502 	iocbq->cmd_flag &= ~LPFC_FIP_ELS_ID_MASK;
19503 	iocbq->cmd_flag |= LPFC_USE_FCPWQIDX;
19504 	iocbq->num_bdes = 0;
19505 
19506 	pwqe = &iocbq->wqe;
19507 	/* fill in BDE's for command */
19508 	pwqe->gen_req.bde.addrHigh = putPaddrHigh(pcmd->phys);
19509 	pwqe->gen_req.bde.addrLow = putPaddrLow(pcmd->phys);
19510 	pwqe->gen_req.bde.tus.f.bdeSize = frame_len;
19511 	pwqe->gen_req.bde.tus.f.bdeFlags = BUFF_TYPE_BDE_64;
19512 
19513 	pwqe->send_frame.frame_len = frame_len;
19514 	pwqe->send_frame.fc_hdr_wd0 = be32_to_cpu(*((__be32 *)fc_hdr));
19515 	pwqe->send_frame.fc_hdr_wd1 = be32_to_cpu(*((__be32 *)fc_hdr + 1));
19516 	pwqe->send_frame.fc_hdr_wd2 = be32_to_cpu(*((__be32 *)fc_hdr + 2));
19517 	pwqe->send_frame.fc_hdr_wd3 = be32_to_cpu(*((__be32 *)fc_hdr + 3));
19518 	pwqe->send_frame.fc_hdr_wd4 = be32_to_cpu(*((__be32 *)fc_hdr + 4));
19519 	pwqe->send_frame.fc_hdr_wd5 = be32_to_cpu(*((__be32 *)fc_hdr + 5));
19520 
19521 	pwqe->generic.wqe_com.word7 = 0;
19522 	pwqe->generic.wqe_com.word10 = 0;
19523 
19524 	bf_set(wqe_cmnd, &pwqe->generic.wqe_com, CMD_SEND_FRAME);
19525 	bf_set(wqe_sof, &pwqe->generic.wqe_com, 0x2E); /* SOF byte */
19526 	bf_set(wqe_eof, &pwqe->generic.wqe_com, 0x41); /* EOF byte */
19527 	bf_set(wqe_lenloc, &pwqe->generic.wqe_com, 1);
19528 	bf_set(wqe_xbl, &pwqe->generic.wqe_com, 1);
19529 	bf_set(wqe_dbde, &pwqe->generic.wqe_com, 1);
19530 	bf_set(wqe_xc, &pwqe->generic.wqe_com, 1);
19531 	bf_set(wqe_cmd_type, &pwqe->generic.wqe_com, 0xA);
19532 	bf_set(wqe_cqid, &pwqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
19533 	bf_set(wqe_xri_tag, &pwqe->generic.wqe_com, iocbq->sli4_xritag);
19534 	bf_set(wqe_reqtag, &pwqe->generic.wqe_com, iocbq->iotag);
19535 	bf_set(wqe_class, &pwqe->generic.wqe_com, CLASS3);
19536 	pwqe->generic.wqe_com.abort_tag = iocbq->iotag;
19537 
19538 	iocbq->cmd_cmpl = lpfc_sli4_mds_loopback_cmpl;
19539 
19540 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, iocbq, 0);
19541 	if (rc == IOCB_ERROR)
19542 		goto exit;
19543 
19544 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
19545 	return;
19546 
19547 exit:
19548 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
19549 			"2023 Unable to process MDS loopback frame\n");
19550 	if (pcmd && pcmd->virt)
19551 		dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
19552 	kfree(pcmd);
19553 	if (iocbq)
19554 		lpfc_sli_release_iocbq(phba, iocbq);
19555 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
19556 }
19557 
19558 /**
19559  * lpfc_sli4_handle_received_buffer - Handle received buffers from firmware
19560  * @phba: Pointer to HBA context object.
19561  * @dmabuf: Pointer to a dmabuf that describes the FC sequence.
19562  *
19563  * This function is called with no lock held. This function processes all
19564  * the received buffers and gives it to upper layers when a received buffer
19565  * indicates that it is the final frame in the sequence. The interrupt
19566  * service routine processes received buffers at interrupt contexts.
19567  * Worker thread calls lpfc_sli4_handle_received_buffer, which will call the
19568  * appropriate receive function when the final frame in a sequence is received.
19569  **/
19570 void
19571 lpfc_sli4_handle_received_buffer(struct lpfc_hba *phba,
19572 				 struct hbq_dmabuf *dmabuf)
19573 {
19574 	struct hbq_dmabuf *seq_dmabuf;
19575 	struct fc_frame_header *fc_hdr;
19576 	struct lpfc_vport *vport;
19577 	uint32_t fcfi;
19578 	uint32_t did;
19579 
19580 	/* Process each received buffer */
19581 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
19582 
19583 	if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
19584 	    fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
19585 		vport = phba->pport;
19586 		/* Handle MDS Loopback frames */
19587 		if  (!test_bit(FC_UNLOADING, &phba->pport->load_flag))
19588 			lpfc_sli4_handle_mds_loopback(vport, dmabuf);
19589 		else
19590 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
19591 		return;
19592 	}
19593 
19594 	/* check to see if this a valid type of frame */
19595 	if (lpfc_fc_frame_check(phba, fc_hdr)) {
19596 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
19597 		return;
19598 	}
19599 
19600 	if ((bf_get(lpfc_cqe_code,
19601 		    &dmabuf->cq_event.cqe.rcqe_cmpl) == CQE_CODE_RECEIVE_V1))
19602 		fcfi = bf_get(lpfc_rcqe_fcf_id_v1,
19603 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
19604 	else
19605 		fcfi = bf_get(lpfc_rcqe_fcf_id,
19606 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
19607 
19608 	if (fc_hdr->fh_r_ctl == 0xF4 && fc_hdr->fh_type == 0xFF) {
19609 		vport = phba->pport;
19610 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
19611 				"2023 MDS Loopback %d bytes\n",
19612 				bf_get(lpfc_rcqe_length,
19613 				       &dmabuf->cq_event.cqe.rcqe_cmpl));
19614 		/* Handle MDS Loopback frames */
19615 		lpfc_sli4_handle_mds_loopback(vport, dmabuf);
19616 		return;
19617 	}
19618 
19619 	/* d_id this frame is directed to */
19620 	did = sli4_did_from_fc_hdr(fc_hdr);
19621 
19622 	vport = lpfc_fc_frame_to_vport(phba, fc_hdr, fcfi, did);
19623 	if (!vport) {
19624 		/* throw out the frame */
19625 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
19626 		return;
19627 	}
19628 
19629 	/* vport is registered unless we rcv a FLOGI directed to Fabric_DID */
19630 	if (!(vport->vpi_state & LPFC_VPI_REGISTERED) &&
19631 		(did != Fabric_DID)) {
19632 		/*
19633 		 * Throw out the frame if we are not pt2pt.
19634 		 * The pt2pt protocol allows for discovery frames
19635 		 * to be received without a registered VPI.
19636 		 */
19637 		if (!test_bit(FC_PT2PT, &vport->fc_flag) ||
19638 		    phba->link_state == LPFC_HBA_READY) {
19639 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
19640 			return;
19641 		}
19642 	}
19643 
19644 	/* Handle the basic abort sequence (BA_ABTS) event */
19645 	if (fc_hdr->fh_r_ctl == FC_RCTL_BA_ABTS) {
19646 		lpfc_sli4_handle_unsol_abort(vport, dmabuf);
19647 		return;
19648 	}
19649 
19650 	/* Link this frame */
19651 	seq_dmabuf = lpfc_fc_frame_add(vport, dmabuf);
19652 	if (!seq_dmabuf) {
19653 		/* unable to add frame to vport - throw it out */
19654 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
19655 		return;
19656 	}
19657 	/* If not last frame in sequence continue processing frames. */
19658 	if (!lpfc_seq_complete(seq_dmabuf))
19659 		return;
19660 
19661 	/* Send the complete sequence to the upper layer protocol */
19662 	lpfc_sli4_send_seq_to_ulp(vport, seq_dmabuf);
19663 }
19664 
19665 /**
19666  * lpfc_sli4_post_all_rpi_hdrs - Post the rpi header memory region to the port
19667  * @phba: pointer to lpfc hba data structure.
19668  *
19669  * This routine is invoked to post rpi header templates to the
19670  * HBA consistent with the SLI-4 interface spec.  This routine
19671  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
19672  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
19673  *
19674  * This routine does not require any locks.  It's usage is expected
19675  * to be driver load or reset recovery when the driver is
19676  * sequential.
19677  *
19678  * Return codes
19679  * 	0 - successful
19680  *      -EIO - The mailbox failed to complete successfully.
19681  * 	When this error occurs, the driver is not guaranteed
19682  *	to have any rpi regions posted to the device and
19683  *	must either attempt to repost the regions or take a
19684  *	fatal error.
19685  **/
19686 int
19687 lpfc_sli4_post_all_rpi_hdrs(struct lpfc_hba *phba)
19688 {
19689 	struct lpfc_rpi_hdr *rpi_page;
19690 	uint32_t rc = 0;
19691 	uint16_t lrpi = 0;
19692 
19693 	/* SLI4 ports that support extents do not require RPI headers. */
19694 	if (!phba->sli4_hba.rpi_hdrs_in_use)
19695 		goto exit;
19696 	if (phba->sli4_hba.extents_in_use)
19697 		return -EIO;
19698 
19699 	list_for_each_entry(rpi_page, &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
19700 		/*
19701 		 * Assign the rpi headers a physical rpi only if the driver
19702 		 * has not initialized those resources.  A port reset only
19703 		 * needs the headers posted.
19704 		 */
19705 		if (bf_get(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags) !=
19706 		    LPFC_RPI_RSRC_RDY)
19707 			rpi_page->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
19708 
19709 		rc = lpfc_sli4_post_rpi_hdr(phba, rpi_page);
19710 		if (rc != MBX_SUCCESS) {
19711 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19712 					"2008 Error %d posting all rpi "
19713 					"headers\n", rc);
19714 			rc = -EIO;
19715 			break;
19716 		}
19717 	}
19718 
19719  exit:
19720 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags,
19721 	       LPFC_RPI_RSRC_RDY);
19722 	return rc;
19723 }
19724 
19725 /**
19726  * lpfc_sli4_post_rpi_hdr - Post an rpi header memory region to the port
19727  * @phba: pointer to lpfc hba data structure.
19728  * @rpi_page:  pointer to the rpi memory region.
19729  *
19730  * This routine is invoked to post a single rpi header to the
19731  * HBA consistent with the SLI-4 interface spec.  This memory region
19732  * maps up to 64 rpi context regions.
19733  *
19734  * Return codes
19735  * 	0 - successful
19736  * 	-ENOMEM - No available memory
19737  *      -EIO - The mailbox failed to complete successfully.
19738  **/
19739 int
19740 lpfc_sli4_post_rpi_hdr(struct lpfc_hba *phba, struct lpfc_rpi_hdr *rpi_page)
19741 {
19742 	LPFC_MBOXQ_t *mboxq;
19743 	struct lpfc_mbx_post_hdr_tmpl *hdr_tmpl;
19744 	uint32_t rc = 0;
19745 	uint32_t shdr_status, shdr_add_status;
19746 	union lpfc_sli4_cfg_shdr *shdr;
19747 
19748 	/* SLI4 ports that support extents do not require RPI headers. */
19749 	if (!phba->sli4_hba.rpi_hdrs_in_use)
19750 		return rc;
19751 	if (phba->sli4_hba.extents_in_use)
19752 		return -EIO;
19753 
19754 	/* The port is notified of the header region via a mailbox command. */
19755 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19756 	if (!mboxq) {
19757 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19758 				"2001 Unable to allocate memory for issuing "
19759 				"SLI_CONFIG_SPECIAL mailbox command\n");
19760 		return -ENOMEM;
19761 	}
19762 
19763 	/* Post all rpi memory regions to the port. */
19764 	hdr_tmpl = &mboxq->u.mqe.un.hdr_tmpl;
19765 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
19766 			 LPFC_MBOX_OPCODE_FCOE_POST_HDR_TEMPLATE,
19767 			 sizeof(struct lpfc_mbx_post_hdr_tmpl) -
19768 			 sizeof(struct lpfc_sli4_cfg_mhdr),
19769 			 LPFC_SLI4_MBX_EMBED);
19770 
19771 
19772 	/* Post the physical rpi to the port for this rpi header. */
19773 	bf_set(lpfc_mbx_post_hdr_tmpl_rpi_offset, hdr_tmpl,
19774 	       rpi_page->start_rpi);
19775 	bf_set(lpfc_mbx_post_hdr_tmpl_page_cnt,
19776 	       hdr_tmpl, rpi_page->page_count);
19777 
19778 	hdr_tmpl->rpi_paddr_lo = putPaddrLow(rpi_page->dmabuf->phys);
19779 	hdr_tmpl->rpi_paddr_hi = putPaddrHigh(rpi_page->dmabuf->phys);
19780 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
19781 	shdr = (union lpfc_sli4_cfg_shdr *) &hdr_tmpl->header.cfg_shdr;
19782 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
19783 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
19784 	mempool_free(mboxq, phba->mbox_mem_pool);
19785 	if (shdr_status || shdr_add_status || rc) {
19786 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19787 				"2514 POST_RPI_HDR mailbox failed with "
19788 				"status x%x add_status x%x, mbx status x%x\n",
19789 				shdr_status, shdr_add_status, rc);
19790 		rc = -ENXIO;
19791 	} else {
19792 		/*
19793 		 * The next_rpi stores the next logical module-64 rpi value used
19794 		 * to post physical rpis in subsequent rpi postings.
19795 		 */
19796 		spin_lock_irq(&phba->hbalock);
19797 		phba->sli4_hba.next_rpi = rpi_page->next_rpi;
19798 		spin_unlock_irq(&phba->hbalock);
19799 	}
19800 	return rc;
19801 }
19802 
19803 /**
19804  * lpfc_sli4_alloc_rpi - Get an available rpi in the device's range
19805  * @phba: pointer to lpfc hba data structure.
19806  *
19807  * This routine is invoked to post rpi header templates to the
19808  * HBA consistent with the SLI-4 interface spec.  This routine
19809  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
19810  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
19811  *
19812  * Returns
19813  * 	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
19814  * 	LPFC_RPI_ALLOC_ERROR if no rpis are available.
19815  **/
19816 int
19817 lpfc_sli4_alloc_rpi(struct lpfc_hba *phba)
19818 {
19819 	unsigned long rpi;
19820 	uint16_t max_rpi, rpi_limit;
19821 	uint16_t rpi_remaining, lrpi = 0;
19822 	struct lpfc_rpi_hdr *rpi_hdr;
19823 	unsigned long iflag;
19824 
19825 	/*
19826 	 * Fetch the next logical rpi.  Because this index is logical,
19827 	 * the  driver starts at 0 each time.
19828 	 */
19829 	spin_lock_irqsave(&phba->hbalock, iflag);
19830 	max_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
19831 	rpi_limit = phba->sli4_hba.next_rpi;
19832 
19833 	rpi = find_first_zero_bit(phba->sli4_hba.rpi_bmask, rpi_limit);
19834 	if (rpi >= rpi_limit)
19835 		rpi = LPFC_RPI_ALLOC_ERROR;
19836 	else {
19837 		set_bit(rpi, phba->sli4_hba.rpi_bmask);
19838 		phba->sli4_hba.max_cfg_param.rpi_used++;
19839 		phba->sli4_hba.rpi_count++;
19840 	}
19841 	lpfc_printf_log(phba, KERN_INFO,
19842 			LOG_NODE | LOG_DISCOVERY,
19843 			"0001 Allocated rpi:x%x max:x%x lim:x%x\n",
19844 			(int) rpi, max_rpi, rpi_limit);
19845 
19846 	/*
19847 	 * Don't try to allocate more rpi header regions if the device limit
19848 	 * has been exhausted.
19849 	 */
19850 	if ((rpi == LPFC_RPI_ALLOC_ERROR) &&
19851 	    (phba->sli4_hba.rpi_count >= max_rpi)) {
19852 		spin_unlock_irqrestore(&phba->hbalock, iflag);
19853 		return rpi;
19854 	}
19855 
19856 	/*
19857 	 * RPI header postings are not required for SLI4 ports capable of
19858 	 * extents.
19859 	 */
19860 	if (!phba->sli4_hba.rpi_hdrs_in_use) {
19861 		spin_unlock_irqrestore(&phba->hbalock, iflag);
19862 		return rpi;
19863 	}
19864 
19865 	/*
19866 	 * If the driver is running low on rpi resources, allocate another
19867 	 * page now.  Note that the next_rpi value is used because
19868 	 * it represents how many are actually in use whereas max_rpi notes
19869 	 * how many are supported max by the device.
19870 	 */
19871 	rpi_remaining = phba->sli4_hba.next_rpi - phba->sli4_hba.rpi_count;
19872 	spin_unlock_irqrestore(&phba->hbalock, iflag);
19873 	if (rpi_remaining < LPFC_RPI_LOW_WATER_MARK) {
19874 		rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
19875 		if (!rpi_hdr) {
19876 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19877 					"2002 Error Could not grow rpi "
19878 					"count\n");
19879 		} else {
19880 			lrpi = rpi_hdr->start_rpi;
19881 			rpi_hdr->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
19882 			lpfc_sli4_post_rpi_hdr(phba, rpi_hdr);
19883 		}
19884 	}
19885 
19886 	return rpi;
19887 }
19888 
19889 /**
19890  * __lpfc_sli4_free_rpi - Release an rpi for reuse.
19891  * @phba: pointer to lpfc hba data structure.
19892  * @rpi: rpi to free
19893  *
19894  * This routine is invoked to release an rpi to the pool of
19895  * available rpis maintained by the driver.
19896  **/
19897 static void
19898 __lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
19899 {
19900 	/*
19901 	 * if the rpi value indicates a prior unreg has already
19902 	 * been done, skip the unreg.
19903 	 */
19904 	if (rpi == LPFC_RPI_ALLOC_ERROR)
19905 		return;
19906 
19907 	if (test_and_clear_bit(rpi, phba->sli4_hba.rpi_bmask)) {
19908 		phba->sli4_hba.rpi_count--;
19909 		phba->sli4_hba.max_cfg_param.rpi_used--;
19910 	} else {
19911 		lpfc_printf_log(phba, KERN_INFO,
19912 				LOG_NODE | LOG_DISCOVERY,
19913 				"2016 rpi %x not inuse\n",
19914 				rpi);
19915 	}
19916 }
19917 
19918 /**
19919  * lpfc_sli4_free_rpi - Release an rpi for reuse.
19920  * @phba: pointer to lpfc hba data structure.
19921  * @rpi: rpi to free
19922  *
19923  * This routine is invoked to release an rpi to the pool of
19924  * available rpis maintained by the driver.
19925  **/
19926 void
19927 lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
19928 {
19929 	spin_lock_irq(&phba->hbalock);
19930 	__lpfc_sli4_free_rpi(phba, rpi);
19931 	spin_unlock_irq(&phba->hbalock);
19932 }
19933 
19934 /**
19935  * lpfc_sli4_remove_rpis - Remove the rpi bitmask region
19936  * @phba: pointer to lpfc hba data structure.
19937  *
19938  * This routine is invoked to remove the memory region that
19939  * provided rpi via a bitmask.
19940  **/
19941 void
19942 lpfc_sli4_remove_rpis(struct lpfc_hba *phba)
19943 {
19944 	kfree(phba->sli4_hba.rpi_bmask);
19945 	kfree(phba->sli4_hba.rpi_ids);
19946 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
19947 }
19948 
19949 /**
19950  * lpfc_sli4_resume_rpi - Resume traffic relative to an RPI
19951  * @ndlp: pointer to lpfc nodelist data structure.
19952  * @cmpl: completion call-back.
19953  * @iocbq: data to load as mbox ctx_u information
19954  *
19955  * Return codes
19956  *	0 - successful
19957  *	-ENOMEM - No available memory
19958  *	-EIO - The mailbox failed to complete successfully.
19959  **/
19960 int
19961 lpfc_sli4_resume_rpi(struct lpfc_nodelist *ndlp,
19962 		     void (*cmpl)(struct lpfc_hba *, LPFC_MBOXQ_t *),
19963 		     struct lpfc_iocbq *iocbq)
19964 {
19965 	LPFC_MBOXQ_t *mboxq;
19966 	struct lpfc_hba *phba = ndlp->phba;
19967 	int rc;
19968 
19969 	/* The port is notified of the header region via a mailbox command. */
19970 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19971 	if (!mboxq)
19972 		return -ENOMEM;
19973 
19974 	/* If cmpl assigned, then this nlp_get pairs with
19975 	 * lpfc_mbx_cmpl_resume_rpi.
19976 	 *
19977 	 * Else cmpl is NULL, then this nlp_get pairs with
19978 	 * lpfc_sli_def_mbox_cmpl.
19979 	 */
19980 	if (!lpfc_nlp_get(ndlp)) {
19981 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19982 				"2122 %s: Failed to get nlp ref\n",
19983 				__func__);
19984 		mempool_free(mboxq, phba->mbox_mem_pool);
19985 		return -EIO;
19986 	}
19987 
19988 	lpfc_resume_rpi(mboxq, ndlp);
19989 	if (cmpl) {
19990 		mboxq->mbox_cmpl = cmpl;
19991 		mboxq->ctx_u.save_iocb = iocbq;
19992 	} else
19993 		mboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
19994 	mboxq->ctx_ndlp = ndlp;
19995 	mboxq->vport = ndlp->vport;
19996 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19997 	if (rc == MBX_NOT_FINISHED) {
19998 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19999 				"2010 Resume RPI Mailbox failed "
20000 				"status %d, mbxStatus x%x\n", rc,
20001 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
20002 		lpfc_nlp_put(ndlp);
20003 		mempool_free(mboxq, phba->mbox_mem_pool);
20004 		return -EIO;
20005 	}
20006 	return 0;
20007 }
20008 
20009 /**
20010  * lpfc_sli4_init_vpi - Initialize a vpi with the port
20011  * @vport: Pointer to the vport for which the vpi is being initialized
20012  *
20013  * This routine is invoked to activate a vpi with the port.
20014  *
20015  * Returns:
20016  *    0 success
20017  *    -Evalue otherwise
20018  **/
20019 int
20020 lpfc_sli4_init_vpi(struct lpfc_vport *vport)
20021 {
20022 	LPFC_MBOXQ_t *mboxq;
20023 	int rc = 0;
20024 	int retval = MBX_SUCCESS;
20025 	uint32_t mbox_tmo;
20026 	struct lpfc_hba *phba = vport->phba;
20027 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20028 	if (!mboxq)
20029 		return -ENOMEM;
20030 	lpfc_init_vpi(phba, mboxq, vport->vpi);
20031 	mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
20032 	rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
20033 	if (rc != MBX_SUCCESS) {
20034 		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
20035 				"2022 INIT VPI Mailbox failed "
20036 				"status %d, mbxStatus x%x\n", rc,
20037 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
20038 		retval = -EIO;
20039 	}
20040 	if (rc != MBX_TIMEOUT)
20041 		mempool_free(mboxq, vport->phba->mbox_mem_pool);
20042 
20043 	return retval;
20044 }
20045 
20046 /**
20047  * lpfc_mbx_cmpl_add_fcf_record - add fcf mbox completion handler.
20048  * @phba: pointer to lpfc hba data structure.
20049  * @mboxq: Pointer to mailbox object.
20050  *
20051  * This routine is invoked to manually add a single FCF record. The caller
20052  * must pass a completely initialized FCF_Record.  This routine takes
20053  * care of the nonembedded mailbox operations.
20054  **/
20055 static void
20056 lpfc_mbx_cmpl_add_fcf_record(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
20057 {
20058 	void *virt_addr;
20059 	union lpfc_sli4_cfg_shdr *shdr;
20060 	uint32_t shdr_status, shdr_add_status;
20061 
20062 	virt_addr = mboxq->sge_array->addr[0];
20063 	/* The IOCTL status is embedded in the mailbox subheader. */
20064 	shdr = (union lpfc_sli4_cfg_shdr *) virt_addr;
20065 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
20066 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
20067 
20068 	if ((shdr_status || shdr_add_status) &&
20069 		(shdr_status != STATUS_FCF_IN_USE))
20070 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20071 			"2558 ADD_FCF_RECORD mailbox failed with "
20072 			"status x%x add_status x%x\n",
20073 			shdr_status, shdr_add_status);
20074 
20075 	lpfc_sli4_mbox_cmd_free(phba, mboxq);
20076 }
20077 
20078 /**
20079  * lpfc_sli4_add_fcf_record - Manually add an FCF Record.
20080  * @phba: pointer to lpfc hba data structure.
20081  * @fcf_record:  pointer to the initialized fcf record to add.
20082  *
20083  * This routine is invoked to manually add a single FCF record. The caller
20084  * must pass a completely initialized FCF_Record.  This routine takes
20085  * care of the nonembedded mailbox operations.
20086  **/
20087 int
20088 lpfc_sli4_add_fcf_record(struct lpfc_hba *phba, struct fcf_record *fcf_record)
20089 {
20090 	int rc = 0;
20091 	LPFC_MBOXQ_t *mboxq;
20092 	uint8_t *bytep;
20093 	void *virt_addr;
20094 	struct lpfc_mbx_sge sge;
20095 	uint32_t alloc_len, req_len;
20096 	uint32_t fcfindex;
20097 
20098 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20099 	if (!mboxq) {
20100 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20101 			"2009 Failed to allocate mbox for ADD_FCF cmd\n");
20102 		return -ENOMEM;
20103 	}
20104 
20105 	req_len = sizeof(struct fcf_record) + sizeof(union lpfc_sli4_cfg_shdr) +
20106 		  sizeof(uint32_t);
20107 
20108 	/* Allocate DMA memory and set up the non-embedded mailbox command */
20109 	alloc_len = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
20110 				     LPFC_MBOX_OPCODE_FCOE_ADD_FCF,
20111 				     req_len, LPFC_SLI4_MBX_NEMBED);
20112 	if (alloc_len < req_len) {
20113 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20114 			"2523 Allocated DMA memory size (x%x) is "
20115 			"less than the requested DMA memory "
20116 			"size (x%x)\n", alloc_len, req_len);
20117 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
20118 		return -ENOMEM;
20119 	}
20120 
20121 	/*
20122 	 * Get the first SGE entry from the non-embedded DMA memory.  This
20123 	 * routine only uses a single SGE.
20124 	 */
20125 	lpfc_sli4_mbx_sge_get(mboxq, 0, &sge);
20126 	virt_addr = mboxq->sge_array->addr[0];
20127 	/*
20128 	 * Configure the FCF record for FCFI 0.  This is the driver's
20129 	 * hardcoded default and gets used in nonFIP mode.
20130 	 */
20131 	fcfindex = bf_get(lpfc_fcf_record_fcf_index, fcf_record);
20132 	bytep = virt_addr + sizeof(union lpfc_sli4_cfg_shdr);
20133 	lpfc_sli_pcimem_bcopy(&fcfindex, bytep, sizeof(uint32_t));
20134 
20135 	/*
20136 	 * Copy the fcf_index and the FCF Record Data. The data starts after
20137 	 * the FCoE header plus word10. The data copy needs to be endian
20138 	 * correct.
20139 	 */
20140 	bytep += sizeof(uint32_t);
20141 	lpfc_sli_pcimem_bcopy(fcf_record, bytep, sizeof(struct fcf_record));
20142 	mboxq->vport = phba->pport;
20143 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_add_fcf_record;
20144 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20145 	if (rc == MBX_NOT_FINISHED) {
20146 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20147 			"2515 ADD_FCF_RECORD mailbox failed with "
20148 			"status 0x%x\n", rc);
20149 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
20150 		rc = -EIO;
20151 	} else
20152 		rc = 0;
20153 
20154 	return rc;
20155 }
20156 
20157 /**
20158  * lpfc_sli4_build_dflt_fcf_record - Build the driver's default FCF Record.
20159  * @phba: pointer to lpfc hba data structure.
20160  * @fcf_record:  pointer to the fcf record to write the default data.
20161  * @fcf_index: FCF table entry index.
20162  *
20163  * This routine is invoked to build the driver's default FCF record.  The
20164  * values used are hardcoded.  This routine handles memory initialization.
20165  *
20166  **/
20167 void
20168 lpfc_sli4_build_dflt_fcf_record(struct lpfc_hba *phba,
20169 				struct fcf_record *fcf_record,
20170 				uint16_t fcf_index)
20171 {
20172 	memset(fcf_record, 0, sizeof(struct fcf_record));
20173 	fcf_record->max_rcv_size = LPFC_FCOE_MAX_RCV_SIZE;
20174 	fcf_record->fka_adv_period = LPFC_FCOE_FKA_ADV_PER;
20175 	fcf_record->fip_priority = LPFC_FCOE_FIP_PRIORITY;
20176 	bf_set(lpfc_fcf_record_mac_0, fcf_record, phba->fc_map[0]);
20177 	bf_set(lpfc_fcf_record_mac_1, fcf_record, phba->fc_map[1]);
20178 	bf_set(lpfc_fcf_record_mac_2, fcf_record, phba->fc_map[2]);
20179 	bf_set(lpfc_fcf_record_mac_3, fcf_record, LPFC_FCOE_FCF_MAC3);
20180 	bf_set(lpfc_fcf_record_mac_4, fcf_record, LPFC_FCOE_FCF_MAC4);
20181 	bf_set(lpfc_fcf_record_mac_5, fcf_record, LPFC_FCOE_FCF_MAC5);
20182 	bf_set(lpfc_fcf_record_fc_map_0, fcf_record, phba->fc_map[0]);
20183 	bf_set(lpfc_fcf_record_fc_map_1, fcf_record, phba->fc_map[1]);
20184 	bf_set(lpfc_fcf_record_fc_map_2, fcf_record, phba->fc_map[2]);
20185 	bf_set(lpfc_fcf_record_fcf_valid, fcf_record, 1);
20186 	bf_set(lpfc_fcf_record_fcf_avail, fcf_record, 1);
20187 	bf_set(lpfc_fcf_record_fcf_index, fcf_record, fcf_index);
20188 	bf_set(lpfc_fcf_record_mac_addr_prov, fcf_record,
20189 		LPFC_FCF_FPMA | LPFC_FCF_SPMA);
20190 	/* Set the VLAN bit map */
20191 	if (phba->valid_vlan) {
20192 		fcf_record->vlan_bitmap[phba->vlan_id / 8]
20193 			= 1 << (phba->vlan_id % 8);
20194 	}
20195 }
20196 
20197 /**
20198  * lpfc_sli4_fcf_scan_read_fcf_rec - Read hba fcf record for fcf scan.
20199  * @phba: pointer to lpfc hba data structure.
20200  * @fcf_index: FCF table entry offset.
20201  *
20202  * This routine is invoked to scan the entire FCF table by reading FCF
20203  * record and processing it one at a time starting from the @fcf_index
20204  * for initial FCF discovery or fast FCF failover rediscovery.
20205  *
20206  * Return 0 if the mailbox command is submitted successfully, none 0
20207  * otherwise.
20208  **/
20209 int
20210 lpfc_sli4_fcf_scan_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
20211 {
20212 	int rc = 0, error;
20213 	LPFC_MBOXQ_t *mboxq;
20214 
20215 	phba->fcoe_eventtag_at_fcf_scan = phba->fcoe_eventtag;
20216 	phba->fcoe_cvl_eventtag_attn = phba->fcoe_cvl_eventtag;
20217 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20218 	if (!mboxq) {
20219 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20220 				"2000 Failed to allocate mbox for "
20221 				"READ_FCF cmd\n");
20222 		error = -ENOMEM;
20223 		goto fail_fcf_scan;
20224 	}
20225 	/* Construct the read FCF record mailbox command */
20226 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
20227 	if (rc) {
20228 		error = -EINVAL;
20229 		goto fail_fcf_scan;
20230 	}
20231 	/* Issue the mailbox command asynchronously */
20232 	mboxq->vport = phba->pport;
20233 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_scan_read_fcf_rec;
20234 
20235 	set_bit(FCF_TS_INPROG, &phba->hba_flag);
20236 
20237 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20238 	if (rc == MBX_NOT_FINISHED)
20239 		error = -EIO;
20240 	else {
20241 		/* Reset eligible FCF count for new scan */
20242 		if (fcf_index == LPFC_FCOE_FCF_GET_FIRST)
20243 			phba->fcf.eligible_fcf_cnt = 0;
20244 		error = 0;
20245 	}
20246 fail_fcf_scan:
20247 	if (error) {
20248 		if (mboxq)
20249 			lpfc_sli4_mbox_cmd_free(phba, mboxq);
20250 		/* FCF scan failed, clear FCF_TS_INPROG flag */
20251 		clear_bit(FCF_TS_INPROG, &phba->hba_flag);
20252 	}
20253 	return error;
20254 }
20255 
20256 /**
20257  * lpfc_sli4_fcf_rr_read_fcf_rec - Read hba fcf record for roundrobin fcf.
20258  * @phba: pointer to lpfc hba data structure.
20259  * @fcf_index: FCF table entry offset.
20260  *
20261  * This routine is invoked to read an FCF record indicated by @fcf_index
20262  * and to use it for FLOGI roundrobin FCF failover.
20263  *
20264  * Return 0 if the mailbox command is submitted successfully, none 0
20265  * otherwise.
20266  **/
20267 int
20268 lpfc_sli4_fcf_rr_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
20269 {
20270 	int rc = 0, error;
20271 	LPFC_MBOXQ_t *mboxq;
20272 
20273 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20274 	if (!mboxq) {
20275 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
20276 				"2763 Failed to allocate mbox for "
20277 				"READ_FCF cmd\n");
20278 		error = -ENOMEM;
20279 		goto fail_fcf_read;
20280 	}
20281 	/* Construct the read FCF record mailbox command */
20282 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
20283 	if (rc) {
20284 		error = -EINVAL;
20285 		goto fail_fcf_read;
20286 	}
20287 	/* Issue the mailbox command asynchronously */
20288 	mboxq->vport = phba->pport;
20289 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_rr_read_fcf_rec;
20290 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20291 	if (rc == MBX_NOT_FINISHED)
20292 		error = -EIO;
20293 	else
20294 		error = 0;
20295 
20296 fail_fcf_read:
20297 	if (error && mboxq)
20298 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
20299 	return error;
20300 }
20301 
20302 /**
20303  * lpfc_sli4_read_fcf_rec - Read hba fcf record for update eligible fcf bmask.
20304  * @phba: pointer to lpfc hba data structure.
20305  * @fcf_index: FCF table entry offset.
20306  *
20307  * This routine is invoked to read an FCF record indicated by @fcf_index to
20308  * determine whether it's eligible for FLOGI roundrobin failover list.
20309  *
20310  * Return 0 if the mailbox command is submitted successfully, none 0
20311  * otherwise.
20312  **/
20313 int
20314 lpfc_sli4_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
20315 {
20316 	int rc = 0, error;
20317 	LPFC_MBOXQ_t *mboxq;
20318 
20319 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20320 	if (!mboxq) {
20321 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
20322 				"2758 Failed to allocate mbox for "
20323 				"READ_FCF cmd\n");
20324 				error = -ENOMEM;
20325 				goto fail_fcf_read;
20326 	}
20327 	/* Construct the read FCF record mailbox command */
20328 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
20329 	if (rc) {
20330 		error = -EINVAL;
20331 		goto fail_fcf_read;
20332 	}
20333 	/* Issue the mailbox command asynchronously */
20334 	mboxq->vport = phba->pport;
20335 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_read_fcf_rec;
20336 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20337 	if (rc == MBX_NOT_FINISHED)
20338 		error = -EIO;
20339 	else
20340 		error = 0;
20341 
20342 fail_fcf_read:
20343 	if (error && mboxq)
20344 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
20345 	return error;
20346 }
20347 
20348 /**
20349  * lpfc_check_next_fcf_pri_level
20350  * @phba: pointer to the lpfc_hba struct for this port.
20351  * This routine is called from the lpfc_sli4_fcf_rr_next_index_get
20352  * routine when the rr_bmask is empty. The FCF indecies are put into the
20353  * rr_bmask based on their priority level. Starting from the highest priority
20354  * to the lowest. The most likely FCF candidate will be in the highest
20355  * priority group. When this routine is called it searches the fcf_pri list for
20356  * next lowest priority group and repopulates the rr_bmask with only those
20357  * fcf_indexes.
20358  * returns:
20359  * 1=success 0=failure
20360  **/
20361 static int
20362 lpfc_check_next_fcf_pri_level(struct lpfc_hba *phba)
20363 {
20364 	uint16_t next_fcf_pri;
20365 	uint16_t last_index;
20366 	struct lpfc_fcf_pri *fcf_pri;
20367 	int rc;
20368 	int ret = 0;
20369 
20370 	last_index = find_first_bit(phba->fcf.fcf_rr_bmask,
20371 			LPFC_SLI4_FCF_TBL_INDX_MAX);
20372 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20373 			"3060 Last IDX %d\n", last_index);
20374 
20375 	/* Verify the priority list has 2 or more entries */
20376 	spin_lock_irq(&phba->hbalock);
20377 	if (list_empty(&phba->fcf.fcf_pri_list) ||
20378 	    list_is_singular(&phba->fcf.fcf_pri_list)) {
20379 		spin_unlock_irq(&phba->hbalock);
20380 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20381 			"3061 Last IDX %d\n", last_index);
20382 		return 0; /* Empty rr list */
20383 	}
20384 	spin_unlock_irq(&phba->hbalock);
20385 
20386 	next_fcf_pri = 0;
20387 	/*
20388 	 * Clear the rr_bmask and set all of the bits that are at this
20389 	 * priority.
20390 	 */
20391 	memset(phba->fcf.fcf_rr_bmask, 0,
20392 			sizeof(*phba->fcf.fcf_rr_bmask));
20393 	spin_lock_irq(&phba->hbalock);
20394 	list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
20395 		if (fcf_pri->fcf_rec.flag & LPFC_FCF_FLOGI_FAILED)
20396 			continue;
20397 		/*
20398 		 * the 1st priority that has not FLOGI failed
20399 		 * will be the highest.
20400 		 */
20401 		if (!next_fcf_pri)
20402 			next_fcf_pri = fcf_pri->fcf_rec.priority;
20403 		spin_unlock_irq(&phba->hbalock);
20404 		if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
20405 			rc = lpfc_sli4_fcf_rr_index_set(phba,
20406 						fcf_pri->fcf_rec.fcf_index);
20407 			if (rc)
20408 				return 0;
20409 		}
20410 		spin_lock_irq(&phba->hbalock);
20411 	}
20412 	/*
20413 	 * if next_fcf_pri was not set above and the list is not empty then
20414 	 * we have failed flogis on all of them. So reset flogi failed
20415 	 * and start at the beginning.
20416 	 */
20417 	if (!next_fcf_pri && !list_empty(&phba->fcf.fcf_pri_list)) {
20418 		list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
20419 			fcf_pri->fcf_rec.flag &= ~LPFC_FCF_FLOGI_FAILED;
20420 			/*
20421 			 * the 1st priority that has not FLOGI failed
20422 			 * will be the highest.
20423 			 */
20424 			if (!next_fcf_pri)
20425 				next_fcf_pri = fcf_pri->fcf_rec.priority;
20426 			spin_unlock_irq(&phba->hbalock);
20427 			if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
20428 				rc = lpfc_sli4_fcf_rr_index_set(phba,
20429 						fcf_pri->fcf_rec.fcf_index);
20430 				if (rc)
20431 					return 0;
20432 			}
20433 			spin_lock_irq(&phba->hbalock);
20434 		}
20435 	} else
20436 		ret = 1;
20437 	spin_unlock_irq(&phba->hbalock);
20438 
20439 	return ret;
20440 }
20441 /**
20442  * lpfc_sli4_fcf_rr_next_index_get - Get next eligible fcf record index
20443  * @phba: pointer to lpfc hba data structure.
20444  *
20445  * This routine is to get the next eligible FCF record index in a round
20446  * robin fashion. If the next eligible FCF record index equals to the
20447  * initial roundrobin FCF record index, LPFC_FCOE_FCF_NEXT_NONE (0xFFFF)
20448  * shall be returned, otherwise, the next eligible FCF record's index
20449  * shall be returned.
20450  **/
20451 uint16_t
20452 lpfc_sli4_fcf_rr_next_index_get(struct lpfc_hba *phba)
20453 {
20454 	uint16_t next;
20455 
20456 	do {
20457 		for_each_set_bit_wrap(next, phba->fcf.fcf_rr_bmask,
20458 				LPFC_SLI4_FCF_TBL_INDX_MAX, phba->fcf.current_rec.fcf_indx) {
20459 			if (next == phba->fcf.current_rec.fcf_indx)
20460 				continue;
20461 
20462 			if (!(phba->fcf.fcf_pri[next].fcf_rec.flag & LPFC_FCF_FLOGI_FAILED)) {
20463 				lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20464 					"2845 Get next roundrobin failover FCF (x%x)\n", next);
20465 				return next;
20466 			}
20467 
20468 			if (list_is_singular(&phba->fcf.fcf_pri_list))
20469 				return LPFC_FCOE_FCF_NEXT_NONE;
20470 		}
20471 
20472 		/*
20473 		 * If next fcf index is not found check if there are lower
20474 		 * Priority level fcf's in the fcf_priority list.
20475 		 * Set up the rr_bmask with all of the available fcf bits
20476 		 * at that level and continue the selection process.
20477 		 */
20478 	} while (lpfc_check_next_fcf_pri_level(phba));
20479 
20480 	lpfc_printf_log(phba, KERN_WARNING, LOG_FIP,
20481 			"2844 No roundrobin failover FCF available\n");
20482 
20483 	return LPFC_FCOE_FCF_NEXT_NONE;
20484 }
20485 
20486 /**
20487  * lpfc_sli4_fcf_rr_index_set - Set bmask with eligible fcf record index
20488  * @phba: pointer to lpfc hba data structure.
20489  * @fcf_index: index into the FCF table to 'set'
20490  *
20491  * This routine sets the FCF record index in to the eligible bmask for
20492  * roundrobin failover search. It checks to make sure that the index
20493  * does not go beyond the range of the driver allocated bmask dimension
20494  * before setting the bit.
20495  *
20496  * Returns 0 if the index bit successfully set, otherwise, it returns
20497  * -EINVAL.
20498  **/
20499 int
20500 lpfc_sli4_fcf_rr_index_set(struct lpfc_hba *phba, uint16_t fcf_index)
20501 {
20502 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
20503 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20504 				"2610 FCF (x%x) reached driver's book "
20505 				"keeping dimension:x%x\n",
20506 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
20507 		return -EINVAL;
20508 	}
20509 	/* Set the eligible FCF record index bmask */
20510 	set_bit(fcf_index, phba->fcf.fcf_rr_bmask);
20511 
20512 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20513 			"2790 Set FCF (x%x) to roundrobin FCF failover "
20514 			"bmask\n", fcf_index);
20515 
20516 	return 0;
20517 }
20518 
20519 /**
20520  * lpfc_sli4_fcf_rr_index_clear - Clear bmask from eligible fcf record index
20521  * @phba: pointer to lpfc hba data structure.
20522  * @fcf_index: index into the FCF table to 'clear'
20523  *
20524  * This routine clears the FCF record index from the eligible bmask for
20525  * roundrobin failover search. It checks to make sure that the index
20526  * does not go beyond the range of the driver allocated bmask dimension
20527  * before clearing the bit.
20528  **/
20529 void
20530 lpfc_sli4_fcf_rr_index_clear(struct lpfc_hba *phba, uint16_t fcf_index)
20531 {
20532 	struct lpfc_fcf_pri *fcf_pri, *fcf_pri_next;
20533 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
20534 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20535 				"2762 FCF (x%x) reached driver's book "
20536 				"keeping dimension:x%x\n",
20537 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
20538 		return;
20539 	}
20540 	/* Clear the eligible FCF record index bmask */
20541 	spin_lock_irq(&phba->hbalock);
20542 	list_for_each_entry_safe(fcf_pri, fcf_pri_next, &phba->fcf.fcf_pri_list,
20543 				 list) {
20544 		if (fcf_pri->fcf_rec.fcf_index == fcf_index) {
20545 			list_del_init(&fcf_pri->list);
20546 			break;
20547 		}
20548 	}
20549 	spin_unlock_irq(&phba->hbalock);
20550 	clear_bit(fcf_index, phba->fcf.fcf_rr_bmask);
20551 
20552 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20553 			"2791 Clear FCF (x%x) from roundrobin failover "
20554 			"bmask\n", fcf_index);
20555 }
20556 
20557 /**
20558  * lpfc_mbx_cmpl_redisc_fcf_table - completion routine for rediscover FCF table
20559  * @phba: pointer to lpfc hba data structure.
20560  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
20561  *
20562  * This routine is the completion routine for the rediscover FCF table mailbox
20563  * command. If the mailbox command returned failure, it will try to stop the
20564  * FCF rediscover wait timer.
20565  **/
20566 static void
20567 lpfc_mbx_cmpl_redisc_fcf_table(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
20568 {
20569 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
20570 	uint32_t shdr_status, shdr_add_status;
20571 
20572 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
20573 
20574 	shdr_status = bf_get(lpfc_mbox_hdr_status,
20575 			     &redisc_fcf->header.cfg_shdr.response);
20576 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
20577 			     &redisc_fcf->header.cfg_shdr.response);
20578 	if (shdr_status || shdr_add_status) {
20579 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20580 				"2746 Requesting for FCF rediscovery failed "
20581 				"status x%x add_status x%x\n",
20582 				shdr_status, shdr_add_status);
20583 		if (phba->fcf.fcf_flag & FCF_ACVL_DISC) {
20584 			spin_lock_irq(&phba->hbalock);
20585 			phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
20586 			spin_unlock_irq(&phba->hbalock);
20587 			/*
20588 			 * CVL event triggered FCF rediscover request failed,
20589 			 * last resort to re-try current registered FCF entry.
20590 			 */
20591 			lpfc_retry_pport_discovery(phba);
20592 		} else {
20593 			spin_lock_irq(&phba->hbalock);
20594 			phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
20595 			spin_unlock_irq(&phba->hbalock);
20596 			/*
20597 			 * DEAD FCF event triggered FCF rediscover request
20598 			 * failed, last resort to fail over as a link down
20599 			 * to FCF registration.
20600 			 */
20601 			lpfc_sli4_fcf_dead_failthrough(phba);
20602 		}
20603 	} else {
20604 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20605 				"2775 Start FCF rediscover quiescent timer\n");
20606 		/*
20607 		 * Start FCF rediscovery wait timer for pending FCF
20608 		 * before rescan FCF record table.
20609 		 */
20610 		lpfc_fcf_redisc_wait_start_timer(phba);
20611 	}
20612 
20613 	mempool_free(mbox, phba->mbox_mem_pool);
20614 }
20615 
20616 /**
20617  * lpfc_sli4_redisc_fcf_table - Request to rediscover entire FCF table by port.
20618  * @phba: pointer to lpfc hba data structure.
20619  *
20620  * This routine is invoked to request for rediscovery of the entire FCF table
20621  * by the port.
20622  **/
20623 int
20624 lpfc_sli4_redisc_fcf_table(struct lpfc_hba *phba)
20625 {
20626 	LPFC_MBOXQ_t *mbox;
20627 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
20628 	int rc, length;
20629 
20630 	/* Cancel retry delay timers to all vports before FCF rediscover */
20631 	lpfc_cancel_all_vport_retry_delay_timer(phba);
20632 
20633 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20634 	if (!mbox) {
20635 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20636 				"2745 Failed to allocate mbox for "
20637 				"requesting FCF rediscover.\n");
20638 		return -ENOMEM;
20639 	}
20640 
20641 	length = (sizeof(struct lpfc_mbx_redisc_fcf_tbl) -
20642 		  sizeof(struct lpfc_sli4_cfg_mhdr));
20643 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
20644 			 LPFC_MBOX_OPCODE_FCOE_REDISCOVER_FCF,
20645 			 length, LPFC_SLI4_MBX_EMBED);
20646 
20647 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
20648 	/* Set count to 0 for invalidating the entire FCF database */
20649 	bf_set(lpfc_mbx_redisc_fcf_count, redisc_fcf, 0);
20650 
20651 	/* Issue the mailbox command asynchronously */
20652 	mbox->vport = phba->pport;
20653 	mbox->mbox_cmpl = lpfc_mbx_cmpl_redisc_fcf_table;
20654 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
20655 
20656 	if (rc == MBX_NOT_FINISHED) {
20657 		mempool_free(mbox, phba->mbox_mem_pool);
20658 		return -EIO;
20659 	}
20660 	return 0;
20661 }
20662 
20663 /**
20664  * lpfc_sli4_fcf_dead_failthrough - Failthrough routine to fcf dead event
20665  * @phba: pointer to lpfc hba data structure.
20666  *
20667  * This function is the failover routine as a last resort to the FCF DEAD
20668  * event when driver failed to perform fast FCF failover.
20669  **/
20670 void
20671 lpfc_sli4_fcf_dead_failthrough(struct lpfc_hba *phba)
20672 {
20673 	uint32_t link_state;
20674 
20675 	/*
20676 	 * Last resort as FCF DEAD event failover will treat this as
20677 	 * a link down, but save the link state because we don't want
20678 	 * it to be changed to Link Down unless it is already down.
20679 	 */
20680 	link_state = phba->link_state;
20681 	lpfc_linkdown(phba);
20682 	phba->link_state = link_state;
20683 
20684 	/* Unregister FCF if no devices connected to it */
20685 	lpfc_unregister_unused_fcf(phba);
20686 }
20687 
20688 /**
20689  * lpfc_sli_get_config_region23 - Get sli3 port region 23 data.
20690  * @phba: pointer to lpfc hba data structure.
20691  * @rgn23_data: pointer to configure region 23 data.
20692  *
20693  * This function gets SLI3 port configure region 23 data through memory dump
20694  * mailbox command. When it successfully retrieves data, the size of the data
20695  * will be returned, otherwise, 0 will be returned.
20696  **/
20697 static uint32_t
20698 lpfc_sli_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
20699 {
20700 	LPFC_MBOXQ_t *pmb = NULL;
20701 	MAILBOX_t *mb;
20702 	uint32_t offset = 0;
20703 	int rc;
20704 
20705 	if (!rgn23_data)
20706 		return 0;
20707 
20708 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20709 	if (!pmb) {
20710 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20711 				"2600 failed to allocate mailbox memory\n");
20712 		return 0;
20713 	}
20714 	mb = &pmb->u.mb;
20715 
20716 	do {
20717 		lpfc_dump_mem(phba, pmb, offset, DMP_REGION_23);
20718 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
20719 
20720 		if (rc != MBX_SUCCESS) {
20721 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
20722 					"2601 failed to read config "
20723 					"region 23, rc 0x%x Status 0x%x\n",
20724 					rc, mb->mbxStatus);
20725 			mb->un.varDmp.word_cnt = 0;
20726 		}
20727 		/*
20728 		 * dump mem may return a zero when finished or we got a
20729 		 * mailbox error, either way we are done.
20730 		 */
20731 		if (mb->un.varDmp.word_cnt == 0)
20732 			break;
20733 
20734 		if (mb->un.varDmp.word_cnt > DMP_RGN23_SIZE - offset)
20735 			mb->un.varDmp.word_cnt = DMP_RGN23_SIZE - offset;
20736 
20737 		lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
20738 				       rgn23_data + offset,
20739 				       mb->un.varDmp.word_cnt);
20740 		offset += mb->un.varDmp.word_cnt;
20741 	} while (mb->un.varDmp.word_cnt && offset < DMP_RGN23_SIZE);
20742 
20743 	mempool_free(pmb, phba->mbox_mem_pool);
20744 	return offset;
20745 }
20746 
20747 /**
20748  * lpfc_sli4_get_config_region23 - Get sli4 port region 23 data.
20749  * @phba: pointer to lpfc hba data structure.
20750  * @rgn23_data: pointer to configure region 23 data.
20751  *
20752  * This function gets SLI4 port configure region 23 data through memory dump
20753  * mailbox command. When it successfully retrieves data, the size of the data
20754  * will be returned, otherwise, 0 will be returned.
20755  **/
20756 static uint32_t
20757 lpfc_sli4_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
20758 {
20759 	LPFC_MBOXQ_t *mboxq = NULL;
20760 	struct lpfc_dmabuf *mp = NULL;
20761 	struct lpfc_mqe *mqe;
20762 	uint32_t data_length = 0;
20763 	int rc;
20764 
20765 	if (!rgn23_data)
20766 		return 0;
20767 
20768 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20769 	if (!mboxq) {
20770 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20771 				"3105 failed to allocate mailbox memory\n");
20772 		return 0;
20773 	}
20774 
20775 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq))
20776 		goto out;
20777 	mqe = &mboxq->u.mqe;
20778 	mp = mboxq->ctx_buf;
20779 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
20780 	if (rc)
20781 		goto out;
20782 	data_length = mqe->un.mb_words[5];
20783 	if (data_length == 0)
20784 		goto out;
20785 	if (data_length > DMP_RGN23_SIZE) {
20786 		data_length = 0;
20787 		goto out;
20788 	}
20789 	lpfc_sli_pcimem_bcopy((char *)mp->virt, rgn23_data, data_length);
20790 out:
20791 	lpfc_mbox_rsrc_cleanup(phba, mboxq, MBOX_THD_UNLOCKED);
20792 	return data_length;
20793 }
20794 
20795 /**
20796  * lpfc_sli_read_link_ste - Read region 23 to decide if link is disabled.
20797  * @phba: pointer to lpfc hba data structure.
20798  *
20799  * This function read region 23 and parse TLV for port status to
20800  * decide if the user disaled the port. If the TLV indicates the
20801  * port is disabled, the hba_flag is set accordingly.
20802  **/
20803 void
20804 lpfc_sli_read_link_ste(struct lpfc_hba *phba)
20805 {
20806 	uint8_t *rgn23_data = NULL;
20807 	uint32_t if_type, data_size, sub_tlv_len, tlv_offset;
20808 	uint32_t offset = 0;
20809 
20810 	/* Get adapter Region 23 data */
20811 	rgn23_data = kzalloc(DMP_RGN23_SIZE, GFP_KERNEL);
20812 	if (!rgn23_data)
20813 		goto out;
20814 
20815 	if (phba->sli_rev < LPFC_SLI_REV4)
20816 		data_size = lpfc_sli_get_config_region23(phba, rgn23_data);
20817 	else {
20818 		if_type = bf_get(lpfc_sli_intf_if_type,
20819 				 &phba->sli4_hba.sli_intf);
20820 		if (if_type == LPFC_SLI_INTF_IF_TYPE_0)
20821 			goto out;
20822 		data_size = lpfc_sli4_get_config_region23(phba, rgn23_data);
20823 	}
20824 
20825 	if (!data_size)
20826 		goto out;
20827 
20828 	/* Check the region signature first */
20829 	if (memcmp(&rgn23_data[offset], LPFC_REGION23_SIGNATURE, 4)) {
20830 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20831 			"2619 Config region 23 has bad signature\n");
20832 			goto out;
20833 	}
20834 	offset += 4;
20835 
20836 	/* Check the data structure version */
20837 	if (rgn23_data[offset] != LPFC_REGION23_VERSION) {
20838 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20839 			"2620 Config region 23 has bad version\n");
20840 		goto out;
20841 	}
20842 	offset += 4;
20843 
20844 	/* Parse TLV entries in the region */
20845 	while (offset < data_size) {
20846 		if (rgn23_data[offset] == LPFC_REGION23_LAST_REC)
20847 			break;
20848 		/*
20849 		 * If the TLV is not driver specific TLV or driver id is
20850 		 * not linux driver id, skip the record.
20851 		 */
20852 		if ((rgn23_data[offset] != DRIVER_SPECIFIC_TYPE) ||
20853 		    (rgn23_data[offset + 2] != LINUX_DRIVER_ID) ||
20854 		    (rgn23_data[offset + 3] != 0)) {
20855 			offset += rgn23_data[offset + 1] * 4 + 4;
20856 			continue;
20857 		}
20858 
20859 		/* Driver found a driver specific TLV in the config region */
20860 		sub_tlv_len = rgn23_data[offset + 1] * 4;
20861 		offset += 4;
20862 		tlv_offset = 0;
20863 
20864 		/*
20865 		 * Search for configured port state sub-TLV.
20866 		 */
20867 		while ((offset < data_size) &&
20868 			(tlv_offset < sub_tlv_len)) {
20869 			if (rgn23_data[offset] == LPFC_REGION23_LAST_REC) {
20870 				offset += 4;
20871 				tlv_offset += 4;
20872 				break;
20873 			}
20874 			if (rgn23_data[offset] != PORT_STE_TYPE) {
20875 				offset += rgn23_data[offset + 1] * 4 + 4;
20876 				tlv_offset += rgn23_data[offset + 1] * 4 + 4;
20877 				continue;
20878 			}
20879 
20880 			/* This HBA contains PORT_STE configured */
20881 			if (!rgn23_data[offset + 2])
20882 				set_bit(LINK_DISABLED, &phba->hba_flag);
20883 
20884 			goto out;
20885 		}
20886 	}
20887 
20888 out:
20889 	kfree(rgn23_data);
20890 	return;
20891 }
20892 
20893 /**
20894  * lpfc_log_fw_write_cmpl - logs firmware write completion status
20895  * @phba: pointer to lpfc hba data structure
20896  * @shdr_status: wr_object rsp's status field
20897  * @shdr_add_status: wr_object rsp's add_status field
20898  * @shdr_add_status_2: wr_object rsp's add_status_2 field
20899  * @shdr_change_status: wr_object rsp's change_status field
20900  * @shdr_csf: wr_object rsp's csf bit
20901  *
20902  * This routine is intended to be called after a firmware write completes.
20903  * It will log next action items to be performed by the user to instantiate
20904  * the newly downloaded firmware or reason for incompatibility.
20905  **/
20906 static void
20907 lpfc_log_fw_write_cmpl(struct lpfc_hba *phba, u32 shdr_status,
20908 		       u32 shdr_add_status, u32 shdr_add_status_2,
20909 		       u32 shdr_change_status, u32 shdr_csf)
20910 {
20911 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20912 			"4198 %s: flash_id x%02x, asic_rev x%02x, "
20913 			"status x%02x, add_status x%02x, add_status_2 x%02x, "
20914 			"change_status x%02x, csf %01x\n", __func__,
20915 			phba->sli4_hba.flash_id, phba->sli4_hba.asic_rev,
20916 			shdr_status, shdr_add_status, shdr_add_status_2,
20917 			shdr_change_status, shdr_csf);
20918 
20919 	if (shdr_add_status == LPFC_ADD_STATUS_INCOMPAT_OBJ) {
20920 		switch (shdr_add_status_2) {
20921 		case LPFC_ADD_STATUS_2_INCOMPAT_FLASH:
20922 			lpfc_log_msg(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20923 				     "4199 Firmware write failed: "
20924 				     "image incompatible with flash x%02x\n",
20925 				     phba->sli4_hba.flash_id);
20926 			break;
20927 		case LPFC_ADD_STATUS_2_INCORRECT_ASIC:
20928 			lpfc_log_msg(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20929 				     "4200 Firmware write failed: "
20930 				     "image incompatible with ASIC "
20931 				     "architecture x%02x\n",
20932 				     phba->sli4_hba.asic_rev);
20933 			break;
20934 		default:
20935 			lpfc_log_msg(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20936 				     "4210 Firmware write failed: "
20937 				     "add_status_2 x%02x\n",
20938 				     shdr_add_status_2);
20939 			break;
20940 		}
20941 	} else if (!shdr_status && !shdr_add_status) {
20942 		if (shdr_change_status == LPFC_CHANGE_STATUS_FW_RESET ||
20943 		    shdr_change_status == LPFC_CHANGE_STATUS_PORT_MIGRATION) {
20944 			if (shdr_csf)
20945 				shdr_change_status =
20946 						   LPFC_CHANGE_STATUS_PCI_RESET;
20947 		}
20948 
20949 		switch (shdr_change_status) {
20950 		case (LPFC_CHANGE_STATUS_PHYS_DEV_RESET):
20951 			lpfc_log_msg(phba, KERN_NOTICE, LOG_MBOX | LOG_SLI,
20952 				     "3198 Firmware write complete: System "
20953 				     "reboot required to instantiate\n");
20954 			break;
20955 		case (LPFC_CHANGE_STATUS_FW_RESET):
20956 			lpfc_log_msg(phba, KERN_NOTICE, LOG_MBOX | LOG_SLI,
20957 				     "3199 Firmware write complete: "
20958 				     "Firmware reset required to "
20959 				     "instantiate\n");
20960 			break;
20961 		case (LPFC_CHANGE_STATUS_PORT_MIGRATION):
20962 			lpfc_log_msg(phba, KERN_NOTICE, LOG_MBOX | LOG_SLI,
20963 				     "3200 Firmware write complete: Port "
20964 				     "Migration or PCI Reset required to "
20965 				     "instantiate\n");
20966 			break;
20967 		case (LPFC_CHANGE_STATUS_PCI_RESET):
20968 			lpfc_log_msg(phba, KERN_NOTICE, LOG_MBOX | LOG_SLI,
20969 				     "3201 Firmware write complete: PCI "
20970 				     "Reset required to instantiate\n");
20971 			break;
20972 		default:
20973 			break;
20974 		}
20975 	}
20976 }
20977 
20978 /**
20979  * lpfc_wr_object - write an object to the firmware
20980  * @phba: HBA structure that indicates port to create a queue on.
20981  * @dmabuf_list: list of dmabufs to write to the port.
20982  * @size: the total byte value of the objects to write to the port.
20983  * @offset: the current offset to be used to start the transfer.
20984  *
20985  * This routine will create a wr_object mailbox command to send to the port.
20986  * the mailbox command will be constructed using the dma buffers described in
20987  * @dmabuf_list to create a list of BDEs. This routine will fill in as many
20988  * BDEs that the imbedded mailbox can support. The @offset variable will be
20989  * used to indicate the starting offset of the transfer and will also return
20990  * the offset after the write object mailbox has completed. @size is used to
20991  * determine the end of the object and whether the eof bit should be set.
20992  *
20993  * Return 0 is successful and offset will contain the new offset to use
20994  * for the next write.
20995  * Return negative value for error cases.
20996  **/
20997 int
20998 lpfc_wr_object(struct lpfc_hba *phba, struct list_head *dmabuf_list,
20999 	       uint32_t size, uint32_t *offset)
21000 {
21001 	struct lpfc_mbx_wr_object *wr_object;
21002 	LPFC_MBOXQ_t *mbox;
21003 	int rc = 0, i = 0;
21004 	int mbox_status = 0;
21005 	uint32_t shdr_status, shdr_add_status, shdr_add_status_2;
21006 	uint32_t shdr_change_status = 0, shdr_csf = 0;
21007 	uint32_t mbox_tmo;
21008 	struct lpfc_dmabuf *dmabuf;
21009 	uint32_t written = 0;
21010 	bool check_change_status = false;
21011 
21012 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
21013 	if (!mbox)
21014 		return -ENOMEM;
21015 
21016 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
21017 			LPFC_MBOX_OPCODE_WRITE_OBJECT,
21018 			sizeof(struct lpfc_mbx_wr_object) -
21019 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
21020 
21021 	wr_object = (struct lpfc_mbx_wr_object *)&mbox->u.mqe.un.wr_object;
21022 	wr_object->u.request.write_offset = *offset;
21023 	sprintf((uint8_t *)wr_object->u.request.object_name, "/");
21024 	wr_object->u.request.object_name[0] =
21025 		cpu_to_le32(wr_object->u.request.object_name[0]);
21026 	bf_set(lpfc_wr_object_eof, &wr_object->u.request, 0);
21027 	list_for_each_entry(dmabuf, dmabuf_list, list) {
21028 		if (i >= LPFC_MBX_WR_CONFIG_MAX_BDE || written >= size)
21029 			break;
21030 		wr_object->u.request.bde[i].addrLow = putPaddrLow(dmabuf->phys);
21031 		wr_object->u.request.bde[i].addrHigh =
21032 			putPaddrHigh(dmabuf->phys);
21033 		if (written + SLI4_PAGE_SIZE >= size) {
21034 			wr_object->u.request.bde[i].tus.f.bdeSize =
21035 				(size - written);
21036 			written += (size - written);
21037 			bf_set(lpfc_wr_object_eof, &wr_object->u.request, 1);
21038 			bf_set(lpfc_wr_object_eas, &wr_object->u.request, 1);
21039 			check_change_status = true;
21040 		} else {
21041 			wr_object->u.request.bde[i].tus.f.bdeSize =
21042 				SLI4_PAGE_SIZE;
21043 			written += SLI4_PAGE_SIZE;
21044 		}
21045 		i++;
21046 	}
21047 	wr_object->u.request.bde_count = i;
21048 	bf_set(lpfc_wr_object_write_length, &wr_object->u.request, written);
21049 	if (!phba->sli4_hba.intr_enable)
21050 		mbox_status = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
21051 	else {
21052 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
21053 		mbox_status = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
21054 	}
21055 
21056 	/* The mbox status needs to be maintained to detect MBOX_TIMEOUT. */
21057 	rc = mbox_status;
21058 
21059 	/* The IOCTL status is embedded in the mailbox subheader. */
21060 	shdr_status = bf_get(lpfc_mbox_hdr_status,
21061 			     &wr_object->header.cfg_shdr.response);
21062 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
21063 				 &wr_object->header.cfg_shdr.response);
21064 	shdr_add_status_2 = bf_get(lpfc_mbox_hdr_add_status_2,
21065 				   &wr_object->header.cfg_shdr.response);
21066 	if (check_change_status) {
21067 		shdr_change_status = bf_get(lpfc_wr_object_change_status,
21068 					    &wr_object->u.response);
21069 		shdr_csf = bf_get(lpfc_wr_object_csf,
21070 				  &wr_object->u.response);
21071 	}
21072 
21073 	if (shdr_status || shdr_add_status || shdr_add_status_2 || rc) {
21074 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
21075 				"3025 Write Object mailbox failed with "
21076 				"status x%x add_status x%x, add_status_2 x%x, "
21077 				"mbx status x%x\n",
21078 				shdr_status, shdr_add_status, shdr_add_status_2,
21079 				rc);
21080 		rc = -ENXIO;
21081 		*offset = shdr_add_status;
21082 	} else {
21083 		*offset += wr_object->u.response.actual_write_length;
21084 	}
21085 
21086 	if (rc || check_change_status)
21087 		lpfc_log_fw_write_cmpl(phba, shdr_status, shdr_add_status,
21088 				       shdr_add_status_2, shdr_change_status,
21089 				       shdr_csf);
21090 
21091 	if (!phba->sli4_hba.intr_enable)
21092 		mempool_free(mbox, phba->mbox_mem_pool);
21093 	else if (mbox_status != MBX_TIMEOUT)
21094 		mempool_free(mbox, phba->mbox_mem_pool);
21095 
21096 	return rc;
21097 }
21098 
21099 /**
21100  * lpfc_cleanup_pending_mbox - Free up vport discovery mailbox commands.
21101  * @vport: pointer to vport data structure.
21102  *
21103  * This function iterate through the mailboxq and clean up all REG_LOGIN
21104  * and REG_VPI mailbox commands associated with the vport. This function
21105  * is called when driver want to restart discovery of the vport due to
21106  * a Clear Virtual Link event.
21107  **/
21108 void
21109 lpfc_cleanup_pending_mbox(struct lpfc_vport *vport)
21110 {
21111 	struct lpfc_hba *phba = vport->phba;
21112 	LPFC_MBOXQ_t *mb, *nextmb;
21113 	struct lpfc_nodelist *ndlp;
21114 	struct lpfc_nodelist *act_mbx_ndlp = NULL;
21115 	LIST_HEAD(mbox_cmd_list);
21116 	uint8_t restart_loop;
21117 
21118 	/* Clean up internally queued mailbox commands with the vport */
21119 	spin_lock_irq(&phba->hbalock);
21120 	list_for_each_entry_safe(mb, nextmb, &phba->sli.mboxq, list) {
21121 		if (mb->vport != vport)
21122 			continue;
21123 
21124 		if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
21125 			(mb->u.mb.mbxCommand != MBX_REG_VPI))
21126 			continue;
21127 
21128 		list_move_tail(&mb->list, &mbox_cmd_list);
21129 	}
21130 	/* Clean up active mailbox command with the vport */
21131 	mb = phba->sli.mbox_active;
21132 	if (mb && (mb->vport == vport)) {
21133 		if ((mb->u.mb.mbxCommand == MBX_REG_LOGIN64) ||
21134 			(mb->u.mb.mbxCommand == MBX_REG_VPI))
21135 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
21136 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
21137 			act_mbx_ndlp = mb->ctx_ndlp;
21138 
21139 			/* This reference is local to this routine.  The
21140 			 * reference is removed at routine exit.
21141 			 */
21142 			act_mbx_ndlp = lpfc_nlp_get(act_mbx_ndlp);
21143 
21144 			/* Unregister the RPI when mailbox complete */
21145 			mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
21146 		}
21147 	}
21148 	/* Cleanup any mailbox completions which are not yet processed */
21149 	do {
21150 		restart_loop = 0;
21151 		list_for_each_entry(mb, &phba->sli.mboxq_cmpl, list) {
21152 			/*
21153 			 * If this mailox is already processed or it is
21154 			 * for another vport ignore it.
21155 			 */
21156 			if ((mb->vport != vport) ||
21157 				(mb->mbox_flag & LPFC_MBX_IMED_UNREG))
21158 				continue;
21159 
21160 			if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
21161 				(mb->u.mb.mbxCommand != MBX_REG_VPI))
21162 				continue;
21163 
21164 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
21165 			if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
21166 				ndlp = mb->ctx_ndlp;
21167 				/* Unregister the RPI when mailbox complete */
21168 				mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
21169 				restart_loop = 1;
21170 				clear_bit(NLP_IGNR_REG_CMPL, &ndlp->nlp_flag);
21171 				break;
21172 			}
21173 		}
21174 	} while (restart_loop);
21175 
21176 	spin_unlock_irq(&phba->hbalock);
21177 
21178 	/* Release the cleaned-up mailbox commands */
21179 	while (!list_empty(&mbox_cmd_list)) {
21180 		list_remove_head(&mbox_cmd_list, mb, LPFC_MBOXQ_t, list);
21181 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
21182 			ndlp = mb->ctx_ndlp;
21183 			mb->ctx_ndlp = NULL;
21184 			if (ndlp) {
21185 				clear_bit(NLP_IGNR_REG_CMPL, &ndlp->nlp_flag);
21186 				lpfc_nlp_put(ndlp);
21187 			}
21188 		}
21189 		lpfc_mbox_rsrc_cleanup(phba, mb, MBOX_THD_UNLOCKED);
21190 	}
21191 
21192 	/* Release the ndlp with the cleaned-up active mailbox command */
21193 	if (act_mbx_ndlp) {
21194 		clear_bit(NLP_IGNR_REG_CMPL, &act_mbx_ndlp->nlp_flag);
21195 		lpfc_nlp_put(act_mbx_ndlp);
21196 	}
21197 }
21198 
21199 /**
21200  * lpfc_drain_txq - Drain the txq
21201  * @phba: Pointer to HBA context object.
21202  *
21203  * This function attempt to submit IOCBs on the txq
21204  * to the adapter.  For SLI4 adapters, the txq contains
21205  * ELS IOCBs that have been deferred because the there
21206  * are no SGLs.  This congestion can occur with large
21207  * vport counts during node discovery.
21208  **/
21209 
21210 uint32_t
21211 lpfc_drain_txq(struct lpfc_hba *phba)
21212 {
21213 	LIST_HEAD(completions);
21214 	struct lpfc_sli_ring *pring;
21215 	struct lpfc_iocbq *piocbq = NULL;
21216 	unsigned long iflags = 0;
21217 	char *fail_msg = NULL;
21218 	uint32_t txq_cnt = 0;
21219 	struct lpfc_queue *wq;
21220 	int ret = 0;
21221 
21222 	if (phba->link_flag & LS_MDS_LOOPBACK) {
21223 		/* MDS WQE are posted only to first WQ*/
21224 		wq = phba->sli4_hba.hdwq[0].io_wq;
21225 		if (unlikely(!wq))
21226 			return 0;
21227 		pring = wq->pring;
21228 	} else {
21229 		wq = phba->sli4_hba.els_wq;
21230 		if (unlikely(!wq))
21231 			return 0;
21232 		pring = lpfc_phba_elsring(phba);
21233 	}
21234 
21235 	if (unlikely(!pring) || list_empty(&pring->txq))
21236 		return 0;
21237 
21238 	spin_lock_irqsave(&pring->ring_lock, iflags);
21239 	list_for_each_entry(piocbq, &pring->txq, list) {
21240 		txq_cnt++;
21241 	}
21242 
21243 	if (txq_cnt > pring->txq_max)
21244 		pring->txq_max = txq_cnt;
21245 
21246 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
21247 
21248 	while (!list_empty(&pring->txq)) {
21249 		spin_lock_irqsave(&pring->ring_lock, iflags);
21250 
21251 		piocbq = lpfc_sli_ringtx_get(phba, pring);
21252 		if (!piocbq) {
21253 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21254 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
21255 				"2823 txq empty and txq_cnt is %d\n",
21256 				txq_cnt);
21257 			break;
21258 		}
21259 		txq_cnt--;
21260 
21261 		ret = __lpfc_sli_issue_iocb(phba, pring->ringno, piocbq, 0);
21262 
21263 		if (ret && ret != IOCB_BUSY) {
21264 			fail_msg = " - Cannot send IO ";
21265 			piocbq->cmd_flag &= ~LPFC_DRIVER_ABORTED;
21266 		}
21267 		if (fail_msg) {
21268 			piocbq->cmd_flag |= LPFC_DRIVER_ABORTED;
21269 			/* Failed means we can't issue and need to cancel */
21270 			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
21271 					"2822 IOCB failed %s iotag 0x%x "
21272 					"xri 0x%x %d flg x%x\n",
21273 					fail_msg, piocbq->iotag,
21274 					piocbq->sli4_xritag, ret,
21275 					piocbq->cmd_flag);
21276 			list_add_tail(&piocbq->list, &completions);
21277 			fail_msg = NULL;
21278 		}
21279 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21280 		if (txq_cnt == 0 || ret == IOCB_BUSY)
21281 			break;
21282 	}
21283 	/* Cancel all the IOCBs that cannot be issued */
21284 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
21285 			      IOERR_SLI_ABORTED);
21286 
21287 	return txq_cnt;
21288 }
21289 
21290 /**
21291  * lpfc_wqe_bpl2sgl - Convert the bpl/bde to a sgl.
21292  * @phba: Pointer to HBA context object.
21293  * @pwqeq: Pointer to command WQE.
21294  * @sglq: Pointer to the scatter gather queue object.
21295  *
21296  * This routine converts the bpl or bde that is in the WQE
21297  * to a sgl list for the sli4 hardware. The physical address
21298  * of the bpl/bde is converted back to a virtual address.
21299  * If the WQE contains a BPL then the list of BDE's is
21300  * converted to sli4_sge's. If the WQE contains a single
21301  * BDE then it is converted to a single sli_sge.
21302  * The WQE is still in cpu endianness so the contents of
21303  * the bpl can be used without byte swapping.
21304  *
21305  * Returns valid XRI = Success, NO_XRI = Failure.
21306  */
21307 static uint16_t
21308 lpfc_wqe_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *pwqeq,
21309 		 struct lpfc_sglq *sglq)
21310 {
21311 	uint16_t xritag = NO_XRI;
21312 	struct ulp_bde64 *bpl = NULL;
21313 	struct ulp_bde64 bde;
21314 	struct sli4_sge *sgl  = NULL;
21315 	struct lpfc_dmabuf *dmabuf;
21316 	union lpfc_wqe128 *wqe;
21317 	int numBdes = 0;
21318 	int i = 0;
21319 	uint32_t offset = 0; /* accumulated offset in the sg request list */
21320 	int inbound = 0; /* number of sg reply entries inbound from firmware */
21321 	uint32_t cmd;
21322 
21323 	if (!pwqeq || !sglq)
21324 		return xritag;
21325 
21326 	sgl  = (struct sli4_sge *)sglq->sgl;
21327 	wqe = &pwqeq->wqe;
21328 	pwqeq->iocb.ulpIoTag = pwqeq->iotag;
21329 
21330 	cmd = bf_get(wqe_cmnd, &wqe->generic.wqe_com);
21331 	if (cmd == CMD_XMIT_BLS_RSP64_WQE)
21332 		return sglq->sli4_xritag;
21333 	numBdes = pwqeq->num_bdes;
21334 	if (numBdes) {
21335 		/* The addrHigh and addrLow fields within the WQE
21336 		 * have not been byteswapped yet so there is no
21337 		 * need to swap them back.
21338 		 */
21339 		if (pwqeq->bpl_dmabuf)
21340 			dmabuf = pwqeq->bpl_dmabuf;
21341 		else
21342 			return xritag;
21343 
21344 		bpl  = (struct ulp_bde64 *)dmabuf->virt;
21345 		if (!bpl)
21346 			return xritag;
21347 
21348 		for (i = 0; i < numBdes; i++) {
21349 			/* Should already be byte swapped. */
21350 			sgl->addr_hi = bpl->addrHigh;
21351 			sgl->addr_lo = bpl->addrLow;
21352 
21353 			sgl->word2 = le32_to_cpu(sgl->word2);
21354 			if ((i+1) == numBdes)
21355 				bf_set(lpfc_sli4_sge_last, sgl, 1);
21356 			else
21357 				bf_set(lpfc_sli4_sge_last, sgl, 0);
21358 			/* swap the size field back to the cpu so we
21359 			 * can assign it to the sgl.
21360 			 */
21361 			bde.tus.w = le32_to_cpu(bpl->tus.w);
21362 			sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
21363 			/* The offsets in the sgl need to be accumulated
21364 			 * separately for the request and reply lists.
21365 			 * The request is always first, the reply follows.
21366 			 */
21367 			switch (cmd) {
21368 			case CMD_GEN_REQUEST64_WQE:
21369 				/* add up the reply sg entries */
21370 				if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
21371 					inbound++;
21372 				/* first inbound? reset the offset */
21373 				if (inbound == 1)
21374 					offset = 0;
21375 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
21376 				bf_set(lpfc_sli4_sge_type, sgl,
21377 					LPFC_SGE_TYPE_DATA);
21378 				offset += bde.tus.f.bdeSize;
21379 				break;
21380 			case CMD_FCP_TRSP64_WQE:
21381 				bf_set(lpfc_sli4_sge_offset, sgl, 0);
21382 				bf_set(lpfc_sli4_sge_type, sgl,
21383 					LPFC_SGE_TYPE_DATA);
21384 				break;
21385 			case CMD_FCP_TSEND64_WQE:
21386 			case CMD_FCP_TRECEIVE64_WQE:
21387 				bf_set(lpfc_sli4_sge_type, sgl,
21388 					bpl->tus.f.bdeFlags);
21389 				if (i < 3)
21390 					offset = 0;
21391 				else
21392 					offset += bde.tus.f.bdeSize;
21393 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
21394 				break;
21395 			}
21396 			sgl->word2 = cpu_to_le32(sgl->word2);
21397 			bpl++;
21398 			sgl++;
21399 		}
21400 	} else if (wqe->gen_req.bde.tus.f.bdeFlags == BUFF_TYPE_BDE_64) {
21401 		/* The addrHigh and addrLow fields of the BDE have not
21402 		 * been byteswapped yet so they need to be swapped
21403 		 * before putting them in the sgl.
21404 		 */
21405 		sgl->addr_hi = cpu_to_le32(wqe->gen_req.bde.addrHigh);
21406 		sgl->addr_lo = cpu_to_le32(wqe->gen_req.bde.addrLow);
21407 		sgl->word2 = le32_to_cpu(sgl->word2);
21408 		bf_set(lpfc_sli4_sge_last, sgl, 1);
21409 		sgl->word2 = cpu_to_le32(sgl->word2);
21410 		sgl->sge_len = cpu_to_le32(wqe->gen_req.bde.tus.f.bdeSize);
21411 	}
21412 	return sglq->sli4_xritag;
21413 }
21414 
21415 /**
21416  * lpfc_sli4_issue_wqe - Issue an SLI4 Work Queue Entry (WQE)
21417  * @phba: Pointer to HBA context object.
21418  * @qp: Pointer to HDW queue.
21419  * @pwqe: Pointer to command WQE.
21420  **/
21421 int
21422 lpfc_sli4_issue_wqe(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
21423 		    struct lpfc_iocbq *pwqe)
21424 {
21425 	union lpfc_wqe128 *wqe = &pwqe->wqe;
21426 	struct lpfc_async_xchg_ctx *ctxp;
21427 	struct lpfc_queue *wq;
21428 	struct lpfc_sglq *sglq;
21429 	struct lpfc_sli_ring *pring;
21430 	unsigned long iflags;
21431 	int ret = 0;
21432 
21433 	/* NVME_LS and NVME_LS ABTS requests. */
21434 	if (pwqe->cmd_flag & LPFC_IO_NVME_LS) {
21435 		pring =  phba->sli4_hba.nvmels_wq->pring;
21436 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
21437 					  qp, wq_access);
21438 		sglq = __lpfc_sli_get_els_sglq(phba, pwqe);
21439 		if (!sglq) {
21440 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21441 			return WQE_BUSY;
21442 		}
21443 		pwqe->sli4_lxritag = sglq->sli4_lxritag;
21444 		pwqe->sli4_xritag = sglq->sli4_xritag;
21445 		if (lpfc_wqe_bpl2sgl(phba, pwqe, sglq) == NO_XRI) {
21446 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21447 			return WQE_ERROR;
21448 		}
21449 		bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
21450 		       pwqe->sli4_xritag);
21451 		ret = lpfc_sli4_wq_put(phba->sli4_hba.nvmels_wq, wqe);
21452 		if (ret) {
21453 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21454 			return ret;
21455 		}
21456 
21457 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
21458 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21459 
21460 		lpfc_sli4_poll_eq(qp->hba_eq);
21461 		return 0;
21462 	}
21463 
21464 	/* NVME_FCREQ and NVME_ABTS requests */
21465 	if (pwqe->cmd_flag & (LPFC_IO_NVME | LPFC_IO_FCP | LPFC_IO_CMF)) {
21466 		/* Get the IO distribution (hba_wqidx) for WQ assignment. */
21467 		wq = qp->io_wq;
21468 		pring = wq->pring;
21469 
21470 		bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
21471 
21472 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
21473 					  qp, wq_access);
21474 		ret = lpfc_sli4_wq_put(wq, wqe);
21475 		if (ret) {
21476 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21477 			return ret;
21478 		}
21479 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
21480 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21481 
21482 		lpfc_sli4_poll_eq(qp->hba_eq);
21483 		return 0;
21484 	}
21485 
21486 	/* NVMET requests */
21487 	if (pwqe->cmd_flag & LPFC_IO_NVMET) {
21488 		/* Get the IO distribution (hba_wqidx) for WQ assignment. */
21489 		wq = qp->io_wq;
21490 		pring = wq->pring;
21491 
21492 		ctxp = pwqe->context_un.axchg;
21493 		sglq = ctxp->ctxbuf->sglq;
21494 		if (pwqe->sli4_xritag ==  NO_XRI) {
21495 			pwqe->sli4_lxritag = sglq->sli4_lxritag;
21496 			pwqe->sli4_xritag = sglq->sli4_xritag;
21497 		}
21498 		bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
21499 		       pwqe->sli4_xritag);
21500 		bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
21501 
21502 		lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
21503 					  qp, wq_access);
21504 		ret = lpfc_sli4_wq_put(wq, wqe);
21505 		if (ret) {
21506 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
21507 			return ret;
21508 		}
21509 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
21510 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
21511 
21512 		lpfc_sli4_poll_eq(qp->hba_eq);
21513 		return 0;
21514 	}
21515 	return WQE_ERROR;
21516 }
21517 
21518 /**
21519  * lpfc_sli4_issue_abort_iotag - SLI-4 WQE init & issue for the Abort
21520  * @phba: Pointer to HBA context object.
21521  * @cmdiocb: Pointer to driver command iocb object.
21522  * @cmpl: completion function.
21523  *
21524  * Fill the appropriate fields for the abort WQE and call
21525  * internal routine lpfc_sli4_issue_wqe to send the WQE
21526  * This function is called with hbalock held and no ring_lock held.
21527  *
21528  * RETURNS 0 - SUCCESS
21529  **/
21530 
21531 int
21532 lpfc_sli4_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
21533 			    void *cmpl)
21534 {
21535 	struct lpfc_vport *vport = cmdiocb->vport;
21536 	struct lpfc_iocbq *abtsiocb = NULL;
21537 	union lpfc_wqe128 *abtswqe;
21538 	struct lpfc_io_buf *lpfc_cmd;
21539 	int retval = IOCB_ERROR;
21540 	u16 xritag = cmdiocb->sli4_xritag;
21541 
21542 	/*
21543 	 * The scsi command can not be in txq and it is in flight because the
21544 	 * pCmd is still pointing at the SCSI command we have to abort. There
21545 	 * is no need to search the txcmplq. Just send an abort to the FW.
21546 	 */
21547 
21548 	abtsiocb = __lpfc_sli_get_iocbq(phba);
21549 	if (!abtsiocb)
21550 		return WQE_NORESOURCE;
21551 
21552 	/* Indicate the IO is being aborted by the driver. */
21553 	cmdiocb->cmd_flag |= LPFC_DRIVER_ABORTED;
21554 
21555 	abtswqe = &abtsiocb->wqe;
21556 	memset(abtswqe, 0, sizeof(*abtswqe));
21557 
21558 	if (!lpfc_is_link_up(phba) || (phba->link_flag & LS_EXTERNAL_LOOPBACK))
21559 		bf_set(abort_cmd_ia, &abtswqe->abort_cmd, 1);
21560 	bf_set(abort_cmd_criteria, &abtswqe->abort_cmd, T_XRI_TAG);
21561 	abtswqe->abort_cmd.rsrvd5 = 0;
21562 	abtswqe->abort_cmd.wqe_com.abort_tag = xritag;
21563 	bf_set(wqe_reqtag, &abtswqe->abort_cmd.wqe_com, abtsiocb->iotag);
21564 	bf_set(wqe_cmnd, &abtswqe->abort_cmd.wqe_com, CMD_ABORT_XRI_CX);
21565 	bf_set(wqe_xri_tag, &abtswqe->generic.wqe_com, 0);
21566 	bf_set(wqe_qosd, &abtswqe->abort_cmd.wqe_com, 1);
21567 	bf_set(wqe_lenloc, &abtswqe->abort_cmd.wqe_com, LPFC_WQE_LENLOC_NONE);
21568 	bf_set(wqe_cmd_type, &abtswqe->abort_cmd.wqe_com, OTHER_COMMAND);
21569 
21570 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
21571 	abtsiocb->hba_wqidx = cmdiocb->hba_wqidx;
21572 	abtsiocb->cmd_flag |= LPFC_USE_FCPWQIDX;
21573 	if (cmdiocb->cmd_flag & LPFC_IO_FCP)
21574 		abtsiocb->cmd_flag |= LPFC_IO_FCP;
21575 	if (cmdiocb->cmd_flag & LPFC_IO_NVME)
21576 		abtsiocb->cmd_flag |= LPFC_IO_NVME;
21577 	if (cmdiocb->cmd_flag & LPFC_IO_FOF)
21578 		abtsiocb->cmd_flag |= LPFC_IO_FOF;
21579 	abtsiocb->vport = vport;
21580 	abtsiocb->cmd_cmpl = cmpl;
21581 
21582 	lpfc_cmd = container_of(cmdiocb, struct lpfc_io_buf, cur_iocbq);
21583 	retval = lpfc_sli4_issue_wqe(phba, lpfc_cmd->hdwq, abtsiocb);
21584 
21585 	lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
21586 			 "0359 Abort xri x%x, original iotag x%x, "
21587 			 "abort cmd iotag x%x retval x%x\n",
21588 			 xritag, cmdiocb->iotag, abtsiocb->iotag, retval);
21589 
21590 	if (retval) {
21591 		cmdiocb->cmd_flag &= ~LPFC_DRIVER_ABORTED;
21592 		__lpfc_sli_release_iocbq(phba, abtsiocb);
21593 	}
21594 
21595 	return retval;
21596 }
21597 
21598 #ifdef LPFC_MXP_STAT
21599 /**
21600  * lpfc_snapshot_mxp - Snapshot pbl, pvt and busy count
21601  * @phba: pointer to lpfc hba data structure.
21602  * @hwqid: belong to which HWQ.
21603  *
21604  * The purpose of this routine is to take a snapshot of pbl, pvt and busy count
21605  * 15 seconds after a test case is running.
21606  *
21607  * The user should call lpfc_debugfs_multixripools_write before running a test
21608  * case to clear stat_snapshot_taken. Then the user starts a test case. During
21609  * test case is running, stat_snapshot_taken is incremented by 1 every time when
21610  * this routine is called from heartbeat timer. When stat_snapshot_taken is
21611  * equal to LPFC_MXP_SNAPSHOT_TAKEN, a snapshot is taken.
21612  **/
21613 void lpfc_snapshot_mxp(struct lpfc_hba *phba, u32 hwqid)
21614 {
21615 	struct lpfc_sli4_hdw_queue *qp;
21616 	struct lpfc_multixri_pool *multixri_pool;
21617 	struct lpfc_pvt_pool *pvt_pool;
21618 	struct lpfc_pbl_pool *pbl_pool;
21619 	u32 txcmplq_cnt;
21620 
21621 	qp = &phba->sli4_hba.hdwq[hwqid];
21622 	multixri_pool = qp->p_multixri_pool;
21623 	if (!multixri_pool)
21624 		return;
21625 
21626 	if (multixri_pool->stat_snapshot_taken == LPFC_MXP_SNAPSHOT_TAKEN) {
21627 		pvt_pool = &qp->p_multixri_pool->pvt_pool;
21628 		pbl_pool = &qp->p_multixri_pool->pbl_pool;
21629 		txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21630 
21631 		multixri_pool->stat_pbl_count = pbl_pool->count;
21632 		multixri_pool->stat_pvt_count = pvt_pool->count;
21633 		multixri_pool->stat_busy_count = txcmplq_cnt;
21634 	}
21635 
21636 	multixri_pool->stat_snapshot_taken++;
21637 }
21638 #endif
21639 
21640 /**
21641  * lpfc_adjust_pvt_pool_count - Adjust private pool count
21642  * @phba: pointer to lpfc hba data structure.
21643  * @hwqid: belong to which HWQ.
21644  *
21645  * This routine moves some XRIs from private to public pool when private pool
21646  * is not busy.
21647  **/
21648 void lpfc_adjust_pvt_pool_count(struct lpfc_hba *phba, u32 hwqid)
21649 {
21650 	struct lpfc_multixri_pool *multixri_pool;
21651 	u32 io_req_count;
21652 	u32 prev_io_req_count;
21653 
21654 	multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
21655 	if (!multixri_pool)
21656 		return;
21657 	io_req_count = multixri_pool->io_req_count;
21658 	prev_io_req_count = multixri_pool->prev_io_req_count;
21659 
21660 	if (prev_io_req_count != io_req_count) {
21661 		/* Private pool is busy */
21662 		multixri_pool->prev_io_req_count = io_req_count;
21663 	} else {
21664 		/* Private pool is not busy.
21665 		 * Move XRIs from private to public pool.
21666 		 */
21667 		lpfc_move_xri_pvt_to_pbl(phba, hwqid);
21668 	}
21669 }
21670 
21671 /**
21672  * lpfc_adjust_high_watermark - Adjust high watermark
21673  * @phba: pointer to lpfc hba data structure.
21674  * @hwqid: belong to which HWQ.
21675  *
21676  * This routine sets high watermark as number of outstanding XRIs,
21677  * but make sure the new value is between xri_limit/2 and xri_limit.
21678  **/
21679 void lpfc_adjust_high_watermark(struct lpfc_hba *phba, u32 hwqid)
21680 {
21681 	u32 new_watermark;
21682 	u32 watermark_max;
21683 	u32 watermark_min;
21684 	u32 xri_limit;
21685 	u32 txcmplq_cnt;
21686 	u32 abts_io_bufs;
21687 	struct lpfc_multixri_pool *multixri_pool;
21688 	struct lpfc_sli4_hdw_queue *qp;
21689 
21690 	qp = &phba->sli4_hba.hdwq[hwqid];
21691 	multixri_pool = qp->p_multixri_pool;
21692 	if (!multixri_pool)
21693 		return;
21694 	xri_limit = multixri_pool->xri_limit;
21695 
21696 	watermark_max = xri_limit;
21697 	watermark_min = xri_limit / 2;
21698 
21699 	txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21700 	abts_io_bufs = qp->abts_scsi_io_bufs;
21701 	abts_io_bufs += qp->abts_nvme_io_bufs;
21702 
21703 	new_watermark = txcmplq_cnt + abts_io_bufs;
21704 	new_watermark = min(watermark_max, new_watermark);
21705 	new_watermark = max(watermark_min, new_watermark);
21706 	multixri_pool->pvt_pool.high_watermark = new_watermark;
21707 
21708 #ifdef LPFC_MXP_STAT
21709 	multixri_pool->stat_max_hwm = max(multixri_pool->stat_max_hwm,
21710 					  new_watermark);
21711 #endif
21712 }
21713 
21714 /**
21715  * lpfc_move_xri_pvt_to_pbl - Move some XRIs from private to public pool
21716  * @phba: pointer to lpfc hba data structure.
21717  * @hwqid: belong to which HWQ.
21718  *
21719  * This routine is called from heartbeat timer when pvt_pool is idle.
21720  * All free XRIs are moved from private to public pool on hwqid with 2 steps.
21721  * The first step moves (all - low_watermark) amount of XRIs.
21722  * The second step moves the rest of XRIs.
21723  **/
21724 void lpfc_move_xri_pvt_to_pbl(struct lpfc_hba *phba, u32 hwqid)
21725 {
21726 	struct lpfc_pbl_pool *pbl_pool;
21727 	struct lpfc_pvt_pool *pvt_pool;
21728 	struct lpfc_sli4_hdw_queue *qp;
21729 	struct lpfc_io_buf *lpfc_ncmd;
21730 	struct lpfc_io_buf *lpfc_ncmd_next;
21731 	unsigned long iflag;
21732 	struct list_head tmp_list;
21733 	u32 tmp_count;
21734 
21735 	qp = &phba->sli4_hba.hdwq[hwqid];
21736 	pbl_pool = &qp->p_multixri_pool->pbl_pool;
21737 	pvt_pool = &qp->p_multixri_pool->pvt_pool;
21738 	tmp_count = 0;
21739 
21740 	lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag, qp, mv_to_pub_pool);
21741 	lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_from_pvt_pool);
21742 
21743 	if (pvt_pool->count > pvt_pool->low_watermark) {
21744 		/* Step 1: move (all - low_watermark) from pvt_pool
21745 		 * to pbl_pool
21746 		 */
21747 
21748 		/* Move low watermark of bufs from pvt_pool to tmp_list */
21749 		INIT_LIST_HEAD(&tmp_list);
21750 		list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
21751 					 &pvt_pool->list, list) {
21752 			list_move_tail(&lpfc_ncmd->list, &tmp_list);
21753 			tmp_count++;
21754 			if (tmp_count >= pvt_pool->low_watermark)
21755 				break;
21756 		}
21757 
21758 		/* Move all bufs from pvt_pool to pbl_pool */
21759 		list_splice_init(&pvt_pool->list, &pbl_pool->list);
21760 
21761 		/* Move all bufs from tmp_list to pvt_pool */
21762 		list_splice(&tmp_list, &pvt_pool->list);
21763 
21764 		pbl_pool->count += (pvt_pool->count - tmp_count);
21765 		pvt_pool->count = tmp_count;
21766 	} else {
21767 		/* Step 2: move the rest from pvt_pool to pbl_pool */
21768 		list_splice_init(&pvt_pool->list, &pbl_pool->list);
21769 		pbl_pool->count += pvt_pool->count;
21770 		pvt_pool->count = 0;
21771 	}
21772 
21773 	spin_unlock(&pvt_pool->lock);
21774 	spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21775 }
21776 
21777 /**
21778  * _lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
21779  * @phba: pointer to lpfc hba data structure
21780  * @qp: pointer to HDW queue
21781  * @pbl_pool: specified public free XRI pool
21782  * @pvt_pool: specified private free XRI pool
21783  * @count: number of XRIs to move
21784  *
21785  * This routine tries to move some free common bufs from the specified pbl_pool
21786  * to the specified pvt_pool. It might move less than count XRIs if there's not
21787  * enough in public pool.
21788  *
21789  * Return:
21790  *   true - if XRIs are successfully moved from the specified pbl_pool to the
21791  *          specified pvt_pool
21792  *   false - if the specified pbl_pool is empty or locked by someone else
21793  **/
21794 static bool
21795 _lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
21796 			  struct lpfc_pbl_pool *pbl_pool,
21797 			  struct lpfc_pvt_pool *pvt_pool, u32 count)
21798 {
21799 	struct lpfc_io_buf *lpfc_ncmd;
21800 	struct lpfc_io_buf *lpfc_ncmd_next;
21801 	unsigned long iflag;
21802 	int ret;
21803 
21804 	ret = spin_trylock_irqsave(&pbl_pool->lock, iflag);
21805 	if (ret) {
21806 		if (pbl_pool->count) {
21807 			/* Move a batch of XRIs from public to private pool */
21808 			lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_to_pvt_pool);
21809 			list_for_each_entry_safe(lpfc_ncmd,
21810 						 lpfc_ncmd_next,
21811 						 &pbl_pool->list,
21812 						 list) {
21813 				list_move_tail(&lpfc_ncmd->list,
21814 					       &pvt_pool->list);
21815 				pvt_pool->count++;
21816 				pbl_pool->count--;
21817 				count--;
21818 				if (count == 0)
21819 					break;
21820 			}
21821 
21822 			spin_unlock(&pvt_pool->lock);
21823 			spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21824 			return true;
21825 		}
21826 		spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21827 	}
21828 
21829 	return false;
21830 }
21831 
21832 /**
21833  * lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
21834  * @phba: pointer to lpfc hba data structure.
21835  * @hwqid: belong to which HWQ.
21836  * @count: number of XRIs to move
21837  *
21838  * This routine tries to find some free common bufs in one of public pools with
21839  * Round Robin method. The search always starts from local hwqid, then the next
21840  * HWQ which was found last time (rrb_next_hwqid). Once a public pool is found,
21841  * a batch of free common bufs are moved to private pool on hwqid.
21842  * It might move less than count XRIs if there's not enough in public pool.
21843  **/
21844 void lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, u32 hwqid, u32 count)
21845 {
21846 	struct lpfc_multixri_pool *multixri_pool;
21847 	struct lpfc_multixri_pool *next_multixri_pool;
21848 	struct lpfc_pvt_pool *pvt_pool;
21849 	struct lpfc_pbl_pool *pbl_pool;
21850 	struct lpfc_sli4_hdw_queue *qp;
21851 	u32 next_hwqid;
21852 	u32 hwq_count;
21853 	int ret;
21854 
21855 	qp = &phba->sli4_hba.hdwq[hwqid];
21856 	multixri_pool = qp->p_multixri_pool;
21857 	pvt_pool = &multixri_pool->pvt_pool;
21858 	pbl_pool = &multixri_pool->pbl_pool;
21859 
21860 	/* Check if local pbl_pool is available */
21861 	ret = _lpfc_move_xri_pbl_to_pvt(phba, qp, pbl_pool, pvt_pool, count);
21862 	if (ret) {
21863 #ifdef LPFC_MXP_STAT
21864 		multixri_pool->local_pbl_hit_count++;
21865 #endif
21866 		return;
21867 	}
21868 
21869 	hwq_count = phba->cfg_hdw_queue;
21870 
21871 	/* Get the next hwqid which was found last time */
21872 	next_hwqid = multixri_pool->rrb_next_hwqid;
21873 
21874 	do {
21875 		/* Go to next hwq */
21876 		next_hwqid = (next_hwqid + 1) % hwq_count;
21877 
21878 		next_multixri_pool =
21879 			phba->sli4_hba.hdwq[next_hwqid].p_multixri_pool;
21880 		pbl_pool = &next_multixri_pool->pbl_pool;
21881 
21882 		/* Check if the public free xri pool is available */
21883 		ret = _lpfc_move_xri_pbl_to_pvt(
21884 			phba, qp, pbl_pool, pvt_pool, count);
21885 
21886 		/* Exit while-loop if success or all hwqid are checked */
21887 	} while (!ret && next_hwqid != multixri_pool->rrb_next_hwqid);
21888 
21889 	/* Starting point for the next time */
21890 	multixri_pool->rrb_next_hwqid = next_hwqid;
21891 
21892 	if (!ret) {
21893 		/* stats: all public pools are empty*/
21894 		multixri_pool->pbl_empty_count++;
21895 	}
21896 
21897 #ifdef LPFC_MXP_STAT
21898 	if (ret) {
21899 		if (next_hwqid == hwqid)
21900 			multixri_pool->local_pbl_hit_count++;
21901 		else
21902 			multixri_pool->other_pbl_hit_count++;
21903 	}
21904 #endif
21905 }
21906 
21907 /**
21908  * lpfc_keep_pvt_pool_above_lowwm - Keep pvt_pool above low watermark
21909  * @phba: pointer to lpfc hba data structure.
21910  * @hwqid: belong to which HWQ.
21911  *
21912  * This routine get a batch of XRIs from pbl_pool if pvt_pool is less than
21913  * low watermark.
21914  **/
21915 void lpfc_keep_pvt_pool_above_lowwm(struct lpfc_hba *phba, u32 hwqid)
21916 {
21917 	struct lpfc_multixri_pool *multixri_pool;
21918 	struct lpfc_pvt_pool *pvt_pool;
21919 
21920 	multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
21921 	pvt_pool = &multixri_pool->pvt_pool;
21922 
21923 	if (pvt_pool->count < pvt_pool->low_watermark)
21924 		lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
21925 }
21926 
21927 /**
21928  * lpfc_release_io_buf - Return one IO buf back to free pool
21929  * @phba: pointer to lpfc hba data structure.
21930  * @lpfc_ncmd: IO buf to be returned.
21931  * @qp: belong to which HWQ.
21932  *
21933  * This routine returns one IO buf back to free pool. If this is an urgent IO,
21934  * the IO buf is returned to expedite pool. If cfg_xri_rebalancing==1,
21935  * the IO buf is returned to pbl_pool or pvt_pool based on watermark and
21936  * xri_limit.  If cfg_xri_rebalancing==0, the IO buf is returned to
21937  * lpfc_io_buf_list_put.
21938  **/
21939 void lpfc_release_io_buf(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_ncmd,
21940 			 struct lpfc_sli4_hdw_queue *qp)
21941 {
21942 	unsigned long iflag;
21943 	struct lpfc_pbl_pool *pbl_pool;
21944 	struct lpfc_pvt_pool *pvt_pool;
21945 	struct lpfc_epd_pool *epd_pool;
21946 	u32 txcmplq_cnt;
21947 	u32 xri_owned;
21948 	u32 xri_limit;
21949 	u32 abts_io_bufs;
21950 
21951 	/* MUST zero fields if buffer is reused by another protocol */
21952 	lpfc_ncmd->nvmeCmd = NULL;
21953 	lpfc_ncmd->cur_iocbq.cmd_cmpl = NULL;
21954 
21955 	if (phba->cfg_xpsgl && !phba->nvmet_support &&
21956 	    !list_empty(&lpfc_ncmd->dma_sgl_xtra_list))
21957 		lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
21958 
21959 	if (!list_empty(&lpfc_ncmd->dma_cmd_rsp_list))
21960 		lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
21961 
21962 	if (phba->cfg_xri_rebalancing) {
21963 		if (lpfc_ncmd->expedite) {
21964 			/* Return to expedite pool */
21965 			epd_pool = &phba->epd_pool;
21966 			spin_lock_irqsave(&epd_pool->lock, iflag);
21967 			list_add_tail(&lpfc_ncmd->list, &epd_pool->list);
21968 			epd_pool->count++;
21969 			spin_unlock_irqrestore(&epd_pool->lock, iflag);
21970 			return;
21971 		}
21972 
21973 		/* Avoid invalid access if an IO sneaks in and is being rejected
21974 		 * just _after_ xri pools are destroyed in lpfc_offline.
21975 		 * Nothing much can be done at this point.
21976 		 */
21977 		if (!qp->p_multixri_pool)
21978 			return;
21979 
21980 		pbl_pool = &qp->p_multixri_pool->pbl_pool;
21981 		pvt_pool = &qp->p_multixri_pool->pvt_pool;
21982 
21983 		txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21984 		abts_io_bufs = qp->abts_scsi_io_bufs;
21985 		abts_io_bufs += qp->abts_nvme_io_bufs;
21986 
21987 		xri_owned = pvt_pool->count + txcmplq_cnt + abts_io_bufs;
21988 		xri_limit = qp->p_multixri_pool->xri_limit;
21989 
21990 #ifdef LPFC_MXP_STAT
21991 		if (xri_owned <= xri_limit)
21992 			qp->p_multixri_pool->below_limit_count++;
21993 		else
21994 			qp->p_multixri_pool->above_limit_count++;
21995 #endif
21996 
21997 		/* XRI goes to either public or private free xri pool
21998 		 *     based on watermark and xri_limit
21999 		 */
22000 		if ((pvt_pool->count < pvt_pool->low_watermark) ||
22001 		    (xri_owned < xri_limit &&
22002 		     pvt_pool->count < pvt_pool->high_watermark)) {
22003 			lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag,
22004 						  qp, free_pvt_pool);
22005 			list_add_tail(&lpfc_ncmd->list,
22006 				      &pvt_pool->list);
22007 			pvt_pool->count++;
22008 			spin_unlock_irqrestore(&pvt_pool->lock, iflag);
22009 		} else {
22010 			lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag,
22011 						  qp, free_pub_pool);
22012 			list_add_tail(&lpfc_ncmd->list,
22013 				      &pbl_pool->list);
22014 			pbl_pool->count++;
22015 			spin_unlock_irqrestore(&pbl_pool->lock, iflag);
22016 		}
22017 	} else {
22018 		lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag,
22019 					  qp, free_xri);
22020 		list_add_tail(&lpfc_ncmd->list,
22021 			      &qp->lpfc_io_buf_list_put);
22022 		qp->put_io_bufs++;
22023 		spin_unlock_irqrestore(&qp->io_buf_list_put_lock,
22024 				       iflag);
22025 	}
22026 }
22027 
22028 /**
22029  * lpfc_get_io_buf_from_private_pool - Get one free IO buf from private pool
22030  * @phba: pointer to lpfc hba data structure.
22031  * @qp: pointer to HDW queue
22032  * @pvt_pool: pointer to private pool data structure.
22033  * @ndlp: pointer to lpfc nodelist data structure.
22034  *
22035  * This routine tries to get one free IO buf from private pool.
22036  *
22037  * Return:
22038  *   pointer to one free IO buf - if private pool is not empty
22039  *   NULL - if private pool is empty
22040  **/
22041 static struct lpfc_io_buf *
22042 lpfc_get_io_buf_from_private_pool(struct lpfc_hba *phba,
22043 				  struct lpfc_sli4_hdw_queue *qp,
22044 				  struct lpfc_pvt_pool *pvt_pool,
22045 				  struct lpfc_nodelist *ndlp)
22046 {
22047 	struct lpfc_io_buf *lpfc_ncmd;
22048 	struct lpfc_io_buf *lpfc_ncmd_next;
22049 	unsigned long iflag;
22050 
22051 	lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag, qp, alloc_pvt_pool);
22052 	list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
22053 				 &pvt_pool->list, list) {
22054 		if (lpfc_test_rrq_active(
22055 			phba, ndlp, lpfc_ncmd->cur_iocbq.sli4_lxritag))
22056 			continue;
22057 		list_del(&lpfc_ncmd->list);
22058 		pvt_pool->count--;
22059 		spin_unlock_irqrestore(&pvt_pool->lock, iflag);
22060 		return lpfc_ncmd;
22061 	}
22062 	spin_unlock_irqrestore(&pvt_pool->lock, iflag);
22063 
22064 	return NULL;
22065 }
22066 
22067 /**
22068  * lpfc_get_io_buf_from_expedite_pool - Get one free IO buf from expedite pool
22069  * @phba: pointer to lpfc hba data structure.
22070  *
22071  * This routine tries to get one free IO buf from expedite pool.
22072  *
22073  * Return:
22074  *   pointer to one free IO buf - if expedite pool is not empty
22075  *   NULL - if expedite pool is empty
22076  **/
22077 static struct lpfc_io_buf *
22078 lpfc_get_io_buf_from_expedite_pool(struct lpfc_hba *phba)
22079 {
22080 	struct lpfc_io_buf *lpfc_ncmd = NULL, *iter;
22081 	struct lpfc_io_buf *lpfc_ncmd_next;
22082 	unsigned long iflag;
22083 	struct lpfc_epd_pool *epd_pool;
22084 
22085 	epd_pool = &phba->epd_pool;
22086 
22087 	spin_lock_irqsave(&epd_pool->lock, iflag);
22088 	if (epd_pool->count > 0) {
22089 		list_for_each_entry_safe(iter, lpfc_ncmd_next,
22090 					 &epd_pool->list, list) {
22091 			list_del(&iter->list);
22092 			epd_pool->count--;
22093 			lpfc_ncmd = iter;
22094 			break;
22095 		}
22096 	}
22097 	spin_unlock_irqrestore(&epd_pool->lock, iflag);
22098 
22099 	return lpfc_ncmd;
22100 }
22101 
22102 /**
22103  * lpfc_get_io_buf_from_multixri_pools - Get one free IO bufs
22104  * @phba: pointer to lpfc hba data structure.
22105  * @ndlp: pointer to lpfc nodelist data structure.
22106  * @hwqid: belong to which HWQ
22107  * @expedite: 1 means this request is urgent.
22108  *
22109  * This routine will do the following actions and then return a pointer to
22110  * one free IO buf.
22111  *
22112  * 1. If private free xri count is empty, move some XRIs from public to
22113  *    private pool.
22114  * 2. Get one XRI from private free xri pool.
22115  * 3. If we fail to get one from pvt_pool and this is an expedite request,
22116  *    get one free xri from expedite pool.
22117  *
22118  * Note: ndlp is only used on SCSI side for RRQ testing.
22119  *       The caller should pass NULL for ndlp on NVME side.
22120  *
22121  * Return:
22122  *   pointer to one free IO buf - if private pool is not empty
22123  *   NULL - if private pool is empty
22124  **/
22125 static struct lpfc_io_buf *
22126 lpfc_get_io_buf_from_multixri_pools(struct lpfc_hba *phba,
22127 				    struct lpfc_nodelist *ndlp,
22128 				    int hwqid, int expedite)
22129 {
22130 	struct lpfc_sli4_hdw_queue *qp;
22131 	struct lpfc_multixri_pool *multixri_pool;
22132 	struct lpfc_pvt_pool *pvt_pool;
22133 	struct lpfc_io_buf *lpfc_ncmd;
22134 
22135 	qp = &phba->sli4_hba.hdwq[hwqid];
22136 	lpfc_ncmd = NULL;
22137 	if (!qp) {
22138 		lpfc_printf_log(phba, KERN_INFO,
22139 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
22140 				"5556 NULL qp for hwqid  x%x\n", hwqid);
22141 		return lpfc_ncmd;
22142 	}
22143 	multixri_pool = qp->p_multixri_pool;
22144 	if (!multixri_pool) {
22145 		lpfc_printf_log(phba, KERN_INFO,
22146 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
22147 				"5557 NULL multixri for hwqid  x%x\n", hwqid);
22148 		return lpfc_ncmd;
22149 	}
22150 	pvt_pool = &multixri_pool->pvt_pool;
22151 	if (!pvt_pool) {
22152 		lpfc_printf_log(phba, KERN_INFO,
22153 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
22154 				"5558 NULL pvt_pool for hwqid  x%x\n", hwqid);
22155 		return lpfc_ncmd;
22156 	}
22157 	multixri_pool->io_req_count++;
22158 
22159 	/* If pvt_pool is empty, move some XRIs from public to private pool */
22160 	if (pvt_pool->count == 0)
22161 		lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
22162 
22163 	/* Get one XRI from private free xri pool */
22164 	lpfc_ncmd = lpfc_get_io_buf_from_private_pool(phba, qp, pvt_pool, ndlp);
22165 
22166 	if (lpfc_ncmd) {
22167 		lpfc_ncmd->hdwq = qp;
22168 		lpfc_ncmd->hdwq_no = hwqid;
22169 	} else if (expedite) {
22170 		/* If we fail to get one from pvt_pool and this is an expedite
22171 		 * request, get one free xri from expedite pool.
22172 		 */
22173 		lpfc_ncmd = lpfc_get_io_buf_from_expedite_pool(phba);
22174 	}
22175 
22176 	return lpfc_ncmd;
22177 }
22178 
22179 static inline struct lpfc_io_buf *
22180 lpfc_io_buf(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp, int idx)
22181 {
22182 	struct lpfc_sli4_hdw_queue *qp;
22183 	struct lpfc_io_buf *lpfc_cmd, *lpfc_cmd_next;
22184 
22185 	qp = &phba->sli4_hba.hdwq[idx];
22186 	list_for_each_entry_safe(lpfc_cmd, lpfc_cmd_next,
22187 				 &qp->lpfc_io_buf_list_get, list) {
22188 		if (lpfc_test_rrq_active(phba, ndlp,
22189 					 lpfc_cmd->cur_iocbq.sli4_lxritag))
22190 			continue;
22191 
22192 		if (lpfc_cmd->flags & LPFC_SBUF_NOT_POSTED)
22193 			continue;
22194 
22195 		list_del_init(&lpfc_cmd->list);
22196 		qp->get_io_bufs--;
22197 		lpfc_cmd->hdwq = qp;
22198 		lpfc_cmd->hdwq_no = idx;
22199 		return lpfc_cmd;
22200 	}
22201 	return NULL;
22202 }
22203 
22204 /**
22205  * lpfc_get_io_buf - Get one IO buffer from free pool
22206  * @phba: The HBA for which this call is being executed.
22207  * @ndlp: pointer to lpfc nodelist data structure.
22208  * @hwqid: belong to which HWQ
22209  * @expedite: 1 means this request is urgent.
22210  *
22211  * This routine gets one IO buffer from free pool. If cfg_xri_rebalancing==1,
22212  * removes a IO buffer from multiXRI pools. If cfg_xri_rebalancing==0, removes
22213  * a IO buffer from head of @hdwq io_buf_list and returns to caller.
22214  *
22215  * Note: ndlp is only used on SCSI side for RRQ testing.
22216  *       The caller should pass NULL for ndlp on NVME side.
22217  *
22218  * Return codes:
22219  *   NULL - Error
22220  *   Pointer to lpfc_io_buf - Success
22221  **/
22222 struct lpfc_io_buf *lpfc_get_io_buf(struct lpfc_hba *phba,
22223 				    struct lpfc_nodelist *ndlp,
22224 				    u32 hwqid, int expedite)
22225 {
22226 	struct lpfc_sli4_hdw_queue *qp;
22227 	unsigned long iflag;
22228 	struct lpfc_io_buf *lpfc_cmd;
22229 
22230 	qp = &phba->sli4_hba.hdwq[hwqid];
22231 	lpfc_cmd = NULL;
22232 	if (!qp) {
22233 		lpfc_printf_log(phba, KERN_WARNING,
22234 				LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
22235 				"5555 NULL qp for hwqid  x%x\n", hwqid);
22236 		return lpfc_cmd;
22237 	}
22238 
22239 	if (phba->cfg_xri_rebalancing)
22240 		lpfc_cmd = lpfc_get_io_buf_from_multixri_pools(
22241 			phba, ndlp, hwqid, expedite);
22242 	else {
22243 		lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_get_lock, iflag,
22244 					  qp, alloc_xri_get);
22245 		if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT || expedite)
22246 			lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
22247 		if (!lpfc_cmd) {
22248 			lpfc_qp_spin_lock(&qp->io_buf_list_put_lock,
22249 					  qp, alloc_xri_put);
22250 			list_splice(&qp->lpfc_io_buf_list_put,
22251 				    &qp->lpfc_io_buf_list_get);
22252 			qp->get_io_bufs += qp->put_io_bufs;
22253 			INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
22254 			qp->put_io_bufs = 0;
22255 			spin_unlock(&qp->io_buf_list_put_lock);
22256 			if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT ||
22257 			    expedite)
22258 				lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
22259 		}
22260 		spin_unlock_irqrestore(&qp->io_buf_list_get_lock, iflag);
22261 	}
22262 
22263 	return lpfc_cmd;
22264 }
22265 
22266 /**
22267  * lpfc_read_object - Retrieve object data from HBA
22268  * @phba: The HBA for which this call is being executed.
22269  * @rdobject: Pathname of object data we want to read.
22270  * @datap: Pointer to where data will be copied to.
22271  * @datasz: size of data area
22272  *
22273  * This routine is limited to object sizes of LPFC_BPL_SIZE (1024) or less.
22274  * The data will be truncated if datasz is not large enough.
22275  * Version 1 is not supported with Embedded mbox cmd, so we must use version 0.
22276  * Returns the actual bytes read from the object.
22277  *
22278  * This routine is hard coded to use a poll completion.  Unlike other
22279  * sli4_config mailboxes, it uses lpfc_mbuf memory which is not
22280  * cleaned up in lpfc_sli4_cmd_mbox_free.  If this routine is modified
22281  * to use interrupt-based completions, code is needed to fully cleanup
22282  * the memory.
22283  */
22284 int
22285 lpfc_read_object(struct lpfc_hba *phba, char *rdobject, uint32_t *datap,
22286 		 uint32_t datasz)
22287 {
22288 	struct lpfc_mbx_read_object *read_object;
22289 	LPFC_MBOXQ_t *mbox;
22290 	int rc, length, eof, j, byte_cnt = 0;
22291 	uint32_t shdr_status, shdr_add_status;
22292 	union lpfc_sli4_cfg_shdr *shdr;
22293 	struct lpfc_dmabuf *pcmd;
22294 	u32 rd_object_name[LPFC_MBX_OBJECT_NAME_LEN_DW] = {0};
22295 
22296 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
22297 	if (!mbox)
22298 		return -ENOMEM;
22299 	length = (sizeof(struct lpfc_mbx_read_object) -
22300 		  sizeof(struct lpfc_sli4_cfg_mhdr));
22301 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
22302 			 LPFC_MBOX_OPCODE_READ_OBJECT,
22303 			 length, LPFC_SLI4_MBX_EMBED);
22304 	read_object = &mbox->u.mqe.un.read_object;
22305 	shdr = (union lpfc_sli4_cfg_shdr *)&read_object->header.cfg_shdr;
22306 
22307 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_Q_CREATE_VERSION_0);
22308 	bf_set(lpfc_mbx_rd_object_rlen, &read_object->u.request, datasz);
22309 	read_object->u.request.rd_object_offset = 0;
22310 	read_object->u.request.rd_object_cnt = 1;
22311 
22312 	memset((void *)read_object->u.request.rd_object_name, 0,
22313 	       LPFC_OBJ_NAME_SZ);
22314 	scnprintf((char *)rd_object_name, sizeof(rd_object_name), rdobject);
22315 	for (j = 0; j < strlen(rdobject); j++)
22316 		read_object->u.request.rd_object_name[j] =
22317 			cpu_to_le32(rd_object_name[j]);
22318 
22319 	pcmd = kmalloc_obj(*pcmd);
22320 	if (pcmd)
22321 		pcmd->virt = lpfc_mbuf_alloc(phba, MEM_PRI, &pcmd->phys);
22322 	if (!pcmd || !pcmd->virt) {
22323 		kfree(pcmd);
22324 		mempool_free(mbox, phba->mbox_mem_pool);
22325 		return -ENOMEM;
22326 	}
22327 	memset((void *)pcmd->virt, 0, LPFC_BPL_SIZE);
22328 	read_object->u.request.rd_object_hbuf[0].pa_lo =
22329 		putPaddrLow(pcmd->phys);
22330 	read_object->u.request.rd_object_hbuf[0].pa_hi =
22331 		putPaddrHigh(pcmd->phys);
22332 	read_object->u.request.rd_object_hbuf[0].length = LPFC_BPL_SIZE;
22333 
22334 	mbox->vport = phba->pport;
22335 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
22336 	mbox->ctx_ndlp = NULL;
22337 
22338 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
22339 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
22340 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
22341 
22342 	if (shdr_status == STATUS_FAILED &&
22343 	    shdr_add_status == ADD_STATUS_INVALID_OBJECT_NAME) {
22344 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_CGN_MGMT,
22345 				"4674 No port cfg file in FW.\n");
22346 		byte_cnt = -ENOENT;
22347 	} else if (shdr_status || shdr_add_status || rc) {
22348 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_CGN_MGMT,
22349 				"2625 READ_OBJECT mailbox failed with "
22350 				"status x%x add_status x%x, mbx status x%x\n",
22351 				shdr_status, shdr_add_status, rc);
22352 		byte_cnt = -ENXIO;
22353 	} else {
22354 		/* Success */
22355 		length = read_object->u.response.rd_object_actual_rlen;
22356 		eof = bf_get(lpfc_mbx_rd_object_eof, &read_object->u.response);
22357 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_CGN_MGMT,
22358 				"2626 READ_OBJECT Success len %d:%d, EOF %d\n",
22359 				length, datasz, eof);
22360 
22361 		/* Detect the port config file exists but is empty */
22362 		if (!length && eof) {
22363 			byte_cnt = 0;
22364 			goto exit;
22365 		}
22366 
22367 		byte_cnt = length;
22368 		lpfc_sli_pcimem_bcopy(pcmd->virt, datap, byte_cnt);
22369 	}
22370 
22371  exit:
22372 	/* This is an embedded SLI4 mailbox with an external buffer allocated.
22373 	 * Free the pcmd and then cleanup with the correct routine.
22374 	 */
22375 	lpfc_mbuf_free(phba, pcmd->virt, pcmd->phys);
22376 	kfree(pcmd);
22377 	lpfc_sli4_mbox_cmd_free(phba, mbox);
22378 	return byte_cnt;
22379 }
22380 
22381 /**
22382  * lpfc_get_sgl_per_hdwq - Get one SGL chunk from hdwq's pool
22383  * @phba: The HBA for which this call is being executed.
22384  * @lpfc_buf: IO buf structure to append the SGL chunk
22385  *
22386  * This routine gets one SGL chunk buffer from hdwq's SGL chunk pool,
22387  * and will allocate an SGL chunk if the pool is empty.
22388  *
22389  * Return codes:
22390  *   NULL - Error
22391  *   Pointer to sli4_hybrid_sgl - Success
22392  **/
22393 struct sli4_hybrid_sgl *
22394 lpfc_get_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
22395 {
22396 	struct sli4_hybrid_sgl *list_entry = NULL;
22397 	struct sli4_hybrid_sgl *tmp = NULL;
22398 	struct sli4_hybrid_sgl *allocated_sgl = NULL;
22399 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22400 	struct list_head *buf_list = &hdwq->sgl_list;
22401 	unsigned long iflags;
22402 
22403 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22404 
22405 	if (likely(!list_empty(buf_list))) {
22406 		/* break off 1 chunk from the sgl_list */
22407 		list_for_each_entry_safe(list_entry, tmp,
22408 					 buf_list, list_node) {
22409 			list_move_tail(&list_entry->list_node,
22410 				       &lpfc_buf->dma_sgl_xtra_list);
22411 			break;
22412 		}
22413 	} else {
22414 		/* allocate more */
22415 		spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22416 		tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
22417 				   cpu_to_node(hdwq->io_wq->chann));
22418 		if (!tmp) {
22419 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22420 					"8353 error kmalloc memory for HDWQ "
22421 					"%d %s\n",
22422 					lpfc_buf->hdwq_no, __func__);
22423 			return NULL;
22424 		}
22425 
22426 		tmp->dma_sgl = dma_pool_alloc(phba->lpfc_sg_dma_buf_pool,
22427 					      GFP_ATOMIC, &tmp->dma_phys_sgl);
22428 		if (!tmp->dma_sgl) {
22429 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22430 					"8354 error pool_alloc memory for HDWQ "
22431 					"%d %s\n",
22432 					lpfc_buf->hdwq_no, __func__);
22433 			kfree(tmp);
22434 			return NULL;
22435 		}
22436 
22437 		spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22438 		list_add_tail(&tmp->list_node, &lpfc_buf->dma_sgl_xtra_list);
22439 	}
22440 
22441 	allocated_sgl = list_last_entry(&lpfc_buf->dma_sgl_xtra_list,
22442 					struct sli4_hybrid_sgl,
22443 					list_node);
22444 
22445 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22446 
22447 	return allocated_sgl;
22448 }
22449 
22450 /**
22451  * lpfc_put_sgl_per_hdwq - Put one SGL chunk into hdwq pool
22452  * @phba: The HBA for which this call is being executed.
22453  * @lpfc_buf: IO buf structure with the SGL chunk
22454  *
22455  * This routine puts one SGL chunk buffer into hdwq's SGL chunk pool.
22456  *
22457  * Return codes:
22458  *   0 - Success
22459  *   -EINVAL - Error
22460  **/
22461 int
22462 lpfc_put_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
22463 {
22464 	int rc = 0;
22465 	struct sli4_hybrid_sgl *list_entry = NULL;
22466 	struct sli4_hybrid_sgl *tmp = NULL;
22467 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22468 	struct list_head *buf_list = &hdwq->sgl_list;
22469 	unsigned long iflags;
22470 
22471 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22472 
22473 	if (likely(!list_empty(&lpfc_buf->dma_sgl_xtra_list))) {
22474 		list_for_each_entry_safe(list_entry, tmp,
22475 					 &lpfc_buf->dma_sgl_xtra_list,
22476 					 list_node) {
22477 			list_move_tail(&list_entry->list_node,
22478 				       buf_list);
22479 		}
22480 	} else {
22481 		rc = -EINVAL;
22482 	}
22483 
22484 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22485 	return rc;
22486 }
22487 
22488 /**
22489  * lpfc_free_sgl_per_hdwq - Free all SGL chunks of hdwq pool
22490  * @phba: phba object
22491  * @hdwq: hdwq to cleanup sgl buff resources on
22492  *
22493  * This routine frees all SGL chunks of hdwq SGL chunk pool.
22494  *
22495  * Return codes:
22496  *   None
22497  **/
22498 void
22499 lpfc_free_sgl_per_hdwq(struct lpfc_hba *phba,
22500 		       struct lpfc_sli4_hdw_queue *hdwq)
22501 {
22502 	struct list_head *buf_list = &hdwq->sgl_list;
22503 	struct sli4_hybrid_sgl *list_entry = NULL;
22504 	struct sli4_hybrid_sgl *tmp = NULL;
22505 	unsigned long iflags;
22506 
22507 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22508 
22509 	/* Free sgl pool */
22510 	list_for_each_entry_safe(list_entry, tmp,
22511 				 buf_list, list_node) {
22512 		list_del(&list_entry->list_node);
22513 		dma_pool_free(phba->lpfc_sg_dma_buf_pool,
22514 			      list_entry->dma_sgl,
22515 			      list_entry->dma_phys_sgl);
22516 		kfree(list_entry);
22517 	}
22518 
22519 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22520 }
22521 
22522 /**
22523  * lpfc_get_cmd_rsp_buf_per_hdwq - Get one CMD/RSP buffer from hdwq
22524  * @phba: The HBA for which this call is being executed.
22525  * @lpfc_buf: IO buf structure to attach the CMD/RSP buffer
22526  *
22527  * This routine gets one CMD/RSP buffer from hdwq's CMD/RSP pool,
22528  * and will allocate an CMD/RSP buffer if the pool is empty.
22529  *
22530  * Return codes:
22531  *   NULL - Error
22532  *   Pointer to fcp_cmd_rsp_buf - Success
22533  **/
22534 struct fcp_cmd_rsp_buf *
22535 lpfc_get_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
22536 			      struct lpfc_io_buf *lpfc_buf)
22537 {
22538 	struct fcp_cmd_rsp_buf *list_entry = NULL;
22539 	struct fcp_cmd_rsp_buf *tmp = NULL;
22540 	struct fcp_cmd_rsp_buf *allocated_buf = NULL;
22541 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22542 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
22543 	unsigned long iflags;
22544 
22545 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22546 
22547 	if (likely(!list_empty(buf_list))) {
22548 		/* break off 1 chunk from the list */
22549 		list_for_each_entry_safe(list_entry, tmp,
22550 					 buf_list,
22551 					 list_node) {
22552 			list_move_tail(&list_entry->list_node,
22553 				       &lpfc_buf->dma_cmd_rsp_list);
22554 			break;
22555 		}
22556 	} else {
22557 		/* allocate more */
22558 		spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22559 		tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
22560 				   cpu_to_node(hdwq->io_wq->chann));
22561 		if (!tmp) {
22562 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22563 					"8355 error kmalloc memory for HDWQ "
22564 					"%d %s\n",
22565 					lpfc_buf->hdwq_no, __func__);
22566 			return NULL;
22567 		}
22568 
22569 		tmp->fcp_cmnd = dma_pool_zalloc(phba->lpfc_cmd_rsp_buf_pool,
22570 						GFP_ATOMIC,
22571 						&tmp->fcp_cmd_rsp_dma_handle);
22572 
22573 		if (!tmp->fcp_cmnd) {
22574 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22575 					"8356 error pool_alloc memory for HDWQ "
22576 					"%d %s\n",
22577 					lpfc_buf->hdwq_no, __func__);
22578 			kfree(tmp);
22579 			return NULL;
22580 		}
22581 
22582 		tmp->fcp_rsp = (struct fcp_rsp *)((uint8_t *)tmp->fcp_cmnd +
22583 				sizeof(struct fcp_cmnd32));
22584 
22585 		spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22586 		list_add_tail(&tmp->list_node, &lpfc_buf->dma_cmd_rsp_list);
22587 	}
22588 
22589 	allocated_buf = list_last_entry(&lpfc_buf->dma_cmd_rsp_list,
22590 					struct fcp_cmd_rsp_buf,
22591 					list_node);
22592 
22593 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22594 
22595 	return allocated_buf;
22596 }
22597 
22598 /**
22599  * lpfc_put_cmd_rsp_buf_per_hdwq - Put one CMD/RSP buffer into hdwq pool
22600  * @phba: The HBA for which this call is being executed.
22601  * @lpfc_buf: IO buf structure with the CMD/RSP buf
22602  *
22603  * This routine puts one CMD/RSP buffer into executing CPU's CMD/RSP pool.
22604  *
22605  * Return codes:
22606  *   0 - Success
22607  *   -EINVAL - Error
22608  **/
22609 int
22610 lpfc_put_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
22611 			      struct lpfc_io_buf *lpfc_buf)
22612 {
22613 	int rc = 0;
22614 	struct fcp_cmd_rsp_buf *list_entry = NULL;
22615 	struct fcp_cmd_rsp_buf *tmp = NULL;
22616 	struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22617 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
22618 	unsigned long iflags;
22619 
22620 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22621 
22622 	if (likely(!list_empty(&lpfc_buf->dma_cmd_rsp_list))) {
22623 		list_for_each_entry_safe(list_entry, tmp,
22624 					 &lpfc_buf->dma_cmd_rsp_list,
22625 					 list_node) {
22626 			list_move_tail(&list_entry->list_node,
22627 				       buf_list);
22628 		}
22629 	} else {
22630 		rc = -EINVAL;
22631 	}
22632 
22633 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22634 	return rc;
22635 }
22636 
22637 /**
22638  * lpfc_free_cmd_rsp_buf_per_hdwq - Free all CMD/RSP chunks of hdwq pool
22639  * @phba: phba object
22640  * @hdwq: hdwq to cleanup cmd rsp buff resources on
22641  *
22642  * This routine frees all CMD/RSP buffers of hdwq's CMD/RSP buf pool.
22643  *
22644  * Return codes:
22645  *   None
22646  **/
22647 void
22648 lpfc_free_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
22649 			       struct lpfc_sli4_hdw_queue *hdwq)
22650 {
22651 	struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
22652 	struct fcp_cmd_rsp_buf *list_entry = NULL;
22653 	struct fcp_cmd_rsp_buf *tmp = NULL;
22654 	unsigned long iflags;
22655 
22656 	spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22657 
22658 	/* Free cmd_rsp buf pool */
22659 	list_for_each_entry_safe(list_entry, tmp,
22660 				 buf_list,
22661 				 list_node) {
22662 		list_del(&list_entry->list_node);
22663 		dma_pool_free(phba->lpfc_cmd_rsp_buf_pool,
22664 			      list_entry->fcp_cmnd,
22665 			      list_entry->fcp_cmd_rsp_dma_handle);
22666 		kfree(list_entry);
22667 	}
22668 
22669 	spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22670 }
22671 
22672 /**
22673  * lpfc_sli_prep_wqe - Prepare WQE for the command to be posted
22674  * @phba: phba object
22675  * @job: job entry of the command to be posted.
22676  *
22677  * Fill the common fields of the wqe for each of the command.
22678  *
22679  * Return codes:
22680  *	None
22681  **/
22682 void
22683 lpfc_sli_prep_wqe(struct lpfc_hba *phba, struct lpfc_iocbq *job)
22684 {
22685 	u8 cmnd;
22686 	u32 *pcmd;
22687 	u32 if_type = 0;
22688 	u32 abort_tag;
22689 	bool fip;
22690 	struct lpfc_nodelist *ndlp = NULL;
22691 	union lpfc_wqe128 *wqe = &job->wqe;
22692 	u8 command_type = ELS_COMMAND_NON_FIP;
22693 
22694 	fip = test_bit(HBA_FIP_SUPPORT, &phba->hba_flag);
22695 	/* The fcp commands will set command type */
22696 	if (job->cmd_flag &  LPFC_IO_FCP)
22697 		command_type = FCP_COMMAND;
22698 	else if (fip && (job->cmd_flag & LPFC_FIP_ELS_ID_MASK))
22699 		command_type = ELS_COMMAND_FIP;
22700 	else
22701 		command_type = ELS_COMMAND_NON_FIP;
22702 
22703 	abort_tag = job->iotag;
22704 	cmnd = bf_get(wqe_cmnd, &wqe->els_req.wqe_com);
22705 
22706 	switch (cmnd) {
22707 	case CMD_ELS_REQUEST64_WQE:
22708 		ndlp = job->ndlp;
22709 
22710 		if_type = bf_get(lpfc_sli_intf_if_type,
22711 				 &phba->sli4_hba.sli_intf);
22712 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
22713 			pcmd = (u32 *)job->cmd_dmabuf->virt;
22714 			if (pcmd && (*pcmd == ELS_CMD_FLOGI ||
22715 				     *pcmd == ELS_CMD_SCR ||
22716 				     *pcmd == ELS_CMD_RDF ||
22717 				     *pcmd == ELS_CMD_EDC ||
22718 				     *pcmd == ELS_CMD_RSCN_XMT ||
22719 				     *pcmd == ELS_CMD_FDISC ||
22720 				     *pcmd == ELS_CMD_LOGO ||
22721 				     *pcmd == ELS_CMD_QFPA ||
22722 				     *pcmd == ELS_CMD_UVEM ||
22723 				     *pcmd == ELS_CMD_PLOGI)) {
22724 				bf_set(els_req64_sp, &wqe->els_req, 1);
22725 				bf_set(els_req64_sid, &wqe->els_req,
22726 				       job->vport->fc_myDID);
22727 
22728 				if ((*pcmd == ELS_CMD_FLOGI) &&
22729 				    !(phba->fc_topology ==
22730 				      LPFC_TOPOLOGY_LOOP))
22731 					bf_set(els_req64_sid, &wqe->els_req, 0);
22732 
22733 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 1);
22734 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
22735 				       phba->vpi_ids[job->vport->vpi]);
22736 			} else if (pcmd) {
22737 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 0);
22738 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
22739 				       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
22740 			}
22741 		}
22742 
22743 		bf_set(wqe_temp_rpi, &wqe->els_req.wqe_com,
22744 		       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
22745 
22746 		bf_set(wqe_dbde, &wqe->els_req.wqe_com, 1);
22747 		bf_set(wqe_iod, &wqe->els_req.wqe_com, LPFC_WQE_IOD_READ);
22748 		bf_set(wqe_qosd, &wqe->els_req.wqe_com, 1);
22749 		bf_set(wqe_lenloc, &wqe->els_req.wqe_com, LPFC_WQE_LENLOC_NONE);
22750 		bf_set(wqe_ebde_cnt, &wqe->els_req.wqe_com, 0);
22751 		break;
22752 	case CMD_XMIT_ELS_RSP64_WQE:
22753 		ndlp = job->ndlp;
22754 
22755 		/* word4 */
22756 		wqe->xmit_els_rsp.word4 = 0;
22757 
22758 		if_type = bf_get(lpfc_sli_intf_if_type,
22759 				 &phba->sli4_hba.sli_intf);
22760 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
22761 			if (test_bit(FC_PT2PT, &job->vport->fc_flag)) {
22762 				bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
22763 				bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
22764 				       job->vport->fc_myDID);
22765 				if (job->vport->fc_myDID == Fabric_DID) {
22766 					bf_set(wqe_els_did,
22767 					       &wqe->xmit_els_rsp.wqe_dest, 0);
22768 				}
22769 			}
22770 		}
22771 
22772 		bf_set(wqe_dbde, &wqe->xmit_els_rsp.wqe_com, 1);
22773 		bf_set(wqe_iod, &wqe->xmit_els_rsp.wqe_com, LPFC_WQE_IOD_WRITE);
22774 		bf_set(wqe_qosd, &wqe->xmit_els_rsp.wqe_com, 1);
22775 		bf_set(wqe_lenloc, &wqe->xmit_els_rsp.wqe_com,
22776 		       LPFC_WQE_LENLOC_WORD3);
22777 		bf_set(wqe_ebde_cnt, &wqe->xmit_els_rsp.wqe_com, 0);
22778 
22779 		if (phba->fc_topology == LPFC_TOPOLOGY_LOOP) {
22780 			bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
22781 			bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
22782 			       job->vport->fc_myDID);
22783 			bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com, 1);
22784 		}
22785 
22786 		if (phba->sli_rev == LPFC_SLI_REV4) {
22787 			bf_set(wqe_rsp_temp_rpi, &wqe->xmit_els_rsp,
22788 			       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
22789 
22790 			if (bf_get(wqe_ct, &wqe->xmit_els_rsp.wqe_com))
22791 				bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
22792 				       phba->vpi_ids[job->vport->vpi]);
22793 		}
22794 		command_type = OTHER_COMMAND;
22795 		break;
22796 	case CMD_GEN_REQUEST64_WQE:
22797 		/* Word 10 */
22798 		bf_set(wqe_dbde, &wqe->gen_req.wqe_com, 1);
22799 		bf_set(wqe_iod, &wqe->gen_req.wqe_com, LPFC_WQE_IOD_READ);
22800 		bf_set(wqe_qosd, &wqe->gen_req.wqe_com, 1);
22801 		bf_set(wqe_lenloc, &wqe->gen_req.wqe_com, LPFC_WQE_LENLOC_NONE);
22802 		bf_set(wqe_ebde_cnt, &wqe->gen_req.wqe_com, 0);
22803 		command_type = OTHER_COMMAND;
22804 		break;
22805 	case CMD_XMIT_SEQUENCE64_WQE:
22806 		if (phba->link_flag & LS_LOOPBACK_MODE)
22807 			bf_set(wqe_xo, &wqe->xmit_sequence.wge_ctl, 1);
22808 
22809 		wqe->xmit_sequence.rsvd3 = 0;
22810 		bf_set(wqe_pu, &wqe->xmit_sequence.wqe_com, 0);
22811 		bf_set(wqe_dbde, &wqe->xmit_sequence.wqe_com, 1);
22812 		bf_set(wqe_iod, &wqe->xmit_sequence.wqe_com,
22813 		       LPFC_WQE_IOD_WRITE);
22814 		bf_set(wqe_lenloc, &wqe->xmit_sequence.wqe_com,
22815 		       LPFC_WQE_LENLOC_WORD12);
22816 		bf_set(wqe_ebde_cnt, &wqe->xmit_sequence.wqe_com, 0);
22817 		command_type = OTHER_COMMAND;
22818 		break;
22819 	case CMD_XMIT_BLS_RSP64_WQE:
22820 		bf_set(xmit_bls_rsp64_seqcnthi, &wqe->xmit_bls_rsp, 0xffff);
22821 		bf_set(wqe_xmit_bls_pt, &wqe->xmit_bls_rsp.wqe_dest, 0x1);
22822 		bf_set(wqe_ct, &wqe->xmit_bls_rsp.wqe_com, 1);
22823 		bf_set(wqe_ctxt_tag, &wqe->xmit_bls_rsp.wqe_com,
22824 		       phba->vpi_ids[phba->pport->vpi]);
22825 		bf_set(wqe_qosd, &wqe->xmit_bls_rsp.wqe_com, 1);
22826 		bf_set(wqe_lenloc, &wqe->xmit_bls_rsp.wqe_com,
22827 		       LPFC_WQE_LENLOC_NONE);
22828 		/* Overwrite the pre-set comnd type with OTHER_COMMAND */
22829 		command_type = OTHER_COMMAND;
22830 		break;
22831 	case CMD_FCP_ICMND64_WQE:	/* task mgmt commands */
22832 	case CMD_ABORT_XRI_WQE:		/* abort iotag */
22833 	case CMD_SEND_FRAME:		/* mds loopback */
22834 		/* cases already formatted for sli4 wqe - no chgs necessary */
22835 		return;
22836 	default:
22837 		dump_stack();
22838 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
22839 				"6207 Invalid command 0x%x\n",
22840 				cmnd);
22841 		break;
22842 	}
22843 
22844 	wqe->generic.wqe_com.abort_tag = abort_tag;
22845 	bf_set(wqe_reqtag, &wqe->generic.wqe_com, job->iotag);
22846 	bf_set(wqe_cmd_type, &wqe->generic.wqe_com, command_type);
22847 	bf_set(wqe_cqid, &wqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
22848 }
22849